title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
difftime() function in C++
In this article we are going to discuss the difftime() function in C++, its syntax, working and its return values. difftime() function is an inbuilt function in C++ which is defined in header file. The function accepts two parameters of time_t type, function calculate the difference between the two times double difftime(time_t end, time_t beginning); Returns the difference of the time in seconds, stored as double data type. Live Demo #include <stdio.h> #include <time.h> int main () { time_t now; struct tm newyear; double seconds; time(&now); /* get current time; */ newyear = *localtime(&now); newyear.tm_hour = 0; newyear.tm_min = 0; newyear.tm_sec = 0; newyear.tm_mon = 0; newyear.tm_mday = 1; seconds = difftime(now,mktime(&newyear)); printf ("%.f seconds since new year in the current timezone.\n", seconds); return 0; } If we run the above code it will generate the following output − 3351041 seconds since new year in the current timezone. #include <iostream> #include <ctime> using namespace std; int main() { time_t start, ending; long addition; time(&start); for (int i = 0; i < 50000; i++) { for (int j = 0; j < 50000; j++); } for (int i = 0; i < 50000; i++) { for (int j = 0; j < 50000; j++); } for (int i = 0; i < 50000; i++) { for (int j = 0; j < 50000; j++); } time(&ending); cout << "Total time required = " << difftime(ending, start) << " seconds " << endl; return 0; } If we run the above code it will generate the following output − Total time required = 37 seconds
[ { "code": null, "e": 1177, "s": 1062, "text": "In this article we are going to discuss the difftime() function in C++, its syntax, working and its return values." }, { "code": null, "e": 1368, "s": 1177, "text": "difftime() function is an inbuilt function in C++ which is defined in header file. The function accepts two parameters of time_t type, function calculate the difference between the two times" }, { "code": null, "e": 1415, "s": 1368, "text": "double difftime(time_t end, time_t beginning);" }, { "code": null, "e": 1490, "s": 1415, "text": "Returns the difference of the time in seconds, stored as double data type." }, { "code": null, "e": 1501, "s": 1490, "text": " Live Demo" }, { "code": null, "e": 1924, "s": 1501, "text": "#include <stdio.h>\n#include <time.h>\nint main () {\n time_t now;\n struct tm newyear;\n double seconds;\n time(&now); /* get current time; */\n newyear = *localtime(&now);\n newyear.tm_hour = 0; newyear.tm_min = 0; newyear.tm_sec = 0;\n newyear.tm_mon = 0; newyear.tm_mday = 1;\n seconds = difftime(now,mktime(&newyear));\n printf (\"%.f seconds since new year in the current timezone.\\n\", seconds);\n return 0;\n}" }, { "code": null, "e": 1989, "s": 1924, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 2045, "s": 1989, "text": "3351041 seconds since new year in the current timezone." }, { "code": null, "e": 2536, "s": 2045, "text": "#include <iostream>\n#include <ctime>\nusing namespace std;\nint main() {\n time_t start, ending;\n long addition;\n time(&start);\n for (int i = 0;\n i < 50000; i++) {\n for (int j = 0; j < 50000; j++);\n }\n for (int i = 0; i < 50000; i++) {\n for (int j = 0; j < 50000; j++);\n } for (int i = 0; i < 50000; i++) {\n for (int j = 0; j < 50000; j++);\n } time(&ending);\n cout << \"Total time required = \" << difftime(ending, start) << \" seconds \" << endl;\n return 0;\n}" }, { "code": null, "e": 2601, "s": 2536, "text": "If we run the above code it will generate the following output −" }, { "code": null, "e": 2634, "s": 2601, "text": "Total time required = 37 seconds" } ]
HTML - <body> Tag
The HTML <body> tag is used for indicating the main content section of the HTML document. <!DOCTYPE html> <html> <head> <title>HTML body Tag</title> </head> <body> Body of the document... </body> </html> This will produce the following result − This tag supports all the global attributes described in HTML Attribute Reference The HTML <body> tag also supports the following additional attributes − This tag supports all the event attributes described in HTML Events Reference 19 Lectures 2 hours Anadi Sharma 16 Lectures 1.5 hours Anadi Sharma 18 Lectures 1.5 hours Frahaan Hussain 57 Lectures 5.5 hours DigiFisk (Programming Is Fun) 54 Lectures 6 hours DigiFisk (Programming Is Fun) 45 Lectures 5.5 hours DigiFisk (Programming Is Fun) Print Add Notes Bookmark this page
[ { "code": null, "e": 2464, "s": 2374, "text": "The HTML <body> tag is used for indicating the main content section of the HTML document." }, { "code": null, "e": 2606, "s": 2464, "text": "<!DOCTYPE html>\n<html>\n\n <head>\n <title>HTML body Tag</title>\n </head>\n\t\n <body>\n Body of the document...\n </body>\n\n</html>" }, { "code": null, "e": 2647, "s": 2606, "text": "This will produce the following result −" }, { "code": null, "e": 2729, "s": 2647, "text": "This tag supports all the global attributes described in HTML Attribute Reference" }, { "code": null, "e": 2802, "s": 2729, "text": "The HTML <body> tag also supports the following additional attributes −" }, { "code": null, "e": 2880, "s": 2802, "text": "This tag supports all the event attributes described in HTML Events Reference" }, { "code": null, "e": 2913, "s": 2880, "text": "\n 19 Lectures \n 2 hours \n" }, { "code": null, "e": 2927, "s": 2913, "text": " Anadi Sharma" }, { "code": null, "e": 2962, "s": 2927, "text": "\n 16 Lectures \n 1.5 hours \n" }, { "code": null, "e": 2976, "s": 2962, "text": " Anadi Sharma" }, { "code": null, "e": 3011, "s": 2976, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3028, "s": 3011, "text": " Frahaan Hussain" }, { "code": null, "e": 3063, "s": 3028, "text": "\n 57 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3094, "s": 3063, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3127, "s": 3094, "text": "\n 54 Lectures \n 6 hours \n" }, { "code": null, "e": 3158, "s": 3127, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3193, "s": 3158, "text": "\n 45 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3224, "s": 3193, "text": " DigiFisk (Programming Is Fun)" }, { "code": null, "e": 3231, "s": 3224, "text": " Print" }, { "code": null, "e": 3242, "s": 3231, "text": " Add Notes" } ]
Plot two horizontal bar charts sharing the same Y-axis in Python Matplotlib
To plot two horizontal bar charts sharing the same Y-axis, we can use sharey=ax1 in subplot() method and for horizontal bar, we can use barh() method. Create lists for data points. Create a new figure or activate an existing figure using figure() method Add a subplot to the current figure using subplot() method, at index=1. Plot horizontal bar on axis 1 using barh() method. Add a subplot to the current figure using subplot() method, at index=2. Share the Yaxis of axis 1. Plot the horizontal bar on axis 2. To display the figure, use show() method. import matplotlib.pyplot as plt import numpy as np plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True y = [3, 1, 5] x1 = [10, 7, 3] x2 = [9, 5, 1] fig = plt.figure() axe1 = plt.subplot(121) axe1.barh(y, x1, align='center', color='red', edgecolor='black') axe2 = plt.subplot(122, sharey=axe1) axe2.barh(y, x2, align='center', color='green', edgecolor='black') plt.show()
[ { "code": null, "e": 1213, "s": 1062, "text": "To plot two horizontal bar charts sharing the same Y-axis, we can use sharey=ax1 in subplot() method and for horizontal bar, we can use barh() method." }, { "code": null, "e": 1243, "s": 1213, "text": "Create lists for data points." }, { "code": null, "e": 1316, "s": 1243, "text": "Create a new figure or activate an existing figure using figure() method" }, { "code": null, "e": 1388, "s": 1316, "text": "Add a subplot to the current figure using subplot() method, at index=1." }, { "code": null, "e": 1439, "s": 1388, "text": "Plot horizontal bar on axis 1 using barh() method." }, { "code": null, "e": 1538, "s": 1439, "text": "Add a subplot to the current figure using subplot() method, at index=2. Share the Yaxis of axis 1." }, { "code": null, "e": 1573, "s": 1538, "text": "Plot the horizontal bar on axis 2." }, { "code": null, "e": 1615, "s": 1573, "text": "To display the figure, use show() method." }, { "code": null, "e": 2027, "s": 1615, "text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\ny = [3, 1, 5]\nx1 = [10, 7, 3]\nx2 = [9, 5, 1]\n\nfig = plt.figure()\n\naxe1 = plt.subplot(121)\naxe1.barh(y, x1, align='center', color='red', edgecolor='black')\n\naxe2 = plt.subplot(122, sharey=axe1)\naxe2.barh(y, x2, align='center', color='green', edgecolor='black')\n\nplt.show()" } ]
VBScript - Constants
Constant is a named memory location used to hold a value that CANNOT be changed during the script execution. If a user tries to change a Constant Value, the Script execution ends up with an error. Constants are declared the same way the variables are declared. [Public | Private] Const Constant_Name = Value The Constant can be of type Public or Private. The Use of Public or Private is Optional. The Public constants are available for all the scripts and procedures while the Private Constants are available within the procedure or Class. One can assign any value such as number, String or Date to the declared Constant. In this example, the value of pi is 3.4 and it displays the area of the circle in a message box. <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Dim intRadius intRadius = 20 const pi = 3.14 Area = pi*intRadius*intRadius Msgbox Area </script> </body> </html> The below example illustrates how to assign a String and Date Value to a Constant. <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Const myString = "VBScript" Const myDate = #01/01/2050# Msgbox myString Msgbox myDate </script> </body> </html> In the below example, the user tries to change the Constant Value; hence, it will end up with an Execution Error. <!DOCTYPE html> <html> <body> <script language = "vbscript" type = "text/vbscript"> Dim intRadius intRadius = 20 const pi = 3.14 pi = pi*pi 'pi VALUE CANNOT BE CHANGED.THROWS ERROR' Area = pi*intRadius*intRadius Msgbox Area </script> </body> </html> 63 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2341, "s": 2080, "text": "Constant is a named memory location used to hold a value that CANNOT be changed during the script execution. If a user tries to change a Constant Value, the Script execution ends up with an error. Constants are declared the same way the variables are declared." }, { "code": null, "e": 2389, "s": 2341, "text": "[Public | Private] Const Constant_Name = Value\n" }, { "code": null, "e": 2703, "s": 2389, "text": "The Constant can be of type Public or Private. The Use of Public or Private is Optional. The Public constants are available for all the scripts and procedures while the Private Constants are available within the procedure or Class. One can assign any value such as number, String or Date to the declared Constant." }, { "code": null, "e": 2800, "s": 2703, "text": "In this example, the value of pi is 3.4 and it displays the area of the circle in a message box." }, { "code": null, "e": 3061, "s": 2800, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n Dim intRadius\n intRadius = 20\n const pi = 3.14\n Area = pi*intRadius*intRadius\n Msgbox Area\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 3144, "s": 3061, "text": "The below example illustrates how to assign a String and Date Value to a Constant." }, { "code": null, "e": 3395, "s": 3144, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n Const myString = \"VBScript\"\n Const myDate = #01/01/2050#\n Msgbox myString\n Msgbox myDate\n\n </script>\n </body>\n</html>" }, { "code": null, "e": 3509, "s": 3395, "text": "In the below example, the user tries to change the Constant Value; hence, it will end up with an Execution Error." }, { "code": null, "e": 3841, "s": 3509, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script language = \"vbscript\" type = \"text/vbscript\">\n Dim intRadius\n intRadius = 20\n const pi = 3.14\n pi = pi*pi\t'pi VALUE CANNOT BE CHANGED.THROWS ERROR'\n Area = pi*intRadius*intRadius\n Msgbox Area\n \n </script>\n </body>\n</html>" }, { "code": null, "e": 3874, "s": 3841, "text": "\n 63 Lectures \n 4 hours \n" }, { "code": null, "e": 3891, "s": 3874, "text": " Frahaan Hussain" }, { "code": null, "e": 3898, "s": 3891, "text": " Print" }, { "code": null, "e": 3909, "s": 3898, "text": " Add Notes" } ]
Use of 'ClickAt ' selenium command.
We can use the ClickAt command in Selenium IDE. The ClickAt command has two arguments − the element locator and the coordinates which mentions the x and y coordinates of the mouse with respect to the element identified by the locator. This method is used when we want to click on a position having a specific mouse coordinate. It can click on a checkbox, radio button or link. clickAt(locator, coordinates) In the Selenium IDE, Choose a row inside the test script edit box. Enter click at the Command field. To identify the dropdown with the id locator, enter the Target field. The x and y coordinates are to be entered inside the Value field.
[ { "code": null, "e": 1297, "s": 1062, "text": "We can use the ClickAt command in Selenium IDE. The ClickAt command\nhas two arguments − the element locator and the coordinates which mentions the x and y coordinates of the mouse with respect to the element identified by the locator." }, { "code": null, "e": 1439, "s": 1297, "text": "This method is used when we want to click on a position having a specific mouse coordinate. It can click on a checkbox, radio button or link." }, { "code": null, "e": 1469, "s": 1439, "text": "clickAt(locator, coordinates)" }, { "code": null, "e": 1706, "s": 1469, "text": "In the Selenium IDE, Choose a row inside the test script edit box. Enter click at the Command field. To identify the dropdown with the id locator, enter the Target field. The x and y coordinates are to be entered inside the Value field." } ]
Tryit Editor v3.7
CSS Web Fonts Tryit: The font-face rule
[ { "code": null, "e": 23, "s": 9, "text": "CSS Web Fonts" } ]
How to add more values to array on button click using PHP ? - GeeksforGeeks
02 Jul, 2021 In this article, we will learn to add elements to an existing array with the click of a button using PHP. PHP is a server-side language, and it only responds to requests (GET, POST, PUT, PATCH, and DELETE). The button click action happens as a part of the client-side to directly call a PHP function. We need an intermediary language to perform this action. In this case, we will be using JavaScript. When a user will click on the button, the button will call the JavaScript function. The function will then send a POST request to our PHP script on the server to append data to the array. Each time the button will be clicked, a new request will be sent to the PHP script and thus will reinitialize our array. To overcome this, we will store our array in a JSON file on the server, and then for each request, we will append data to it. We will be dealing with three files “index.html” containing text input and button, “data.php” which handles the request, read from JSON file and append data to it and “array.json” to store array. Example: index.html <!DOCTYPE html><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script></head> <body> <!--We are taking array elements from user--> <input type="text" value="name" id="name" /> <!--It will call our JS function--> <button type="button" id="add">Add</button> <script> $(document).ready(function () { var he = $("#name").value; $("#add").click(function () { $.post( "data.php", { data: document.getElementById("name").value, }, function (data, status) { alert("Data: " + data + "\nStatus: " + status); } ); }); }); </script></body> </html> The following is the PHP code for “data.php” used in the above HTML file. We are using post() method of jQuery, to make a request. data.php <?php if(isset($_POST['data'])) { $data= $_POST['data']; $inp = file_get_contents('array.json'); $tempArray = json_decode($inp); if($tempArray) { array_push($tempArray, $data); $jsonData = json_encode($tempArray); } else { $jsonData=json_encode(array($data)); } file_put_contents('array.json', $jsonData); $inp = file_get_contents('array.json'); $tempArray = json_decode($inp); print_r($tempArray);} ?> We are handling the request along with the data sent to “data.php“. Whenever a request is sent, it opens the JSON file and reads the previous array from it. If there is no previous array i.e. the “array.json” file is empty then it creates an array. It then appends data to it. Output: Steps of execution: We will first confirm that our “results.json” file is empty. empty file user entry screen first entry Check “results.json” file. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. HTML-Questions PHP-function PHP-Questions Picked HTML PHP Web Technologies HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments REST API (Introduction) Design a web page using HTML and CSS Form validation using jQuery How to place text on image using HTML and CSS? How to auto-resize an image to fit a div container using CSS? How to pop an alert message box using PHP ? PHP in_array() Function How to pass a PHP array to a JavaScript function? PHP | Converting string to Date and DateTime How to execute PHP code using command line ?
[ { "code": null, "e": 24713, "s": 24685, "text": "\n02 Jul, 2021" }, { "code": null, "e": 24819, "s": 24713, "text": "In this article, we will learn to add elements to an existing array with the click of a button using PHP." }, { "code": null, "e": 25014, "s": 24819, "text": "PHP is a server-side language, and it only responds to requests (GET, POST, PUT, PATCH, and DELETE). The button click action happens as a part of the client-side to directly call a PHP function." }, { "code": null, "e": 25303, "s": 25014, "text": "We need an intermediary language to perform this action. In this case, we will be using JavaScript. When a user will click on the button, the button will call the JavaScript function. The function will then send a POST request to our PHP script on the server to append data to the array. " }, { "code": null, "e": 25746, "s": 25303, "text": "Each time the button will be clicked, a new request will be sent to the PHP script and thus will reinitialize our array. To overcome this, we will store our array in a JSON file on the server, and then for each request, we will append data to it. We will be dealing with three files “index.html” containing text input and button, “data.php” which handles the request, read from JSON file and append data to it and “array.json” to store array." }, { "code": null, "e": 25757, "s": 25748, "text": "Example:" }, { "code": null, "e": 25768, "s": 25757, "text": "index.html" }, { "code": "<!DOCTYPE html><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script></head> <body> <!--We are taking array elements from user--> <input type=\"text\" value=\"name\" id=\"name\" /> <!--It will call our JS function--> <button type=\"button\" id=\"add\">Add</button> <script> $(document).ready(function () { var he = $(\"#name\").value; $(\"#add\").click(function () { $.post( \"data.php\", { data: document.getElementById(\"name\").value, }, function (data, status) { alert(\"Data: \" + data + \"\\nStatus: \" + status); } ); }); }); </script></body> </html>", "e": 26584, "s": 25768, "text": null }, { "code": null, "e": 26715, "s": 26584, "text": "The following is the PHP code for “data.php” used in the above HTML file. We are using post() method of jQuery, to make a request." }, { "code": null, "e": 26724, "s": 26715, "text": "data.php" }, { "code": "<?php if(isset($_POST['data'])) { $data= $_POST['data']; $inp = file_get_contents('array.json'); $tempArray = json_decode($inp); if($tempArray) { array_push($tempArray, $data); $jsonData = json_encode($tempArray); } else { $jsonData=json_encode(array($data)); } file_put_contents('array.json', $jsonData); $inp = file_get_contents('array.json'); $tempArray = json_decode($inp); print_r($tempArray);} ?>", "e": 27193, "s": 26724, "text": null }, { "code": null, "e": 27470, "s": 27193, "text": "We are handling the request along with the data sent to “data.php“. Whenever a request is sent, it opens the JSON file and reads the previous array from it. If there is no previous array i.e. the “array.json” file is empty then it creates an array. It then appends data to it." }, { "code": null, "e": 27478, "s": 27470, "text": "Output:" }, { "code": null, "e": 27559, "s": 27478, "text": "Steps of execution: We will first confirm that our “results.json” file is empty." }, { "code": null, "e": 27571, "s": 27559, "text": "empty file " }, { "code": null, "e": 27589, "s": 27571, "text": "user entry screen" }, { "code": null, "e": 27601, "s": 27589, "text": "first entry" }, { "code": null, "e": 27628, "s": 27601, "text": "Check “results.json” file." }, { "code": null, "e": 27765, "s": 27628, "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": 27780, "s": 27765, "text": "HTML-Questions" }, { "code": null, "e": 27793, "s": 27780, "text": "PHP-function" }, { "code": null, "e": 27807, "s": 27793, "text": "PHP-Questions" }, { "code": null, "e": 27814, "s": 27807, "text": "Picked" }, { "code": null, "e": 27819, "s": 27814, "text": "HTML" }, { "code": null, "e": 27823, "s": 27819, "text": "PHP" }, { "code": null, "e": 27840, "s": 27823, "text": "Web Technologies" }, { "code": null, "e": 27845, "s": 27840, "text": "HTML" }, { "code": null, "e": 27849, "s": 27845, "text": "PHP" }, { "code": null, "e": 27947, "s": 27849, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27956, "s": 27947, "text": "Comments" }, { "code": null, "e": 27969, "s": 27956, "text": "Old Comments" }, { "code": null, "e": 27993, "s": 27969, "text": "REST API (Introduction)" }, { "code": null, "e": 28030, "s": 27993, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 28059, "s": 28030, "text": "Form validation using jQuery" }, { "code": null, "e": 28106, "s": 28059, "text": "How to place text on image using HTML and CSS?" }, { "code": null, "e": 28168, "s": 28106, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 28212, "s": 28168, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 28236, "s": 28212, "text": "PHP in_array() Function" }, { "code": null, "e": 28286, "s": 28236, "text": "How to pass a PHP array to a JavaScript function?" }, { "code": null, "e": 28331, "s": 28286, "text": "PHP | Converting string to Date and DateTime" } ]
Stringstream in C++ programming
This sample draft calculates the total number of words in a given string as well as counts the total occurrence of a particular word using stringstream in the C++ programming code. The stringstream class partners a string object with a stream enabling you to peruse from the string as though it were a stream. This code shall achieve two feats, first, it will count the total number of words then calculates the frequencies of individual words subsequently in a string using the map iterator essential methods as follows; Live Demo #include <bits/stdc++.h> using namespace std; int totalWords(string str){ stringstream s(str); string word; int count = 0; while (s >> word) count++; return count; } void countFrequency(string st){ map<string, int> FW; stringstream ss(st); string Word; while (ss >> Word) FW[Word]++; map<string, int>::iterator m; for (m = FW.begin(); m != FW.end(); m++) cout << m->first << " = " << m->second << "\n"; } int main(){ string s = "Ajay Tutorial Plus, Ajay author"; cout << "Total Number of Words=" << totalWords(s)<<endl; countFrequency(s); return 0; } When the string “Ajay Tutorial Plus, Ajay author” supplied to this program, the total counts and frequencies of words in output as follows; Enter a Total Number of Words=5 Ajay=2 Tutorial=1 Plus,=1 Author=1
[ { "code": null, "e": 1584, "s": 1062, "text": "This sample draft calculates the total number of words in a given string as well as counts the total occurrence of a particular word using stringstream in the C++ programming code. The stringstream class partners a string object with a stream enabling you to peruse from the string as though it were a stream. This code shall achieve two feats, first, it will count the total number of words then calculates the frequencies of individual words subsequently in a string using the map\niterator essential methods as follows;" }, { "code": null, "e": 1595, "s": 1584, "text": " Live Demo" }, { "code": null, "e": 2209, "s": 1595, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint totalWords(string str){\n stringstream s(str);\n string word;\n int count = 0;\n while (s >> word)\n count++;\n return count;\n}\nvoid countFrequency(string st){\n map<string, int> FW;\n stringstream ss(st);\n string Word;\n while (ss >> Word)\n FW[Word]++;\n map<string, int>::iterator m;\n for (m = FW.begin(); m != FW.end(); m++)\n cout << m->first << \" = \" << m->second << \"\\n\";\n}\nint main(){\n string s = \"Ajay Tutorial Plus, Ajay author\";\n cout << \"Total Number of Words=\" << totalWords(s)<<endl;\n countFrequency(s);\n return 0;\n}" }, { "code": null, "e": 2349, "s": 2209, "text": "When the string “Ajay Tutorial Plus, Ajay author” supplied to this program, the total counts and frequencies of words in output as follows;" }, { "code": null, "e": 2416, "s": 2349, "text": "Enter a Total Number of Words=5\nAjay=2\nTutorial=1\nPlus,=1\nAuthor=1" } ]
Difference Between Pseudo-Class and Pseudo-Element in CSS
A pseudo-class represents a state of a selector like :hover, :active, :last-child,etc. These start with a single colon(:). The syntax of CSS pseudo-class is as follows − :pseudo-class{ attribute: /*value*/ } Similarly, a pseudo-element is used to select virtual elements like ::after, ::before, ::first-line, etc. These start with a double colon(::). The syntax of CSS pseudo-element is as follows − ::pseudo-element{ attribute: /*value*/ } The following examples illustrate CSS pseudo-class and pseudo-element property. Live Demo <!DOCTYPE html> <html> <head> <style> a:hover{ padding: 3%; font-size:1.4em; color: tomato; background: bisque; } </style> </head> <body> <p>You're somebody else</p> <a href=#>Dummy link 1</a> <a href=#>Dummy link 2</a> </body> </html> This will produce the following result − Live Demo <!DOCTYPE html> <html> <head> <style> p::after { content: " BOOM!"; background: hotpink; } p:last-child { font-size: 1.4em; color: red; } </style> </head> <body> <p>Anymore Snare?</p> <p>Donec in semper diam. Morbi sollicitudin sed eros nec elementum. Praesent eget nisl vitaeneque consectetur tincidunt. Ut molestie vulputate sem, nec convallis odio molestie nec.</p> <p>Hit</p> <p>Pop</p> </body> </html> This will produce the following result −
[ { "code": null, "e": 1185, "s": 1062, "text": "A pseudo-class represents a state of a selector like :hover, :active, :last-child,etc. These start with a single colon(:)." }, { "code": null, "e": 1232, "s": 1185, "text": "The syntax of CSS pseudo-class is as follows −" }, { "code": null, "e": 1273, "s": 1232, "text": ":pseudo-class{\n attribute: /*value*/\n}" }, { "code": null, "e": 1379, "s": 1273, "text": "Similarly, a pseudo-element is used to select virtual elements like ::after, ::before, ::first-line, etc." }, { "code": null, "e": 1416, "s": 1379, "text": "These start with a double colon(::)." }, { "code": null, "e": 1465, "s": 1416, "text": "The syntax of CSS pseudo-element is as follows −" }, { "code": null, "e": 1509, "s": 1465, "text": "::pseudo-element{\n attribute: /*value*/\n}" }, { "code": null, "e": 1589, "s": 1509, "text": "The following examples illustrate CSS pseudo-class and pseudo-element property." }, { "code": null, "e": 1600, "s": 1589, "text": " Live Demo" }, { "code": null, "e": 1848, "s": 1600, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\na:hover{\n padding: 3%;\n font-size:1.4em;\n color: tomato;\n background: bisque;\n}\n</style>\n</head>\n<body>\n<p>You're somebody else</p>\n<a href=#>Dummy link 1</a>\n<a href=#>Dummy link 2</a>\n</body>\n</html>" }, { "code": null, "e": 1889, "s": 1848, "text": "This will produce the following result −" }, { "code": null, "e": 1900, "s": 1889, "text": " Live Demo" }, { "code": null, "e": 2319, "s": 1900, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\np::after {\n content: \" BOOM!\";\n background: hotpink;\n}\np:last-child {\n font-size: 1.4em;\n color: red;\n}\n</style>\n</head>\n<body>\n<p>Anymore Snare?</p>\n<p>Donec in semper diam. Morbi sollicitudin sed eros nec elementum. Praesent eget nisl vitaeneque consectetur tincidunt. Ut molestie vulputate sem, nec convallis odio molestie nec.</p>\n<p>Hit</p>\n<p>Pop</p>\n</body>\n</html>" }, { "code": null, "e": 2360, "s": 2319, "text": "This will produce the following result −" } ]
Explore your activity on Netflix with R: How to analyze and visualize your viewing history | by Saúl Buentello | Towards Data Science
The arrival of video streaming services revolutionized the entertainment industry and with it, many of our habits also changed. Whether you spend hours or minutes watching a movie or TV series, Netflix has become a favorite on the scene. Netflix, like many applications today, allows its users to be free to view their viewing activity history. For this article, we will use my history to analyze and visualize some interesting data. As an active Netflix user and with access to account data, you must enter the URL https://www.netflix.com/viewingactivity, where you will find a list of the titles that you have recently seen on the platform. Before the end of the page, there is a link that says “Download it all”, which by clicking will invite you to download a CSV file with your complete history. This file by default is downloaded with the name “NetflixViewingHistory.csv”, and is what we need to work on R. Well, creating a new R script, you can import the packages that we will be using and the downloaded CSV data to start analyzing them, with a more readable date format. # LIBRARIESlibrary(dplyr)library(tidyr)library(lubridate)library(zoo)library(ggplot2)# READING DATA FROM CSV DOWNLOADED FROM NETFLIX ACCOUNTminetflix <- read.csv("NetflixViewingHistory.csv") str(minetflix)minetflix$Date <- dmy(minetflix$Date) As you can see, the CSV file only has two columns: Date (the exact date) and Title (the title of the movie or episode and season of the TV series you have seen). Many of us get hooked watching one or more TV series, and suddenly you have spent hours of being in an almost hypnotic state in which the rest simply does not matter. There is no definition of how many hours or how many episodes “Binge-watching” is, but we are all familiar with the concept. Making the first analysis, consider that “Binge-watching” is from 6 episodes to more, and let’s see what are the most viewed TV series. Let’s separate the Title column from our data, taking advantage of the constant in the format in which Netflix names them by TV series title, TV series season, and TV series episode. Let’s also clean the data, removing everything that does not have this format (that is, movies) to focus on TV series. We also need to identify a record of episodes watched per day, belonging to a single TV series. # SEPARATE TITLE COLUMN IN TITLE OF TV SERIES, SEASON AND EPISODE TITLEminetflix_serie <- minetflix %>% separate(col = Title, into = c("title", "temporada", "titulo_episodio"), sep = ': ')# REMOVE OCCURRENCES WHERE SEASON AND EPISODE ARE EMPTY (BECAUSE THEY ARE NOT TV SERIES)minetflix_serie <- minetflix_serie[!is.na(minetflix_serie$temporada),]minetflix_serie <- minetflix_serie[!is.na(minetflix_serie$titulo_episodio),]# REGISTRO DE NÚMERO DE EPISODIOS VISTOS POR DÍA, POR SERIEmaratones_minetflix <- minetflix_serie %>% count(title, Date)# LET'S CONSIDER "BINGE-WATCHING" 6 OR MORE EPISODES PER DAY AND SORT BY DATEmaratones_minetflix <- maratones_minetflix[maratones_minetflix$n >= 6,]maratones_minetflixmaratones_minetflix <- maratones_minetflix[order(maratones_minetflix$Date),]maratones_minetflix Under those conditions, in my case, I got 35 observations with 3 variables now. Now we are ready to view the top 10 of the most viewed TV series to which you have dedicated “Binge-watching”. We will group the data by the title of the TV series and we will order them by the number of episodes watched. # GROUPING DATA BY TV SERIES TITLE AND SORTING BY NUMBER OF EPISODES VIEWEDmaratones_minetflix_todas <- maratones_minetflix %>% group_by(title) %>% summarise(n = sum(n)) %>% arrange(desc(n))# PLOTTING TOP 10 OF BINGE-WATCHING TV SERIESmaratones_minetflix_top <- maratones_minetflix_todas %>% top_n(10) %>% ggplot(aes(x = reorder(title, n), y = n)) + geom_col(fill = "#0097d6") + coord_flip() + ggtitle("Top 10 de series más vistas en maratón en mi Netflix", "4 o más episodios por día") + labs(x = "Serie en Netflix", y = "Episodios vistos en total") + theme_minimal()maratones_minetflix_top We will then obtain the following plot. Please don’t judge me for spending so much time watching “Betty, la fea” (It’s a popular Colombian “soap opera”). It would be interesting to see how much your consuming habits have changed over time. Do the maximum peaks match the lockdown by the Covid-19, for example? Or maybe it coincides with all that time since you were single again? You can make a general count of episodes per day in the history of your activity. # EPISODES PER DAYnetflix_episodios_dia <- minetflix %>% count(Date) %>% arrange(desc(n))# PLOTTING EPISODES PER DAYnetflix_episodios_dia_plot <- ggplot(aes(x = Date, y = n, color = n), data = netflix_episodios_dia) + geom_col(color = c("#f16727")) + theme_minimal() + ggtitle("Episodios vistos en mi Netflix por día", "Historial de 2016 a 2020") + labs(x = "Fecha", y = "Episodios vistos") netflix_episodios_dia_plot In my case, in the following plot, it’s very remarkable that in my Netflix account consumption has been increasing. You can go deeper. Let’s look at the activity in another way, with a heatmap distributed by days, weeks, months, and years, with which we can specify a little better the times when we had more or less consumption of episodes of TV series per day. # CALENDAR WITH NUMBER OF EPISODES SEEN PER DAY IN HEATMAPnetflix_episodios_dia <- netflix_episodios_dia[order(netflix_episodios_dia$Date),]netflix_episodios_dia$diasemana <- wday(netflix_episodios_dia$Date)netflix_episodios_dia$diasemanaF <- weekdays(netflix_episodios_dia$Date, abbreviate = T)netflix_episodios_dia$mesF <- months(netflix_episodios_dia$Date, abbreviate = T)# YOU DON'T NEED TO RENAME NECESSARILY IN SPANISH DAYS OF THE WEEK AND MONTHSnetflix_episodios_dia$diasemanaF <-factor(netflix_episodios_dia$diasemana, levels = rev(1:7), labels = rev(c("Lun","Mar","Mier","Jue","Vier","Sáb","Dom")),ordered = TRUE)netflix_episodios_dia$mesF <- factor(month(netflix_episodios_dia$Date),levels = as.character(1:12), labels = c("Enero","Febrero","Marzo","Abril","Mayo","Junio","Julio","Agosto","Septiembre","Octubre","Noviembre","Diciembre"),ordered = TRUE)netflix_episodios_dia$añomes <- factor(as.yearmon(netflix_episodios_dia$Date)) netflix_episodios_dia$semana <- as.numeric(format(netflix_episodios_dia$Date,"%W"))netflix_episodios_dia$semanames <- ceiling(day(netflix_episodios_dia$Date) / 7)netflix_episodios_dia_calendario <- ggplot(netflix_episodios_dia, aes(semanames, diasemanaF, fill = netflix_episodios_dia$n)) + geom_tile(colour = "white") + facet_grid(year(netflix_episodios_dia$Date) ~ mesF) + scale_fill_gradient(low = "#FFD000", high = "#FF1919") + ggtitle("Episodios vistos por día en mi Netflix", "Heatmap por día de la semana, mes y año") + labs(x = "Número de semana", y = "Día de la semana") + labs(fill = "No.Episodios")netflix_episodios_dia_calendario What happened in June and July 2017, that a loss of interest on the platform is visible on the plot? Is it related to the trial month that Amazon Prime Video gave me to convince me? Maybe. We can also see in a very visual and detailed way which are the days of the week that there is more or less activity watching episodes of TV series. # FREQUENCY OF ACTIVITY IN MY NETFLIX ACCOUNT PER DAYvista_dia <- netflix_episodios_dia %>% count(diasemanaF)vista_diavista_dia_plot <- vista_dia %>% ggplot(aes(diasemanaF, n)) + geom_col(fill = "#5b59d6") + coord_polar() + theme_minimal() + theme(axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank(), axis.text.x = element_text(face = "bold"), plot.title = element_text(size = 16, face = "bold")) + ggtitle("Frecuencia de episodios vistos", "Actividad por día de la semana en mi Netflix")vista_dia_plot There is a clear trend, as the plot shows, that Mondays are busy days to spend time on Netflix. Will it be your case too? Like the previous example, we can repeat the operation but now based on the months, which is the favorite month that we choose to give our valuable time to Netflix. # FREQUENCY OF ACTIVITY IN MY NETFLIX ACCOUNT PER MONTHvista_mes <- netflix_episodios_dia %>% count(mesF)vista_mesvista_mes_plot <- vista_mes %>% ggplot(aes(mesF, n)) + geom_col(fill = "#808000") + coord_polar() + theme_minimal() + theme(axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank(), axis.text.x = element_text(face = "bold"), plot.title = element_text(size = 18, face = "bold")) + ggtitle("Frecuencia de episodios vistos", "Actividad por mes en mi Netflix") vista_mes_plot You will get a plot like the following. The months of June, July, and September have not been the best in my relationship with Netflix. Finally, let’s review once again in the same format as the two previous examples, your activity but now segmented by the month of each year. # FREQUENCY OF ACTIVITY IN MY NETFLIX ACCOUNT PER YEARvista_años <- netflix_episodios_dia %>% count(añomes)vista_añosvista_años_plot <- vista_años %>% ggplot(aes(añomes, n)) + geom_col(fill = "#1a954d") + coord_polar() + theme_minimal() + theme(axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank(), axis.text.x = element_text(face = "bold"), plot.title = element_text(size = 18, face = "bold")) + ggtitle("Frecuencia de episodios vistos", "Actividad por mes del año en mi Netflix")vista_años_plot You can see in the plot obtained, that in my case the months of October and November 2019 were great for Netflix collecting data about my preferences and habits. I have to say that I share my account with my girlfriend. Sometimes the recommendations that the platform makes, are not exactly the most appropriate for me or her, lol. Thanks for your kind reading. You can see the plots generated for this article, a little more fancy with plotly, in the flexdashboard that I put together: https://rpubs.com/cosmoduende/netflix-data-analysis-r I also share the complete code, in case you are curious to analyze your viewing activity on Netflix: https://github.com/cosmoduende/r-netflix-data-analysis Have a happy analysis, that you can practice it and even improve it, play, and surprise yourself with interesting results. This article was translated into English, from the article I previously published in Spanish, at the request of people who do not speak Spanish and who asked me in groups and forums if I would publish it in English. Thank you and see you soon. Some rights reserved
[ { "code": null, "e": 285, "s": 47, "text": "The arrival of video streaming services revolutionized the entertainment industry and with it, many of our habits also changed. Whether you spend hours or minutes watching a movie or TV series, Netflix has become a favorite on the scene." }, { "code": null, "e": 481, "s": 285, "text": "Netflix, like many applications today, allows its users to be free to view their viewing activity history. For this article, we will use my history to analyze and visualize some interesting data." }, { "code": null, "e": 690, "s": 481, "text": "As an active Netflix user and with access to account data, you must enter the URL https://www.netflix.com/viewingactivity, where you will find a list of the titles that you have recently seen on the platform." }, { "code": null, "e": 960, "s": 690, "text": "Before the end of the page, there is a link that says “Download it all”, which by clicking will invite you to download a CSV file with your complete history. This file by default is downloaded with the name “NetflixViewingHistory.csv”, and is what we need to work on R." }, { "code": null, "e": 1128, "s": 960, "text": "Well, creating a new R script, you can import the packages that we will be using and the downloaded CSV data to start analyzing them, with a more readable date format." }, { "code": null, "e": 1371, "s": 1128, "text": "# LIBRARIESlibrary(dplyr)library(tidyr)library(lubridate)library(zoo)library(ggplot2)# READING DATA FROM CSV DOWNLOADED FROM NETFLIX ACCOUNTminetflix <- read.csv(\"NetflixViewingHistory.csv\") str(minetflix)minetflix$Date <- dmy(minetflix$Date)" }, { "code": null, "e": 1533, "s": 1371, "text": "As you can see, the CSV file only has two columns: Date (the exact date) and Title (the title of the movie or episode and season of the TV series you have seen)." }, { "code": null, "e": 1961, "s": 1533, "text": "Many of us get hooked watching one or more TV series, and suddenly you have spent hours of being in an almost hypnotic state in which the rest simply does not matter. There is no definition of how many hours or how many episodes “Binge-watching” is, but we are all familiar with the concept. Making the first analysis, consider that “Binge-watching” is from 6 episodes to more, and let’s see what are the most viewed TV series." }, { "code": null, "e": 2359, "s": 1961, "text": "Let’s separate the Title column from our data, taking advantage of the constant in the format in which Netflix names them by TV series title, TV series season, and TV series episode. Let’s also clean the data, removing everything that does not have this format (that is, movies) to focus on TV series. We also need to identify a record of episodes watched per day, belonging to a single TV series." }, { "code": null, "e": 3168, "s": 2359, "text": "# SEPARATE TITLE COLUMN IN TITLE OF TV SERIES, SEASON AND EPISODE TITLEminetflix_serie <- minetflix %>% separate(col = Title, into = c(\"title\", \"temporada\", \"titulo_episodio\"), sep = ': ')# REMOVE OCCURRENCES WHERE SEASON AND EPISODE ARE EMPTY (BECAUSE THEY ARE NOT TV SERIES)minetflix_serie <- minetflix_serie[!is.na(minetflix_serie$temporada),]minetflix_serie <- minetflix_serie[!is.na(minetflix_serie$titulo_episodio),]# REGISTRO DE NÚMERO DE EPISODIOS VISTOS POR DÍA, POR SERIEmaratones_minetflix <- minetflix_serie %>% count(title, Date)# LET'S CONSIDER \"BINGE-WATCHING\" 6 OR MORE EPISODES PER DAY AND SORT BY DATEmaratones_minetflix <- maratones_minetflix[maratones_minetflix$n >= 6,]maratones_minetflixmaratones_minetflix <- maratones_minetflix[order(maratones_minetflix$Date),]maratones_minetflix" }, { "code": null, "e": 3248, "s": 3168, "text": "Under those conditions, in my case, I got 35 observations with 3 variables now." }, { "code": null, "e": 3470, "s": 3248, "text": "Now we are ready to view the top 10 of the most viewed TV series to which you have dedicated “Binge-watching”. We will group the data by the title of the TV series and we will order them by the number of episodes watched." }, { "code": null, "e": 4079, "s": 3470, "text": "# GROUPING DATA BY TV SERIES TITLE AND SORTING BY NUMBER OF EPISODES VIEWEDmaratones_minetflix_todas <- maratones_minetflix %>% group_by(title) %>% summarise(n = sum(n)) %>% arrange(desc(n))# PLOTTING TOP 10 OF BINGE-WATCHING TV SERIESmaratones_minetflix_top <- maratones_minetflix_todas %>% top_n(10) %>% ggplot(aes(x = reorder(title, n), y = n)) + geom_col(fill = \"#0097d6\") + coord_flip() + ggtitle(\"Top 10 de series más vistas en maratón en mi Netflix\", \"4 o más episodios por día\") + labs(x = \"Serie en Netflix\", y = \"Episodios vistos en total\") + theme_minimal()maratones_minetflix_top" }, { "code": null, "e": 4233, "s": 4079, "text": "We will then obtain the following plot. Please don’t judge me for spending so much time watching “Betty, la fea” (It’s a popular Colombian “soap opera”)." }, { "code": null, "e": 4459, "s": 4233, "text": "It would be interesting to see how much your consuming habits have changed over time. Do the maximum peaks match the lockdown by the Covid-19, for example? Or maybe it coincides with all that time since you were single again?" }, { "code": null, "e": 4541, "s": 4459, "text": "You can make a general count of episodes per day in the history of your activity." }, { "code": null, "e": 4966, "s": 4541, "text": "# EPISODES PER DAYnetflix_episodios_dia <- minetflix %>% count(Date) %>% arrange(desc(n))# PLOTTING EPISODES PER DAYnetflix_episodios_dia_plot <- ggplot(aes(x = Date, y = n, color = n), data = netflix_episodios_dia) + geom_col(color = c(\"#f16727\")) + theme_minimal() + ggtitle(\"Episodios vistos en mi Netflix por día\", \"Historial de 2016 a 2020\") + labs(x = \"Fecha\", y = \"Episodios vistos\") netflix_episodios_dia_plot" }, { "code": null, "e": 5082, "s": 4966, "text": "In my case, in the following plot, it’s very remarkable that in my Netflix account consumption has been increasing." }, { "code": null, "e": 5329, "s": 5082, "text": "You can go deeper. Let’s look at the activity in another way, with a heatmap distributed by days, weeks, months, and years, with which we can specify a little better the times when we had more or less consumption of episodes of TV series per day." }, { "code": null, "e": 6928, "s": 5329, "text": "# CALENDAR WITH NUMBER OF EPISODES SEEN PER DAY IN HEATMAPnetflix_episodios_dia <- netflix_episodios_dia[order(netflix_episodios_dia$Date),]netflix_episodios_dia$diasemana <- wday(netflix_episodios_dia$Date)netflix_episodios_dia$diasemanaF <- weekdays(netflix_episodios_dia$Date, abbreviate = T)netflix_episodios_dia$mesF <- months(netflix_episodios_dia$Date, abbreviate = T)# YOU DON'T NEED TO RENAME NECESSARILY IN SPANISH DAYS OF THE WEEK AND MONTHSnetflix_episodios_dia$diasemanaF <-factor(netflix_episodios_dia$diasemana, levels = rev(1:7), labels = rev(c(\"Lun\",\"Mar\",\"Mier\",\"Jue\",\"Vier\",\"Sáb\",\"Dom\")),ordered = TRUE)netflix_episodios_dia$mesF <- factor(month(netflix_episodios_dia$Date),levels = as.character(1:12), labels = c(\"Enero\",\"Febrero\",\"Marzo\",\"Abril\",\"Mayo\",\"Junio\",\"Julio\",\"Agosto\",\"Septiembre\",\"Octubre\",\"Noviembre\",\"Diciembre\"),ordered = TRUE)netflix_episodios_dia$añomes <- factor(as.yearmon(netflix_episodios_dia$Date)) netflix_episodios_dia$semana <- as.numeric(format(netflix_episodios_dia$Date,\"%W\"))netflix_episodios_dia$semanames <- ceiling(day(netflix_episodios_dia$Date) / 7)netflix_episodios_dia_calendario <- ggplot(netflix_episodios_dia, aes(semanames, diasemanaF, fill = netflix_episodios_dia$n)) + geom_tile(colour = \"white\") + facet_grid(year(netflix_episodios_dia$Date) ~ mesF) + scale_fill_gradient(low = \"#FFD000\", high = \"#FF1919\") + ggtitle(\"Episodios vistos por día en mi Netflix\", \"Heatmap por día de la semana, mes y año\") + labs(x = \"Número de semana\", y = \"Día de la semana\") + labs(fill = \"No.Episodios\")netflix_episodios_dia_calendario" }, { "code": null, "e": 7117, "s": 6928, "text": "What happened in June and July 2017, that a loss of interest on the platform is visible on the plot? Is it related to the trial month that Amazon Prime Video gave me to convince me? Maybe." }, { "code": null, "e": 7266, "s": 7117, "text": "We can also see in a very visual and detailed way which are the days of the week that there is more or less activity watching episodes of TV series." }, { "code": null, "e": 7849, "s": 7266, "text": "# FREQUENCY OF ACTIVITY IN MY NETFLIX ACCOUNT PER DAYvista_dia <- netflix_episodios_dia %>% count(diasemanaF)vista_diavista_dia_plot <- vista_dia %>% ggplot(aes(diasemanaF, n)) + geom_col(fill = \"#5b59d6\") + coord_polar() + theme_minimal() + theme(axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank(), axis.text.x = element_text(face = \"bold\"), plot.title = element_text(size = 16, face = \"bold\")) + ggtitle(\"Frecuencia de episodios vistos\", \"Actividad por día de la semana en mi Netflix\")vista_dia_plot" }, { "code": null, "e": 7971, "s": 7849, "text": "There is a clear trend, as the plot shows, that Mondays are busy days to spend time on Netflix. Will it be your case too?" }, { "code": null, "e": 8136, "s": 7971, "text": "Like the previous example, we can repeat the operation but now based on the months, which is the favorite month that we choose to give our valuable time to Netflix." }, { "code": null, "e": 8696, "s": 8136, "text": "# FREQUENCY OF ACTIVITY IN MY NETFLIX ACCOUNT PER MONTHvista_mes <- netflix_episodios_dia %>% count(mesF)vista_mesvista_mes_plot <- vista_mes %>% ggplot(aes(mesF, n)) + geom_col(fill = \"#808000\") + coord_polar() + theme_minimal() + theme(axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank(), axis.text.x = element_text(face = \"bold\"), plot.title = element_text(size = 18, face = \"bold\")) + ggtitle(\"Frecuencia de episodios vistos\", \"Actividad por mes en mi Netflix\") vista_mes_plot" }, { "code": null, "e": 8832, "s": 8696, "text": "You will get a plot like the following. The months of June, July, and September have not been the best in my relationship with Netflix." }, { "code": null, "e": 8973, "s": 8832, "text": "Finally, let’s review once again in the same format as the two previous examples, your activity but now segmented by the month of each year." }, { "code": null, "e": 9556, "s": 8973, "text": "# FREQUENCY OF ACTIVITY IN MY NETFLIX ACCOUNT PER YEARvista_años <- netflix_episodios_dia %>% count(añomes)vista_añosvista_años_plot <- vista_años %>% ggplot(aes(añomes, n)) + geom_col(fill = \"#1a954d\") + coord_polar() + theme_minimal() + theme(axis.title.x = element_blank(), axis.title.y = element_blank(), axis.text.y = element_blank(), axis.text.x = element_text(face = \"bold\"), plot.title = element_text(size = 18, face = \"bold\")) + ggtitle(\"Frecuencia de episodios vistos\", \"Actividad por mes del año en mi Netflix\")vista_años_plot" }, { "code": null, "e": 9718, "s": 9556, "text": "You can see in the plot obtained, that in my case the months of October and November 2019 were great for Netflix collecting data about my preferences and habits." }, { "code": null, "e": 9888, "s": 9718, "text": "I have to say that I share my account with my girlfriend. Sometimes the recommendations that the platform makes, are not exactly the most appropriate for me or her, lol." }, { "code": null, "e": 10097, "s": 9888, "text": "Thanks for your kind reading. You can see the plots generated for this article, a little more fancy with plotly, in the flexdashboard that I put together: https://rpubs.com/cosmoduende/netflix-data-analysis-r" }, { "code": null, "e": 10253, "s": 10097, "text": "I also share the complete code, in case you are curious to analyze your viewing activity on Netflix: https://github.com/cosmoduende/r-netflix-data-analysis" }, { "code": null, "e": 10376, "s": 10253, "text": "Have a happy analysis, that you can practice it and even improve it, play, and surprise yourself with interesting results." }, { "code": null, "e": 10592, "s": 10376, "text": "This article was translated into English, from the article I previously published in Spanish, at the request of people who do not speak Spanish and who asked me in groups and forums if I would publish it in English." }, { "code": null, "e": 10620, "s": 10592, "text": "Thank you and see you soon." } ]
Program for dot product and cross product of two vectors
04 Jun, 2022 There are two vector A and B and we have to find the dot product and cross product of two vector array. Dot product is also known as scalar product and cross product also known as vector product.Dot Product – Let we have given two vector A = a1 * i + a2 * j + a3 * k and B = b1 * i + b2 * j + b3 * k. Where i, j and k are the unit vector along the x, y and z directions. Then dot product is calculated as dot product = a1 * b1 + a2 * b2 + a3 * b3Example – A = 3 * i + 5 * j + 4 * k B = 2 * i + 7 * j + 5 * k dot product = 3 * 2 + 5 * 7 + 4 * 5 = 6 + 35 + 20 = 61 Cross Product – Let we have given two vector A = a1 * i + a2 * j + a3 * k and B = b1 * i + b2 * j + b3 * k. Then cross product is calculated as cross product = (a2 * b3 – a3 * b2) * i + (a3 * b1 – a1 * b3) * j + (a1 * b2 – a2 * b1) * k, where [(a2 * b3 – a3 * b2), (a3 * b1 – a1 * b3), (a1 * b2 – a2 * b1)] are the coefficient of unit vector along i, j and k directions.Example – A = 3 * i + 5 * j + 4 * k B = 2 * i + 7 * j + 5 * k cross product = (5 * 5 - 4 * 7) * i + (4 * 2 - 3 * 5) * j + (3 * 7 - 5 * 2) * k = (-3)*i + (-7)*j + (11)*k Example – Input: vect_A[] = {3, -5, 4} vect_B[] = {2, 6, 5} Output: Dot product: -4 Cross product = -49 -7 28 Code- C++ Java Python3 C# PHP Javascript // C++ implementation for dot product// and cross product of two vector.#include <bits/stdc++.h>#define n 3 using namespace std; // Function that return// dot product of two vector array.int dotProduct(int vect_A[], int vect_B[]){ int product = 0; // Loop for calculate dot product for (int i = 0; i < n; i++) product = product + vect_A[i] * vect_B[i]; return product;} // Function to find// cross product of two vector array.void crossProduct(int vect_A[], int vect_B[], int cross_P[]) { cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0];} // Driver functionint main(){ int vect_A[] = { 3, -5, 4 }; int vect_B[] = { 2, 6, 5 }; int cross_P[n]; // dotProduct function call cout << "Dot product:"; cout << dotProduct(vect_A, vect_B) << endl; // crossProduct function call cout << "Cross product:"; crossProduct(vect_A, vect_B, cross_P); // Loop that print // cross product of two vector array. for (int i = 0; i < n; i++) cout << cross_P[i] << " "; return 0;} // java implementation for dot product// and cross product of two vector.import java.io.*; class GFG { static int n = 3; // Function that return // dot product of two vector array. static int dotProduct(int vect_A[], int vect_B[]) { int product = 0; // Loop for calculate dot product for (int i = 0; i < n; i++) product = product + vect_A[i] * vect_B[i]; return product; } // Function to find // cross product of two vector array. static void crossProduct(int vect_A[], int vect_B[], int cross_P[]) { cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0]; } // Driver code public static void main(String[] args) { int vect_A[] = { 3, -5, 4 }; int vect_B[] = { 2, 6, 5 }; int cross_P[] = new int[n]; // dotProduct function call System.out.print("Dot product:"); System.out.println(dotProduct(vect_A, vect_B)); // crossProduct function call System.out.print("Cross product:"); crossProduct(vect_A, vect_B, cross_P); // Loop that print // cross product of two vector array. for (int i = 0; i < n; i++) System.out.print(cross_P[i] + " "); }} // This code is contributed by vt_m # Python3 implementation for dot product# and cross product of two vector. n = 3 # Function that return# dot product of two vector array.def dotProduct(vect_A, vect_B): product = 0 # Loop for calculate dot product for i in range(0, n): product = product + vect_A[i] * vect_B[i] return product # Function to find# cross product of two vector array.def crossProduct(vect_A, vect_B, cross_P): cross_P.append(vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]) cross_P.append(vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]) cross_P.append(vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0]) # Driver functionif __name__=='__main__': vect_A = [3, -5, 4] vect_B = [2, 6, 5] cross_P = [] # dotProduct function call print("Dot product:", end =" ") print(dotProduct(vect_A, vect_B)) # crossProduct function call print("Cross product:", end =" ") crossProduct(vect_A, vect_B, cross_P) # Loop that print# cross product of two vector array. for i in range(0, n): print(cross_P[i], end =" ") # This code is contributed by# Sanjit_Prasad // C# implementation for dot product// and cross product of two vector.using System; class GFG { static int n = 3; // Function that return dot // product of two vector array. static int dotProduct(int[] vect_A, int[] vect_B) { int product = 0; // Loop for calculate dot product for (int i = 0; i < n; i++) product = product + vect_A[i] * vect_B[i]; return product; } // Function to find cross product // of two vector array. static void crossProduct(int[] vect_A, int[] vect_B, int[] cross_P) { cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0]; } // Driver code public static void Main() { int[] vect_A = { 3, -5, 4 }; int[] vect_B = { 2, 6, 5 }; int[] cross_P = new int[n]; // dotProduct function call Console.Write("Dot product:"); Console.WriteLine( dotProduct(vect_A, vect_B)); // crossProduct function call Console.Write("Cross product:"); crossProduct(vect_A, vect_B, cross_P); // Loop that print // cross product of two vector array. for (int i = 0; i < n; i++) Console.Write(cross_P[i] + " "); }} // This code is contributed by vt_m. <?php// PHP implementation for dot// product and cross product// of two vector.$n = 3; // Function that return// dot product of two// vector array.function dotproduct($vect_A, $vect_B){ global $n; $product = 0; // Loop for calculate // dot product for ($i = 0; $i < $n; $i++) $product = $product + $vect_A[$i] * $vect_B[$i]; return $product;} // Function to find// cross product of// two vector array.function crossproduct($vect_A, $vect_B, $cross_P) { $cross_P[0] = $vect_A[1] * $vect_B[2] - $vect_A[2] * $vect_B[1]; $cross_P[1] = $vect_A[2] * $vect_B[0] - $vect_A[0] * $vect_B[2]; $cross_P[2] = $vect_A[0] * $vect_B[1] - $vect_A[1] * $vect_B[0]; return $cross_P;} // Driver Code$vect_A = array( 3, -5, 4 );$vect_B = array( 2, 6, 5 );$cross_P = array_fill(0, $n, 0); // dotproduct function callecho "Dot product:";echo dotproduct($vect_A, $vect_B); // crossproduct function callecho "\nCross product:";$cross_P = crossproduct($vect_A, $vect_B, $cross_P); // Loop that print// cross product of// two vector array.for ($i = 0; $i < $n; $i++) echo $cross_P[$i] . " "; // This code is contributed by mits?> <script> // Javascript implementation for dot product// and cross product of two vector. let n = 3; // Function that return // dot product of two vector array. function dotProduct(vect_A, vect_B) { let product = 0; // Loop for calculate dot product for (let i = 0; i < n; i++) product = product + vect_A[i] * vect_B[i]; return product; } // Function to find // cross product of two vector array. function crossProduct(vect_A, vect_B, cross_P) { cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0]; } // Driver code let vect_A = [ 3, -5, 4 ]; let vect_B = [ 2, 6, 5 ]; let cross_P = []; // dotProduct function call document.write("Dot product:"); document.write(dotProduct(vect_A, vect_B) + "<br/>"); // crossProduct function call document.write("Cross product:"); crossProduct(vect_A, vect_B, cross_P); // Loop that print // cross product of two vector array. for (let i = 0; i < n; i++) document.write(cross_P[i] + " "); // This code is contributed by sanjoy_62. </script> Dot product:-4 Cross product:-49 -7 28 Time Complexity: O(3), the code will run in a constant time because the size of the arrays will be always 3.Auxiliary Space: O(3), no extra space is required, so it is a constant. This article is contributed by Dharmendra Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. vt_m Mithun Kumar Sanjit_Prasad rghm0398 sanjoy_62 khushboogoyal499 surinderdawra388 samim2000 C++ Programs Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Jun, 2022" }, { "code": null, "e": 510, "s": 52, "text": "There are two vector A and B and we have to find the dot product and cross product of two vector array. Dot product is also known as scalar product and cross product also known as vector product.Dot Product – Let we have given two vector A = a1 * i + a2 * j + a3 * k and B = b1 * i + b2 * j + b3 * k. Where i, j and k are the unit vector along the x, y and z directions. Then dot product is calculated as dot product = a1 * b1 + a2 * b2 + a3 * b3Example – " }, { "code": null, "e": 641, "s": 510, "text": "A = 3 * i + 5 * j + 4 * k\nB = 2 * i + 7 * j + 5 * k\ndot product = 3 * 2 + 5 * 7 + 4 * 5\n = 6 + 35 + 20\n = 61" }, { "code": null, "e": 1023, "s": 641, "text": "Cross Product – Let we have given two vector A = a1 * i + a2 * j + a3 * k and B = b1 * i + b2 * j + b3 * k. Then cross product is calculated as cross product = (a2 * b3 – a3 * b2) * i + (a3 * b1 – a1 * b3) * j + (a1 * b2 – a2 * b1) * k, where [(a2 * b3 – a3 * b2), (a3 * b1 – a1 * b3), (a1 * b2 – a2 * b1)] are the coefficient of unit vector along i, j and k directions.Example – " }, { "code": null, "e": 1190, "s": 1023, "text": "A = 3 * i + 5 * j + 4 * k\nB = 2 * i + 7 * j + 5 * k\ncross product \n= (5 * 5 - 4 * 7) * i \n + (4 * 2 - 3 * 5) * j + (3 * 7 - 5 * 2) * k\n= (-3)*i + (-7)*j + (11)*k" }, { "code": null, "e": 1202, "s": 1190, "text": "Example – " }, { "code": null, "e": 1319, "s": 1202, "text": "Input: vect_A[] = {3, -5, 4}\n vect_B[] = {2, 6, 5}\nOutput: Dot product: -4\n Cross product = -49 -7 28" }, { "code": null, "e": 1329, "s": 1321, "text": "Code- " }, { "code": null, "e": 1333, "s": 1329, "text": "C++" }, { "code": null, "e": 1338, "s": 1333, "text": "Java" }, { "code": null, "e": 1346, "s": 1338, "text": "Python3" }, { "code": null, "e": 1349, "s": 1346, "text": "C#" }, { "code": null, "e": 1353, "s": 1349, "text": "PHP" }, { "code": null, "e": 1364, "s": 1353, "text": "Javascript" }, { "code": "// C++ implementation for dot product// and cross product of two vector.#include <bits/stdc++.h>#define n 3 using namespace std; // Function that return// dot product of two vector array.int dotProduct(int vect_A[], int vect_B[]){ int product = 0; // Loop for calculate dot product for (int i = 0; i < n; i++) product = product + vect_A[i] * vect_B[i]; return product;} // Function to find// cross product of two vector array.void crossProduct(int vect_A[], int vect_B[], int cross_P[]) { cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0];} // Driver functionint main(){ int vect_A[] = { 3, -5, 4 }; int vect_B[] = { 2, 6, 5 }; int cross_P[n]; // dotProduct function call cout << \"Dot product:\"; cout << dotProduct(vect_A, vect_B) << endl; // crossProduct function call cout << \"Cross product:\"; crossProduct(vect_A, vect_B, cross_P); // Loop that print // cross product of two vector array. for (int i = 0; i < n; i++) cout << cross_P[i] << \" \"; return 0;}", "e": 2534, "s": 1364, "text": null }, { "code": "// java implementation for dot product// and cross product of two vector.import java.io.*; class GFG { static int n = 3; // Function that return // dot product of two vector array. static int dotProduct(int vect_A[], int vect_B[]) { int product = 0; // Loop for calculate dot product for (int i = 0; i < n; i++) product = product + vect_A[i] * vect_B[i]; return product; } // Function to find // cross product of two vector array. static void crossProduct(int vect_A[], int vect_B[], int cross_P[]) { cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0]; } // Driver code public static void main(String[] args) { int vect_A[] = { 3, -5, 4 }; int vect_B[] = { 2, 6, 5 }; int cross_P[] = new int[n]; // dotProduct function call System.out.print(\"Dot product:\"); System.out.println(dotProduct(vect_A, vect_B)); // crossProduct function call System.out.print(\"Cross product:\"); crossProduct(vect_A, vect_B, cross_P); // Loop that print // cross product of two vector array. for (int i = 0; i < n; i++) System.out.print(cross_P[i] + \" \"); }} // This code is contributed by vt_m", "e": 4033, "s": 2534, "text": null }, { "code": "# Python3 implementation for dot product# and cross product of two vector. n = 3 # Function that return# dot product of two vector array.def dotProduct(vect_A, vect_B): product = 0 # Loop for calculate dot product for i in range(0, n): product = product + vect_A[i] * vect_B[i] return product # Function to find# cross product of two vector array.def crossProduct(vect_A, vect_B, cross_P): cross_P.append(vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]) cross_P.append(vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]) cross_P.append(vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0]) # Driver functionif __name__=='__main__': vect_A = [3, -5, 4] vect_B = [2, 6, 5] cross_P = [] # dotProduct function call print(\"Dot product:\", end =\" \") print(dotProduct(vect_A, vect_B)) # crossProduct function call print(\"Cross product:\", end =\" \") crossProduct(vect_A, vect_B, cross_P) # Loop that print# cross product of two vector array. for i in range(0, n): print(cross_P[i], end =\" \") # This code is contributed by# Sanjit_Prasad", "e": 5110, "s": 4033, "text": null }, { "code": "// C# implementation for dot product// and cross product of two vector.using System; class GFG { static int n = 3; // Function that return dot // product of two vector array. static int dotProduct(int[] vect_A, int[] vect_B) { int product = 0; // Loop for calculate dot product for (int i = 0; i < n; i++) product = product + vect_A[i] * vect_B[i]; return product; } // Function to find cross product // of two vector array. static void crossProduct(int[] vect_A, int[] vect_B, int[] cross_P) { cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0]; } // Driver code public static void Main() { int[] vect_A = { 3, -5, 4 }; int[] vect_B = { 2, 6, 5 }; int[] cross_P = new int[n]; // dotProduct function call Console.Write(\"Dot product:\"); Console.WriteLine( dotProduct(vect_A, vect_B)); // crossProduct function call Console.Write(\"Cross product:\"); crossProduct(vect_A, vect_B, cross_P); // Loop that print // cross product of two vector array. for (int i = 0; i < n; i++) Console.Write(cross_P[i] + \" \"); }} // This code is contributed by vt_m.", "e": 6618, "s": 5110, "text": null }, { "code": "<?php// PHP implementation for dot// product and cross product// of two vector.$n = 3; // Function that return// dot product of two// vector array.function dotproduct($vect_A, $vect_B){ global $n; $product = 0; // Loop for calculate // dot product for ($i = 0; $i < $n; $i++) $product = $product + $vect_A[$i] * $vect_B[$i]; return $product;} // Function to find// cross product of// two vector array.function crossproduct($vect_A, $vect_B, $cross_P) { $cross_P[0] = $vect_A[1] * $vect_B[2] - $vect_A[2] * $vect_B[1]; $cross_P[1] = $vect_A[2] * $vect_B[0] - $vect_A[0] * $vect_B[2]; $cross_P[2] = $vect_A[0] * $vect_B[1] - $vect_A[1] * $vect_B[0]; return $cross_P;} // Driver Code$vect_A = array( 3, -5, 4 );$vect_B = array( 2, 6, 5 );$cross_P = array_fill(0, $n, 0); // dotproduct function callecho \"Dot product:\";echo dotproduct($vect_A, $vect_B); // crossproduct function callecho \"\\nCross product:\";$cross_P = crossproduct($vect_A, $vect_B, $cross_P); // Loop that print// cross product of// two vector array.for ($i = 0; $i < $n; $i++) echo $cross_P[$i] . \" \"; // This code is contributed by mits?>", "e": 7903, "s": 6618, "text": null }, { "code": "<script> // Javascript implementation for dot product// and cross product of two vector. let n = 3; // Function that return // dot product of two vector array. function dotProduct(vect_A, vect_B) { let product = 0; // Loop for calculate dot product for (let i = 0; i < n; i++) product = product + vect_A[i] * vect_B[i]; return product; } // Function to find // cross product of two vector array. function crossProduct(vect_A, vect_B, cross_P) { cross_P[0] = vect_A[1] * vect_B[2] - vect_A[2] * vect_B[1]; cross_P[1] = vect_A[2] * vect_B[0] - vect_A[0] * vect_B[2]; cross_P[2] = vect_A[0] * vect_B[1] - vect_A[1] * vect_B[0]; } // Driver code let vect_A = [ 3, -5, 4 ]; let vect_B = [ 2, 6, 5 ]; let cross_P = []; // dotProduct function call document.write(\"Dot product:\"); document.write(dotProduct(vect_A, vect_B) + \"<br/>\"); // crossProduct function call document.write(\"Cross product:\"); crossProduct(vect_A, vect_B, cross_P); // Loop that print // cross product of two vector array. for (let i = 0; i < n; i++) document.write(cross_P[i] + \" \"); // This code is contributed by sanjoy_62. </script>", "e": 9342, "s": 7903, "text": null }, { "code": null, "e": 9381, "s": 9342, "text": "Dot product:-4\nCross product:-49 -7 28" }, { "code": null, "e": 9564, "s": 9383, "text": "Time Complexity: O(3), the code will run in a constant time because the size of the arrays will be always 3.Auxiliary Space: O(3), no extra space is required, so it is a constant. " }, { "code": null, "e": 9989, "s": 9564, "text": "This article is contributed by Dharmendra Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 9994, "s": 9989, "text": "vt_m" }, { "code": null, "e": 10007, "s": 9994, "text": "Mithun Kumar" }, { "code": null, "e": 10021, "s": 10007, "text": "Sanjit_Prasad" }, { "code": null, "e": 10030, "s": 10021, "text": "rghm0398" }, { "code": null, "e": 10040, "s": 10030, "text": "sanjoy_62" }, { "code": null, "e": 10057, "s": 10040, "text": "khushboogoyal499" }, { "code": null, "e": 10074, "s": 10057, "text": "surinderdawra388" }, { "code": null, "e": 10084, "s": 10074, "text": "samim2000" }, { "code": null, "e": 10097, "s": 10084, "text": "C++ Programs" }, { "code": null, "e": 10110, "s": 10097, "text": "Mathematical" }, { "code": null, "e": 10123, "s": 10110, "text": "Mathematical" } ]
Inserting data into a new column of an already existing table in MySQL using Python
24 Feb, 2021 Prerequisite: Python: MySQL Create Table In this article, we are going to see how to Inserting data into a new column of an already existing table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector Python module is an API in python for communicating with a MySQL database. Database table in use: We are going to use geeks(Database name) database and table describing the salary. Approach: Import module. Make a connection request with the database. Create an object for the database cursor. Execute the following MySQL query: ALTER TABLE person ADD salary int(20); UPDATE persons SET salary = '145000' where Emp_Id=12; And print the result. Before starting let do the same in SQL: Step 1: Create a new column with alter command. ALTER TABLE table_name ADD column_name datatype; Step 2: Insert data in a new column. Below is the full implementation in python: Python3 # Establish connection to MySQL databaseimport mysql.connector db = mysql.connector.connect( host="localhost", user="root", password="root123", database="geeks") # getting the cursor by cursor() methodmycursor = db.cursor()query_1 = "ALTER TABLE person ADD salary int(20);"query_2 = "UPDATE persons SET salary = '145000' where Emp_Id=12;" # execute the queriesmycursor.execute(query_1)mycursor.execute(query_2) mycursor.execute("select * from persons;")myresult = mycursor.fetchall()for row in myresult: print(row) db.commit() # close the Connectiondb.close() Output: Picked Python-mySQL Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Feb, 2021" }, { "code": null, "e": 93, "s": 52, "text": "Prerequisite: Python: MySQL Create Table" }, { "code": null, "e": 466, "s": 93, "text": "In this article, we are going to see how to Inserting data into a new column of an already existing table in MySQL using Python. Python allows the integration of a wide range of database servers with applications. A database interface is required to access a database from Python. MySQL Connector Python module is an API in python for communicating with a MySQL database. " }, { "code": null, "e": 489, "s": 466, "text": "Database table in use:" }, { "code": null, "e": 572, "s": 489, "text": "We are going to use geeks(Database name) database and table describing the salary." }, { "code": null, "e": 582, "s": 572, "text": "Approach:" }, { "code": null, "e": 597, "s": 582, "text": "Import module." }, { "code": null, "e": 642, "s": 597, "text": "Make a connection request with the database." }, { "code": null, "e": 684, "s": 642, "text": "Create an object for the database cursor." }, { "code": null, "e": 719, "s": 684, "text": "Execute the following MySQL query:" }, { "code": null, "e": 812, "s": 719, "text": "ALTER TABLE person\nADD salary int(20);\nUPDATE persons SET salary = '145000' where Emp_Id=12;" }, { "code": null, "e": 834, "s": 812, "text": "And print the result." }, { "code": null, "e": 874, "s": 834, "text": "Before starting let do the same in SQL:" }, { "code": null, "e": 922, "s": 874, "text": "Step 1: Create a new column with alter command." }, { "code": null, "e": 971, "s": 922, "text": "ALTER TABLE table_name ADD column_name datatype;" }, { "code": null, "e": 1008, "s": 971, "text": "Step 2: Insert data in a new column." }, { "code": null, "e": 1052, "s": 1008, "text": "Below is the full implementation in python:" }, { "code": null, "e": 1060, "s": 1052, "text": "Python3" }, { "code": "# Establish connection to MySQL databaseimport mysql.connector db = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"root123\", database=\"geeks\") # getting the cursor by cursor() methodmycursor = db.cursor()query_1 = \"ALTER TABLE person ADD salary int(20);\"query_2 = \"UPDATE persons SET salary = '145000' where Emp_Id=12;\" # execute the queriesmycursor.execute(query_1)mycursor.execute(query_2) mycursor.execute(\"select * from persons;\")myresult = mycursor.fetchall()for row in myresult: print(row) db.commit() # close the Connectiondb.close()", "e": 1641, "s": 1060, "text": null }, { "code": null, "e": 1649, "s": 1641, "text": "Output:" }, { "code": null, "e": 1656, "s": 1649, "text": "Picked" }, { "code": null, "e": 1669, "s": 1656, "text": "Python-mySQL" }, { "code": null, "e": 1676, "s": 1669, "text": "Python" } ]
std::transform() in C++ STL (Perform an operation on all elements)
22 Jun, 2021 Consider the problem of adding contents of two arrays into a third array. It is given that all arrays are of same size.Following is simple C++ program without transform(). CPP // A C++ code to add two arrays#include <bits/stdc++.h>using namespace std; int main(){ int arr1[] = {1, 2, 3}; int arr2[] = {4, 5, 6}; int n = sizeof(arr1)/sizeof(arr1[0]); int res[n]; // Code to add two arrays for (int i=0; i<n; i++) res[i] = arr1[i] + arr2[i]; for (int i=0; i<3; i++) cout << res[i] << " ";} Output : 5 7 9 Using transform function of STL, we can add arrays in single line. C // Using transform() in STL to add two arrays#include <bits/stdc++.h>using namespace std; int main(){ int arr1[] = {1, 2, 3}; int arr2[] = {4, 5, 6}; int n = sizeof(arr1)/sizeof(arr1[0]); int res[n]; // Single line code to add arr1[] and arr2[] and // store result in res[] transform(arr1, arr1+n, arr2, res, plus<int>()); for (int i=0; i<n; i++) cout << res[i] << " ";} Output : 5 7 9 transform() in C++ is used in two forms: Unary Operation : Applies a unary operator on input to convert into output Unary Operation : Applies a unary operator on input to convert into output transform(Iterator inputBegin, Iterator inputEnd, Iterator OutputBegin, unary_operation) Following is C++ example. Following is C++ example. C // C++ program to demonstrate working of// transform with unary operator.#include <bits/stdc++.h>using namespace std; int increment(int x) { return (x+1); } int main(){ int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); // Apply increment to all elements of // arr[] and store the modified elements // back in arr[] transform(arr, arr+n, arr, increment); for (int i=0; i<n; i++) cout << arr[i] << " "; return 0;} Output : Output : 2 3 4 5 6 Binary Operation : Applies a binary operator on input to convert into output Binary Operation : Applies a binary operator on input to convert into output transform(Iterator inputBegin1, Iterator inputEnd1, Iterator inputBegin2, Iterator OutputBegin, binary_operation) The example mentioned above for adding two arrays is an example of transform with binary operation. The example mentioned above for adding two arrays is an example of transform with binary operation. More examples: We can use transform to convert a string to upper case (See this) We can modify above examples for vectors also. // vect is a vector of integers. transform(vect.begin(), vect.end(), vect.begin(), increment); Related Topic: Functors in C++Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above sagar0719kumar cpp-algorithm-library CPP-Library STL C Language C++ STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) Set in C++ Standard Template Library (STL) Priority Queue in C++ Standard Template Library (STL)
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jun, 2021" }, { "code": null, "e": 225, "s": 52, "text": "Consider the problem of adding contents of two arrays into a third array. It is given that all arrays are of same size.Following is simple C++ program without transform(). " }, { "code": null, "e": 229, "s": 225, "text": "CPP" }, { "code": "// A C++ code to add two arrays#include <bits/stdc++.h>using namespace std; int main(){ int arr1[] = {1, 2, 3}; int arr2[] = {4, 5, 6}; int n = sizeof(arr1)/sizeof(arr1[0]); int res[n]; // Code to add two arrays for (int i=0; i<n; i++) res[i] = arr1[i] + arr2[i]; for (int i=0; i<3; i++) cout << res[i] << \" \";}", "e": 556, "s": 229, "text": null }, { "code": null, "e": 566, "s": 556, "text": "Output : " }, { "code": null, "e": 572, "s": 566, "text": "5 7 9" }, { "code": null, "e": 641, "s": 572, "text": "Using transform function of STL, we can add arrays in single line. " }, { "code": null, "e": 643, "s": 641, "text": "C" }, { "code": "// Using transform() in STL to add two arrays#include <bits/stdc++.h>using namespace std; int main(){ int arr1[] = {1, 2, 3}; int arr2[] = {4, 5, 6}; int n = sizeof(arr1)/sizeof(arr1[0]); int res[n]; // Single line code to add arr1[] and arr2[] and // store result in res[] transform(arr1, arr1+n, arr2, res, plus<int>()); for (int i=0; i<n; i++) cout << res[i] << \" \";}", "e": 1027, "s": 643, "text": null }, { "code": null, "e": 1037, "s": 1027, "text": "Output : " }, { "code": null, "e": 1043, "s": 1037, "text": "5 7 9" }, { "code": null, "e": 1086, "s": 1043, "text": "transform() in C++ is used in two forms: " }, { "code": null, "e": 1162, "s": 1086, "text": "Unary Operation : Applies a unary operator on input to convert into output " }, { "code": null, "e": 1238, "s": 1162, "text": "Unary Operation : Applies a unary operator on input to convert into output " }, { "code": null, "e": 1338, "s": 1238, "text": "transform(Iterator inputBegin, Iterator inputEnd, \n Iterator OutputBegin, unary_operation) " }, { "code": null, "e": 1365, "s": 1338, "text": "Following is C++ example. " }, { "code": null, "e": 1392, "s": 1365, "text": "Following is C++ example. " }, { "code": null, "e": 1394, "s": 1392, "text": "C" }, { "code": "// C++ program to demonstrate working of// transform with unary operator.#include <bits/stdc++.h>using namespace std; int increment(int x) { return (x+1); } int main(){ int arr[] = {1, 2, 3, 4, 5}; int n = sizeof(arr)/sizeof(arr[0]); // Apply increment to all elements of // arr[] and store the modified elements // back in arr[] transform(arr, arr+n, arr, increment); for (int i=0; i<n; i++) cout << arr[i] << \" \"; return 0;}", "e": 1856, "s": 1394, "text": null }, { "code": null, "e": 1866, "s": 1856, "text": "Output : " }, { "code": null, "e": 1876, "s": 1866, "text": "Output : " }, { "code": null, "e": 1887, "s": 1876, "text": "2 3 4 5 6 " }, { "code": null, "e": 1966, "s": 1887, "text": " Binary Operation : Applies a binary operator on input to convert into output " }, { "code": null, "e": 2046, "s": 1968, "text": "Binary Operation : Applies a binary operator on input to convert into output " }, { "code": null, "e": 2181, "s": 2046, "text": "transform(Iterator inputBegin1, Iterator inputEnd1, \n Iterator inputBegin2, Iterator OutputBegin, \n binary_operation) " }, { "code": null, "e": 2283, "s": 2181, "text": "The example mentioned above for adding two arrays is an example of transform with binary operation. " }, { "code": null, "e": 2385, "s": 2283, "text": "The example mentioned above for adding two arrays is an example of transform with binary operation. " }, { "code": null, "e": 2514, "s": 2385, "text": "More examples: We can use transform to convert a string to upper case (See this) We can modify above examples for vectors also. " }, { "code": null, "e": 2638, "s": 2514, "text": " \n // vect is a vector of integers.\n transform(vect.begin(), vect.end(), \n vect.begin(), increment); " }, { "code": null, "e": 2793, "s": 2638, "text": "Related Topic: Functors in C++Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 2808, "s": 2793, "text": "sagar0719kumar" }, { "code": null, "e": 2830, "s": 2808, "text": "cpp-algorithm-library" }, { "code": null, "e": 2842, "s": 2830, "text": "CPP-Library" }, { "code": null, "e": 2846, "s": 2842, "text": "STL" }, { "code": null, "e": 2857, "s": 2846, "text": "C Language" }, { "code": null, "e": 2861, "s": 2857, "text": "C++" }, { "code": null, "e": 2865, "s": 2861, "text": "STL" }, { "code": null, "e": 2869, "s": 2865, "text": "CPP" }, { "code": null, "e": 2967, "s": 2869, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2984, "s": 2967, "text": "Substring in C++" }, { "code": null, "e": 3006, "s": 2984, "text": "Function Pointer in C" }, { "code": null, "e": 3052, "s": 3006, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 3097, "s": 3052, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 3122, "s": 3097, "text": "std::string class in C++" }, { "code": null, "e": 3140, "s": 3122, "text": "Vector in C++ STL" }, { "code": null, "e": 3183, "s": 3140, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 3229, "s": 3183, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 3272, "s": 3229, "text": "Set in C++ Standard Template Library (STL)" } ]
Elasticsearch - Mapping
Mapping is the outline of the documents stored in an index. It defines the data type like geo_point or string and format of the fields present in the documents and rules to control the mapping of dynamically added fields. PUT bankaccountdetails { "mappings":{ "properties":{ "name": { "type":"text"}, "date":{ "type":"date"}, "balance":{ "type":"double"}, "liability":{ "type":"double"} } } } When we run the above code, we get the response as shown below − { "acknowledged" : true, "shards_acknowledged" : true, "index" : "bankaccountdetails" } Elasticsearch supports a number of different datatypes for the fields in a document. The data types used to store fields in Elasticsearch are discussed in detail here. These are the basic data types such as text, keyword, date, long, double, boolean or ip, which are supported by almost all the systems. These data types are a combination of core data types. These include array, JSON object and nested data type. An example of nested data type is shown below &minus POST /tabletennis/_doc/1 { "group" : "players", "user" : [ { "first" : "dave", "last" : "jones" }, { "first" : "kevin", "last" : "morris" } ] } When we run the above code, we get the response as shown below − { "_index" : "tabletennis", "_type" : "_doc", "_id" : "1", _version" : 2, "result" : "updated", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 1, "_primary_term" : 1 } Another sample code is shown below − POST /accountdetails/_doc/1 { "from_acc":"7056443341", "to_acc":"7032460534", "date":"11/1/2016", "amount":10000 } When we run the above code, we get the response as shown below − { "_index" : "accountdetails", "_type" : "_doc", "_id" : "1", "_version" : 1, "result" : "created", "_shards" : { "total" : 2, "successful" : 1, "failed" : 0 }, "_seq_no" : 1, "_primary_term" : 1 } We can check the above document by using the following command − GET /accountdetails/_mappings?include_type_name=false Indices created in Elasticsearch 7.0.0 or later no longer accept a _default_ mapping. Indices created in 6.x will continue to function as before in Elasticsearch 6.x. Types are deprecated in APIs in 7.0.
[ { "code": null, "e": 2937, "s": 2715, "text": "Mapping is the outline of the documents stored in an index. It defines the data type like geo_point or string and format of the fields present in the documents and rules to control the mapping of dynamically added fields." }, { "code": null, "e": 3145, "s": 2937, "text": "PUT bankaccountdetails\n{\n \"mappings\":{\n \"properties\":{\n \"name\": { \"type\":\"text\"}, \"date\":{ \"type\":\"date\"},\n \"balance\":{ \"type\":\"double\"}, \"liability\":{ \"type\":\"double\"}\n }\n }\n }" }, { "code": null, "e": 3210, "s": 3145, "text": "When we run the above code, we get the response as shown below −" }, { "code": null, "e": 3308, "s": 3210, "text": "{\n \"acknowledged\" : true,\n \"shards_acknowledged\" : true,\n \"index\" : \"bankaccountdetails\"\n}\n" }, { "code": null, "e": 3476, "s": 3308, "text": "Elasticsearch supports a number of different datatypes for the fields in a document. The\ndata types used to store fields in Elasticsearch are discussed in detail here." }, { "code": null, "e": 3612, "s": 3476, "text": "These are the basic data types such as text, keyword, date, long, double, boolean or ip,\nwhich are supported by almost all the systems." }, { "code": null, "e": 3775, "s": 3612, "text": "These data types are a combination of core data types. These include array, JSON object\nand nested data type. An example of nested data type is shown below &minus" }, { "code": null, "e": 3970, "s": 3775, "text": "POST /tabletennis/_doc/1\n{\n \"group\" : \"players\",\n \"user\" : [\n {\n \"first\" : \"dave\", \"last\" : \"jones\"\n },\n {\n \"first\" : \"kevin\", \"last\" : \"morris\"\n }\n ]\n}" }, { "code": null, "e": 4035, "s": 3970, "text": "When we run the above code, we get the response as shown below −" }, { "code": null, "e": 4275, "s": 4035, "text": "{\n \"_index\" : \"tabletennis\",\n \"_type\" : \"_doc\",\n \"_id\" : \"1\",\n _version\" : 2,\n \"result\" : \"updated\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 1,\n \"_primary_term\" : 1\n}\n" }, { "code": null, "e": 4312, "s": 4275, "text": "Another sample code is shown below −" }, { "code": null, "e": 4433, "s": 4312, "text": "POST /accountdetails/_doc/1\n{\n \"from_acc\":\"7056443341\", \"to_acc\":\"7032460534\",\n \"date\":\"11/1/2016\", \"amount\":10000\n}" }, { "code": null, "e": 4498, "s": 4433, "text": "When we run the above code, we get the response as shown below −" }, { "code": null, "e": 4740, "s": 4498, "text": "{ \"_index\" : \"accountdetails\",\n \"_type\" : \"_doc\",\n \"_id\" : \"1\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 1,\n \"_primary_term\" : 1\n}\n" }, { "code": null, "e": 4805, "s": 4740, "text": "We can check the above document by using the following command −" }, { "code": null, "e": 4860, "s": 4805, "text": "GET /accountdetails/_mappings?include_type_name=false\n" } ]
Program to find compound interest
21 Jun, 2022 What is ‘Compound interest’? Compound interest is the addition of interest to the principal sum of a loan or deposit, or in other words, interest on interest. It is the result of reinvesting interest, rather than paying it out, so that interest in the next period is then earned on the principal sum plus previously-accumulated interest. Compound interest is standard in finance and economics.Compound interest may be contrasted with simple interest, where interest is not added to the principal, so there is no compounding.Compound Interest formula: Formula to calculate compound interest annually is given by: Amount= P(1 + R/100)t Compound Interest = Amount – PWhere, P is principle amount R is the rate and T is the time span Pseudo Code: Input principle amount. Store it in some variable say principle. Input time in some variable say time. Input rate in some variable say rate. Calculate Amount using formula, Amount = principle * (1 + rate / 100) time). Calculate Compound Interest using Formula. Finally, print the resultant value of CI. Example: Input : Principle (amount): 1200 Time: 2 Rate: 5.4 Output : Compound Interest = 133.099243 C++ C Java Python3 C# PHP Javascript // CPP program to find compound interest for// given values.#include <bits/stdc++.h>using namespace std; int main(){ double principle = 10000, rate = 5, time = 2; /* Calculate compound interest */ double A = principle * (pow((1 + rate / 100), time)); double CI = A- principle; cout << "Compound interest is " << CI; return 0;}//This Code is Contributed by Sahil Rai. // C program to calculate Compound Interest#include <stdio.h>#include<math.h> // for using pow function we must include math.h int main() { double principal = 10000; // principal amount double rate = 5; //annual rate of interest double time = 2; // time // Calculating compound Interest double Amount = principal * (pow((1 + rate / 100), time)); double CI = Amount - principal; printf("Compound Interest is : %lf",CI); return 0;} // Java program to find compound interest for// given values.import java.io.*; class GFG{ public static void main(String args[]) { double principle = 10000, rate = 5, time = 2; /* Calculate compound interest */ double A = principle * (Math.pow((1 + rate / 100), time)); double CI = A - principle; System.out.println("Compound Interest is "+ CI); }} //This Code is Contributed by Sahil Rai. # Python3 program to find compound# interest for given values. def compound_interest(principle, rate, time): # Calculates compound interest A = principle * (pow((1 + rate / 100), time)) CI= A - principle print("Compound interest is", CI) compound_interest(10000, 5, 2) #This Code is Contributed by Sahil Rai. // C# program to find compound// interest for given valuesusing System; class GFG { // Driver Code public static void Main() { double principle = 10000, rate = 5, time = 2; // Calculate compound interest double A = principle * (Math.Pow((1 + rate / 100), time)); double CI = A - principle; Console.Write("Compound Interest is "+ CI); }} //This Code is Contributed by Sahil Rai. <?php// PHP program to find// compound interest for// given values. $principle = 10000;$rate = 5;$time = 2; // Calculate compound interest$A = $principle * (pow((1 + $rate / 100), $time));$CI = $A - $principle; echo("Compound interest is " . $CI); ?> <script> // JavaScript program to// find compound interest for// given values. let principle = 10000, rate = 5, time = 2; /* Calculate compound interest */ let A = principle * (Math.pow((1 + rate / 100), time)); let CI = A - principle; document.write("Compound interest is " + CI);</script> // This Code is Contributed by Sahil Rai. Output: Compound interest is 1025 Time complexity: O(log(m)) where m=1+rate/100 space complexity: O(1) nitin mittal jit_t surbhityagi15 thesahilrai akashish__ krishnav4 Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of subarrays with average K Operators in C / C++ The Knight's tour problem | Backtracking-1 Count of longest possible subarrays with sum not divisible by K Find minimum number of coins that make a given value Python Dictionary Reverse a string in Java Arrays in C/C++ Interfaces in Java Inheritance in C++
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Jun, 2022" }, { "code": null, "e": 605, "s": 52, "text": "What is ‘Compound interest’? Compound interest is the addition of interest to the principal sum of a loan or deposit, or in other words, interest on interest. It is the result of reinvesting interest, rather than paying it out, so that interest in the next period is then earned on the principal sum plus previously-accumulated interest. Compound interest is standard in finance and economics.Compound interest may be contrasted with simple interest, where interest is not added to the principal, so there is no compounding.Compound Interest formula: " }, { "code": null, "e": 688, "s": 605, "text": "Formula to calculate compound interest annually is given by: Amount= P(1 + R/100)t" }, { "code": null, "e": 784, "s": 688, "text": "Compound Interest = Amount – PWhere, P is principle amount R is the rate and T is the time span" }, { "code": null, "e": 799, "s": 784, "text": "Pseudo Code: " }, { "code": null, "e": 1104, "s": 799, "text": "Input principle amount. Store it in some variable say principle.\nInput time in some variable say time.\nInput rate in some variable say rate.\nCalculate Amount using formula, \nAmount = principle * (1 + rate / 100) time).\nCalculate Compound Interest using Formula.\nFinally, print the resultant value of CI." }, { "code": null, "e": 1115, "s": 1104, "text": "Example: " }, { "code": null, "e": 1222, "s": 1115, "text": "Input : Principle (amount): 1200\n Time: 2\n Rate: 5.4\nOutput : Compound Interest = 133.099243" }, { "code": null, "e": 1228, "s": 1224, "text": "C++" }, { "code": null, "e": 1230, "s": 1228, "text": "C" }, { "code": null, "e": 1235, "s": 1230, "text": "Java" }, { "code": null, "e": 1243, "s": 1235, "text": "Python3" }, { "code": null, "e": 1246, "s": 1243, "text": "C#" }, { "code": null, "e": 1250, "s": 1246, "text": "PHP" }, { "code": null, "e": 1261, "s": 1250, "text": "Javascript" }, { "code": "// CPP program to find compound interest for// given values.#include <bits/stdc++.h>using namespace std; int main(){ double principle = 10000, rate = 5, time = 2; /* Calculate compound interest */ double A = principle * (pow((1 + rate / 100), time)); double CI = A- principle; cout << \"Compound interest is \" << CI; return 0;}//This Code is Contributed by Sahil Rai.", "e": 1651, "s": 1261, "text": null }, { "code": "// C program to calculate Compound Interest#include <stdio.h>#include<math.h> // for using pow function we must include math.h int main() { double principal = 10000; // principal amount double rate = 5; //annual rate of interest double time = 2; // time // Calculating compound Interest double Amount = principal * (pow((1 + rate / 100), time)); double CI = Amount - principal; printf(\"Compound Interest is : %lf\",CI); return 0;}", "e": 2100, "s": 1651, "text": null }, { "code": "// Java program to find compound interest for// given values.import java.io.*; class GFG{ public static void main(String args[]) { double principle = 10000, rate = 5, time = 2; /* Calculate compound interest */ double A = principle * (Math.pow((1 + rate / 100), time)); double CI = A - principle; System.out.println(\"Compound Interest is \"+ CI); }} //This Code is Contributed by Sahil Rai.", "e": 2565, "s": 2100, "text": null }, { "code": "# Python3 program to find compound# interest for given values. def compound_interest(principle, rate, time): # Calculates compound interest A = principle * (pow((1 + rate / 100), time)) CI= A - principle print(\"Compound interest is\", CI) compound_interest(10000, 5, 2) #This Code is Contributed by Sahil Rai.", "e": 2888, "s": 2565, "text": null }, { "code": "// C# program to find compound// interest for given valuesusing System; class GFG { // Driver Code public static void Main() { double principle = 10000, rate = 5, time = 2; // Calculate compound interest double A = principle * (Math.Pow((1 + rate / 100), time)); double CI = A - principle; Console.Write(\"Compound Interest is \"+ CI); }} //This Code is Contributed by Sahil Rai.", "e": 3345, "s": 2888, "text": null }, { "code": "<?php// PHP program to find// compound interest for// given values. $principle = 10000;$rate = 5;$time = 2; // Calculate compound interest$A = $principle * (pow((1 + $rate / 100), $time));$CI = $A - $principle; echo(\"Compound interest is \" . $CI); ?>", "e": 3601, "s": 3345, "text": null }, { "code": "<script> // JavaScript program to// find compound interest for// given values. let principle = 10000, rate = 5, time = 2; /* Calculate compound interest */ let A = principle * (Math.pow((1 + rate / 100), time)); let CI = A - principle; document.write(\"Compound interest is \" + CI);</script> // This Code is Contributed by Sahil Rai.", "e": 3966, "s": 3601, "text": null }, { "code": null, "e": 3975, "s": 3966, "text": "Output: " }, { "code": null, "e": 4001, "s": 3975, "text": "Compound interest is 1025" }, { "code": null, "e": 4047, "s": 4001, "text": "Time complexity: O(log(m)) where m=1+rate/100" }, { "code": null, "e": 4070, "s": 4047, "text": "space complexity: O(1)" }, { "code": null, "e": 4083, "s": 4070, "text": "nitin mittal" }, { "code": null, "e": 4089, "s": 4083, "text": "jit_t" }, { "code": null, "e": 4103, "s": 4089, "text": "surbhityagi15" }, { "code": null, "e": 4115, "s": 4103, "text": "thesahilrai" }, { "code": null, "e": 4126, "s": 4115, "text": "akashish__" }, { "code": null, "e": 4136, "s": 4126, "text": "krishnav4" }, { "code": null, "e": 4149, "s": 4136, "text": "Mathematical" }, { "code": null, "e": 4168, "s": 4149, "text": "School Programming" }, { "code": null, "e": 4181, "s": 4168, "text": "Mathematical" }, { "code": null, "e": 4279, "s": 4181, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4313, "s": 4279, "text": "Count of subarrays with average K" }, { "code": null, "e": 4334, "s": 4313, "text": "Operators in C / C++" }, { "code": null, "e": 4377, "s": 4334, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 4441, "s": 4377, "text": "Count of longest possible subarrays with sum not divisible by K" }, { "code": null, "e": 4494, "s": 4441, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 4512, "s": 4494, "text": "Python Dictionary" }, { "code": null, "e": 4537, "s": 4512, "text": "Reverse a string in Java" }, { "code": null, "e": 4553, "s": 4537, "text": "Arrays in C/C++" }, { "code": null, "e": 4572, "s": 4553, "text": "Interfaces in Java" } ]
Python – API.friends() in Tweepy
05 Jun, 2020 Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication. The friends() method of the API class in Tweepy module is used to get the specified user’s friends(the users they are following) ordered in which they were added. Syntax : API.friends(id / user_id / screen_name) Parameters : Only use one of the 3 options:id : specifies the ID or the screen name of the useruser_id : specifies the ID of the user, useful to differentiate accounts when a valid user ID is also a valid screen namescreen_name : specifies the screen name of the user, useful to differentiate accounts when a valid screen name is also a user IDIf no user is specified it defaults to the authenticated user. Returns : a list of objects of the class User Example 1 :The friends() method returns the 20 most recent friends. # import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the screen_name of the targeted userscreen_name = "TwitterIndia" # printing the latest 20 friends of the userfor friend in api.friends(screen_name): print(friend.screen_name) Output : misskaul rajyasabhatv DDNewslive TwitterMedia abpmajhatv htTweets News18Haryana jack BBCHindi the_hindu mentalhealthind ProKabaddi firstpost livemint hcmariwala mathrubhumi PTUshaOfficial anubhabhonsle kmmalleswari DipaKarmakar Example 2: More than 20 friends can be accessed using the Cursor() method. # the screen_name of the targeted userscreen_name = "TwitterIndia" # getting only 30 friendsfor friend in tweepy.Cursor(api.friends, screen_name).items(30): print(friend.screen_name) Output : misskaul rajyasabhatv DDNewslive TwitterMedia abpmajhatv htTweets News18Haryana jack BBCHindi the_hindu mentalhealthind ProKabaddi firstpost livemint hcmariwala mathrubhumi PTUshaOfficial anubhabhonsle kmmalleswari DipaKarmakar NewIndianXpress M_Raj03 DDNational isro PTTVOnlineNews cricketnext thebetterindia AGSawant MahendraP_BJP DrRPNishank Example 3: Counting the number of followers. # the screen_name of the targeted userscreen_name = "geeksforgeeks" # getting all the friendsc = tweepy.Cursor(api.friends, screen_name) # counting the number of friendscount = 0for friends in c.items(): count += 1print(screen_name + " has " + str(count) + " friends.") Output : geeksforgeeks has 8 friends. Python-Tweepy 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 Iterate over a list in Python Python Classes and Objects Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 428, "s": 28, "text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication." }, { "code": null, "e": 591, "s": 428, "text": "The friends() method of the API class in Tweepy module is used to get the specified user’s friends(the users they are following) ordered in which they were added." }, { "code": null, "e": 640, "s": 591, "text": "Syntax : API.friends(id / user_id / screen_name)" }, { "code": null, "e": 1047, "s": 640, "text": "Parameters : Only use one of the 3 options:id : specifies the ID or the screen name of the useruser_id : specifies the ID of the user, useful to differentiate accounts when a valid user ID is also a valid screen namescreen_name : specifies the screen name of the user, useful to differentiate accounts when a valid screen name is also a user IDIf no user is specified it defaults to the authenticated user." }, { "code": null, "e": 1093, "s": 1047, "text": "Returns : a list of objects of the class User" }, { "code": null, "e": 1161, "s": 1093, "text": "Example 1 :The friends() method returns the 20 most recent friends." }, { "code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the screen_name of the targeted userscreen_name = \"TwitterIndia\" # printing the latest 20 friends of the userfor friend in api.friends(screen_name): print(friend.screen_name)", "e": 1749, "s": 1161, "text": null }, { "code": null, "e": 1758, "s": 1749, "text": "Output :" }, { "code": null, "e": 1987, "s": 1758, "text": "misskaul\nrajyasabhatv\nDDNewslive\nTwitterMedia\nabpmajhatv\nhtTweets\nNews18Haryana\njack\nBBCHindi\nthe_hindu\nmentalhealthind\nProKabaddi\nfirstpost\nlivemint\nhcmariwala\nmathrubhumi\nPTUshaOfficial\nanubhabhonsle\nkmmalleswari\nDipaKarmakar\n" }, { "code": null, "e": 2062, "s": 1987, "text": "Example 2: More than 20 friends can be accessed using the Cursor() method." }, { "code": "# the screen_name of the targeted userscreen_name = \"TwitterIndia\" # getting only 30 friendsfor friend in tweepy.Cursor(api.friends, screen_name).items(30): print(friend.screen_name)", "e": 2249, "s": 2062, "text": null }, { "code": null, "e": 2258, "s": 2249, "text": "Output :" }, { "code": null, "e": 2604, "s": 2258, "text": "misskaul\nrajyasabhatv\nDDNewslive\nTwitterMedia\nabpmajhatv\nhtTweets\nNews18Haryana\njack\nBBCHindi\nthe_hindu\nmentalhealthind\nProKabaddi\nfirstpost\nlivemint\nhcmariwala\nmathrubhumi\nPTUshaOfficial\nanubhabhonsle\nkmmalleswari\nDipaKarmakar\nNewIndianXpress\nM_Raj03\nDDNational\nisro\nPTTVOnlineNews\ncricketnext\nthebetterindia\nAGSawant\nMahendraP_BJP\nDrRPNishank\n" }, { "code": null, "e": 2649, "s": 2604, "text": "Example 3: Counting the number of followers." }, { "code": "# the screen_name of the targeted userscreen_name = \"geeksforgeeks\" # getting all the friendsc = tweepy.Cursor(api.friends, screen_name) # counting the number of friendscount = 0for friends in c.items(): count += 1print(screen_name + \" has \" + str(count) + \" friends.\")", "e": 2924, "s": 2649, "text": null }, { "code": null, "e": 2933, "s": 2924, "text": "Output :" }, { "code": null, "e": 2962, "s": 2933, "text": "geeksforgeeks has 8 friends." }, { "code": null, "e": 2976, "s": 2962, "text": "Python-Tweepy" }, { "code": null, "e": 2983, "s": 2976, "text": "Python" }, { "code": null, "e": 3081, "s": 2983, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3099, "s": 3081, "text": "Python Dictionary" }, { "code": null, "e": 3141, "s": 3099, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3163, "s": 3141, "text": "Enumerate() in Python" }, { "code": null, "e": 3198, "s": 3163, "text": "Read a file line by line in Python" }, { "code": null, "e": 3224, "s": 3198, "text": "Python String | replace()" }, { "code": null, "e": 3256, "s": 3224, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3285, "s": 3256, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3315, "s": 3285, "text": "Iterate over a list in Python" }, { "code": null, "e": 3342, "s": 3315, "text": "Python Classes and Objects" } ]
Java.io.FileInputStream Class in Java
19 Apr, 2022 FileInputStream class is useful to read data from a file in the form of sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader. Constructors of FileInputStream Class 1. FileInputStream(File file): Creates an input file stream to read from the specified File object. 2. FileInputStream(FileDescriptor fdobj) :Creates an input file stream to read from the specified file descriptor. 3. FileInputStream(String name): Creates an input file stream to read from a file with the specified name. Methods of FileInputStream Class Now when we do use these methods we do generically follow these steps to read data from a file using FileInputStream which is ultimatum the goal of FileInputClass Step 1: Attach a file to a FileInputStream as this will enable us to read data from the file as shown below as follows: FileInputStream fileInputStream =new FileInputStream(“file.txt”); Step 2: Now in order to read data from the file, we should read data from the FileInputStream as shown below: ch=fileInputStream.read(); Step 3-A: When there is no more data available to read further, the read() method returns -1; Step 3-B: Then we should attach the monitor to the output stream. For displaying the data, we can use System.out.print. System.out.print(ch); Implementation: Original File content: This is my first line This is my second line Example: Java // Java Program to Demonstrate FileInputStream Class // Importing I/O classesimport java.io.*; // Main class// ReadFileclass GFG { // Main driver method public static void main(String args[]) throws IOException { // Attaching the file to FileInputStream FileInputStream fin = new FileInputStream("file1.txt"); // Illustrating getChannel() method System.out.println(fin.getChannel()); // Illustrating getFD() method System.out.println(fin.getFD()); // Illustrating available method System.out.println("Number of remaining bytes:" + fin.available()); // Illustrating skip() method fin.skip(4); // Display message for better readability System.out.println("FileContents :"); // Reading characters from FileInputStream // and write them int ch; // Holds true till there is data inside file while ((ch = fin.read()) != -1) System.out.print((char)ch); // Close the file connections // using close() method fin.close(); }} Output: sun.nio.ch.FileChannelImpl@1540e19d java.io.FileDescriptor@677327b6 Number of remaining bytes:45 FileContents : is my first line This is my second line BufferedInputStream can be used to read a buffer full of data at a time from a file. This improves the speed of execution.This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. solankimayank kashishsoda surindertarika1234 simmytarika5 java-file-handling Java-I/O java-stream Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Apr, 2022" }, { "code": null, "e": 283, "s": 52, "text": "FileInputStream class is useful to read data from a file in the form of sequence of bytes. FileInputStream is meant for reading streams of raw bytes such as image data. For reading streams of characters, consider using FileReader." }, { "code": null, "e": 321, "s": 283, "text": "Constructors of FileInputStream Class" }, { "code": null, "e": 422, "s": 321, "text": "1. FileInputStream(File file): Creates an input file stream to read from the specified File object. " }, { "code": null, "e": 538, "s": 422, "text": "2. FileInputStream(FileDescriptor fdobj) :Creates an input file stream to read from the specified file descriptor. " }, { "code": null, "e": 647, "s": 538, "text": "3. FileInputStream(String name): Creates an input file stream to read from a file with the specified name. " }, { "code": null, "e": 680, "s": 647, "text": "Methods of FileInputStream Class" }, { "code": null, "e": 843, "s": 680, "text": "Now when we do use these methods we do generically follow these steps to read data from a file using FileInputStream which is ultimatum the goal of FileInputClass" }, { "code": null, "e": 963, "s": 843, "text": "Step 1: Attach a file to a FileInputStream as this will enable us to read data from the file as shown below as follows:" }, { "code": null, "e": 1030, "s": 963, "text": "FileInputStream fileInputStream =new FileInputStream(“file.txt”);" }, { "code": null, "e": 1140, "s": 1030, "text": "Step 2: Now in order to read data from the file, we should read data from the FileInputStream as shown below:" }, { "code": null, "e": 1167, "s": 1140, "text": "ch=fileInputStream.read();" }, { "code": null, "e": 1262, "s": 1167, "text": "Step 3-A: When there is no more data available to read further, the read() method returns -1; " }, { "code": null, "e": 1384, "s": 1262, "text": "Step 3-B: Then we should attach the monitor to the output stream. For displaying the data, we can use System.out.print. " }, { "code": null, "e": 1406, "s": 1384, "text": "System.out.print(ch);" }, { "code": null, "e": 1422, "s": 1406, "text": "Implementation:" }, { "code": null, "e": 1445, "s": 1422, "text": "Original File content:" }, { "code": null, "e": 1490, "s": 1445, "text": "This is my first line\nThis is my second line" }, { "code": null, "e": 1499, "s": 1490, "text": "Example:" }, { "code": null, "e": 1504, "s": 1499, "text": "Java" }, { "code": "// Java Program to Demonstrate FileInputStream Class // Importing I/O classesimport java.io.*; // Main class// ReadFileclass GFG { // Main driver method public static void main(String args[]) throws IOException { // Attaching the file to FileInputStream FileInputStream fin = new FileInputStream(\"file1.txt\"); // Illustrating getChannel() method System.out.println(fin.getChannel()); // Illustrating getFD() method System.out.println(fin.getFD()); // Illustrating available method System.out.println(\"Number of remaining bytes:\" + fin.available()); // Illustrating skip() method fin.skip(4); // Display message for better readability System.out.println(\"FileContents :\"); // Reading characters from FileInputStream // and write them int ch; // Holds true till there is data inside file while ((ch = fin.read()) != -1) System.out.print((char)ch); // Close the file connections // using close() method fin.close(); }}", "e": 2637, "s": 1504, "text": null }, { "code": null, "e": 2646, "s": 2637, "text": "Output: " }, { "code": null, "e": 2799, "s": 2646, "text": "sun.nio.ch.FileChannelImpl@1540e19d\njava.io.FileDescriptor@677327b6\nNumber of remaining bytes:45\nFileContents :\n is my first line\nThis is my second line" }, { "code": null, "e": 3344, "s": 2799, "text": "BufferedInputStream can be used to read a buffer full of data at a time from a file. This improves the speed of execution.This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 3358, "s": 3344, "text": "solankimayank" }, { "code": null, "e": 3370, "s": 3358, "text": "kashishsoda" }, { "code": null, "e": 3389, "s": 3370, "text": "surindertarika1234" }, { "code": null, "e": 3402, "s": 3389, "text": "simmytarika5" }, { "code": null, "e": 3421, "s": 3402, "text": "java-file-handling" }, { "code": null, "e": 3430, "s": 3421, "text": "Java-I/O" }, { "code": null, "e": 3442, "s": 3430, "text": "java-stream" }, { "code": null, "e": 3447, "s": 3442, "text": "Java" }, { "code": null, "e": 3452, "s": 3447, "text": "Java" } ]
Remove the Chrome’s “No file chosen option” from a file input using JavaScript
11 Jul, 2022 The task is to remove the “no file chosen” value from the empty input element in chrome. We are going to achieve that task with the help of JavaScript. Approach 1: Remove the tooltip value(‘No file chosen’). Use .attr() method to set the value of title attribute to empty. Example 1: This example removes the tooltip value. <!DOCTYPE HTML><html> <head> <title> Remove the “No file chosen” from a file input in Chrome? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <div> <input type='file' /> </div> <br> <button onclick="gfg_Run()"> Remove tooltip </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to remove the tooltip value '" + "No file is chosen.'"; function gfg_Run() { $('input').attr('title', ''); el_down.innerHTML = "Tooltip value has been removed."; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Remove the value(‘No file chosen’). Use .addClass() method to add the class which removes the value “No file chosen”. Example 2: This example remove the value “No file chosen” from input element. <!DOCTYPE HTML><html> <head> <title> Remove the “No file chosen” from a file input in Chrome? </title> <style> .removeValue { color: transparent; } </style> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 15px; font-weight: bold;"> </p> <div> <input type="file" /> </div> <br> <button onclick="gfg_Run()"> Remove value </button> <p id="GFG_DOWN" style="color:green; font-size: 20px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); el_up.innerHTML = "Click on the button to remove the value '" + "No file is chosen.'"; function gfg_Run() { $('input').addClass('removeValue'); el_down.innerHTML = "Value has been removed."; } </script></body> </html> Output: Before clicking on the button: After clicking on the button: JavaScript-Misc JavaScript 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": "\n11 Jul, 2022" }, { "code": null, "e": 180, "s": 28, "text": "The task is to remove the “no file chosen” value from the empty input element in chrome. We are going to achieve that task with the help of JavaScript." }, { "code": null, "e": 192, "s": 180, "text": "Approach 1:" }, { "code": null, "e": 236, "s": 192, "text": "Remove the tooltip value(‘No file chosen’)." }, { "code": null, "e": 301, "s": 236, "text": "Use .attr() method to set the value of title attribute to empty." }, { "code": null, "e": 352, "s": 301, "text": "Example 1: This example removes the tooltip value." }, { "code": "<!DOCTYPE HTML><html> <head> <title> Remove the “No file chosen” from a file input in Chrome? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <div> <input type='file' /> </div> <br> <button onclick=\"gfg_Run()\"> Remove tooltip </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to remove the tooltip value '\" + \"No file is chosen.'\"; function gfg_Run() { $('input').attr('title', ''); el_down.innerHTML = \"Tooltip value has been removed.\"; } </script></body> </html>", "e": 1453, "s": 352, "text": null }, { "code": null, "e": 1461, "s": 1453, "text": "Output:" }, { "code": null, "e": 1492, "s": 1461, "text": "Before clicking on the button:" }, { "code": null, "e": 1522, "s": 1492, "text": "After clicking on the button:" }, { "code": null, "e": 1534, "s": 1522, "text": "Approach 2:" }, { "code": null, "e": 1570, "s": 1534, "text": "Remove the value(‘No file chosen’)." }, { "code": null, "e": 1652, "s": 1570, "text": "Use .addClass() method to add the class which removes the value “No file chosen”." }, { "code": null, "e": 1730, "s": 1652, "text": "Example 2: This example remove the value “No file chosen” from input element." }, { "code": "<!DOCTYPE HTML><html> <head> <title> Remove the “No file chosen” from a file input in Chrome? </title> <style> .removeValue { color: transparent; } </style> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 15px; font-weight: bold;\"> </p> <div> <input type=\"file\" /> </div> <br> <button onclick=\"gfg_Run()\"> Remove value </button> <p id=\"GFG_DOWN\" style=\"color:green; font-size: 20px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); el_up.innerHTML = \"Click on the button to remove the value '\" + \"No file is chosen.'\"; function gfg_Run() { $('input').addClass('removeValue'); el_down.innerHTML = \"Value has been removed.\"; } </script></body> </html>", "e": 2900, "s": 1730, "text": null }, { "code": null, "e": 2908, "s": 2900, "text": "Output:" }, { "code": null, "e": 2939, "s": 2908, "text": "Before clicking on the button:" }, { "code": null, "e": 2969, "s": 2939, "text": "After clicking on the button:" }, { "code": null, "e": 2985, "s": 2969, "text": "JavaScript-Misc" }, { "code": null, "e": 2996, "s": 2985, "text": "JavaScript" }, { "code": null, "e": 3013, "s": 2996, "text": "Web Technologies" } ]
Python program to print negative numbers in a list
26 Oct, 2018 Given a list of numbers, write a Python program to print all negative numbers in given list. Example: Input: list1 = [12, -7, 5, 64, -14] Output: -7, -14 Input: list2 = [12, 14, -95, 3] Output: -95 Example #1: Print all negative numbers from given list using for loop Iterate each element in the list using for loop and check if number is less than 0. If the condition satisfies, then only print the number. # Python program to print negative Numbers in a List # list of numberslist1 = [11, -21, 0, 45, 66, -93] # iterating each number in listfor num in list1: # checking condition if num < 0: print(num, end = " ") Output: -21 -93 Example #2: Using while loop # Python program to print negative Numbers in a List # list of numberslist1 = [-10, 21, -4, -45, -66, 93]num = 0 # using while loop while(num < len(list1)): # checking condition if list1[num] < 0: print(list1[num], end = " ") # increment num num += 1 Output: -10 -4 -45 -66 Example #3: Using list comprehension # Python program to print negative Numbers in a List # list of numberslist1 = [-10, -21, -4, 45, -66, 93] # using list comprehensionneg_nos = [num for num in list1 if num < 0] print("Negative numbers in the list: ", *neg_nos) Output: Negative numbers in the list: -10 -21 -4 -66 Example #4: Using lambda expressions # Python program to print negative Numbers in a List # list of numbers list1 = [-10, 21, 4, -45, -66, 93, -11] # we can also print negative no's using lambda exp. neg_nos = list(filter(lambda x: (x < 0), list1)) print("Negative numbers in the list: ", *neg_nos) Output: Negative numbers in the list: -10 -45 -66 -11 Python list-programs python-list Python Python Programs School Programming python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Oct, 2018" }, { "code": null, "e": 145, "s": 52, "text": "Given a list of numbers, write a Python program to print all negative numbers in given list." }, { "code": null, "e": 154, "s": 145, "text": "Example:" }, { "code": null, "e": 251, "s": 154, "text": "Input: list1 = [12, -7, 5, 64, -14]\nOutput: -7, -14\n\nInput: list2 = [12, 14, -95, 3]\nOutput: -95" }, { "code": null, "e": 321, "s": 251, "text": "Example #1: Print all negative numbers from given list using for loop" }, { "code": null, "e": 461, "s": 321, "text": "Iterate each element in the list using for loop and check if number is less than 0. If the condition satisfies, then only print the number." }, { "code": "# Python program to print negative Numbers in a List # list of numberslist1 = [11, -21, 0, 45, 66, -93] # iterating each number in listfor num in list1: # checking condition if num < 0: print(num, end = \" \")", "e": 689, "s": 461, "text": null }, { "code": null, "e": 697, "s": 689, "text": "Output:" }, { "code": null, "e": 706, "s": 697, "text": "-21 -93 " }, { "code": null, "e": 736, "s": 706, "text": " Example #2: Using while loop" }, { "code": "# Python program to print negative Numbers in a List # list of numberslist1 = [-10, 21, -4, -45, -66, 93]num = 0 # using while loop while(num < len(list1)): # checking condition if list1[num] < 0: print(list1[num], end = \" \") # increment num num += 1 ", "e": 1030, "s": 736, "text": null }, { "code": null, "e": 1038, "s": 1030, "text": "Output:" }, { "code": null, "e": 1054, "s": 1038, "text": "-10 -4 -45 -66 " }, { "code": null, "e": 1092, "s": 1054, "text": " Example #3: Using list comprehension" }, { "code": "# Python program to print negative Numbers in a List # list of numberslist1 = [-10, -21, -4, 45, -66, 93] # using list comprehensionneg_nos = [num for num in list1 if num < 0] print(\"Negative numbers in the list: \", *neg_nos)", "e": 1321, "s": 1092, "text": null }, { "code": null, "e": 1329, "s": 1321, "text": "Output:" }, { "code": null, "e": 1375, "s": 1329, "text": "Negative numbers in the list: -10 -21 -4 -66" }, { "code": null, "e": 1413, "s": 1375, "text": " Example #4: Using lambda expressions" }, { "code": "# Python program to print negative Numbers in a List # list of numbers list1 = [-10, 21, 4, -45, -66, 93, -11] # we can also print negative no's using lambda exp. neg_nos = list(filter(lambda x: (x < 0), list1)) print(\"Negative numbers in the list: \", *neg_nos) ", "e": 1682, "s": 1413, "text": null }, { "code": null, "e": 1690, "s": 1682, "text": "Output:" }, { "code": null, "e": 1737, "s": 1690, "text": "Negative numbers in the list: -10 -45 -66 -11" }, { "code": null, "e": 1758, "s": 1737, "text": "Python list-programs" }, { "code": null, "e": 1770, "s": 1758, "text": "python-list" }, { "code": null, "e": 1777, "s": 1770, "text": "Python" }, { "code": null, "e": 1793, "s": 1777, "text": "Python Programs" }, { "code": null, "e": 1812, "s": 1793, "text": "School Programming" }, { "code": null, "e": 1824, "s": 1812, "text": "python-list" }, { "code": null, "e": 1922, "s": 1824, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1964, "s": 1922, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1986, "s": 1964, "text": "Enumerate() in Python" }, { "code": null, "e": 2012, "s": 1986, "text": "Python String | replace()" }, { "code": null, "e": 2044, "s": 2012, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2073, "s": 2044, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2095, "s": 2073, "text": "Defaultdict in Python" }, { "code": null, "e": 2134, "s": 2095, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2172, "s": 2134, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2221, "s": 2172, "text": "Python | Convert string dictionary to dictionary" } ]
Date from() method in Java with Examples
26 Mar, 2019 The from(Instant inst) method of Java Date class returns an instance of date which is obtained from an Instant object. Syntax: public static Date from(Instant inst) Parameters: The method takes one parameter inst of Instant type which is required to be converted. Return Value: The method returns a date representing the same point on the timeline as the passing instant. Exceptions: NullPointerException: This is thrown when the instant is left null. IllegalArgumentException: This is thrown when the instant is too large to be represented as a Date. Below programs illustrate the use of from() Method in Java:Example 1: // Java code to demonstrate// from() method of Date class import java.time.Instant;import java.util.Date; public class JavaDateDemo { public static void main(String args[]) { // Creating Date Object Date dateOne = new Date(); // Creating Instant object Instant inst = Instant.now(); // Displaying the instant System.out.println( "Present: " + dateOne.from(inst)); }} Present: Tue Mar 26 06:45:40 UTC 2019 Example 2: import java.util.Date;import java.util.Calendar;import java.time.Instant; public class GfG { public static void main(String args[]) { // Creating a Calendar object Calendar c1 = Calendar.getInstance(); // Set Month // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 00); // Set Date c1.set(Calendar.DATE, 30); // Set Year c1.set(Calendar.YEAR, 2019); // Creating a date object // with specified time. Date dateOne = c1.getTime(); Instant inst = dateOne.toInstant(); System.out.println( "Date: " + dateOne.from(inst)); }} Date: Wed Jan 30 06:45:43 UTC 2019 Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#from-java.time.Instant- Java - util package Java-Functions Java-util-Date Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2019" }, { "code": null, "e": 147, "s": 28, "text": "The from(Instant inst) method of Java Date class returns an instance of date which is obtained from an Instant object." }, { "code": null, "e": 155, "s": 147, "text": "Syntax:" }, { "code": null, "e": 193, "s": 155, "text": "public static Date from(Instant inst)" }, { "code": null, "e": 292, "s": 193, "text": "Parameters: The method takes one parameter inst of Instant type which is required to be converted." }, { "code": null, "e": 400, "s": 292, "text": "Return Value: The method returns a date representing the same point on the timeline as the passing instant." }, { "code": null, "e": 412, "s": 400, "text": "Exceptions:" }, { "code": null, "e": 480, "s": 412, "text": "NullPointerException: This is thrown when the instant is left null." }, { "code": null, "e": 580, "s": 480, "text": "IllegalArgumentException: This is thrown when the instant is too large to be represented as a Date." }, { "code": null, "e": 650, "s": 580, "text": "Below programs illustrate the use of from() Method in Java:Example 1:" }, { "code": "// Java code to demonstrate// from() method of Date class import java.time.Instant;import java.util.Date; public class JavaDateDemo { public static void main(String args[]) { // Creating Date Object Date dateOne = new Date(); // Creating Instant object Instant inst = Instant.now(); // Displaying the instant System.out.println( \"Present: \" + dateOne.from(inst)); }}", "e": 1096, "s": 650, "text": null }, { "code": null, "e": 1135, "s": 1096, "text": "Present: Tue Mar 26 06:45:40 UTC 2019\n" }, { "code": null, "e": 1146, "s": 1135, "text": "Example 2:" }, { "code": "import java.util.Date;import java.util.Calendar;import java.time.Instant; public class GfG { public static void main(String args[]) { // Creating a Calendar object Calendar c1 = Calendar.getInstance(); // Set Month // MONTH starts with 0 i.e. ( 0 - Jan) c1.set(Calendar.MONTH, 00); // Set Date c1.set(Calendar.DATE, 30); // Set Year c1.set(Calendar.YEAR, 2019); // Creating a date object // with specified time. Date dateOne = c1.getTime(); Instant inst = dateOne.toInstant(); System.out.println( \"Date: \" + dateOne.from(inst)); }}", "e": 1809, "s": 1146, "text": null }, { "code": null, "e": 1845, "s": 1809, "text": "Date: Wed Jan 30 06:45:43 UTC 2019\n" }, { "code": null, "e": 1942, "s": 1845, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html#from-java.time.Instant-" }, { "code": null, "e": 1962, "s": 1942, "text": "Java - util package" }, { "code": null, "e": 1977, "s": 1962, "text": "Java-Functions" }, { "code": null, "e": 1992, "s": 1977, "text": "Java-util-Date" }, { "code": null, "e": 1997, "s": 1992, "text": "Java" }, { "code": null, "e": 2002, "s": 1997, "text": "Java" } ]
JSP PageContext – Implicit Objects
28 Jul, 2021 PageContext extends JspContext to contribute helpful context details while JSP technology is applied in a Servlet environment. A PageContext is an instance that gives access to all the namespaces related to a JSP page, gives access to some page attributes and a layer over the application details. Implicit objects are connected to the pageContext consequently. The PageContext class is an abstract class that is formed to be extended to give application-dependent applications whereof by compatible JSP engine runtime environments. In JSP, pageContext is an instance of javax.servlet.jsp.PageContext. The entire JSP page is represented by the PageContext object. This object is considered as a method to obtain detail about the page while keeping away from most of the execution information. For each request, the credentials to the response and request objects are saved by this pageContext object. By accessing attributes of the pageContext object, the out, session, config, and application objects are obtained. This pageContext object further holds information regarding the directives provided to the JSP page, together with the page scope, buffering information, and the errorPageURL. By using the pageContext object you can set attributes, get attributes and remove attributes that are present in the different scopes like as page, request, session, and application scopes which are given below as follows: page – Scope: PAGE_CONTEXTrequest – Scope: REQUEST_CONTEXTsession – Scope: SESSION_CONTEXTapplication – Scope: APPLICATION_CONTEXT page – Scope: PAGE_CONTEXT request – Scope: REQUEST_CONTEXT session – Scope: SESSION_CONTEXT application – Scope: APPLICATION_CONTEXT Note: Page scope is the default scope in JSP. Syntax: public abstract class PageContext extends JspContext Syntax: To use pageContext pageContext.methodName(“name of attribute”, “scope”); Adhering forward, now let us discuss the methods used in pageContext implicit object. Below several methods are proposed that are used in pageContext object of which most frequently been involved are discussed below individually to a depth followed by clean java program to illustrate the implementation of implicit objects in JSP PageContext class. Remember: It supports over 40 methods which are inherited from ContextClass. Method 1: getAttribute (String AttributeName, int Scope) The getAttribute method finds an attribute in the described scope. For example, the statement given below the getAttribute method finds the attribute “GeeksforGeeks” in the scope of Session (Session layer). If it finds the attribute then it will assign the attribute to Object obj otherwise it will return Null. Syntax: Object obj = pageContext.getAttribute("GeeksforGeeks", PageContext.SESSION_CONTEXT); Correspondingly, this method can be used for more other scopes also, like as follows: Object obj = pageContext.getAttribute(“GeeksforGeeks”, PageContext. REQUEST_CONTEXT); Object obj = pageContext.getAttribute(“GeeksforGeeks”, PageContext. PAGE_CONTEXT); Object obj = pageContext.getAttribute(“GeeksforGeeks”, PageContext. APPLICATION_CONTEXT); Method 2: findAttribute (String AttributeName) The findAttribute() method finds the described attribute in all four levels in the following order listed below. At any level, if no attribute is found then it will return NULL. Page --> Request --> Session and Application Method 3: void setAttribute(String AttributeName, Object AttributeValue, int Scope) This method sets down an attribute in a given scope. For example, consider the statement given below will save an Attribute “data” in the scope of application with the value “This is data”. Syntax: pageContext.setAttribute(“data”, “This is data”, PageContext. APPLICATION_CONTEXT); Correspondingly, this method will design an attribute named attr1 in the scope of Request with the value “Attr1 value” is as follows: pageContext.setAttribute(“attr1”, “Attr1 value”, PageContext. REQUEST_CONTEXT); Method 4: void removeAttribute(String AttributeName, int Scope) In order to remove an attribute from a given scope, this method is used. For example, consider the JSP statement given below will remove an Attribute “Attr” from page scope. Syntax: pageContext.removeAttribute(“Attr”, PageContext. PAGE_CONTEXT); Lastly, let us implement via illustrating HTML code samples of pageContext implicit object Example 1: index.html Page 1: In this HTML page, we are simply asking the user to enter the name. HTML <!DOCTYPE html><html><head><meta charset="ISO-8859-1"><title>GeeksforGeeks</title></head><body> <form action="welcome.jsp"> <input type="text" name="uname"> <input type="submit" value="go"><br/> </form> </body></html> Page 2: It is a JSP page, we are saving the user’s name using pageContext implicit object with the session scope, means we will be able to access the details until the user’s session is active. Example 2: welcome.jsp HTML <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html><html><head><meta charset="ISO-8859-1"><title>Insert title here</title></head><body> <% String name=request.getParameter("uname"); out.print("Welcome "+name); pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE); %> <a href="second.jsp">second jsp page</a> </body></html> Page 3: In this JSP page, we are retrieving the saved attributes using the getAttribute method. The point which is to be considered here is that we have saved the attributes with session scope so we should need to state scope as a session so as to retrieve those attribute’s value. Example 3: second.jsp HTML <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%><!DOCTYPE html><html><head><meta charset="ISO-8859-1"><title>Insert title here</title></head><body> <% String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE); out.print("Hello "+name); %> </body></html> Output: An HTML page where we are receiving the user’s name. B JSP page along with details page link. C User Credentials display page that we have moved from html page to this page by pageContext instance. Java-JSP Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Functional Interfaces in Java Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2021" }, { "code": null, "e": 390, "s": 28, "text": "PageContext extends JspContext to contribute helpful context details while JSP technology is applied in a Servlet environment. A PageContext is an instance that gives access to all the namespaces related to a JSP page, gives access to some page attributes and a layer over the application details. Implicit objects are connected to the pageContext consequently." }, { "code": null, "e": 630, "s": 390, "text": "The PageContext class is an abstract class that is formed to be extended to give application-dependent applications whereof by compatible JSP engine runtime environments. In JSP, pageContext is an instance of javax.servlet.jsp.PageContext." }, { "code": null, "e": 821, "s": 630, "text": "The entire JSP page is represented by the PageContext object. This object is considered as a method to obtain detail about the page while keeping away from most of the execution information." }, { "code": null, "e": 1044, "s": 821, "text": "For each request, the credentials to the response and request objects are saved by this pageContext object. By accessing attributes of the pageContext object, the out, session, config, and application objects are obtained." }, { "code": null, "e": 1220, "s": 1044, "text": "This pageContext object further holds information regarding the directives provided to the JSP page, together with the page scope, buffering information, and the errorPageURL." }, { "code": null, "e": 1443, "s": 1220, "text": "By using the pageContext object you can set attributes, get attributes and remove attributes that are present in the different scopes like as page, request, session, and application scopes which are given below as follows:" }, { "code": null, "e": 1574, "s": 1443, "text": "page – Scope: PAGE_CONTEXTrequest – Scope: REQUEST_CONTEXTsession – Scope: SESSION_CONTEXTapplication – Scope: APPLICATION_CONTEXT" }, { "code": null, "e": 1601, "s": 1574, "text": "page – Scope: PAGE_CONTEXT" }, { "code": null, "e": 1634, "s": 1601, "text": "request – Scope: REQUEST_CONTEXT" }, { "code": null, "e": 1667, "s": 1634, "text": "session – Scope: SESSION_CONTEXT" }, { "code": null, "e": 1708, "s": 1667, "text": "application – Scope: APPLICATION_CONTEXT" }, { "code": null, "e": 1754, "s": 1708, "text": "Note: Page scope is the default scope in JSP." }, { "code": null, "e": 1762, "s": 1754, "text": "Syntax:" }, { "code": null, "e": 1815, "s": 1762, "text": "public abstract class PageContext\nextends JspContext" }, { "code": null, "e": 1842, "s": 1815, "text": "Syntax: To use pageContext" }, { "code": null, "e": 1896, "s": 1842, "text": "pageContext.methodName(“name of attribute”, “scope”);" }, { "code": null, "e": 2246, "s": 1896, "text": "Adhering forward, now let us discuss the methods used in pageContext implicit object. Below several methods are proposed that are used in pageContext object of which most frequently been involved are discussed below individually to a depth followed by clean java program to illustrate the implementation of implicit objects in JSP PageContext class." }, { "code": null, "e": 2324, "s": 2246, "text": "Remember: It supports over 40 methods which are inherited from ContextClass. " }, { "code": null, "e": 2382, "s": 2324, "text": "Method 1: getAttribute (String AttributeName, int Scope) " }, { "code": null, "e": 2694, "s": 2382, "text": "The getAttribute method finds an attribute in the described scope. For example, the statement given below the getAttribute method finds the attribute “GeeksforGeeks” in the scope of Session (Session layer). If it finds the attribute then it will assign the attribute to Object obj otherwise it will return Null." }, { "code": null, "e": 2703, "s": 2694, "text": "Syntax: " }, { "code": null, "e": 2788, "s": 2703, "text": "Object obj = pageContext.getAttribute(\"GeeksforGeeks\", PageContext.SESSION_CONTEXT);" }, { "code": null, "e": 2874, "s": 2788, "text": "Correspondingly, this method can be used for more other scopes also, like as follows:" }, { "code": null, "e": 2960, "s": 2874, "text": "Object obj = pageContext.getAttribute(“GeeksforGeeks”, PageContext. REQUEST_CONTEXT);" }, { "code": null, "e": 3043, "s": 2960, "text": "Object obj = pageContext.getAttribute(“GeeksforGeeks”, PageContext. PAGE_CONTEXT);" }, { "code": null, "e": 3133, "s": 3043, "text": "Object obj = pageContext.getAttribute(“GeeksforGeeks”, PageContext. APPLICATION_CONTEXT);" }, { "code": null, "e": 3180, "s": 3133, "text": "Method 2: findAttribute (String AttributeName)" }, { "code": null, "e": 3359, "s": 3180, "text": "The findAttribute() method finds the described attribute in all four levels in the following order listed below. At any level, if no attribute is found then it will return NULL. " }, { "code": null, "e": 3404, "s": 3359, "text": "Page --> Request --> Session and Application" }, { "code": null, "e": 3488, "s": 3404, "text": "Method 3: void setAttribute(String AttributeName, Object AttributeValue, int Scope)" }, { "code": null, "e": 3678, "s": 3488, "text": "This method sets down an attribute in a given scope. For example, consider the statement given below will save an Attribute “data” in the scope of application with the value “This is data”." }, { "code": null, "e": 3686, "s": 3678, "text": "Syntax:" }, { "code": null, "e": 3770, "s": 3686, "text": "pageContext.setAttribute(“data”, “This is data”, PageContext. APPLICATION_CONTEXT);" }, { "code": null, "e": 3904, "s": 3770, "text": "Correspondingly, this method will design an attribute named attr1 in the scope of Request with the value “Attr1 value” is as follows:" }, { "code": null, "e": 3984, "s": 3904, "text": "pageContext.setAttribute(“attr1”, “Attr1 value”, PageContext. REQUEST_CONTEXT);" }, { "code": null, "e": 4049, "s": 3984, "text": "Method 4: void removeAttribute(String AttributeName, int Scope) " }, { "code": null, "e": 4223, "s": 4049, "text": "In order to remove an attribute from a given scope, this method is used. For example, consider the JSP statement given below will remove an Attribute “Attr” from page scope." }, { "code": null, "e": 4231, "s": 4223, "text": "Syntax:" }, { "code": null, "e": 4295, "s": 4231, "text": "pageContext.removeAttribute(“Attr”, PageContext. PAGE_CONTEXT);" }, { "code": null, "e": 4386, "s": 4295, "text": "Lastly, let us implement via illustrating HTML code samples of pageContext implicit object" }, { "code": null, "e": 4408, "s": 4386, "text": "Example 1: index.html" }, { "code": null, "e": 4484, "s": 4408, "text": "Page 1: In this HTML page, we are simply asking the user to enter the name." }, { "code": null, "e": 4489, "s": 4484, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>GeeksforGeeks</title></head><body> <form action=\"welcome.jsp\"> <input type=\"text\" name=\"uname\"> <input type=\"submit\" value=\"go\"><br/> </form> </body></html>", "e": 4712, "s": 4489, "text": null }, { "code": null, "e": 4906, "s": 4712, "text": "Page 2: It is a JSP page, we are saving the user’s name using pageContext implicit object with the session scope, means we will be able to access the details until the user’s session is active." }, { "code": null, "e": 4930, "s": 4906, "text": "Example 2: welcome.jsp " }, { "code": null, "e": 4935, "s": 4930, "text": "HTML" }, { "code": "<%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%><!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Insert title here</title></head><body> <% String name=request.getParameter(\"uname\"); out.print(\"Welcome \"+name); pageContext.setAttribute(\"user\",name,PageContext.SESSION_SCOPE); %> <a href=\"second.jsp\">second jsp page</a> </body></html>", "e": 5353, "s": 4935, "text": null }, { "code": null, "e": 5635, "s": 5353, "text": "Page 3: In this JSP page, we are retrieving the saved attributes using the getAttribute method. The point which is to be considered here is that we have saved the attributes with session scope so we should need to state scope as a session so as to retrieve those attribute’s value." }, { "code": null, "e": 5657, "s": 5635, "text": "Example 3: second.jsp" }, { "code": null, "e": 5662, "s": 5657, "text": "HTML" }, { "code": "<%@ page language=\"java\" contentType=\"text/html; charset=ISO-8859-1\" pageEncoding=\"ISO-8859-1\"%><!DOCTYPE html><html><head><meta charset=\"ISO-8859-1\"><title>Insert title here</title></head><body> <% String name=(String)pageContext.getAttribute(\"user\",PageContext.SESSION_SCOPE); out.print(\"Hello \"+name); %> </body></html>", "e": 6002, "s": 5662, "text": null }, { "code": null, "e": 6011, "s": 6002, "text": "Output: " }, { "code": null, "e": 6064, "s": 6011, "text": "An HTML page where we are receiving the user’s name." }, { "code": null, "e": 6105, "s": 6064, "text": "B JSP page along with details page link." }, { "code": null, "e": 6209, "s": 6105, "text": "C User Credentials display page that we have moved from html page to this page by pageContext instance." }, { "code": null, "e": 6218, "s": 6209, "text": "Java-JSP" }, { "code": null, "e": 6223, "s": 6218, "text": "Java" }, { "code": null, "e": 6228, "s": 6223, "text": "Java" }, { "code": null, "e": 6326, "s": 6228, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6341, "s": 6326, "text": "Stream In Java" }, { "code": null, "e": 6362, "s": 6341, "text": "Introduction to Java" }, { "code": null, "e": 6383, "s": 6362, "text": "Constructors in Java" }, { "code": null, "e": 6402, "s": 6383, "text": "Exceptions in Java" }, { "code": null, "e": 6419, "s": 6402, "text": "Generics in Java" }, { "code": null, "e": 6445, "s": 6419, "text": "Java Programming Examples" }, { "code": null, "e": 6475, "s": 6445, "text": "Functional Interfaces in Java" }, { "code": null, "e": 6491, "s": 6475, "text": "Strings in Java" }, { "code": null, "e": 6528, "s": 6491, "text": "Differences between JDK, JRE and JVM" } ]
SQL Query to Convert Datetime to Date
14 Sep, 2021 In MS SQL Server, dates are complicated for newbies, since while working with the database, the format of the date in the table must be matched with the input date in order to insert. In various scenarios instead of date, DateTime (time is also involved with date) is used. In this article, we will learn how to convert a DateTime to a DATE by using the three different functions. CAST( ) CONVERT( ) TRY_CONVERT( ) Using Substring The aim of this article data is to convert DateTime to Date in SQL Server like YYYY-MM-DD HH:MM: SS to YYYY-MM-DD. This is a function for casting one type to another type, So here we will use for cast DateTime to date. Syntax: CAST( dateToConvert AS DATE) Example 1: Query: SELECT CAST(GETDATE() AS DATE) AS CURRENT_DATE Output: GETDATE(): This function return current date time like(2021-08-27 17:26:36.710) Example 2; Query: SELECT CAST('2021-08-27 17:26:36.710' AS DATE) AS CURRENT_DATE_GFG Output: This is a function for convert one type to another type, So here we will use it to convert DateTime to date. Syntax: CONVERT(DATE, dateToConvert) Example 1: Query: SELECT CONVERT(DATE, GETDATE()) AS CURRENT_DATE_GFG Output: Example 2: Query: SELECT CONVERT(DATE, '2021-08-27 17:26:36.710' ) AS CURRENT_DATE_GFG Output: This is a function for casting one type to another type, So here we will use for Convert DateTime to date. if the date is invalid then it will be null while Convert generates an error. Syntax: TRY_CONVERT(DATE, dateToConvert) SELECT TRY_CONVERT(DATE,’2021-08-27 17:26:36.710′) AS CURRENT_DATE_GFG Example 1: Query: SELECT TRY_CONVERT(DATE,GETDATE()) AS CURRENT_DATE_GFG Output: Example 2: Query: SELECT TRY_CONVERT(DATE,'2021-08-27 17:26:36.710') AS CURRENT_DATE_GFG Output: This is a function to use get a short string or substring, so here use we get substring 0 to 11 index. Syntax: SUBSTRING( dateToConvert ,0,11) Example 1: Query: SELECT SUBSTRING( '2021-08-27 17:26:36.710' ,0,11) AS CURRENT_DATE_GFG Output: Example 2; Query: SELECT SUBSTRING( CONVERT(varchar(17), GETDATE(), 23) ,0,11) AS CURRENT_DATE_GFG Output: Blogathon-2021 Picked SQL-Query Blogathon SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Sep, 2021" }, { "code": null, "e": 409, "s": 28, "text": "In MS SQL Server, dates are complicated for newbies, since while working with the database, the format of the date in the table must be matched with the input date in order to insert. In various scenarios instead of date, DateTime (time is also involved with date) is used. In this article, we will learn how to convert a DateTime to a DATE by using the three different functions." }, { "code": null, "e": 418, "s": 409, "text": "CAST( ) " }, { "code": null, "e": 429, "s": 418, "text": "CONVERT( )" }, { "code": null, "e": 444, "s": 429, "text": "TRY_CONVERT( )" }, { "code": null, "e": 460, "s": 444, "text": "Using Substring" }, { "code": null, "e": 577, "s": 460, "text": " The aim of this article data is to convert DateTime to Date in SQL Server like YYYY-MM-DD HH:MM: SS to YYYY-MM-DD. " }, { "code": null, "e": 681, "s": 577, "text": "This is a function for casting one type to another type, So here we will use for cast DateTime to date." }, { "code": null, "e": 689, "s": 681, "text": "Syntax:" }, { "code": null, "e": 718, "s": 689, "text": "CAST( dateToConvert AS DATE)" }, { "code": null, "e": 729, "s": 718, "text": "Example 1:" }, { "code": null, "e": 736, "s": 729, "text": "Query:" }, { "code": null, "e": 783, "s": 736, "text": "SELECT CAST(GETDATE() AS DATE) AS CURRENT_DATE" }, { "code": null, "e": 791, "s": 783, "text": "Output:" }, { "code": null, "e": 871, "s": 791, "text": "GETDATE(): This function return current date time like(2021-08-27 17:26:36.710)" }, { "code": null, "e": 882, "s": 871, "text": "Example 2;" }, { "code": null, "e": 889, "s": 882, "text": "Query:" }, { "code": null, "e": 956, "s": 889, "text": "SELECT CAST('2021-08-27 17:26:36.710' AS DATE) AS CURRENT_DATE_GFG" }, { "code": null, "e": 964, "s": 956, "text": "Output:" }, { "code": null, "e": 1073, "s": 964, "text": "This is a function for convert one type to another type, So here we will use it to convert DateTime to date." }, { "code": null, "e": 1081, "s": 1073, "text": "Syntax:" }, { "code": null, "e": 1110, "s": 1081, "text": "CONVERT(DATE, dateToConvert)" }, { "code": null, "e": 1121, "s": 1110, "text": "Example 1:" }, { "code": null, "e": 1128, "s": 1121, "text": "Query:" }, { "code": null, "e": 1180, "s": 1128, "text": "SELECT CONVERT(DATE, GETDATE()) AS CURRENT_DATE_GFG" }, { "code": null, "e": 1188, "s": 1180, "text": "Output:" }, { "code": null, "e": 1199, "s": 1188, "text": "Example 2:" }, { "code": null, "e": 1206, "s": 1199, "text": "Query:" }, { "code": null, "e": 1275, "s": 1206, "text": "SELECT CONVERT(DATE, '2021-08-27 17:26:36.710' ) AS CURRENT_DATE_GFG" }, { "code": null, "e": 1283, "s": 1275, "text": "Output:" }, { "code": null, "e": 1469, "s": 1283, "text": "This is a function for casting one type to another type, So here we will use for Convert DateTime to date. if the date is invalid then it will be null while Convert generates an error. " }, { "code": null, "e": 1477, "s": 1469, "text": "Syntax:" }, { "code": null, "e": 1510, "s": 1477, "text": "TRY_CONVERT(DATE, dateToConvert)" }, { "code": null, "e": 1581, "s": 1510, "text": "SELECT TRY_CONVERT(DATE,’2021-08-27 17:26:36.710′) AS CURRENT_DATE_GFG" }, { "code": null, "e": 1592, "s": 1581, "text": "Example 1:" }, { "code": null, "e": 1599, "s": 1592, "text": "Query:" }, { "code": null, "e": 1654, "s": 1599, "text": "SELECT TRY_CONVERT(DATE,GETDATE()) AS CURRENT_DATE_GFG" }, { "code": null, "e": 1662, "s": 1654, "text": "Output:" }, { "code": null, "e": 1673, "s": 1662, "text": "Example 2:" }, { "code": null, "e": 1680, "s": 1673, "text": "Query:" }, { "code": null, "e": 1751, "s": 1680, "text": "SELECT TRY_CONVERT(DATE,'2021-08-27 17:26:36.710') AS CURRENT_DATE_GFG" }, { "code": null, "e": 1759, "s": 1751, "text": "Output:" }, { "code": null, "e": 1862, "s": 1759, "text": "This is a function to use get a short string or substring, so here use we get substring 0 to 11 index." }, { "code": null, "e": 1870, "s": 1862, "text": "Syntax:" }, { "code": null, "e": 1902, "s": 1870, "text": "SUBSTRING( dateToConvert ,0,11)" }, { "code": null, "e": 1913, "s": 1902, "text": "Example 1:" }, { "code": null, "e": 1920, "s": 1913, "text": "Query:" }, { "code": null, "e": 1991, "s": 1920, "text": "SELECT SUBSTRING( '2021-08-27 17:26:36.710' ,0,11) AS CURRENT_DATE_GFG" }, { "code": null, "e": 1999, "s": 1991, "text": "Output:" }, { "code": null, "e": 2010, "s": 1999, "text": "Example 2;" }, { "code": null, "e": 2017, "s": 2010, "text": "Query:" }, { "code": null, "e": 2098, "s": 2017, "text": "SELECT SUBSTRING( CONVERT(varchar(17), GETDATE(), 23) ,0,11) AS CURRENT_DATE_GFG" }, { "code": null, "e": 2106, "s": 2098, "text": "Output:" }, { "code": null, "e": 2121, "s": 2106, "text": "Blogathon-2021" }, { "code": null, "e": 2128, "s": 2121, "text": "Picked" }, { "code": null, "e": 2138, "s": 2128, "text": "SQL-Query" }, { "code": null, "e": 2148, "s": 2138, "text": "Blogathon" }, { "code": null, "e": 2152, "s": 2148, "text": "SQL" }, { "code": null, "e": 2156, "s": 2152, "text": "SQL" } ]
Draw an rectangle using OpenCV in C++
19 Mar, 2021 In this article, the task is to draw an rectangle using OpenCV in C++. The rectangle() function from OpenCV C++ library will be used. Syntax: rectangle( img, pt1, pt2, color, thickness, line Type, shift) Parameters: image: It is the image on which the rectangle is to be drawn. start(pt1): It is the top left corner of the rectangle represented as the tuple of two coordinates i.e., (x-coordinate, y-coordinate). end(pt2): It is the bottom right corner of the rectangle represented as the tuple of two coordinates i.e., (x-coordinate, y-coordinate). color: It is the color of the borderline of the rectangle to be drawn. A tuple representing 3 colors (B, G, R) i.e., (Blue, Green, Red). thickness: It is the thickness of the rectangle borderline in px. The thickness of -1 px will fill the rectangle shape by the specified color. lineType: Type of the line. There are 3 types of line:LINE_4: Line was drawn using 4 connected Bresenham algorithm.LINE_8: Line was drawn using 8 connected Bresenham algorithm.LINE_AA: It draws Anti-aliased lines formed by using a Gaussian filter. LINE_4: Line was drawn using 4 connected Bresenham algorithm. LINE_8: Line was drawn using 8 connected Bresenham algorithm. LINE_AA: It draws Anti-aliased lines formed by using a Gaussian filter. shift: The number of fractional bits in the point coordinates. Return Value: It returns an image. Program 1: Below is the C++ program demonstrating how to draw a rectangle over a self-formed background image: C++ // C++ program to demonstrate rectangle// over a self-formed background image #include <iostream>#include <opencv2/core/core.hpp> // Drawing shapes#include <opencv2/imgproc.hpp> #include <opencv2/highgui/highgui.hpp>using namespace cv;using namespace std; // Driver Codeint main(int argc, char** argv){ // Creating a blank image with // white background Mat image(500, 500, CV_8UC3, Scalar(255, 255, 255)); // Check if the image is created // successfully or not if (!image.data) { std::cout << "Could not open or " << "find the image\n"; return 0; } // Top Left Corner Point p1(30, 30); // Bottom Right Corner Point p2(255, 255); int thickness = 2; // Drawing the Rectangle rectangle(image, p1, p2, Scalar(255, 0, 0), thickness, LINE_8); // Show our image inside a window imshow("Output", image); waitKey(0); return 0;} Output: Program 2: Below is the C++ program demonstrating how to draw a rectangle over the image of the GFG Logo: C++ // C++ program to demonstrate rectangle// over a loaded image of GFG logo #include <iostream>#include <opencv2/core/core.hpp> // Drawing shapes#include <opencv2/imgproc.hpp> #include <opencv2/highgui/highgui.hpp>using namespace cv;using namespace std; // Driver Codeint main(int argc, char** argv){ // Reading the Image Mat image = imread("C:/Users/harsh/Downloads/geeks.png", IMREAD_COLOR); // Check if the image is created // successfully or not if (!image.data) { std::cout << "Could not open or " << "find the image\n"; return 0; } // Top Left Coordinates Point p1(30, 70); // Bottom Right Coordinates Point p2(115, 155); int thickness = 2; // Drawing the Rectangle rectangle(image, p1, p2, Scalar(255, 0, 0), thickness, LINE_8); // Show our image inside a window imshow("Output", image); waitKey(0); return 0;} Output: Program 3: Below is the C++ program demonstrating how to draw a rectangle filled with color: C++ // C++ program to demonstrate rectangle// filled with any color #include <iostream>#include <opencv2/core/core.hpp> // Drawing shapes#include <opencv2/imgproc.hpp> #include <opencv2/highgui/highgui.hpp>using namespace cv;using namespace std; // Driver Codeint main(int argc, char** argv){ // Creating a blank image with // white background Mat image(500, 500, CV_8UC3, Scalar(255, 255, 255)); // Check if the image is created // successfully or not if (!image.data) { std::cout << "Could not open or " << "find the image\n"; return 0; } // Top Left Corner Point p1(30, 30); // Bottom Right Corner Point p2(255, 255); int thickness = -1; // Drawing the Rectangle rectangle(image, p1, p2, Scalar(0, 255, 0), thickness, LINE_8); // Show our image inside a window imshow("Output", image); waitKey(0); return 0;} Output: computer-graphics OpenCV C++ C++ Programs CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sorting a vector in C++ Polymorphism in C++ Friend class and function in C++ Pair in C++ Standard Template Library (STL) std::string class in C++ Header files in C/C++ and its uses Sorting a Map by value in C++ STL Program to print ASCII Value of a character How to return multiple values from a function in C or C++? Shallow Copy and Deep Copy in C++
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Mar, 2021" }, { "code": null, "e": 162, "s": 28, "text": "In this article, the task is to draw an rectangle using OpenCV in C++. The rectangle() function from OpenCV C++ library will be used." }, { "code": null, "e": 170, "s": 162, "text": "Syntax:" }, { "code": null, "e": 232, "s": 170, "text": "rectangle( img, pt1, pt2, color, thickness, line Type, shift)" }, { "code": null, "e": 244, "s": 232, "text": "Parameters:" }, { "code": null, "e": 306, "s": 244, "text": "image: It is the image on which the rectangle is to be drawn." }, { "code": null, "e": 441, "s": 306, "text": "start(pt1): It is the top left corner of the rectangle represented as the tuple of two coordinates i.e., (x-coordinate, y-coordinate)." }, { "code": null, "e": 578, "s": 441, "text": "end(pt2): It is the bottom right corner of the rectangle represented as the tuple of two coordinates i.e., (x-coordinate, y-coordinate)." }, { "code": null, "e": 715, "s": 578, "text": "color: It is the color of the borderline of the rectangle to be drawn. A tuple representing 3 colors (B, G, R) i.e., (Blue, Green, Red)." }, { "code": null, "e": 858, "s": 715, "text": "thickness: It is the thickness of the rectangle borderline in px. The thickness of -1 px will fill the rectangle shape by the specified color." }, { "code": null, "e": 1106, "s": 858, "text": "lineType: Type of the line. There are 3 types of line:LINE_4: Line was drawn using 4 connected Bresenham algorithm.LINE_8: Line was drawn using 8 connected Bresenham algorithm.LINE_AA: It draws Anti-aliased lines formed by using a Gaussian filter." }, { "code": null, "e": 1168, "s": 1106, "text": "LINE_4: Line was drawn using 4 connected Bresenham algorithm." }, { "code": null, "e": 1230, "s": 1168, "text": "LINE_8: Line was drawn using 8 connected Bresenham algorithm." }, { "code": null, "e": 1302, "s": 1230, "text": "LINE_AA: It draws Anti-aliased lines formed by using a Gaussian filter." }, { "code": null, "e": 1365, "s": 1302, "text": "shift: The number of fractional bits in the point coordinates." }, { "code": null, "e": 1400, "s": 1365, "text": "Return Value: It returns an image." }, { "code": null, "e": 1411, "s": 1400, "text": "Program 1:" }, { "code": null, "e": 1511, "s": 1411, "text": "Below is the C++ program demonstrating how to draw a rectangle over a self-formed background image:" }, { "code": null, "e": 1515, "s": 1511, "text": "C++" }, { "code": "// C++ program to demonstrate rectangle// over a self-formed background image #include <iostream>#include <opencv2/core/core.hpp> // Drawing shapes#include <opencv2/imgproc.hpp> #include <opencv2/highgui/highgui.hpp>using namespace cv;using namespace std; // Driver Codeint main(int argc, char** argv){ // Creating a blank image with // white background Mat image(500, 500, CV_8UC3, Scalar(255, 255, 255)); // Check if the image is created // successfully or not if (!image.data) { std::cout << \"Could not open or \" << \"find the image\\n\"; return 0; } // Top Left Corner Point p1(30, 30); // Bottom Right Corner Point p2(255, 255); int thickness = 2; // Drawing the Rectangle rectangle(image, p1, p2, Scalar(255, 0, 0), thickness, LINE_8); // Show our image inside a window imshow(\"Output\", image); waitKey(0); return 0;}", "e": 2480, "s": 1515, "text": null }, { "code": null, "e": 2488, "s": 2480, "text": "Output:" }, { "code": null, "e": 2499, "s": 2488, "text": "Program 2:" }, { "code": null, "e": 2594, "s": 2499, "text": "Below is the C++ program demonstrating how to draw a rectangle over the image of the GFG Logo:" }, { "code": null, "e": 2598, "s": 2594, "text": "C++" }, { "code": "// C++ program to demonstrate rectangle// over a loaded image of GFG logo #include <iostream>#include <opencv2/core/core.hpp> // Drawing shapes#include <opencv2/imgproc.hpp> #include <opencv2/highgui/highgui.hpp>using namespace cv;using namespace std; // Driver Codeint main(int argc, char** argv){ // Reading the Image Mat image = imread(\"C:/Users/harsh/Downloads/geeks.png\", IMREAD_COLOR); // Check if the image is created // successfully or not if (!image.data) { std::cout << \"Could not open or \" << \"find the image\\n\"; return 0; } // Top Left Coordinates Point p1(30, 70); // Bottom Right Coordinates Point p2(115, 155); int thickness = 2; // Drawing the Rectangle rectangle(image, p1, p2, Scalar(255, 0, 0), thickness, LINE_8); // Show our image inside a window imshow(\"Output\", image); waitKey(0); return 0;}", "e": 3562, "s": 2598, "text": null }, { "code": null, "e": 3570, "s": 3562, "text": "Output:" }, { "code": null, "e": 3581, "s": 3570, "text": "Program 3:" }, { "code": null, "e": 3663, "s": 3581, "text": "Below is the C++ program demonstrating how to draw a rectangle filled with color:" }, { "code": null, "e": 3667, "s": 3663, "text": "C++" }, { "code": "// C++ program to demonstrate rectangle// filled with any color #include <iostream>#include <opencv2/core/core.hpp> // Drawing shapes#include <opencv2/imgproc.hpp> #include <opencv2/highgui/highgui.hpp>using namespace cv;using namespace std; // Driver Codeint main(int argc, char** argv){ // Creating a blank image with // white background Mat image(500, 500, CV_8UC3, Scalar(255, 255, 255)); // Check if the image is created // successfully or not if (!image.data) { std::cout << \"Could not open or \" << \"find the image\\n\"; return 0; } // Top Left Corner Point p1(30, 30); // Bottom Right Corner Point p2(255, 255); int thickness = -1; // Drawing the Rectangle rectangle(image, p1, p2, Scalar(0, 255, 0), thickness, LINE_8); // Show our image inside a window imshow(\"Output\", image); waitKey(0); return 0;}", "e": 4619, "s": 3667, "text": null }, { "code": null, "e": 4627, "s": 4619, "text": "Output:" }, { "code": null, "e": 4645, "s": 4627, "text": "computer-graphics" }, { "code": null, "e": 4652, "s": 4645, "text": "OpenCV" }, { "code": null, "e": 4656, "s": 4652, "text": "C++" }, { "code": null, "e": 4669, "s": 4656, "text": "C++ Programs" }, { "code": null, "e": 4673, "s": 4669, "text": "CPP" }, { "code": null, "e": 4771, "s": 4673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4795, "s": 4771, "text": "Sorting a vector in C++" }, { "code": null, "e": 4815, "s": 4795, "text": "Polymorphism in C++" }, { "code": null, "e": 4848, "s": 4815, "text": "Friend class and function in C++" }, { "code": null, "e": 4892, "s": 4848, "text": "Pair in C++ Standard Template Library (STL)" }, { "code": null, "e": 4917, "s": 4892, "text": "std::string class in C++" }, { "code": null, "e": 4952, "s": 4917, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 4986, "s": 4952, "text": "Sorting a Map by value in C++ STL" }, { "code": null, "e": 5030, "s": 4986, "text": "Program to print ASCII Value of a character" }, { "code": null, "e": 5089, "s": 5030, "text": "How to return multiple values from a function in C or C++?" } ]
ReactJS - Forms
In this chapter, we will learn how to use forms in React. In the following example, we will set an input form with value = {this.state.data}. This allows to update the state whenever the input value changes. We are using onChange event that will watch the input changes and update the state accordingly. import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { data: 'Initial data...' } this.updateState = this.updateState.bind(this); }; updateState(e) { this.setState({data: e.target.value}); } render() { return ( <div> <input type = "text" value = {this.state.data} onChange = {this.updateState} /> <h4>{this.state.data}</h4> </div> ); } } export default App; import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/>, document.getElementById('app')); When the input text value changes, the state will be updated. In the following example, we will see how to use forms from child component. onChange method will trigger state update that will be passed to the child input value and rendered on the screen. A similar example is used in the Events chapter. Whenever we need to update state from child component, we need to pass the function that will handle updating (updateState) as a prop (updateStateProp). import React from 'react'; class App extends React.Component { constructor(props) { super(props); this.state = { data: 'Initial data...' } this.updateState = this.updateState.bind(this); }; updateState(e) { this.setState({data: e.target.value}); } render() { return ( <div> <Content myDataProp = {this.state.data} updateStateProp = {this.updateState}></Content> </div> ); } } class Content extends React.Component { render() { return ( <div> <input type = "text" value = {this.props.myDataProp} onChange = {this.props.updateStateProp} /> <h3>{this.props.myDataProp}</h3> </div> ); } } export default App; import React from 'react'; import ReactDOM from 'react-dom'; import App from './App.jsx'; ReactDOM.render(<App/>, document.getElementById('app')); This will produce the following result.
[ { "code": null, "e": 2225, "s": 2167, "text": "In this chapter, we will learn how to use forms in React." }, { "code": null, "e": 2471, "s": 2225, "text": "In the following example, we will set an input form with value = {this.state.data}. This allows to update the state whenever the input value changes. We are using onChange event that will watch the input changes and update the state accordingly." }, { "code": null, "e": 3021, "s": 2471, "text": "import React from 'react';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n \n this.state = {\n data: 'Initial data...'\n }\n this.updateState = this.updateState.bind(this);\n };\n updateState(e) {\n this.setState({data: e.target.value});\n }\n render() {\n return (\n <div>\n <input type = \"text\" value = {this.state.data} \n onChange = {this.updateState} />\n <h4>{this.state.data}</h4>\n </div>\n );\n }\n}\nexport default App;" }, { "code": null, "e": 3169, "s": 3021, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App.jsx';\n\nReactDOM.render(<App/>, document.getElementById('app'));" }, { "code": null, "e": 3231, "s": 3169, "text": "When the input text value changes, the state will be updated." }, { "code": null, "e": 3625, "s": 3231, "text": "In the following example, we will see how to use forms from child component. onChange method will trigger state update that will be passed to the child input value and rendered on the screen. A similar example is used in the Events chapter. Whenever we need to update state from child component, we need to pass the function that will handle updating (updateState) as a prop (updateStateProp)." }, { "code": null, "e": 4429, "s": 3625, "text": "import React from 'react';\n\nclass App extends React.Component {\n constructor(props) {\n super(props);\n \n this.state = {\n data: 'Initial data...'\n }\n this.updateState = this.updateState.bind(this);\n };\n updateState(e) {\n this.setState({data: e.target.value});\n }\n render() {\n return (\n <div>\n <Content myDataProp = {this.state.data} \n updateStateProp = {this.updateState}></Content>\n </div>\n );\n }\n}\nclass Content extends React.Component {\n render() {\n return (\n <div>\n <input type = \"text\" value = {this.props.myDataProp} \n onChange = {this.props.updateStateProp} />\n <h3>{this.props.myDataProp}</h3>\n </div>\n );\n }\n}\nexport default App;" }, { "code": null, "e": 4577, "s": 4429, "text": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App.jsx';\n\nReactDOM.render(<App/>, document.getElementById('app'));" } ]
Matplotlib.axes.Axes.format_ydata() in Python
19 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.format_ydata() function in axes module of matplotlib library is used to return y formatted as an y-value. Syntax: Axes.format_ydata(self, y) Below examples illustrate the matplotlib.axes.Axes.format_ydata() function in matplotlib.axes: Example 1: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.cbook as cbook years = mdates.YearLocator() months = mdates.MonthLocator() years_fmt = mdates.DateFormatter('% Y') with cbook.get_sample_data('goog.npz') as datafile: data = np.load(datafile)['price_data'].view(np.recarray) fig, ax = plt.subplots()ax.plot('date', 'adj_close', data = data[:300], color ="green") ax.xaxis.set_major_locator(years) ax.format_ydata = lambda x: '$% 1.2f' % xax.grid(True) fig.autofmt_xdate()fig.suptitle('matplotlib.axes.Axes.format_ydata() function\ Example', fontweight ="bold")plt.show() Output: Example 2: # Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.cbook as cbook years = mdates.YearLocator() months = mdates.MonthLocator() years_fmt = mdates.DateFormatter('% Y') with cbook.get_sample_data('goog.npz') as datafile: data = np.load(datafile)['price_data'] fig, ax = plt.subplots()ax.plot('date', 'adj_close', data = data, color ="k") ax.yaxis.set_major_locator(years)ax.yaxis.set_major_formatter(years_fmt)ax.yaxis.set_minor_locator(months) ax.format_ydata = mdates.DateFormatter('% Y')ax.grid(True) fig.suptitle('matplotlib.axes.Axes.format_ydata() function\ Example', fontweight ="bold")plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Apr, 2020" }, { "code": null, "e": 328, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 443, "s": 328, "text": "The Axes.format_ydata() function in axes module of matplotlib library is used to return y formatted as an y-value." }, { "code": null, "e": 451, "s": 443, "text": "Syntax:" }, { "code": null, "e": 479, "s": 451, "text": "Axes.format_ydata(self, y)\n" }, { "code": null, "e": 574, "s": 479, "text": "Below examples illustrate the matplotlib.axes.Axes.format_ydata() function in matplotlib.axes:" }, { "code": null, "e": 585, "s": 574, "text": "Example 1:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.cbook as cbook years = mdates.YearLocator() months = mdates.MonthLocator() years_fmt = mdates.DateFormatter('% Y') with cbook.get_sample_data('goog.npz') as datafile: data = np.load(datafile)['price_data'].view(np.recarray) fig, ax = plt.subplots()ax.plot('date', 'adj_close', data = data[:300], color =\"green\") ax.xaxis.set_major_locator(years) ax.format_ydata = lambda x: '$% 1.2f' % xax.grid(True) fig.autofmt_xdate()fig.suptitle('matplotlib.axes.Axes.format_ydata() function\\ Example', fontweight =\"bold\")plt.show()", "e": 1263, "s": 585, "text": null }, { "code": null, "e": 1271, "s": 1263, "text": "Output:" }, { "code": null, "e": 1282, "s": 1271, "text": "Example 2:" }, { "code": "# Implementation of matplotlib functionimport numpy as npimport matplotlib.pyplot as pltimport matplotlib.dates as mdatesimport matplotlib.cbook as cbook years = mdates.YearLocator() months = mdates.MonthLocator() years_fmt = mdates.DateFormatter('% Y') with cbook.get_sample_data('goog.npz') as datafile: data = np.load(datafile)['price_data'] fig, ax = plt.subplots()ax.plot('date', 'adj_close', data = data, color =\"k\") ax.yaxis.set_major_locator(years)ax.yaxis.set_major_formatter(years_fmt)ax.yaxis.set_minor_locator(months) ax.format_ydata = mdates.DateFormatter('% Y')ax.grid(True) fig.suptitle('matplotlib.axes.Axes.format_ydata() function\\ Example', fontweight =\"bold\")plt.show()", "e": 1988, "s": 1282, "text": null }, { "code": null, "e": 1996, "s": 1988, "text": "Output:" }, { "code": null, "e": 2014, "s": 1996, "text": "Python-matplotlib" }, { "code": null, "e": 2021, "s": 2014, "text": "Python" } ]
Get first and last elements from ArrayList in Java
07 Jun, 2019 Given an array list, find the first and last elements of it. Examples: Input : aList = {10, 30, 20, 14, 2} Output : First = 10, Last = 2 Input : aList = {10, 30, 40, 50, 60} Output : First = 10, Last = 60 The last element is at index, size – 1 and the first element is stored at index 0. If we know how to get the size of ArrayList then we can get those two values easily. But remember, that you need to use size() method for ArrayList, not length, length is used to get the length of an array. Find First and Last in ArrayList: // java program print first and last element of a Listimport java.util.ArrayList;import java.util.List;public class FindFirstLast { public static void getFirstLat(List<Integer> list) { // Displaying ArrayList elements System.out.println("ArrayList contains: " + list); // Logic to get the last element from ArrayList if (list != null && !list.isEmpty()) { System.out.println("First element is: " + list.get(0)); System.out.println("Last element is: " + list.get(list.size() - 1)); return; } } public static void main(String[] args) { /* Creating ArrayList of Integer and adding elements to it */ List<Integer> al = new ArrayList<Integer>(); al.add(3); al.add(1); al.add(4); al.add(5); al.add(2); getFirstLat(al); }} ArrayList contains: [3, 1, 4, 5, 2] First element is: 3 Last element is: 2 Application : The first element is your lowest and the last element is your highest in case of ascending order and opposite then the first element would be the maximum and last element would be the minimum if List is in descending order. // java program print Maximum and Minimum Value of a// sorted List, List may be increasing or decreasing orderimport java.util.ArrayList;import java.util.List;public class FindFirstLast { // function find and print Maximum and Minimum value public static void getFirstLat(List<Integer> list) { // Displaying ArrayList elements System.out.println("ArrayList contains: " + list); // Logic to get the last element from ArrayList if (list != null && !list.isEmpty()) { if (list.get(0) < list.get(list.size() - 1)) { // if list in increasing order System.out.println("Minimum Value: " + list.get(0)); System.out.println("Maximum Value: " + list.get(list.size() - 1)); return; } else { // if list in decreasing order System.out.println("Minimum Value: " + list.get(list.size() - 1)); System.out.println("Maximum Value: " + list.get(0)); return; } } } public static void main(String[] args) { /* Creating ArrayList of Integer and adding elements to it */ List<Integer> al = new ArrayList<Integer>(); al.add(5); al.add(4); al.add(3); al.add(2); al.add(1); getFirstLat(al); }} ArrayList contains: [5, 4, 3, 2, 1] Minimum Value: 1 Maximum Value: 5 nidhi_biet Java-ArrayList Java-Collections Java-List-Programs Technical Scripter 2018 Java Technical Scripter Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Queue Interface In Java For-each loop in Java Interfaces in Java Object Oriented Programming (OOPs) Concept in Java Stack Class in Java ChronoZonedDateTime isAfter() method in Java with Examples
[ { "code": null, "e": 52, "s": 24, "text": "\n07 Jun, 2019" }, { "code": null, "e": 113, "s": 52, "text": "Given an array list, find the first and last elements of it." }, { "code": null, "e": 123, "s": 113, "text": "Examples:" }, { "code": null, "e": 259, "s": 123, "text": "Input : aList = {10, 30, 20, 14, 2}\nOutput : First = 10, Last = 2\n\nInput : aList = {10, 30, 40, 50, 60}\nOutput : First = 10, Last = 60\n" }, { "code": null, "e": 549, "s": 259, "text": "The last element is at index, size – 1 and the first element is stored at index 0. If we know how to get the size of ArrayList then we can get those two values easily. But remember, that you need to use size() method for ArrayList, not length, length is used to get the length of an array." }, { "code": null, "e": 583, "s": 549, "text": "Find First and Last in ArrayList:" }, { "code": "// java program print first and last element of a Listimport java.util.ArrayList;import java.util.List;public class FindFirstLast { public static void getFirstLat(List<Integer> list) { // Displaying ArrayList elements System.out.println(\"ArrayList contains: \" + list); // Logic to get the last element from ArrayList if (list != null && !list.isEmpty()) { System.out.println(\"First element is: \" + list.get(0)); System.out.println(\"Last element is: \" + list.get(list.size() - 1)); return; } } public static void main(String[] args) { /* Creating ArrayList of Integer and adding elements to it */ List<Integer> al = new ArrayList<Integer>(); al.add(3); al.add(1); al.add(4); al.add(5); al.add(2); getFirstLat(al); }}", "e": 1518, "s": 583, "text": null }, { "code": null, "e": 1594, "s": 1518, "text": "ArrayList contains: [3, 1, 4, 5, 2]\nFirst element is: 3\nLast element is: 2\n" }, { "code": null, "e": 1832, "s": 1594, "text": "Application : The first element is your lowest and the last element is your highest in case of ascending order and opposite then the first element would be the maximum and last element would be the minimum if List is in descending order." }, { "code": "// java program print Maximum and Minimum Value of a// sorted List, List may be increasing or decreasing orderimport java.util.ArrayList;import java.util.List;public class FindFirstLast { // function find and print Maximum and Minimum value public static void getFirstLat(List<Integer> list) { // Displaying ArrayList elements System.out.println(\"ArrayList contains: \" + list); // Logic to get the last element from ArrayList if (list != null && !list.isEmpty()) { if (list.get(0) < list.get(list.size() - 1)) { // if list in increasing order System.out.println(\"Minimum Value: \" + list.get(0)); System.out.println(\"Maximum Value: \" + list.get(list.size() - 1)); return; } else { // if list in decreasing order System.out.println(\"Minimum Value: \" + list.get(list.size() - 1)); System.out.println(\"Maximum Value: \" + list.get(0)); return; } } } public static void main(String[] args) { /* Creating ArrayList of Integer and adding elements to it */ List<Integer> al = new ArrayList<Integer>(); al.add(5); al.add(4); al.add(3); al.add(2); al.add(1); getFirstLat(al); }}", "e": 3322, "s": 1832, "text": null }, { "code": null, "e": 3393, "s": 3322, "text": "ArrayList contains: [5, 4, 3, 2, 1]\nMinimum Value: 1\nMaximum Value: 5\n" }, { "code": null, "e": 3404, "s": 3393, "text": "nidhi_biet" }, { "code": null, "e": 3419, "s": 3404, "text": "Java-ArrayList" }, { "code": null, "e": 3436, "s": 3419, "text": "Java-Collections" }, { "code": null, "e": 3455, "s": 3436, "text": "Java-List-Programs" }, { "code": null, "e": 3479, "s": 3455, "text": "Technical Scripter 2018" }, { "code": null, "e": 3484, "s": 3479, "text": "Java" }, { "code": null, "e": 3503, "s": 3484, "text": "Technical Scripter" }, { "code": null, "e": 3508, "s": 3503, "text": "Java" }, { "code": null, "e": 3525, "s": 3508, "text": "Java-Collections" }, { "code": null, "e": 3623, "s": 3525, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3638, "s": 3623, "text": "Arrays in Java" }, { "code": null, "e": 3682, "s": 3638, "text": "Split() String method in Java with examples" }, { "code": null, "e": 3718, "s": 3682, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 3743, "s": 3718, "text": "Reverse a string in Java" }, { "code": null, "e": 3767, "s": 3743, "text": "Queue Interface In Java" }, { "code": null, "e": 3789, "s": 3767, "text": "For-each loop in Java" }, { "code": null, "e": 3808, "s": 3789, "text": "Interfaces in Java" }, { "code": null, "e": 3859, "s": 3808, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3879, "s": 3859, "text": "Stack Class in Java" } ]
How to Build a Simple Web Server with Golang?
10 Oct, 2021 Golang is a procedural programming language ideal to build simple, reliable, and efficient software. Create a project folder with a .go file inside eg. server.go. Directory structure: The server.go file: Go package main import ( "fmt" "log" "net/http") func main() { // API routes http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hello world from GfG") }) http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hi") }) port := ":5000" fmt.Println("Server is running on port" + port) // Start server on port specified above log.Fatal(http.ListenAndServe(port, nil))} Run the server using the following command (make sure you’re in the project directory): go run server.go Note: You have to stop the server with Ctrl + C and restart via the same command whenever the server.go file is changed. Console: Open the desired web browser and any of these URLs to verify if the server is running: http://localhost:5000/ or http://localhost:5000/hi Output: Create a static folder with all the static files.Example directory structure: The GfG logo The index.html file HTML <html> <head> <title>Home</title> </head> <body> <h2>Home page</h2> </body></html> The about.html file HTML <html> <head> <title>About</title> </head> <body> <h2>about page!</h2> </body></html> Now Edit the server.go file: Go package main import ( "fmt" "log" "net/http") func main() { // API routes // Serve files from static folder http.Handle("/", http.FileServer(http.Dir("./static"))) // Serve api /hi http.HandleFunc("/hi", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, "Hi") }) port := ":5000" fmt.Println("Server is running on port" + port) // Start server on port specified above log.Fatal(http.ListenAndServe(port, nil)) } Verifying if static files are served: aniruddhashriwant Go Language How To Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Parse JSON in Golang? How to iterate over an Array using for loop in Golang? Structures in Golang Loops in Go Language Time Durations in Golang How to Install PIP on Windows ? How to Find the Wi-Fi Password Using CMD in Windows? How to install Jupyter Notebook on Windows? Java Tutorial How to filter object array based on attributes?
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Oct, 2021" }, { "code": null, "e": 130, "s": 28, "text": "Golang is a procedural programming language ideal to build simple, reliable, and efficient software. " }, { "code": null, "e": 193, "s": 130, "text": "Create a project folder with a .go file inside eg. server.go. " }, { "code": null, "e": 214, "s": 193, "text": "Directory structure:" }, { "code": null, "e": 234, "s": 214, "text": "The server.go file:" }, { "code": null, "e": 237, "s": 234, "text": "Go" }, { "code": "package main import ( \"fmt\" \"log\" \"net/http\") func main() { // API routes http.HandleFunc(\"/\", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, \"Hello world from GfG\") }) http.HandleFunc(\"/hi\", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, \"Hi\") }) port := \":5000\" fmt.Println(\"Server is running on port\" + port) // Start server on port specified above log.Fatal(http.ListenAndServe(port, nil))}", "e": 715, "s": 237, "text": null }, { "code": null, "e": 803, "s": 715, "text": "Run the server using the following command (make sure you’re in the project directory):" }, { "code": null, "e": 820, "s": 803, "text": "go run server.go" }, { "code": null, "e": 944, "s": 820, "text": "Note: You have to stop the server with Ctrl + C and restart via the same command whenever the server.go file is changed. " }, { "code": null, "e": 953, "s": 944, "text": "Console:" }, { "code": null, "e": 1040, "s": 953, "text": "Open the desired web browser and any of these URLs to verify if the server is running:" }, { "code": null, "e": 1091, "s": 1040, "text": "http://localhost:5000/ or http://localhost:5000/hi" }, { "code": null, "e": 1099, "s": 1091, "text": "Output:" }, { "code": null, "e": 1177, "s": 1099, "text": "Create a static folder with all the static files.Example directory structure:" }, { "code": null, "e": 1190, "s": 1177, "text": "The GfG logo" }, { "code": null, "e": 1210, "s": 1190, "text": "The index.html file" }, { "code": null, "e": 1215, "s": 1210, "text": "HTML" }, { "code": "<html> <head> <title>Home</title> </head> <body> <h2>Home page</h2> </body></html>", "e": 1308, "s": 1215, "text": null }, { "code": null, "e": 1331, "s": 1311, "text": "The about.html file" }, { "code": null, "e": 1338, "s": 1333, "text": "HTML" }, { "code": "<html> <head> <title>About</title> </head> <body> <h2>about page!</h2> </body></html>", "e": 1434, "s": 1338, "text": null }, { "code": null, "e": 1463, "s": 1434, "text": "Now Edit the server.go file:" }, { "code": null, "e": 1466, "s": 1463, "text": "Go" }, { "code": "package main import ( \"fmt\" \"log\" \"net/http\") func main() { // API routes // Serve files from static folder http.Handle(\"/\", http.FileServer(http.Dir(\"./static\"))) // Serve api /hi http.HandleFunc(\"/hi\", func(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, \"Hi\") }) port := \":5000\" fmt.Println(\"Server is running on port\" + port) // Start server on port specified above log.Fatal(http.ListenAndServe(port, nil)) }", "e": 1940, "s": 1466, "text": null }, { "code": null, "e": 1978, "s": 1940, "text": "Verifying if static files are served:" }, { "code": null, "e": 1996, "s": 1978, "text": "aniruddhashriwant" }, { "code": null, "e": 2008, "s": 1996, "text": "Go Language" }, { "code": null, "e": 2015, "s": 2008, "text": "How To" }, { "code": null, "e": 2032, "s": 2015, "text": "Web Technologies" }, { "code": null, "e": 2130, "s": 2032, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2159, "s": 2130, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 2214, "s": 2159, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 2235, "s": 2214, "text": "Structures in Golang" }, { "code": null, "e": 2256, "s": 2235, "text": "Loops in Go Language" }, { "code": null, "e": 2281, "s": 2256, "text": "Time Durations in Golang" }, { "code": null, "e": 2313, "s": 2281, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2366, "s": 2313, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 2410, "s": 2366, "text": "How to install Jupyter Notebook on Windows?" }, { "code": null, "e": 2424, "s": 2410, "text": "Java Tutorial" } ]
mode() function in Python statistics module
23 Aug, 2021 The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode.Python is very robust when it comes to statistics and working with a set of a large range of values. The statistics module has a very large number of functions to work with very large data-sets. The mode() function is one of such methods. This function returns the robust measure of a central data point in a given range of data-sets. Example : Given data-set is : [1, 2, 3, 4, 4, 4, 4, 5, 6, 7, 7, 7, 8] The mode of the given data-set is 4 Logic: 4 is the most occurring/ most common element from the given list Syntax : mode([data-set]) Parameters : [data-set] which is a tuple, list or a iterator of real valued numbers as well as Strings. Return type : Returns the most-common data point from discrete or nominal data. Errors and Exceptions : Raises StatisticsError when data set is empty. Code #1 : This piece will demonstrate mode() function through a simple example. Python3 # Python code to demonstrate the# use of mode() function # mode() function a sub-set of the statistics module# We need to import the statistics module before doing any workimport statistics # declaring a simple data-set consisting of real valued# positive integers.set1 =[1, 2, 3, 3, 4, 4, 4, 5, 5, 6] # In the given data-set# Count of 1 is 1# Count of 2 is 1# Count of 3 is 2# Count of 4 is 3# Count of 5 is 2# Count of 6 is 1# We can infer that 4 has the highest population distribution# So mode of set1 is 4 # Printing out mode of given data-setprint("Mode of given data set is % s" % (statistics.mode(set1))) Mode of given data set is 4 Code #2 : In this code we will be demonstrating the mode() function a various range of data-sets. Python3 # Python code to demonstrate the# working of mode() function# on a various range of data types # Importing the statistics modulefrom statistics import mode # Importing fractions module as fr# Enables to calculate harmonic_mean of a# set in Fractionfrom fractions import Fraction as fr # tuple of positive integer numbersdata1 = (2, 3, 3, 4, 5, 5, 5, 5, 6, 6, 6, 7) # tuple of a set of floating point valuesdata2 = (2.4, 1.3, 1.3, 1.3, 2.4, 4.6) # tuple of a set of fractional numbersdata3 = (fr(1, 2), fr(1, 2), fr(10, 3), fr(2, 3)) # tuple of a set of negative integersdata4 = (-1, -2, -2, -2, -7, -7, -9) # tuple of stringsdata5 = ("red", "blue", "black", "blue", "black", "black", "brown") # Printing out the mode of the above data-setsprint("Mode of data set 1 is % s" % (mode(data1)))print("Mode of data set 2 is % s" % (mode(data2)))print("Mode of data set 3 is % s" % (mode(data3)))print("Mode of data set 4 is % s" % (mode(data4)))print("Mode of data set 5 is % s" % (mode(data5))) Mode of data set 1 is 5 Mode of data set 2 is 1.3 Mode of data set 3 is 1/2 Mode of data set 4 is -2 Mode of data set 5 is black Code #3 : In this piece of code will demonstrate when StatisticsError is raised Python3 # Python code to demonstrate the # statistics error in mode function '''StatisticsError is raised while using mode when there aretwo equal modes present in a data set and when the data setis empty or null''' # importing statistics moduleimport statistics # creating a data set consisting of two equal data-setsdata1 =[1, 1, 1, -1, -1, -1] # In the above data set# Count of 1 is 3# Count of -1 is also 3# StatisticsError will be raised print(statistics.mode(data1)) Output Traceback (most recent call last): File "/home/38fbe95fe09d5f65aaa038e37aac20fa.py", line 20, in print(statistics.mode(data1)) File "/usr/lib/python3.5/statistics.py", line 474, in mode raise StatisticsError('no mode for empty data') from None statistics.StatisticsError: no mode for empty data NOTE: In newer versions of Python, like Python 3.8, the actual mathematical concept will be applied when there are multiple modes for a sequence, where, the smallest element is considered as a mode. Say, for the above code, the frequencies of -1 and 1 are the same, however, -1 will be the mode, because of its smaller value. Applications: The mode() is a statistics function and mostly used in Financial Sectors to compare values/prices with past details, calculate/predict probable future prices from a price distribution set. mean() is not used separately but along with two other pillars of statistics mean and median creates a very powerful tool that can be used to reveal any aspect of your data. retr0 shubham_singh edusanketdk kalrap615 Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Aug, 2021" }, { "code": null, "e": 675, "s": 28, "text": "The mode of a set of data values is the value that appears most often. It is the value at which the data is most likely to be sampled. A mode of a continuous probability distribution is often considered to be any value x at which its probability density function has a local maximum value, so any peak is a mode.Python is very robust when it comes to statistics and working with a set of a large range of values. The statistics module has a very large number of functions to work with very large data-sets. The mode() function is one of such methods. This function returns the robust measure of a central data point in a given range of data-sets." }, { "code": null, "e": 686, "s": 675, "text": "Example : " }, { "code": null, "e": 856, "s": 686, "text": "Given data-set is : [1, 2, 3, 4, 4, 4, 4, 5, 6, 7, 7, 7, 8]\nThe mode of the given data-set is 4\nLogic: 4 is the most occurring/ most common element from the given list " }, { "code": null, "e": 1141, "s": 856, "text": "Syntax :\nmode([data-set])\nParameters : \n[data-set] which is a tuple, list or a iterator of \nreal valued numbers as well as Strings.\nReturn type : \nReturns the most-common data point from discrete or nominal data.\nErrors and Exceptions : \nRaises StatisticsError when data set is empty." }, { "code": null, "e": 1222, "s": 1141, "text": "Code #1 : This piece will demonstrate mode() function through a simple example. " }, { "code": null, "e": 1230, "s": 1222, "text": "Python3" }, { "code": "# Python code to demonstrate the# use of mode() function # mode() function a sub-set of the statistics module# We need to import the statistics module before doing any workimport statistics # declaring a simple data-set consisting of real valued# positive integers.set1 =[1, 2, 3, 3, 4, 4, 4, 5, 5, 6] # In the given data-set# Count of 1 is 1# Count of 2 is 1# Count of 3 is 2# Count of 4 is 3# Count of 5 is 2# Count of 6 is 1# We can infer that 4 has the highest population distribution# So mode of set1 is 4 # Printing out mode of given data-setprint(\"Mode of given data set is % s\" % (statistics.mode(set1)))", "e": 1843, "s": 1230, "text": null }, { "code": null, "e": 1871, "s": 1843, "text": "Mode of given data set is 4" }, { "code": null, "e": 1970, "s": 1871, "text": "Code #2 : In this code we will be demonstrating the mode() function a various range of data-sets. " }, { "code": null, "e": 1978, "s": 1970, "text": "Python3" }, { "code": "# Python code to demonstrate the# working of mode() function# on a various range of data types # Importing the statistics modulefrom statistics import mode # Importing fractions module as fr# Enables to calculate harmonic_mean of a# set in Fractionfrom fractions import Fraction as fr # tuple of positive integer numbersdata1 = (2, 3, 3, 4, 5, 5, 5, 5, 6, 6, 6, 7) # tuple of a set of floating point valuesdata2 = (2.4, 1.3, 1.3, 1.3, 2.4, 4.6) # tuple of a set of fractional numbersdata3 = (fr(1, 2), fr(1, 2), fr(10, 3), fr(2, 3)) # tuple of a set of negative integersdata4 = (-1, -2, -2, -2, -7, -7, -9) # tuple of stringsdata5 = (\"red\", \"blue\", \"black\", \"blue\", \"black\", \"black\", \"brown\") # Printing out the mode of the above data-setsprint(\"Mode of data set 1 is % s\" % (mode(data1)))print(\"Mode of data set 2 is % s\" % (mode(data2)))print(\"Mode of data set 3 is % s\" % (mode(data3)))print(\"Mode of data set 4 is % s\" % (mode(data4)))print(\"Mode of data set 5 is % s\" % (mode(data5)))", "e": 2969, "s": 1978, "text": null }, { "code": null, "e": 3098, "s": 2969, "text": "Mode of data set 1 is 5\nMode of data set 2 is 1.3\nMode of data set 3 is 1/2\nMode of data set 4 is -2\nMode of data set 5 is black" }, { "code": null, "e": 3179, "s": 3098, "text": "Code #3 : In this piece of code will demonstrate when StatisticsError is raised " }, { "code": null, "e": 3187, "s": 3179, "text": "Python3" }, { "code": "# Python code to demonstrate the # statistics error in mode function '''StatisticsError is raised while using mode when there aretwo equal modes present in a data set and when the data setis empty or null''' # importing statistics moduleimport statistics # creating a data set consisting of two equal data-setsdata1 =[1, 1, 1, -1, -1, -1] # In the above data set# Count of 1 is 3# Count of -1 is also 3# StatisticsError will be raised print(statistics.mode(data1))", "e": 3662, "s": 3187, "text": null }, { "code": null, "e": 3670, "s": 3662, "text": "Output " }, { "code": null, "e": 3978, "s": 3670, "text": "Traceback (most recent call last):\n File \"/home/38fbe95fe09d5f65aaa038e37aac20fa.py\", line 20, in \n print(statistics.mode(data1))\n File \"/usr/lib/python3.5/statistics.py\", line 474, in mode\n raise StatisticsError('no mode for empty data') from None\nstatistics.StatisticsError: no mode for empty data" }, { "code": null, "e": 4177, "s": 3978, "text": "NOTE: In newer versions of Python, like Python 3.8, the actual mathematical concept will be applied when there are multiple modes for a sequence, where, the smallest element is considered as a mode." }, { "code": null, "e": 4304, "s": 4177, "text": "Say, for the above code, the frequencies of -1 and 1 are the same, however, -1 will be the mode, because of its smaller value." }, { "code": null, "e": 4683, "s": 4304, "text": "Applications: The mode() is a statistics function and mostly used in Financial Sectors to compare values/prices with past details, calculate/predict probable future prices from a price distribution set. mean() is not used separately but along with two other pillars of statistics mean and median creates a very powerful tool that can be used to reveal any aspect of your data. " }, { "code": null, "e": 4689, "s": 4683, "text": "retr0" }, { "code": null, "e": 4703, "s": 4689, "text": "shubham_singh" }, { "code": null, "e": 4715, "s": 4703, "text": "edusanketdk" }, { "code": null, "e": 4725, "s": 4715, "text": "kalrap615" }, { "code": null, "e": 4751, "s": 4725, "text": "Python-Built-in-functions" }, { "code": null, "e": 4758, "s": 4751, "text": "Python" } ]
Twin Prime Numbers
24 Mar, 2021 A Twin prime are those numbers which are prime and having a difference of two ( 2 ) between the two prime numbers. In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime pair. Usually the pair (2, 3) is not considered to be a pair of twin primes. Since 2 is the only even prime, this pair is the only pair of prime numbers that differ by one; thus twin primes are as closely spaced as possible for any other two primes.The first few twin prime pairs are : (3, 5), (5, 7), (11, 13), (17, 19), (29, 31), (41, 43), (59, 61), (71, 73), (101, 103), (107, 109), (137, 139), ...etc. FACT : There are 409 Twin primes below 10, 000.Every twin prime pair except (3, 5) is of the form (6n – 1, 6n + 1) for some natural number n; that is, the number between the two primes is a multiple of 6.Examples : Input : n1 = 11, n2 = 13 Output : Twin Prime Input : n1 = 23, n2 = 37 Output : Not Twin Prime Prerequisite : Primality Test | Set 1 (Introduction and School Method) C++ Java Python3 C# PHP Javascript // CPP program to check twin prime#include <iostream>using namespace std; // Please refer below post for details of this// function// https://goo.gl/Wv3fGvbool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true;} // Returns true if n1 and n2 are twin primesbool twinPrime(int n1, int n2){ return (isPrime(n1) && isPrime(n2) && abs(n1 - n2) == 2);} // Driver codeint main(){ int n1 = 11, n2 = 13; if (twinPrime(n1, n2)) cout << "Twin Prime" << endl; else cout << endl << "Not Twin Prime" << endl; return 0;} // JAVA Code for Twin Prime Numbersimport java.util.*; class GFG { // Please refer below post for // details of this function // https://goo.gl/Wv3fGv static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Returns true if n1 and n2 are twin primes static boolean twinPrime(int n1, int n2) { return (isPrime(n1) && isPrime(n2) && Math.abs(n1 - n2) == 2); } /* Driver program to test above function */ public static void main(String[] args) { int n1 = 11, n2 = 13; if (twinPrime(n1, n2)) System.out.println("Twin Prime"); else System.out.println("Not Twin Prime"); }} // This code is contributed by Arnav Kr. Mandal. # Python3 code to check twin primeimport math # Function to check whether a # number is prime or notdef isPrime( n ): # Corner cases if n <= 1: return False if n <= 3: return True # This is checked so that we # can skip middle five numbers # in below loop if n%2 == 0 or n%3 == 0: return False for i in range(5, int(math.sqrt(n)+1), 6): if n%i == 0 or n%(i + 2) == 0: return False return True # Returns true if n1 and n2 are# twin primesdef twinPrime(n1 , n2): return (isPrime(n1) and isPrime(n2) and abs(n1 - n2) == 2) # Driver coden1 = 137n2 = 139 if twinPrime(n1, n2): print("Twin Prime")else: print("Not Twin Prime") # This code is contributed by "Sharad_Bhardwaj". // C# Code for Twin Prime Numbersusing System; class GFG { // Please refer below post for // details of this function // https://goo.gl/Wv3fGv static bool isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Returns true if n1 and n2 are twin primes static bool twinPrime(int n1, int n2) { return (isPrime(n1) && isPrime(n2) && Math.Abs(n1 - n2) == 2); } // Driver program public static void Main() { int n1 = 11, n2 = 13; if (twinPrime(n1, n2)) Console.WriteLine("Twin Prime"); else Console.WriteLine("Not Twin Prime"); }} // This code is contributed by vt_m. <?php// PhP program to check twin prime // Please refer below post for details// of this function// https://goo.gl/Wv3fGv function isPrime($n){ // Corner cases if ($n <= 1) return false; if ($n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if ($n % 2 == 0 || $n % 3 == 0) return false; for ($i = 5; $i * $i <= $n; $i = $i + 6) if ($n % $i == 0 || $n % ($i + 2) == 0) return false; return true;} // Returns true if n1 and n2 are twin primesfunction twinPrime($n1, $n2){ return (isPrime($n1) && isPrime($n2) && abs($n1 - $n2) == 2);} // Driver code$n1 = 11; $n2 = 13;if (twinPrime($n1, $n2)) echo "Twin Prime", "\n";else echo "\n", "Not Twin Prime", "\n"; // This code is contributed by ajit?> <script>// javascript Code for Twin Prime Numbers // Please refer below post for // details of this function // https://goo.gl/Wv3fGv function isPrime( n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for ( let i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Returns true if n1 and n2 are twin primes function twinPrime( n1, n2) { return (isPrime(n1) && isPrime(n2) && Math.abs(n1 - n2) == 2); } /* Driver program to test above function */ let n1 = 11, n2 = 13; if (twinPrime(n1, n2)) document.write("Twin Prime"); else document.write("Not Twin Prime"); // This code is contributed by gauravrajput1</script> Output : Twin Prime jit_t GauravRajput1 Prime Number Mathematical Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Minimum number of jumps to reach end The Knight's tour problem | Backtracking-1 Algorithm to solve Rubik's Cube Find minimum number of coins that make a given value Program for Decimal to Binary Conversion Modulo 10^9+7 (1000000007) Modulo Operator (%) in C/C++ with Examples Program for factorial of a number
[ { "code": null, "e": 52, "s": 24, "text": "\n24 Mar, 2021" }, { "code": null, "e": 641, "s": 52, "text": "A Twin prime are those numbers which are prime and having a difference of two ( 2 ) between the two prime numbers. In other words, a twin prime is a prime that has a prime gap of two. Sometimes the term twin prime is used for a pair of twin primes; an alternative name for this is prime twin or prime pair. Usually the pair (2, 3) is not considered to be a pair of twin primes. Since 2 is the only even prime, this pair is the only pair of prime numbers that differ by one; thus twin primes are as closely spaced as possible for any other two primes.The first few twin prime pairs are : " }, { "code": null, "e": 763, "s": 641, "text": "(3, 5), (5, 7), (11, 13), (17, 19), (29, 31), \n(41, 43), (59, 61), (71, 73), (101, 103), \n(107, 109), (137, 139), ...etc." }, { "code": null, "e": 980, "s": 763, "text": "FACT : There are 409 Twin primes below 10, 000.Every twin prime pair except (3, 5) is of the form (6n – 1, 6n + 1) for some natural number n; that is, the number between the two primes is a multiple of 6.Examples : " }, { "code": null, "e": 1075, "s": 980, "text": "Input : n1 = 11, n2 = 13\nOutput : Twin Prime\n\nInput : n1 = 23, n2 = 37\nOutput : Not Twin Prime" }, { "code": null, "e": 1149, "s": 1077, "text": "Prerequisite : Primality Test | Set 1 (Introduction and School Method) " }, { "code": null, "e": 1153, "s": 1149, "text": "C++" }, { "code": null, "e": 1158, "s": 1153, "text": "Java" }, { "code": null, "e": 1166, "s": 1158, "text": "Python3" }, { "code": null, "e": 1169, "s": 1166, "text": "C#" }, { "code": null, "e": 1173, "s": 1169, "text": "PHP" }, { "code": null, "e": 1184, "s": 1173, "text": "Javascript" }, { "code": "// CPP program to check twin prime#include <iostream>using namespace std; // Please refer below post for details of this// function// https://goo.gl/Wv3fGvbool isPrime(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n%2 == 0 || n%3 == 0) return false; for (int i=5; i*i<=n; i=i+6) if (n%i == 0 || n%(i+2) == 0) return false; return true;} // Returns true if n1 and n2 are twin primesbool twinPrime(int n1, int n2){ return (isPrime(n1) && isPrime(n2) && abs(n1 - n2) == 2);} // Driver codeint main(){ int n1 = 11, n2 = 13; if (twinPrime(n1, n2)) cout << \"Twin Prime\" << endl; else cout << endl << \"Not Twin Prime\" << endl; return 0;}", "e": 2036, "s": 1184, "text": null }, { "code": "// JAVA Code for Twin Prime Numbersimport java.util.*; class GFG { // Please refer below post for // details of this function // https://goo.gl/Wv3fGv static boolean isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Returns true if n1 and n2 are twin primes static boolean twinPrime(int n1, int n2) { return (isPrime(n1) && isPrime(n2) && Math.abs(n1 - n2) == 2); } /* Driver program to test above function */ public static void main(String[] args) { int n1 = 11, n2 = 13; if (twinPrime(n1, n2)) System.out.println(\"Twin Prime\"); else System.out.println(\"Not Twin Prime\"); }} // This code is contributed by Arnav Kr. Mandal.", "e": 3134, "s": 2036, "text": null }, { "code": "# Python3 code to check twin primeimport math # Function to check whether a # number is prime or notdef isPrime( n ): # Corner cases if n <= 1: return False if n <= 3: return True # This is checked so that we # can skip middle five numbers # in below loop if n%2 == 0 or n%3 == 0: return False for i in range(5, int(math.sqrt(n)+1), 6): if n%i == 0 or n%(i + 2) == 0: return False return True # Returns true if n1 and n2 are# twin primesdef twinPrime(n1 , n2): return (isPrime(n1) and isPrime(n2) and abs(n1 - n2) == 2) # Driver coden1 = 137n2 = 139 if twinPrime(n1, n2): print(\"Twin Prime\")else: print(\"Not Twin Prime\") # This code is contributed by \"Sharad_Bhardwaj\".", "e": 3922, "s": 3134, "text": null }, { "code": "// C# Code for Twin Prime Numbersusing System; class GFG { // Please refer below post for // details of this function // https://goo.gl/Wv3fGv static bool isPrime(int n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Returns true if n1 and n2 are twin primes static bool twinPrime(int n1, int n2) { return (isPrime(n1) && isPrime(n2) && Math.Abs(n1 - n2) == 2); } // Driver program public static void Main() { int n1 = 11, n2 = 13; if (twinPrime(n1, n2)) Console.WriteLine(\"Twin Prime\"); else Console.WriteLine(\"Not Twin Prime\"); }} // This code is contributed by vt_m.", "e": 4952, "s": 3922, "text": null }, { "code": "<?php// PhP program to check twin prime // Please refer below post for details// of this function// https://goo.gl/Wv3fGv function isPrime($n){ // Corner cases if ($n <= 1) return false; if ($n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if ($n % 2 == 0 || $n % 3 == 0) return false; for ($i = 5; $i * $i <= $n; $i = $i + 6) if ($n % $i == 0 || $n % ($i + 2) == 0) return false; return true;} // Returns true if n1 and n2 are twin primesfunction twinPrime($n1, $n2){ return (isPrime($n1) && isPrime($n2) && abs($n1 - $n2) == 2);} // Driver code$n1 = 11; $n2 = 13;if (twinPrime($n1, $n2)) echo \"Twin Prime\", \"\\n\";else echo \"\\n\", \"Not Twin Prime\", \"\\n\"; // This code is contributed by ajit?>", "e": 5782, "s": 4952, "text": null }, { "code": "<script>// javascript Code for Twin Prime Numbers // Please refer below post for // details of this function // https://goo.gl/Wv3fGv function isPrime( n) { // Corner cases if (n <= 1) return false; if (n <= 3) return true; // This is checked so that we can skip // middle five numbers in below loop if (n % 2 == 0 || n % 3 == 0) return false; for ( let i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return false; return true; } // Returns true if n1 and n2 are twin primes function twinPrime( n1, n2) { return (isPrime(n1) && isPrime(n2) && Math.abs(n1 - n2) == 2); } /* Driver program to test above function */ let n1 = 11, n2 = 13; if (twinPrime(n1, n2)) document.write(\"Twin Prime\"); else document.write(\"Not Twin Prime\"); // This code is contributed by gauravrajput1</script>", "e": 6776, "s": 5782, "text": null }, { "code": null, "e": 6787, "s": 6776, "text": "Output : " }, { "code": null, "e": 6798, "s": 6787, "text": "Twin Prime" }, { "code": null, "e": 6806, "s": 6800, "text": "jit_t" }, { "code": null, "e": 6820, "s": 6806, "text": "GauravRajput1" }, { "code": null, "e": 6833, "s": 6820, "text": "Prime Number" }, { "code": null, "e": 6846, "s": 6833, "text": "Mathematical" }, { "code": null, "e": 6859, "s": 6846, "text": "Mathematical" }, { "code": null, "e": 6872, "s": 6859, "text": "Prime Number" }, { "code": null, "e": 6970, "s": 6872, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6994, "s": 6970, "text": "Merge two sorted arrays" }, { "code": null, "e": 7015, "s": 6994, "text": "Operators in C / C++" }, { "code": null, "e": 7052, "s": 7015, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 7095, "s": 7052, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 7127, "s": 7095, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 7180, "s": 7127, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 7221, "s": 7180, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 7248, "s": 7221, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 7291, "s": 7248, "text": "Modulo Operator (%) in C/C++ with Examples" } ]
Create an Instagram/Twitter Heart Like Animation in Android
23 Feb, 2021 In this article, let’s learn how to create an Instagram/Twitter heart Like animation in android. Twitter’s Like animation is quite good and attractive. Suppose one wants to make an app like Twitter, Instagram, or Facebook where users can like posts there one can use this view. One can also use Leonids instead of this but it is very easy to use as compare to Leonids. This is an Animation Library and animations help to gain the attention of the user so it is best to learn it. Add the support Library in build.gradle file and add dependency in the dependencies section.implementation 'pub.hanks:smallbang:1.2.2' Create a new Android Resource Directory and for that right-click on res folder -> Android Resource Directory, make sure to select resource type as color.Now create a new file text_selector.xml in color directory and add the following code. This file is used to select the TextColor based on the state of TextView.text_selector.xmltext_selector.xml<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/colorPrimary" android:state_selected="true"/> <item android:color="#D6D6D6"/></selector>Now create a new file ic_heart.xml in drawable directory and add the following code or you can download the vector image from this Link and paste it in drawable folder.ic_heart.xmlic_heart.xml<vector android:height="32dp" android:viewportHeight="412.735" android:viewportWidth="412.735" android:width="32dp" xmlns:android="http://schemas.android.com/apk/res/android"> <path android:fillColor="#FF000000" android:pathData="M295.706,35.522C295.706,35.522 295.706, 35.522 295.706,35.522c-34.43,-0.184 -67.161,14.937 -89.339,41.273c-22.039,-26.516 -54.861,-41.68 -89.339, -41.273C52.395,35.522 0,87.917 0,152.55C0,263.31 193.306, 371.456 201.143,375.636c3.162,2.113 7.286,2.113 10.449, 0c7.837,-4.18 201.143,-110.759 201.143,-223.086C412.735, 87.917 360.339,35.522 295.706,35.522zM206.367, 354.738C176.065,336.975 20.898,242.412 20.898,152.55c0, -53.091 43.039,-96.131 96.131,-96.131c32.512,-0.427 62.938,15.972 80.457,43.363c3.557, 4.905 10.418,5.998 15.323,2.44c0.937,-0.68 1.761,-1.503 2.44, -2.44c29.055,-44.435 88.631,-56.903 133.066,-27.848c27.202, 17.787 43.575,48.114 43.521,80.615C391.837,243.456 236.669, 337.497 206.367,354.738z"/></vector>Now create a new file ic_heart_red.xml in drawable directory and add the following code or you can download the vector image from this Link and paste it in drawable folder.ic_heart_red.xmlic_heart_red.xml<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="391.837dp" android:height="391.837dp" android:viewportWidth="391.837" android:viewportHeight="391.837"> <path android:pathData="M285.257,35.528c58.743,0.286 106.294, 47.836 106.58,106.58c0,107.624 -195.918,214.204 -195.918,214.204S0,248.165 0,142.108c0, -58.862 47.717,-106.58 106.58,-106.58l0,0c36.032, -0.281 69.718,17.842 89.339,48.065C215.674,53.517 249.273,35.441 285.257,35.528z" android:fillColor="#D7443E"/></vector>Now create a new file heart_selector.xml in drawable and add the following code. This file is used to select the Image based on the state of ImageView.heart_selector.xmlheart_selector.xml<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/ic_heart_red" android:state_selected="true"/> <item android:drawable="@drawable/ic_heart"/></selector>Add the following code in activity_main.xml file. In this file we add a ImageView and a TextView as a childView to the SmallBangView layout. Add the heart_selector in src tag of imageView and text_Selector in textColor tag of TextView.activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <xyz.hanks.library.bang.SmallBangView android:layout_margin="20dp" android:id="@+id/imageViewAnimation" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:src="@drawable/heart_selector" /> </xyz.hanks.library.bang.SmallBangView> <xyz.hanks.library.bang.SmallBangView android:id="@+id/textViewAnimation" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:textColor="@color/text_selector" android:textAlignment="center" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="GeeksForGeeks" android:textSize="25sp" android:textStyle="bold" /> </xyz.hanks.library.bang.SmallBangView></LinearLayout>Add the following code in MainActivity.java file. In this file we add OnClickListner to the ImageView and TextView which will invoked automatically whenever user taps on the view. If the state is true i.e. ImageView or textView is already selected we call setSelected to false otherwise call LikeAnimation on the view.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.twitterLikeAnimaton; import android.os.Bundle;import android.view.View;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import xyz.hanks.library.bang.SmallBangView; public class MainActivity extends AppCompatActivity { SmallBangView imageView,textView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textViewAnimation); imageView = findViewById(R.id.imageViewAnimation); textView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (textView.isSelected()) { textView.setSelected(false); } else { // if not selected only // then show animation. textView.setSelected(true); textView.likeAnimation(); } } }); imageView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (imageView.isSelected()) { imageView.setSelected(false); } else { // if not selected only // then show animation. imageView.setSelected(true); imageView.likeAnimation(); } } }); }}Run as EmulatorVideo Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200723022557/Record_2020-07-23-02-24-23_69fa71ed7e998de6cab47c8740bea3c11.mp400:0000:0000:11Use Up/Down Arrow keys to increase or decrease volume.My Personal Notes arrow_drop_upSave Add the support Library in build.gradle file and add dependency in the dependencies section.implementation 'pub.hanks:smallbang:1.2.2' implementation 'pub.hanks:smallbang:1.2.2' Create a new Android Resource Directory and for that right-click on res folder -> Android Resource Directory, make sure to select resource type as color. Now create a new file text_selector.xml in color directory and add the following code. This file is used to select the TextColor based on the state of TextView.text_selector.xmltext_selector.xml<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/colorPrimary" android:state_selected="true"/> <item android:color="#D6D6D6"/></selector> text_selector.xml <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:color="@color/colorPrimary" android:state_selected="true"/> <item android:color="#D6D6D6"/></selector> Now create a new file ic_heart.xml in drawable directory and add the following code or you can download the vector image from this Link and paste it in drawable folder.ic_heart.xmlic_heart.xml<vector android:height="32dp" android:viewportHeight="412.735" android:viewportWidth="412.735" android:width="32dp" xmlns:android="http://schemas.android.com/apk/res/android"> <path android:fillColor="#FF000000" android:pathData="M295.706,35.522C295.706,35.522 295.706, 35.522 295.706,35.522c-34.43,-0.184 -67.161,14.937 -89.339,41.273c-22.039,-26.516 -54.861,-41.68 -89.339, -41.273C52.395,35.522 0,87.917 0,152.55C0,263.31 193.306, 371.456 201.143,375.636c3.162,2.113 7.286,2.113 10.449, 0c7.837,-4.18 201.143,-110.759 201.143,-223.086C412.735, 87.917 360.339,35.522 295.706,35.522zM206.367, 354.738C176.065,336.975 20.898,242.412 20.898,152.55c0, -53.091 43.039,-96.131 96.131,-96.131c32.512,-0.427 62.938,15.972 80.457,43.363c3.557, 4.905 10.418,5.998 15.323,2.44c0.937,-0.68 1.761,-1.503 2.44, -2.44c29.055,-44.435 88.631,-56.903 133.066,-27.848c27.202, 17.787 43.575,48.114 43.521,80.615C391.837,243.456 236.669, 337.497 206.367,354.738z"/></vector> ic_heart.xml <vector android:height="32dp" android:viewportHeight="412.735" android:viewportWidth="412.735" android:width="32dp" xmlns:android="http://schemas.android.com/apk/res/android"> <path android:fillColor="#FF000000" android:pathData="M295.706,35.522C295.706,35.522 295.706, 35.522 295.706,35.522c-34.43,-0.184 -67.161,14.937 -89.339,41.273c-22.039,-26.516 -54.861,-41.68 -89.339, -41.273C52.395,35.522 0,87.917 0,152.55C0,263.31 193.306, 371.456 201.143,375.636c3.162,2.113 7.286,2.113 10.449, 0c7.837,-4.18 201.143,-110.759 201.143,-223.086C412.735, 87.917 360.339,35.522 295.706,35.522zM206.367, 354.738C176.065,336.975 20.898,242.412 20.898,152.55c0, -53.091 43.039,-96.131 96.131,-96.131c32.512,-0.427 62.938,15.972 80.457,43.363c3.557, 4.905 10.418,5.998 15.323,2.44c0.937,-0.68 1.761,-1.503 2.44, -2.44c29.055,-44.435 88.631,-56.903 133.066,-27.848c27.202, 17.787 43.575,48.114 43.521,80.615C391.837,243.456 236.669, 337.497 206.367,354.738z"/></vector> Now create a new file ic_heart_red.xml in drawable directory and add the following code or you can download the vector image from this Link and paste it in drawable folder.ic_heart_red.xmlic_heart_red.xml<vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="391.837dp" android:height="391.837dp" android:viewportWidth="391.837" android:viewportHeight="391.837"> <path android:pathData="M285.257,35.528c58.743,0.286 106.294, 47.836 106.58,106.58c0,107.624 -195.918,214.204 -195.918,214.204S0,248.165 0,142.108c0, -58.862 47.717,-106.58 106.58,-106.58l0,0c36.032, -0.281 69.718,17.842 89.339,48.065C215.674,53.517 249.273,35.441 285.257,35.528z" android:fillColor="#D7443E"/></vector> ic_heart_red.xml <vector xmlns:android="http://schemas.android.com/apk/res/android" android:width="391.837dp" android:height="391.837dp" android:viewportWidth="391.837" android:viewportHeight="391.837"> <path android:pathData="M285.257,35.528c58.743,0.286 106.294, 47.836 106.58,106.58c0,107.624 -195.918,214.204 -195.918,214.204S0,248.165 0,142.108c0, -58.862 47.717,-106.58 106.58,-106.58l0,0c36.032, -0.281 69.718,17.842 89.339,48.065C215.674,53.517 249.273,35.441 285.257,35.528z" android:fillColor="#D7443E"/></vector> Now create a new file heart_selector.xml in drawable and add the following code. This file is used to select the Image based on the state of ImageView.heart_selector.xmlheart_selector.xml<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/ic_heart_red" android:state_selected="true"/> <item android:drawable="@drawable/ic_heart"/></selector> heart_selector.xml <?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/ic_heart_red" android:state_selected="true"/> <item android:drawable="@drawable/ic_heart"/></selector> Add the following code in activity_main.xml file. In this file we add a ImageView and a TextView as a childView to the SmallBangView layout. Add the heart_selector in src tag of imageView and text_Selector in textColor tag of TextView.activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <xyz.hanks.library.bang.SmallBangView android:layout_margin="20dp" android:id="@+id/imageViewAnimation" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:src="@drawable/heart_selector" /> </xyz.hanks.library.bang.SmallBangView> <xyz.hanks.library.bang.SmallBangView android:id="@+id/textViewAnimation" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:textColor="@color/text_selector" android:textAlignment="center" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="GeeksForGeeks" android:textSize="25sp" android:textStyle="bold" /> </xyz.hanks.library.bang.SmallBangView></LinearLayout> activity_main.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:gravity="center"> <xyz.hanks.library.bang.SmallBangView android:layout_margin="20dp" android:id="@+id/imageViewAnimation" android:layout_width="wrap_content" android:layout_height="wrap_content" > <ImageView android:id="@+id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center" android:src="@drawable/heart_selector" /> </xyz.hanks.library.bang.SmallBangView> <xyz.hanks.library.bang.SmallBangView android:id="@+id/textViewAnimation" android:layout_width="match_parent" android:layout_height="wrap_content"> <TextView android:textColor="@color/text_selector" android:textAlignment="center" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="GeeksForGeeks" android:textSize="25sp" android:textStyle="bold" /> </xyz.hanks.library.bang.SmallBangView></LinearLayout> Add the following code in MainActivity.java file. In this file we add OnClickListner to the ImageView and TextView which will invoked automatically whenever user taps on the view. If the state is true i.e. ImageView or textView is already selected we call setSelected to false otherwise call LikeAnimation on the view.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.twitterLikeAnimaton; import android.os.Bundle;import android.view.View;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import xyz.hanks.library.bang.SmallBangView; public class MainActivity extends AppCompatActivity { SmallBangView imageView,textView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textViewAnimation); imageView = findViewById(R.id.imageViewAnimation); textView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (textView.isSelected()) { textView.setSelected(false); } else { // if not selected only // then show animation. textView.setSelected(true); textView.likeAnimation(); } } }); imageView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (imageView.isSelected()) { imageView.setSelected(false); } else { // if not selected only // then show animation. imageView.setSelected(true); imageView.likeAnimation(); } } }); }} MainActivity.java package org.geeksforgeeks.twitterLikeAnimaton; import android.os.Bundle;import android.view.View;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import xyz.hanks.library.bang.SmallBangView; public class MainActivity extends AppCompatActivity { SmallBangView imageView,textView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textViewAnimation); imageView = findViewById(R.id.imageViewAnimation); textView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (textView.isSelected()) { textView.setSelected(false); } else { // if not selected only // then show animation. textView.setSelected(true); textView.likeAnimation(); } } }); imageView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (imageView.isSelected()) { imageView.setSelected(false); } else { // if not selected only // then show animation. imageView.setSelected(true); imageView.likeAnimation(); } } }); }} Run as EmulatorVideo Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200723022557/Record_2020-07-23-02-24-23_69fa71ed7e998de6cab47c8740bea3c11.mp400:0000:0000:11Use Up/Down Arrow keys to increase or decrease volume.My Personal Notes arrow_drop_upSave Android-Animation Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Broadcast Receiver in Android With Example Content Providers in Android with Example Navigation Drawer in Android Android RecyclerView in Kotlin How to Post Data to API using Retrofit in Android? Arrays in Java Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java Split() String method in Java with examples Interfaces in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Feb, 2021" }, { "code": null, "e": 533, "s": 54, "text": "In this article, let’s learn how to create an Instagram/Twitter heart Like animation in android. Twitter’s Like animation is quite good and attractive. Suppose one wants to make an app like Twitter, Instagram, or Facebook where users can like posts there one can use this view. One can also use Leonids instead of this but it is very easy to use as compare to Leonids. This is an Animation Library and animations help to gain the attention of the user so it is best to learn it." }, { "code": null, "e": 7596, "s": 533, "text": "Add the support Library in build.gradle file and add dependency in the dependencies section.implementation 'pub.hanks:smallbang:1.2.2' Create a new Android Resource Directory and for that right-click on res folder -> Android Resource Directory, make sure to select resource type as color.Now create a new file text_selector.xml in color directory and add the following code. This file is used to select the TextColor based on the state of TextView.text_selector.xmltext_selector.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item android:color=\"@color/colorPrimary\" android:state_selected=\"true\"/> <item android:color=\"#D6D6D6\"/></selector>Now create a new file ic_heart.xml in drawable directory and add the following code or you can download the vector image from this Link and paste it in drawable folder.ic_heart.xmlic_heart.xml<vector android:height=\"32dp\" android:viewportHeight=\"412.735\" android:viewportWidth=\"412.735\" android:width=\"32dp\" xmlns:android=\"http://schemas.android.com/apk/res/android\"> <path android:fillColor=\"#FF000000\" android:pathData=\"M295.706,35.522C295.706,35.522 295.706, 35.522 295.706,35.522c-34.43,-0.184 -67.161,14.937 -89.339,41.273c-22.039,-26.516 -54.861,-41.68 -89.339, -41.273C52.395,35.522 0,87.917 0,152.55C0,263.31 193.306, 371.456 201.143,375.636c3.162,2.113 7.286,2.113 10.449, 0c7.837,-4.18 201.143,-110.759 201.143,-223.086C412.735, 87.917 360.339,35.522 295.706,35.522zM206.367, 354.738C176.065,336.975 20.898,242.412 20.898,152.55c0, -53.091 43.039,-96.131 96.131,-96.131c32.512,-0.427 62.938,15.972 80.457,43.363c3.557, 4.905 10.418,5.998 15.323,2.44c0.937,-0.68 1.761,-1.503 2.44, -2.44c29.055,-44.435 88.631,-56.903 133.066,-27.848c27.202, 17.787 43.575,48.114 43.521,80.615C391.837,243.456 236.669, 337.497 206.367,354.738z\"/></vector>Now create a new file ic_heart_red.xml in drawable directory and add the following code or you can download the vector image from this Link and paste it in drawable folder.ic_heart_red.xmlic_heart_red.xml<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"391.837dp\" android:height=\"391.837dp\" android:viewportWidth=\"391.837\" android:viewportHeight=\"391.837\"> <path android:pathData=\"M285.257,35.528c58.743,0.286 106.294, 47.836 106.58,106.58c0,107.624 -195.918,214.204 -195.918,214.204S0,248.165 0,142.108c0, -58.862 47.717,-106.58 106.58,-106.58l0,0c36.032, -0.281 69.718,17.842 89.339,48.065C215.674,53.517 249.273,35.441 285.257,35.528z\" android:fillColor=\"#D7443E\"/></vector>Now create a new file heart_selector.xml in drawable and add the following code. This file is used to select the Image based on the state of ImageView.heart_selector.xmlheart_selector.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item android:drawable=\"@drawable/ic_heart_red\" android:state_selected=\"true\"/> <item android:drawable=\"@drawable/ic_heart\"/></selector>Add the following code in activity_main.xml file. In this file we add a ImageView and a TextView as a childView to the SmallBangView layout. Add the heart_selector in src tag of imageView and text_Selector in textColor tag of TextView.activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:gravity=\"center\"> <xyz.hanks.library.bang.SmallBangView android:layout_margin=\"20dp\" android:id=\"@+id/imageViewAnimation\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" > <ImageView android:id=\"@+id/imageView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:src=\"@drawable/heart_selector\" /> </xyz.hanks.library.bang.SmallBangView> <xyz.hanks.library.bang.SmallBangView android:id=\"@+id/textViewAnimation\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <TextView android:textColor=\"@color/text_selector\" android:textAlignment=\"center\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"GeeksForGeeks\" android:textSize=\"25sp\" android:textStyle=\"bold\" /> </xyz.hanks.library.bang.SmallBangView></LinearLayout>Add the following code in MainActivity.java file. In this file we add OnClickListner to the ImageView and TextView which will invoked automatically whenever user taps on the view. If the state is true i.e. ImageView or textView is already selected we call setSelected to false otherwise call LikeAnimation on the view.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.twitterLikeAnimaton; import android.os.Bundle;import android.view.View;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import xyz.hanks.library.bang.SmallBangView; public class MainActivity extends AppCompatActivity { SmallBangView imageView,textView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textViewAnimation); imageView = findViewById(R.id.imageViewAnimation); textView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (textView.isSelected()) { textView.setSelected(false); } else { // if not selected only // then show animation. textView.setSelected(true); textView.likeAnimation(); } } }); imageView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (imageView.isSelected()) { imageView.setSelected(false); } else { // if not selected only // then show animation. imageView.setSelected(true); imageView.likeAnimation(); } } }); }}Run as EmulatorVideo Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200723022557/Record_2020-07-23-02-24-23_69fa71ed7e998de6cab47c8740bea3c11.mp400:0000:0000:11Use Up/Down Arrow keys to increase or decrease volume.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 7736, "s": 7596, "text": "Add the support Library in build.gradle file and add dependency in the dependencies section.implementation 'pub.hanks:smallbang:1.2.2' " }, { "code": "implementation 'pub.hanks:smallbang:1.2.2' ", "e": 7784, "s": 7736, "text": null }, { "code": null, "e": 7938, "s": 7784, "text": "Create a new Android Resource Directory and for that right-click on res folder -> Android Resource Directory, make sure to select resource type as color." }, { "code": null, "e": 8372, "s": 7938, "text": "Now create a new file text_selector.xml in color directory and add the following code. This file is used to select the TextColor based on the state of TextView.text_selector.xmltext_selector.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item android:color=\"@color/colorPrimary\" android:state_selected=\"true\"/> <item android:color=\"#D6D6D6\"/></selector>" }, { "code": null, "e": 8390, "s": 8372, "text": "text_selector.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item android:color=\"@color/colorPrimary\" android:state_selected=\"true\"/> <item android:color=\"#D6D6D6\"/></selector>", "e": 8630, "s": 8390, "text": null }, { "code": null, "e": 9920, "s": 8630, "text": "Now create a new file ic_heart.xml in drawable directory and add the following code or you can download the vector image from this Link and paste it in drawable folder.ic_heart.xmlic_heart.xml<vector android:height=\"32dp\" android:viewportHeight=\"412.735\" android:viewportWidth=\"412.735\" android:width=\"32dp\" xmlns:android=\"http://schemas.android.com/apk/res/android\"> <path android:fillColor=\"#FF000000\" android:pathData=\"M295.706,35.522C295.706,35.522 295.706, 35.522 295.706,35.522c-34.43,-0.184 -67.161,14.937 -89.339,41.273c-22.039,-26.516 -54.861,-41.68 -89.339, -41.273C52.395,35.522 0,87.917 0,152.55C0,263.31 193.306, 371.456 201.143,375.636c3.162,2.113 7.286,2.113 10.449, 0c7.837,-4.18 201.143,-110.759 201.143,-223.086C412.735, 87.917 360.339,35.522 295.706,35.522zM206.367, 354.738C176.065,336.975 20.898,242.412 20.898,152.55c0, -53.091 43.039,-96.131 96.131,-96.131c32.512,-0.427 62.938,15.972 80.457,43.363c3.557, 4.905 10.418,5.998 15.323,2.44c0.937,-0.68 1.761,-1.503 2.44, -2.44c29.055,-44.435 88.631,-56.903 133.066,-27.848c27.202, 17.787 43.575,48.114 43.521,80.615C391.837,243.456 236.669, 337.497 206.367,354.738z\"/></vector>" }, { "code": null, "e": 9933, "s": 9920, "text": "ic_heart.xml" }, { "code": "<vector android:height=\"32dp\" android:viewportHeight=\"412.735\" android:viewportWidth=\"412.735\" android:width=\"32dp\" xmlns:android=\"http://schemas.android.com/apk/res/android\"> <path android:fillColor=\"#FF000000\" android:pathData=\"M295.706,35.522C295.706,35.522 295.706, 35.522 295.706,35.522c-34.43,-0.184 -67.161,14.937 -89.339,41.273c-22.039,-26.516 -54.861,-41.68 -89.339, -41.273C52.395,35.522 0,87.917 0,152.55C0,263.31 193.306, 371.456 201.143,375.636c3.162,2.113 7.286,2.113 10.449, 0c7.837,-4.18 201.143,-110.759 201.143,-223.086C412.735, 87.917 360.339,35.522 295.706,35.522zM206.367, 354.738C176.065,336.975 20.898,242.412 20.898,152.55c0, -53.091 43.039,-96.131 96.131,-96.131c32.512,-0.427 62.938,15.972 80.457,43.363c3.557, 4.905 10.418,5.998 15.323,2.44c0.937,-0.68 1.761,-1.503 2.44, -2.44c29.055,-44.435 88.631,-56.903 133.066,-27.848c27.202, 17.787 43.575,48.114 43.521,80.615C391.837,243.456 236.669, 337.497 206.367,354.738z\"/></vector>", "e": 11031, "s": 9933, "text": null }, { "code": null, "e": 11828, "s": 11031, "text": "Now create a new file ic_heart_red.xml in drawable directory and add the following code or you can download the vector image from this Link and paste it in drawable folder.ic_heart_red.xmlic_heart_red.xml<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"391.837dp\" android:height=\"391.837dp\" android:viewportWidth=\"391.837\" android:viewportHeight=\"391.837\"> <path android:pathData=\"M285.257,35.528c58.743,0.286 106.294, 47.836 106.58,106.58c0,107.624 -195.918,214.204 -195.918,214.204S0,248.165 0,142.108c0, -58.862 47.717,-106.58 106.58,-106.58l0,0c36.032, -0.281 69.718,17.842 89.339,48.065C215.674,53.517 249.273,35.441 285.257,35.528z\" android:fillColor=\"#D7443E\"/></vector>" }, { "code": null, "e": 11845, "s": 11828, "text": "ic_heart_red.xml" }, { "code": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\" android:width=\"391.837dp\" android:height=\"391.837dp\" android:viewportWidth=\"391.837\" android:viewportHeight=\"391.837\"> <path android:pathData=\"M285.257,35.528c58.743,0.286 106.294, 47.836 106.58,106.58c0,107.624 -195.918,214.204 -195.918,214.204S0,248.165 0,142.108c0, -58.862 47.717,-106.58 106.58,-106.58l0,0c36.032, -0.281 69.718,17.842 89.339,48.065C215.674,53.517 249.273,35.441 285.257,35.528z\" android:fillColor=\"#D7443E\"/></vector>", "e": 12438, "s": 11845, "text": null }, { "code": null, "e": 12885, "s": 12438, "text": "Now create a new file heart_selector.xml in drawable and add the following code. This file is used to select the Image based on the state of ImageView.heart_selector.xmlheart_selector.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item android:drawable=\"@drawable/ic_heart_red\" android:state_selected=\"true\"/> <item android:drawable=\"@drawable/ic_heart\"/></selector>" }, { "code": null, "e": 12904, "s": 12885, "text": "heart_selector.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><selector xmlns:android=\"http://schemas.android.com/apk/res/android\"> <item android:drawable=\"@drawable/ic_heart_red\" android:state_selected=\"true\"/> <item android:drawable=\"@drawable/ic_heart\"/></selector>", "e": 13164, "s": 12904, "text": null }, { "code": null, "e": 14767, "s": 13164, "text": "Add the following code in activity_main.xml file. In this file we add a ImageView and a TextView as a childView to the SmallBangView layout. Add the heart_selector in src tag of imageView and text_Selector in textColor tag of TextView.activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:gravity=\"center\"> <xyz.hanks.library.bang.SmallBangView android:layout_margin=\"20dp\" android:id=\"@+id/imageViewAnimation\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" > <ImageView android:id=\"@+id/imageView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:src=\"@drawable/heart_selector\" /> </xyz.hanks.library.bang.SmallBangView> <xyz.hanks.library.bang.SmallBangView android:id=\"@+id/textViewAnimation\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <TextView android:textColor=\"@color/text_selector\" android:textAlignment=\"center\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"GeeksForGeeks\" android:textSize=\"25sp\" android:textStyle=\"bold\" /> </xyz.hanks.library.bang.SmallBangView></LinearLayout>" }, { "code": null, "e": 14785, "s": 14767, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:orientation=\"vertical\" android:gravity=\"center\"> <xyz.hanks.library.bang.SmallBangView android:layout_margin=\"20dp\" android:id=\"@+id/imageViewAnimation\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" > <ImageView android:id=\"@+id/imageView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_gravity=\"center\" android:src=\"@drawable/heart_selector\" /> </xyz.hanks.library.bang.SmallBangView> <xyz.hanks.library.bang.SmallBangView android:id=\"@+id/textViewAnimation\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <TextView android:textColor=\"@color/text_selector\" android:textAlignment=\"center\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:text=\"GeeksForGeeks\" android:textSize=\"25sp\" android:textStyle=\"bold\" /> </xyz.hanks.library.bang.SmallBangView></LinearLayout>", "e": 16119, "s": 14785, "text": null }, { "code": null, "e": 18063, "s": 16119, "text": "Add the following code in MainActivity.java file. In this file we add OnClickListner to the ImageView and TextView which will invoked automatically whenever user taps on the view. If the state is true i.e. ImageView or textView is already selected we call setSelected to false otherwise call LikeAnimation on the view.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.twitterLikeAnimaton; import android.os.Bundle;import android.view.View;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import xyz.hanks.library.bang.SmallBangView; public class MainActivity extends AppCompatActivity { SmallBangView imageView,textView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textViewAnimation); imageView = findViewById(R.id.imageViewAnimation); textView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (textView.isSelected()) { textView.setSelected(false); } else { // if not selected only // then show animation. textView.setSelected(true); textView.likeAnimation(); } } }); imageView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (imageView.isSelected()) { imageView.setSelected(false); } else { // if not selected only // then show animation. imageView.setSelected(true); imageView.likeAnimation(); } } }); }}" }, { "code": null, "e": 18081, "s": 18063, "text": "MainActivity.java" }, { "code": "package org.geeksforgeeks.twitterLikeAnimaton; import android.os.Bundle;import android.view.View;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import xyz.hanks.library.bang.SmallBangView; public class MainActivity extends AppCompatActivity { SmallBangView imageView,textView; @Override protected void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.textViewAnimation); imageView = findViewById(R.id.imageViewAnimation); textView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (textView.isSelected()) { textView.setSelected(false); } else { // if not selected only // then show animation. textView.setSelected(true); textView.likeAnimation(); } } }); imageView.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { if (imageView.isSelected()) { imageView.setSelected(false); } else { // if not selected only // then show animation. imageView.setSelected(true); imageView.likeAnimation(); } } }); }}", "e": 19673, "s": 18081, "text": null }, { "code": null, "e": 19935, "s": 19673, "text": "Run as EmulatorVideo Playerhttps://media.geeksforgeeks.org/wp-content/uploads/20200723022557/Record_2020-07-23-02-24-23_69fa71ed7e998de6cab47c8740bea3c11.mp400:0000:0000:11Use Up/Down Arrow keys to increase or decrease volume.My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 19953, "s": 19935, "text": "Android-Animation" }, { "code": null, "e": 19961, "s": 19953, "text": "Android" }, { "code": null, "e": 19966, "s": 19961, "text": "Java" }, { "code": null, "e": 19971, "s": 19966, "text": "Java" }, { "code": null, "e": 19979, "s": 19971, "text": "Android" }, { "code": null, "e": 20077, "s": 19979, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 20120, "s": 20077, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 20162, "s": 20120, "text": "Content Providers in Android with Example" }, { "code": null, "e": 20191, "s": 20162, "text": "Navigation Drawer in Android" }, { "code": null, "e": 20222, "s": 20191, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 20273, "s": 20222, "text": "How to Post Data to API using Retrofit in Android?" }, { "code": null, "e": 20288, "s": 20273, "text": "Arrays in Java" }, { "code": null, "e": 20339, "s": 20288, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 20364, "s": 20339, "text": "Reverse a string in Java" }, { "code": null, "e": 20408, "s": 20364, "text": "Split() String method in Java with examples" } ]
Testing BERT based Question Answering on Coronavirus articles | by Priya Dwivedi | Towards Data Science
Most of the world is currently affected by the COVID-19 pandemic. For many of us this has meant quarantine at home, social distancing, disruptions in our work enviroment. I am very passionate about using data science and machine learning to solve problems. Please reach out to me through here if you are a Health Services company and looking for data science help in fighting this crisis. Media outlets around the world are constantly covering the pandemic — latest stats, guidelines from your government, tips for keeping yourself safe etc. It can quickly get overwhelming to sort through all the information out there. In this blog I want to share how you can use BERT based question answering to extract information from news articles about the virus. I provide code tips on how to set this up on your own, as well as share where this approach works and when it tends to fail. My code is also uploaded to Github. Please note that I am not a health professional and the opinions of this article should not be interpreted as professional advice. Question Answering is a field of Computer Science within the umbrella of Natural Language Processing, which involves building systems which are capable of answering questions from a given piece of text. It has been a very active area of research for the past 2–3 years. The initial systems of Question Answering were mainly rule-based and only restricted to specific domains , but now, with the availability of better computing resources and deep learning architectures we are getting to models that have generalized question answering capabilities. Most of the best performing Question Answering models are now based on Transformers Architecture. To learn more about transformers, I recommed this youtube video. Transformers are encoder-decoder based architectures which treat Question Answer problem as a Text generation problem ; it takes the context and question as the trigger and tries to generate the answer from the paragraph. BERT, ALBERT, XLNET and Roberta are all commonly used Question Answering models. The Stanford Question Answering Dataset(SQuAD) is a dataset for training and evaluation of the Question Answering task. SQuAD now has released two versions — v1 and v2. The main difference between the two datasets is that SQuAD v2 also considers samples where the questions have no answer in the given paragraph. When a model is trained on SQuAD v1, the model will return an answer even if one doesn’t exist. To some extent you can use the probability of the answer to filter out unlikely answers but this doesn’t always work. On the other hand, training on SQuAD v2 dataset is a challenging task requiring careful monitoring of precision and hyper parameter tuning. With the outbreak of this virus worldwide, there has been a plethora of news articles providing facts, events and other news about the virus. We test how question answering works on articles that the model has never seen before. To showcase this capability, we have chosen a few informative articles from CNN: The transformers repository from huggingface is an amazing github repo where they have compiled multiple transformer based training and inference pipelines. For this question answering task, we will download a pre-trained squad model from https://huggingface.co/models. The model we will use for this article is bert-large-uncased-whole-word-masking-finetuned-squad. As apparent from the model name, the model is trained on the large bert model with uncased vocabulary and masking the whole word. There are three main files we need for using the model: Bert-large-uncased-whole-word-masking-finetuned-squad-config.json: This file is the configuration file which has parameters that the code will use to do the inference.Bert-large-uncased-whole-word-masking-finetuned-squad-pytorch_model.bin: This file is the actual model file which has all the weights of the model.bert-large-uncased-whole-word-masking-finetuned-squad-tf_model.h5:This file has the vocabulary model used to train the file. Bert-large-uncased-whole-word-masking-finetuned-squad-config.json: This file is the configuration file which has parameters that the code will use to do the inference. Bert-large-uncased-whole-word-masking-finetuned-squad-pytorch_model.bin: This file is the actual model file which has all the weights of the model. bert-large-uncased-whole-word-masking-finetuned-squad-tf_model.h5:This file has the vocabulary model used to train the file. We can load the model we have downloaded using the following commands: tokenizer = AutoTokenizer.from_pretrained(‘bert-large-uncased-whole-word-masking-finetuned-squad’, do_lower_case=True)model = AutoModelForQuestionAnswering.from_pretrained(“bert-large-uncased-whole-word-masking-finetuned-squad”) Overall, we have structured our code in two files. Please find the following on my Github: question_answering_inference.pyquestion_answering_main.py question_answering_inference.py question_answering_main.py The question_answering_inference.py file is a wrapper file which has supporting functions to process the input and outputs. In this file, we load the text from the file path, clean the text (remove the stop words after converting all words to lowercase), convert the text into paragraphs and then pass it on to the answer_prediction function in the question_answering_main.py. The answer_prediction function returns the answers and their probabilities. Then, we filter the answers based on a probability threshold and then display the answers with their probability. The question_answering_main.py file is the main file which has all the functions required to use the pre-trained model and tokenizer to predict the answer given the paragraphs and questions. The main driver function in this file is the answer_prediction function which loads the model and tokenizer files, calls functions to convert paragraphs to text, segment the text, convert features to the relevant objects, convert the objects into batches and then predict the answer with the probabilities. In order to run the script, run the following command: python question_answering_inference.py — ques ‘How many confirmed cases are in Mexico?’ — source ‘sample2.txt’ The program takes the following parameters: ques : Question parameter which expects a question enclosed in single(or double) quotes. source: This parameter has the source path of the text file containing the text/article We test this model on several articles of coronavirus. : edition.cnn.com edition.cnn.com In the following examples, we have the text and the question passed to the model and the answer and its probability that was returned. The above answer is correct. The model is able to pick the right answer with high confidence. This is a trickier question as there are several stats shared in the article. One study from Iceland shows about 50% of carriers are asymptomatic whereas the CDC estimates 25%. Its amazing to see the model is able to pick and return the correct answer. The same article later talks about the effect of interventions and how many deaths it can avert. The relevant text is copied below. However when running the code we pass the full article not the subset below. Since the SQUAD model has limitation on how much text can be processed, we pass the full text in multiple loops. As you see below this can mean that the model returns several answers. Here the first answer with the highest probability is the correct one. Another example where this happens is shared below. Here the correct answer is that Mike Ryan is the director of WHO health emergencies program. The model is able to pick that up with a probability of 96%. However it does return Dr. Fauci as a low probability answer. Here as well, we can use the probability score to get to the correct answer. The above examples show how powerful SQuAD question answering can be to get answers from very long news texts. One other amazing learning here is how powerful models trained on SQuAD are. They are able to generalize very well on texts never seen before. All said there are still a few challenges in this approach working perfectly in all situations. Few challenges with using Squad v1 for Question Answering are: 1) Many times , the model will provide an answer with high enough probability even if the answer doesn’t exist in the text, which leads to false positives. 2) While in many cases answers can be ranked by probability correctly, this is not always bullet proof. We have observed cases where the incorrect answer has similar or higher probability than the correct answer. 3) The model seems sensitive to punctuation in the input text. While feeding the input to the model, the text has to be clean(no junk words, symbols,etc), otherwise it may lead to wrong results. The first two challenges can be resolved to some extent using a SQuAD v2 model instead of SQuAD v1. The SQuAD v2 dataset has samples in the training set where there are no answers for the question asked. This allows the model to better judge when no answer should be returned. We have experience using SQuAD v2 models. Please contact me through my website if you are interested in applying this to your use case. In this article, we saw how Question Answering can be easily implemented to build systems capable of finding information from long news articles. I encourage you to give this a shot for yourself, and learn something new while you are in quarantine. I am extremely passionate about NLP, Transformers and deep learning in general. I have my own deep learning consultancy and love to work on interesting problems. I have helped many startups deploy innovative AI based solutions. Check us out at — http://deeplearninganalytics.org/. Transformer Model Paper: https://arxiv.org/abs/1706.03762 BERT Model Explained: https://towardsdatascience.com/bert-explained-state-of-the-art-language-model-for-nlp-f8b21a9b6270
[ { "code": null, "e": 560, "s": 171, "text": "Most of the world is currently affected by the COVID-19 pandemic. For many of us this has meant quarantine at home, social distancing, disruptions in our work enviroment. I am very passionate about using data science and machine learning to solve problems. Please reach out to me through here if you are a Health Services company and looking for data science help in fighting this crisis." }, { "code": null, "e": 792, "s": 560, "text": "Media outlets around the world are constantly covering the pandemic — latest stats, guidelines from your government, tips for keeping yourself safe etc. It can quickly get overwhelming to sort through all the information out there." }, { "code": null, "e": 1218, "s": 792, "text": "In this blog I want to share how you can use BERT based question answering to extract information from news articles about the virus. I provide code tips on how to set this up on your own, as well as share where this approach works and when it tends to fail. My code is also uploaded to Github. Please note that I am not a health professional and the opinions of this article should not be interpreted as professional advice." }, { "code": null, "e": 1768, "s": 1218, "text": "Question Answering is a field of Computer Science within the umbrella of Natural Language Processing, which involves building systems which are capable of answering questions from a given piece of text. It has been a very active area of research for the past 2–3 years. The initial systems of Question Answering were mainly rule-based and only restricted to specific domains , but now, with the availability of better computing resources and deep learning architectures we are getting to models that have generalized question answering capabilities." }, { "code": null, "e": 2234, "s": 1768, "text": "Most of the best performing Question Answering models are now based on Transformers Architecture. To learn more about transformers, I recommed this youtube video. Transformers are encoder-decoder based architectures which treat Question Answer problem as a Text generation problem ; it takes the context and question as the trigger and tries to generate the answer from the paragraph. BERT, ALBERT, XLNET and Roberta are all commonly used Question Answering models." }, { "code": null, "e": 2901, "s": 2234, "text": "The Stanford Question Answering Dataset(SQuAD) is a dataset for training and evaluation of the Question Answering task. SQuAD now has released two versions — v1 and v2. The main difference between the two datasets is that SQuAD v2 also considers samples where the questions have no answer in the given paragraph. When a model is trained on SQuAD v1, the model will return an answer even if one doesn’t exist. To some extent you can use the probability of the answer to filter out unlikely answers but this doesn’t always work. On the other hand, training on SQuAD v2 dataset is a challenging task requiring careful monitoring of precision and hyper parameter tuning." }, { "code": null, "e": 3130, "s": 2901, "text": "With the outbreak of this virus worldwide, there has been a plethora of news articles providing facts, events and other news about the virus. We test how question answering works on articles that the model has never seen before." }, { "code": null, "e": 3211, "s": 3130, "text": "To showcase this capability, we have chosen a few informative articles from CNN:" }, { "code": null, "e": 3764, "s": 3211, "text": "The transformers repository from huggingface is an amazing github repo where they have compiled multiple transformer based training and inference pipelines. For this question answering task, we will download a pre-trained squad model from https://huggingface.co/models. The model we will use for this article is bert-large-uncased-whole-word-masking-finetuned-squad. As apparent from the model name, the model is trained on the large bert model with uncased vocabulary and masking the whole word. There are three main files we need for using the model:" }, { "code": null, "e": 4203, "s": 3764, "text": "Bert-large-uncased-whole-word-masking-finetuned-squad-config.json: This file is the configuration file which has parameters that the code will use to do the inference.Bert-large-uncased-whole-word-masking-finetuned-squad-pytorch_model.bin: This file is the actual model file which has all the weights of the model.bert-large-uncased-whole-word-masking-finetuned-squad-tf_model.h5:This file has the vocabulary model used to train the file." }, { "code": null, "e": 4371, "s": 4203, "text": "Bert-large-uncased-whole-word-masking-finetuned-squad-config.json: This file is the configuration file which has parameters that the code will use to do the inference." }, { "code": null, "e": 4519, "s": 4371, "text": "Bert-large-uncased-whole-word-masking-finetuned-squad-pytorch_model.bin: This file is the actual model file which has all the weights of the model." }, { "code": null, "e": 4644, "s": 4519, "text": "bert-large-uncased-whole-word-masking-finetuned-squad-tf_model.h5:This file has the vocabulary model used to train the file." }, { "code": null, "e": 4715, "s": 4644, "text": "We can load the model we have downloaded using the following commands:" }, { "code": null, "e": 4944, "s": 4715, "text": "tokenizer = AutoTokenizer.from_pretrained(‘bert-large-uncased-whole-word-masking-finetuned-squad’, do_lower_case=True)model = AutoModelForQuestionAnswering.from_pretrained(“bert-large-uncased-whole-word-masking-finetuned-squad”)" }, { "code": null, "e": 5035, "s": 4944, "text": "Overall, we have structured our code in two files. Please find the following on my Github:" }, { "code": null, "e": 5093, "s": 5035, "text": "question_answering_inference.pyquestion_answering_main.py" }, { "code": null, "e": 5125, "s": 5093, "text": "question_answering_inference.py" }, { "code": null, "e": 5152, "s": 5125, "text": "question_answering_main.py" }, { "code": null, "e": 5719, "s": 5152, "text": "The question_answering_inference.py file is a wrapper file which has supporting functions to process the input and outputs. In this file, we load the text from the file path, clean the text (remove the stop words after converting all words to lowercase), convert the text into paragraphs and then pass it on to the answer_prediction function in the question_answering_main.py. The answer_prediction function returns the answers and their probabilities. Then, we filter the answers based on a probability threshold and then display the answers with their probability." }, { "code": null, "e": 5910, "s": 5719, "text": "The question_answering_main.py file is the main file which has all the functions required to use the pre-trained model and tokenizer to predict the answer given the paragraphs and questions." }, { "code": null, "e": 6217, "s": 5910, "text": "The main driver function in this file is the answer_prediction function which loads the model and tokenizer files, calls functions to convert paragraphs to text, segment the text, convert features to the relevant objects, convert the objects into batches and then predict the answer with the probabilities." }, { "code": null, "e": 6272, "s": 6217, "text": "In order to run the script, run the following command:" }, { "code": null, "e": 6383, "s": 6272, "text": "python question_answering_inference.py — ques ‘How many confirmed cases are in Mexico?’ — source ‘sample2.txt’" }, { "code": null, "e": 6427, "s": 6383, "text": "The program takes the following parameters:" }, { "code": null, "e": 6516, "s": 6427, "text": "ques : Question parameter which expects a question enclosed in single(or double) quotes." }, { "code": null, "e": 6604, "s": 6516, "text": "source: This parameter has the source path of the text file containing the text/article" }, { "code": null, "e": 6661, "s": 6604, "text": "We test this model on several articles of coronavirus. :" }, { "code": null, "e": 6677, "s": 6661, "text": "edition.cnn.com" }, { "code": null, "e": 6693, "s": 6677, "text": "edition.cnn.com" }, { "code": null, "e": 6828, "s": 6693, "text": "In the following examples, we have the text and the question passed to the model and the answer and its probability that was returned." }, { "code": null, "e": 6922, "s": 6828, "text": "The above answer is correct. The model is able to pick the right answer with high confidence." }, { "code": null, "e": 7175, "s": 6922, "text": "This is a trickier question as there are several stats shared in the article. One study from Iceland shows about 50% of carriers are asymptomatic whereas the CDC estimates 25%. Its amazing to see the model is able to pick and return the correct answer." }, { "code": null, "e": 7639, "s": 7175, "text": "The same article later talks about the effect of interventions and how many deaths it can avert. The relevant text is copied below. However when running the code we pass the full article not the subset below. Since the SQUAD model has limitation on how much text can be processed, we pass the full text in multiple loops. As you see below this can mean that the model returns several answers. Here the first answer with the highest probability is the correct one." }, { "code": null, "e": 7984, "s": 7639, "text": "Another example where this happens is shared below. Here the correct answer is that Mike Ryan is the director of WHO health emergencies program. The model is able to pick that up with a probability of 96%. However it does return Dr. Fauci as a low probability answer. Here as well, we can use the probability score to get to the correct answer." }, { "code": null, "e": 8238, "s": 7984, "text": "The above examples show how powerful SQuAD question answering can be to get answers from very long news texts. One other amazing learning here is how powerful models trained on SQuAD are. They are able to generalize very well on texts never seen before." }, { "code": null, "e": 8334, "s": 8238, "text": "All said there are still a few challenges in this approach working perfectly in all situations." }, { "code": null, "e": 8397, "s": 8334, "text": "Few challenges with using Squad v1 for Question Answering are:" }, { "code": null, "e": 8553, "s": 8397, "text": "1) Many times , the model will provide an answer with high enough probability even if the answer doesn’t exist in the text, which leads to false positives." }, { "code": null, "e": 8766, "s": 8553, "text": "2) While in many cases answers can be ranked by probability correctly, this is not always bullet proof. We have observed cases where the incorrect answer has similar or higher probability than the correct answer." }, { "code": null, "e": 8961, "s": 8766, "text": "3) The model seems sensitive to punctuation in the input text. While feeding the input to the model, the text has to be clean(no junk words, symbols,etc), otherwise it may lead to wrong results." }, { "code": null, "e": 9374, "s": 8961, "text": "The first two challenges can be resolved to some extent using a SQuAD v2 model instead of SQuAD v1. The SQuAD v2 dataset has samples in the training set where there are no answers for the question asked. This allows the model to better judge when no answer should be returned. We have experience using SQuAD v2 models. Please contact me through my website if you are interested in applying this to your use case." }, { "code": null, "e": 9623, "s": 9374, "text": "In this article, we saw how Question Answering can be easily implemented to build systems capable of finding information from long news articles. I encourage you to give this a shot for yourself, and learn something new while you are in quarantine." }, { "code": null, "e": 9904, "s": 9623, "text": "I am extremely passionate about NLP, Transformers and deep learning in general. I have my own deep learning consultancy and love to work on interesting problems. I have helped many startups deploy innovative AI based solutions. Check us out at — http://deeplearninganalytics.org/." }, { "code": null, "e": 9962, "s": 9904, "text": "Transformer Model Paper: https://arxiv.org/abs/1706.03762" } ]
Python Modules of Cryptography
In this chapter, you will learn in detail about various modules of cryptography in Python. It includes all the recipes and primitives, and provides a high level interface of coding in Python. You can install cryptography module using the following command − pip install cryptography You can use the following code to implement the cryptography module − from cryptography.fernet import Fernet key = Fernet.generate_key() cipher_suite = Fernet(key) cipher_text = cipher_suite.encrypt("This example is used to demonstrate cryptography module") plain_text = cipher_suite.decrypt(cipher_text) The code given above produces the following output − The code given here is used to verify the password and creating its hash. It also includes logic for verifying the password for authentication purpose. import uuid import hashlib def hash_password(password): # uuid is used to generate a random number of the specified password salt = uuid.uuid4().hex return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt def check_password(hashed_password, user_password): password, salt = hashed_password.split(':') return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest() new_pass = input('Please enter a password: ') hashed_password = hash_password(new_pass) print('The string to store in the db is: ' + hashed_password) old_pass = input('Now please enter the password again to check: ') if check_password(hashed_password, old_pass): print('You entered the right password') else: print('Passwords do not match') Scenario 1 − If you have entered a correct password, you can find the following output − Scenario 2 − If we enter wrong password, you can find the following output − Hashlib package is used for storing passwords in a database. In this program, salt is used which adds a random sequence to the password string before implementing the hash function. 10 Lectures 2 hours Total Seminars 10 Lectures 2 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 2383, "s": 2292, "text": "In this chapter, you will learn in detail about various modules of cryptography in Python." }, { "code": null, "e": 2550, "s": 2383, "text": "It includes all the recipes and primitives, and provides a high level interface of coding in Python. You can install cryptography module using the following command −" }, { "code": null, "e": 2576, "s": 2550, "text": "pip install cryptography\n" }, { "code": null, "e": 2646, "s": 2576, "text": "You can use the following code to implement the cryptography module −" }, { "code": null, "e": 2881, "s": 2646, "text": "from cryptography.fernet import Fernet\nkey = Fernet.generate_key()\ncipher_suite = Fernet(key)\ncipher_text = cipher_suite.encrypt(\"This example is used to demonstrate cryptography module\")\nplain_text = cipher_suite.decrypt(cipher_text)" }, { "code": null, "e": 2934, "s": 2881, "text": "The code given above produces the following output −" }, { "code": null, "e": 3086, "s": 2934, "text": "The code given here is used to verify the password and creating its hash. It also includes logic for verifying the password for authentication purpose." }, { "code": null, "e": 3865, "s": 3086, "text": "import uuid\nimport hashlib\n\ndef hash_password(password):\n # uuid is used to generate a random number of the specified password\n salt = uuid.uuid4().hex\n return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ':' + salt\n\ndef check_password(hashed_password, user_password):\n password, salt = hashed_password.split(':')\n return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest()\n\nnew_pass = input('Please enter a password: ')\nhashed_password = hash_password(new_pass)\nprint('The string to store in the db is: ' + hashed_password)\nold_pass = input('Now please enter the password again to check: ')\n\nif check_password(hashed_password, old_pass):\n print('You entered the right password')\nelse:\n print('Passwords do not match')" }, { "code": null, "e": 3954, "s": 3865, "text": "Scenario 1 − If you have entered a correct password, you can find the following output −" }, { "code": null, "e": 4031, "s": 3954, "text": "Scenario 2 − If we enter wrong password, you can find the following output −" }, { "code": null, "e": 4213, "s": 4031, "text": "Hashlib package is used for storing passwords in a database. In this program, salt is used which adds a random sequence to the password string before implementing the hash function." }, { "code": null, "e": 4246, "s": 4213, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4262, "s": 4246, "text": " Total Seminars" }, { "code": null, "e": 4295, "s": 4262, "text": "\n 10 Lectures \n 2 hours \n" }, { "code": null, "e": 4318, "s": 4295, "text": " Stone River ELearning" }, { "code": null, "e": 4325, "s": 4318, "text": " Print" }, { "code": null, "e": 4336, "s": 4325, "text": " Add Notes" } ]
How to create a NumPy 1D-array with equally spaced numbers in an interval? - GeeksforGeeks
11 May, 2021 At times, we need to make arrays of different types like in AP(equally spaced series of numbers), GP(exponentially spaced series of numbers) or HP(reciprocally spaced series of numbers) to solve various problems, especially while solving some scientific or astronomical problem, in order to reduce the calculations. Python is one of the best languages when it comes to the pre-implemented codes, and is present there almost every time, at the cost of processing speed. NumPy has a built-in method called arange() which is capable of creating an array of a given integer type(in bytes), with equal spacing between the numbers. Syntax: arange([start,] stop[, step,][, dtype]) Parameters: start: This is a default parameter. The value of the first number of the element, the default value of this parameter is 0. stop: This is not a default parameter. This has to be greater than the maximum possible value of the last element. e.g. , If you want the last element to be 8, you should give the stop value as 9 or more, depending upon the difference you want between two consecutive numbers in the array. step: This is also a default parameter. This number will be the difference between the two consecutive elements in the array. The default value of step is 1. dtype: This is also a default parameter. This is the data type of the numbers in NumPy, for simplicity, it is a number(in power of 2) preceded by np.int, e.g., np.int8, np.int16, np.int32. The function will return an array as per the demand of the user. Let’s see some examples of it: Example 1: To create a simple array starting from 0 to a given number Python3 import numpy as np # Here, the array has only one parameter,# and that is the open ended limit of# last number of the arraymyArray = np.arange(8)print(myArray) Output: [0 1 2 3 4 5 6 7] Example 2: To create a simple array starting from a given number to another number Python3 import numpy as np # This line has two parameters# The first one is the closed and beginning limit# The second one is the open and end limitmySecondArray = np.arange(1, 6)print(mySecondArray) Output: [1 2 3 4 5] Example 3: To create an array from a given number to another number with a given interval. Python3 import numpy as np # This line has two parameters# The first one is the closed and beginning limit# The second one is the open and end limit# The third one is the steps(difference between# two elements in the array)myThirdArray = np.arange(2, 12, 2)print(myThirdArray) Output: [ 2 4 6 8 10] Example 4: We use dtype especially in the cases when we want to deal with images or some other sort of computation. Python3 import numpy as np # This line has two parameters# The first one is the closed and beginning limit# The second one is the open and end limit# The third one is the steps(difference between# two elements in the array)myForthArray = np.arange(5, 101, 10, np.int32)print(myForthArray) Output: [ 5 15 25 35 45 55 65 75 85 95] arorakashish0911 Pyhton numpy-arrayCreation Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python OOPs Concepts How to Install PIP on Windows ? Bar Plot in Matplotlib Defaultdict in Python Python Classes and Objects Deque in Python Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python - Ways to remove duplicates from list Class method vs Static method in Python
[ { "code": null, "e": 23901, "s": 23873, "text": "\n11 May, 2021" }, { "code": null, "e": 24370, "s": 23901, "text": "At times, we need to make arrays of different types like in AP(equally spaced series of numbers), GP(exponentially spaced series of numbers) or HP(reciprocally spaced series of numbers) to solve various problems, especially while solving some scientific or astronomical problem, in order to reduce the calculations. Python is one of the best languages when it comes to the pre-implemented codes, and is present there almost every time, at the cost of processing speed." }, { "code": null, "e": 24527, "s": 24370, "text": "NumPy has a built-in method called arange() which is capable of creating an array of a given integer type(in bytes), with equal spacing between the numbers." }, { "code": null, "e": 24575, "s": 24527, "text": "Syntax: arange([start,] stop[, step,][, dtype])" }, { "code": null, "e": 24587, "s": 24575, "text": "Parameters:" }, { "code": null, "e": 24711, "s": 24587, "text": "start: This is a default parameter. The value of the first number of the element, the default value of this parameter is 0." }, { "code": null, "e": 25001, "s": 24711, "text": "stop: This is not a default parameter. This has to be greater than the maximum possible value of the last element. e.g. , If you want the last element to be 8, you should give the stop value as 9 or more, depending upon the difference you want between two consecutive numbers in the array." }, { "code": null, "e": 25159, "s": 25001, "text": "step: This is also a default parameter. This number will be the difference between the two consecutive elements in the array. The default value of step is 1." }, { "code": null, "e": 25348, "s": 25159, "text": "dtype: This is also a default parameter. This is the data type of the numbers in NumPy, for simplicity, it is a number(in power of 2) preceded by np.int, e.g., np.int8, np.int16, np.int32." }, { "code": null, "e": 25444, "s": 25348, "text": "The function will return an array as per the demand of the user. Let’s see some examples of it:" }, { "code": null, "e": 25514, "s": 25444, "text": "Example 1: To create a simple array starting from 0 to a given number" }, { "code": null, "e": 25522, "s": 25514, "text": "Python3" }, { "code": "import numpy as np # Here, the array has only one parameter,# and that is the open ended limit of# last number of the arraymyArray = np.arange(8)print(myArray)", "e": 25682, "s": 25522, "text": null }, { "code": null, "e": 25690, "s": 25682, "text": "Output:" }, { "code": null, "e": 25708, "s": 25690, "text": "[0 1 2 3 4 5 6 7]" }, { "code": null, "e": 25791, "s": 25708, "text": "Example 2: To create a simple array starting from a given number to another number" }, { "code": null, "e": 25799, "s": 25791, "text": "Python3" }, { "code": "import numpy as np # This line has two parameters# The first one is the closed and beginning limit# The second one is the open and end limitmySecondArray = np.arange(1, 6)print(mySecondArray)", "e": 25992, "s": 25799, "text": null }, { "code": null, "e": 26000, "s": 25992, "text": "Output:" }, { "code": null, "e": 26012, "s": 26000, "text": "[1 2 3 4 5]" }, { "code": null, "e": 26103, "s": 26012, "text": "Example 3: To create an array from a given number to another number with a given interval." }, { "code": null, "e": 26111, "s": 26103, "text": "Python3" }, { "code": "import numpy as np # This line has two parameters# The first one is the closed and beginning limit# The second one is the open and end limit# The third one is the steps(difference between# two elements in the array)myThirdArray = np.arange(2, 12, 2)print(myThirdArray)", "e": 26381, "s": 26111, "text": null }, { "code": null, "e": 26389, "s": 26381, "text": "Output:" }, { "code": null, "e": 26406, "s": 26389, "text": "[ 2 4 6 8 10]" }, { "code": null, "e": 26522, "s": 26406, "text": "Example 4: We use dtype especially in the cases when we want to deal with images or some other sort of computation." }, { "code": null, "e": 26530, "s": 26522, "text": "Python3" }, { "code": "import numpy as np # This line has two parameters# The first one is the closed and beginning limit# The second one is the open and end limit# The third one is the steps(difference between# two elements in the array)myForthArray = np.arange(5, 101, 10, np.int32)print(myForthArray)", "e": 26812, "s": 26530, "text": null }, { "code": null, "e": 26820, "s": 26812, "text": "Output:" }, { "code": null, "e": 26852, "s": 26820, "text": "[ 5 15 25 35 45 55 65 75 85 95]" }, { "code": null, "e": 26869, "s": 26852, "text": "arorakashish0911" }, { "code": null, "e": 26896, "s": 26869, "text": "Pyhton numpy-arrayCreation" }, { "code": null, "e": 26909, "s": 26896, "text": "Python-numpy" }, { "code": null, "e": 26916, "s": 26909, "text": "Python" }, { "code": null, "e": 27014, "s": 26916, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27023, "s": 27014, "text": "Comments" }, { "code": null, "e": 27036, "s": 27023, "text": "Old Comments" }, { "code": null, "e": 27057, "s": 27036, "text": "Python OOPs Concepts" }, { "code": null, "e": 27089, "s": 27057, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27112, "s": 27089, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 27134, "s": 27112, "text": "Defaultdict in Python" }, { "code": null, "e": 27161, "s": 27134, "text": "Python Classes and Objects" }, { "code": null, "e": 27177, "s": 27161, "text": "Deque in Python" }, { "code": null, "e": 27219, "s": 27177, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27275, "s": 27219, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27320, "s": 27275, "text": "Python - Ways to remove duplicates from list" } ]
Forcing Tkinter window to stay on top of fullscreen in Windows 10?
To render widgets in a Tkinter application, we generally use mainloop() function which helps to display the widgets in a window. In many cases, tkinter window displays over the other windows or programs. While switching to other programs or windows, it seems difficult to find and switch back to the Tkinter window again. We can force our tkinter window to stay on Top of other window or programs by creating a function and defining win.lift() method in a loop. In the loop, it will execute win.after(2000, function()) function to ensure that the tkinter window will always stays on top of other windows. # Import the required libraries from tkinter import * import lorem # Create an instance of tkinter frame or window win=Tk() # Set the size of the window win.geometry("700x350") def stay_on_top(): win.lift() win.after(2000, stay_on_top) # Add a Label widget Label(win, text="This window will always stay on Top", font=('Aerial 14')).pack(pady=30, anchor =CENTER) # Call function to make the window stay on top stay_on_top() win.mainloop() Running the above code will display a window that will automatically remain on top of all other windows.
[ { "code": null, "e": 1384, "s": 1062, "text": "To render widgets in a Tkinter application, we generally use mainloop() function which helps to display the widgets in a window. In many cases, tkinter window displays over the other windows or programs. While switching to other programs or windows, it seems difficult to find and switch back to the Tkinter window again." }, { "code": null, "e": 1667, "s": 1384, "text": "We can force our tkinter window to stay on Top of other window or programs by creating a function and defining win.lift() method in a loop. In the loop, it will execute win.after(2000, function()) function to ensure that the tkinter window will always stays on top of other windows." }, { "code": null, "e": 2117, "s": 1667, "text": "# Import the required libraries\nfrom tkinter import *\nimport lorem\n\n# Create an instance of tkinter frame or window\nwin=Tk()\n\n# Set the size of the window\nwin.geometry(\"700x350\")\n\ndef stay_on_top():\n win.lift()\n win.after(2000, stay_on_top)\n\n# Add a Label widget\nLabel(win, text=\"This window will always stay on Top\", font=('Aerial 14')).pack(pady=30, anchor =CENTER)\n\n# Call function to make the window stay on top\nstay_on_top()\n\nwin.mainloop()" }, { "code": null, "e": 2222, "s": 2117, "text": "Running the above code will display a window that will automatically remain on top of all other windows." } ]
Lua - break Statement
When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. If you are using nested loops (i.e., one loop inside another loop), the break statement will stop execution of the innermost loop and start executing the next line of code after the block. The syntax for a break statement in Lua is as follows − break --[ local variable definition --] a = 10 --[ while loop execution --] while( a < 20 ) do print("value of a:", a) a=a+1 if( a > 15) then --[ terminate the loop using break statement --] break end end When you build and run the above code, 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 12 Lectures 2 hours Manish Gupta 80 Lectures 3 hours Sanjeev Mittal 54 Lectures 3.5 hours Mehmet GOKTEPE Print Add Notes Bookmark this page
[ { "code": null, "e": 2267, "s": 2103, "text": "When the break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop." }, { "code": null, "e": 2456, "s": 2267, "text": "If you are using nested loops (i.e., one loop inside another loop), the break statement will stop execution of the innermost loop and start executing the next line of code after the block." }, { "code": null, "e": 2512, "s": 2456, "text": "The syntax for a break statement in Lua is as follows −" }, { "code": null, "e": 2519, "s": 2512, "text": "break\n" }, { "code": null, "e": 2750, "s": 2519, "text": "--[ local variable definition --]\na = 10\n\n--[ while loop execution --]\nwhile( a < 20 )\ndo\n print(\"value of a:\", a)\n a=a+1\n\t\n if( a > 15)\n then\n --[ terminate the loop using break statement --]\n break\n end\n\t\nend" }, { "code": null, "e": 2823, "s": 2750, "text": "When you build and run the above code, it produces the following result." }, { "code": null, "e": 2914, "s": 2823, "text": "value of a:\t10\nvalue of a:\t11\nvalue of a:\t12\nvalue of a:\t13\nvalue of a:\t14\nvalue of a:\t15\n" }, { "code": null, "e": 2947, "s": 2914, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 2961, "s": 2947, "text": " Manish Gupta" }, { "code": null, "e": 2994, "s": 2961, "text": "\n 80 Lectures \n 3 hours \n" }, { "code": null, "e": 3010, "s": 2994, "text": " Sanjeev Mittal" }, { "code": null, "e": 3045, "s": 3010, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3061, "s": 3045, "text": " Mehmet GOKTEPE" }, { "code": null, "e": 3068, "s": 3061, "text": " Print" }, { "code": null, "e": 3079, "s": 3068, "text": " Add Notes" } ]
fastText and Tensorflow to perform NLP classification | by Antoine Hue | Towards Data Science
fastText is a state-of-the-art open-source library released in 2017 by Facebook to compute word embeddings or create text classifiers. However, embeddings and classifiers are only building blocks within a data-science job. There are many preparation tasks before and validation tasks after, and there are many candidate architectures based on these tools. Let’s work out a full use case based on the data of the community site for mountaineering sports, CampToCamp.org. As a deep learning engine, we will use Tensorflow 2 / Keras. As for the validation, we will use UMAP, a projection tool from high dimension manifolds onto the 2D plane. www.camptocamp.org is a community site for mountain sports. It is a lively source of information and has become a reference for French and Swiss alps. The site has four main sections: a knowledge base of waypoints and routes, a live feed of outings, accident reports, and a forum. Our task is based on the route data: given the textual description, design and train a classifier to tag the type of activity related to the route among ten possibilities: hiking, mountain biking, ski touring, snowshoeing, four types of climbing (rock, ice, mountain and mixed), via-ferrata and slack-lining. All flying related activities (paragliding, base-jump...) are not listed as routes, and downhill/resort skiing is not the purpose of the site. Each route can be tagged with more than one activity if it is a combination, or if it has a winter and a summer variant. There are up to three activity tags per route. As the tags are set, this is a supervised training. We will use the route descriptions from www.camptocamp.org restricted to the central-north French Alps (administrative regions of Hautes-Alpes, Isère, Savoie, Haute Savoie). As Camp To Camp is international, we want to focus on regions in which the French versions of the description is probably long and accurate. www.camptocamp.org has an open Web API [5], it is not documented but it is quite easy to understand looking through the XHR requests from Web pages. In total, 14'074 routes are extracted. Rich text features (HTML) are removed. 610 are dropped because they have no French description. Before computing the embeddings with either fastText or Tensorflow, the punctuation is stripped down. More data cleaning and eviction could be done, e.g. very short descriptions or descriptions in English (language mismatch), but it is a parti pris to go forward with this data quality. Embedding representation of texts, also called vectorization, is very common in natural language processing (NLP) initiated in 2013 by Mikolov et al. [3]. It has been popularized under the term Word2Vec. There are several famous implementations and pre-trained models, for example GloVe [4]. fastText is one of the most advanced algorithms and implementation of vectorizers taking advantage of many refinements like the Skip-grams, or the Continuous Bag-of-Words (CBOW) and subword Ngrams [1]. fastText precomputed embeddings are delivered under the name language model. Given the complexity of human languages, language model training required GB of data. For fastText, 157 language models are provided [2] which is quite distinctive to other previous libraries. Let’s start with the French language and observe the outcome on terms used in mountaineering activities. For example, corde (rope) is found to be close to: cordes (the plural form) Corde (1st letter capitalized) corde. (with punctuation) cordelette (small rope) cordage (rope set) ficelle (small rope synonym) sangle (flat rope, strap) corder (the verb) filin (synonym) poulie (pullet) This single observation gives us some clues about what is close (synonyms, other forms, closely related objects), and also some remaining issues of the vocabulary: punctuation, case. The case has no easy solution as some common words might refer to a specific location like Mont-Blanc (i.e. white-mount). fastText is also computing analogies from a triplet: distance is computed between the first two words and vocabulary words are extracted at the same distance from the third word in argument. It does not always lead to meaningful associations but still is quite accurate. For example, with the words skier (to ski), ski (the sport or the object), and vélo (bicycle), the analogy output is: pédaler (to pedal, to go cycling) promener, balader (to hang out) pédalant (pedaling) and less meaningful that synonyms with punctuation: vélo.A, vélo., Pédaler, bicyclette, vélo.-, velo Another view on the embeddings is a projection of the cloud of words from the high dimension space (300 dimensions for the French model) onto the 2D plane. The most common projection mechanism is the principal component analysis (PCA), but there are more advanced technics like t-SNE [6] and UMAP [7] that preserve the local distance between items. Beware that the projections by t-SNE or UMAP are not stable: multiple runs on the same data lead to different outputs Below is a projection of the embeddings of some vocabulary from the sailing, cycling, and mountaineering sport activities. Mountaineering and sailing are quite well separated, cycling is spread between them among shared vocabulary like carte (map) and corde (rope). Let’s now project more specific vocabulary of mountaineering activities ranging from rock climbing to ski: There is little structure in this image. Even things that seems obviously close like the cable car variants (télésiège, téléski, télécabine) are not always gathered. Let’s now perform a more complete machine learning task: classification of the route descriptions from CampToCamp.org as a function of the activity: hiking, climbing (on rock, ice, mix, in mountain, via-ferrata), skiing, mountain biking and snowshoeing. Each route can be labeled with multiple activities, the problem is multi-class and multi-label. In practice, most routes have 1 activity and there are at most 3 activities. Four classifier models are compared: 1. fastText French model to compute embedding and then a convolutional neural network (CNN) 2. fastText classifier (multinomial logistic) built on the corpus 3. fastText embeddings built on the corpus to feed a CNN 4. CNN computing the embeddings at the first stage Corpus sequences (route descriptions) are padded and truncated at 300 (more than 80% are shorter) or 600 words (more than 95% are shorter). The convolutions are on the 2-dimension plane of the sequence words and embeddings. The architecture is a classical funnel shape (the feature space is smaller and smaller the deeper in the network), initial computation layers are convolutional and final layers are dense. The main parameters are: Number of layers Width of the convolutions Pooling or stride parameters Regularization, mainly using Dropout The loss is categorical cross-entropy applied at the output of sigmoid activation. The performance is also assessed during training by a categorical accuracy. One of the challenges is overfitting as the total number of parameters remains quite high compared to the number of samples. Another challenge is the fact that 1 class (ski touring) is much larger than others (40% of total) while 4 / 10 classes are below 5%. As illustrated in the figure below, the models are quite well handling this issue but for the activities that are related to one or more major activities. For example, snowshoeing is in a sandwich between ski touring and summer hiking (most people actually prefer ski touring to snowshoeing). The test dataset is verified with a slightly different accuracy compared to the one of the training. It computes top-1, top-2 and top-3 accuracies with following rules: Top-1 is based on the predicted class with the highest probability and checking if this class is among the labels for this sequence Top-2 is based on the two highest predicted probabilities and is comparing to labels. In case the label number applied to a given sequence is 1, the top-2 match is easier than top-1 as two candidate classes are applied. In the case of 2 or more labels applied to the sequence, the difference to top-1 statistic is not as favorable as the previous case. Top-3 si similar to top-2 but with the three highest probabilities With this metric, the 1st model is a little under-performing, while all other models are performing similarly. The ranking among these 3 models depends on the initialization and training-test dataset split. It means that the simple and efficient classifier generated by fastText is performing as well as the more complex DNN. The histogram of the description length of the routes that are misclassified is similar to the one of all routes. Let’s inspect the estimates at the input of the last DNN layer of model 4. The dimension is 64, it is often more interesting compared to the output of this last layer that takes out probabilities (sigmoid activation) of the 10 candidate classes. The routes are generally quite well separated in clusters corresponding to the activities. Amazingly, there is a cluster that is quite far away and relates to ‘hiking’. Changing the color encoding to be the pass or fail at top-1 accuracy, we see that fail are spread all over but with a higher concentration at the thin junction of the clusters. Some of the failing quite obvious reading the route description: it is short, incomplete, and imprecise and the classifier is assigning activities with pure likelihood. This is verified by looking at the strange remote cluster of hiking routes. It is made of routes with description “Info”, this could be easily detected by a rule but the classifiers have cornered them. Some others are more disturbing like the following one in which the activity is clearly named in the description: And the classifier could still be improved if it would better understand the subtleties of the language like on this itinerary description: For this task of medium complexity, the fastText simple classifier is performing well and at a computation cost much lower than the association of the training of a full language model, the computation of the embedding, and the classification through a CNN. This classifier might anyway not be flexible enough if the task is more complicated, like computing several outputs (e.g.: the activity and the difficulty of the route). We have evaluated three ways to build and use embeddings, and feed a neural network: 1. Model 1: Using a pre-computed language model with fastText 2. Model 3: Using fastText to build the model from the corpus and compute the embeddings 3. Model 4: Directly fit the embeddings within the neural network The first solution is the best if the language of the corpus is not specific, or if ethics issues like bias are of importance. The second solution is taking advantage at the same time of the specific language of the corpus and the optimization of fastText (e.g.: subwords Ngrams that are more robust to out of vocabulary words and thus have better generalization) The third solution is taking advantage of the combined optimization of the embeddings and the classifier but is not performing better than the others. It is also showing that Tensorflow and similar tools are quickly becoming the universal tool to perform machine learning. Without much engineering complexity a tailored solution is created. However, it lacks interpretability as shown in the following image of the embeddings generated on the mountaineering vocabulary. CampToCamp.org data preparation Main notebook with the classifier evaluation [1] Bag of Tricks for Efficient Text Classification, J. Armand, G. Edouard, B. Piotr, M. Tomas, 2017, Proceedings of the 15th Conference of the {E}uropean Chapter of the Association for Computational Linguistics: Volume 2, Short Papers (https://www.aclweb.org/anthology/E17-2068/)[2] Learning Word Vectors for 157 Languages, G. Edouard, B. Piotr, G. Prakhar, J. Armand, M. Tomas, 2018, Proceedings of the International Conference on Language Resources and Evaluation (LREC 2018)} (https://arxiv.org/abs/1802.06893, https://fasttext.cc/docs/en/crawl-vectors.html)[3] Efficient Estimation of Word Representations in Vector Space, T. Mikolov, K. Chen, G. Corrado, J. Dean, 2013 (https://arxiv.org/abs/1301.3781)[4] GloVe, Global Vectors for Word Representation , J. Pennington, R. Socher, C.D. Manning, 2014 (http://www.aclweb.org/anthology/D14-1162)[5] REST API for www.camptocamp.org, Github (https://github.com/c2corg/v6_api)[6] Visualizing Data using t-SNE, L. Van der Maaten, G. Hinton, Journal of Machine Learning Research, 2008 (http://www.jmlr.org/papers/volume9/vandermaaten08a/vandermaaten08a.pdf)[7] UMAP: Uniform Manifold Approximation and Projection for Dimension Reduction, McInnes, Healy, Melville, 2018, (https://arxiv.org/abs/1802.03426)
[ { "code": null, "e": 811, "s": 172, "text": "fastText is a state-of-the-art open-source library released in 2017 by Facebook to compute word embeddings or create text classifiers. However, embeddings and classifiers are only building blocks within a data-science job. There are many preparation tasks before and validation tasks after, and there are many candidate architectures based on these tools. Let’s work out a full use case based on the data of the community site for mountaineering sports, CampToCamp.org. As a deep learning engine, we will use Tensorflow 2 / Keras. As for the validation, we will use UMAP, a projection tool from high dimension manifolds onto the 2D plane." }, { "code": null, "e": 1092, "s": 811, "text": "www.camptocamp.org is a community site for mountain sports. It is a lively source of information and has become a reference for French and Swiss alps. The site has four main sections: a knowledge base of waypoints and routes, a live feed of outings, accident reports, and a forum." }, { "code": null, "e": 1544, "s": 1092, "text": "Our task is based on the route data: given the textual description, design and train a classifier to tag the type of activity related to the route among ten possibilities: hiking, mountain biking, ski touring, snowshoeing, four types of climbing (rock, ice, mountain and mixed), via-ferrata and slack-lining. All flying related activities (paragliding, base-jump...) are not listed as routes, and downhill/resort skiing is not the purpose of the site." }, { "code": null, "e": 1764, "s": 1544, "text": "Each route can be tagged with more than one activity if it is a combination, or if it has a winter and a summer variant. There are up to three activity tags per route. As the tags are set, this is a supervised training." }, { "code": null, "e": 2080, "s": 1764, "text": "We will use the route descriptions from www.camptocamp.org restricted to the central-north French Alps (administrative regions of Hautes-Alpes, Isère, Savoie, Haute Savoie). As Camp To Camp is international, we want to focus on regions in which the French versions of the description is probably long and accurate." }, { "code": null, "e": 2229, "s": 2080, "text": "www.camptocamp.org has an open Web API [5], it is not documented but it is quite easy to understand looking through the XHR requests from Web pages." }, { "code": null, "e": 2466, "s": 2229, "text": "In total, 14'074 routes are extracted. Rich text features (HTML) are removed. 610 are dropped because they have no French description. Before computing the embeddings with either fastText or Tensorflow, the punctuation is stripped down." }, { "code": null, "e": 2651, "s": 2466, "text": "More data cleaning and eviction could be done, e.g. very short descriptions or descriptions in English (language mismatch), but it is a parti pris to go forward with this data quality." }, { "code": null, "e": 3145, "s": 2651, "text": "Embedding representation of texts, also called vectorization, is very common in natural language processing (NLP) initiated in 2013 by Mikolov et al. [3]. It has been popularized under the term Word2Vec. There are several famous implementations and pre-trained models, for example GloVe [4]. fastText is one of the most advanced algorithms and implementation of vectorizers taking advantage of many refinements like the Skip-grams, or the Continuous Bag-of-Words (CBOW) and subword Ngrams [1]." }, { "code": null, "e": 3415, "s": 3145, "text": "fastText precomputed embeddings are delivered under the name language model. Given the complexity of human languages, language model training required GB of data. For fastText, 157 language models are provided [2] which is quite distinctive to other previous libraries." }, { "code": null, "e": 3520, "s": 3415, "text": "Let’s start with the French language and observe the outcome on terms used in mountaineering activities." }, { "code": null, "e": 3571, "s": 3520, "text": "For example, corde (rope) is found to be close to:" }, { "code": null, "e": 3596, "s": 3571, "text": "cordes (the plural form)" }, { "code": null, "e": 3627, "s": 3596, "text": "Corde (1st letter capitalized)" }, { "code": null, "e": 3653, "s": 3627, "text": "corde. (with punctuation)" }, { "code": null, "e": 3677, "s": 3653, "text": "cordelette (small rope)" }, { "code": null, "e": 3696, "s": 3677, "text": "cordage (rope set)" }, { "code": null, "e": 3725, "s": 3696, "text": "ficelle (small rope synonym)" }, { "code": null, "e": 3751, "s": 3725, "text": "sangle (flat rope, strap)" }, { "code": null, "e": 3769, "s": 3751, "text": "corder (the verb)" }, { "code": null, "e": 3785, "s": 3769, "text": "filin (synonym)" }, { "code": null, "e": 3801, "s": 3785, "text": "poulie (pullet)" }, { "code": null, "e": 4106, "s": 3801, "text": "This single observation gives us some clues about what is close (synonyms, other forms, closely related objects), and also some remaining issues of the vocabulary: punctuation, case. The case has no easy solution as some common words might refer to a specific location like Mont-Blanc (i.e. white-mount)." }, { "code": null, "e": 4496, "s": 4106, "text": "fastText is also computing analogies from a triplet: distance is computed between the first two words and vocabulary words are extracted at the same distance from the third word in argument. It does not always lead to meaningful associations but still is quite accurate. For example, with the words skier (to ski), ski (the sport or the object), and vélo (bicycle), the analogy output is:" }, { "code": null, "e": 4531, "s": 4496, "text": "pédaler (to pedal, to go cycling)" }, { "code": null, "e": 4563, "s": 4531, "text": "promener, balader (to hang out)" }, { "code": null, "e": 4584, "s": 4563, "text": "pédalant (pedaling)" }, { "code": null, "e": 4689, "s": 4584, "text": "and less meaningful that synonyms with punctuation: vélo.A, vélo., Pédaler, bicyclette, vélo.-, velo" }, { "code": null, "e": 5156, "s": 4689, "text": "Another view on the embeddings is a projection of the cloud of words from the high dimension space (300 dimensions for the French model) onto the 2D plane. The most common projection mechanism is the principal component analysis (PCA), but there are more advanced technics like t-SNE [6] and UMAP [7] that preserve the local distance between items. Beware that the projections by t-SNE or UMAP are not stable: multiple runs on the same data lead to different outputs" }, { "code": null, "e": 5422, "s": 5156, "text": "Below is a projection of the embeddings of some vocabulary from the sailing, cycling, and mountaineering sport activities. Mountaineering and sailing are quite well separated, cycling is spread between them among shared vocabulary like carte (map) and corde (rope)." }, { "code": null, "e": 5529, "s": 5422, "text": "Let’s now project more specific vocabulary of mountaineering activities ranging from rock climbing to ski:" }, { "code": null, "e": 5702, "s": 5529, "text": "There is little structure in this image. Even things that seems obviously close like the cable car variants (télésiège, téléski, télécabine) are not always gathered." }, { "code": null, "e": 5956, "s": 5702, "text": "Let’s now perform a more complete machine learning task: classification of the route descriptions from CampToCamp.org as a function of the activity: hiking, climbing (on rock, ice, mix, in mountain, via-ferrata), skiing, mountain biking and snowshoeing." }, { "code": null, "e": 6129, "s": 5956, "text": "Each route can be labeled with multiple activities, the problem is multi-class and multi-label. In practice, most routes have 1 activity and there are at most 3 activities." }, { "code": null, "e": 6166, "s": 6129, "text": "Four classifier models are compared:" }, { "code": null, "e": 6258, "s": 6166, "text": "1. fastText French model to compute embedding and then a convolutional neural network (CNN)" }, { "code": null, "e": 6324, "s": 6258, "text": "2. fastText classifier (multinomial logistic) built on the corpus" }, { "code": null, "e": 6381, "s": 6324, "text": "3. fastText embeddings built on the corpus to feed a CNN" }, { "code": null, "e": 6432, "s": 6381, "text": "4. CNN computing the embeddings at the first stage" }, { "code": null, "e": 6572, "s": 6432, "text": "Corpus sequences (route descriptions) are padded and truncated at 300 (more than 80% are shorter) or 600 words (more than 95% are shorter)." }, { "code": null, "e": 6869, "s": 6572, "text": "The convolutions are on the 2-dimension plane of the sequence words and embeddings. The architecture is a classical funnel shape (the feature space is smaller and smaller the deeper in the network), initial computation layers are convolutional and final layers are dense. The main parameters are:" }, { "code": null, "e": 6886, "s": 6869, "text": "Number of layers" }, { "code": null, "e": 6912, "s": 6886, "text": "Width of the convolutions" }, { "code": null, "e": 6941, "s": 6912, "text": "Pooling or stride parameters" }, { "code": null, "e": 6978, "s": 6941, "text": "Regularization, mainly using Dropout" }, { "code": null, "e": 7137, "s": 6978, "text": "The loss is categorical cross-entropy applied at the output of sigmoid activation. The performance is also assessed during training by a categorical accuracy." }, { "code": null, "e": 7689, "s": 7137, "text": "One of the challenges is overfitting as the total number of parameters remains quite high compared to the number of samples. Another challenge is the fact that 1 class (ski touring) is much larger than others (40% of total) while 4 / 10 classes are below 5%. As illustrated in the figure below, the models are quite well handling this issue but for the activities that are related to one or more major activities. For example, snowshoeing is in a sandwich between ski touring and summer hiking (most people actually prefer ski touring to snowshoeing)." }, { "code": null, "e": 7858, "s": 7689, "text": "The test dataset is verified with a slightly different accuracy compared to the one of the training. It computes top-1, top-2 and top-3 accuracies with following rules:" }, { "code": null, "e": 7990, "s": 7858, "text": "Top-1 is based on the predicted class with the highest probability and checking if this class is among the labels for this sequence" }, { "code": null, "e": 8343, "s": 7990, "text": "Top-2 is based on the two highest predicted probabilities and is comparing to labels. In case the label number applied to a given sequence is 1, the top-2 match is easier than top-1 as two candidate classes are applied. In the case of 2 or more labels applied to the sequence, the difference to top-1 statistic is not as favorable as the previous case." }, { "code": null, "e": 8410, "s": 8343, "text": "Top-3 si similar to top-2 but with the three highest probabilities" }, { "code": null, "e": 8736, "s": 8410, "text": "With this metric, the 1st model is a little under-performing, while all other models are performing similarly. The ranking among these 3 models depends on the initialization and training-test dataset split. It means that the simple and efficient classifier generated by fastText is performing as well as the more complex DNN." }, { "code": null, "e": 8850, "s": 8736, "text": "The histogram of the description length of the routes that are misclassified is similar to the one of all routes." }, { "code": null, "e": 9096, "s": 8850, "text": "Let’s inspect the estimates at the input of the last DNN layer of model 4. The dimension is 64, it is often more interesting compared to the output of this last layer that takes out probabilities (sigmoid activation) of the 10 candidate classes." }, { "code": null, "e": 9265, "s": 9096, "text": "The routes are generally quite well separated in clusters corresponding to the activities. Amazingly, there is a cluster that is quite far away and relates to ‘hiking’." }, { "code": null, "e": 9442, "s": 9265, "text": "Changing the color encoding to be the pass or fail at top-1 accuracy, we see that fail are spread all over but with a higher concentration at the thin junction of the clusters." }, { "code": null, "e": 9611, "s": 9442, "text": "Some of the failing quite obvious reading the route description: it is short, incomplete, and imprecise and the classifier is assigning activities with pure likelihood." }, { "code": null, "e": 9813, "s": 9611, "text": "This is verified by looking at the strange remote cluster of hiking routes. It is made of routes with description “Info”, this could be easily detected by a rule but the classifiers have cornered them." }, { "code": null, "e": 9927, "s": 9813, "text": "Some others are more disturbing like the following one in which the activity is clearly named in the description:" }, { "code": null, "e": 10067, "s": 9927, "text": "And the classifier could still be improved if it would better understand the subtleties of the language like on this itinerary description:" }, { "code": null, "e": 10325, "s": 10067, "text": "For this task of medium complexity, the fastText simple classifier is performing well and at a computation cost much lower than the association of the training of a full language model, the computation of the embedding, and the classification through a CNN." }, { "code": null, "e": 10495, "s": 10325, "text": "This classifier might anyway not be flexible enough if the task is more complicated, like computing several outputs (e.g.: the activity and the difficulty of the route)." }, { "code": null, "e": 10580, "s": 10495, "text": "We have evaluated three ways to build and use embeddings, and feed a neural network:" }, { "code": null, "e": 10642, "s": 10580, "text": "1. Model 1: Using a pre-computed language model with fastText" }, { "code": null, "e": 10731, "s": 10642, "text": "2. Model 3: Using fastText to build the model from the corpus and compute the embeddings" }, { "code": null, "e": 10797, "s": 10731, "text": "3. Model 4: Directly fit the embeddings within the neural network" }, { "code": null, "e": 10924, "s": 10797, "text": "The first solution is the best if the language of the corpus is not specific, or if ethics issues like bias are of importance." }, { "code": null, "e": 11161, "s": 10924, "text": "The second solution is taking advantage at the same time of the specific language of the corpus and the optimization of fastText (e.g.: subwords Ngrams that are more robust to out of vocabulary words and thus have better generalization)" }, { "code": null, "e": 11631, "s": 11161, "text": "The third solution is taking advantage of the combined optimization of the embeddings and the classifier but is not performing better than the others. It is also showing that Tensorflow and similar tools are quickly becoming the universal tool to perform machine learning. Without much engineering complexity a tailored solution is created. However, it lacks interpretability as shown in the following image of the embeddings generated on the mountaineering vocabulary." }, { "code": null, "e": 11663, "s": 11631, "text": "CampToCamp.org data preparation" }, { "code": null, "e": 11708, "s": 11663, "text": "Main notebook with the classifier evaluation" } ]
Writing Scrapy Python Output to JSON file - GeeksforGeeks
14 Sep, 2021 In this article, we are going to see how to write scrapy output into a JSON file in Python. This is the easiest way to save data to JSON is by using the following command: scrapy crawl <spiderName> -O <fileName>.json This will generate a file with a provided file name containing all scraped data. Note that using -O in the command line overwrites any existing file with that name whereas using -o appends the new content to the existing file. However, appending to a JSON file makes the file contents invalid JSON. So use the following command to append data to an existing file. scrapy crawl <spiderName> -o <fileName>.jl Note: .jl represents JSON lines format. Step 1: Creating the project Now to start a new project in scrapy use the following command scrapy startproject tutorial This will create a directory with the following content: Move to the tutorial directory we created using the following command: cd tutorial Step 2: Creating a spider (tutorial/spiders/quotes_spider.py) Spiders are the programs that user defines and scrapy uses to scrape information from website(s). This is the code for our Spider. Create a file named quotes_spider.py under the tutorial/spiders directory in your project: Python3 import scrapy class QuotesSpider(scrapy.Spider): # name of variable should be 'name' only name = "quotes" # urls from which will be used to extract information # list should be named 'start_urls' only start_urls = [ 'http://quotes.toscrape.com/page/1/', 'http://quotes.toscrape.com/page/2/', ] def parse(self, response): # handle the response downloaded for each of the # requests made should be named 'parse' only for quote in response.css('div.quote'): yield { 'text': quote.css('span.text::text').get(), 'author': quote.css('small.author::text').get(), 'tags': quote.css('div.tags a.tag::text').getall(), } This is a simple spider to get the quotes, author names, and tags from the website. Step 5: Running the program To run the program and save scrawled data to JSON using: scrapy crawl quotes -O quotes.json We can see that a file quotes.json has been created in our project structure, this file contains all the scraped data. JSON Output: These are just a few of many quotes of quotes.json file scraped by our spider. Picked Python-Scrapy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python Classes and Objects Create a directory in Python Python | os.path.join() method Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 24415, "s": 24387, "text": "\n14 Sep, 2021" }, { "code": null, "e": 24507, "s": 24415, "text": "In this article, we are going to see how to write scrapy output into a JSON file in Python." }, { "code": null, "e": 24587, "s": 24507, "text": "This is the easiest way to save data to JSON is by using the following command:" }, { "code": null, "e": 24632, "s": 24587, "text": "scrapy crawl <spiderName> -O <fileName>.json" }, { "code": null, "e": 24713, "s": 24632, "text": "This will generate a file with a provided file name containing all scraped data." }, { "code": null, "e": 24996, "s": 24713, "text": "Note that using -O in the command line overwrites any existing file with that name whereas using -o appends the new content to the existing file. However, appending to a JSON file makes the file contents invalid JSON. So use the following command to append data to an existing file." }, { "code": null, "e": 25039, "s": 24996, "text": "scrapy crawl <spiderName> -o <fileName>.jl" }, { "code": null, "e": 25079, "s": 25039, "text": "Note: .jl represents JSON lines format." }, { "code": null, "e": 25108, "s": 25079, "text": "Step 1: Creating the project" }, { "code": null, "e": 25171, "s": 25108, "text": "Now to start a new project in scrapy use the following command" }, { "code": null, "e": 25200, "s": 25171, "text": "scrapy startproject tutorial" }, { "code": null, "e": 25257, "s": 25200, "text": "This will create a directory with the following content:" }, { "code": null, "e": 25328, "s": 25257, "text": "Move to the tutorial directory we created using the following command:" }, { "code": null, "e": 25340, "s": 25328, "text": "cd tutorial" }, { "code": null, "e": 25402, "s": 25340, "text": "Step 2: Creating a spider (tutorial/spiders/quotes_spider.py)" }, { "code": null, "e": 25624, "s": 25402, "text": "Spiders are the programs that user defines and scrapy uses to scrape information from website(s). This is the code for our Spider. Create a file named quotes_spider.py under the tutorial/spiders directory in your project:" }, { "code": null, "e": 25632, "s": 25624, "text": "Python3" }, { "code": "import scrapy class QuotesSpider(scrapy.Spider): # name of variable should be 'name' only name = \"quotes\" # urls from which will be used to extract information # list should be named 'start_urls' only start_urls = [ 'http://quotes.toscrape.com/page/1/', 'http://quotes.toscrape.com/page/2/', ] def parse(self, response): # handle the response downloaded for each of the # requests made should be named 'parse' only for quote in response.css('div.quote'): yield { 'text': quote.css('span.text::text').get(), 'author': quote.css('small.author::text').get(), 'tags': quote.css('div.tags a.tag::text').getall(), }", "e": 26385, "s": 25632, "text": null }, { "code": null, "e": 26469, "s": 26385, "text": "This is a simple spider to get the quotes, author names, and tags from the website." }, { "code": null, "e": 26497, "s": 26469, "text": "Step 5: Running the program" }, { "code": null, "e": 26554, "s": 26497, "text": "To run the program and save scrawled data to JSON using:" }, { "code": null, "e": 26589, "s": 26554, "text": "scrapy crawl quotes -O quotes.json" }, { "code": null, "e": 26708, "s": 26589, "text": "We can see that a file quotes.json has been created in our project structure, this file contains all the scraped data." }, { "code": null, "e": 26721, "s": 26708, "text": "JSON Output:" }, { "code": null, "e": 26800, "s": 26721, "text": "These are just a few of many quotes of quotes.json file scraped by our spider." }, { "code": null, "e": 26807, "s": 26800, "text": "Picked" }, { "code": null, "e": 26821, "s": 26807, "text": "Python-Scrapy" }, { "code": null, "e": 26828, "s": 26821, "text": "Python" }, { "code": null, "e": 26926, "s": 26828, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26958, "s": 26926, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27000, "s": 26958, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27042, "s": 27000, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27098, "s": 27042, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27120, "s": 27098, "text": "Defaultdict in Python" }, { "code": null, "e": 27147, "s": 27120, "text": "Python Classes and Objects" }, { "code": null, "e": 27176, "s": 27147, "text": "Create a directory in Python" }, { "code": null, "e": 27207, "s": 27176, "text": "Python | os.path.join() method" }, { "code": null, "e": 27243, "s": 27207, "text": "Python | Pandas dataframe.groupby()" } ]
Edge Coloring of a Graph - GeeksforGeeks
07 Dec, 2021 In graph theory, edge coloring of a graph is an assignment of “colors” to the edges of the graph so that no two adjacent edges have the same color with an optimal number of colors. Two edges are said to be adjacent if they are connected to the same vertex. There is no known polynomial time algorithm for edge-coloring every graph with an optimal number of colors. Nevertheless, a number of algorithms have been developed that relax one or more of these criteria, they only work on a subset of graphs, or they do not always use an optimal number of colors, or they do not always run in polynomial time.Examples: Input : u1 = 1, v1 = 4 u2 = 1, v2 = 2 u3 = 2, v3 = 3 u4 = 3, v4 = 4 Output : Edge 1 is of color 1 Edge 2 is of color 2 Edge 3 is of color 1 Edge 4 is of color 2 The above input shows the pair of vertices(ui, vi) who have an edge between them. The output shows the color assigned to the respective edges. Edge colorings are one of several different types of graph coloring problems. The above figure of a Graph shows an edge coloring of a graph by the colors green and black, in which no adjacent edge have the same color.Below is an algorithm to solve the edge coloring problem which may not use an optimal number of colors: Algorithm: Use BFS traversal to start traversing the graph.Pick any vertex and give different colors to all of the edges connected to it, and mark those edges as colored.Traverse one of it’s edges.Repeat step to with a new vertexd until all edges are colored. Use BFS traversal to start traversing the graph. Pick any vertex and give different colors to all of the edges connected to it, and mark those edges as colored. Traverse one of it’s edges. Repeat step to with a new vertexd until all edges are colored. Below is the implementation of above approach: C++ Python3 // C++ program to illustrate Edge Coloring#include <bits/stdc++.h>using namespace std; // function to determine the edge colorsvoid colorEdges(int ptr, vector<vector<pair<int, int> > >& gra, vector<int>& edgeColors, bool isVisited[]){ queue<int> q; int c = 0; unordered_set<int> colored; // return if isVisited[ptr] is true if (isVisited[ptr]) return; // Mark the current node visited isVisited[ptr] = 1; // Traverse all edges of current vertex for (int i = 0; i < gra[ptr].size(); i++) { // if already colored, insert it into the set if (edgeColors[gra[ptr][i].second] != -1) colored.insert(edgeColors[gra[ptr][i].second]); } for (int i = 0; i < gra[ptr].size(); i++) { // if not visited, inset into the queue if (!isVisited[gra[ptr][i].first]) q.push(gra[ptr][i].first); if (edgeColors[gra[ptr][i].second] == -1) { // if col vector -> negative while (colored.find(c) != colored.end()) // increment the color c++; // copy it in the vector edgeColors[gra[ptr][i].second] = c; // then add it to the set colored.insert(c); c++; } } // while queue's not empty while (!q.empty()) { int temp = q.front(); q.pop(); colorEdges(temp, gra, edgeColors, isVisited); } return;} // Driver Functionint main(){ set<int> empty; // declaring vector of vector of pairs, to define Graph vector<vector<pair<int, int> > > gra; vector<int> edgeColors; bool isVisited[100000] = { 0 }; // Enter the Number of Vertices // and the number of edges int ver = 4; int edge = 4; gra.resize(ver); edgeColors.resize(edge, -1); // Enter edge & vertices of edge // x--; y--; // Since graph is undirected, push both pairs // (x, y) and (y, x) // graph[x].push_back(make_pair(y, i)); // graph[y].push_back(make_pair(x, i)); gra[0].push_back(make_pair(1, 0)); gra[1].push_back(make_pair(0, 0)); gra[1].push_back(make_pair(2, 1)); gra[2].push_back(make_pair(1, 1)); gra[2].push_back(make_pair(3, 2)); gra[3].push_back(make_pair(2, 2)); gra[0].push_back(make_pair(3, 3)); gra[3].push_back(make_pair(0, 3)); colorEdges(0, gra, edgeColors, isVisited); // printing all the edge colors for (int i = 0; i < edge; i++) cout << "Edge " << i + 1 << " is of color " << edgeColors[i] + 1 << "\n"; return 0;} # Python3 program to illustrate Edge Coloring from queue import Queue# function to determine the edge colorsdef colorEdges(ptr, gra, edgeColors, isVisited): q=Queue() c = 0 colored=set() # return if isVisited[ptr] is true if (isVisited[ptr]): return # Mark the current node visited isVisited[ptr] = True # Traverse all edges of current vertex for i in range(len(gra[ptr])) : # if already colored, insert it into the set if (edgeColors[gra[ptr][i][1]] != -1): colored.add(edgeColors[gra[ptr][i][1]]) for i in range(len(gra[ptr])) : # if not visited, inset into the queue if not isVisited[gra[ptr][i][0]]: q.put(gra[ptr][i][0]) if (edgeColors[gra[ptr][i][1]] == -1) : # if col vector -> negative while c in colored: # increment the color c+=1 # copy it in the vector edgeColors[gra[ptr][i][1]] = c # then add it to the set colored.add(c) c+=1 # while queue's not empty while not q.empty() : temp = q.get() colorEdges(temp, gra, edgeColors, isVisited) return # Driver Functionif __name__=='__main__': empty=set() # declaring vector of vector of pairs, to define Graph gra=[] edgeColors=[] isVisited=[False]*100000 # Enter the Number of Vertices # and the number of edges ver = 4 edge = 4 gra=[[] for _ in range(ver)] edgeColors=[-1]*edge # Enter edge & vertices of edge # x-- y-- # Since graph is undirected, push both pairs # (x, y) and (y, x) # graph[x].append((y, i)) # graph[y].append((x, i)) gra[0].append((1, 0)) gra[1].append((0, 0)) gra[1].append((2, 1)) gra[2].append((1, 1)) gra[2].append((3, 2)) gra[3].append((2, 2)) gra[0].append((3, 3)) gra[3].append((0, 3)) colorEdges(0, gra, edgeColors, isVisited) # printing all the edge colors for i in range(edge): print("Edge {} is of color {}".format(i + 1,edgeColors[i] + 1)) Edge 1 is of color 1 Edge 2 is of color 2 Edge 3 is of color 1 Edge 4 is of color 2 Time Complexity: O(N) Where N is the number of nodes in the graph.Auxiliary Space: O(N) Reference : https://en.wikipedia.org/wiki/Edge_coloring arorakashish0911 pankajsharmagfg amartyaghoshgfg Algorithms-Graph Traversals BFS Graph Coloring Algorithms Graph Graph BFS Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar How to Start Learning DSA? K means Clustering - Introduction Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Quadratic Probing in Hashing Breadth First Search or BFS for a Graph Depth First Search or DFS for a Graph Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
[ { "code": null, "e": 25941, "s": 25913, "text": "\n07 Dec, 2021" }, { "code": null, "e": 26555, "s": 25941, "text": "In graph theory, edge coloring of a graph is an assignment of “colors” to the edges of the graph so that no two adjacent edges have the same color with an optimal number of colors. Two edges are said to be adjacent if they are connected to the same vertex. There is no known polynomial time algorithm for edge-coloring every graph with an optimal number of colors. Nevertheless, a number of algorithms have been developed that relax one or more of these criteria, they only work on a subset of graphs, or they do not always use an optimal number of colors, or they do not always run in polynomial time.Examples: " }, { "code": null, "e": 26913, "s": 26555, "text": "Input : u1 = 1, v1 = 4 \n u2 = 1, v2 = 2\n u3 = 2, v3 = 3\n u4 = 3, v4 = 4\nOutput : Edge 1 is of color 1\n Edge 2 is of color 2\n Edge 3 is of color 1\n Edge 4 is of color 2\n\nThe above input shows the pair of vertices(ui, vi)\nwho have an edge between them. The output shows the color \nassigned to the respective edges." }, { "code": null, "e": 27251, "s": 26917, "text": "Edge colorings are one of several different types of graph coloring problems. The above figure of a Graph shows an edge coloring of a graph by the colors green and black, in which no adjacent edge have the same color.Below is an algorithm to solve the edge coloring problem which may not use an optimal number of colors: Algorithm: " }, { "code": null, "e": 27500, "s": 27251, "text": "Use BFS traversal to start traversing the graph.Pick any vertex and give different colors to all of the edges connected to it, and mark those edges as colored.Traverse one of it’s edges.Repeat step to with a new vertexd until all edges are colored." }, { "code": null, "e": 27549, "s": 27500, "text": "Use BFS traversal to start traversing the graph." }, { "code": null, "e": 27661, "s": 27549, "text": "Pick any vertex and give different colors to all of the edges connected to it, and mark those edges as colored." }, { "code": null, "e": 27689, "s": 27661, "text": "Traverse one of it’s edges." }, { "code": null, "e": 27752, "s": 27689, "text": "Repeat step to with a new vertexd until all edges are colored." }, { "code": null, "e": 27801, "s": 27752, "text": "Below is the implementation of above approach: " }, { "code": null, "e": 27805, "s": 27801, "text": "C++" }, { "code": null, "e": 27813, "s": 27805, "text": "Python3" }, { "code": "// C++ program to illustrate Edge Coloring#include <bits/stdc++.h>using namespace std; // function to determine the edge colorsvoid colorEdges(int ptr, vector<vector<pair<int, int> > >& gra, vector<int>& edgeColors, bool isVisited[]){ queue<int> q; int c = 0; unordered_set<int> colored; // return if isVisited[ptr] is true if (isVisited[ptr]) return; // Mark the current node visited isVisited[ptr] = 1; // Traverse all edges of current vertex for (int i = 0; i < gra[ptr].size(); i++) { // if already colored, insert it into the set if (edgeColors[gra[ptr][i].second] != -1) colored.insert(edgeColors[gra[ptr][i].second]); } for (int i = 0; i < gra[ptr].size(); i++) { // if not visited, inset into the queue if (!isVisited[gra[ptr][i].first]) q.push(gra[ptr][i].first); if (edgeColors[gra[ptr][i].second] == -1) { // if col vector -> negative while (colored.find(c) != colored.end()) // increment the color c++; // copy it in the vector edgeColors[gra[ptr][i].second] = c; // then add it to the set colored.insert(c); c++; } } // while queue's not empty while (!q.empty()) { int temp = q.front(); q.pop(); colorEdges(temp, gra, edgeColors, isVisited); } return;} // Driver Functionint main(){ set<int> empty; // declaring vector of vector of pairs, to define Graph vector<vector<pair<int, int> > > gra; vector<int> edgeColors; bool isVisited[100000] = { 0 }; // Enter the Number of Vertices // and the number of edges int ver = 4; int edge = 4; gra.resize(ver); edgeColors.resize(edge, -1); // Enter edge & vertices of edge // x--; y--; // Since graph is undirected, push both pairs // (x, y) and (y, x) // graph[x].push_back(make_pair(y, i)); // graph[y].push_back(make_pair(x, i)); gra[0].push_back(make_pair(1, 0)); gra[1].push_back(make_pair(0, 0)); gra[1].push_back(make_pair(2, 1)); gra[2].push_back(make_pair(1, 1)); gra[2].push_back(make_pair(3, 2)); gra[3].push_back(make_pair(2, 2)); gra[0].push_back(make_pair(3, 3)); gra[3].push_back(make_pair(0, 3)); colorEdges(0, gra, edgeColors, isVisited); // printing all the edge colors for (int i = 0; i < edge; i++) cout << \"Edge \" << i + 1 << \" is of color \" << edgeColors[i] + 1 << \"\\n\"; return 0;}", "e": 30363, "s": 27813, "text": null }, { "code": "# Python3 program to illustrate Edge Coloring from queue import Queue# function to determine the edge colorsdef colorEdges(ptr, gra, edgeColors, isVisited): q=Queue() c = 0 colored=set() # return if isVisited[ptr] is true if (isVisited[ptr]): return # Mark the current node visited isVisited[ptr] = True # Traverse all edges of current vertex for i in range(len(gra[ptr])) : # if already colored, insert it into the set if (edgeColors[gra[ptr][i][1]] != -1): colored.add(edgeColors[gra[ptr][i][1]]) for i in range(len(gra[ptr])) : # if not visited, inset into the queue if not isVisited[gra[ptr][i][0]]: q.put(gra[ptr][i][0]) if (edgeColors[gra[ptr][i][1]] == -1) : # if col vector -> negative while c in colored: # increment the color c+=1 # copy it in the vector edgeColors[gra[ptr][i][1]] = c # then add it to the set colored.add(c) c+=1 # while queue's not empty while not q.empty() : temp = q.get() colorEdges(temp, gra, edgeColors, isVisited) return # Driver Functionif __name__=='__main__': empty=set() # declaring vector of vector of pairs, to define Graph gra=[] edgeColors=[] isVisited=[False]*100000 # Enter the Number of Vertices # and the number of edges ver = 4 edge = 4 gra=[[] for _ in range(ver)] edgeColors=[-1]*edge # Enter edge & vertices of edge # x-- y-- # Since graph is undirected, push both pairs # (x, y) and (y, x) # graph[x].append((y, i)) # graph[y].append((x, i)) gra[0].append((1, 0)) gra[1].append((0, 0)) gra[1].append((2, 1)) gra[2].append((1, 1)) gra[2].append((3, 2)) gra[3].append((2, 2)) gra[0].append((3, 3)) gra[3].append((0, 3)) colorEdges(0, gra, edgeColors, isVisited) # printing all the edge colors for i in range(edge): print(\"Edge {} is of color {}\".format(i + 1,edgeColors[i] + 1))", "e": 32455, "s": 30363, "text": null }, { "code": null, "e": 32539, "s": 32455, "text": "Edge 1 is of color 1\nEdge 2 is of color 2\nEdge 3 is of color 1\nEdge 4 is of color 2" }, { "code": null, "e": 32686, "s": 32541, "text": "Time Complexity: O(N) Where N is the number of nodes in the graph.Auxiliary Space: O(N) Reference : https://en.wikipedia.org/wiki/Edge_coloring " }, { "code": null, "e": 32703, "s": 32686, "text": "arorakashish0911" }, { "code": null, "e": 32719, "s": 32703, "text": "pankajsharmagfg" }, { "code": null, "e": 32735, "s": 32719, "text": "amartyaghoshgfg" }, { "code": null, "e": 32763, "s": 32735, "text": "Algorithms-Graph Traversals" }, { "code": null, "e": 32767, "s": 32763, "text": "BFS" }, { "code": null, "e": 32782, "s": 32767, "text": "Graph Coloring" }, { "code": null, "e": 32793, "s": 32782, "text": "Algorithms" }, { "code": null, "e": 32799, "s": 32793, "text": "Graph" }, { "code": null, "e": 32805, "s": 32799, "text": "Graph" }, { "code": null, "e": 32809, "s": 32805, "text": "BFS" }, { "code": null, "e": 32820, "s": 32809, "text": "Algorithms" }, { "code": null, "e": 32918, "s": 32820, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32943, "s": 32918, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 32970, "s": 32943, "text": "How to Start Learning DSA?" }, { "code": null, "e": 33004, "s": 32970, "text": "K means Clustering - Introduction" }, { "code": null, "e": 33071, "s": 33004, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 33100, "s": 33071, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 33140, "s": 33100, "text": "Breadth First Search or BFS for a Graph" }, { "code": null, "e": 33178, "s": 33140, "text": "Depth First Search or DFS for a Graph" }, { "code": null, "e": 33229, "s": 33178, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 33287, "s": 33229, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
10 Interesting Python Cool Tricks - GeeksforGeeks
31 Dec, 2018 In python we can return multiple values – It’s very unique feature of Python that returns multiple value at time.def GFG(): g = 1 f = 2 return g, f x, y = GFG()print(x, y)Output:(1, 2) Allows Negative Indexing: Python allows negative indexing for its sequences. Index -1 refer to the last element, -2 second last element and so on.my_list = ['geeks', 'practice', 'contribute']print(my_list[-1])Output:contribute Combining Multiple Strings. We can easily concatenate all the tokens available in the list.my_list = ['geeks', 'for', 'geeks']print(''.join(my_list))Output:geeksforgeeks Swapping is as easy as none.See, How we could swap two object in Python.x = 1y = 2 print('Before Swapping')print(x, y) x, y = y, xprint('After Swapping')print(x, y)Output:Before Swapping (1, 2) After Swapping (2, 1) Want to create file server in PythonWe can easily do this just by using below code of line.python -m SimpleHTTPServer # default port 8080You can access your file server from the connected device in same network.Want to know about Python version you are using(Just by doing some coding). Use below lines of Code –import sysprint("My Python version Number: {}".format(sys.version)) Output:My Python version Number: 2.7.12 (default, Nov 12 2018, 14:36:49) [GCC 5.4.0 20160609] It prints version you are using.Store all values of List in new separate variables.a = [1, 2, 3]x, y, z = a print(x)print(y)print(z) Output:1 2 3 Convert nested list into one list, just by using Itertools one line of code. Example – [[1, 2], [3, 4], [5, 6]] should be converted into [1, 2, 3, 4, 5, 6]import itertools a = [[1, 2], [3, 4], [5, 6]]print(list(itertools.chain.from_iterable(a)))Output:[1, 2, 3, 4, 5, 6] Want to transpose a Matrix. Just use zip to do that.matrix = [[1, 2, 3], [4, 5, 6]]print(zip(*matrix))Output:[(1, 4), (2, 5), (3, 6)] Want to declare some small function, but not using conventional way of declaring. Use lambda. The lambda keyword in python provides shortcut for declare anonymous function.subtract = lambda x, y : x-ysubtract(5, 4) It’s very unique feature of Python that returns multiple value at time.def GFG(): g = 1 f = 2 return g, f x, y = GFG()print(x, y)Output:(1, 2) def GFG(): g = 1 f = 2 return g, f x, y = GFG()print(x, y) (1, 2) Allows Negative Indexing: Python allows negative indexing for its sequences. Index -1 refer to the last element, -2 second last element and so on.my_list = ['geeks', 'practice', 'contribute']print(my_list[-1])Output:contribute my_list = ['geeks', 'practice', 'contribute']print(my_list[-1]) contribute Combining Multiple Strings. We can easily concatenate all the tokens available in the list.my_list = ['geeks', 'for', 'geeks']print(''.join(my_list))Output:geeksforgeeks my_list = ['geeks', 'for', 'geeks']print(''.join(my_list)) geeksforgeeks Swapping is as easy as none.See, How we could swap two object in Python.x = 1y = 2 print('Before Swapping')print(x, y) x, y = y, xprint('After Swapping')print(x, y)Output:Before Swapping (1, 2) After Swapping (2, 1) See, How we could swap two object in Python. x = 1y = 2 print('Before Swapping')print(x, y) x, y = y, xprint('After Swapping')print(x, y) Before Swapping (1, 2) After Swapping (2, 1) Want to create file server in PythonWe can easily do this just by using below code of line.python -m SimpleHTTPServer # default port 8080You can access your file server from the connected device in same network. python -m SimpleHTTPServer # default port 8080 You can access your file server from the connected device in same network. Want to know about Python version you are using(Just by doing some coding). Use below lines of Code –import sysprint("My Python version Number: {}".format(sys.version)) Output:My Python version Number: 2.7.12 (default, Nov 12 2018, 14:36:49) [GCC 5.4.0 20160609] It prints version you are using. import sysprint("My Python version Number: {}".format(sys.version)) My Python version Number: 2.7.12 (default, Nov 12 2018, 14:36:49) [GCC 5.4.0 20160609] It prints version you are using. Store all values of List in new separate variables.a = [1, 2, 3]x, y, z = a print(x)print(y)print(z) Output:1 2 3 a = [1, 2, 3]x, y, z = a print(x)print(y)print(z) 1 2 3 Convert nested list into one list, just by using Itertools one line of code. Example – [[1, 2], [3, 4], [5, 6]] should be converted into [1, 2, 3, 4, 5, 6]import itertools a = [[1, 2], [3, 4], [5, 6]]print(list(itertools.chain.from_iterable(a)))Output:[1, 2, 3, 4, 5, 6] import itertools a = [[1, 2], [3, 4], [5, 6]]print(list(itertools.chain.from_iterable(a))) [1, 2, 3, 4, 5, 6] Want to transpose a Matrix. Just use zip to do that.matrix = [[1, 2, 3], [4, 5, 6]]print(zip(*matrix))Output:[(1, 4), (2, 5), (3, 6)] matrix = [[1, 2, 3], [4, 5, 6]]print(zip(*matrix)) [(1, 4), (2, 5), (3, 6)] Want to declare some small function, but not using conventional way of declaring. Use lambda. The lambda keyword in python provides shortcut for declare anonymous function.subtract = lambda x, y : x-ysubtract(5, 4) subtract = lambda x, y : x-ysubtract(5, 4) python-basics Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python Create a Pandas DataFrame from Lists *args and **kwargs in Python Selecting rows in pandas DataFrame based on conditions
[ { "code": null, "e": 24614, "s": 24586, "text": "\n31 Dec, 2018" }, { "code": null, "e": 24656, "s": 24614, "text": "In python we can return multiple values –" }, { "code": null, "e": 26668, "s": 24656, "text": "It’s very unique feature of Python that returns multiple value at time.def GFG(): g = 1 f = 2 return g, f x, y = GFG()print(x, y)Output:(1, 2)\nAllows Negative Indexing: Python allows negative indexing for its sequences. Index -1 refer to the last element, -2 second last element and so on.my_list = ['geeks', 'practice', 'contribute']print(my_list[-1])Output:contribute\nCombining Multiple Strings. We can easily concatenate all the tokens available in the list.my_list = ['geeks', 'for', 'geeks']print(''.join(my_list))Output:geeksforgeeks\nSwapping is as easy as none.See, How we could swap two object in Python.x = 1y = 2 print('Before Swapping')print(x, y) x, y = y, xprint('After Swapping')print(x, y)Output:Before Swapping\n(1, 2)\nAfter Swapping\n(2, 1)\nWant to create file server in PythonWe can easily do this just by using below code of line.python -m SimpleHTTPServer # default port 8080You can access your file server from the connected device in same network.Want to know about Python version you are using(Just by doing some coding). Use below lines of Code –import sysprint(\"My Python version Number: {}\".format(sys.version)) Output:My Python version Number: 2.7.12 (default, Nov 12 2018, 14:36:49) \n[GCC 5.4.0 20160609]\nIt prints version you are using.Store all values of List in new separate variables.a = [1, 2, 3]x, y, z = a print(x)print(y)print(z) Output:1\n2\n3\nConvert nested list into one list, just by using Itertools one line of code. Example – [[1, 2], [3, 4], [5, 6]] should be converted into [1, 2, 3, 4, 5, 6]import itertools a = [[1, 2], [3, 4], [5, 6]]print(list(itertools.chain.from_iterable(a)))Output:[1, 2, 3, 4, 5, 6]\nWant to transpose a Matrix. Just use zip to do that.matrix = [[1, 2, 3], [4, 5, 6]]print(zip(*matrix))Output:[(1, 4), (2, 5), (3, 6)]\nWant to declare some small function, but not using conventional way of declaring. Use lambda. The lambda keyword in python provides shortcut for declare anonymous function.subtract = lambda x, y : x-ysubtract(5, 4)" }, { "code": null, "e": 26824, "s": 26668, "text": "It’s very unique feature of Python that returns multiple value at time.def GFG(): g = 1 f = 2 return g, f x, y = GFG()print(x, y)Output:(1, 2)\n" }, { "code": "def GFG(): g = 1 f = 2 return g, f x, y = GFG()print(x, y)", "e": 26895, "s": 26824, "text": null }, { "code": null, "e": 26903, "s": 26895, "text": "(1, 2)\n" }, { "code": null, "e": 27131, "s": 26903, "text": "Allows Negative Indexing: Python allows negative indexing for its sequences. Index -1 refer to the last element, -2 second last element and so on.my_list = ['geeks', 'practice', 'contribute']print(my_list[-1])Output:contribute\n" }, { "code": "my_list = ['geeks', 'practice', 'contribute']print(my_list[-1])", "e": 27195, "s": 27131, "text": null }, { "code": null, "e": 27207, "s": 27195, "text": "contribute\n" }, { "code": null, "e": 27378, "s": 27207, "text": "Combining Multiple Strings. We can easily concatenate all the tokens available in the list.my_list = ['geeks', 'for', 'geeks']print(''.join(my_list))Output:geeksforgeeks\n" }, { "code": "my_list = ['geeks', 'for', 'geeks']print(''.join(my_list))", "e": 27437, "s": 27378, "text": null }, { "code": null, "e": 27452, "s": 27437, "text": "geeksforgeeks\n" }, { "code": null, "e": 27671, "s": 27452, "text": "Swapping is as easy as none.See, How we could swap two object in Python.x = 1y = 2 print('Before Swapping')print(x, y) x, y = y, xprint('After Swapping')print(x, y)Output:Before Swapping\n(1, 2)\nAfter Swapping\n(2, 1)\n" }, { "code": null, "e": 27716, "s": 27671, "text": "See, How we could swap two object in Python." }, { "code": "x = 1y = 2 print('Before Swapping')print(x, y) x, y = y, xprint('After Swapping')print(x, y)", "e": 27811, "s": 27716, "text": null }, { "code": null, "e": 27857, "s": 27811, "text": "Before Swapping\n(1, 2)\nAfter Swapping\n(2, 1)\n" }, { "code": null, "e": 28069, "s": 27857, "text": "Want to create file server in PythonWe can easily do this just by using below code of line.python -m SimpleHTTPServer # default port 8080You can access your file server from the connected device in same network." }, { "code": "python -m SimpleHTTPServer # default port 8080", "e": 28116, "s": 28069, "text": null }, { "code": null, "e": 28191, "s": 28116, "text": "You can access your file server from the connected device in same network." }, { "code": null, "e": 28489, "s": 28191, "text": "Want to know about Python version you are using(Just by doing some coding). Use below lines of Code –import sysprint(\"My Python version Number: {}\".format(sys.version)) Output:My Python version Number: 2.7.12 (default, Nov 12 2018, 14:36:49) \n[GCC 5.4.0 20160609]\nIt prints version you are using." }, { "code": "import sysprint(\"My Python version Number: {}\".format(sys.version)) ", "e": 28559, "s": 28489, "text": null }, { "code": null, "e": 28648, "s": 28559, "text": "My Python version Number: 2.7.12 (default, Nov 12 2018, 14:36:49) \n[GCC 5.4.0 20160609]\n" }, { "code": null, "e": 28681, "s": 28648, "text": "It prints version you are using." }, { "code": null, "e": 28796, "s": 28681, "text": "Store all values of List in new separate variables.a = [1, 2, 3]x, y, z = a print(x)print(y)print(z) Output:1\n2\n3\n" }, { "code": "a = [1, 2, 3]x, y, z = a print(x)print(y)print(z) ", "e": 28847, "s": 28796, "text": null }, { "code": null, "e": 28854, "s": 28847, "text": "1\n2\n3\n" }, { "code": null, "e": 29126, "s": 28854, "text": "Convert nested list into one list, just by using Itertools one line of code. Example – [[1, 2], [3, 4], [5, 6]] should be converted into [1, 2, 3, 4, 5, 6]import itertools a = [[1, 2], [3, 4], [5, 6]]print(list(itertools.chain.from_iterable(a)))Output:[1, 2, 3, 4, 5, 6]\n" }, { "code": "import itertools a = [[1, 2], [3, 4], [5, 6]]print(list(itertools.chain.from_iterable(a)))", "e": 29217, "s": 29126, "text": null }, { "code": null, "e": 29237, "s": 29217, "text": "[1, 2, 3, 4, 5, 6]\n" }, { "code": null, "e": 29372, "s": 29237, "text": "Want to transpose a Matrix. Just use zip to do that.matrix = [[1, 2, 3], [4, 5, 6]]print(zip(*matrix))Output:[(1, 4), (2, 5), (3, 6)]\n" }, { "code": "matrix = [[1, 2, 3], [4, 5, 6]]print(zip(*matrix))", "e": 29423, "s": 29372, "text": null }, { "code": null, "e": 29449, "s": 29423, "text": "[(1, 4), (2, 5), (3, 6)]\n" }, { "code": null, "e": 29664, "s": 29449, "text": "Want to declare some small function, but not using conventional way of declaring. Use lambda. The lambda keyword in python provides shortcut for declare anonymous function.subtract = lambda x, y : x-ysubtract(5, 4)" }, { "code": "subtract = lambda x, y : x-ysubtract(5, 4)", "e": 29707, "s": 29664, "text": null }, { "code": null, "e": 29721, "s": 29707, "text": "python-basics" }, { "code": null, "e": 29745, "s": 29721, "text": "Technical Scripter 2018" }, { "code": null, "e": 29752, "s": 29745, "text": "Python" }, { "code": null, "e": 29771, "s": 29752, "text": "Technical Scripter" }, { "code": null, "e": 29869, "s": 29771, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29878, "s": 29869, "text": "Comments" }, { "code": null, "e": 29891, "s": 29878, "text": "Old Comments" }, { "code": null, "e": 29909, "s": 29891, "text": "Python Dictionary" }, { "code": null, "e": 29944, "s": 29909, "text": "Read a file line by line in Python" }, { "code": null, "e": 29976, "s": 29944, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30018, "s": 29976, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 30044, "s": 30018, "text": "Python String | replace()" }, { "code": null, "e": 30087, "s": 30044, "text": "Python program to convert a list to string" }, { "code": null, "e": 30131, "s": 30087, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 30168, "s": 30131, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 30197, "s": 30168, "text": "*args and **kwargs in Python" } ]
Count subtrees that sum up to a given value x only using single recursive function - GeeksforGeeks
27 Dec, 2021 Given a binary tree containing n nodes. The problem is to count subtrees having total node’s data sum equal to a given value using only single recursive functions. Examples: Input : 5 / \ -10 3 / \ / \ 9 8 -4 7 x = 7 Output : 2 There are 2 subtrees with sum 7. 1st one is leaf node: 7. 2nd one is: -10 / \ 9 8 Source: Microsoft Interview Experience | Set 157. Approach: countSubtreesWithSumX(root, count, x) if !root then return 0 ls = countSubtreesWithSumX(root->left, count, x) rs = countSubtreesWithSumX(root->right, count, x) sum = ls + rs + root->data if sum == x then count++ return sum countSubtreesWithSumXUtil(root, x) if !root then return 0 Initialize count = 0 ls = countSubtreesWithSumX(root->left, count, x) rs = countSubtreesWithSumX(root->right, count, x) if (ls + rs + root->data) == x count++ return count C++ Java Python3 C# Javascript // C++ implementation to count subtrees that// sum up to a given value x#include <bits/stdc++.h> using namespace std; // structure of a node of binary treestruct Node { int data; Node *left, *right;}; // function to get a new nodeNode* getNode(int data){ // allocate space Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // function to count subtrees that// sum up to a given value xint countSubtreesWithSumX(Node* root, int& count, int x){ // if tree is empty if (!root) return 0; // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root->left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root->right, count, x); // sum of nodes in the subtree rooted // with 'root->data' int sum = ls + rs + root->data; // if true if (sum == x) count++; // return subtree's nodes sum return sum;} // utility function to count subtrees that// sum up to a given value xint countSubtreesWithSumXUtil(Node* root, int x){ // if tree is empty if (!root) return 0; int count = 0; // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root->left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root->right, count, x); // if tree's nodes sum == x if ((ls + rs + root->data) == x) count++; // required count of subtrees return count;} // Driver program to test aboveint main(){ /* binary tree creation 5 / \ -10 3 / \ / \ 9 8 -4 7 */ Node* root = getNode(5); root->left = getNode(-10); root->right = getNode(3); root->left->left = getNode(9); root->left->right = getNode(8); root->right->left = getNode(-4); root->right->right = getNode(7); int x = 7; cout << "Count = " << countSubtreesWithSumXUtil(root, x); return 0;} // Java program to find if// there is a subtree with// given sumimport java.util.*;class GFG{ // structure of a node// of binary treestatic class Node{ int data; Node left, right;} static class INT{ int v; INT(int a) { v = a; }} // function to get a new nodestatic Node getNode(int data){ // allocate space Node newNode = new Node(); // put in the data newNode.data = data; newNode.left = newNode.right = null; return newNode;} // function to count subtrees that// sum up to a given value xstatic int countSubtreesWithSumX(Node root, INT count, int x){ // if tree is empty if (root == null) return 0; // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root.left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root.right, count, x); // sum of nodes in the subtree // rooted with 'root.data' int sum = ls + rs + root.data; // if true if (sum == x) count.v++; // return subtree's nodes sum return sum;} // utility function to// count subtrees that// sum up to a given value xstatic int countSubtreesWithSumXUtil(Node root, int x){ // if tree is empty if (root == null) return 0; INT count = new INT(0); // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root.left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root.right, count, x); // if tree's nodes sum == x if ((ls + rs + root.data) == x) count.v++; // required count of subtrees return count.v;} // Driver Codepublic static void main(String args[]){ /* binary tree creation 5 / \ -10 3 / \ / \ 9 8 -4 7 */ Node root = getNode(5); root.left = getNode(-10); root.right = getNode(3); root.left.left = getNode(9); root.left.right = getNode(8); root.right.left = getNode(-4); root.right.right = getNode(7); int x = 7; System.out.println("Count = " + countSubtreesWithSumXUtil(root, x));}} // This code is contributed// by Arnab Kundu # Python3 implementation to count subtrees# that Sum up to a given value x # class to get a new nodeclass getNode: def __init__(self, data): # put in the data self.data = data self.left = self.right = None # function to count subtrees that# Sum up to a given value xdef countSubtreesWithSumX(root, count, x): # if tree is empty if (not root): return 0 # Sum of nodes in the left subtree ls = countSubtreesWithSumX(root.left, count, x) # Sum of nodes in the right subtree rs = countSubtreesWithSumX(root.right, count, x) # Sum of nodes in the subtree # rooted with 'root.data' Sum = ls + rs + root.data # if true if (Sum == x): count[0] += 1 # return subtree's nodes Sum return Sum # utility function to count subtrees# that Sum up to a given value xdef countSubtreesWithSumXUtil(root, x): # if tree is empty if (not root): return 0 count = [0] # Sum of nodes in the left subtree ls = countSubtreesWithSumX(root.left, count, x) # Sum of nodes in the right subtree rs = countSubtreesWithSumX(root.right, count, x) # if tree's nodes Sum == x if ((ls + rs + root.data) == x): count[0] += 1 # required count of subtrees return count[0] # Driver Codeif __name__ == '__main__': # binary tree creation # 5 # / \ # -10 3 # / \ / \ # 9 8 -4 7 root = getNode(5) root.left = getNode(-10) root.right = getNode(3) root.left.left = getNode(9) root.left.right = getNode(8) root.right.left = getNode(-4) root.right.right = getNode(7) x = 7 print("Count =", countSubtreesWithSumXUtil(root, x)) # This code is contributed by PranchalK using System; // c# program to find if// there is a subtree with// given sumpublic class GFG{ // structure of a node// of binary treepublic class Node{ public int data; public Node left, right;} public class INT{ public int v; public INT(int a) { v = a; }} // function to get a new nodepublic static Node getNode(int data){ // allocate space Node newNode = new Node(); // put in the data newNode.data = data; newNode.left = newNode.right = null; return newNode;} // function to count subtrees that// sum up to a given value xpublic static int countSubtreesWithSumX(Node root, INT count, int x){ // if tree is empty if (root == null) { return 0; } // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root.left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root.right, count, x); // sum of nodes in the subtree // rooted with 'root.data' int sum = ls + rs + root.data; // if true if (sum == x) { count.v++; } // return subtree's nodes sum return sum;} // utility function to// count subtrees that// sum up to a given value xpublic static int countSubtreesWithSumXUtil(Node root, int x){ // if tree is empty if (root == null) { return 0; } INT count = new INT(0); // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root.left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root.right, count, x); // if tree's nodes sum == x if ((ls + rs + root.data) == x) { count.v++; } // required count of subtrees return count.v;} // Driver Codepublic static void Main(string[] args){ /* binary tree creation 5 / \ -10 3 / \ / \ 9 8 -4 7 */ Node root = getNode(5); root.left = getNode(-10); root.right = getNode(3); root.left.left = getNode(9); root.left.right = getNode(8); root.right.left = getNode(-4); root.right.right = getNode(7); int x = 7; Console.WriteLine("Count = " + countSubtreesWithSumXUtil(root, x));}} // This code is contributed by Shrikant13 <script> // Javascript program to find if // there is a subtree with given sum class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let v; // function to get a new node function getNode(data) { // allocate space let newNode = new Node(data); return newNode; } // function to count subtrees that // sum up to a given value x function countSubtreesWithSumX(root, x) { // if tree is empty if (root == null) return 0; // sum of nodes in the left subtree let ls = countSubtreesWithSumX(root.left, x); // sum of nodes in the right subtree let rs = countSubtreesWithSumX(root.right, x); // sum of nodes in the subtree // rooted with 'root.data' let sum = ls + rs + root.data; // if true if (sum == x) v++; // return subtree's nodes sum return sum; } // utility function to // count subtrees that // sum up to a given value x function countSubtreesWithSumXUtil(root, x) { // if tree is empty if (root == null) return 0; v = 0; // sum of nodes in the left subtree let ls = countSubtreesWithSumX(root.left, x); // sum of nodes in the right subtree let rs = countSubtreesWithSumX(root.right, x); // if tree's nodes sum == x if ((ls + rs + root.data) == x) v++; // required count of subtrees return v; } /* binary tree creation 5 / \ -10 3 / \ / \ 9 8 -4 7 */ let root = getNode(5); root.left = getNode(-10); root.right = getNode(3); root.left.left = getNode(9); root.left.right = getNode(8); root.right.left = getNode(-4); root.right.right = getNode(7); let x = 7; document.write("Count = " + countSubtreesWithSumXUtil(root, x)); // This code is contributed by decode2207.</script> Output: Count = 2 Time Complexity: O(n). Another Approach: countSubtreesWithSumXUtil(root, x) Initialize static count = 0 Initialize static *ptr = root if !root then return 0 Initialize static count = 0 ls+ = countSubtreesWithSumXUtil(root->left, count, x) rs+ = countSubtreesWithSumXUtil(root->right, count, x) if (ls + rs + root->data) == x count++ if(ptr!=root) return ls + root->data + rs else return count C++ Java Python3 C# Javascript // C++ program to find if// there is a subtree with// given sum#include <bits/stdc++.h> using namespace std; // Structure of a node of binary treestruct Node { int data; Node *left, *right;}; // Function to get a new nodeNode* getNode(int data){ // Allocate space Node* newNode = (Node*)malloc(sizeof(Node)); // Put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // Utility function to count subtrees that// sum up to a given value xint countSubtreesWithSumXUtil(Node* root, int x){ static int count=0; static Node* ptr=root; int l=0,r=0; if(root==NULL) return 0; l+=countSubtreesWithSumXUtil(root->left,x); r+=countSubtreesWithSumXUtil(root->right,x); if(l+r+root->data==x) count++; if(ptr!=root) return l+root->data+r; return count; } // Driver codeint main(){ /* binary tree creation 5 / \ -10 3 / \ / \ 9 8 -4 7 */ Node* root = getNode(5); root->left = getNode(-10); root->right = getNode(3); root->left->left = getNode(9); root->left->right = getNode(8); root->right->left = getNode(-4); root->right->right = getNode(7); int x = 7; cout << "Count = " << countSubtreesWithSumXUtil(root, x); return 0;}// This code is contributed by Sadik Ali // Java program to find if// there is a subtree with// given sumimport java.io.*; // Node class to create new nodeclass Node{ int data; Node left; Node right; Node(int data) { this.data = data; }} class GFG{ static int count = 0; static Node ptr; // Utility function to count subtrees that // sum up to a given value x int countSubtreesWithSumXUtil(Node root, int x) { int l = 0, r = 0; if(root == null) return 0; l += countSubtreesWithSumXUtil(root.left, x); r += countSubtreesWithSumXUtil(root.right, x); if(l + r + root.data == x) count++; if(ptr != root) return l + root.data + r; return count; } // Driver Code public static void main(String[] args) { /* binary tree creation 5 / \ -10 3 / \ / \ 9 8 -4 7 */ Node root = new Node(5); root.left = new Node(-10); root.right = new Node(3); root.left.left = new Node(9); root.left.right = new Node(8); root.right.left = new Node(-4); root.right.right = new Node(7); int x = 7; ptr = root; // assigning global value of ptr System.out.println("Count = " + new GFG().countSubtreesWithSumXUtil(root, x)); }} // This code is submitted by Devarshi_Singh # Python3 program to find if there is# a subtree with given sum # Structure of a node of binary treeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to get a new nodedef getNode(data): # Allocate space newNode = Node(data) return newNode count = 0ptr = None # Utility function to count subtrees that# sum up to a given value xdef countSubtreesWithSumXUtil(root, x): global count, ptr l = 0 r = 0 if (root == None): return 0 l += countSubtreesWithSumXUtil(root.left, x) r += countSubtreesWithSumXUtil(root.right, x) if (l + r + root.data == x): count += 1 if (ptr != root): return l + root.data + r return count # Driver codeif __name__=='__main__': ''' binary tree creation 5 / \ -10 3 / \ / \ 9 8 -4 7 ''' root = getNode(5) root.left = getNode(-10) root.right = getNode(3) root.left.left = getNode(9) root.left.right = getNode(8) root.right.left = getNode(-4) root.right.right = getNode(7) x = 7 ptr = root print("Count = " + str(countSubtreesWithSumXUtil( root, x))) # This code is contributed by pratham76 // C# program to find if// there is a subtree with// given sumusing System; // Node class to// create new nodepublic class Node{ public int data; public Node left; public Node right; public Node(int data) { this.data = data; }} class GFG{ static int count = 0;static Node ptr; // Utility function to count subtrees// that sum up to a given value xint countSubtreesWithSumXUtil(Node root, int x){ int l = 0, r = 0; if(root == null) return 0; l += countSubtreesWithSumXUtil(root.left, x); r += countSubtreesWithSumXUtil(root.right, x); if(l + r + root.data == x) count++; if(ptr != root) return l + root.data + r; return count;} // Driver Codepublic static void Main(string[] args){ /* binary tree creation 5 / \ -10 3 / \ / \ 9 8 -4 7 */ Node root = new Node(5); root.left = new Node(-10); root.right = new Node(3); root.left.left = new Node(9); root.left.right = new Node(8); root.right.left = new Node(-4); root.right.right = new Node(7); int x = 7; // Assigning global value of ptr ptr = root; Console.Write("Count = " + new GFG().countSubtreesWithSumXUtil(root, x));}} // This code is contributed by rutvik_56 <script> // JavaScript program to find if // there is a subtree with // given sum class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let count = 0; let ptr; // Utility function to count subtrees that // sum up to a given value x function countSubtreesWithSumXUtil(root, x) { let l = 0, r = 0; if(root == null) return 0; l += countSubtreesWithSumXUtil(root.left, x); r += countSubtreesWithSumXUtil(root.right, x); if(l + r + root.data == x) count++; if(ptr != root) return l + root.data + r; return count; } /* binary tree creation 5 / \ -10 3 / \ / \ 9 8 -4 7 */ let root = new Node(5); root.left = new Node(-10); root.right = new Node(3); root.left.left = new Node(9); root.left.right = new Node(8); root.right.left = new Node(-4); root.right.right = new Node(7); let x = 7; ptr = root; // assigning global value of ptr document.write("Count = " + countSubtreesWithSumXUtil(root, x)); </script> Output: Count = 2 Time Complexity: O(n). andrew1234 shrikanth13 PranchalKatiyar chsadik99 Devarshi_Singh rutvik_56 pratham76 mukesh07 decode2207 arorakashish0911 Microsoft Recursion Tree Microsoft Recursion Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Print all possible combinations of r elements in a given array of size n Backtracking | Introduction Recursive Practice Problems with Solutions Write a program to reverse digits of a number Recursive Functions Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal AVL Tree | Set 1 (Insertion) Inorder Tree Traversal without Recursion
[ { "code": null, "e": 25306, "s": 25278, "text": "\n27 Dec, 2021" }, { "code": null, "e": 25470, "s": 25306, "text": "Given a binary tree containing n nodes. The problem is to count subtrees having total node’s data sum equal to a given value using only single recursive functions." }, { "code": null, "e": 25481, "s": 25470, "text": "Examples: " }, { "code": null, "e": 25722, "s": 25481, "text": "Input : \n 5\n / \\ \n -10 3\n / \\ / \\\n 9 8 -4 7\n \n x = 7\n\nOutput : 2\nThere are 2 subtrees with sum 7.\n\n1st one is leaf node:\n7.\n\n2nd one is:\n\n -10\n / \\\n 9 8" }, { "code": null, "e": 25772, "s": 25722, "text": "Source: Microsoft Interview Experience | Set 157." }, { "code": null, "e": 25783, "s": 25772, "text": "Approach: " }, { "code": null, "e": 26337, "s": 25783, "text": "countSubtreesWithSumX(root, count, x)\n if !root then\n return 0\n \n ls = countSubtreesWithSumX(root->left, count, x)\n rs = countSubtreesWithSumX(root->right, count, x)\n sum = ls + rs + root->data\n \n if sum == x then\n count++\n return sum\n\ncountSubtreesWithSumXUtil(root, x)\n if !root then\n return 0\n \n Initialize count = 0\n ls = countSubtreesWithSumX(root->left, count, x)\n rs = countSubtreesWithSumX(root->right, count, x)\n \n if (ls + rs + root->data) == x\n count++\n return count" }, { "code": null, "e": 26341, "s": 26337, "text": "C++" }, { "code": null, "e": 26346, "s": 26341, "text": "Java" }, { "code": null, "e": 26354, "s": 26346, "text": "Python3" }, { "code": null, "e": 26357, "s": 26354, "text": "C#" }, { "code": null, "e": 26368, "s": 26357, "text": "Javascript" }, { "code": "// C++ implementation to count subtrees that// sum up to a given value x#include <bits/stdc++.h> using namespace std; // structure of a node of binary treestruct Node { int data; Node *left, *right;}; // function to get a new nodeNode* getNode(int data){ // allocate space Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // function to count subtrees that// sum up to a given value xint countSubtreesWithSumX(Node* root, int& count, int x){ // if tree is empty if (!root) return 0; // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root->left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root->right, count, x); // sum of nodes in the subtree rooted // with 'root->data' int sum = ls + rs + root->data; // if true if (sum == x) count++; // return subtree's nodes sum return sum;} // utility function to count subtrees that// sum up to a given value xint countSubtreesWithSumXUtil(Node* root, int x){ // if tree is empty if (!root) return 0; int count = 0; // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root->left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root->right, count, x); // if tree's nodes sum == x if ((ls + rs + root->data) == x) count++; // required count of subtrees return count;} // Driver program to test aboveint main(){ /* binary tree creation 5 / \\ -10 3 / \\ / \\ 9 8 -4 7 */ Node* root = getNode(5); root->left = getNode(-10); root->right = getNode(3); root->left->left = getNode(9); root->left->right = getNode(8); root->right->left = getNode(-4); root->right->right = getNode(7); int x = 7; cout << \"Count = \" << countSubtreesWithSumXUtil(root, x); return 0;}", "e": 28436, "s": 26368, "text": null }, { "code": "// Java program to find if// there is a subtree with// given sumimport java.util.*;class GFG{ // structure of a node// of binary treestatic class Node{ int data; Node left, right;} static class INT{ int v; INT(int a) { v = a; }} // function to get a new nodestatic Node getNode(int data){ // allocate space Node newNode = new Node(); // put in the data newNode.data = data; newNode.left = newNode.right = null; return newNode;} // function to count subtrees that// sum up to a given value xstatic int countSubtreesWithSumX(Node root, INT count, int x){ // if tree is empty if (root == null) return 0; // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root.left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root.right, count, x); // sum of nodes in the subtree // rooted with 'root.data' int sum = ls + rs + root.data; // if true if (sum == x) count.v++; // return subtree's nodes sum return sum;} // utility function to// count subtrees that// sum up to a given value xstatic int countSubtreesWithSumXUtil(Node root, int x){ // if tree is empty if (root == null) return 0; INT count = new INT(0); // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root.left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root.right, count, x); // if tree's nodes sum == x if ((ls + rs + root.data) == x) count.v++; // required count of subtrees return count.v;} // Driver Codepublic static void main(String args[]){ /* binary tree creation 5 / \\ -10 3 / \\ / \\ 9 8 -4 7 */ Node root = getNode(5); root.left = getNode(-10); root.right = getNode(3); root.left.left = getNode(9); root.left.right = getNode(8); root.right.left = getNode(-4); root.right.right = getNode(7); int x = 7; System.out.println(\"Count = \" + countSubtreesWithSumXUtil(root, x));}} // This code is contributed// by Arnab Kundu", "e": 30767, "s": 28436, "text": null }, { "code": "# Python3 implementation to count subtrees# that Sum up to a given value x # class to get a new nodeclass getNode: def __init__(self, data): # put in the data self.data = data self.left = self.right = None # function to count subtrees that# Sum up to a given value xdef countSubtreesWithSumX(root, count, x): # if tree is empty if (not root): return 0 # Sum of nodes in the left subtree ls = countSubtreesWithSumX(root.left, count, x) # Sum of nodes in the right subtree rs = countSubtreesWithSumX(root.right, count, x) # Sum of nodes in the subtree # rooted with 'root.data' Sum = ls + rs + root.data # if true if (Sum == x): count[0] += 1 # return subtree's nodes Sum return Sum # utility function to count subtrees# that Sum up to a given value xdef countSubtreesWithSumXUtil(root, x): # if tree is empty if (not root): return 0 count = [0] # Sum of nodes in the left subtree ls = countSubtreesWithSumX(root.left, count, x) # Sum of nodes in the right subtree rs = countSubtreesWithSumX(root.right, count, x) # if tree's nodes Sum == x if ((ls + rs + root.data) == x): count[0] += 1 # required count of subtrees return count[0] # Driver Codeif __name__ == '__main__': # binary tree creation # 5 # / \\ # -10 3 # / \\ / \\ # 9 8 -4 7 root = getNode(5) root.left = getNode(-10) root.right = getNode(3) root.left.left = getNode(9) root.left.right = getNode(8) root.right.left = getNode(-4) root.right.right = getNode(7) x = 7 print(\"Count =\", countSubtreesWithSumXUtil(root, x)) # This code is contributed by PranchalK", "e": 32662, "s": 30767, "text": null }, { "code": "using System; // c# program to find if// there is a subtree with// given sumpublic class GFG{ // structure of a node// of binary treepublic class Node{ public int data; public Node left, right;} public class INT{ public int v; public INT(int a) { v = a; }} // function to get a new nodepublic static Node getNode(int data){ // allocate space Node newNode = new Node(); // put in the data newNode.data = data; newNode.left = newNode.right = null; return newNode;} // function to count subtrees that// sum up to a given value xpublic static int countSubtreesWithSumX(Node root, INT count, int x){ // if tree is empty if (root == null) { return 0; } // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root.left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root.right, count, x); // sum of nodes in the subtree // rooted with 'root.data' int sum = ls + rs + root.data; // if true if (sum == x) { count.v++; } // return subtree's nodes sum return sum;} // utility function to// count subtrees that// sum up to a given value xpublic static int countSubtreesWithSumXUtil(Node root, int x){ // if tree is empty if (root == null) { return 0; } INT count = new INT(0); // sum of nodes in the left subtree int ls = countSubtreesWithSumX(root.left, count, x); // sum of nodes in the right subtree int rs = countSubtreesWithSumX(root.right, count, x); // if tree's nodes sum == x if ((ls + rs + root.data) == x) { count.v++; } // required count of subtrees return count.v;} // Driver Codepublic static void Main(string[] args){ /* binary tree creation 5 / \\ -10 3 / \\ / \\ 9 8 -4 7 */ Node root = getNode(5); root.left = getNode(-10); root.right = getNode(3); root.left.left = getNode(9); root.left.right = getNode(8); root.right.left = getNode(-4); root.right.right = getNode(7); int x = 7; Console.WriteLine(\"Count = \" + countSubtreesWithSumXUtil(root, x));}} // This code is contributed by Shrikant13", "e": 34906, "s": 32662, "text": null }, { "code": "<script> // Javascript program to find if // there is a subtree with given sum class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let v; // function to get a new node function getNode(data) { // allocate space let newNode = new Node(data); return newNode; } // function to count subtrees that // sum up to a given value x function countSubtreesWithSumX(root, x) { // if tree is empty if (root == null) return 0; // sum of nodes in the left subtree let ls = countSubtreesWithSumX(root.left, x); // sum of nodes in the right subtree let rs = countSubtreesWithSumX(root.right, x); // sum of nodes in the subtree // rooted with 'root.data' let sum = ls + rs + root.data; // if true if (sum == x) v++; // return subtree's nodes sum return sum; } // utility function to // count subtrees that // sum up to a given value x function countSubtreesWithSumXUtil(root, x) { // if tree is empty if (root == null) return 0; v = 0; // sum of nodes in the left subtree let ls = countSubtreesWithSumX(root.left, x); // sum of nodes in the right subtree let rs = countSubtreesWithSumX(root.right, x); // if tree's nodes sum == x if ((ls + rs + root.data) == x) v++; // required count of subtrees return v; } /* binary tree creation 5 / \\ -10 3 / \\ / \\ 9 8 -4 7 */ let root = getNode(5); root.left = getNode(-10); root.right = getNode(3); root.left.left = getNode(9); root.left.right = getNode(8); root.right.left = getNode(-4); root.right.right = getNode(7); let x = 7; document.write(\"Count = \" + countSubtreesWithSumXUtil(root, x)); // This code is contributed by decode2207.</script>", "e": 36989, "s": 34906, "text": null }, { "code": null, "e": 36998, "s": 36989, "text": "Output: " }, { "code": null, "e": 37008, "s": 36998, "text": "Count = 2" }, { "code": null, "e": 37031, "s": 37008, "text": "Time Complexity: O(n)." }, { "code": null, "e": 37050, "s": 37031, "text": "Another Approach: " }, { "code": null, "e": 37475, "s": 37050, "text": "countSubtreesWithSumXUtil(root, x)\n\n Initialize static count = 0\n Initialize static *ptr = root\n if !root then\n return 0\n \n Initialize static count = 0\n ls+ = countSubtreesWithSumXUtil(root->left, count, x)\n rs+ = countSubtreesWithSumXUtil(root->right, count, x)\n \n if (ls + rs + root->data) == x\n count++\n \n if(ptr!=root)\n return ls + root->data + rs\n else\n return count" }, { "code": null, "e": 37479, "s": 37475, "text": "C++" }, { "code": null, "e": 37484, "s": 37479, "text": "Java" }, { "code": null, "e": 37492, "s": 37484, "text": "Python3" }, { "code": null, "e": 37495, "s": 37492, "text": "C#" }, { "code": null, "e": 37506, "s": 37495, "text": "Javascript" }, { "code": "// C++ program to find if// there is a subtree with// given sum#include <bits/stdc++.h> using namespace std; // Structure of a node of binary treestruct Node { int data; Node *left, *right;}; // Function to get a new nodeNode* getNode(int data){ // Allocate space Node* newNode = (Node*)malloc(sizeof(Node)); // Put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // Utility function to count subtrees that// sum up to a given value xint countSubtreesWithSumXUtil(Node* root, int x){ static int count=0; static Node* ptr=root; int l=0,r=0; if(root==NULL) return 0; l+=countSubtreesWithSumXUtil(root->left,x); r+=countSubtreesWithSumXUtil(root->right,x); if(l+r+root->data==x) count++; if(ptr!=root) return l+root->data+r; return count; } // Driver codeint main(){ /* binary tree creation 5 / \\ -10 3 / \\ / \\ 9 8 -4 7 */ Node* root = getNode(5); root->left = getNode(-10); root->right = getNode(3); root->left->left = getNode(9); root->left->right = getNode(8); root->right->left = getNode(-4); root->right->right = getNode(7); int x = 7; cout << \"Count = \" << countSubtreesWithSumXUtil(root, x); return 0;}// This code is contributed by Sadik Ali", "e": 38894, "s": 37506, "text": null }, { "code": "// Java program to find if// there is a subtree with// given sumimport java.io.*; // Node class to create new nodeclass Node{ int data; Node left; Node right; Node(int data) { this.data = data; }} class GFG{ static int count = 0; static Node ptr; // Utility function to count subtrees that // sum up to a given value x int countSubtreesWithSumXUtil(Node root, int x) { int l = 0, r = 0; if(root == null) return 0; l += countSubtreesWithSumXUtil(root.left, x); r += countSubtreesWithSumXUtil(root.right, x); if(l + r + root.data == x) count++; if(ptr != root) return l + root.data + r; return count; } // Driver Code public static void main(String[] args) { /* binary tree creation 5 / \\ -10 3 / \\ / \\ 9 8 -4 7 */ Node root = new Node(5); root.left = new Node(-10); root.right = new Node(3); root.left.left = new Node(9); root.left.right = new Node(8); root.right.left = new Node(-4); root.right.right = new Node(7); int x = 7; ptr = root; // assigning global value of ptr System.out.println(\"Count = \" + new GFG().countSubtreesWithSumXUtil(root, x)); }} // This code is submitted by Devarshi_Singh", "e": 40242, "s": 38894, "text": null }, { "code": "# Python3 program to find if there is# a subtree with given sum # Structure of a node of binary treeclass Node: def __init__(self, data): self.data = data self.left = None self.right = None # Function to get a new nodedef getNode(data): # Allocate space newNode = Node(data) return newNode count = 0ptr = None # Utility function to count subtrees that# sum up to a given value xdef countSubtreesWithSumXUtil(root, x): global count, ptr l = 0 r = 0 if (root == None): return 0 l += countSubtreesWithSumXUtil(root.left, x) r += countSubtreesWithSumXUtil(root.right, x) if (l + r + root.data == x): count += 1 if (ptr != root): return l + root.data + r return count # Driver codeif __name__=='__main__': ''' binary tree creation 5 / \\ -10 3 / \\ / \\ 9 8 -4 7 ''' root = getNode(5) root.left = getNode(-10) root.right = getNode(3) root.left.left = getNode(9) root.left.right = getNode(8) root.right.left = getNode(-4) root.right.right = getNode(7) x = 7 ptr = root print(\"Count = \" + str(countSubtreesWithSumXUtil( root, x))) # This code is contributed by pratham76", "e": 41551, "s": 40242, "text": null }, { "code": "// C# program to find if// there is a subtree with// given sumusing System; // Node class to// create new nodepublic class Node{ public int data; public Node left; public Node right; public Node(int data) { this.data = data; }} class GFG{ static int count = 0;static Node ptr; // Utility function to count subtrees// that sum up to a given value xint countSubtreesWithSumXUtil(Node root, int x){ int l = 0, r = 0; if(root == null) return 0; l += countSubtreesWithSumXUtil(root.left, x); r += countSubtreesWithSumXUtil(root.right, x); if(l + r + root.data == x) count++; if(ptr != root) return l + root.data + r; return count;} // Driver Codepublic static void Main(string[] args){ /* binary tree creation 5 / \\ -10 3 / \\ / \\ 9 8 -4 7 */ Node root = new Node(5); root.left = new Node(-10); root.right = new Node(3); root.left.left = new Node(9); root.left.right = new Node(8); root.right.left = new Node(-4); root.right.right = new Node(7); int x = 7; // Assigning global value of ptr ptr = root; Console.Write(\"Count = \" + new GFG().countSubtreesWithSumXUtil(root, x));}} // This code is contributed by rutvik_56", "e": 42781, "s": 41551, "text": null }, { "code": "<script> // JavaScript program to find if // there is a subtree with // given sum class Node { constructor(data) { this.left = null; this.right = null; this.data = data; } } let count = 0; let ptr; // Utility function to count subtrees that // sum up to a given value x function countSubtreesWithSumXUtil(root, x) { let l = 0, r = 0; if(root == null) return 0; l += countSubtreesWithSumXUtil(root.left, x); r += countSubtreesWithSumXUtil(root.right, x); if(l + r + root.data == x) count++; if(ptr != root) return l + root.data + r; return count; } /* binary tree creation 5 / \\ -10 3 / \\ / \\ 9 8 -4 7 */ let root = new Node(5); root.left = new Node(-10); root.right = new Node(3); root.left.left = new Node(9); root.left.right = new Node(8); root.right.left = new Node(-4); root.right.right = new Node(7); let x = 7; ptr = root; // assigning global value of ptr document.write(\"Count = \" + countSubtreesWithSumXUtil(root, x)); </script>", "e": 43962, "s": 42781, "text": null }, { "code": null, "e": 43971, "s": 43962, "text": "Output: " }, { "code": null, "e": 43981, "s": 43971, "text": "Count = 2" }, { "code": null, "e": 44004, "s": 43981, "text": "Time Complexity: O(n)." }, { "code": null, "e": 44015, "s": 44004, "text": "andrew1234" }, { "code": null, "e": 44027, "s": 44015, "text": "shrikanth13" }, { "code": null, "e": 44043, "s": 44027, "text": "PranchalKatiyar" }, { "code": null, "e": 44053, "s": 44043, "text": "chsadik99" }, { "code": null, "e": 44068, "s": 44053, "text": "Devarshi_Singh" }, { "code": null, "e": 44078, "s": 44068, "text": "rutvik_56" }, { "code": null, "e": 44088, "s": 44078, "text": "pratham76" }, { "code": null, "e": 44097, "s": 44088, "text": "mukesh07" }, { "code": null, "e": 44108, "s": 44097, "text": "decode2207" }, { "code": null, "e": 44125, "s": 44108, "text": "arorakashish0911" }, { "code": null, "e": 44135, "s": 44125, "text": "Microsoft" }, { "code": null, "e": 44145, "s": 44135, "text": "Recursion" }, { "code": null, "e": 44150, "s": 44145, "text": "Tree" }, { "code": null, "e": 44160, "s": 44150, "text": "Microsoft" }, { "code": null, "e": 44170, "s": 44160, "text": "Recursion" }, { "code": null, "e": 44175, "s": 44170, "text": "Tree" }, { "code": null, "e": 44273, "s": 44175, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44282, "s": 44273, "text": "Comments" }, { "code": null, "e": 44295, "s": 44282, "text": "Old Comments" }, { "code": null, "e": 44368, "s": 44295, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 44396, "s": 44368, "text": "Backtracking | Introduction" }, { "code": null, "e": 44439, "s": 44396, "text": "Recursive Practice Problems with Solutions" }, { "code": null, "e": 44485, "s": 44439, "text": "Write a program to reverse digits of a number" }, { "code": null, "e": 44505, "s": 44485, "text": "Recursive Functions" }, { "code": null, "e": 44555, "s": 44505, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 44590, "s": 44555, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 44624, "s": 44590, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 44653, "s": 44624, "text": "AVL Tree | Set 1 (Insertion)" } ]
JavaScript | Auto Complete / Suggestion feature - GeeksforGeeks
07 Feb, 2022 There are many ways to make an autocomplete feature in javascript. We will be targeting two of them. One using Pure Javascript and other by using Framework like Jquery. Prerequisites: Html Javascript JQuery Basics 1) Using Pure Javascript (No frameworks): This method shows the results faster than the method of using frameworks.Important functions: getElementsByTagName: Used to get elements by their class or id from html. createElement(“type”): create element creates an element of the passed type appendChild(node): Appends the passed node at the end of attached parent. Code #1: HTML <!DOCTYPE html><html><head> <title>Auto complete using Pure Javascript</title></head><body><script type="text/javascript"> var tags = [ "Delhi", "Ahemdabad", "Punjab", "Uttar Pradesh", "Himachal Pradesh", "Karnatka", "Kerela", "Maharashtra", "Gujrat", "Rajasthan", "Bihar", "Tamil Nadu", "Haryana" ]; /*list of available options*/ var n= tags.length; //length of datalist tags function ac(value) { document.getElementById('datalist').innerHTML = ''; //setting datalist empty at the start of function //if we skip this step, same name will be repeated l=value.length; //input query length for (var i = 0; i<n; i++) { if(((tags[i].toLowerCase()).indexOf(value.toLowerCase()))>-1) { //comparing if input string is existing in tags[i] string var node = document.createElement("option"); var val = document.createTextNode(tags[i]); node.appendChild(val); document.getElementById("datalist").appendChild(node); //creating and appending new elements in data list } } } </script> <input type="text" list="datalist" onkeyup="ac(this.value)"><!-- On keyup calls the function everytime a key is released --><datalist id="datalist"> <option value="Delhi"></option><option value="Ahemdabad"></option><option value="Punjab"></option><option value="Uttar Pradesh"></option><option value="Himachal Pradesh"></option><option value="Karnatka"></option><option value="Kerela"></option><option value="Maharashtra"></option><option value="Gujrat"></option><option value="Rajasthan"></option><option value="Bihar"></option><option value="Tamil Nadu"></option><option value="Haryana"></option> <!-- This data list will be edited through javascript --></datalist></body></html> Output: At first output will be like below- And when B is put inside of the box then output becomes like below- 2) USING JQUERY jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML. JQuery has an inbuilt autocomplete function which takes id and a list of available tags. Code #2: HTML <!doctype html><html lang="en"><head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Autocomplete using Jquery</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { var tags = [ "Delhi", "Ahemdabad", "Punjab", "Uttar Pradesh", "Himachal Pradesh", "Karnatka", "Kerela", "Maharashtra", "Gujrat", "Rajasthan", "Bihar", "Tamil Nadu", "Haryana" /* Making a list of available tags */ ]; $( "#tags" ).autocomplete({ source: tags /* #the ags is the id of the input elementsource: tags is the list of available tags*/ }); } ); </script></head><body> <div class="ui-widget"> <H3>Enter an alphabet to get suggestion:</H3> <input id="tags"></div> </body></html> Type a letter to see recommendations and click to complete the text automatically. Output: At first, output will be like below- And when D is put inside of the box then output becomes like below- Reference: http://api.jqueryui.com/autocomplete/ avtarkumar719 varshagumber28 JavaScript-Misc JavaScript JQuery Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to change the background color after clicking the button in JavaScript ? How to fetch data from JSON file and display in HTML table using jQuery ?
[ { "code": null, "e": 25916, "s": 25888, "text": "\n07 Feb, 2022" }, { "code": null, "e": 26101, "s": 25916, "text": "There are many ways to make an autocomplete feature in javascript. We will be targeting two of them. One using Pure Javascript and other by using Framework like Jquery. Prerequisites: " }, { "code": null, "e": 26106, "s": 26101, "text": "Html" }, { "code": null, "e": 26117, "s": 26106, "text": "Javascript" }, { "code": null, "e": 26131, "s": 26117, "text": "JQuery Basics" }, { "code": null, "e": 26503, "s": 26131, "text": "1) Using Pure Javascript (No frameworks): This method shows the results faster than the method of using frameworks.Important functions: getElementsByTagName: Used to get elements by their class or id from html. createElement(“type”): create element creates an element of the passed type appendChild(node): Appends the passed node at the end of attached parent. Code #1: " }, { "code": null, "e": 26508, "s": 26503, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head> <title>Auto complete using Pure Javascript</title></head><body><script type=\"text/javascript\"> var tags = [ \"Delhi\", \"Ahemdabad\", \"Punjab\", \"Uttar Pradesh\", \"Himachal Pradesh\", \"Karnatka\", \"Kerela\", \"Maharashtra\", \"Gujrat\", \"Rajasthan\", \"Bihar\", \"Tamil Nadu\", \"Haryana\" ]; /*list of available options*/ var n= tags.length; //length of datalist tags function ac(value) { document.getElementById('datalist').innerHTML = ''; //setting datalist empty at the start of function //if we skip this step, same name will be repeated l=value.length; //input query length for (var i = 0; i<n; i++) { if(((tags[i].toLowerCase()).indexOf(value.toLowerCase()))>-1) { //comparing if input string is existing in tags[i] string var node = document.createElement(\"option\"); var val = document.createTextNode(tags[i]); node.appendChild(val); document.getElementById(\"datalist\").appendChild(node); //creating and appending new elements in data list } } } </script> <input type=\"text\" list=\"datalist\" onkeyup=\"ac(this.value)\"><!-- On keyup calls the function everytime a key is released --><datalist id=\"datalist\"> <option value=\"Delhi\"></option><option value=\"Ahemdabad\"></option><option value=\"Punjab\"></option><option value=\"Uttar Pradesh\"></option><option value=\"Himachal Pradesh\"></option><option value=\"Karnatka\"></option><option value=\"Kerela\"></option><option value=\"Maharashtra\"></option><option value=\"Gujrat\"></option><option value=\"Rajasthan\"></option><option value=\"Bihar\"></option><option value=\"Tamil Nadu\"></option><option value=\"Haryana\"></option> <!-- This data list will be edited through javascript --></datalist></body></html>", "e": 28411, "s": 26508, "text": null }, { "code": null, "e": 28457, "s": 28411, "text": "Output: At first output will be like below- " }, { "code": null, "e": 28527, "s": 28457, "text": "And when B is put inside of the box then output becomes like below- " }, { "code": null, "e": 28745, "s": 28527, "text": "2) USING JQUERY jQuery is a cross-platform JavaScript library designed to simplify the client-side scripting of HTML. JQuery has an inbuilt autocomplete function which takes id and a list of available tags. Code #2: " }, { "code": null, "e": 28750, "s": 28745, "text": "HTML" }, { "code": "<!doctype html><html lang=\"en\"><head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\"> <title>Autocomplete using Jquery</title> <link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\"> <link rel=\"stylesheet\" href=\"/resources/demos/style.css\"> <script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script> <script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script> <script> $( function() { var tags = [ \"Delhi\", \"Ahemdabad\", \"Punjab\", \"Uttar Pradesh\", \"Himachal Pradesh\", \"Karnatka\", \"Kerela\", \"Maharashtra\", \"Gujrat\", \"Rajasthan\", \"Bihar\", \"Tamil Nadu\", \"Haryana\" /* Making a list of available tags */ ]; $( \"#tags\" ).autocomplete({ source: tags /* #the ags is the id of the input elementsource: tags is the list of available tags*/ }); } ); </script></head><body> <div class=\"ui-widget\"> <H3>Enter an alphabet to get suggestion:</H3> <input id=\"tags\"></div> </body></html>", "e": 29791, "s": 28750, "text": null }, { "code": null, "e": 29921, "s": 29791, "text": "Type a letter to see recommendations and click to complete the text automatically. Output: At first, output will be like below- " }, { "code": null, "e": 29991, "s": 29921, "text": "And when D is put inside of the box then output becomes like below- " }, { "code": null, "e": 30041, "s": 29991, "text": "Reference: http://api.jqueryui.com/autocomplete/ " }, { "code": null, "e": 30055, "s": 30041, "text": "avtarkumar719" }, { "code": null, "e": 30070, "s": 30055, "text": "varshagumber28" }, { "code": null, "e": 30086, "s": 30070, "text": "JavaScript-Misc" }, { "code": null, "e": 30097, "s": 30086, "text": "JavaScript" }, { "code": null, "e": 30104, "s": 30097, "text": "JQuery" }, { "code": null, "e": 30202, "s": 30104, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30242, "s": 30202, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 30287, "s": 30242, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 30348, "s": 30287, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 30420, "s": 30348, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 30461, "s": 30420, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 30507, "s": 30461, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 30536, "s": 30507, "text": "Form validation using jQuery" }, { "code": null, "e": 30599, "s": 30536, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 30676, "s": 30599, "text": "How to change the background color after clicking the button in JavaScript ?" } ]
Merging tables using SQL. This article discusses about merging... | by KSV Muralidhar | Towards Data Science
In practice, it is very rare to have an SQL query involving a single table. We may need to merge multiple tables by rows (records) or columns (fields) to get the desired result. In this article, we’ll discuss the operators/commands in SQL that enable use to merge tables by rows or columns. Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other). Below is the generic syntax of SQL joins. SELECT * FROM table_1 JOIN table_2 USING (id); In the above syntax, table_1 and table_2 are the two tables with the key column (matching column in both the tables), id. We use the keyword USING only when the key column has the same name in both the tables. Otherwise, we need to explicitly mention the key columns of both the tables as shown below. SELECT * FROM table_1 t1 JOIN table_2 t2 ON t1.t1_id = t2.t2_id; In the above syntax, t1 is an alias of table_1 and t2 is of table_2. When the names of the key columns are not same in both the tables, we need to match them using the ON keyword as shown above. We’ll now discuss a few important joins in SQL. Inner join merges two tables by columns and returns only the matching records (based on the specified columns) in both the tables. In the below query result, we can see that only the records with common id in both left_table and right_table are returned. SELECT * FROM left_table INNER JOIN right_table USING (id); Or SELECT * FROM left_table l INNER JOIN right_table r ON l.id = r.id; Left join merges two tables by columns and returns all the records in the left table but only the matching records (based on the specified columns) from the right table. In the below query result, we can see the records with common id in both the tables along with all the records of the left_table. Records in the right_table with no matching id in the left_table have NULL. SELECT * FROM left_table LEFT JOIN right_table USING (id); Or SELECT * FROM left_table l LEFT JOIN right_table r ON l.id = r.id; Right join merges two tables by columns and returns all the records in the right table but only the matching records (based on the specified columns) from the left table. In the below query result, we can see the records with common id in both the tables along with all the records of the right_table. Records in the left_table with no matching id in the right_table have NULL. SELECT * FROM left_table RIGHT JOIN right_table USING (id); Or SELECT * FROM left_table l RIGHT JOIN right_table r ON l.id = r.id; Full join can be considered as a combination of left and right joins. Full join merges two tables by columns and returns all the records in both the left and right tables. In the below query result, we can see that all the records of both the tables are returned. Records with no matching id in the other table have NULL. SELECT * FROM left_table FULL JOIN right_table USING (id); Or SELECT * FROM left_table l FULL JOIN right_table r ON l.id = r.id; Cross join returns the cartesian product of two tables. Cartesian product of two sets A = {1, 2}, B = {3, 4} is A x B = {(1, 3), (1, 4), (2, 3), (2, 4)}. We need not specify a key column in cross joins. SELECT * FROM left_table CROSS JOIN right_table Semi join is technically not an SQL join but works like a join. Semi join returns the matching records in the left table based on a key column in the right table. Semi join doesn’t include the columns of the right table in the query result. In the below example, we want to return the records from the left_table with matching id in the right_table. In other words, we want the records in the left_table whose id is present in the right_table. SELECT * FROM left_table WHERE id IN ( SELECT id FROM right_table ) Anti join is also technically not an SQL join but works like a join. Anti join returns the non-matching records in the left table based on a key column in the right table. Anti join also doesn’t include the columns of the right table in the query result. In the below example, we want to return the records from the left_table whose id doesn’t match with the id of the right_table. In other words, we want the records in the left_table whose id is not present in the right_table. SELECT * FROM left_table WHERE id NOT IN ( SELECT id FROM right_table ) Self join enables us to join a table with itself. In the below query, we need to find the records with the same left value. For this, we have joined the table with itself and filtered the records with same left value but different id. SELECT * FROM left_table l1, left_table l2 WHERE l1.left = l2.left AND l1.id <> l2.id ORDER BY l1.left Union merges two tables by rows, provided the data types of the columns of one table matches with that of the other. We cannot merge a table having column data types as integer and text with a table having column data types as text and integer. However, we can merge two tables even if the column names of one table doesn’t match with that of the other. Union returns only the unique records of both the tables. ( SELECT * FROM left_table)UNION( SELECT * FROM right_table) Similar to Union, Union All also merges tables by rows. Unlike Union, Union All retains the duplicate records of both the tables. In the below query result, we have merged the id of left_table and right_table. We can see a few duplicates in the result. ( SELECT id FROM left_table)UNION ALL( SELECT id FROM right_table) Intersect returns the common records of both the tables. In the below query result, we can see the common ids of left_table and right_table. ( SELECT id FROM left_table)INTERSECT( SELECT id FROM right_table) Except returns the records from the first table (left table) which are not present in the second table (right table). In the below query result, we can see the ids of left_table which aren’t present in the right_table. We’ll use the dvd_rental database downloaded from here and restore it. Below is the documentation to restore a database in PostgreSQL. www.pgadmin.org In this example, we need to find the top 5 customers who rented the most. For this, we’ll Join the customer and rental tables using customer_id.Count the customers (as rental_count) by grouping customer_id.Sort the result according to rental_count in descending order.Limit the results to first 5 records. Join the customer and rental tables using customer_id. Count the customers (as rental_count) by grouping customer_id. Sort the result according to rental_count in descending order. Limit the results to first 5 records. SELECT c.customer_id, c.first_name, c.last_name, COUNT(c.customer_id) AS rental_count FROM customer c INNER JOIN rental r USING (customer_id) GROUP BY customer_id ORDER BY COUNT(c.customer_id) DESC LIMIT 5; In this example, we’ll use common table expressions (CTE). With CTEs, we can create temporary table that exist for a particular query. Below is the official Postgres documentation on CTEs. www.postgresql.org In this example, we need to find out top and bottom 5 customers who generated the most revenue. For this, we’ll 1. Create a CTE named revenue_per_customer by Joining the customer and rental tables using customer_id. Joining the resultant table with payment table using rental_id. Computing the total amount paid by customers for each rental transaction (as total_amount) grouping by customer_id. Finally, selecting the customer_id, first_name, last_name and total_amount. 2. Select top 5 customers by revenue from the above CTE by Sorting total_amount in the revenue_per_customer (CTE result) in descending order. Limiting the result to first 5 records. Adding a comment specifying the records as ‘Top 5’. 3. Select bottom 5 customers by revenue from the above CTE by Sorting total_amount in the revenue_per_customer (CTE result) in ascending order. Limiting the result to first 5 records. Adding a comment specifying the records as ‘Bottom 5’. 4. Merging the above two results using UNION. WITH revenue_per_customer AS (SELECT c.customer_id, c.first_name, c.last_name, SUM(p.amount) AS "total_amount" FROM customer c INNER JOIN rental r USING (customer_id) INNER JOIN payment p USING (rental_id) GROUP BY c.customer_id)(SELECT *, 'Top 5' AS comment FROM revenue_per_customer ORDER BY total_amount DESC LIMIT 5)UNION(SELECT *, 'Bottom 5' AS comment FROM revenue_per_customer ORDER BY total_amount ASC LIMIT 5)ORDER BY comment DESC, total_amount DESC; We can also get the above query result using window functions. Below is the official Postgres documentation on window functions. www.postgresql.org To find out the top and bottom 5 customers who generated the most revenue using window functions, we’ll 1. Create a CTE named total_amt_rank by Joining the customer and rental tables using customer_id. Joining the resultant table with payment table using rental_id. Computing the total amount paid by customers for each rental transaction (as total_amount) grouping by customer_id. Finally, selecting the customer_id, first_name, last_name, total_amount and rank of total_amount (as total_amount_rank) by sorting it in descending order. This gives rank 1 to the highest amount and so on. 2. Select top 5 customers by revenue by selecting the customers whose total_amount_rank is BETWEEN 1 and 5 from the above CTE. 3. Select bottom 5 customers by revenue from the above CTE by Sorting total_amount_rank in the total_amt_rank (CTE result) in descending order. Limiting the result to first 5 records. 4. Merging the above two results using UNION. WITH total_amt_rank AS ( SELECT c.customer_id, c.first_name, c.last_name, SUM(p.amount) AS "total_amount", RANK() OVER (ORDER BY SUM(p.amount) DESC) AS total_amount_rank FROM customer c INNER JOIN rental r USING (customer_id) INNER JOIN payment p USING (rental_id) GROUP BY c.customer_id )( SELECT * FROM total_amt_rank WHERE total_amount_rank BETWEEN 1 AND 5) UNION ( SELECT * FROM total_amt_rank ORDER BY total_amount_rank DESC LIMIT 5) ORDER BY total_amount_rank; In this example, we need to find the top 5 countries with the highest rentals. For this, we’ll Join the country and city tables using country_id.Join the resultant table with address table using city_id.Join the resultant table with customer table using address_id.Join the resultant table with rental table using customer_id.Count the country_id (as rental_count) by grouping country_id. We may also use rental_id to get rental_count.Sort the result by rental_count in descending order.Limit the results to 5 records. Join the country and city tables using country_id. Join the resultant table with address table using city_id. Join the resultant table with customer table using address_id. Join the resultant table with rental table using customer_id. Count the country_id (as rental_count) by grouping country_id. We may also use rental_id to get rental_count. Sort the result by rental_count in descending order. Limit the results to 5 records. SELECT co.country_id, co.country, COUNT(co.country_id) AS rental_count FROM country co INNER JOIN city ci USING (country_id) INNER JOIN address a USING (city_id) INNER JOIN customer cu USING (address_id) INNER JOIN rental r USING (customer_id) GROUP BY co.country_id ORDER BY COUNT(co.country_id) DESC LIMIT 5; There are a few addresses and cities with no customers. Using inner join omits such records. In the below query, we’ll look at how the result will include addresses without customers on using left join. There are a few cities and addresses without any customers (these may be store addresses). Using inner joins would have omitted them from the results as there are no matching entries in the other table. For example, a city named London in Canada has no matching city_id in the address table. Using inner join would have omitted London in Canada from the result. Similarly, four addresses in Canada and Australia have no matching address_id in the customer table. SELECT co.country, ci.city, a.address, cu.customer_id FROM country co LEFT JOIN city ci USING (country_id) LEFT JOIN address a USING (city_id) LEFT JOIN customer cu USING (address_id) WHERE cu.address_id IS NULL; In this example, we’ll find the countries with no customers by 1. Creating a subquery to find the countries with at least one customer by Joining the country table with city table using country_id. Joining the remainder table with address table using city_id. Joining the remainder table with customer table using address_id. 2. Selecting country from country table where country_id is not present in the country_id of the above subquery. SELECT country FROM country WHERE country_id NOT IN ( SELECT co.country_id FROM country co INNER JOIN city ci USING (country_id) INNER JOIN address a USING (city_id) INNER JOIN customer USING (address_id) ); In the above example, we saw that Australia has no customers. In this example, we’ll see are there any stores in Australia by Joining the country table with city table using country_id.Joining the resultant table with address table using city_id.Joining the resultant table with store table using address_id.Selecting records where store_id IS NOT NULL in Australia. Joining the country table with city table using country_id. Joining the resultant table with address table using city_id. Joining the resultant table with store table using address_id. Selecting records where store_id IS NOT NULL in Australia. Left join ensures that countries with no cities and cities with no stores are also included in the query result. SELECT st.store_id, co.country, ad.address FROM country co LEFT JOIN city ci USING (country_id) LEFT JOIN address ad USING (city_id) LEFT JOIN store st USING (address_id) WHERE (st.store_id IS NOT NULL) AND (co.country = 'Australia'); There is one store in Australia. In fact, there are just two stores in the whole database. We’ll view them using the below query. SELECT * FROM store; In this example, we’ll see if there are any languages with no films by Joining the language table with film table using language_id. The left join ensures languages without any films are also includes.Filtering records where film_id IS NULL. Joining the language table with film table using language_id. The left join ensures languages without any films are also includes. Filtering records where film_id IS NULL. SELECT * FROM language l LEFT JOIN film f USING (language_id) WHERE f.film_id IS NULL; We see a few languages with no films in the database. We’ll make sure that it’s not an error by selecting the films with language_id in (2,3,4,5,6) from the film table. The query result should return no records. SELECT * FROM film WHERE language_id IN (2,3,4,5,6); In this example, we’ll find the number of rentals per film category in India by joining the required tables as discussed in the earlier examples and Grouping by country and category and filtering records from India and counting the film category name (as film_category_count).Ordering the result by country in ascending order and film_category_count in descending order. Grouping by country and category and filtering records from India and counting the film category name (as film_category_count). Ordering the result by country in ascending order and film_category_count in descending order. SELECT co.country, cat.name AS film_category, COUNT(cat.name) AS film_category_count FROM country co INNER JOIN city ci USING (country_id) INNER JOIN address ad USING (city_id) INNER JOIN customer cu USING (address_id) INNER JOIN rental re USING (customer_id) INNER JOIN inventory inv USING (inventory_id) INNER JOIN film fi USING (film_id) INNER JOIN film_category fc USING (film_id) INNER JOIN category cat USING (category_id) /* Using WHERE co.country = 'India' here, instead of HAVING co.country = 'India' reduces the query execution time. */ GROUP BY (co.country, cat.name) HAVING co.country = 'India' ORDER BY co.country ASC, COUNT(cat.name) DESC; In this example, we‘ll find the films with a single actor by Joining the film table with film_actor table using film_id.Grouping by film_id and counting the number of actors (as actor_count).Filtering records where actor_count is 1. Joining the film table with film_actor table using film_id. Grouping by film_id and counting the number of actors (as actor_count). Filtering records where actor_count is 1. SELECT f.film_id, f.title, COUNT(fa.actor_id) AS actor_count FROM film f INNER JOIN film_actor fa USING (film_id) GROUP BY f.film_id HAVING COUNT(fa.actor_id) = 1; In this example, we’ll find the number of films of an actor by film category by Creating a CTE named actor_cat_cnt that returns the number of films for each actor_id and category_id.Joining the above CTE with category table using category_id.Joining the resultant table with actor table using actor_id.Sort actor name (concatenation of first_name and last_name) in ascending order and film_count in descending order. Creating a CTE named actor_cat_cnt that returns the number of films for each actor_id and category_id. Joining the above CTE with category table using category_id. Joining the resultant table with actor table using actor_id. Sort actor name (concatenation of first_name and last_name) in ascending order and film_count in descending order. WITH actor_cat_cnt AS ( SELECT fa.actor_id, fc.category_id, COUNT(f.film_id) AS film_count FROM film_actor fa INNER JOIN film f USING (film_id) INNER JOIN film_category fc USING (film_id) GROUP BY fa.actor_id, fc.category_id )SELECT CONCAT(ac.first_name, ' ', ac.last_name) AS actor, ca.name AS category, film_count FROM actor_cat_cnt INNER JOIN category ca USING (category_id) INNER JOIN actor ac USING (actor_id) ORDER BY CONCAT(ac.first_name, ' ', ac.last_name) ASC, film_count DESC; In the above example, we found the number of films of an actor by film category. In this example, we’ll find the popular categories of an actor (i.e. the categories in which an actor has the most films) by Creating a CTE named actor_cat_cnt that returns the number of films for each actor_id and category_id and rank the categories of each actor by the count of films in descending order (as cat_rank).Joining the above CTE with category table using category_id.Joining the resultant table with actor table using actor_id.Filtering the records with cat_rank = 1.Sort actor name (concatenation of first_name and last_name) in ascending order and film_count in descending order. Creating a CTE named actor_cat_cnt that returns the number of films for each actor_id and category_id and rank the categories of each actor by the count of films in descending order (as cat_rank). Joining the above CTE with category table using category_id. Joining the resultant table with actor table using actor_id. Filtering the records with cat_rank = 1. Sort actor name (concatenation of first_name and last_name) in ascending order and film_count in descending order. WITH actor_cat_cnt AS ( SELECT fa.actor_id, fc.category_id, COUNT(f.film_id) AS film_count, RANK() OVER (PARTITION BY fa.actor_id ORDER BY COUNT(f.film_id) DESC) AS cat_rank FROM film_actor fa INNER JOIN film f USING (film_id) INNER JOIN film_category fc USING (film_id) GROUP BY fa.actor_id, fc.category_id )SELECT CONCAT(ac.first_name, ' ', ac.last_name) AS actor, ca.name AS category, film_count FROM actor_cat_cnt INNER JOIN category ca USING (category_id) INNER JOIN actor ac USING (actor_id) WHERE cat_rank = 1 ORDER BY CONCAT(ac.first_name, ' ', ac.last_name) ASC, film_count DESC; This brings this article to an end. We’ve discussed ways of merging tables by rows or columns using SQL along with a few examples using the dvd_rental database. These are the fundamental concepts that are used in almost every query we write in SQL. We may not frequently use a few of them in practice, but knowing them is necessary.
[ { "code": null, "e": 463, "s": 172, "text": "In practice, it is very rare to have an SQL query involving a single table. We may need to merge multiple tables by rows (records) or columns (fields) to get the desired result. In this article, we’ll discuss the operators/commands in SQL that enable use to merge tables by rows or columns." }, { "code": null, "e": 694, "s": 463, "text": "Multiple tables can be merged by columns in SQL using joins. Joins merge two tables based on the specified columns (generally, the primary key of one table and a foreign key of the other). Below is the generic syntax of SQL joins." }, { "code": null, "e": 748, "s": 694, "text": "SELECT * FROM table_1 JOIN table_2 USING (id);" }, { "code": null, "e": 1050, "s": 748, "text": "In the above syntax, table_1 and table_2 are the two tables with the key column (matching column in both the tables), id. We use the keyword USING only when the key column has the same name in both the tables. Otherwise, we need to explicitly mention the key columns of both the tables as shown below." }, { "code": null, "e": 1122, "s": 1050, "text": "SELECT * FROM table_1 t1 JOIN table_2 t2 ON t1.t1_id = t2.t2_id;" }, { "code": null, "e": 1365, "s": 1122, "text": "In the above syntax, t1 is an alias of table_1 and t2 is of table_2. When the names of the key columns are not same in both the tables, we need to match them using the ON keyword as shown above. We’ll now discuss a few important joins in SQL." }, { "code": null, "e": 1620, "s": 1365, "text": "Inner join merges two tables by columns and returns only the matching records (based on the specified columns) in both the tables. In the below query result, we can see that only the records with common id in both left_table and right_table are returned." }, { "code": null, "e": 1687, "s": 1620, "text": "SELECT * FROM left_table INNER JOIN right_table USING (id);" }, { "code": null, "e": 1690, "s": 1687, "text": "Or" }, { "code": null, "e": 1765, "s": 1690, "text": "SELECT * FROM left_table l INNER JOIN right_table r ON l.id = r.id;" }, { "code": null, "e": 2141, "s": 1765, "text": "Left join merges two tables by columns and returns all the records in the left table but only the matching records (based on the specified columns) from the right table. In the below query result, we can see the records with common id in both the tables along with all the records of the left_table. Records in the right_table with no matching id in the left_table have NULL." }, { "code": null, "e": 2207, "s": 2141, "text": "SELECT * FROM left_table LEFT JOIN right_table USING (id);" }, { "code": null, "e": 2210, "s": 2207, "text": "Or" }, { "code": null, "e": 2284, "s": 2210, "text": "SELECT * FROM left_table l LEFT JOIN right_table r ON l.id = r.id;" }, { "code": null, "e": 2662, "s": 2284, "text": "Right join merges two tables by columns and returns all the records in the right table but only the matching records (based on the specified columns) from the left table. In the below query result, we can see the records with common id in both the tables along with all the records of the right_table. Records in the left_table with no matching id in the right_table have NULL." }, { "code": null, "e": 2729, "s": 2662, "text": "SELECT * FROM left_table RIGHT JOIN right_table USING (id);" }, { "code": null, "e": 2732, "s": 2729, "text": "Or" }, { "code": null, "e": 2807, "s": 2732, "text": "SELECT * FROM left_table l RIGHT JOIN right_table r ON l.id = r.id;" }, { "code": null, "e": 3129, "s": 2807, "text": "Full join can be considered as a combination of left and right joins. Full join merges two tables by columns and returns all the records in both the left and right tables. In the below query result, we can see that all the records of both the tables are returned. Records with no matching id in the other table have NULL." }, { "code": null, "e": 3195, "s": 3129, "text": "SELECT * FROM left_table FULL JOIN right_table USING (id);" }, { "code": null, "e": 3198, "s": 3195, "text": "Or" }, { "code": null, "e": 3272, "s": 3198, "text": "SELECT * FROM left_table l FULL JOIN right_table r ON l.id = r.id;" }, { "code": null, "e": 3475, "s": 3272, "text": "Cross join returns the cartesian product of two tables. Cartesian product of two sets A = {1, 2}, B = {3, 4} is A x B = {(1, 3), (1, 4), (2, 3), (2, 4)}. We need not specify a key column in cross joins." }, { "code": null, "e": 3527, "s": 3475, "text": "SELECT * FROM left_table CROSS JOIN right_table" }, { "code": null, "e": 3971, "s": 3527, "text": "Semi join is technically not an SQL join but works like a join. Semi join returns the matching records in the left table based on a key column in the right table. Semi join doesn’t include the columns of the right table in the query result. In the below example, we want to return the records from the left_table with matching id in the right_table. In other words, we want the records in the left_table whose id is present in the right_table." }, { "code": null, "e": 4054, "s": 3971, "text": "SELECT * FROM left_table WHERE id IN ( SELECT id FROM right_table )" }, { "code": null, "e": 4534, "s": 4054, "text": "Anti join is also technically not an SQL join but works like a join. Anti join returns the non-matching records in the left table based on a key column in the right table. Anti join also doesn’t include the columns of the right table in the query result. In the below example, we want to return the records from the left_table whose id doesn’t match with the id of the right_table. In other words, we want the records in the left_table whose id is not present in the right_table." }, { "code": null, "e": 4630, "s": 4534, "text": "SELECT * FROM left_table WHERE id NOT IN ( SELECT id FROM right_table )" }, { "code": null, "e": 4865, "s": 4630, "text": "Self join enables us to join a table with itself. In the below query, we need to find the records with the same left value. For this, we have joined the table with itself and filtered the records with same left value but different id." }, { "code": null, "e": 4980, "s": 4865, "text": "SELECT * FROM left_table l1, left_table l2 WHERE l1.left = l2.left AND l1.id <> l2.id ORDER BY l1.left" }, { "code": null, "e": 5392, "s": 4980, "text": "Union merges two tables by rows, provided the data types of the columns of one table matches with that of the other. We cannot merge a table having column data types as integer and text with a table having column data types as text and integer. However, we can merge two tables even if the column names of one table doesn’t match with that of the other. Union returns only the unique records of both the tables." }, { "code": null, "e": 5463, "s": 5392, "text": "( SELECT * FROM left_table)UNION( SELECT * FROM right_table)" }, { "code": null, "e": 5716, "s": 5463, "text": "Similar to Union, Union All also merges tables by rows. Unlike Union, Union All retains the duplicate records of both the tables. In the below query result, we have merged the id of left_table and right_table. We can see a few duplicates in the result." }, { "code": null, "e": 5793, "s": 5716, "text": "( SELECT id FROM left_table)UNION ALL( SELECT id FROM right_table)" }, { "code": null, "e": 5934, "s": 5793, "text": "Intersect returns the common records of both the tables. In the below query result, we can see the common ids of left_table and right_table." }, { "code": null, "e": 6011, "s": 5934, "text": "( SELECT id FROM left_table)INTERSECT( SELECT id FROM right_table)" }, { "code": null, "e": 6230, "s": 6011, "text": "Except returns the records from the first table (left table) which are not present in the second table (right table). In the below query result, we can see the ids of left_table which aren’t present in the right_table." }, { "code": null, "e": 6365, "s": 6230, "text": "We’ll use the dvd_rental database downloaded from here and restore it. Below is the documentation to restore a database in PostgreSQL." }, { "code": null, "e": 6381, "s": 6365, "text": "www.pgadmin.org" }, { "code": null, "e": 6471, "s": 6381, "text": "In this example, we need to find the top 5 customers who rented the most. For this, we’ll" }, { "code": null, "e": 6687, "s": 6471, "text": "Join the customer and rental tables using customer_id.Count the customers (as rental_count) by grouping customer_id.Sort the result according to rental_count in descending order.Limit the results to first 5 records." }, { "code": null, "e": 6742, "s": 6687, "text": "Join the customer and rental tables using customer_id." }, { "code": null, "e": 6805, "s": 6742, "text": "Count the customers (as rental_count) by grouping customer_id." }, { "code": null, "e": 6868, "s": 6805, "text": "Sort the result according to rental_count in descending order." }, { "code": null, "e": 6906, "s": 6868, "text": "Limit the results to first 5 records." }, { "code": null, "e": 7134, "s": 6906, "text": "SELECT c.customer_id, c.first_name, c.last_name, COUNT(c.customer_id) AS rental_count FROM customer c INNER JOIN rental r USING (customer_id) GROUP BY customer_id ORDER BY COUNT(c.customer_id) DESC LIMIT 5;" }, { "code": null, "e": 7323, "s": 7134, "text": "In this example, we’ll use common table expressions (CTE). With CTEs, we can create temporary table that exist for a particular query. Below is the official Postgres documentation on CTEs." }, { "code": null, "e": 7342, "s": 7323, "text": "www.postgresql.org" }, { "code": null, "e": 7454, "s": 7342, "text": "In this example, we need to find out top and bottom 5 customers who generated the most revenue. For this, we’ll" }, { "code": null, "e": 7500, "s": 7454, "text": "1. Create a CTE named revenue_per_customer by" }, { "code": null, "e": 7558, "s": 7500, "text": "Joining the customer and rental tables using customer_id." }, { "code": null, "e": 7622, "s": 7558, "text": "Joining the resultant table with payment table using rental_id." }, { "code": null, "e": 7738, "s": 7622, "text": "Computing the total amount paid by customers for each rental transaction (as total_amount) grouping by customer_id." }, { "code": null, "e": 7814, "s": 7738, "text": "Finally, selecting the customer_id, first_name, last_name and total_amount." }, { "code": null, "e": 7873, "s": 7814, "text": "2. Select top 5 customers by revenue from the above CTE by" }, { "code": null, "e": 7956, "s": 7873, "text": "Sorting total_amount in the revenue_per_customer (CTE result) in descending order." }, { "code": null, "e": 7996, "s": 7956, "text": "Limiting the result to first 5 records." }, { "code": null, "e": 8048, "s": 7996, "text": "Adding a comment specifying the records as ‘Top 5’." }, { "code": null, "e": 8110, "s": 8048, "text": "3. Select bottom 5 customers by revenue from the above CTE by" }, { "code": null, "e": 8192, "s": 8110, "text": "Sorting total_amount in the revenue_per_customer (CTE result) in ascending order." }, { "code": null, "e": 8232, "s": 8192, "text": "Limiting the result to first 5 records." }, { "code": null, "e": 8287, "s": 8232, "text": "Adding a comment specifying the records as ‘Bottom 5’." }, { "code": null, "e": 8333, "s": 8287, "text": "4. Merging the above two results using UNION." }, { "code": null, "e": 8834, "s": 8333, "text": "WITH revenue_per_customer AS (SELECT c.customer_id, c.first_name, c.last_name, SUM(p.amount) AS \"total_amount\" FROM customer c INNER JOIN rental r USING (customer_id) INNER JOIN payment p USING (rental_id) GROUP BY c.customer_id)(SELECT *, 'Top 5' AS comment FROM revenue_per_customer ORDER BY total_amount DESC LIMIT 5)UNION(SELECT *, 'Bottom 5' AS comment FROM revenue_per_customer ORDER BY total_amount ASC LIMIT 5)ORDER BY comment DESC, total_amount DESC;" }, { "code": null, "e": 8963, "s": 8834, "text": "We can also get the above query result using window functions. Below is the official Postgres documentation on window functions." }, { "code": null, "e": 8982, "s": 8963, "text": "www.postgresql.org" }, { "code": null, "e": 9086, "s": 8982, "text": "To find out the top and bottom 5 customers who generated the most revenue using window functions, we’ll" }, { "code": null, "e": 9126, "s": 9086, "text": "1. Create a CTE named total_amt_rank by" }, { "code": null, "e": 9184, "s": 9126, "text": "Joining the customer and rental tables using customer_id." }, { "code": null, "e": 9248, "s": 9184, "text": "Joining the resultant table with payment table using rental_id." }, { "code": null, "e": 9364, "s": 9248, "text": "Computing the total amount paid by customers for each rental transaction (as total_amount) grouping by customer_id." }, { "code": null, "e": 9570, "s": 9364, "text": "Finally, selecting the customer_id, first_name, last_name, total_amount and rank of total_amount (as total_amount_rank) by sorting it in descending order. This gives rank 1 to the highest amount and so on." }, { "code": null, "e": 9697, "s": 9570, "text": "2. Select top 5 customers by revenue by selecting the customers whose total_amount_rank is BETWEEN 1 and 5 from the above CTE." }, { "code": null, "e": 9759, "s": 9697, "text": "3. Select bottom 5 customers by revenue from the above CTE by" }, { "code": null, "e": 9841, "s": 9759, "text": "Sorting total_amount_rank in the total_amt_rank (CTE result) in descending order." }, { "code": null, "e": 9881, "s": 9841, "text": "Limiting the result to first 5 records." }, { "code": null, "e": 9927, "s": 9881, "text": "4. Merging the above two results using UNION." }, { "code": null, "e": 10481, "s": 9927, "text": "WITH total_amt_rank AS ( SELECT c.customer_id, c.first_name, c.last_name, SUM(p.amount) AS \"total_amount\", RANK() OVER (ORDER BY SUM(p.amount) DESC) AS total_amount_rank FROM customer c INNER JOIN rental r USING (customer_id) INNER JOIN payment p USING (rental_id) GROUP BY c.customer_id )( SELECT * FROM total_amt_rank WHERE total_amount_rank BETWEEN 1 AND 5) UNION ( SELECT * FROM total_amt_rank ORDER BY total_amount_rank DESC LIMIT 5) ORDER BY total_amount_rank;" }, { "code": null, "e": 10576, "s": 10481, "text": "In this example, we need to find the top 5 countries with the highest rentals. For this, we’ll" }, { "code": null, "e": 11000, "s": 10576, "text": "Join the country and city tables using country_id.Join the resultant table with address table using city_id.Join the resultant table with customer table using address_id.Join the resultant table with rental table using customer_id.Count the country_id (as rental_count) by grouping country_id. We may also use rental_id to get rental_count.Sort the result by rental_count in descending order.Limit the results to 5 records." }, { "code": null, "e": 11051, "s": 11000, "text": "Join the country and city tables using country_id." }, { "code": null, "e": 11110, "s": 11051, "text": "Join the resultant table with address table using city_id." }, { "code": null, "e": 11173, "s": 11110, "text": "Join the resultant table with customer table using address_id." }, { "code": null, "e": 11235, "s": 11173, "text": "Join the resultant table with rental table using customer_id." }, { "code": null, "e": 11345, "s": 11235, "text": "Count the country_id (as rental_count) by grouping country_id. We may also use rental_id to get rental_count." }, { "code": null, "e": 11398, "s": 11345, "text": "Sort the result by rental_count in descending order." }, { "code": null, "e": 11430, "s": 11398, "text": "Limit the results to 5 records." }, { "code": null, "e": 11770, "s": 11430, "text": "SELECT co.country_id, co.country, COUNT(co.country_id) AS rental_count FROM country co INNER JOIN city ci USING (country_id) INNER JOIN address a USING (city_id) INNER JOIN customer cu USING (address_id) INNER JOIN rental r USING (customer_id) GROUP BY co.country_id ORDER BY COUNT(co.country_id) DESC LIMIT 5;" }, { "code": null, "e": 11973, "s": 11770, "text": "There are a few addresses and cities with no customers. Using inner join omits such records. In the below query, we’ll look at how the result will include addresses without customers on using left join." }, { "code": null, "e": 12436, "s": 11973, "text": "There are a few cities and addresses without any customers (these may be store addresses). Using inner joins would have omitted them from the results as there are no matching entries in the other table. For example, a city named London in Canada has no matching city_id in the address table. Using inner join would have omitted London in Canada from the result. Similarly, four addresses in Canada and Australia have no matching address_id in the customer table." }, { "code": null, "e": 12671, "s": 12436, "text": "SELECT co.country, ci.city, a.address, cu.customer_id FROM country co LEFT JOIN city ci USING (country_id) LEFT JOIN address a USING (city_id) LEFT JOIN customer cu USING (address_id) WHERE cu.address_id IS NULL;" }, { "code": null, "e": 12734, "s": 12671, "text": "In this example, we’ll find the countries with no customers by" }, { "code": null, "e": 12809, "s": 12734, "text": "1. Creating a subquery to find the countries with at least one customer by" }, { "code": null, "e": 12869, "s": 12809, "text": "Joining the country table with city table using country_id." }, { "code": null, "e": 12931, "s": 12869, "text": "Joining the remainder table with address table using city_id." }, { "code": null, "e": 12997, "s": 12931, "text": "Joining the remainder table with customer table using address_id." }, { "code": null, "e": 13110, "s": 12997, "text": "2. Selecting country from country table where country_id is not present in the country_id of the above subquery." }, { "code": null, "e": 13449, "s": 13110, "text": "SELECT country FROM country WHERE country_id NOT IN ( SELECT co.country_id FROM country co INNER JOIN city ci USING (country_id) INNER JOIN address a USING (city_id) INNER JOIN customer USING (address_id) );" }, { "code": null, "e": 13575, "s": 13449, "text": "In the above example, we saw that Australia has no customers. In this example, we’ll see are there any stores in Australia by" }, { "code": null, "e": 13816, "s": 13575, "text": "Joining the country table with city table using country_id.Joining the resultant table with address table using city_id.Joining the resultant table with store table using address_id.Selecting records where store_id IS NOT NULL in Australia." }, { "code": null, "e": 13876, "s": 13816, "text": "Joining the country table with city table using country_id." }, { "code": null, "e": 13938, "s": 13876, "text": "Joining the resultant table with address table using city_id." }, { "code": null, "e": 14001, "s": 13938, "text": "Joining the resultant table with store table using address_id." }, { "code": null, "e": 14060, "s": 14001, "text": "Selecting records where store_id IS NOT NULL in Australia." }, { "code": null, "e": 14173, "s": 14060, "text": "Left join ensures that countries with no cities and cities with no stores are also included in the query result." }, { "code": null, "e": 14440, "s": 14173, "text": "SELECT st.store_id, co.country, ad.address FROM country co LEFT JOIN city ci USING (country_id) LEFT JOIN address ad USING (city_id) LEFT JOIN store st USING (address_id) WHERE (st.store_id IS NOT NULL) AND (co.country = 'Australia');" }, { "code": null, "e": 14570, "s": 14440, "text": "There is one store in Australia. In fact, there are just two stores in the whole database. We’ll view them using the below query." }, { "code": null, "e": 14591, "s": 14570, "text": "SELECT * FROM store;" }, { "code": null, "e": 14662, "s": 14591, "text": "In this example, we’ll see if there are any languages with no films by" }, { "code": null, "e": 14833, "s": 14662, "text": "Joining the language table with film table using language_id. The left join ensures languages without any films are also includes.Filtering records where film_id IS NULL." }, { "code": null, "e": 14964, "s": 14833, "text": "Joining the language table with film table using language_id. The left join ensures languages without any films are also includes." }, { "code": null, "e": 15005, "s": 14964, "text": "Filtering records where film_id IS NULL." }, { "code": null, "e": 15100, "s": 15005, "text": "SELECT * FROM language l LEFT JOIN film f USING (language_id) WHERE f.film_id IS NULL;" }, { "code": null, "e": 15312, "s": 15100, "text": "We see a few languages with no films in the database. We’ll make sure that it’s not an error by selecting the films with language_id in (2,3,4,5,6) from the film table. The query result should return no records." }, { "code": null, "e": 15370, "s": 15312, "text": "SELECT * FROM film WHERE language_id IN (2,3,4,5,6);" }, { "code": null, "e": 15519, "s": 15370, "text": "In this example, we’ll find the number of rentals per film category in India by joining the required tables as discussed in the earlier examples and" }, { "code": null, "e": 15741, "s": 15519, "text": "Grouping by country and category and filtering records from India and counting the film category name (as film_category_count).Ordering the result by country in ascending order and film_category_count in descending order." }, { "code": null, "e": 15869, "s": 15741, "text": "Grouping by country and category and filtering records from India and counting the film category name (as film_category_count)." }, { "code": null, "e": 15964, "s": 15869, "text": "Ordering the result by country in ascending order and film_category_count in descending order." }, { "code": null, "e": 16691, "s": 15964, "text": "SELECT co.country, cat.name AS film_category, COUNT(cat.name) AS film_category_count FROM country co INNER JOIN city ci USING (country_id) INNER JOIN address ad USING (city_id) INNER JOIN customer cu USING (address_id) INNER JOIN rental re USING (customer_id) INNER JOIN inventory inv USING (inventory_id) INNER JOIN film fi USING (film_id) INNER JOIN film_category fc USING (film_id) INNER JOIN category cat USING (category_id) /* Using WHERE co.country = 'India' here, instead of HAVING co.country = 'India' reduces the query execution time. */ GROUP BY (co.country, cat.name) HAVING co.country = 'India' ORDER BY co.country ASC, COUNT(cat.name) DESC;" }, { "code": null, "e": 16752, "s": 16691, "text": "In this example, we‘ll find the films with a single actor by" }, { "code": null, "e": 16924, "s": 16752, "text": "Joining the film table with film_actor table using film_id.Grouping by film_id and counting the number of actors (as actor_count).Filtering records where actor_count is 1." }, { "code": null, "e": 16984, "s": 16924, "text": "Joining the film table with film_actor table using film_id." }, { "code": null, "e": 17056, "s": 16984, "text": "Grouping by film_id and counting the number of actors (as actor_count)." }, { "code": null, "e": 17098, "s": 17056, "text": "Filtering records where actor_count is 1." }, { "code": null, "e": 17273, "s": 17098, "text": "SELECT f.film_id, f.title, COUNT(fa.actor_id) AS actor_count FROM film f INNER JOIN film_actor fa USING (film_id) GROUP BY f.film_id HAVING COUNT(fa.actor_id) = 1;" }, { "code": null, "e": 17353, "s": 17273, "text": "In this example, we’ll find the number of films of an actor by film category by" }, { "code": null, "e": 17690, "s": 17353, "text": "Creating a CTE named actor_cat_cnt that returns the number of films for each actor_id and category_id.Joining the above CTE with category table using category_id.Joining the resultant table with actor table using actor_id.Sort actor name (concatenation of first_name and last_name) in ascending order and film_count in descending order." }, { "code": null, "e": 17793, "s": 17690, "text": "Creating a CTE named actor_cat_cnt that returns the number of films for each actor_id and category_id." }, { "code": null, "e": 17854, "s": 17793, "text": "Joining the above CTE with category table using category_id." }, { "code": null, "e": 17915, "s": 17854, "text": "Joining the resultant table with actor table using actor_id." }, { "code": null, "e": 18030, "s": 17915, "text": "Sort actor name (concatenation of first_name and last_name) in ascending order and film_count in descending order." }, { "code": null, "e": 18581, "s": 18030, "text": "WITH actor_cat_cnt AS ( SELECT fa.actor_id, fc.category_id, COUNT(f.film_id) AS film_count FROM film_actor fa INNER JOIN film f USING (film_id) INNER JOIN film_category fc USING (film_id) GROUP BY fa.actor_id, fc.category_id )SELECT CONCAT(ac.first_name, ' ', ac.last_name) AS actor, ca.name AS category, film_count FROM actor_cat_cnt INNER JOIN category ca USING (category_id) INNER JOIN actor ac USING (actor_id) ORDER BY CONCAT(ac.first_name, ' ', ac.last_name) ASC, film_count DESC;" }, { "code": null, "e": 18787, "s": 18581, "text": "In the above example, we found the number of films of an actor by film category. In this example, we’ll find the popular categories of an actor (i.e. the categories in which an actor has the most films) by" }, { "code": null, "e": 19258, "s": 18787, "text": "Creating a CTE named actor_cat_cnt that returns the number of films for each actor_id and category_id and rank the categories of each actor by the count of films in descending order (as cat_rank).Joining the above CTE with category table using category_id.Joining the resultant table with actor table using actor_id.Filtering the records with cat_rank = 1.Sort actor name (concatenation of first_name and last_name) in ascending order and film_count in descending order." }, { "code": null, "e": 19455, "s": 19258, "text": "Creating a CTE named actor_cat_cnt that returns the number of films for each actor_id and category_id and rank the categories of each actor by the count of films in descending order (as cat_rank)." }, { "code": null, "e": 19516, "s": 19455, "text": "Joining the above CTE with category table using category_id." }, { "code": null, "e": 19577, "s": 19516, "text": "Joining the resultant table with actor table using actor_id." }, { "code": null, "e": 19618, "s": 19577, "text": "Filtering the records with cat_rank = 1." }, { "code": null, "e": 19733, "s": 19618, "text": "Sort actor name (concatenation of first_name and last_name) in ascending order and film_count in descending order." }, { "code": null, "e": 20401, "s": 19733, "text": "WITH actor_cat_cnt AS ( SELECT fa.actor_id, fc.category_id, COUNT(f.film_id) AS film_count, RANK() OVER (PARTITION BY fa.actor_id ORDER BY COUNT(f.film_id) DESC) AS cat_rank FROM film_actor fa INNER JOIN film f USING (film_id) INNER JOIN film_category fc USING (film_id) GROUP BY fa.actor_id, fc.category_id )SELECT CONCAT(ac.first_name, ' ', ac.last_name) AS actor, ca.name AS category, film_count FROM actor_cat_cnt INNER JOIN category ca USING (category_id) INNER JOIN actor ac USING (actor_id) WHERE cat_rank = 1 ORDER BY CONCAT(ac.first_name, ' ', ac.last_name) ASC, film_count DESC;" } ]
Check whether two straight lines are parallel or not - GeeksforGeeks
07 Feb, 2022 Given equations of two lines (a1, b1, c1) and (a2, b2, c2) such that (ai, bi, ci) are the coefficients of X2, X and a constant term of the straight line respectively, in the general equation , the task is to check if both the straight lines are parallel or not. If they are found to be parallel, then print “Yes”. Otherwise, print “No”. Examples: Input: a1 = -2, b1 = 4, a2 = -6, b2 = 12Output: YesExplanation:The slope of both lines are equal i.e., a1/b1 = a2/ b2 = -2. Input: a1 = 11, b1 = 3, a2 = 7, b2 = -10Output: NoExplanation: The slope of both lines are not equal i.e., a1/b1≠ a2/b2. Approach: To check if two lines are parallel to each other or not, the idea is to compare the slope of the given lines. If the slope of the given lines is equal then the given lines are parallel. Therefore, print “Yes” else print “No”. 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 check if two lines// are parallel or notvoid parallel(float a1, float b1, float c1, float a2, float b2, float c2){ // If slopes are equal // then -(a1 / b1) = -(a2 / b2) // which is a1*b2 = a2*b1 if (a1*b2 == a2*b1) { cout << "Yes"; } else { cout << "No"; }} // Driver Codeint main(){ float a1 = -2, b1 = 4, c1 = 5; float a2 = -6, b2 = 12, c2 = 6; // Function Call parallel(a1, b1, c1, a2, b2, c2); return 0;} // Java program to implement// the above approachimport java.util.*;class GFG{ // Function to check if two lines// are parallel or notstatic void parallel(float a1, float b1, float c1, float a2, float b2, float c2){ // If slopes are equal // then (-(a1 / b1)) == (-(a2 / b2)) // which is a1*b2 = a2*b1 if (a1*b2 == a2*b1) { System.out.println("Yes"); } else { System.out.println("No"); }} // Driver Codepublic static void main(String args[]){ float a1 = -2, b1 = 4, c1 = 5; float a2 = -6, b2 = 12, c2 = 6; // Function Call parallel(a1, b1, c1, a2, b2, c2);}} // This code is contributed by splevel62. # Python program to implement# the above approach # Function to check if two lines# are parallel or notdef parallel(a1, b1, c1, a2, b2, c2): # If slopes are equal # then ((-(a1 / b1)) == (-(a2 / b2))) # which is a1*b2 = a2*b1 if a1*b2==a2*b1: print("Yes"); else: print("No"); # Driver Codeif __name__ == '__main__': a1 = -2; b1 = 4; c1 = 5; a2 = -6; b2 = 12; c2 = 6; # Function Call parallel(a1, b1, c1, a2, b2, c2); # This code is contributed by 29AjayKumar // C# program to implement// the above approachusing System;class GFG{ // Function to check if two lines// are parallel or notstatic void parallel(float a1, float b1, float c1, float a2, float b2, float c2){ // If slopes are equal // then (-(a1 / b1)) == (-(a2 / b2)) // which is a1*b2 = a2*b1 if (a1*b2 == a2*b1) { Console.Write("Yes"); } else { Console.Write("No"); }} // Driver Codepublic static void Main(){ float a1 = -2, b1 = 4, c1 = 5; float a2 = -6, b2 = 12, c2 = 6; // Function Call parallel(a1, b1, c1, a2, b2, c2);}} // This code is contributed by susmitakundugoaldanga. <script>// javascript program of the above approach // Function to check if two lines// are parallel or notfunction parallel(a1, b1, c1, a2, b2, c2){ // If slopes are equal // then (-(a1 / b1)) == (-(a2 / b2)) // which is a1*b2==a2*b1 if (a1*b2==a2*b1) { document.write("Yes"); } else { document.write("No"); }} // Driver Code let a1 = -2, b1 = 4, c1 = 5; let a2 = -6, b2 = 12, c2 = 6; // Function Call parallel(a1, b1, c1, a2, b2, c2); </script> Yes Time Complexity: O(1)Auxiliary Space: O(1) splevel62 susmitakundugoaldanga 29AjayKumar chinmoy1997pal DevarshiAgarwal Geometric-Lines Technical Scripter 2020 Geometric Mathematical Technical Scripter 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": "\n07 Feb, 2022" }, { "code": null, "e": 26898, "s": 26561, "text": "Given equations of two lines (a1, b1, c1) and (a2, b2, c2) such that (ai, bi, ci) are the coefficients of X2, X and a constant term of the straight line respectively, in the general equation , the task is to check if both the straight lines are parallel or not. If they are found to be parallel, then print “Yes”. Otherwise, print “No”." }, { "code": null, "e": 26908, "s": 26898, "text": "Examples:" }, { "code": null, "e": 27032, "s": 26908, "text": "Input: a1 = -2, b1 = 4, a2 = -6, b2 = 12Output: YesExplanation:The slope of both lines are equal i.e., a1/b1 = a2/ b2 = -2." }, { "code": null, "e": 27154, "s": 27032, "text": "Input: a1 = 11, b1 = 3, a2 = 7, b2 = -10Output: NoExplanation: The slope of both lines are not equal i.e., a1/b1≠ a2/b2." }, { "code": null, "e": 27390, "s": 27154, "text": "Approach: To check if two lines are parallel to each other or not, the idea is to compare the slope of the given lines. If the slope of the given lines is equal then the given lines are parallel. Therefore, print “Yes” else print “No”." }, { "code": null, "e": 27441, "s": 27390, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27445, "s": 27441, "text": "C++" }, { "code": null, "e": 27450, "s": 27445, "text": "Java" }, { "code": null, "e": 27458, "s": 27450, "text": "Python3" }, { "code": null, "e": 27461, "s": 27458, "text": "C#" }, { "code": null, "e": 27472, "s": 27461, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if two lines// are parallel or notvoid parallel(float a1, float b1, float c1, float a2, float b2, float c2){ // If slopes are equal // then -(a1 / b1) = -(a2 / b2) // which is a1*b2 = a2*b1 if (a1*b2 == a2*b1) { cout << \"Yes\"; } else { cout << \"No\"; }} // Driver Codeint main(){ float a1 = -2, b1 = 4, c1 = 5; float a2 = -6, b2 = 12, c2 = 6; // Function Call parallel(a1, b1, c1, a2, b2, c2); return 0;}", "e": 28057, "s": 27472, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to check if two lines// are parallel or notstatic void parallel(float a1, float b1, float c1, float a2, float b2, float c2){ // If slopes are equal // then (-(a1 / b1)) == (-(a2 / b2)) // which is a1*b2 = a2*b1 if (a1*b2 == a2*b1) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); }} // Driver Codepublic static void main(String args[]){ float a1 = -2, b1 = 4, c1 = 5; float a2 = -6, b2 = 12, c2 = 6; // Function Call parallel(a1, b1, c1, a2, b2, c2);}} // This code is contributed by splevel62.", "e": 28742, "s": 28057, "text": null }, { "code": "# Python program to implement# the above approach # Function to check if two lines# are parallel or notdef parallel(a1, b1, c1, a2, b2, c2): # If slopes are equal # then ((-(a1 / b1)) == (-(a2 / b2))) # which is a1*b2 = a2*b1 if a1*b2==a2*b1: print(\"Yes\"); else: print(\"No\"); # Driver Codeif __name__ == '__main__': a1 = -2; b1 = 4; c1 = 5; a2 = -6; b2 = 12; c2 = 6; # Function Call parallel(a1, b1, c1, a2, b2, c2); # This code is contributed by 29AjayKumar", "e": 29247, "s": 28742, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ // Function to check if two lines// are parallel or notstatic void parallel(float a1, float b1, float c1, float a2, float b2, float c2){ // If slopes are equal // then (-(a1 / b1)) == (-(a2 / b2)) // which is a1*b2 = a2*b1 if (a1*b2 == a2*b1) { Console.Write(\"Yes\"); } else { Console.Write(\"No\"); }} // Driver Codepublic static void Main(){ float a1 = -2, b1 = 4, c1 = 5; float a2 = -6, b2 = 12, c2 = 6; // Function Call parallel(a1, b1, c1, a2, b2, c2);}} // This code is contributed by susmitakundugoaldanga.", "e": 29917, "s": 29247, "text": null }, { "code": "<script>// javascript program of the above approach // Function to check if two lines// are parallel or notfunction parallel(a1, b1, c1, a2, b2, c2){ // If slopes are equal // then (-(a1 / b1)) == (-(a2 / b2)) // which is a1*b2==a2*b1 if (a1*b2==a2*b1) { document.write(\"Yes\"); } else { document.write(\"No\"); }} // Driver Code let a1 = -2, b1 = 4, c1 = 5; let a2 = -6, b2 = 12, c2 = 6; // Function Call parallel(a1, b1, c1, a2, b2, c2); </script>", "e": 30457, "s": 29917, "text": null }, { "code": null, "e": 30461, "s": 30457, "text": "Yes" }, { "code": null, "e": 30504, "s": 30461, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 30514, "s": 30504, "text": "splevel62" }, { "code": null, "e": 30536, "s": 30514, "text": "susmitakundugoaldanga" }, { "code": null, "e": 30548, "s": 30536, "text": "29AjayKumar" }, { "code": null, "e": 30563, "s": 30548, "text": "chinmoy1997pal" }, { "code": null, "e": 30579, "s": 30563, "text": "DevarshiAgarwal" }, { "code": null, "e": 30595, "s": 30579, "text": "Geometric-Lines" }, { "code": null, "e": 30619, "s": 30595, "text": "Technical Scripter 2020" }, { "code": null, "e": 30629, "s": 30619, "text": "Geometric" }, { "code": null, "e": 30642, "s": 30629, "text": "Mathematical" }, { "code": null, "e": 30661, "s": 30642, "text": "Technical Scripter" }, { "code": null, "e": 30674, "s": 30661, "text": "Mathematical" }, { "code": null, "e": 30684, "s": 30674, "text": "Geometric" }, { "code": null, "e": 30782, "s": 30684, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30848, "s": 30782, "text": "Haversine formula to find distance between two points on a sphere" }, { "code": null, "e": 30880, "s": 30848, "text": "Program to find slope of a line" }, { "code": null, "e": 30941, "s": 30880, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 30987, "s": 30941, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 31057, "s": 30987, "text": "Maximum Manhattan distance between a distinct pair from N coordinates" }, { "code": null, "e": 31087, "s": 31057, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31147, "s": 31087, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31162, "s": 31147, "text": "C++ Data Types" }, { "code": null, "e": 31205, "s": 31162, "text": "Set in C++ Standard Template Library (STL)" } ]
Comparing Python with C and C++ - GeeksforGeeks
27 May, 2021 In the following article, we will compare the 3 most used coding languages from a beginner’s perspective. It will help you to learn basics of all the 3 languages together while saving your time and will also help you to inter shift from one language you know to the other which you don’t. Let’s discuss a brief history of all the 3 languages and then we will move on to the practical learning. Header Files: The files that tell the compiler how to call some functionality (without knowing how the functionality actually works) are called header files. They contain the function prototypes. They also contain Data types and constants used with the libraries. We use #include to use these header files in programs. These files end with .h extension. Library: Library is the place where the actual functionality is implemented i.e. they contain function body.Modules: A module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. C C++ Python // C program to demonstrate// adding header file #include <stdio.h>#include <string.h> // C++ program to demonstrate// adding header file #include <iostream>using namespace std;#include <math.h> # Python program to demonstrate# including modules import tensorflow # Including a class# from existing modulefrom tensorflow import keras Main method declaration is declaring to computer that from here the implementation of my code should be done. The process of declaring main is same in C and C++. As we declare int main where int stands for return type we should have to return something integral at the end of code so that it compiles without error. We can write our code in between the curly braces. C C++ # C program to demonstrate# declaring main #include <stdio.h>int main(){ // Your code here return 0;} # C++ program to demonstrate# declaring main #include <iostream.h>int main(){ // Your code here return 0} It is not necessary to declare main in python code unless and until you are declaring another function in your code. So we can declare main in python as follows. Python3 # Python program to demonstrate# declaring main def main(): # write your code here if __name__=="__main__": main() In C and C++ we first declare the data type of the variable and then declare the name of Variables. A few examples of data types are int, char, float, double, etc.Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. C C++ Python // C program to demonstrate// declaring variable #include <stdio.h> int main(){ // Declaring one variable at a time int a; // Declaring more than one variable char a, b, c, d; // Initializing variables float a = 0, b, c; b = 1; return 0;} // C++ program to demonstrate// declaring variables #include <iostream.h> int main(){ // Declaring one variable at a time int a; // Declaring more than one variable char a, b, c, d; // Initializing variables float a = 0, b, c; b = 1; return 0;} # Python program to demonstrate# creating variables # An integer assignmentage = 45 # A floating pointsalary = 1456.8 # A string name = "John" The Syntax for printing something as output is different for all the 3 languages. C C++ Python // C program to showing// how to print data// on screen #include <stdio.h> int main(){ printf("Hello World"); return 0;} // C++ program to showing// how to print data// on screen #include <iostream>using namespace std; int main(){ cout << "Hello World"; return 0;} # Python program to showing# how to print data# on screen print("Hello World") The Syntax for taking input from the user is different in all three languages, so let’s see the syntax and write your first basic code in all the 3 languages. C C++ Python // C program showing// how to take input// from user #include <stdio.h> int main(){ int a, b, c; printf("first number: "); scanf("%d", &a); printf("second number: "); scanf("%d", &b); c = a + b; printf("Hello World\n%d + %d = %d", a, b, c); return 0;} // C++ program showing// how to take input// from user #include <iostream>using namespace std; int main(){ int a, b, c; cout << "first number: "; cin >> a; cout << endl; cout << "second number: "; cin >> b; cout << endl; c = a + b; cout << "Hello World" << endl; cout << a << "+" << b << "=" << c; return 0;} # Python program showing# how to take input# from user a = input("first number: ")b = input("second number: ") c = a + b print("Hello World")print(a, "+", b, "=", c) nidhi_biet simmytarika5 GBlog Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Roadmap to Become a Web Developer in 2022 DSA Sheet by Love Babbar Top 10 Angular Libraries For Web Developers A Freshers Guide To Programming ML | Underfitting and Overfitting Virtualization In Cloud Computing and Types Top 10 Programming Languages to Learn in 2022 Bloom Filters - Introduction and Implementation What is web socket and how it is different from the HTTP? Introduction to Hill Climbing | Artificial Intelligence
[ { "code": null, "e": 24984, "s": 24956, "text": "\n27 May, 2021" }, { "code": null, "e": 25379, "s": 24984, "text": "In the following article, we will compare the 3 most used coding languages from a beginner’s perspective. It will help you to learn basics of all the 3 languages together while saving your time and will also help you to inter shift from one language you know to the other which you don’t. Let’s discuss a brief history of all the 3 languages and then we will move on to the practical learning. " }, { "code": null, "e": 26262, "s": 25383, "text": "Header Files: The files that tell the compiler how to call some functionality (without knowing how the functionality actually works) are called header files. They contain the function prototypes. They also contain Data types and constants used with the libraries. We use #include to use these header files in programs. These files end with .h extension. Library: Library is the place where the actual functionality is implemented i.e. they contain function body.Modules: A module is a file containing Python definitions and statements. A module can define functions, classes, and variables. A module can also include runnable code. Grouping related code into a module makes the code easier to understand and use. Import in python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. " }, { "code": null, "e": 26264, "s": 26262, "text": "C" }, { "code": null, "e": 26268, "s": 26264, "text": "C++" }, { "code": null, "e": 26275, "s": 26268, "text": "Python" }, { "code": "// C program to demonstrate// adding header file #include <stdio.h>#include <string.h>", "e": 26362, "s": 26275, "text": null }, { "code": "// C++ program to demonstrate// adding header file #include <iostream>using namespace std;#include <math.h>", "e": 26470, "s": 26362, "text": null }, { "code": "# Python program to demonstrate# including modules import tensorflow # Including a class# from existing modulefrom tensorflow import keras", "e": 26610, "s": 26470, "text": null }, { "code": null, "e": 26979, "s": 26610, "text": "Main method declaration is declaring to computer that from here the implementation of my code should be done. The process of declaring main is same in C and C++. As we declare int main where int stands for return type we should have to return something integral at the end of code so that it compiles without error. We can write our code in between the curly braces. " }, { "code": null, "e": 26981, "s": 26979, "text": "C" }, { "code": null, "e": 26985, "s": 26981, "text": "C++" }, { "code": "# C program to demonstrate# declaring main #include <stdio.h>int main(){ // Your code here return 0;}", "e": 27087, "s": 26985, "text": null }, { "code": "# C++ program to demonstrate# declaring main #include <iostream.h>int main(){ // Your code here return 0}", "e": 27193, "s": 27087, "text": null }, { "code": null, "e": 27357, "s": 27193, "text": "It is not necessary to declare main in python code unless and until you are declaring another function in your code. So we can declare main in python as follows. " }, { "code": null, "e": 27365, "s": 27357, "text": "Python3" }, { "code": "# Python program to demonstrate# declaring main def main(): # write your code here if __name__==\"__main__\": main()", "e": 27486, "s": 27365, "text": null }, { "code": null, "e": 27825, "s": 27486, "text": "In C and C++ we first declare the data type of the variable and then declare the name of Variables. A few examples of data types are int, char, float, double, etc.Python is not “statically typed”. We do not need to declare variables before using them or declare their type. A variable is created the moment we first assign a value to it. " }, { "code": null, "e": 27827, "s": 27825, "text": "C" }, { "code": null, "e": 27831, "s": 27827, "text": "C++" }, { "code": null, "e": 27838, "s": 27831, "text": "Python" }, { "code": "// C program to demonstrate// declaring variable #include <stdio.h> int main(){ // Declaring one variable at a time int a; // Declaring more than one variable char a, b, c, d; // Initializing variables float a = 0, b, c; b = 1; return 0;}", "e": 28104, "s": 27838, "text": null }, { "code": "// C++ program to demonstrate// declaring variables #include <iostream.h> int main(){ // Declaring one variable at a time int a; // Declaring more than one variable char a, b, c, d; // Initializing variables float a = 0, b, c; b = 1; return 0;}", "e": 28377, "s": 28104, "text": null }, { "code": "# Python program to demonstrate# creating variables # An integer assignmentage = 45 # A floating pointsalary = 1456.8 # A string name = \"John\" ", "e": 28572, "s": 28377, "text": null }, { "code": null, "e": 28655, "s": 28572, "text": "The Syntax for printing something as output is different for all the 3 languages. " }, { "code": null, "e": 28657, "s": 28655, "text": "C" }, { "code": null, "e": 28661, "s": 28657, "text": "C++" }, { "code": null, "e": 28668, "s": 28661, "text": "Python" }, { "code": "// C program to showing// how to print data// on screen #include <stdio.h> int main(){ printf(\"Hello World\"); return 0;}", "e": 28793, "s": 28668, "text": null }, { "code": "// C++ program to showing// how to print data// on screen #include <iostream>using namespace std; int main(){ cout << \"Hello World\"; return 0;}", "e": 28943, "s": 28793, "text": null }, { "code": "# Python program to showing# how to print data# on screen print(\"Hello World\")", "e": 29022, "s": 28943, "text": null }, { "code": null, "e": 29182, "s": 29022, "text": "The Syntax for taking input from the user is different in all three languages, so let’s see the syntax and write your first basic code in all the 3 languages. " }, { "code": null, "e": 29184, "s": 29182, "text": "C" }, { "code": null, "e": 29188, "s": 29184, "text": "C++" }, { "code": null, "e": 29195, "s": 29188, "text": "Python" }, { "code": "// C program showing// how to take input// from user #include <stdio.h> int main(){ int a, b, c; printf(\"first number: \"); scanf(\"%d\", &a); printf(\"second number: \"); scanf(\"%d\", &b); c = a + b; printf(\"Hello World\\n%d + %d = %d\", a, b, c); return 0;}", "e": 29475, "s": 29195, "text": null }, { "code": "// C++ program showing// how to take input// from user #include <iostream>using namespace std; int main(){ int a, b, c; cout << \"first number: \"; cin >> a; cout << endl; cout << \"second number: \"; cin >> b; cout << endl; c = a + b; cout << \"Hello World\" << endl; cout << a << \"+\" << b << \"=\" << c; return 0;}", "e": 29821, "s": 29475, "text": null }, { "code": "# Python program showing# how to take input# from user a = input(\"first number: \")b = input(\"second number: \") c = a + b print(\"Hello World\")print(a, \"+\", b, \"=\", c)", "e": 29987, "s": 29821, "text": null }, { "code": null, "e": 29998, "s": 29987, "text": "nidhi_biet" }, { "code": null, "e": 30011, "s": 29998, "text": "simmytarika5" }, { "code": null, "e": 30017, "s": 30011, "text": "GBlog" }, { "code": null, "e": 30115, "s": 30017, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30124, "s": 30115, "text": "Comments" }, { "code": null, "e": 30137, "s": 30124, "text": "Old Comments" }, { "code": null, "e": 30179, "s": 30137, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 30204, "s": 30179, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 30248, "s": 30204, "text": "Top 10 Angular Libraries For Web Developers" }, { "code": null, "e": 30280, "s": 30248, "text": "A Freshers Guide To Programming" }, { "code": null, "e": 30314, "s": 30280, "text": "ML | Underfitting and Overfitting" }, { "code": null, "e": 30358, "s": 30314, "text": "Virtualization In Cloud Computing and Types" }, { "code": null, "e": 30404, "s": 30358, "text": "Top 10 Programming Languages to Learn in 2022" }, { "code": null, "e": 30452, "s": 30404, "text": "Bloom Filters - Introduction and Implementation" }, { "code": null, "e": 30510, "s": 30452, "text": "What is web socket and how it is different from the HTTP?" } ]
Count Squares | Practice | GeeksforGeeks
Consider a sample space S consisting of all perfect squares starting from 1, 4, 9 and so on. You are given a number N, you have to output the number of integers less than N in the sample space S. Example 1: Input : N = 9 Output: 2 Explanation: 1 and 4 are the only Perfect Squares less than 9. So, the Output is 2. Example 2: Input : N = 3 Output: 1 Explanation: 1 is the only Perfect Square less than 3. So, the Output is 1. Your Task: You don't need to read input or print anything. Your task is to complete the function countSquares() which takes an Integer N as input and returns the answer. Expected Time Complexity: O(sqrt(N)) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 108 0 hrithikjain98892 days ago Total Time Taken: 0.02/1.31 int countSquares(int N) { // code here int x=sqrt(N); if(x*x==N) return x-1; else return x; } 0 jainamkothari142 days ago static int countSquares(int N) { int count=0; int i=1; while(i*i<N) { count++; i++; } return count; } 0 dharmikpatel4912 days ago int countSquares(int N) { int ans; float sq = sqrt(N); if(floor(sq) != sq){ ans = (int)sq; } else { ans = (int)sq-1; } return ans; } 0 btech60063192 days ago int i; for(i=0; i*i<N; i++); return i-1; 0 amitrrrvaa00035 days ago Python Code return int(math.sqrt(N-1)) 0 satyamjaiswal88281 week ago int countSquares(int N) { // code here return sqrt(N-1); } //sqrt is square root function in stl library. 0 rohanmeher1641 week ago //Simple Java Solution class Solution { static int countSquares(int N) { int ans=0; for(int i=0;i*i<N;i++) { // we dont need to create any 'count' variable because,value of 'i' and 'count' will be same. ans=i; } return ans; }} +1 mayank180919991 week ago int countSquares(int N) { // code here int count=0; for(int i=1;i<sqrt(N);i++){ if(i*i<N){ count++; } } return count; } 0 sharmanitish1832 weeks ago class Solution { static int countSquares(int N) { return (int)Math.sqrt(N-1); }} 0 anandpatel982601 month ago Easy to understand approach class Solution { public: int countSquares(int N) { int count=0; for(int i=1;i*i<N;i++)count++; return count; }}; 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": 434, "s": 238, "text": "Consider a sample space S consisting of all perfect squares starting from 1, 4, 9 and so on. You are given a number N, you have to output the number of integers less than N in the sample space S." }, { "code": null, "e": 447, "s": 436, "text": "Example 1:" }, { "code": null, "e": 555, "s": 447, "text": "Input :\nN = 9\nOutput:\n2\nExplanation:\n1 and 4 are the only Perfect Squares\nless than 9. So, the Output is 2." }, { "code": null, "e": 566, "s": 555, "text": "Example 2:" }, { "code": null, "e": 666, "s": 566, "text": "Input :\nN = 3\nOutput:\n1\nExplanation:\n1 is the only Perfect Square\nless than 3. So, the Output is 1." }, { "code": null, "e": 838, "s": 668, "text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function countSquares() which takes an Integer N as input and returns the answer." }, { "code": null, "e": 908, "s": 840, "text": "Expected Time Complexity: O(sqrt(N))\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 937, "s": 910, "text": "Constraints:\n1 <= N <= 108" }, { "code": null, "e": 939, "s": 937, "text": "0" }, { "code": null, "e": 965, "s": 939, "text": "hrithikjain98892 days ago" }, { "code": null, "e": 983, "s": 965, "text": "Total Time Taken:" }, { "code": null, "e": 993, "s": 983, "text": "0.02/1.31" }, { "code": null, "e": 1115, "s": 993, "text": "int countSquares(int N) { // code here int x=sqrt(N); if(x*x==N) return x-1; else return x; }" }, { "code": null, "e": 1117, "s": 1115, "text": "0" }, { "code": null, "e": 1143, "s": 1117, "text": "jainamkothari142 days ago" }, { "code": null, "e": 1310, "s": 1143, "text": "static int countSquares(int N) { int count=0; int i=1; while(i*i<N) { count++; i++; } return count; }" }, { "code": null, "e": 1312, "s": 1310, "text": "0" }, { "code": null, "e": 1338, "s": 1312, "text": "dharmikpatel4912 days ago" }, { "code": null, "e": 1529, "s": 1338, "text": "int countSquares(int N) { int ans; float sq = sqrt(N); if(floor(sq) != sq){ ans = (int)sq; } else { ans = (int)sq-1; } return ans; }" }, { "code": null, "e": 1531, "s": 1529, "text": "0" }, { "code": null, "e": 1554, "s": 1531, "text": "btech60063192 days ago" }, { "code": null, "e": 1614, "s": 1554, "text": " int i; for(i=0; i*i<N; i++); return i-1;" }, { "code": null, "e": 1616, "s": 1614, "text": "0" }, { "code": null, "e": 1641, "s": 1616, "text": "amitrrrvaa00035 days ago" }, { "code": null, "e": 1653, "s": 1641, "text": "Python Code" }, { "code": null, "e": 1680, "s": 1653, "text": "return int(math.sqrt(N-1))" }, { "code": null, "e": 1682, "s": 1680, "text": "0" }, { "code": null, "e": 1710, "s": 1682, "text": "satyamjaiswal88281 week ago" }, { "code": null, "e": 1783, "s": 1710, "text": "int countSquares(int N) { // code here return sqrt(N-1); }" }, { "code": null, "e": 1830, "s": 1783, "text": "//sqrt is square root function in stl library." }, { "code": null, "e": 1832, "s": 1830, "text": "0" }, { "code": null, "e": 1856, "s": 1832, "text": "rohanmeher1641 week ago" }, { "code": null, "e": 1879, "s": 1856, "text": "//Simple Java Solution" }, { "code": null, "e": 2127, "s": 1881, "text": "class Solution { static int countSquares(int N) { int ans=0; for(int i=0;i*i<N;i++) { // we dont need to create any 'count' variable because,value of 'i' and 'count' will be same. ans=i; } return ans; }}" }, { "code": null, "e": 2130, "s": 2127, "text": "+1" }, { "code": null, "e": 2155, "s": 2130, "text": "mayank180919991 week ago" }, { "code": null, "e": 2358, "s": 2155, "text": " int countSquares(int N) {\n // code here\n int count=0;\n for(int i=1;i<sqrt(N);i++){\n if(i*i<N){\n count++;\n }\n }\n return count;\n }" }, { "code": null, "e": 2360, "s": 2358, "text": "0" }, { "code": null, "e": 2387, "s": 2360, "text": "sharmanitish1832 weeks ago" }, { "code": null, "e": 2478, "s": 2387, "text": "class Solution { static int countSquares(int N) { return (int)Math.sqrt(N-1); }}" }, { "code": null, "e": 2480, "s": 2478, "text": "0" }, { "code": null, "e": 2507, "s": 2480, "text": "anandpatel982601 month ago" }, { "code": null, "e": 2535, "s": 2507, "text": "Easy to understand approach" }, { "code": null, "e": 2670, "s": 2535, "text": "class Solution { public: int countSquares(int N) { int count=0; for(int i=1;i*i<N;i++)count++; return count; }};" }, { "code": null, "e": 2816, "s": 2670, "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": 2852, "s": 2816, "text": " Login to access your submissions. " }, { "code": null, "e": 2862, "s": 2852, "text": "\nProblem\n" }, { "code": null, "e": 2872, "s": 2862, "text": "\nContest\n" }, { "code": null, "e": 2935, "s": 2872, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3083, "s": 2935, "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": 3291, "s": 3083, "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": 3397, "s": 3291, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
NLP: Classification & Recommendation Project | by Alper Çakır | Towards Data Science
NLP is the science of extracting meaning and learning from text data, and It’s one of the most used algorithms in data science projects. Text data is in everywhere, in the conclusion of that, NLP has many application areas, as you can see in the chart below. In this context, I decided to make an NLP project that covers the arxiv data. By going into this project, I aimed to classify tags of the articles and building a recommendation system via the article’s summary, title, author, and genre features. To achieve my objectives, I extracted an arxiv dataset which includes 41000 rows and 6 columns: author, link, summary, tag, title, and year. And my dataset contains articles between 1998–2018. As can be seen in the left photo, it contains articles mostly in the computer science area. Some of my features were in the type of dictionary, so I transformed these columns into list type to have a usable data structure. from ast import literal_eval# convert 'stringfield' lists to usable structurefeatures = ['author', 'link', 'tag']for feature in features: arxivData[feature] = arxivData[feature].apply(literal_eval) After performing literal_eval, I coded three functions for the list transformation: def get_names(x): if isinstance(x, list): names = [i['name'] for i in x] #Check if more than 3 elements exist. If yes, return only first three. If no, return entire list. if len(names) > 3: names = names[:3] return namesdef get_link(x): for i in x: return i['href'] def get_tag(x): if isinstance(x, list): terms = [i['term'] for i in x] #Check if more than 5 elements exist. If yes, return only first five. If no, return entire list. if len(terms) > 5: terms = terms[:5] return terms Well, I’m ready to write a text cleaning function now. These are one of the most important parts of an NLP project to build a robust model structure. To do this, we need to remove capital letters, punctuation, and numbers: # Data Cleaning & Preprocessing techniquesdef clean_text(text): # remove everything except alphabets text = re.sub("[^a-zA-Z]", " ", text) # remove whitespaces text = ' '.join(text.split()) text = text.lower() return text Now it’s time to extract features from the text data. Text files are originally just a series of words. With the aim of running machine learning algorithms, we have to convert the text files into numerical feature vectors. There’re two common ways to do so: CountVectorizer and Tfidf. CountVectorizer: The CountVectorizer provides a simple way to both tokenize a collection of text documents and build a vocabulary of known words, but also to encode new documents using that vocabulary. Tfidf: TF-IDF is a statistical measure that evaluates how relevant a word is to a document in a collection of documents. This is done by multiplying two metrics: how many times a word appears in a document, and the inverse document frequency of the word across a set of documents. The difference between them is basically, one counts all the words to vectorize and the other one uses a statistical method instead. To perform text mining on my dataset, I coded a lemmatize function firstly, and then performed vectorization. # Lemmatization process'''Words in the third person are changed to first person and verbs in past and future tenses are changed into the present by the lemmatization process. '''lemmatizer = WordNetLemmatizer()def tokenize_and_lemmatize(text): # tokenization to ensure that punctuation is caught as its own token tokens = [word.lower() for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)] filtered_tokens = [] for token in tokens: if re.search('[a-zA-Z]', token): filtered_tokens.append(token) lem = [lemmatizer.lemmatize(t) for t in filtered_tokens] return lem With this matrix in hand, we can now build a machine learning model. # Defining a Count Vectorizer objectcount_vec = CountVectorizer(stop_words='english', max_features=10000)# Defining a TF-IDF Vectorizertfidf_vec = TfidfVectorizer(stop_words='english', ngram_range=(1, 2), tokenizer=tokenize_and_lemmatize, max_features=10000, use_idf=True) There are various algorithms that can be used for text classification. Well, I started by exploring these models: Logistic Regression, Naive Bayes, Linear SVC, and Random Forest. My method was, choosing the best model to optimize, after running all my models in this section. Hence, I ran all the models with their default parameters to see the results. Here are the results of my classification models. The reason for the conflict between accuracy and f1 scores is there are multiple tags for an article. Machine Learning models failed to predict all the tags for an article. Still, f1 score is higher than accuracy because I set the average parameter of f1 to ‘micro’. I skipped to the optimization section following to evaluations of models. For that purpose, I used the GridSearchCV: param = {'estimator__penalty':['l1', 'l2'], 'estimator__C':[0.001, 0.01, 1, 10]}# GridSearchCVkf=KFold(n_splits=10, shuffle=True, random_state=55)lr_grid = GridSearchCV(oneVsRest, param_grid = param, cv = kf, scoring='f1_micro', n_jobs=-1)lr_grid.fit(xtrain_tfidf, y_train) I have chosen Logistic Regression for the Grid Search process because of the accuracy score, and as a result, I got an F1-score that has increased to %64,1. Here are some of the results of the optimized regression model: I made two recommendation systems, first one is based on a summary and the other is based on a title, tags, and authors. To build a recommender, firstly I computed the cosine similarity on vectorized text data. # TfIdf matrix transformation on clean_summary columntfidf_matrix = tfidf_vec.fit_transform(arxivData['clean_summary'])# Compute the cosine similaritycosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix) Following the calculation, I wrote the recommendation function: def get_recommendations(title, similarity): idx = indices[title] # pairwsie similarity scores sim_scores = list(enumerate(similarity[idx])) # sorting sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) sim_scores = sim_scores[1:11] article_indices = [i[0] for i in sim_scores] # Return the top 10 most related articles return arxivData[['link', 'title']].iloc[article_indices] It gets two parameters and then sorts the articles via their cosine similarity values. Finally, It returns 10 most related articles as a result. We have learned the general approach to a basic level of NLP projects. We have learned that there are two common ways to preprocess our text data: Count and Tfidf Vectorizer. We saw that our classification models failed for a multi-class problem but when we evaluate f1 score as a success metric, we’re not so bad. The most written articles are from computer science studies and the most frequently used word is ‘neural network’. Finally, we learned how to use cosine similarity to build a recommender. As further work, I planned to do a Flask app to make my recommender online. Well, that’s all for now. See you soon in the next post! Also, check out my Github profile too if you want to learn more!
[ { "code": null, "e": 431, "s": 172, "text": "NLP is the science of extracting meaning and learning from text data, and It’s one of the most used algorithms in data science projects. Text data is in everywhere, in the conclusion of that, NLP has many application areas, as you can see in the chart below." }, { "code": null, "e": 677, "s": 431, "text": "In this context, I decided to make an NLP project that covers the arxiv data. By going into this project, I aimed to classify tags of the articles and building a recommendation system via the article’s summary, title, author, and genre features." }, { "code": null, "e": 962, "s": 677, "text": "To achieve my objectives, I extracted an arxiv dataset which includes 41000 rows and 6 columns: author, link, summary, tag, title, and year. And my dataset contains articles between 1998–2018. As can be seen in the left photo, it contains articles mostly in the computer science area." }, { "code": null, "e": 1093, "s": 962, "text": "Some of my features were in the type of dictionary, so I transformed these columns into list type to have a usable data structure." }, { "code": null, "e": 1294, "s": 1093, "text": "from ast import literal_eval# convert 'stringfield' lists to usable structurefeatures = ['author', 'link', 'tag']for feature in features: arxivData[feature] = arxivData[feature].apply(literal_eval)" }, { "code": null, "e": 1378, "s": 1294, "text": "After performing literal_eval, I coded three functions for the list transformation:" }, { "code": null, "e": 1959, "s": 1378, "text": "def get_names(x): if isinstance(x, list): names = [i['name'] for i in x] #Check if more than 3 elements exist. If yes, return only first three. If no, return entire list. if len(names) > 3: names = names[:3] return namesdef get_link(x): for i in x: return i['href'] def get_tag(x): if isinstance(x, list): terms = [i['term'] for i in x] #Check if more than 5 elements exist. If yes, return only first five. If no, return entire list. if len(terms) > 5: terms = terms[:5] return terms" }, { "code": null, "e": 2182, "s": 1959, "text": "Well, I’m ready to write a text cleaning function now. These are one of the most important parts of an NLP project to build a robust model structure. To do this, we need to remove capital letters, punctuation, and numbers:" }, { "code": null, "e": 2422, "s": 2182, "text": "# Data Cleaning & Preprocessing techniquesdef clean_text(text): # remove everything except alphabets text = re.sub(\"[^a-zA-Z]\", \" \", text) # remove whitespaces text = ' '.join(text.split()) text = text.lower() return text" }, { "code": null, "e": 2707, "s": 2422, "text": "Now it’s time to extract features from the text data. Text files are originally just a series of words. With the aim of running machine learning algorithms, we have to convert the text files into numerical feature vectors. There’re two common ways to do so: CountVectorizer and Tfidf." }, { "code": null, "e": 2909, "s": 2707, "text": "CountVectorizer: The CountVectorizer provides a simple way to both tokenize a collection of text documents and build a vocabulary of known words, but also to encode new documents using that vocabulary." }, { "code": null, "e": 3190, "s": 2909, "text": "Tfidf: TF-IDF is a statistical measure that evaluates how relevant a word is to a document in a collection of documents. This is done by multiplying two metrics: how many times a word appears in a document, and the inverse document frequency of the word across a set of documents." }, { "code": null, "e": 3323, "s": 3190, "text": "The difference between them is basically, one counts all the words to vectorize and the other one uses a statistical method instead." }, { "code": null, "e": 3433, "s": 3323, "text": "To perform text mining on my dataset, I coded a lemmatize function firstly, and then performed vectorization." }, { "code": null, "e": 4057, "s": 3433, "text": "# Lemmatization process'''Words in the third person are changed to first person and verbs in past and future tenses are changed into the present by the lemmatization process. '''lemmatizer = WordNetLemmatizer()def tokenize_and_lemmatize(text): # tokenization to ensure that punctuation is caught as its own token tokens = [word.lower() for sent in nltk.sent_tokenize(text) for word in nltk.word_tokenize(sent)] filtered_tokens = [] for token in tokens: if re.search('[a-zA-Z]', token): filtered_tokens.append(token) lem = [lemmatizer.lemmatize(t) for t in filtered_tokens] return lem" }, { "code": null, "e": 4126, "s": 4057, "text": "With this matrix in hand, we can now build a machine learning model." }, { "code": null, "e": 4399, "s": 4126, "text": "# Defining a Count Vectorizer objectcount_vec = CountVectorizer(stop_words='english', max_features=10000)# Defining a TF-IDF Vectorizertfidf_vec = TfidfVectorizer(stop_words='english', ngram_range=(1, 2), tokenizer=tokenize_and_lemmatize, max_features=10000, use_idf=True)" }, { "code": null, "e": 4753, "s": 4399, "text": "There are various algorithms that can be used for text classification. Well, I started by exploring these models: Logistic Regression, Naive Bayes, Linear SVC, and Random Forest. My method was, choosing the best model to optimize, after running all my models in this section. Hence, I ran all the models with their default parameters to see the results." }, { "code": null, "e": 4905, "s": 4753, "text": "Here are the results of my classification models. The reason for the conflict between accuracy and f1 scores is there are multiple tags for an article." }, { "code": null, "e": 5070, "s": 4905, "text": "Machine Learning models failed to predict all the tags for an article. Still, f1 score is higher than accuracy because I set the average parameter of f1 to ‘micro’." }, { "code": null, "e": 5187, "s": 5070, "text": "I skipped to the optimization section following to evaluations of models. For that purpose, I used the GridSearchCV:" }, { "code": null, "e": 5461, "s": 5187, "text": "param = {'estimator__penalty':['l1', 'l2'], 'estimator__C':[0.001, 0.01, 1, 10]}# GridSearchCVkf=KFold(n_splits=10, shuffle=True, random_state=55)lr_grid = GridSearchCV(oneVsRest, param_grid = param, cv = kf, scoring='f1_micro', n_jobs=-1)lr_grid.fit(xtrain_tfidf, y_train)" }, { "code": null, "e": 5682, "s": 5461, "text": "I have chosen Logistic Regression for the Grid Search process because of the accuracy score, and as a result, I got an F1-score that has increased to %64,1. Here are some of the results of the optimized regression model:" }, { "code": null, "e": 5893, "s": 5682, "text": "I made two recommendation systems, first one is based on a summary and the other is based on a title, tags, and authors. To build a recommender, firstly I computed the cosine similarity on vectorized text data." }, { "code": null, "e": 6098, "s": 5893, "text": "# TfIdf matrix transformation on clean_summary columntfidf_matrix = tfidf_vec.fit_transform(arxivData['clean_summary'])# Compute the cosine similaritycosine_sim = linear_kernel(tfidf_matrix, tfidf_matrix)" }, { "code": null, "e": 6162, "s": 6098, "text": "Following the calculation, I wrote the recommendation function:" }, { "code": null, "e": 6581, "s": 6162, "text": "def get_recommendations(title, similarity): idx = indices[title] # pairwsie similarity scores sim_scores = list(enumerate(similarity[idx])) # sorting sim_scores = sorted(sim_scores, key=lambda x: x[1], reverse=True) sim_scores = sim_scores[1:11] article_indices = [i[0] for i in sim_scores] # Return the top 10 most related articles return arxivData[['link', 'title']].iloc[article_indices]" }, { "code": null, "e": 6726, "s": 6581, "text": "It gets two parameters and then sorts the articles via their cosine similarity values. Finally, It returns 10 most related articles as a result." }, { "code": null, "e": 6797, "s": 6726, "text": "We have learned the general approach to a basic level of NLP projects." }, { "code": null, "e": 6901, "s": 6797, "text": "We have learned that there are two common ways to preprocess our text data: Count and Tfidf Vectorizer." }, { "code": null, "e": 7041, "s": 6901, "text": "We saw that our classification models failed for a multi-class problem but when we evaluate f1 score as a success metric, we’re not so bad." }, { "code": null, "e": 7156, "s": 7041, "text": "The most written articles are from computer science studies and the most frequently used word is ‘neural network’." }, { "code": null, "e": 7229, "s": 7156, "text": "Finally, we learned how to use cosine similarity to build a recommender." }, { "code": null, "e": 7305, "s": 7229, "text": "As further work, I planned to do a Flask app to make my recommender online." }, { "code": null, "e": 7362, "s": 7305, "text": "Well, that’s all for now. See you soon in the next post!" } ]
Loop through a Set using Javascript
In the set that we implemented, we can create a for each function in our class and accept a callback that we can call on every element. Let's see how we can implement such a function − forEach(callback) { for (let prop in this.container) { callback(prop); } } You can test this using − const testSet = new MySet(); testSet.add(1); testSet.add(2); testSet.add(5); testSet.forEach(elem => console.log(`Element is ${elem}`)); This will give the output − Element is 1 Element is 2 Element is 5 The ES6 Set API also provides the same functionality using the forEach method.
[ { "code": null, "e": 1248, "s": 1062, "text": "In the set that we implemented, we can create a for each function in our class and accept a callback that we can call on every element. Let's see how we can implement such a function − " }, { "code": null, "e": 1335, "s": 1248, "text": "forEach(callback) {\n for (let prop in this.container) {\n callback(prop);\n }\n}" }, { "code": null, "e": 1362, "s": 1335, "text": "You can test this using − " }, { "code": null, "e": 1501, "s": 1362, "text": "const testSet = new MySet();\n\ntestSet.add(1);\ntestSet.add(2);\ntestSet.add(5);\n\ntestSet.forEach(elem => console.log(`Element is ${elem}`));" }, { "code": null, "e": 1529, "s": 1501, "text": "This will give the output −" }, { "code": null, "e": 1568, "s": 1529, "text": "Element is 1\nElement is 2\nElement is 5" }, { "code": null, "e": 1647, "s": 1568, "text": "The ES6 Set API also provides the same functionality using the forEach method." } ]
Procol Interview Experience
16 Sep, 2020 Procol visited our campus(virtually) in September for the campus hiring(SDE intern + FTE class of 2021). Round 1 Talent Decrypt online test: Total duration of 90 mins. The test consists of 2 sections:21 MCQ’s and 3 coding questions. MCQ’s were based on concepts of networking, operating systems, MySQL and oops. Coding questions 1 Minimum changes required to make all Array elements Prime. https://www.geeksforgeeks.org/minimum-changes-required-to-make-all-array-elements-prime/ Coding question 2 Basic String-based question Coding question 3 https://codeforces.com/blog/entry/67665 I was able to do 1 and 2 question completely and 3rd question partially (out of 3 test cases I got 2 passed). Out of 230 students, 23 were shortlisted. Round 2:(Technical Interview 1 Around 60 mins) Discussion about my projects and Internships. Ds Algo Questions 1. Find the square root of number up to given precision using binary search. https://www.geeksforgeeks.org/find-square-root-number-upto-given-precision-using-binary-search/ 2. Find the index of first 1 in an infinite sorted array of 0s and 1s https://www.geeksforgeeks.org/find-index-first-1-infinite-sorted-array-0s-1s/?ref=rp 3. Object-based question I was able to do 1st and 3rd in the most optimized way and 2nd partially. Database questions 1. What is normalization? 2. Explain any of the normal forms. (I explained first normal form) 3 What is 2nd normal form? Some basic Networking and Operating system questions Out of 23 students, 10 got shortlisted to next round. Round 3: It was a mix of both technical and HR round on google meet. Discussion about company, role and why are you suitable for this role? 2 coding questions were asked. [I was able to solve them completely using Hashing]. Out of 10 students, 5 got an offer from Procol. [Important point: Always read the job description carefully and do some research about the company. It will surely help you in your interviews] Marketing Procol Interview Experiences Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Google SWE Interview Experience (Google Online Coding Challenge) 2022 Amazon Interview Experience for SDE 1 Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022 Amazon Interview Experience SDE-2 (3 Years Experienced) Write It Up: Share Your Interview Experiences TCS Ninja Interview Experience (2020 batch) Amazon Interview Experience for SDE-1 Nagarro Interview Experience | On-Campus 2021 Nagarro Interview Experience Samsung RnD Coding Round Questions
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Sep, 2020" }, { "code": null, "e": 134, "s": 28, "text": "Procol visited our campus(virtually) in September for the campus hiring(SDE intern + FTE class of 2021). " }, { "code": null, "e": 197, "s": 134, "text": "Round 1 Talent Decrypt online test: Total duration of 90 mins." }, { "code": null, "e": 341, "s": 197, "text": "The test consists of 2 sections:21 MCQ’s and 3 coding questions. MCQ’s were based on concepts of networking, operating systems, MySQL and oops." }, { "code": null, "e": 360, "s": 341, "text": "Coding questions 1" }, { "code": null, "e": 419, "s": 360, "text": "Minimum changes required to make all Array elements Prime." }, { "code": null, "e": 508, "s": 419, "text": "https://www.geeksforgeeks.org/minimum-changes-required-to-make-all-array-elements-prime/" }, { "code": null, "e": 526, "s": 508, "text": "Coding question 2" }, { "code": null, "e": 554, "s": 526, "text": "Basic String-based question" }, { "code": null, "e": 572, "s": 554, "text": "Coding question 3" }, { "code": null, "e": 612, "s": 572, "text": "https://codeforces.com/blog/entry/67665" }, { "code": null, "e": 722, "s": 612, "text": "I was able to do 1 and 2 question completely and 3rd question partially (out of 3 test cases I got 2 passed)." }, { "code": null, "e": 764, "s": 722, "text": "Out of 230 students, 23 were shortlisted." }, { "code": null, "e": 811, "s": 764, "text": "Round 2:(Technical Interview 1 Around 60 mins)" }, { "code": null, "e": 857, "s": 811, "text": "Discussion about my projects and Internships." }, { "code": null, "e": 875, "s": 857, "text": "Ds Algo Questions" }, { "code": null, "e": 952, "s": 875, "text": "1. Find the square root of number up to given precision using binary search." }, { "code": null, "e": 1048, "s": 952, "text": "https://www.geeksforgeeks.org/find-square-root-number-upto-given-precision-using-binary-search/" }, { "code": null, "e": 1118, "s": 1048, "text": "2. Find the index of first 1 in an infinite sorted array of 0s and 1s" }, { "code": null, "e": 1203, "s": 1118, "text": "https://www.geeksforgeeks.org/find-index-first-1-infinite-sorted-array-0s-1s/?ref=rp" }, { "code": null, "e": 1228, "s": 1203, "text": "3. Object-based question" }, { "code": null, "e": 1302, "s": 1228, "text": "I was able to do 1st and 3rd in the most optimized way and 2nd partially." }, { "code": null, "e": 1321, "s": 1302, "text": "Database questions" }, { "code": null, "e": 1347, "s": 1321, "text": "1. What is normalization?" }, { "code": null, "e": 1415, "s": 1347, "text": "2. Explain any of the normal forms. (I explained first normal form)" }, { "code": null, "e": 1442, "s": 1415, "text": "3 What is 2nd normal form?" }, { "code": null, "e": 1495, "s": 1442, "text": "Some basic Networking and Operating system questions" }, { "code": null, "e": 1549, "s": 1495, "text": "Out of 23 students, 10 got shortlisted to next round." }, { "code": null, "e": 1558, "s": 1549, "text": "Round 3:" }, { "code": null, "e": 1618, "s": 1558, "text": "It was a mix of both technical and HR round on google meet." }, { "code": null, "e": 1691, "s": 1618, "text": "Discussion about company, role and why are you suitable for this role? " }, { "code": null, "e": 1775, "s": 1691, "text": "2 coding questions were asked. [I was able to solve them completely using Hashing]." }, { "code": null, "e": 1823, "s": 1775, "text": "Out of 10 students, 5 got an offer from Procol." }, { "code": null, "e": 1968, "s": 1823, "text": " [Important point: Always read the job description carefully and do some research about the company. It will surely help you in your interviews]" }, { "code": null, "e": 1978, "s": 1968, "text": "Marketing" }, { "code": null, "e": 1985, "s": 1978, "text": "Procol" }, { "code": null, "e": 2007, "s": 1985, "text": "Interview Experiences" }, { "code": null, "e": 2105, "s": 2007, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2175, "s": 2105, "text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022" }, { "code": null, "e": 2213, "s": 2175, "text": "Amazon Interview Experience for SDE 1" }, { "code": null, "e": 2286, "s": 2213, "text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022" }, { "code": null, "e": 2342, "s": 2286, "text": "Amazon Interview Experience SDE-2 (3 Years Experienced)" }, { "code": null, "e": 2388, "s": 2342, "text": "Write It Up: Share Your Interview Experiences" }, { "code": null, "e": 2432, "s": 2388, "text": "TCS Ninja Interview Experience (2020 batch)" }, { "code": null, "e": 2470, "s": 2432, "text": "Amazon Interview Experience for SDE-1" }, { "code": null, "e": 2516, "s": 2470, "text": "Nagarro Interview Experience | On-Campus 2021" }, { "code": null, "e": 2545, "s": 2516, "text": "Nagarro Interview Experience" } ]
Draw Line Segments between Particular Points in R Programming – segments() Function
19 Jun, 2020 segment() function in R Language is used to draw a line segment between to particular points. Syntax: segments(x0, y0, x1, y1) Parameters:x, y: coordinates to draw a line segment between provided points. Returns: a line segment between given points Example 1: To draw a single line segment # Create empty example plotplot(0, 0, col = "white", xlab = "", ylab = "") # Draw one linesegments(x0 = - 1, y0 = - 0.5, x1 = 0.5, y1 = 0, col = "darkgreen") Output: Here, x0 & y0 are starting points of the line segment and x1 & y1 are ending points of line segment . Example 2: Modifying color, thickness & line type # Create empty example plotplot(0, 0, col = "white", xlab = "", ylab = "") # Draw one line as in Example 1segments(x0 = - 1, y0 = - 1, x1 = 0.5, y1 = 0.5, # Color of line col = "darkgreen", # Thickness of line lwd = 5, # Line type lty = "dotted") Output: Example 3: Draw multiple line segments to R Plot. # Create empty example plotplot(0, 0, col = "white", xlab = "", ylab = "") # Create data frame with line-valuesmultiple_segments <- data.frame(x0 = c(0.1, 0.2, - 0.7, 0.4, - 0.8), y0 = c(0.8, 0.3, 0.5, - 0.4, 0.3), x1 = c(0, 0.4, 0.5, - 0.5, - 0.7), y1 = c(- 0.3, 0.4, - 0.5, - 0.7, 0.8)) # Draw multiple lines segments(x0 = multiple_segments$x0, y0 = multiple_segments$y0, x1 = multiple_segments$x1, y1 = multiple_segments$y1) Output: R-Graphs R-plots R-Statistics R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Joining of Dataframes in R Programming Control Statements in R Programming How to import an Excel File into R ? How to change Colors in ggplot2 Line Plot in R ? Normal Distribution in R
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jun, 2020" }, { "code": null, "e": 122, "s": 28, "text": "segment() function in R Language is used to draw a line segment between to particular points." }, { "code": null, "e": 155, "s": 122, "text": "Syntax: segments(x0, y0, x1, y1)" }, { "code": null, "e": 232, "s": 155, "text": "Parameters:x, y: coordinates to draw a line segment between provided points." }, { "code": null, "e": 277, "s": 232, "text": "Returns: a line segment between given points" }, { "code": null, "e": 318, "s": 277, "text": "Example 1: To draw a single line segment" }, { "code": "# Create empty example plotplot(0, 0, col = \"white\", xlab = \"\", ylab = \"\") # Draw one linesegments(x0 = - 1, y0 = - 0.5, x1 = 0.5, y1 = 0, col = \"darkgreen\") ", "e": 478, "s": 318, "text": null }, { "code": null, "e": 486, "s": 478, "text": "Output:" }, { "code": null, "e": 588, "s": 486, "text": "Here, x0 & y0 are starting points of the line segment and x1 & y1 are ending points of line segment ." }, { "code": null, "e": 639, "s": 588, "text": "Example 2: Modifying color, thickness & line type" }, { "code": "# Create empty example plotplot(0, 0, col = \"white\", xlab = \"\", ylab = \"\") # Draw one line as in Example 1segments(x0 = - 1, y0 = - 1, x1 = 0.5, y1 = 0.5, # Color of line col = \"darkgreen\", # Thickness of line lwd = 5, # Line type lty = \"dotted\") ", "e": 1011, "s": 639, "text": null }, { "code": null, "e": 1019, "s": 1011, "text": "Output:" }, { "code": null, "e": 1069, "s": 1019, "text": "Example 3: Draw multiple line segments to R Plot." }, { "code": "# Create empty example plotplot(0, 0, col = \"white\", xlab = \"\", ylab = \"\") # Create data frame with line-valuesmultiple_segments <- data.frame(x0 = c(0.1, 0.2, - 0.7, 0.4, - 0.8), y0 = c(0.8, 0.3, 0.5, - 0.4, 0.3), x1 = c(0, 0.4, 0.5, - 0.5, - 0.7), y1 = c(- 0.3, 0.4, - 0.5, - 0.7, 0.8)) # Draw multiple lines segments(x0 = multiple_segments$x0, y0 = multiple_segments$y0, x1 = multiple_segments$x1, y1 = multiple_segments$y1)", "e": 1665, "s": 1069, "text": null }, { "code": null, "e": 1673, "s": 1665, "text": "Output:" }, { "code": null, "e": 1682, "s": 1673, "text": "R-Graphs" }, { "code": null, "e": 1690, "s": 1682, "text": "R-plots" }, { "code": null, "e": 1703, "s": 1690, "text": "R-Statistics" }, { "code": null, "e": 1714, "s": 1703, "text": "R Language" }, { "code": null, "e": 1812, "s": 1714, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1847, "s": 1812, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1905, "s": 1847, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1954, "s": 1905, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2006, "s": 1954, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2044, "s": 2006, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2083, "s": 2044, "text": "Joining of Dataframes in R Programming" }, { "code": null, "e": 2119, "s": 2083, "text": "Control Statements in R Programming" }, { "code": null, "e": 2156, "s": 2119, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 2205, "s": 2156, "text": "How to change Colors in ggplot2 Line Plot in R ?" } ]
Namespace in C++ | Set 1 (Introduction)
22 Jun, 2022 Consider the following C++ program: CPP // A program to demonstrate need of namespaceint main(){ int value; value = 0; double value; // Error here value = 0.0;} Output : Compiler Error: 'value' has a previous declaration as 'int value' In each scope, a name can only represent one entity. So, there cannot be two variables with the same name in the same scope. Using namespaces, we can create two variables or member functions having the same name. CPP // Here we can see that more than one variables// are being used without reporting any error.// That is because they are declared in the// different namespaces and scopes.#include <iostream>using namespace std; // Variable created inside namespacenamespace first{ int val = 500;} // Global variableint val = 100; int main(){ // Local variable int val = 200; // These variables can be accessed from // outside the namespace using the scope // operator :: cout << first::val << '\n'; return 0;} Output: 500 Definition and Creation: Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names. Namespaces provide the space where we can define or declare identifiers i.e. names of variables, methods, classes, etc. Namespace is a feature added in C++ and is not present in C. A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it. Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope. A namespace definition begins with the keyword namespace followed by the namespace name as follows: namespace namespace_name { int x, y; // code declarations where // x and y are declared in // namespace_name's scope } Namespace declarations appear only at global scope. Namespace declarations can be nested within another namespace. Namespace declarations don’t have access specifiers (Public or Private). No need to give a semicolon after the closing brace of the definition of namespace. We can split the definition of namespace over several units. A namespace definition begins with the keyword namespace followed by the namespace name as follows:namespace namespace_name{ // code declarations i.e. variable (int a;) method (void add();) classes ( class student{};)} It is to be noted that there is no semicolon (;) after the closing brace.To call the namespace-enabled version of either a function or a variable, prepend the namespace name as follows: namespace_name: :code; // code could be a variable, function or class. C++ // Let us see how namespace scope the entities including variable and functions: #include <iostream>using namespace std; // first name spacenamespace first_space{ void func() { cout << "Inside first_space" << endl; }} // second name spacenamespace second_space{ void func() { cout << "Inside second_space" << endl; }} int main (){ // Calls function from first name space. first_space::func(); // Calls function from second name space. second_space::func(); return 0;} // If we compile and run above code, this would produce the following result:// Inside first_space// Inside second_space Inside first_space Inside second_space You can avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the following code: C++ #include <iostream>using namespace std; // first name spacenamespace first_space{ void func() { cout << "Inside first_space" << endl; }} // second name spacenamespace second_space{ void func() { cout << "Inside second_space" << endl; }} using namespace first_space; int main (){ // This calls function from first name space. func(); return 0;} // If we compile and run above code, this would produce the following result:// Inside first_space Inside first_space The using directive can also be used to refer to a particular item within a namespace. For example, if the only part of the std namespace that you intend to use is cout, you can refer to it as follows:using std::cout;Subsequent code can refer to cout without prepending the namespace, but other items in the std namespace will still need to be explicit as follows:#include <iostream>using std::cout; C++ #include <iostream>using namespace std; int main (){ cout << "std::endl is used with std!" << std::endl; return 0;} std::endl is used with std! Names introduced in a using directive obey normal scope rules, i.e., they are visible from the point the using directive occurs to the end of the scope in which the directive is found. Entities with the same name defined in an outer scope are hidden. C // Creating namespaces#include <iostream>using namespace std;namespace ns1{ int value() { return 5; }}namespace ns2{ const double x = 100; double value() { return 2*x; }} int main(){ // Access value function within ns1 cout << ns1::value() << '\n'; // Access value function within ns2 cout << ns2::value() << '\n'; // Access variable x directly cout << ns2::x << '\n'; return 0;} Output: 5 200 100 Classes and Namespace: The following is a simple way to create classes in a namespace: C++ // A C++ program to demonstrate use of class// in a namespace#include<iostream>using namespace std; namespace ns{ // A Class in a namespace class geek { public: void display() { cout<<"ns::geek::display()"<<endl;; } };} int main(){ // Creating Object of geek Class ns::geek obj; obj.display(); return 0;} ns::geek::display() Output: ns::geek::display() A class can also be declared inside namespace and defined outside namespace using the following syntax: CPP // A C++ program to demonstrate use of class// in a namespace#include <iostream>using namespace std; namespace ns{ // Only declaring class here class geek;} // Defining class outsideclass ns::geek{public: void display() { cout << "ns::geek::display()\n"; }}; int main(){ //Creating Object of geek Class ns::geek obj; obj.display(); return 0;} Output: ns::geek::display() We can define methods as well outside the namespace. The following is an example code: C // A C++ code to demonstrate that we can define// methods outside namespace.#include <iostream>using namespace std; // Creating a namespacenamespace ns{ void display(); class geek { public: void display(); };} // Defining methods of namespacevoid ns::geek::display(){ cout << "ns::geek::display()\n";}void ns::display(){ cout << "ns::display()\n";} // Driver codeint main(){ ns::geek obj; ns::display(); obj.display(); return 0;} Output: ns::display() ns::geek::display() Namespaces can be nested, i.e., you can define one namespace inside another namespace as follows: namespace namespace_name1 { // code declarations namespace namespace_name2 { // code declarations }} You can access the members of a nested namespace by using the resolution operator (::) as follows:// to access members of namespace_name2using namespace namespace_name1::namespace_name2;// to access members of namespace:name1using namespace namespace_name1;In the above statements, if you are using namespace_name1, then it will make the elements of namespace_name2 available in the scope as follows: C++ #include <iostream>using namespace std; // first name spacenamespace first_space{ void func() { cout << "Inside first_space" << endl; } // second name space namespace second_space { void func() { cout << "Inside second_space" << endl; } }}using namespace first_space::second_space;int main (){ // This calls function from second name space. func(); return 0;} // If we compile and run above code, this would produce the following result:// Inside second_space Inside second_space For example, you might be writing some code that has a function called xyz() and there is another library available in your code which also has the same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables, etc. with the same name available in different libraries. The best example of namespace scope is the C++ standard library (std), where all the classes, methods and templates are declared. Hence, while writing a C++ program, we usually include the directive using namespace std; namespace in C++ | Set 2 (Extending namespace and Unnamed namespace) Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing) Can namespaces be nested in C++? Reference: http://www.cplusplus.com/doc/tutorial/namespaces/ This article is contributed by Abhinav Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above MadhuriAgawane aditiyadav20102001 sriparnxnw7 cpp-namespaces C Language C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. std::sort() in C++ STL Bitwise Operators in C/C++ Substring in C++ Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc() Function Pointer in C Vector in C++ STL Map in C++ Standard Template Library (STL) Initialize a vector in C++ (7 different ways) std::sort() in C++ STL Bitwise Operators in C/C++
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 91, "s": 54, "text": "Consider the following C++ program: " }, { "code": null, "e": 95, "s": 91, "text": "CPP" }, { "code": "// A program to demonstrate need of namespaceint main(){ int value; value = 0; double value; // Error here value = 0.0;}", "e": 228, "s": 95, "text": null }, { "code": null, "e": 237, "s": 228, "text": "Output :" }, { "code": null, "e": 303, "s": 237, "text": "Compiler Error:\n'value' has a previous declaration as 'int value'" }, { "code": null, "e": 517, "s": 303, "text": "In each scope, a name can only represent one entity. So, there cannot be two variables with the same name in the same scope. Using namespaces, we can create two variables or member functions having the same name. " }, { "code": null, "e": 521, "s": 517, "text": "CPP" }, { "code": "// Here we can see that more than one variables// are being used without reporting any error.// That is because they are declared in the// different namespaces and scopes.#include <iostream>using namespace std; // Variable created inside namespacenamespace first{ int val = 500;} // Global variableint val = 100; int main(){ // Local variable int val = 200; // These variables can be accessed from // outside the namespace using the scope // operator :: cout << first::val << '\\n'; return 0;}", "e": 1040, "s": 521, "text": null }, { "code": null, "e": 1048, "s": 1040, "text": "Output:" }, { "code": null, "e": 1052, "s": 1048, "text": "500" }, { "code": null, "e": 1432, "s": 1052, "text": " Definition and Creation: Namespaces allow us to group named entities that otherwise would have global scope into narrower scopes, giving them namespace scope. This allows organizing the elements of programs into different logical scopes referred to by names. Namespaces provide the space where we can define or declare identifiers i.e. names of variables, methods, classes, etc." }, { "code": null, "e": 1493, "s": 1432, "text": "Namespace is a feature added in C++ and is not present in C." }, { "code": null, "e": 1646, "s": 1493, "text": "A namespace is a declarative region that provides a scope to the identifiers (names of functions, variables or other user-defined data types) inside it." }, { "code": null, "e": 1774, "s": 1646, "text": "Multiple namespace blocks with the same name are allowed. All declarations within those blocks are declared in the named scope." }, { "code": null, "e": 1874, "s": 1774, "text": "A namespace definition begins with the keyword namespace followed by the namespace name as follows:" }, { "code": null, "e": 2025, "s": 1874, "text": "namespace namespace_name \n{\n int x, y; // code declarations where \n // x and y are declared in \n // namespace_name's scope\n}" }, { "code": null, "e": 2077, "s": 2025, "text": "Namespace declarations appear only at global scope." }, { "code": null, "e": 2140, "s": 2077, "text": "Namespace declarations can be nested within another namespace." }, { "code": null, "e": 2213, "s": 2140, "text": "Namespace declarations don’t have access specifiers (Public or Private)." }, { "code": null, "e": 2297, "s": 2213, "text": "No need to give a semicolon after the closing brace of the definition of namespace." }, { "code": null, "e": 2358, "s": 2297, "text": "We can split the definition of namespace over several units." }, { "code": null, "e": 2591, "s": 2358, "text": "A namespace definition begins with the keyword namespace followed by the namespace name as follows:namespace namespace_name{ // code declarations i.e. variable (int a;) method (void add();) classes ( class student{};)}" }, { "code": null, "e": 2777, "s": 2591, "text": "It is to be noted that there is no semicolon (;) after the closing brace.To call the namespace-enabled version of either a function or a variable, prepend the namespace name as follows:" }, { "code": null, "e": 2849, "s": 2777, "text": "namespace_name: :code; // code could be a variable, function or class." }, { "code": null, "e": 2853, "s": 2849, "text": "C++" }, { "code": "// Let us see how namespace scope the entities including variable and functions: #include <iostream>using namespace std; // first name spacenamespace first_space{ void func() { cout << \"Inside first_space\" << endl; }} // second name spacenamespace second_space{ void func() { cout << \"Inside second_space\" << endl; }} int main (){ // Calls function from first name space. first_space::func(); // Calls function from second name space. second_space::func(); return 0;} // If we compile and run above code, this would produce the following result:// Inside first_space// Inside second_space", "e": 3476, "s": 2853, "text": null }, { "code": null, "e": 3515, "s": 3476, "text": "Inside first_space\nInside second_space" }, { "code": null, "e": 3754, "s": 3515, "text": "You can avoid prepending of namespaces with the using namespace directive. This directive tells the compiler that the subsequent code is making use of names in the specified namespace. The namespace is thus implied for the following code:" }, { "code": null, "e": 3758, "s": 3754, "text": "C++" }, { "code": "#include <iostream>using namespace std; // first name spacenamespace first_space{ void func() { cout << \"Inside first_space\" << endl; }} // second name spacenamespace second_space{ void func() { cout << \"Inside second_space\" << endl; }} using namespace first_space; int main (){ // This calls function from first name space. func(); return 0;} // If we compile and run above code, this would produce the following result:// Inside first_space", "e": 4230, "s": 3758, "text": null }, { "code": null, "e": 4249, "s": 4230, "text": "Inside first_space" }, { "code": null, "e": 4650, "s": 4249, "text": "The using directive can also be used to refer to a particular item within a namespace. For example, if the only part of the std namespace that you intend to use is cout, you can refer to it as follows:using std::cout;Subsequent code can refer to cout without prepending the namespace, but other items in the std namespace will still need to be explicit as follows:#include <iostream>using std::cout; " }, { "code": null, "e": 4654, "s": 4650, "text": "C++" }, { "code": "#include <iostream>using namespace std; int main (){ cout << \"std::endl is used with std!\" << std::endl; return 0;}", "e": 4778, "s": 4654, "text": null }, { "code": null, "e": 4806, "s": 4778, "text": "std::endl is used with std!" }, { "code": null, "e": 5057, "s": 4806, "text": "Names introduced in a using directive obey normal scope rules, i.e., they are visible from the point the using directive occurs to the end of the scope in which the directive is found. Entities with the same name defined in an outer scope are hidden." }, { "code": null, "e": 5059, "s": 5057, "text": "C" }, { "code": "// Creating namespaces#include <iostream>using namespace std;namespace ns1{ int value() { return 5; }}namespace ns2{ const double x = 100; double value() { return 2*x; }} int main(){ // Access value function within ns1 cout << ns1::value() << '\\n'; // Access value function within ns2 cout << ns2::value() << '\\n'; // Access variable x directly cout << ns2::x << '\\n'; return 0;}", "e": 5482, "s": 5059, "text": null }, { "code": null, "e": 5490, "s": 5482, "text": "Output:" }, { "code": null, "e": 5500, "s": 5490, "text": "5\n200\n100" }, { "code": null, "e": 5589, "s": 5500, "text": " Classes and Namespace: The following is a simple way to create classes in a namespace: " }, { "code": null, "e": 5593, "s": 5589, "text": "C++" }, { "code": "// A C++ program to demonstrate use of class// in a namespace#include<iostream>using namespace std; namespace ns{ // A Class in a namespace class geek { public: void display() { cout<<\"ns::geek::display()\"<<endl;; } };} int main(){ // Creating Object of geek Class ns::geek obj; obj.display(); return 0;}", "e": 5959, "s": 5593, "text": null }, { "code": null, "e": 5979, "s": 5959, "text": "ns::geek::display()" }, { "code": null, "e": 5987, "s": 5979, "text": "Output:" }, { "code": null, "e": 6007, "s": 5987, "text": "ns::geek::display()" }, { "code": null, "e": 6112, "s": 6007, "text": "A class can also be declared inside namespace and defined outside namespace using the following syntax: " }, { "code": null, "e": 6116, "s": 6112, "text": "CPP" }, { "code": "// A C++ program to demonstrate use of class// in a namespace#include <iostream>using namespace std; namespace ns{ // Only declaring class here class geek;} // Defining class outsideclass ns::geek{public: void display() { cout << \"ns::geek::display()\\n\"; }}; int main(){ //Creating Object of geek Class ns::geek obj; obj.display(); return 0;}", "e": 6493, "s": 6116, "text": null }, { "code": null, "e": 6501, "s": 6493, "text": "Output:" }, { "code": null, "e": 6521, "s": 6501, "text": "ns::geek::display()" }, { "code": null, "e": 6609, "s": 6521, "text": "We can define methods as well outside the namespace. The following is an example code: " }, { "code": null, "e": 6611, "s": 6609, "text": "C" }, { "code": "// A C++ code to demonstrate that we can define// methods outside namespace.#include <iostream>using namespace std; // Creating a namespacenamespace ns{ void display(); class geek { public: void display(); };} // Defining methods of namespacevoid ns::geek::display(){ cout << \"ns::geek::display()\\n\";}void ns::display(){ cout << \"ns::display()\\n\";} // Driver codeint main(){ ns::geek obj; ns::display(); obj.display(); return 0;}", "e": 7080, "s": 6611, "text": null }, { "code": null, "e": 7088, "s": 7080, "text": "Output:" }, { "code": null, "e": 7122, "s": 7088, "text": "ns::display()\nns::geek::display()" }, { "code": null, "e": 7220, "s": 7122, "text": "Namespaces can be nested, i.e., you can define one namespace inside another namespace as follows:" }, { "code": null, "e": 7328, "s": 7220, "text": "namespace namespace_name1 { // code declarations namespace namespace_name2 { // code declarations }}" }, { "code": null, "e": 7730, "s": 7328, "text": "You can access the members of a nested namespace by using the resolution operator (::) as follows:// to access members of namespace_name2using namespace namespace_name1::namespace_name2;// to access members of namespace:name1using namespace namespace_name1;In the above statements, if you are using namespace_name1, then it will make the elements of namespace_name2 available in the scope as follows: " }, { "code": null, "e": 7734, "s": 7730, "text": "C++" }, { "code": "#include <iostream>using namespace std; // first name spacenamespace first_space{ void func() { cout << \"Inside first_space\" << endl; } // second name space namespace second_space { void func() { cout << \"Inside second_space\" << endl; } }}using namespace first_space::second_space;int main (){ // This calls function from second name space. func(); return 0;} // If we compile and run above code, this would produce the following result:// Inside second_space", "e": 8248, "s": 7734, "text": null }, { "code": null, "e": 8268, "s": 8248, "text": "Inside second_space" }, { "code": null, "e": 8971, "s": 8268, "text": "For example, you might be writing some code that has a function called xyz() and there is another library available in your code which also has the same function xyz(). Now the compiler has no way of knowing which version of xyz() function you are referring to within your code.A namespace is designed to overcome this difficulty and is used as additional information to differentiate similar functions, classes, variables, etc. with the same name available in different libraries. The best example of namespace scope is the C++ standard library (std), where all the classes, methods and templates are declared. Hence, while writing a C++ program, we usually include the directive using namespace std; " }, { "code": null, "e": 9603, "s": 8971, "text": "namespace in C++ | Set 2 (Extending namespace and Unnamed namespace) Namespace in C++ | Set 3 (Accessing, creating header, nesting and aliasing) Can namespaces be nested in C++? Reference: http://www.cplusplus.com/doc/tutorial/namespaces/ This article is contributed by Abhinav Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 9618, "s": 9603, "text": "MadhuriAgawane" }, { "code": null, "e": 9637, "s": 9618, "text": "aditiyadav20102001" }, { "code": null, "e": 9649, "s": 9637, "text": "sriparnxnw7" }, { "code": null, "e": 9664, "s": 9649, "text": "cpp-namespaces" }, { "code": null, "e": 9675, "s": 9664, "text": "C Language" }, { "code": null, "e": 9679, "s": 9675, "text": "C++" }, { "code": null, "e": 9683, "s": 9679, "text": "CPP" }, { "code": null, "e": 9781, "s": 9683, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 9804, "s": 9781, "text": "std::sort() in C++ STL" }, { "code": null, "e": 9831, "s": 9804, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 9848, "s": 9831, "text": "Substring in C++" }, { "code": null, "e": 9926, "s": 9848, "text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()" }, { "code": null, "e": 9948, "s": 9926, "text": "Function Pointer in C" }, { "code": null, "e": 9966, "s": 9948, "text": "Vector in C++ STL" }, { "code": null, "e": 10009, "s": 9966, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 10055, "s": 10009, "text": "Initialize a vector in C++ (7 different ways)" }, { "code": null, "e": 10078, "s": 10055, "text": "std::sort() in C++ STL" } ]
How to check whether a form or a control is untouched or not in Angular 10 ?
24 May, 2021 In this article, we are going to check whether a form is untouched or not in Angular 10. untouched property is used to report that the control or the form is valid or not. Syntax: form.untouched Return Value: boolean: the boolean value to check whether a form is untouched or not. NgModule: Module used by the untouched property is: FormsModule Approach: Create the Angular app to be used. In app.component.html make a form using ngForm directive. In app.component.ts get the information using untouched property. Serve the angular app using ng serve to see the output. Example 1: app.component.ts import { Component } from '@angular/core';import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { form = new FormGroup({ name: new FormControl( ), rollno: new FormControl() }); get name(): any { return this.form.get('name');} onSubmit(): void { console.log("Form is untouched : ",this.form.untouched);}} app.component.html <br><form [formGroup]="form" (ngSubmit)="onSubmit()"> <input formControlName="name" placeholder="Name"> <br> <button type='submit'>Submit</button> <br> <br></form> Output: Reference: https://angular.io/api/forms/AbstractControlDirective#untouched Angular10 AngularJS-Basics AngularJS-Questions AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Routing in Angular 9/10 Angular PrimeNG Dropdown Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? How to create module with Routing in Angular 9 ? Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n24 May, 2021" }, { "code": null, "e": 200, "s": 28, "text": "In this article, we are going to check whether a form is untouched or not in Angular 10. untouched property is used to report that the control or the form is valid or not." }, { "code": null, "e": 208, "s": 200, "text": "Syntax:" }, { "code": null, "e": 223, "s": 208, "text": "form.untouched" }, { "code": null, "e": 237, "s": 223, "text": "Return Value:" }, { "code": null, "e": 309, "s": 237, "text": "boolean: the boolean value to check whether a form is untouched or not." }, { "code": null, "e": 361, "s": 309, "text": "NgModule: Module used by the untouched property is:" }, { "code": null, "e": 373, "s": 361, "text": "FormsModule" }, { "code": null, "e": 384, "s": 373, "text": "Approach: " }, { "code": null, "e": 419, "s": 384, "text": "Create the Angular app to be used." }, { "code": null, "e": 477, "s": 419, "text": "In app.component.html make a form using ngForm directive." }, { "code": null, "e": 543, "s": 477, "text": "In app.component.ts get the information using untouched property." }, { "code": null, "e": 599, "s": 543, "text": "Serve the angular app using ng serve to see the output." }, { "code": null, "e": 610, "s": 599, "text": "Example 1:" }, { "code": null, "e": 627, "s": 610, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';import { FormGroup, FormControl, FormArray, Validators } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css']})export class AppComponent { form = new FormGroup({ name: new FormControl( ), rollno: new FormControl() }); get name(): any { return this.form.get('name');} onSubmit(): void { console.log(\"Form is untouched : \",this.form.untouched);}}", "e": 1120, "s": 627, "text": null }, { "code": null, "e": 1139, "s": 1120, "text": "app.component.html" }, { "code": "<br><form [formGroup]=\"form\" (ngSubmit)=\"onSubmit()\"> <input formControlName=\"name\" placeholder=\"Name\"> <br> <button type='submit'>Submit</button> <br> <br></form>", "e": 1310, "s": 1139, "text": null }, { "code": null, "e": 1318, "s": 1310, "text": "Output:" }, { "code": null, "e": 1393, "s": 1318, "text": "Reference: https://angular.io/api/forms/AbstractControlDirective#untouched" }, { "code": null, "e": 1403, "s": 1393, "text": "Angular10" }, { "code": null, "e": 1420, "s": 1403, "text": "AngularJS-Basics" }, { "code": null, "e": 1440, "s": 1420, "text": "AngularJS-Questions" }, { "code": null, "e": 1450, "s": 1440, "text": "AngularJS" }, { "code": null, "e": 1467, "s": 1450, "text": "Web Technologies" }, { "code": null, "e": 1565, "s": 1467, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1589, "s": 1565, "text": "Routing in Angular 9/10" }, { "code": null, "e": 1624, "s": 1589, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 1648, "s": 1624, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 1701, "s": 1648, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 1750, "s": 1701, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 1783, "s": 1750, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 1845, "s": 1783, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1906, "s": 1845, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1956, "s": 1906, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Generate all passwords from given character set
24 Feb, 2022 Given a set of characters generate all possible passwords from them. This means we should generate all possible permutations of words using the given characters, with repetitions and also upto a given length. Examples: Input : arr[] = {a, b}, len = 2. Output : a b aa ab ba bb The solution is to use recursion on the given character array. The idea is to pass all possible lengths and an empty string initially to a helper function. In the helper function we keep appending all the characters one by one to the current string and recur to fill the remaining string till the desired length is reached.It can be better visualized using the below recursion tree: (a, b) / \ a b / \ / \ aa ab ba bb Following is the implementation of the above method. C++ Java Python 3 C# Javascript // C++ program to generate all passwords for given characters#include <bits/stdc++.h>using namespace std; // int cnt; // Recursive helper function, adds/removes characters// until len is reachedvoid generate(char* arr, int i, string s, int len){ // base case if (i == 0) // when len has been reached { // print it out cout << s << "\n"; // cnt++; return; } // iterate through the array for (int j = 0; j < len; j++) { // Create new string with next character // Call generate again until string has // reached its len string appended = s + arr[j]; generate(arr, i - 1, appended, len); } return;} // function to generate all possible passwordsvoid crack(char* arr, int len){ // call for all required lengths for (int i = 1; i <= len; i++) { generate(arr, i, "", len); }} // driver functionint main(){ char arr[] = { 'a', 'b', 'c' }; int len = sizeof(arr) / sizeof(arr[0]); crack(arr, len); //cout << cnt << endl; return 0;}// This code is contributed by Satish Srinivas. // Java program to generate all passwords for given charactersimport java.util.*; class GFG{ // int cnt; // Recursive helper function, adds/removes characters // until len is reached static void generate(char[] arr, int i, String s, int len) { // base case if (i == 0) // when len has been reached { // print it out System.out.println(s); // cnt++; return; } // iterate through the array for (int j = 0; j < len; j++) { // Create new string with next character // Call generate again until string has // reached its len String appended = s + arr[j]; generate(arr, i - 1, appended, len); } return; } // function to generate all possible passwords static void crack(char[] arr, int len) { // call for all required lengths for (int i = 1; i <= len; i++) { generate(arr, i, "", len); } } // Driver code public static void main(String[] args) { char arr[] = {'a', 'b', 'c'}; int len = arr.length; crack(arr, len); } } // This code has been contributed by 29AjayKumar # Python3 program to# generate all passwords# for given characters # Recursive helper function,# adds/removes characters# until len is reacheddef generate(arr, i, s, len): # base case if (i == 0): # when len has # been reached # print it out print(s) return # iterate through the array for j in range(0, len): # Create new string with # next character Call # generate again until # string has reached its len appended = s + arr[j] generate(arr, i - 1, appended, len) return # function to generate# all possible passwordsdef crack(arr, len): # call for all required lengths for i in range(1 , len + 1): generate(arr, i, "", len) # Driver Codearr = ['a', 'b', 'c' ]len = len(arr)crack(arr, len) # This code is contributed by Smita. // C# program to generate all passwords for given charactersusing System; class GFG{ // int cnt; // Recursive helper function, adds/removes characters // until len is reached static void generate(char[] arr, int i, String s, int len) { // base case if (i == 0) // when len has been reached { // print it out Console.WriteLine(s); // cnt++; return; } // iterate through the array for (int j = 0; j < len; j++) { // Create new string with next character // Call generate again until string has // reached its len String appended = s + arr[j]; generate(arr, i - 1, appended, len); } return; } // function to generate all possible passwords static void crack(char[] arr, int len) { // call for all required lengths for (int i = 1; i <= len; i++) { generate(arr, i, "", len); } } // Driver code public static void Main(String[] args) { char []arr = {'a', 'b', 'c'}; int len = arr.Length; crack(arr, len); } } /* This code contributed by PrinciRaj1992 */ <script>// JavaScript program to generate all passwords for given characters // let cnt; // Recursive helper function, adds/removes characters // until len is reached function generate(arr, i, s, len) { // base case if (i == 0) // when len has been reached { // print it out document.write(s + "<br/>"); // cnt++; return; } // iterate through the array for (let j = 0; j < len; j++) { // Create new string with next character // Call generate again until string has // reached its len let appended = s + arr[j]; generate(arr, i - 1, appended, len); } return; } // function to generate all possible passwords function crack(arr, len) { // call for all required lengths for (let i = 1; i <= len; i++) { generate(arr, i, "", len); } } // Driver Code let arr = ['a', 'b', 'c']; let len = arr.length; crack(arr, len); </script> Output: a b c aa ab ac ba bb bc ca cb cc aaa aab aac aba abb abc aca acb acc baa bab bac bba bbb bbc bca bcb bcc caa cab cac cba cbb cbc cca ccb ccc If we want to see the count of the words, we can uncomment the lines having cnt variable in the code. We can observe that it comes out to be , where n = len. Thus the time complexity of the program is also , hence exponential. We can also check for a particular password while generating and break the loop and return if it is found. We can also include other symbols to be generated and if needed remove duplicates by preprocessing the input using a HashTable.This article is contributed by Satish Srinivas. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Smitha Dinesh Semwal 29AjayKumar princiraj1992 susmitakundugoaldanga saurabh1990aror simranarora5sos Combinatorial Recursion Recursion Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count of subsets with sum equal to X Find the K-th Permutation Sequence of first N natural numbers Count Derangements (Permutation such that no element appears in its original position) Stack Permutations (Check if an array is stack permutation of other) Find the Number of Permutations that satisfy the given condition in an array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Recursion Program for Tower of Hanoi Backtracking | Introduction Print all subsequences of a string
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Feb, 2022" }, { "code": null, "e": 275, "s": 54, "text": "Given a set of characters generate all possible passwords from them. This means we should generate all possible permutations of words using the given characters, with repetitions and also upto a given length. Examples: " }, { "code": null, "e": 344, "s": 275, "text": "Input : arr[] = {a, b}, \n len = 2.\nOutput :\na b aa ab ba bb" }, { "code": null, "e": 730, "s": 346, "text": "The solution is to use recursion on the given character array. The idea is to pass all possible lengths and an empty string initially to a helper function. In the helper function we keep appending all the characters one by one to the current string and recur to fill the remaining string till the desired length is reached.It can be better visualized using the below recursion tree: " }, { "code": null, "e": 812, "s": 730, "text": " (a, b)\n / \\\n a b\n / \\ / \\\n aa ab ba bb" }, { "code": null, "e": 866, "s": 812, "text": "Following is the implementation of the above method. " }, { "code": null, "e": 870, "s": 866, "text": "C++" }, { "code": null, "e": 875, "s": 870, "text": "Java" }, { "code": null, "e": 884, "s": 875, "text": "Python 3" }, { "code": null, "e": 887, "s": 884, "text": "C#" }, { "code": null, "e": 898, "s": 887, "text": "Javascript" }, { "code": "// C++ program to generate all passwords for given characters#include <bits/stdc++.h>using namespace std; // int cnt; // Recursive helper function, adds/removes characters// until len is reachedvoid generate(char* arr, int i, string s, int len){ // base case if (i == 0) // when len has been reached { // print it out cout << s << \"\\n\"; // cnt++; return; } // iterate through the array for (int j = 0; j < len; j++) { // Create new string with next character // Call generate again until string has // reached its len string appended = s + arr[j]; generate(arr, i - 1, appended, len); } return;} // function to generate all possible passwordsvoid crack(char* arr, int len){ // call for all required lengths for (int i = 1; i <= len; i++) { generate(arr, i, \"\", len); }} // driver functionint main(){ char arr[] = { 'a', 'b', 'c' }; int len = sizeof(arr) / sizeof(arr[0]); crack(arr, len); //cout << cnt << endl; return 0;}// This code is contributed by Satish Srinivas.", "e": 1990, "s": 898, "text": null }, { "code": "// Java program to generate all passwords for given charactersimport java.util.*; class GFG{ // int cnt; // Recursive helper function, adds/removes characters // until len is reached static void generate(char[] arr, int i, String s, int len) { // base case if (i == 0) // when len has been reached { // print it out System.out.println(s); // cnt++; return; } // iterate through the array for (int j = 0; j < len; j++) { // Create new string with next character // Call generate again until string has // reached its len String appended = s + arr[j]; generate(arr, i - 1, appended, len); } return; } // function to generate all possible passwords static void crack(char[] arr, int len) { // call for all required lengths for (int i = 1; i <= len; i++) { generate(arr, i, \"\", len); } } // Driver code public static void main(String[] args) { char arr[] = {'a', 'b', 'c'}; int len = arr.length; crack(arr, len); } } // This code has been contributed by 29AjayKumar", "e": 3235, "s": 1990, "text": null }, { "code": "# Python3 program to# generate all passwords# for given characters # Recursive helper function,# adds/removes characters# until len is reacheddef generate(arr, i, s, len): # base case if (i == 0): # when len has # been reached # print it out print(s) return # iterate through the array for j in range(0, len): # Create new string with # next character Call # generate again until # string has reached its len appended = s + arr[j] generate(arr, i - 1, appended, len) return # function to generate# all possible passwordsdef crack(arr, len): # call for all required lengths for i in range(1 , len + 1): generate(arr, i, \"\", len) # Driver Codearr = ['a', 'b', 'c' ]len = len(arr)crack(arr, len) # This code is contributed by Smita.", "e": 4090, "s": 3235, "text": null }, { "code": "// C# program to generate all passwords for given charactersusing System; class GFG{ // int cnt; // Recursive helper function, adds/removes characters // until len is reached static void generate(char[] arr, int i, String s, int len) { // base case if (i == 0) // when len has been reached { // print it out Console.WriteLine(s); // cnt++; return; } // iterate through the array for (int j = 0; j < len; j++) { // Create new string with next character // Call generate again until string has // reached its len String appended = s + arr[j]; generate(arr, i - 1, appended, len); } return; } // function to generate all possible passwords static void crack(char[] arr, int len) { // call for all required lengths for (int i = 1; i <= len; i++) { generate(arr, i, \"\", len); } } // Driver code public static void Main(String[] args) { char []arr = {'a', 'b', 'c'}; int len = arr.Length; crack(arr, len); } } /* This code contributed by PrinciRaj1992 */", "e": 5326, "s": 4090, "text": null }, { "code": "<script>// JavaScript program to generate all passwords for given characters // let cnt; // Recursive helper function, adds/removes characters // until len is reached function generate(arr, i, s, len) { // base case if (i == 0) // when len has been reached { // print it out document.write(s + \"<br/>\"); // cnt++; return; } // iterate through the array for (let j = 0; j < len; j++) { // Create new string with next character // Call generate again until string has // reached its len let appended = s + arr[j]; generate(arr, i - 1, appended, len); } return; } // function to generate all possible passwords function crack(arr, len) { // call for all required lengths for (let i = 1; i <= len; i++) { generate(arr, i, \"\", len); } } // Driver Code let arr = ['a', 'b', 'c']; let len = arr.length; crack(arr, len); </script>", "e": 6448, "s": 5326, "text": null }, { "code": null, "e": 6458, "s": 6448, "text": "Output: " }, { "code": null, "e": 6599, "s": 6458, "text": "a\nb\nc\naa\nab\nac\nba\nbb\nbc\nca\ncb\ncc\naaa\naab\naac\naba\nabb\nabc\naca\nacb\nacc\nbaa\nbab\nbac\nbba\nbbb\nbbc\nbca\nbcb\nbcc\ncaa\ncab\ncac\ncba\ncbb\ncbc\ncca\nccb\nccc" }, { "code": null, "e": 7484, "s": 6599, "text": "If we want to see the count of the words, we can uncomment the lines having cnt variable in the code. We can observe that it comes out to be , where n = len. Thus the time complexity of the program is also , hence exponential. We can also check for a particular password while generating and break the loop and return if it is found. We can also include other symbols to be generated and if needed remove duplicates by preprocessing the input using a HashTable.This article is contributed by Satish Srinivas. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 7505, "s": 7484, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 7517, "s": 7505, "text": "29AjayKumar" }, { "code": null, "e": 7531, "s": 7517, "text": "princiraj1992" }, { "code": null, "e": 7553, "s": 7531, "text": "susmitakundugoaldanga" }, { "code": null, "e": 7569, "s": 7553, "text": "saurabh1990aror" }, { "code": null, "e": 7585, "s": 7569, "text": "simranarora5sos" }, { "code": null, "e": 7599, "s": 7585, "text": "Combinatorial" }, { "code": null, "e": 7609, "s": 7599, "text": "Recursion" }, { "code": null, "e": 7619, "s": 7609, "text": "Recursion" }, { "code": null, "e": 7633, "s": 7619, "text": "Combinatorial" }, { "code": null, "e": 7731, "s": 7633, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7768, "s": 7731, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 7830, "s": 7768, "text": "Find the K-th Permutation Sequence of first N natural numbers" }, { "code": null, "e": 7917, "s": 7830, "text": "Count Derangements (Permutation such that no element appears in its original position)" }, { "code": null, "e": 7986, "s": 7917, "text": "Stack Permutations (Check if an array is stack permutation of other)" }, { "code": null, "e": 8063, "s": 7986, "text": "Find the Number of Permutations that satisfy the given condition in an array" }, { "code": null, "e": 8148, "s": 8063, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 8158, "s": 8148, "text": "Recursion" }, { "code": null, "e": 8185, "s": 8158, "text": "Program for Tower of Hanoi" }, { "code": null, "e": 8213, "s": 8185, "text": "Backtracking | Introduction" } ]
SAP ABAP - Reading Internal Tables
We can read the lines of a table by using the following syntax of the READ TABLE statement − READ TABLE <internal_table> FROM <work_area_itab>. In this syntax, the <work_area_itab> expression represents a work area that is compatible with the line type of the <internal_table> table. We can specify a search key, but not a table key, within the READ statement by using the WITH KEY clause, as shown in the following syntax − READ TABLE <internal_table> WITH KEY = <internal_tab_field>. Here the entire line of the internal table is used as a search key. The content of the entire line of the table is compared with the content of the <internal_tab_field> field. If the values of the <internal_tab_field> field are not compatible with the line type of the table, these values are converted according to the line type of the table. The search key allows you to find entries in internal tables that do not have a structured line type, that is, where the line is a single field or an internal table type. The following syntax of the READ statement is used to specify a work area or field symbol by using the COMPARING clause − READ TABLE <internal_table> <key> INTO <work_area_itab> [COMPARING <F1> <F2>...<Fn>]. When the COMPARING clause is used, the specified table fields <F1>, <F2>....<Fn> of the structured line type are compared with the corresponding fields of the work area before being transported. If the ALL FIELDS clause is specified, the SAP system compares all the components. When the SAP system finds an entry on the basis of a key, the value of the SY-SUBRC variable is set to 0. In addition, the value of the SY-SUBRC variable is set to 2 or 4 if the content of the compared fields is not the same or if the SAP system cannot find an entry. However, the SAP system copies the entry into the target work area whenever it finds an entry, regardless of the result of the comparison. REPORT ZREAD_DEMO. */Creating an internal table DATA: BEGIN OF Record1, ColP TYPE I, ColQ TYPE I, END OF Record1. DATA mytable LIKE HASHED TABLE OF Record1 WITH UNIQUE KEY ColP. DO 6 Times. Record1-ColP = SY-INDEX. Record1-ColQ = SY-INDEX + 5. INSERT Record1 INTO TABLE mytable. ENDDO. Record1-ColP = 4. Record1-ColQ = 12. READ TABLE mytable FROM Record1 INTO Record1 COMPARING ColQ. WRITE: 'SY-SUBRC =', SY-SUBRC. SKIP. WRITE: / Record1-ColP, Record1-ColQ. The above code produces the following output − SY-SUBRC = 2 4 9 In the above example, mytable is an internal table of the hashed table type, with Record1 as the work area and ColP as the unique key. Initially, mytable is populated with six lines, where the ColP field contains the values of the SY-INDEX variable and the ColQ field contains (SY-INDEX + 5) values. The Record1 work area is populated with 4 and 12 as values for the ColP and ColQ fields respectively. The READ statement reads the line of the table after comparing the value of the ColP key field with the value in the Record1 work area by using the COMPARING clause, and then copies the content of the read line in the work area. The value of the SY-SUBRC variable is displayed as 2 because when the value in the ColP field is 4, the value in the ColQ is not 12, but 9.
[ { "code": null, "e": 3125, "s": 3032, "text": "We can read the lines of a table by using the following syntax of the READ TABLE statement −" }, { "code": null, "e": 3177, "s": 3125, "text": "READ TABLE <internal_table> FROM <work_area_itab>.\n" }, { "code": null, "e": 3458, "s": 3177, "text": "In this syntax, the <work_area_itab> expression represents a work area that is compatible with the line type of the <internal_table> table. We can specify a search key, but not a table key, within the READ statement by using the WITH KEY clause, as shown in the following syntax −" }, { "code": null, "e": 3520, "s": 3458, "text": "READ TABLE <internal_table> WITH KEY = <internal_tab_field>.\n" }, { "code": null, "e": 4035, "s": 3520, "text": "Here the entire line of the internal table is used as a search key. The content of the entire line of the table is compared with the content of the <internal_tab_field> field. If the values of the <internal_tab_field> field are not compatible with the line type of the table, these values are converted according to the line type of the table. The search key allows you to find entries in internal tables that do not have a structured line type, that is, where the line is a single field or an internal table type." }, { "code": null, "e": 4157, "s": 4035, "text": "The following syntax of the READ statement is used to specify a work area or field symbol by using the COMPARING clause −" }, { "code": null, "e": 4247, "s": 4157, "text": "READ TABLE <internal_table> <key> INTO <work_area_itab>\n [COMPARING <F1> <F2>...<Fn>].\n" }, { "code": null, "e": 4932, "s": 4247, "text": "When the COMPARING clause is used, the specified table fields <F1>, <F2>....<Fn> of the structured line type are compared with the corresponding fields of the work area before being transported. If the ALL FIELDS clause is specified, the SAP system compares all the components. When the SAP system finds an entry on the basis of a key, the value of the SY-SUBRC variable is set to 0. In addition, the value of the SY-SUBRC variable is set to 2 or 4 if the content of the compared fields is not the same or if the SAP system cannot find an entry. However, the SAP system copies the entry into the target work area whenever it finds an entry, regardless of the result of the comparison." }, { "code": null, "e": 5410, "s": 4932, "text": "REPORT ZREAD_DEMO. \n*/Creating an internal table \nDATA: BEGIN OF Record1, \nColP TYPE I, \nColQ TYPE I, \nEND OF Record1. \n\nDATA mytable LIKE HASHED TABLE OF Record1 WITH UNIQUE KEY ColP. \nDO 6 Times.\nRecord1-ColP = SY-INDEX. \nRecord1-ColQ = SY-INDEX + 5. \nINSERT Record1 INTO TABLE mytable. \nENDDO. \n\nRecord1-ColP = 4. \nRecord1-ColQ = 12. \nREAD TABLE mytable FROM Record1 INTO Record1 COMPARING ColQ. \n\nWRITE: 'SY-SUBRC =', SY-SUBRC. \nSKIP. \nWRITE: / Record1-ColP, Record1-ColQ." }, { "code": null, "e": 5457, "s": 5410, "text": "The above code produces the following output −" }, { "code": null, "e": 5488, "s": 5457, "text": "SY-SUBRC = 2 \n\n4 9\n" }, { "code": null, "e": 5788, "s": 5488, "text": "In the above example, mytable is an internal table of the hashed table type, with Record1 as the work area and ColP as the unique key. Initially, mytable is populated with six lines, where the ColP field contains the values of the SY-INDEX variable and the ColQ field contains (SY-INDEX + 5) values." } ]
Violation of constraints in relational database
10 May, 2020 Here, we will learn about the violations that can occur on a database as a result of any changes made in the relation. There are mainly three operations that have the ability to change the state of relations, these modifications are given below: Insert –To insert new tuples in a relation in the database.Delete –To delete some of the existing relation on the database.Update (Modify) –To make changes in the value of some existing tuples. Insert –To insert new tuples in a relation in the database. Delete –To delete some of the existing relation on the database. Update (Modify) –To make changes in the value of some existing tuples. Whenever we apply the above modification to the relation in the database, the constraints on the relational database should not get violated.Insert operation:On inserting the tuples in the relation, it may cause violation of the constraints in the following way:1. Domain constraint :Domain constraint gets violated only when a given value to the attribute does not appear in the corresponding domain or in case it is not of the appropriate datatype.Example:Assume that the domain constraint says that all the values you insert in the relation should be greater than 10, and in case you insert a value less than 10 will cause you violation of the domain constraint, so gets rejected.2. Entity Integrity constraint :On inserting NULL values to any part of the primary key of a new tuple in the relation can cause violation of the Entity integrity constraint.Example:Insert (NULL, ‘Bikash, ‘M’, ‘Jaipur’, ‘123456’) into EMP The above insertion violates the entity integrity constraint since there is NULL for theprimary key EID, it is not allowed, so it gets rejected.3. Key Constraints :On inserting a value in the new tuple of a relation which is already existing in another tuple of the same relation, can cause violation of Key Constraints.Example:Insert (’1200’, ‘Arjun’, ‘9976657777’, ‘Mumbai’) into EMPLOYEE This insertion violates the key constraint if EID=1200 is already present in some tuple in the same relation, so it gets rejected.Referential integrity :On inserting a value in the foreign key of relation 1, for which there is no corresponding value in the Primary key which is referred to in relation 2, in such case Referential integrity is violated.Example:When we try to insert a value say 1200 in EID (foreign key) of table 1, for which there is no corresponding EID (primary key) of table 2, then it causes violation, so gets rejected. Insert operation:On inserting the tuples in the relation, it may cause violation of the constraints in the following way: 1. Domain constraint :Domain constraint gets violated only when a given value to the attribute does not appear in the corresponding domain or in case it is not of the appropriate datatype. Example:Assume that the domain constraint says that all the values you insert in the relation should be greater than 10, and in case you insert a value less than 10 will cause you violation of the domain constraint, so gets rejected. 2. Entity Integrity constraint :On inserting NULL values to any part of the primary key of a new tuple in the relation can cause violation of the Entity integrity constraint. Example: Insert (NULL, ‘Bikash, ‘M’, ‘Jaipur’, ‘123456’) into EMP The above insertion violates the entity integrity constraint since there is NULL for theprimary key EID, it is not allowed, so it gets rejected. 3. Key Constraints :On inserting a value in the new tuple of a relation which is already existing in another tuple of the same relation, can cause violation of Key Constraints. Example: Insert (’1200’, ‘Arjun’, ‘9976657777’, ‘Mumbai’) into EMPLOYEE This insertion violates the key constraint if EID=1200 is already present in some tuple in the same relation, so it gets rejected. Referential integrity :On inserting a value in the foreign key of relation 1, for which there is no corresponding value in the Primary key which is referred to in relation 2, in such case Referential integrity is violated. Example:When we try to insert a value say 1200 in EID (foreign key) of table 1, for which there is no corresponding EID (primary key) of table 2, then it causes violation, so gets rejected. Solution that is possible to correct such violation is if any insertion violates any of the constraints, then the default action is to reject such operation. Deletion operation:On deleting the tuples in the relation, it may cause only violation of Referential integrity constraints. Referential Integrity Constraints :It causes violation only if the tuple in relation 1 is deleted which is referenced by foreign key from other tuples of table 2 in the database, if such deletion takes place then the values in the tuple of the foreign key in table 2 will become empty, which will eventually violate Referential Integrity constraint. Referential Integrity Constraints :It causes violation only if the tuple in relation 1 is deleted which is referenced by foreign key from other tuples of table 2 in the database, if such deletion takes place then the values in the tuple of the foreign key in table 2 will become empty, which will eventually violate Referential Integrity constraint. Solutions that are possible to correct the violation to the referential integrity due to deletion are listed below: Restrict –Here we reject the deletion.Cascade –Here if a record in the parent table(referencing relation) is deleted, then the corresponding records in the child table(referenced relation) will automatically be deleted.Set null or set default –Here we modify the referencing attribute values that cause violation and we either set NULL or change to another valid value Restrict –Here we reject the deletion. Cascade –Here if a record in the parent table(referencing relation) is deleted, then the corresponding records in the child table(referenced relation) will automatically be deleted. Set null or set default –Here we modify the referencing attribute values that cause violation and we either set NULL or change to another valid value DBMS GATE CS DBMS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Functional dependencies in DBMS Difference between OLAP and OLTP in DBMS MySQL | Regular expressions (Regexp) What is Temporary Table in SQL? Difference between Where and Having Clause in SQL Layers of OSI Model TCP/IP Model Types of Operating Systems Page Replacement Algorithms in Operating Systems Inter Process Communication (IPC)
[ { "code": null, "e": 52, "s": 24, "text": "\n10 May, 2020" }, { "code": null, "e": 171, "s": 52, "text": "Here, we will learn about the violations that can occur on a database as a result of any changes made in the relation." }, { "code": null, "e": 298, "s": 171, "text": "There are mainly three operations that have the ability to change the state of relations, these modifications are given below:" }, { "code": null, "e": 492, "s": 298, "text": "Insert –To insert new tuples in a relation in the database.Delete –To delete some of the existing relation on the database.Update (Modify) –To make changes in the value of some existing tuples." }, { "code": null, "e": 552, "s": 492, "text": "Insert –To insert new tuples in a relation in the database." }, { "code": null, "e": 617, "s": 552, "text": "Delete –To delete some of the existing relation on the database." }, { "code": null, "e": 688, "s": 617, "text": "Update (Modify) –To make changes in the value of some existing tuples." }, { "code": null, "e": 2543, "s": 688, "text": "Whenever we apply the above modification to the relation in the database, the constraints on the relational database should not get violated.Insert operation:On inserting the tuples in the relation, it may cause violation of the constraints in the following way:1. Domain constraint :Domain constraint gets violated only when a given value to the attribute does not appear in the corresponding domain or in case it is not of the appropriate datatype.Example:Assume that the domain constraint says that all the values you insert in the relation should be greater than 10, and in case you insert a value less than 10 will cause you violation of the domain constraint, so gets rejected.2. Entity Integrity constraint :On inserting NULL values to any part of the primary key of a new tuple in the relation can cause violation of the Entity integrity constraint.Example:Insert (NULL, ‘Bikash, ‘M’, ‘Jaipur’, ‘123456’) into EMP The above insertion violates the entity integrity constraint since there is NULL for theprimary key EID, it is not allowed, so it gets rejected.3. Key Constraints :On inserting a value in the new tuple of a relation which is already existing in another tuple of the same relation, can cause violation of Key Constraints.Example:Insert (’1200’, ‘Arjun’, ‘9976657777’, ‘Mumbai’) into EMPLOYEE This insertion violates the key constraint if EID=1200 is already present in some tuple in the same relation, so it gets rejected.Referential integrity :On inserting a value in the foreign key of relation 1, for which there is no corresponding value in the Primary key which is referred to in relation 2, in such case Referential integrity is violated.Example:When we try to insert a value say 1200 in EID (foreign key) of table 1, for which there is no corresponding EID (primary key) of table 2, then it causes violation, so gets rejected." }, { "code": null, "e": 2665, "s": 2543, "text": "Insert operation:On inserting the tuples in the relation, it may cause violation of the constraints in the following way:" }, { "code": null, "e": 2854, "s": 2665, "text": "1. Domain constraint :Domain constraint gets violated only when a given value to the attribute does not appear in the corresponding domain or in case it is not of the appropriate datatype." }, { "code": null, "e": 3088, "s": 2854, "text": "Example:Assume that the domain constraint says that all the values you insert in the relation should be greater than 10, and in case you insert a value less than 10 will cause you violation of the domain constraint, so gets rejected." }, { "code": null, "e": 3263, "s": 3088, "text": "2. Entity Integrity constraint :On inserting NULL values to any part of the primary key of a new tuple in the relation can cause violation of the Entity integrity constraint." }, { "code": null, "e": 3272, "s": 3263, "text": "Example:" }, { "code": null, "e": 3330, "s": 3272, "text": "Insert (NULL, ‘Bikash, ‘M’, ‘Jaipur’, ‘123456’) into EMP " }, { "code": null, "e": 3475, "s": 3330, "text": "The above insertion violates the entity integrity constraint since there is NULL for theprimary key EID, it is not allowed, so it gets rejected." }, { "code": null, "e": 3652, "s": 3475, "text": "3. Key Constraints :On inserting a value in the new tuple of a relation which is already existing in another tuple of the same relation, can cause violation of Key Constraints." }, { "code": null, "e": 3661, "s": 3652, "text": "Example:" }, { "code": null, "e": 3725, "s": 3661, "text": "Insert (’1200’, ‘Arjun’, ‘9976657777’, ‘Mumbai’) into EMPLOYEE " }, { "code": null, "e": 3856, "s": 3725, "text": "This insertion violates the key constraint if EID=1200 is already present in some tuple in the same relation, so it gets rejected." }, { "code": null, "e": 4079, "s": 3856, "text": "Referential integrity :On inserting a value in the foreign key of relation 1, for which there is no corresponding value in the Primary key which is referred to in relation 2, in such case Referential integrity is violated." }, { "code": null, "e": 4269, "s": 4079, "text": "Example:When we try to insert a value say 1200 in EID (foreign key) of table 1, for which there is no corresponding EID (primary key) of table 2, then it causes violation, so gets rejected." }, { "code": null, "e": 4427, "s": 4269, "text": "Solution that is possible to correct such violation is if any insertion violates any of the constraints, then the default action is to reject such operation." }, { "code": null, "e": 4552, "s": 4427, "text": "Deletion operation:On deleting the tuples in the relation, it may cause only violation of Referential integrity constraints." }, { "code": null, "e": 4902, "s": 4552, "text": "Referential Integrity Constraints :It causes violation only if the tuple in relation 1 is deleted which is referenced by foreign key from other tuples of table 2 in the database, if such deletion takes place then the values in the tuple of the foreign key in table 2 will become empty, which will eventually violate Referential Integrity constraint." }, { "code": null, "e": 5252, "s": 4902, "text": "Referential Integrity Constraints :It causes violation only if the tuple in relation 1 is deleted which is referenced by foreign key from other tuples of table 2 in the database, if such deletion takes place then the values in the tuple of the foreign key in table 2 will become empty, which will eventually violate Referential Integrity constraint." }, { "code": null, "e": 5368, "s": 5252, "text": "Solutions that are possible to correct the violation to the referential integrity due to deletion are listed below:" }, { "code": null, "e": 5737, "s": 5368, "text": "Restrict –Here we reject the deletion.Cascade –Here if a record in the parent table(referencing relation) is deleted, then the corresponding records in the child table(referenced relation) will automatically be deleted.Set null or set default –Here we modify the referencing attribute values that cause violation and we either set NULL or change to another valid value" }, { "code": null, "e": 5776, "s": 5737, "text": "Restrict –Here we reject the deletion." }, { "code": null, "e": 5958, "s": 5776, "text": "Cascade –Here if a record in the parent table(referencing relation) is deleted, then the corresponding records in the child table(referenced relation) will automatically be deleted." }, { "code": null, "e": 6108, "s": 5958, "text": "Set null or set default –Here we modify the referencing attribute values that cause violation and we either set NULL or change to another valid value" }, { "code": null, "e": 6113, "s": 6108, "text": "DBMS" }, { "code": null, "e": 6121, "s": 6113, "text": "GATE CS" }, { "code": null, "e": 6126, "s": 6121, "text": "DBMS" }, { "code": null, "e": 6224, "s": 6126, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6265, "s": 6224, "text": "Types of Functional dependencies in DBMS" }, { "code": null, "e": 6306, "s": 6265, "text": "Difference between OLAP and OLTP in DBMS" }, { "code": null, "e": 6343, "s": 6306, "text": "MySQL | Regular expressions (Regexp)" }, { "code": null, "e": 6375, "s": 6343, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 6425, "s": 6375, "text": "Difference between Where and Having Clause in SQL" }, { "code": null, "e": 6445, "s": 6425, "text": "Layers of OSI Model" }, { "code": null, "e": 6458, "s": 6445, "text": "TCP/IP Model" }, { "code": null, "e": 6485, "s": 6458, "text": "Types of Operating Systems" }, { "code": null, "e": 6534, "s": 6485, "text": "Page Replacement Algorithms in Operating Systems" } ]
Working with JAR and Manifest files In Java
11 May, 2017 Prerequisite – JAR file format Whenever a developer wants to distribute a version of his software, then all he want is to distribute a single file and not a directory structure filled with class files. JAR files were designed for this purpose. A JAR file can contain both class files and other file types like sound and image files which may be included in the project. All the files in a JAR file are compressed using a format similar to zip. Creating a JAR file – more Options A jar file is created using jar tool. The general command looks somewhat like this: jar options jar-file [manifest-file] file1 file2 file3 ... jar – file : name of jar file on which you want to use jar tool. file1, file2, file3 : files which you want to add inside a jar file. manifest-file is the name of file which contains manifest of that jar file, giving manifest-file as an argument is entirely optional. c : Creates a new or empty archive and adds files to it. If any of the specified file name are directories, then the jar program processes them recursively. C : Temporarily changes the directory. e : Creates an entry point in the manifest. f : Specifies the JAR file name as the second command-line argument. If this parameter is missing, jar will write the result to standard output (when creating a JAR file)or read it from standard input(when extracting or tabulating a JAR file). i : Creates an index file. m : Adds a manifest file to the JAR file. A manifest is a description of the archive contents and origin. Every archive has a default manifest, but you can supply your own if you want to authenticate the contents of the archive. M : Does not create a manifest file for the entries. t : Displays the table of contents. u : Updates an existing JAR file. v : Generates verbose output. x : Extract files. If you supply one or more file names, only those files are extracted Otherwise, all files are extracted. 0 : Stores without zip compression. The options of jar command are almost similar to that of UNIX tar command. In windows you can also get help about various options of jar command just by typing jar in cmd and then pressing enter, the output will be somewhat similar to this: Example : For creating a JAR file which have two classes server.class and client.class and a Jpeg image logo.jpeg, one need to write following command : jar cvf chat.jar server.class client.class logo.jpeg The output of above command will be somewhat like this: It’s a better practice to use -v option along with jar command as you will get to know how the things are going on. Manifest File Each JAR file contains a manifest file that describe the features of the archive. Each JAR file have a manifest file by default. Default manifest file is named as MANIFEST.MF and is present in the META-INF subdirectory of archive. Although the default manifest file contains just two entries, but complex manifest files can have way more. Here, is what a default manifest file looks like – The entries of manifest files are grouped into sections. Each section have two entries section name and its value. We will see a bit later how these sections can really help us in controlling the properties of our archive. Manifest file can also be updated by using the m option of jar command. But there are certain things which need to kept in mind while updating manifest file otherwise you may get the following creepy message. java.io.IOException: invalid manifest format Things to keep in mind while handling Manifest files: You should leave space between the name and value of any section in manifest file, like Version:1.1 is in valid section instead write Version: 1.1 that space between colon and 1.1 really matters a lot.While specifying the main class you should not add .class extension at the end of class name. Simply specify the main class by typing:Main-Class: Classname(I’ll be briefing about Main-Class section very shortly).You must add newline at the end of file. You need not to write \n for specifying newline instead just leave the last line of your manifest file blank that will serve the purpose.Text file for manifest must use UTF-8 encoding otherwise you may get into some trouble. You should leave space between the name and value of any section in manifest file, like Version:1.1 is in valid section instead write Version: 1.1 that space between colon and 1.1 really matters a lot. While specifying the main class you should not add .class extension at the end of class name. Simply specify the main class by typing:Main-Class: Classname(I’ll be briefing about Main-Class section very shortly). Main-Class: Classname (I’ll be briefing about Main-Class section very shortly). You must add newline at the end of file. You need not to write \n for specifying newline instead just leave the last line of your manifest file blank that will serve the purpose. Text file for manifest must use UTF-8 encoding otherwise you may get into some trouble. Example: Now let’s come back and update the contents of our chat.jar archive. To update the manifest file we simply need to write the following command: jar uvfm chat.jar manifest.txt Here manifest.txt is the new manifest file, which has following contents: The output of above command will be somewhat like this: Here we are getting two warnings because we are trying to overwrite to previously present entries. Executable Jar Files You can use the e option of jar command to specify the entry point of your program, ie. class which you normally want to invoke when launching your Java application. Example: To create chat.jar file having client class as main class you need to write following command – jar cvfe chat.jar client client.class server.class logo.jpeg The output of above command will be somewhat like this: Remember not to add .class extension after the name of class which you want to set main class. Alternatively you can add a Main-Class entry in the manifest file and then update it. For the above example you just need to add this entry: Main-Class: client With main class being set one can simply run a jar program by writing following command – java -jar chat.jar Depending on operating system configuration, users may even be able to launch application by double clicking the JAR file icon. Package Sealing Finally, we are going to discuss about package sealing in Java. We can seal a package in Java to ensure that no further classes can add themselves to it. You may want to seal a package if you use a package visible classes, methods and fields in your code. Without package sealing, other classes can add themselves to the same package and thereby gain access to package visible features. To achieve package sealing all one need to do is to put all classes of that package into a JAR file. By default the packages in a jar file are not sealed but one can change the global default by adding few lines in manifest file. Let’s again consider the case of our chat.jar archive, now the package of classes client.class and server.class is application and we want to seal this package all we need to do is to add following line in the manifest file and update it. Name: application Sealed: true Name: application Sealed: true This is all from my side on how to work with JAR files. Stay Tuned!!This article is contributed by Abhey Rana(UselessCoder). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 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 Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java
[ { "code": null, "e": 52, "s": 24, "text": "\n11 May, 2017" }, { "code": null, "e": 83, "s": 52, "text": "Prerequisite – JAR file format" }, { "code": null, "e": 496, "s": 83, "text": "Whenever a developer wants to distribute a version of his software, then all he want is to distribute a single file and not a directory structure filled with class files. JAR files were designed for this purpose. A JAR file can contain both class files and other file types like sound and image files which may be included in the project. All the files in a JAR file are compressed using a format similar to zip." }, { "code": null, "e": 532, "s": 496, "text": "Creating a JAR file – more Options" }, { "code": null, "e": 616, "s": 532, "text": "A jar file is created using jar tool. The general command looks somewhat like this:" }, { "code": null, "e": 676, "s": 616, "text": " jar options jar-file [manifest-file] file1 file2 file3 ..." }, { "code": null, "e": 741, "s": 676, "text": "jar – file : name of jar file on which you want to use jar tool." }, { "code": null, "e": 944, "s": 741, "text": "file1, file2, file3 : files which you want to add inside a jar file. manifest-file is the name of file which contains manifest of that jar file, giving manifest-file as an argument is entirely optional." }, { "code": null, "e": 1101, "s": 944, "text": "c : Creates a new or empty archive and adds files to it. If any of the specified file name are directories, then the jar program processes them recursively." }, { "code": null, "e": 1140, "s": 1101, "text": "C : Temporarily changes the directory." }, { "code": null, "e": 1184, "s": 1140, "text": "e : Creates an entry point in the manifest." }, { "code": null, "e": 1428, "s": 1184, "text": "f : Specifies the JAR file name as the second command-line argument. If this parameter is missing, jar will write the result to standard output (when creating a JAR file)or read it from standard input(when extracting or tabulating a JAR file)." }, { "code": null, "e": 1455, "s": 1428, "text": "i : Creates an index file." }, { "code": null, "e": 1684, "s": 1455, "text": "m : Adds a manifest file to the JAR file. A manifest is a description of the archive contents and origin. Every archive has a default manifest, but you can supply your own if you want to authenticate the contents of the archive." }, { "code": null, "e": 1737, "s": 1684, "text": "M : Does not create a manifest file for the entries." }, { "code": null, "e": 1773, "s": 1737, "text": "t : Displays the table of contents." }, { "code": null, "e": 1807, "s": 1773, "text": "u : Updates an existing JAR file." }, { "code": null, "e": 1837, "s": 1807, "text": "v : Generates verbose output." }, { "code": null, "e": 1961, "s": 1837, "text": "x : Extract files. If you supply one or more file names, only those files are extracted Otherwise, all files are extracted." }, { "code": null, "e": 1997, "s": 1961, "text": "0 : Stores without zip compression." }, { "code": null, "e": 2238, "s": 1997, "text": "The options of jar command are almost similar to that of UNIX tar command. In windows you can also get help about various options of jar command just by typing jar in cmd and then pressing enter, the output will be somewhat similar to this:" }, { "code": null, "e": 2248, "s": 2238, "text": "Example :" }, { "code": null, "e": 2391, "s": 2248, "text": "For creating a JAR file which have two classes server.class and client.class and a Jpeg image logo.jpeg, one need to write following command :" }, { "code": null, "e": 2445, "s": 2391, "text": " jar cvf chat.jar server.class client.class logo.jpeg" }, { "code": null, "e": 2501, "s": 2445, "text": "The output of above command will be somewhat like this:" }, { "code": null, "e": 2617, "s": 2501, "text": "It’s a better practice to use -v option along with jar command as you will get to know how the things are going on." }, { "code": null, "e": 2631, "s": 2617, "text": "Manifest File" }, { "code": null, "e": 3021, "s": 2631, "text": "Each JAR file contains a manifest file that describe the features of the archive. Each JAR file have a manifest file by default. Default manifest file is named as MANIFEST.MF and is present in the META-INF subdirectory of archive. Although the default manifest file contains just two entries, but complex manifest files can have way more. Here, is what a default manifest file looks like –" }, { "code": null, "e": 3453, "s": 3021, "text": "The entries of manifest files are grouped into sections. Each section have two entries section name and its value. We will see a bit later how these sections can really help us in controlling the properties of our archive. Manifest file can also be updated by using the m option of jar command. But there are certain things which need to kept in mind while updating manifest file otherwise you may get the following creepy message." }, { "code": null, "e": 3499, "s": 3453, "text": " java.io.IOException: invalid manifest format" }, { "code": null, "e": 3553, "s": 3499, "text": "Things to keep in mind while handling Manifest files:" }, { "code": null, "e": 4232, "s": 3553, "text": "You should leave space between the name and value of any section in manifest file, like Version:1.1 is in valid section instead write Version: 1.1 that space between colon and 1.1 really matters a lot.While specifying the main class you should not add .class extension at the end of class name. Simply specify the main class by typing:Main-Class: Classname(I’ll be briefing about Main-Class section very shortly).You must add newline at the end of file. You need not to write \\n for specifying newline instead just leave the last line of your manifest file blank that will serve the purpose.Text file for manifest must use UTF-8 encoding otherwise you may get into some trouble." }, { "code": null, "e": 4434, "s": 4232, "text": "You should leave space between the name and value of any section in manifest file, like Version:1.1 is in valid section instead write Version: 1.1 that space between colon and 1.1 really matters a lot." }, { "code": null, "e": 4647, "s": 4434, "text": "While specifying the main class you should not add .class extension at the end of class name. Simply specify the main class by typing:Main-Class: Classname(I’ll be briefing about Main-Class section very shortly)." }, { "code": null, "e": 4669, "s": 4647, "text": "Main-Class: Classname" }, { "code": null, "e": 4727, "s": 4669, "text": "(I’ll be briefing about Main-Class section very shortly)." }, { "code": null, "e": 4906, "s": 4727, "text": "You must add newline at the end of file. You need not to write \\n for specifying newline instead just leave the last line of your manifest file blank that will serve the purpose." }, { "code": null, "e": 4994, "s": 4906, "text": "Text file for manifest must use UTF-8 encoding otherwise you may get into some trouble." }, { "code": null, "e": 5003, "s": 4994, "text": "Example:" }, { "code": null, "e": 5147, "s": 5003, "text": "Now let’s come back and update the contents of our chat.jar archive. To update the manifest file we simply need to write the following command:" }, { "code": null, "e": 5179, "s": 5147, "text": " jar uvfm chat.jar manifest.txt" }, { "code": null, "e": 5253, "s": 5179, "text": "Here manifest.txt is the new manifest file, which has following contents:" }, { "code": null, "e": 5309, "s": 5253, "text": "The output of above command will be somewhat like this:" }, { "code": null, "e": 5408, "s": 5309, "text": "Here we are getting two warnings because we are trying to overwrite to previously present entries." }, { "code": null, "e": 5429, "s": 5408, "text": "Executable Jar Files" }, { "code": null, "e": 5595, "s": 5429, "text": "You can use the e option of jar command to specify the entry point of your program, ie. class which you normally want to invoke when launching your Java application." }, { "code": null, "e": 5604, "s": 5595, "text": "Example:" }, { "code": null, "e": 5700, "s": 5604, "text": "To create chat.jar file having client class as main class you need to write following command –" }, { "code": null, "e": 5762, "s": 5700, "text": " jar cvfe chat.jar client client.class server.class logo.jpeg" }, { "code": null, "e": 5818, "s": 5762, "text": "The output of above command will be somewhat like this:" }, { "code": null, "e": 5913, "s": 5818, "text": "Remember not to add .class extension after the name of class which you want to set main class." }, { "code": null, "e": 6054, "s": 5913, "text": "Alternatively you can add a Main-Class entry in the manifest file and then update it. For the above example you just need to add this entry:" }, { "code": null, "e": 6074, "s": 6054, "text": " Main-Class: client" }, { "code": null, "e": 6164, "s": 6074, "text": "With main class being set one can simply run a jar program by writing following command –" }, { "code": null, "e": 6184, "s": 6164, "text": " java -jar chat.jar" }, { "code": null, "e": 6312, "s": 6184, "text": "Depending on operating system configuration, users may even be able to launch application by double clicking the JAR file icon." }, { "code": null, "e": 6328, "s": 6312, "text": "Package Sealing" }, { "code": null, "e": 6715, "s": 6328, "text": "Finally, we are going to discuss about package sealing in Java. We can seal a package in Java to ensure that no further classes can add themselves to it. You may want to seal a package if you use a package visible classes, methods and fields in your code. Without package sealing, other classes can add themselves to the same package and thereby gain access to package visible features." }, { "code": null, "e": 6816, "s": 6715, "text": "To achieve package sealing all one need to do is to put all classes of that package into a JAR file." }, { "code": null, "e": 6945, "s": 6816, "text": "By default the packages in a jar file are not sealed but one can change the global default by adding few lines in manifest file." }, { "code": null, "e": 7215, "s": 6945, "text": "Let’s again consider the case of our chat.jar archive, now the package of classes client.class and server.class is application and we want to seal this package all we need to do is to add following line in the manifest file and update it. Name: application\nSealed: true" }, { "code": null, "e": 7247, "s": 7215, "text": " Name: application\nSealed: true" }, { "code": null, "e": 7627, "s": 7247, "text": "This is all from my side on how to work with JAR files. Stay Tuned!!This article is contributed by Abhey Rana(UselessCoder). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 7752, "s": 7627, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7757, "s": 7752, "text": "Java" }, { "code": null, "e": 7762, "s": 7757, "text": "Java" }, { "code": null, "e": 7860, "s": 7762, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7911, "s": 7860, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 7942, "s": 7911, "text": "How to iterate any Map in Java" }, { "code": null, "e": 7961, "s": 7942, "text": "Interfaces in Java" }, { "code": null, "e": 7991, "s": 7961, "text": "HashMap in Java with Examples" }, { "code": null, "e": 8006, "s": 7991, "text": "Stream In Java" }, { "code": null, "e": 8026, "s": 8006, "text": "Collections in Java" }, { "code": null, "e": 8050, "s": 8026, "text": "Singleton Class in Java" }, { "code": null, "e": 8082, "s": 8050, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 8094, "s": 8082, "text": "Set in Java" } ]
Structure of Input-Output Interface
07 Aug, 2020 The block diagram of an Input-Output Interface unit contain the following blocks : 1. Data Bus Buffer 2. Read/Write Control Logic 3. Port A, Port B register 4. Control and Status register These are explained as following below. Data Bus Buffer :The bus buffer use bi-directional data bus to communicate with CPU. All control word data and status information between interface unit and CPU are transferred through data bus. Port A and Port B :Port A and Port B are used to transfer data between Input-Output device and Interface Unit. Each port consist of bi-directional data input buffer and bi-directional data output buffer. Interface unit connect directly with an input device and output disk or with device that require both input and output through Port A and Port B i.e. modem, external hard-drive, magnetic disk. Control and Status Register :CPU gives control information to control register on basis of control information. Interface unit control input and output operation between CPU and input-output device. Bits which are present in status register are used for checking of status conditions. Status register indicate status of data register, port A, port B and also record error that may be occur during transfer of data. Read/Write Control Logic :This block generates necessary control signals for overall device operations. All commands from CPU are accepted through this block. It also allow status of interface unit to be transferred onto data bus through this block accept CS, read and write control signal from system bus and S0 , S1 from system address bus. Read and Write signal are used to define direction of data transfer over data bus. Read Operation: CPU <---- I/O device Write Operation: CPU ----> I/O device The read signal direct data transfer from interface unit to CPU and write signal direct data transfer from CPU to interface unit through data bus. Address bus is used to select to interface unit. Two least significant lines of address bus ( A0 , A1 ) are connected to select lines S0, S1. This two select input lines are used to select any one of four registers in interface unit. The selection of interface unit is according to the following criteria : Read state : Selection of Interface unit Write State : Example : If S0, S1 = 0 1, then Port B data register is selected for data transfer between CPU and I/O device. If S0, S1 = 1 0, then Control register is selected and store the control information send by the CPU. Computer Organization & Architecture Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Direct Access Media (DMA) Controller in Computer Architecture Architecture of 8085 microprocessor Pin diagram of 8086 microprocessor Control Characters I2C Communication Protocol Pin diagram of 8085 microprocessor Difference between SRAM and DRAM Computer Organization | Different Instruction Cycles Computer Architecture | Flynn's taxonomy Difference between RISC and CISC processor | Set 2
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Aug, 2020" }, { "code": null, "e": 137, "s": 54, "text": "The block diagram of an Input-Output Interface unit contain the following blocks :" }, { "code": null, "e": 243, "s": 137, "text": "1. Data Bus Buffer\n2. Read/Write Control Logic\n3. Port A, Port B register\n4. Control and Status register " }, { "code": null, "e": 283, "s": 243, "text": "These are explained as following below." }, { "code": null, "e": 478, "s": 283, "text": "Data Bus Buffer :The bus buffer use bi-directional data bus to communicate with CPU. All control word data and status information between interface unit and CPU are transferred through data bus." }, { "code": null, "e": 875, "s": 478, "text": "Port A and Port B :Port A and Port B are used to transfer data between Input-Output device and Interface Unit. Each port consist of bi-directional data input buffer and bi-directional data output buffer. Interface unit connect directly with an input device and output disk or with device that require both input and output through Port A and Port B i.e. modem, external hard-drive, magnetic disk." }, { "code": null, "e": 1290, "s": 875, "text": "Control and Status Register :CPU gives control information to control register on basis of control information. Interface unit control input and output operation between CPU and input-output device. Bits which are present in status register are used for checking of status conditions. Status register indicate status of data register, port A, port B and also record error that may be occur during transfer of data." }, { "code": null, "e": 1716, "s": 1290, "text": "Read/Write Control Logic :This block generates necessary control signals for overall device operations. All commands from CPU are accepted through this block. It also allow status of interface unit to be transferred onto data bus through this block accept CS, read and write control signal from system bus and S0 , S1 from system address bus. Read and Write signal are used to define direction of data transfer over data bus." }, { "code": null, "e": 1792, "s": 1716, "text": "Read Operation: CPU <---- I/O device\nWrite Operation: CPU ----> I/O device\n" }, { "code": null, "e": 1939, "s": 1792, "text": "The read signal direct data transfer from interface unit to CPU and write signal direct data transfer from CPU to interface unit through data bus." }, { "code": null, "e": 2246, "s": 1939, "text": "Address bus is used to select to interface unit. Two least significant lines of address bus ( A0 , A1 ) are connected to select lines S0, S1. This two select input lines are used to select any one of four registers in interface unit. The selection of interface unit is according to the following criteria :" }, { "code": null, "e": 2259, "s": 2246, "text": "Read state :" }, { "code": null, "e": 2273, "s": 2259, "text": "Selection of " }, { "code": null, "e": 2288, "s": 2273, "text": "Interface unit" }, { "code": null, "e": 2302, "s": 2288, "text": "Write State :" }, { "code": null, "e": 2312, "s": 2302, "text": "Example :" }, { "code": null, "e": 2413, "s": 2312, "text": "If S0, S1 = 0 1, then Port B data register is selected for data transfer between CPU and I/O device." }, { "code": null, "e": 2515, "s": 2413, "text": "If S0, S1 = 1 0, then Control register is selected and store the control information send by the CPU." }, { "code": null, "e": 2552, "s": 2515, "text": "Computer Organization & Architecture" }, { "code": null, "e": 2650, "s": 2552, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2712, "s": 2650, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 2748, "s": 2712, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 2783, "s": 2748, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 2802, "s": 2783, "text": "Control Characters" }, { "code": null, "e": 2829, "s": 2802, "text": "I2C Communication Protocol" }, { "code": null, "e": 2864, "s": 2829, "text": "Pin diagram of 8085 microprocessor" }, { "code": null, "e": 2897, "s": 2864, "text": "Difference between SRAM and DRAM" }, { "code": null, "e": 2950, "s": 2897, "text": "Computer Organization | Different Instruction Cycles" }, { "code": null, "e": 2991, "s": 2950, "text": "Computer Architecture | Flynn's taxonomy" } ]
Time Complexity and Space Complexity
24 May, 2022 Generally, there is always more than one way to solve a problem in computer science with different algorithms. Therefore, it is highly required to use a method to compare the solutions in order to judge which one is more optimal. The method must be: Independent of the machine and its configuration, on which the algorithm is running on. Shows a direct correlation with the number of inputs. Can distinguish two algorithms clearly without ambiguity. There are two such methods used, time complexity and space complexity which are discussed below: Time Complexity: The time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the input. Note that the time to run is a function of the length of the input and not the actual execution time of the machine on which the algorithm is running on. In order to calculate time complexity on an algorithm, it is assumed that a constant time c is taken to execute one operation, and then the total operations for an input length on N are calculated. Consider an example to understand the process of calculation: Suppose a problem is to find whether a pair (X, Y) exists in an array, A of N elements whose sum is Z. The simplest idea is to consider every pair and check if it satisfies the given condition or not. The pseudo-code is as follows: int a[n]; for(int i = 0;i < n;i++) cin >> a[i] for(int i = 0;i < n;i++) for(int j = 0;j < n;j++) if(i!=j && a[i]+a[j] == z) return true return false Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find a pair in the given// array whose sum is equal to zbool findPair(int a[], int n, int z){ // Iterate through all the pairs for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) // Check if the sum of the pair // (a[i], a[j]) is equal to z if (i != j && a[i] + a[j] == z) return true; return false;} // Driver Codeint main(){ // Given Input int a[] = { 1, -2, 1, 0, 5 }; int z = 0; int n = sizeof(a) / sizeof(a[0]); // Function Call if (findPair(a, n, z)) cout << "True"; else cout << "False"; return 0;} // Java program for the above approachimport java.lang.*;import java.util.*; class GFG{ // Function to find a pair in the given// array whose sum is equal to zstatic boolean findPair(int a[], int n, int z){ // Iterate through all the pairs for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) // Check if the sum of the pair // (a[i], a[j]) is equal to z if (i != j && a[i] + a[j] == z) return true; return false;} // Driver codepublic static void main(String[] args){ // Given Input int a[] = { 1, -2, 1, 0, 5 }; int z = 0; int n = a.length; // Function Call if (findPair(a, n, z)) System.out.println("True"); else System.out.println("False");}} // This code is contributed by avijitmondal1998 # Python3 program for the above approach # Function to find a pair in the given# array whose sum is equal to zdef findPair(a, n, z) : # Iterate through all the pairs for i in range(n) : for j in range(n) : # Check if the sum of the pair # (a[i], a[j]) is equal to z if (i != j and a[i] + a[j] == z) : return True return False # Driver Code # Given Inputa = [ 1, -2, 1, 0, 5 ]z = 0n = len(a) # Function Callif (findPair(a, n, z)) : print("True")else : print("False") # This code is contributed by splevel62. // C# program for above approachusing System; class GFG{ // Function to find a pair in the given// array whose sum is equal to zstatic bool findPair(int[] a, int n, int z){ // Iterate through all the pairs for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) // Check if the sum of the pair // (a[i], a[j]) is equal to z if (i != j && a[i] + a[j] == z) return true; return false;} // Driver Codestatic void Main(){ // Given Input int[] a = { 1, -2, 1, 0, 5 }; int z = 0; int n = a.Length; // Function Call if (findPair(a, n, z)) Console.WriteLine("True"); else Console.WriteLine("False");}} // This code is contributed by sanjoy_62. <script> // JavaScript program for the above approach // Function to find a pair in the given// array whose sum is equal to zfunction findPair(a, n, z){ // Iterate through all the pairs for(let i = 0; i < n; i++) for(let j = 0; j < n; j++) // Check if the sum of the pair // (a[i], a[j]) is equal to z if (i != j && a[i] + a[j] == z) return true; return false;} // Driver Code // Given Inputlet a = [ 1, -2, 1, 0, 5 ];let z = 0;let n = a.length; // Function Callif (findPair(a, n, z)) document.write("True");else document.write("False"); // This code is contributed by code_hunt </script> False Assuming that each of the operations in the computer takes approximately constant time, let it be c. The number of lines of code executed actually depends on the value of Z. During analyses of the algorithm, mostly the worst-case scenario is considered, i.e., when there is no pair of elements with sum equals Z. In the worst case, N*c operations are required for input. The outer loop i loop runs N times. For each i, the inner loop j loop runs N times. So total execution time is N*c + N*N*c + c. Now ignore the lower order terms since the lower order terms are relatively insignificant for large input, therefore only the highest order term is taken (without constant) which is N*N in this case. Different notations are used to describe the limiting behavior of a function, but since the worst case is taken so big-O notation will be used to represent the time complexity. Hence, the time complexity is O(N2) for the above algorithm. Note that the time complexity is solely based on the number of elements in array A i.e the input length, so if the length of the array will increase the time of execution will also increase. Order of growth is how the time of execution depends on the length of the input. In the above example, it is clearly evident that the time of execution quadratically depends on the length of the array. Order of growth will help to compute the running time with ease. Another Example: Let’s calculate the time complexity of the below algorithm: C++ Java Python3 C# Javascript count = 0for (int i = N; i > 0; i /= 2) for (int j = 0; j < i; j++) count++; int count = 0 ;for (int i = N; i > 0; i /= 2) for (int j = 0; j < i; j++) count++; //This code is contributed by Shubham Singh count = 0i = Nwhile(i > 0): for j in range(i): count+=1 i /= 2 # This code is contributed by subhamsingh10 int count = 0 ;for (int i = N; i > 0; i /= 2) for (int j = 0; j < i; j++) count++; // This code is contributed by Shubham Singh let count = 0for(let i = N; i > 0; i /= 2) for(let j = 0; j < i; j++) count += 1; // This code is contributed by Shubham Singh This is a tricky case. In the first look, it seems like the complexity is O(N * log N). N for the j′s loop and log(N) for i′s loop. But it’s wrong. Let’s see why. Think about how many times count++ will run. When i = N, it will run N times. When i = N / 2, it will run N / 2 times. When i = N / 4, it will run N / 4 times. And so on. The total number of times count++ will run is N + N/2 + N/4+...+1= 2 * N. So the time complexity will be O(N). Some general time complexities are listed below with the input range for which they are accepted in competitive programming: Usually type of solutions 10 -12 O(N!) Recursion and backtracking 15-18 O(2N * N) Recursion, backtracking, and bit manipulation 18-22 O(2N * N) Recursion, backtracking, and bit manipulation 30-40 Meet in the middle, Divide and Conquer 100 O(N4) Dynamic programming, Constructive 400 O(N3) Dynamic programming, Constructive 2K O(N2* log N) Dynamic programming, Binary Search, Sorting, Divide and Conquer 10K O(N2) Dynamic programming, Graph, Trees, Constructive 1M O(N* log N) Sorting, Binary Search, Divide and Conquer 100M O(N), O(log N), O(1) Constructive, Mathematical, Greedy Algorithms Space Complexity: The space complexity of an algorithm quantifies the amount of space taken by an algorithm to run as a function of the length of the input. Consider an example: Suppose a problem to find the frequency of array elements. The pseudo-code is as follows: int freq[n]; int a[n]; for(int i = 0; i<n; i++) { cin>>a[i]; freq[a[i]]++; } Below is the implementation of the above approach: C++ Java Python3 Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count frequencies of array itemsvoid countFreq(int arr[], int n){ unordered_map<int, int> freq; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) freq[arr[i]]++; // Traverse through map and print frequencies for (auto x : freq) cout << x.first << " " << x.second << endl;} // Driver Codeint main(){ // Given array int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call countFreq(arr, n); return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to count frequencies of array items static void countFreq(int arr[], int n) { HashMap<Integer,Integer> freq = new HashMap<>(); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { if(freq.containsKey(arr[i])){ freq.put(arr[i], freq.get(arr[i])+1); } else{ freq.put(arr[i], 1); } } // Traverse through map and print frequencies for (Map.Entry<Integer,Integer> x : freq.entrySet()) System.out.print(x.getKey()+ " " + x.getValue() +"\n"); } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.length; // Function Call countFreq(arr, n); }} // This code is contributed by gauravrajput1 # Python program for the above approach # Function to count frequencies of array itemsdef countFreq(arr, n): freq = dict() # Traverse through array elements and # count frequencies for i in arr: if i not in freq: freq[i] = 0 freq[i]+=1 # Traverse through map and print frequencies for x in freq: print(x, freq[x]) # Driver Code # Given arrayarr = [10, 20, 20, 10, 10, 20, 5, 20 ]n = len(arr) # Function CallcountFreq(arr, n) # This code is contributed by Shubham Singh <script>// Javascript program for the above approach // Function to count frequencies of array itemsfunction countFreq(arr, n) { let freq = new Map(); arr.sort((a, b) => a - b) // Traverse through array elements and // count frequencies for (let i = 0; i < n; i++) { if (freq.has(arr[i])) { freq.set(arr[i], freq.get(arr[i]) + 1) } else { freq.set(arr[i], 1) } } // Traverse through map and print frequencies for (let x of freq) document.write(x[0] + " " + x[1] + "<br>");} // Driver Code // Given arraylet arr = [10, 20, 20, 10, 10, 20, 5, 20];let n = arr.length; // Function CallcountFreq(arr, n); // This code is contributed by Saurabh Jaiswal</script> 5 1 10 3 20 4 Here two arrays of length N, and variable i are used in the algorithm so, the total space used is N * c + N * c + 1 * c = 2N * c + c, where c is a unit space taken. For many inputs, constant c is insignificant, and it can be said that the space complexity is O(N). There is also auxiliary space, which is different from space complexity. The main difference is where space complexity quantifies the total space used by the algorithm, auxiliary space quantifies the extra space that is used in the algorithm apart from the given input. In the above example, the auxiliary space is the space used by the freq[] array because that is not part of the given input. So total auxiliary space is N * c + c which is O(N) only. avijitmondal1998 sanjoy_62 code_hunt splevel62 akankshasrivastava3120 SHUBHAMSINGH10 surinderdawra388 GauravRajput1 _saurabh_jaiswal time complexity Analysis Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n24 May, 2022" }, { "code": null, "e": 304, "s": 54, "text": "Generally, there is always more than one way to solve a problem in computer science with different algorithms. Therefore, it is highly required to use a method to compare the solutions in order to judge which one is more optimal. The method must be:" }, { "code": null, "e": 392, "s": 304, "text": "Independent of the machine and its configuration, on which the algorithm is running on." }, { "code": null, "e": 446, "s": 392, "text": "Shows a direct correlation with the number of inputs." }, { "code": null, "e": 504, "s": 446, "text": "Can distinguish two algorithms clearly without ambiguity." }, { "code": null, "e": 601, "s": 504, "text": "There are two such methods used, time complexity and space complexity which are discussed below:" }, { "code": null, "e": 909, "s": 601, "text": "Time Complexity: The time complexity of an algorithm quantifies the amount of time taken by an algorithm to run as a function of the length of the input. Note that the time to run is a function of the length of the input and not the actual execution time of the machine on which the algorithm is running on." }, { "code": null, "e": 1370, "s": 909, "text": "In order to calculate time complexity on an algorithm, it is assumed that a constant time c is taken to execute one operation, and then the total operations for an input length on N are calculated. Consider an example to understand the process of calculation: Suppose a problem is to find whether a pair (X, Y) exists in an array, A of N elements whose sum is Z. The simplest idea is to consider every pair and check if it satisfies the given condition or not." }, { "code": null, "e": 1401, "s": 1370, "text": "The pseudo-code is as follows:" }, { "code": null, "e": 1570, "s": 1401, "text": "int a[n];\nfor(int i = 0;i < n;i++)\n cin >> a[i]\n \n\nfor(int i = 0;i < n;i++)\n for(int j = 0;j < n;j++)\n if(i!=j && a[i]+a[j] == z)\n return true\n\nreturn false" }, { "code": null, "e": 1621, "s": 1570, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1625, "s": 1621, "text": "C++" }, { "code": null, "e": 1630, "s": 1625, "text": "Java" }, { "code": null, "e": 1638, "s": 1630, "text": "Python3" }, { "code": null, "e": 1641, "s": 1638, "text": "C#" }, { "code": null, "e": 1652, "s": 1641, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find a pair in the given// array whose sum is equal to zbool findPair(int a[], int n, int z){ // Iterate through all the pairs for (int i = 0; i < n; i++) for (int j = 0; j < n; j++) // Check if the sum of the pair // (a[i], a[j]) is equal to z if (i != j && a[i] + a[j] == z) return true; return false;} // Driver Codeint main(){ // Given Input int a[] = { 1, -2, 1, 0, 5 }; int z = 0; int n = sizeof(a) / sizeof(a[0]); // Function Call if (findPair(a, n, z)) cout << \"True\"; else cout << \"False\"; return 0;}", "e": 2364, "s": 1652, "text": null }, { "code": "// Java program for the above approachimport java.lang.*;import java.util.*; class GFG{ // Function to find a pair in the given// array whose sum is equal to zstatic boolean findPair(int a[], int n, int z){ // Iterate through all the pairs for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) // Check if the sum of the pair // (a[i], a[j]) is equal to z if (i != j && a[i] + a[j] == z) return true; return false;} // Driver codepublic static void main(String[] args){ // Given Input int a[] = { 1, -2, 1, 0, 5 }; int z = 0; int n = a.length; // Function Call if (findPair(a, n, z)) System.out.println(\"True\"); else System.out.println(\"False\");}} // This code is contributed by avijitmondal1998", "e": 3184, "s": 2364, "text": null }, { "code": "# Python3 program for the above approach # Function to find a pair in the given# array whose sum is equal to zdef findPair(a, n, z) : # Iterate through all the pairs for i in range(n) : for j in range(n) : # Check if the sum of the pair # (a[i], a[j]) is equal to z if (i != j and a[i] + a[j] == z) : return True return False # Driver Code # Given Inputa = [ 1, -2, 1, 0, 5 ]z = 0n = len(a) # Function Callif (findPair(a, n, z)) : print(\"True\")else : print(\"False\") # This code is contributed by splevel62.", "e": 3776, "s": 3184, "text": null }, { "code": "// C# program for above approachusing System; class GFG{ // Function to find a pair in the given// array whose sum is equal to zstatic bool findPair(int[] a, int n, int z){ // Iterate through all the pairs for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) // Check if the sum of the pair // (a[i], a[j]) is equal to z if (i != j && a[i] + a[j] == z) return true; return false;} // Driver Codestatic void Main(){ // Given Input int[] a = { 1, -2, 1, 0, 5 }; int z = 0; int n = a.Length; // Function Call if (findPair(a, n, z)) Console.WriteLine(\"True\"); else Console.WriteLine(\"False\");}} // This code is contributed by sanjoy_62.", "e": 4530, "s": 3776, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find a pair in the given// array whose sum is equal to zfunction findPair(a, n, z){ // Iterate through all the pairs for(let i = 0; i < n; i++) for(let j = 0; j < n; j++) // Check if the sum of the pair // (a[i], a[j]) is equal to z if (i != j && a[i] + a[j] == z) return true; return false;} // Driver Code // Given Inputlet a = [ 1, -2, 1, 0, 5 ];let z = 0;let n = a.length; // Function Callif (findPair(a, n, z)) document.write(\"True\");else document.write(\"False\"); // This code is contributed by code_hunt </script>", "e": 5208, "s": 4530, "text": null }, { "code": null, "e": 5214, "s": 5208, "text": "False" }, { "code": null, "e": 5547, "s": 5214, "text": "Assuming that each of the operations in the computer takes approximately constant time, let it be c. The number of lines of code executed actually depends on the value of Z. During analyses of the algorithm, mostly the worst-case scenario is considered, i.e., when there is no pair of elements with sum equals Z. In the worst case, " }, { "code": null, "e": 5586, "s": 5547, "text": "N*c operations are required for input." }, { "code": null, "e": 5622, "s": 5586, "text": "The outer loop i loop runs N times." }, { "code": null, "e": 5670, "s": 5622, "text": "For each i, the inner loop j loop runs N times." }, { "code": null, "e": 6091, "s": 5670, "text": "So total execution time is N*c + N*N*c + c. Now ignore the lower order terms since the lower order terms are relatively insignificant for large input, therefore only the highest order term is taken (without constant) which is N*N in this case. Different notations are used to describe the limiting behavior of a function, but since the worst case is taken so big-O notation will be used to represent the time complexity." }, { "code": null, "e": 6343, "s": 6091, "text": "Hence, the time complexity is O(N2) for the above algorithm. Note that the time complexity is solely based on the number of elements in array A i.e the input length, so if the length of the array will increase the time of execution will also increase." }, { "code": null, "e": 6610, "s": 6343, "text": "Order of growth is how the time of execution depends on the length of the input. In the above example, it is clearly evident that the time of execution quadratically depends on the length of the array. Order of growth will help to compute the running time with ease." }, { "code": null, "e": 6687, "s": 6610, "text": "Another Example: Let’s calculate the time complexity of the below algorithm:" }, { "code": null, "e": 6691, "s": 6687, "text": "C++" }, { "code": null, "e": 6696, "s": 6691, "text": "Java" }, { "code": null, "e": 6704, "s": 6696, "text": "Python3" }, { "code": null, "e": 6707, "s": 6704, "text": "C#" }, { "code": null, "e": 6718, "s": 6707, "text": "Javascript" }, { "code": "count = 0for (int i = N; i > 0; i /= 2) for (int j = 0; j < i; j++) count++;", "e": 6799, "s": 6718, "text": null }, { "code": "int count = 0 ;for (int i = N; i > 0; i /= 2) for (int j = 0; j < i; j++) count++; //This code is contributed by Shubham Singh", "e": 6936, "s": 6799, "text": null }, { "code": "count = 0i = Nwhile(i > 0): for j in range(i): count+=1 i /= 2 # This code is contributed by subhamsingh10", "e": 7052, "s": 6936, "text": null }, { "code": "int count = 0 ;for (int i = N; i > 0; i /= 2) for (int j = 0; j < i; j++) count++; // This code is contributed by Shubham Singh", "e": 7190, "s": 7052, "text": null }, { "code": "let count = 0for(let i = N; i > 0; i /= 2) for(let j = 0; j < i; j++) count += 1; // This code is contributed by Shubham Singh", "e": 7328, "s": 7190, "text": null }, { "code": null, "e": 7491, "s": 7328, "text": "This is a tricky case. In the first look, it seems like the complexity is O(N * log N). N for the j′s loop and log(N) for i′s loop. But it’s wrong. Let’s see why." }, { "code": null, "e": 7537, "s": 7491, "text": "Think about how many times count++ will run. " }, { "code": null, "e": 7570, "s": 7537, "text": "When i = N, it will run N times." }, { "code": null, "e": 7611, "s": 7570, "text": "When i = N / 2, it will run N / 2 times." }, { "code": null, "e": 7652, "s": 7611, "text": "When i = N / 4, it will run N / 4 times." }, { "code": null, "e": 7663, "s": 7652, "text": "And so on." }, { "code": null, "e": 7774, "s": 7663, "text": "The total number of times count++ will run is N + N/2 + N/4+...+1= 2 * N. So the time complexity will be O(N)." }, { "code": null, "e": 7900, "s": 7774, "text": "Some general time complexities are listed below with the input range for which they are accepted in competitive programming: " }, { "code": null, "e": 7926, "s": 7900, "text": "Usually type of solutions" }, { "code": null, "e": 7933, "s": 7926, "text": "10 -12" }, { "code": null, "e": 7939, "s": 7933, "text": "O(N!)" }, { "code": null, "e": 7966, "s": 7939, "text": "Recursion and backtracking" }, { "code": null, "e": 7972, "s": 7966, "text": "15-18" }, { "code": null, "e": 7982, "s": 7972, "text": "O(2N * N)" }, { "code": null, "e": 8028, "s": 7982, "text": "Recursion, backtracking, and bit manipulation" }, { "code": null, "e": 8034, "s": 8028, "text": "18-22" }, { "code": null, "e": 8044, "s": 8034, "text": "O(2N * N)" }, { "code": null, "e": 8090, "s": 8044, "text": "Recursion, backtracking, and bit manipulation" }, { "code": null, "e": 8096, "s": 8090, "text": "30-40" }, { "code": null, "e": 8135, "s": 8096, "text": "Meet in the middle, Divide and Conquer" }, { "code": null, "e": 8139, "s": 8135, "text": "100" }, { "code": null, "e": 8145, "s": 8139, "text": "O(N4)" }, { "code": null, "e": 8179, "s": 8145, "text": "Dynamic programming, Constructive" }, { "code": null, "e": 8183, "s": 8179, "text": "400" }, { "code": null, "e": 8189, "s": 8183, "text": "O(N3)" }, { "code": null, "e": 8223, "s": 8189, "text": "Dynamic programming, Constructive" }, { "code": null, "e": 8226, "s": 8223, "text": "2K" }, { "code": null, "e": 8239, "s": 8226, "text": "O(N2* log N)" }, { "code": null, "e": 8303, "s": 8239, "text": "Dynamic programming, Binary Search, Sorting, Divide and Conquer" }, { "code": null, "e": 8307, "s": 8303, "text": "10K" }, { "code": null, "e": 8313, "s": 8307, "text": "O(N2)" }, { "code": null, "e": 8361, "s": 8313, "text": "Dynamic programming, Graph, Trees, Constructive" }, { "code": null, "e": 8364, "s": 8361, "text": "1M" }, { "code": null, "e": 8376, "s": 8364, "text": "O(N* log N)" }, { "code": null, "e": 8419, "s": 8376, "text": "Sorting, Binary Search, Divide and Conquer" }, { "code": null, "e": 8424, "s": 8419, "text": "100M" }, { "code": null, "e": 8445, "s": 8424, "text": "O(N), O(log N), O(1)" }, { "code": null, "e": 8491, "s": 8445, "text": "Constructive, Mathematical, Greedy Algorithms" }, { "code": null, "e": 8728, "s": 8491, "text": "Space Complexity: The space complexity of an algorithm quantifies the amount of space taken by an algorithm to run as a function of the length of the input. Consider an example: Suppose a problem to find the frequency of array elements." }, { "code": null, "e": 8760, "s": 8728, "text": "The pseudo-code is as follows: " }, { "code": null, "e": 8846, "s": 8760, "text": "int freq[n];\nint a[n];\n\nfor(int i = 0; i<n; i++)\n{\n cin>>a[i];\n freq[a[i]]++;\n} " }, { "code": null, "e": 8897, "s": 8846, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 8901, "s": 8897, "text": "C++" }, { "code": null, "e": 8906, "s": 8901, "text": "Java" }, { "code": null, "e": 8914, "s": 8906, "text": "Python3" }, { "code": null, "e": 8925, "s": 8914, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to count frequencies of array itemsvoid countFreq(int arr[], int n){ unordered_map<int, int> freq; // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) freq[arr[i]]++; // Traverse through map and print frequencies for (auto x : freq) cout << x.first << \" \" << x.second << endl;} // Driver Codeint main(){ // Given array int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = sizeof(arr) / sizeof(arr[0]); // Function Call countFreq(arr, n); return 0;}", "e": 9559, "s": 8925, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to count frequencies of array items static void countFreq(int arr[], int n) { HashMap<Integer,Integer> freq = new HashMap<>(); // Traverse through array elements and // count frequencies for (int i = 0; i < n; i++) { if(freq.containsKey(arr[i])){ freq.put(arr[i], freq.get(arr[i])+1); } else{ freq.put(arr[i], 1); } } // Traverse through map and print frequencies for (Map.Entry<Integer,Integer> x : freq.entrySet()) System.out.print(x.getKey()+ \" \" + x.getValue() +\"\\n\"); } // Driver Code public static void main(String[] args) { // Given array int arr[] = { 10, 20, 20, 10, 10, 20, 5, 20 }; int n = arr.length; // Function Call countFreq(arr, n); }} // This code is contributed by gauravrajput1", "e": 10425, "s": 9559, "text": null }, { "code": "# Python program for the above approach # Function to count frequencies of array itemsdef countFreq(arr, n): freq = dict() # Traverse through array elements and # count frequencies for i in arr: if i not in freq: freq[i] = 0 freq[i]+=1 # Traverse through map and print frequencies for x in freq: print(x, freq[x]) # Driver Code # Given arrayarr = [10, 20, 20, 10, 10, 20, 5, 20 ]n = len(arr) # Function CallcountFreq(arr, n) # This code is contributed by Shubham Singh", "e": 10959, "s": 10425, "text": null }, { "code": "<script>// Javascript program for the above approach // Function to count frequencies of array itemsfunction countFreq(arr, n) { let freq = new Map(); arr.sort((a, b) => a - b) // Traverse through array elements and // count frequencies for (let i = 0; i < n; i++) { if (freq.has(arr[i])) { freq.set(arr[i], freq.get(arr[i]) + 1) } else { freq.set(arr[i], 1) } } // Traverse through map and print frequencies for (let x of freq) document.write(x[0] + \" \" + x[1] + \"<br>\");} // Driver Code // Given arraylet arr = [10, 20, 20, 10, 10, 20, 5, 20];let n = arr.length; // Function CallcountFreq(arr, n); // This code is contributed by Saurabh Jaiswal</script>", "e": 11692, "s": 10959, "text": null }, { "code": null, "e": 11706, "s": 11692, "text": "5 1\n10 3\n20 4" }, { "code": null, "e": 11971, "s": 11706, "text": "Here two arrays of length N, and variable i are used in the algorithm so, the total space used is N * c + N * c + 1 * c = 2N * c + c, where c is a unit space taken. For many inputs, constant c is insignificant, and it can be said that the space complexity is O(N)." }, { "code": null, "e": 12425, "s": 11971, "text": "There is also auxiliary space, which is different from space complexity. The main difference is where space complexity quantifies the total space used by the algorithm, auxiliary space quantifies the extra space that is used in the algorithm apart from the given input. In the above example, the auxiliary space is the space used by the freq[] array because that is not part of the given input. So total auxiliary space is N * c + c which is O(N) only. " }, { "code": null, "e": 12444, "s": 12427, "text": "avijitmondal1998" }, { "code": null, "e": 12454, "s": 12444, "text": "sanjoy_62" }, { "code": null, "e": 12464, "s": 12454, "text": "code_hunt" }, { "code": null, "e": 12474, "s": 12464, "text": "splevel62" }, { "code": null, "e": 12497, "s": 12474, "text": "akankshasrivastava3120" }, { "code": null, "e": 12512, "s": 12497, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 12529, "s": 12512, "text": "surinderdawra388" }, { "code": null, "e": 12543, "s": 12529, "text": "GauravRajput1" }, { "code": null, "e": 12560, "s": 12543, "text": "_saurabh_jaiswal" }, { "code": null, "e": 12576, "s": 12560, "text": "time complexity" }, { "code": null, "e": 12585, "s": 12576, "text": "Analysis" }, { "code": null, "e": 12594, "s": 12585, "text": "Articles" } ]
Ternary operator vs Null coalescing operator in PHP
04 Jan, 2019 Ternary Operator Ternary operator is the conditional operator which helps to cut the number of lines in the coding while performing comparisons and conditionals. It is an alternative method of using if else and nested if else statements. The order of execution is from left to right. It is absolutely the best case time saving option. It does produces an e-notice while encountering a void value with its conditionals. Syntax: (Condition) ? (Statement1) : (Statement2); In ternary operator, if condition statement is true then statement1 will execute otherwise statement2 will execute. Alternative Method of Conditional Operation: if (Condition) { return Statement1; } else { return Statement2; } Example: <?php // PHP program to check number is even// or odd using ternary operator // Assign number to variable$num = 21; // Check condition and display resultprint ($num % 2 == 0) ? "Even Number" : "Odd Number";?> Odd Number Null coalescing operator The Null coalescing operator is used to check whether the given variable is null or not and returns the non-null value from the pair of customized values. Null Coalescing operator is mainly used to avoid the object function to return a NULL value rather returning a default optimized value. It is used to avoid exception and compiler error as it does not produce E-Notice at the time of execution. The order of execution is from right to left. While execution, the right side operand which is not null would be the return value, if null the left operand would be the return value. It facilitates better readability of the source code. Syntax: (Condition) ? (Statement1) ? (Statement2); Alternative method of Conditional Operation: // The isset() function is used to take // care that the condition is not NULL if ( isset(Condition) ) { return Statement1; } else { return Statemnet2; } Example: <?PHP // PHP program to use Null // Coalescing Operator // Assign value to variable$num = 10; // Use Null Coalescing Operator // and display resultprint ($num) ?? "NULL"; ?> 10 Difference between Ternary operator and Null coalescing operator: Ternary Operator is left associative where as, Null Coalescing operator is right associative. Ternary Operator throws e-notice if left operand is null, while null coalescing operator does not throws e-notice if left operand does not exist. Ternary Operator checks whether the value is true, but Null coalescing operator checks if the value is not null. If there is more iteration to be executed, null coalescing operator found to be faster than the ternary operator. Null coalescing operator gives better readability as well comparatively. Picked Technical Scripter 2018 PHP PHP Programs Technical Scripter Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP How to receive JSON POST with PHP ? Split a comma delimited string into an array in PHP How to convert array to string in PHP ? How to call PHP function on the click of a Button ? Comparing two dates in PHP Split a comma delimited string into an array in PHP How to get parameters from a URL string in PHP?
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Jan, 2019" }, { "code": null, "e": 45, "s": 28, "text": "Ternary Operator" }, { "code": null, "e": 447, "s": 45, "text": "Ternary operator is the conditional operator which helps to cut the number of lines in the coding while performing comparisons and conditionals. It is an alternative method of using if else and nested if else statements. The order of execution is from left to right. It is absolutely the best case time saving option. It does produces an e-notice while encountering a void value with its conditionals." }, { "code": null, "e": 455, "s": 447, "text": "Syntax:" }, { "code": null, "e": 498, "s": 455, "text": "(Condition) ? (Statement1) : (Statement2);" }, { "code": null, "e": 614, "s": 498, "text": "In ternary operator, if condition statement is true then statement1 will execute otherwise statement2 will execute." }, { "code": null, "e": 659, "s": 614, "text": "Alternative Method of Conditional Operation:" }, { "code": null, "e": 733, "s": 659, "text": "if (Condition) {\n return Statement1;\n} else {\n return Statement2;\n}" }, { "code": null, "e": 742, "s": 733, "text": "Example:" }, { "code": "<?php // PHP program to check number is even// or odd using ternary operator // Assign number to variable$num = 21; // Check condition and display resultprint ($num % 2 == 0) ? \"Even Number\" : \"Odd Number\";?>", "e": 954, "s": 742, "text": null }, { "code": null, "e": 966, "s": 954, "text": "Odd Number\n" }, { "code": null, "e": 991, "s": 966, "text": "Null coalescing operator" }, { "code": null, "e": 1626, "s": 991, "text": "The Null coalescing operator is used to check whether the given variable is null or not and returns the non-null value from the pair of customized values. Null Coalescing operator is mainly used to avoid the object function to return a NULL value rather returning a default optimized value. It is used to avoid exception and compiler error as it does not produce E-Notice at the time of execution. The order of execution is from right to left. While execution, the right side operand which is not null would be the return value, if null the left operand would be the return value. It facilitates better readability of the source code." }, { "code": null, "e": 1634, "s": 1626, "text": "Syntax:" }, { "code": null, "e": 1677, "s": 1634, "text": "(Condition) ? (Statement1) ? (Statement2);" }, { "code": null, "e": 1722, "s": 1677, "text": "Alternative method of Conditional Operation:" }, { "code": null, "e": 1887, "s": 1722, "text": "// The isset() function is used to take\n// care that the condition is not NULL\nif ( isset(Condition) ) { \n return Statement1;\n} else {\n return Statemnet2;\n}" }, { "code": null, "e": 1896, "s": 1887, "text": "Example:" }, { "code": "<?PHP // PHP program to use Null // Coalescing Operator // Assign value to variable$num = 10; // Use Null Coalescing Operator // and display resultprint ($num) ?? \"NULL\"; ?>", "e": 2074, "s": 1896, "text": null }, { "code": null, "e": 2078, "s": 2074, "text": "10\n" }, { "code": null, "e": 2144, "s": 2078, "text": "Difference between Ternary operator and Null coalescing operator:" }, { "code": null, "e": 2238, "s": 2144, "text": "Ternary Operator is left associative where as, Null Coalescing operator is right associative." }, { "code": null, "e": 2384, "s": 2238, "text": "Ternary Operator throws e-notice if left operand is null, while null coalescing operator does not throws e-notice if left operand does not exist." }, { "code": null, "e": 2497, "s": 2384, "text": "Ternary Operator checks whether the value is true, but Null coalescing operator checks if the value is not null." }, { "code": null, "e": 2611, "s": 2497, "text": "If there is more iteration to be executed, null coalescing operator found to be faster than the ternary operator." }, { "code": null, "e": 2684, "s": 2611, "text": "Null coalescing operator gives better readability as well comparatively." }, { "code": null, "e": 2691, "s": 2684, "text": "Picked" }, { "code": null, "e": 2715, "s": 2691, "text": "Technical Scripter 2018" }, { "code": null, "e": 2719, "s": 2715, "text": "PHP" }, { "code": null, "e": 2732, "s": 2719, "text": "PHP Programs" }, { "code": null, "e": 2751, "s": 2732, "text": "Technical Scripter" }, { "code": null, "e": 2768, "s": 2751, "text": "Web Technologies" }, { "code": null, "e": 2772, "s": 2768, "text": "PHP" }, { "code": null, "e": 2870, "s": 2772, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2910, "s": 2870, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 2955, "s": 2910, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 2982, "s": 2955, "text": "Comparing two dates in PHP" }, { "code": null, "e": 3018, "s": 2982, "text": "How to receive JSON POST with PHP ?" }, { "code": null, "e": 3070, "s": 3018, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 3110, "s": 3070, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3162, "s": 3110, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 3189, "s": 3162, "text": "Comparing two dates in PHP" }, { "code": null, "e": 3241, "s": 3189, "text": "Split a comma delimited string into an array in PHP" } ]
Python PIL | Image.new() method
30 Jun, 2021 PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. PIL.Image.new() method creates a new image with the given mode and size. Size is given as a (width, height)-tuple, in pixels. The color is given as a single value for single-band images, and a tuple for multi-band images (with one value for each band). We can also use color names. If the color argument is omitted, the image is filled with zero (this usually corresponds to black). If the color is None, the image is not initialized. This can be useful if you’re going to paste or draw things in the image. Syntax: PIL.Image.new(mode, size) PIL.Image.new(mode, size, color)Parameters: mode: The mode to use for the new image. (It could be RGB, RGBA) size: A 2-tuple containing (width, height) in pixels. color: What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes.Return Value: An Image object. Code #1: Python3 # Imports PIL moduleimport PIL # creating a image object (new image object) with# RGB mode and size 200x200im = PIL.Image.new(mode="RGB", size=(200, 200)) # This method will show image in any image viewerim.show() Output: Code #2: Python3 # imports Pil moduleimport PIL # creating image object which is of specific colorim = PIL.Image.new(mode = "RGB", size = (200, 200), color = (153, 153, 255)) # this will show image in any image viewerim.show() Output: One can alter the value of color tuple to get different colors or we can simply use color name (for single band images). bambolambo0 Image-Processing 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 Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 642, "s": 28, "text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. PIL.Image.new() method creates a new image with the given mode and size. Size is given as a (width, height)-tuple, in pixels. The color is given as a single value for single-band images, and a tuple for multi-band images (with one value for each band). We can also use color names. If the color argument is omitted, the image is filled with zero (this usually corresponds to black). If the color is None, the image is not initialized. This can be useful if you’re going to paste or draw things in the image. " }, { "code": null, "e": 1052, "s": 642, "text": "Syntax: PIL.Image.new(mode, size) PIL.Image.new(mode, size, color)Parameters: mode: The mode to use for the new image. (It could be RGB, RGBA) size: A 2-tuple containing (width, height) in pixels. color: What color to use for the image. Default is black. If given, this should be a single integer or floating point value for single-band modes, and a tuple for multi-band modes.Return Value: An Image object. " }, { "code": null, "e": 1063, "s": 1052, "text": "Code #1: " }, { "code": null, "e": 1071, "s": 1063, "text": "Python3" }, { "code": "# Imports PIL moduleimport PIL # creating a image object (new image object) with# RGB mode and size 200x200im = PIL.Image.new(mode=\"RGB\", size=(200, 200)) # This method will show image in any image viewerim.show()", "e": 1285, "s": 1071, "text": null }, { "code": null, "e": 1295, "s": 1285, "text": "Output: " }, { "code": null, "e": 1308, "s": 1295, "text": " Code #2: " }, { "code": null, "e": 1316, "s": 1308, "text": "Python3" }, { "code": "# imports Pil moduleimport PIL # creating image object which is of specific colorim = PIL.Image.new(mode = \"RGB\", size = (200, 200), color = (153, 153, 255)) # this will show image in any image viewerim.show()", "e": 1552, "s": 1316, "text": null }, { "code": null, "e": 1562, "s": 1552, "text": "Output: " }, { "code": null, "e": 1684, "s": 1562, "text": "One can alter the value of color tuple to get different colors or we can simply use color name (for single band images). " }, { "code": null, "e": 1696, "s": 1684, "text": "bambolambo0" }, { "code": null, "e": 1713, "s": 1696, "text": "Image-Processing" }, { "code": null, "e": 1720, "s": 1713, "text": "Python" }, { "code": null, "e": 1818, "s": 1720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1836, "s": 1818, "text": "Python Dictionary" }, { "code": null, "e": 1878, "s": 1836, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1900, "s": 1878, "text": "Enumerate() in Python" }, { "code": null, "e": 1935, "s": 1900, "text": "Read a file line by line in Python" }, { "code": null, "e": 1961, "s": 1935, "text": "Python String | replace()" }, { "code": null, "e": 1993, "s": 1961, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2022, "s": 1993, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2049, "s": 2022, "text": "Python Classes and Objects" }, { "code": null, "e": 2079, "s": 2049, "text": "Iterate over a list in Python" } ]
Typeof() vs GetType() in C#
The type takes the Type and returns the Type of the argument. For example: System.Byte for the following − typeof(byte) The following is an example − Live Demo using System; class Program { static void Main() { Console.WriteLine(typeof(int)); Console.WriteLine(typeof(byte)); } } System.Int32 System.Byte The GetType() method of array class in C# gets the Type of the current instance. To get the type. Type tp = value.GetType(); In the below example, we are checking the int value using the type. if (tp.Equals(typeof(int))) Console.WriteLine("{0} is an integer data type.", value) The following is the usage of GetType() method in C#. Live Demo using System; class Program { public static void Main() { object[] values = { (int) 100, (long) 17111}; foreach (var value in values) { Type tp = value.GetType(); if (tp.Equals(typeof(int))) Console.WriteLine("{0} is an integer data type.", value); else Console.WriteLine("'{0}' is not an int data type.", value); } } } 100 is an integer data type. '17111' is not an int data type.
[ { "code": null, "e": 1249, "s": 1187, "text": "The type takes the Type and returns the Type of the argument." }, { "code": null, "e": 1294, "s": 1249, "text": "For example: System.Byte for the following −" }, { "code": null, "e": 1307, "s": 1294, "text": "typeof(byte)" }, { "code": null, "e": 1337, "s": 1307, "text": "The following is an example −" }, { "code": null, "e": 1348, "s": 1337, "text": " Live Demo" }, { "code": null, "e": 1486, "s": 1348, "text": "using System;\nclass Program {\n static void Main() {\n Console.WriteLine(typeof(int));\n Console.WriteLine(typeof(byte));\n }\n}" }, { "code": null, "e": 1511, "s": 1486, "text": "System.Int32\nSystem.Byte" }, { "code": null, "e": 1592, "s": 1511, "text": "The GetType() method of array class in C# gets the Type of the current instance." }, { "code": null, "e": 1609, "s": 1592, "text": "To get the type." }, { "code": null, "e": 1636, "s": 1609, "text": "Type tp = value.GetType();" }, { "code": null, "e": 1704, "s": 1636, "text": "In the below example, we are checking the int value using the type." }, { "code": null, "e": 1789, "s": 1704, "text": "if (tp.Equals(typeof(int)))\nConsole.WriteLine(\"{0} is an integer data type.\", value)" }, { "code": null, "e": 1843, "s": 1789, "text": "The following is the usage of GetType() method in C#." }, { "code": null, "e": 1854, "s": 1843, "text": " Live Demo" }, { "code": null, "e": 2247, "s": 1854, "text": "using System;\n\nclass Program {\n public static void Main() {\n object[] values = { (int) 100, (long) 17111};\n foreach (var value in values) {\n\n Type tp = value.GetType();\n\n if (tp.Equals(typeof(int)))\n Console.WriteLine(\"{0} is an integer data type.\", value);\n\n else\n Console.WriteLine(\"'{0}' is not an int data type.\", value);\n }\n }\n}" }, { "code": null, "e": 2309, "s": 2247, "text": "100 is an integer data type.\n'17111' is not an int data type." } ]
Python OpenCV | cv2.cvtColor() method
18 Oct, 2019 OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.cvtColor() method is used to convert an image from one color space to another. There are more than 150 color-space conversion methods available in OpenCV. We will use some of color space conversion codes below. Syntax: cv2.cvtColor(src, code[, dst[, dstCn]]) Parameters:src: It is the image whose color space is to be changed.code: It is the color space conversion code.dst: It is the output image of the same size and depth as src image. It is an optional parameter.dstCn: It is the number of channels in the destination image. If the parameter is 0 then the number of the channels is derived automatically from src and code. It is an optional parameter. Return Value: It returns an image. Image used for all the below examples: Example #1: # Python program to explain cv2.cvtColor() method # importing cv2 import cv2 # path path = r'C:\Users\Administrator\Desktop\geeks.png' # Reading an image in default modesrc = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.cvtColor() method# Using cv2.COLOR_BGR2GRAY color space# conversion codeimage = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY ) # Displaying the image cv2.imshow(window_name, image) Output: Example #2:Using HSV color space. HSV color space is mostly used for object tracking. # Python program to explain cv2.cvtColor() method # importing cv2 import cv2 # path path = r'C:\Users\Administrator\Desktop\geeks.png' # Reading an image in default modesrc = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.cvtColor() method# Using cv2.COLOR_BGR2HSV color space# conversion codeimage = cv2.cvtColor(src, cv2.COLOR_BGR2HSV ) # Displaying the image cv2.imshow(window_name, image) Output: Image-Processing OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 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 Introduction To PYTHON Convert integer to string in Python How to drop one or multiple columns in Pandas Dataframe
[ { "code": null, "e": 53, "s": 25, "text": "\n18 Oct, 2019" }, { "code": null, "e": 358, "s": 53, "text": "OpenCV-Python is a library of Python bindings designed to solve computer vision problems. cv2.cvtColor() method is used to convert an image from one color space to another. There are more than 150 color-space conversion methods available in OpenCV. We will use some of color space conversion codes below." }, { "code": null, "e": 406, "s": 358, "text": "Syntax: cv2.cvtColor(src, code[, dst[, dstCn]])" }, { "code": null, "e": 803, "s": 406, "text": "Parameters:src: It is the image whose color space is to be changed.code: It is the color space conversion code.dst: It is the output image of the same size and depth as src image. It is an optional parameter.dstCn: It is the number of channels in the destination image. If the parameter is 0 then the number of the channels is derived automatically from src and code. It is an optional parameter." }, { "code": null, "e": 838, "s": 803, "text": "Return Value: It returns an image." }, { "code": null, "e": 877, "s": 838, "text": "Image used for all the below examples:" }, { "code": null, "e": 889, "s": 877, "text": "Example #1:" }, { "code": "# Python program to explain cv2.cvtColor() method # importing cv2 import cv2 # path path = r'C:\\Users\\Administrator\\Desktop\\geeks.png' # Reading an image in default modesrc = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.cvtColor() method# Using cv2.COLOR_BGR2GRAY color space# conversion codeimage = cv2.cvtColor(src, cv2.COLOR_BGR2GRAY ) # Displaying the image cv2.imshow(window_name, image)", "e": 1341, "s": 889, "text": null }, { "code": null, "e": 1349, "s": 1341, "text": "Output:" }, { "code": null, "e": 1435, "s": 1349, "text": "Example #2:Using HSV color space. HSV color space is mostly used for object tracking." }, { "code": "# Python program to explain cv2.cvtColor() method # importing cv2 import cv2 # path path = r'C:\\Users\\Administrator\\Desktop\\geeks.png' # Reading an image in default modesrc = cv2.imread(path) # Window name in which image is displayedwindow_name = 'Image' # Using cv2.cvtColor() method# Using cv2.COLOR_BGR2HSV color space# conversion codeimage = cv2.cvtColor(src, cv2.COLOR_BGR2HSV ) # Displaying the image cv2.imshow(window_name, image)", "e": 1885, "s": 1435, "text": null }, { "code": null, "e": 1893, "s": 1885, "text": "Output:" }, { "code": null, "e": 1910, "s": 1893, "text": "Image-Processing" }, { "code": null, "e": 1917, "s": 1910, "text": "OpenCV" }, { "code": null, "e": 1924, "s": 1917, "text": "Python" }, { "code": null, "e": 2022, "s": 1924, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2064, "s": 2022, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2086, "s": 2064, "text": "Enumerate() in Python" }, { "code": null, "e": 2112, "s": 2086, "text": "Python String | replace()" }, { "code": null, "e": 2144, "s": 2112, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2173, "s": 2144, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2200, "s": 2173, "text": "Python Classes and Objects" }, { "code": null, "e": 2221, "s": 2200, "text": "Python OOPs Concepts" }, { "code": null, "e": 2244, "s": 2221, "text": "Introduction To PYTHON" }, { "code": null, "e": 2280, "s": 2244, "text": "Convert integer to string in Python" } ]
SQL - Sub Queries
A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved. Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc. There are a few rules that subqueries must follow − Subqueries must be enclosed within parentheses. Subqueries must be enclosed within parentheses. A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns. A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns. An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery. An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery. Subqueries that return more than one row can only be used with multiple value operators such as the IN operator. Subqueries that return more than one row can only be used with multiple value operators such as the IN operator. The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB. The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB. A subquery cannot be immediately enclosed in a set function. A subquery cannot be immediately enclosed in a set function. The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within the subquery. The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within the subquery. Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows − SELECT column_name [, column_name ] FROM table1 [, table2 ] WHERE column_name OPERATOR (SELECT column_name [, column_name ] FROM table1 [, table2 ] [WHERE]) Consider the CUSTOMERS table having the following records − +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 35 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Now, let us check the following subquery with a SELECT statement. SQL> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS WHERE SALARY > 4500) ; This would produce the following result. +----+----------+-----+---------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+---------+----------+ | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+---------+----------+ Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date or number functions. The basic syntax is as follows. INSERT INTO table_name [ (column1 [, column2 ]) ] SELECT [ *|column1 [, column2 ] FROM table1 [, table2 ] [ WHERE VALUE OPERATOR ] Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the following syntax. SQL> INSERT INTO CUSTOMERS_BKP SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM CUSTOMERS) ; The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement. The basic syntax is as follows. UPDATE table SET column_name = new_value [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ] Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table. The following example updates SALARY by 0.25 times in the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27. SQL> UPDATE CUSTOMERS SET SALARY = SALARY * 0.25 WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 ); This would impact two rows and finally CUSTOMERS table would have the following records. +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 35 | Ahmedabad | 125.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 2125.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above. The basic syntax is as follows. DELETE FROM TABLE_NAME [ WHERE OPERATOR [ VALUE ] (SELECT COLUMN_NAME FROM TABLE_NAME) [ WHERE) ] Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS table. The following example deletes the records from the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27. SQL> DELETE FROM CUSTOMERS WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP WHERE AGE >= 27 ); This would impact two rows and finally the CUSTOMERS table would have the following records. +----+----------+-----+---------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+---------+----------+ | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 |
[ { "code": null, "e": 2705, "s": 2587, "text": "A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause." }, { "code": null, "e": 2836, "s": 2705, "text": "A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved." }, { "code": null, "e": 2979, "s": 2836, "text": "Subqueries can be used with the SELECT, INSERT, UPDATE, and DELETE statements along with the operators like =, <, >, >=, <=, IN, BETWEEN, etc." }, { "code": null, "e": 3031, "s": 2979, "text": "There are a few rules that subqueries must follow −" }, { "code": null, "e": 3079, "s": 3031, "text": "Subqueries must be enclosed within parentheses." }, { "code": null, "e": 3127, "s": 3079, "text": "Subqueries must be enclosed within parentheses." }, { "code": null, "e": 3281, "s": 3127, "text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns." }, { "code": null, "e": 3435, "s": 3281, "text": "A subquery can have only one column in the SELECT clause, unless multiple columns are in the main query for the subquery to compare its selected columns." }, { "code": null, "e": 3623, "s": 3435, "text": "An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery." }, { "code": null, "e": 3811, "s": 3623, "text": "An ORDER BY command cannot be used in a subquery, although the main query can use an ORDER BY. The GROUP BY command can be used to perform the same function as the ORDER BY in a subquery." }, { "code": null, "e": 3924, "s": 3811, "text": "Subqueries that return more than one row can only be used with multiple value operators such as the IN operator." }, { "code": null, "e": 4037, "s": 3924, "text": "Subqueries that return more than one row can only be used with multiple value operators such as the IN operator." }, { "code": null, "e": 4141, "s": 4037, "text": "The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB." }, { "code": null, "e": 4245, "s": 4141, "text": "The SELECT list cannot include any references to values that evaluate to a BLOB, ARRAY, CLOB, or NCLOB." }, { "code": null, "e": 4306, "s": 4245, "text": "A subquery cannot be immediately enclosed in a set function." }, { "code": null, "e": 4367, "s": 4306, "text": "A subquery cannot be immediately enclosed in a set function." }, { "code": null, "e": 4483, "s": 4367, "text": "The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within the subquery." }, { "code": null, "e": 4599, "s": 4483, "text": "The BETWEEN operator cannot be used with a subquery. However, the BETWEEN operator can be used within the subquery." }, { "code": null, "e": 4695, "s": 4599, "text": "Subqueries are most frequently used with the SELECT statement. The basic syntax is as follows −" }, { "code": null, "e": 4865, "s": 4695, "text": "SELECT column_name [, column_name ]\nFROM table1 [, table2 ]\nWHERE column_name OPERATOR\n (SELECT column_name [, column_name ]\n FROM table1 [, table2 ]\n [WHERE])\n" }, { "code": null, "e": 4925, "s": 4865, "text": "Consider the CUSTOMERS table having the following records −" }, { "code": null, "e": 5442, "s": 4925, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 35 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 5508, "s": 5442, "text": "Now, let us check the following subquery with a SELECT statement." }, { "code": null, "e": 5626, "s": 5508, "text": "SQL> SELECT * \n FROM CUSTOMERS \n WHERE ID IN (SELECT ID \n FROM CUSTOMERS \n WHERE SALARY > 4500) ;" }, { "code": null, "e": 5667, "s": 5626, "text": "This would produce the following result." }, { "code": null, "e": 5983, "s": 5667, "text": "+----+----------+-----+---------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+---------+----------+\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+---------+----------+\n" }, { "code": null, "e": 6231, "s": 5983, "text": "Subqueries also can be used with INSERT statements. The INSERT statement uses the data returned from the subquery to insert into another table. The selected data in the subquery can be modified with any of the character, date or number functions." }, { "code": null, "e": 6263, "s": 6231, "text": "The basic syntax is as follows." }, { "code": null, "e": 6404, "s": 6263, "text": "INSERT INTO table_name [ (column1 [, column2 ]) ]\n SELECT [ *|column1 [, column2 ]\n FROM table1 [, table2 ]\n [ WHERE VALUE OPERATOR ]\n" }, { "code": null, "e": 6583, "s": 6404, "text": "Consider a table CUSTOMERS_BKP with similar structure as CUSTOMERS table. Now to copy the complete CUSTOMERS table into the CUSTOMERS_BKP table, you can use the following syntax." }, { "code": null, "e": 6691, "s": 6583, "text": "SQL> INSERT INTO CUSTOMERS_BKP\n SELECT * FROM CUSTOMERS \n WHERE ID IN (SELECT ID \n FROM CUSTOMERS) ;\n" }, { "code": null, "e": 6867, "s": 6691, "text": "The subquery can be used in conjunction with the UPDATE statement. Either single or multiple columns in a table can be updated when using a subquery with the UPDATE statement." }, { "code": null, "e": 6899, "s": 6867, "text": "The basic syntax is as follows." }, { "code": null, "e": 7025, "s": 6899, "text": "UPDATE table\nSET column_name = new_value\n[ WHERE OPERATOR [ VALUE ]\n (SELECT COLUMN_NAME\n FROM TABLE_NAME)\n [ WHERE) ]\n" }, { "code": null, "e": 7247, "s": 7025, "text": "Assuming, we have CUSTOMERS_BKP table available which is backup of CUSTOMERS table. The following example updates SALARY by 0.25 times in the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27." }, { "code": null, "e": 7371, "s": 7247, "text": "SQL> UPDATE CUSTOMERS\n SET SALARY = SALARY * 0.25\n WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP\n WHERE AGE >= 27 );" }, { "code": null, "e": 7460, "s": 7371, "text": "This would impact two rows and finally CUSTOMERS table would have the following records." }, { "code": null, "e": 7978, "s": 7460, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 35 | Ahmedabad | 125.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 2125.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+\n" }, { "code": null, "e": 8092, "s": 7978, "text": "The subquery can be used in conjunction with the DELETE statement like with any other statements mentioned above." }, { "code": null, "e": 8124, "s": 8092, "text": "The basic syntax is as follows." }, { "code": null, "e": 8232, "s": 8124, "text": "DELETE FROM TABLE_NAME\n[ WHERE OPERATOR [ VALUE ]\n (SELECT COLUMN_NAME\n FROM TABLE_NAME)\n [ WHERE) ]\n" }, { "code": null, "e": 8455, "s": 8232, "text": "Assuming, we have a CUSTOMERS_BKP table available which is a backup of the CUSTOMERS table. The following example deletes the records from the CUSTOMERS table for all the customers whose AGE is greater than or equal to 27." }, { "code": null, "e": 8554, "s": 8455, "text": "SQL> DELETE FROM CUSTOMERS\n WHERE AGE IN (SELECT AGE FROM CUSTOMERS_BKP\n WHERE AGE >= 27 );" }, { "code": null, "e": 8647, "s": 8554, "text": "This would impact two rows and finally the CUSTOMERS table would have the following records." } ]
How to delete a CSV file in Python?
13 Jan, 2021 In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column. Approach : Import module. Check the path of the file. If the file is existing then we will delete it with os.remove(). Syntax : os.remove(‘Path) Example 1: Deleting specific csv file. Python3 # Python program to delete a csv file # csv file present in same directoryimport os # first check whether file exists or not# calling remove method to delete the csv file# in remove method you need to pass file name and typefile = 'word.csv'if(os.path.exists(file) and os.path.isfile(file)): os.remove(file) print("file deleted")else: print("file not found") Output: file deleted Example 2: Deleting all csv files in a directory We can use the os.walk() function to walk through a directory and delete specific files. In the example below, we will delete all ‘.csv’ files in the given directory. Python3 import osfor folder, subfolders, files in os.walk('csv/'): for file in files: # checking if file is # of .txt type if file.endswith('.csv'): path = os.path.join(folder, file) # printing the path of the file # to be deleted print('deleted : ', path ) # deleting the csv file os.remove(path) Output: deleted : csv/Sample1.csv deleted : csv/Sample2.csv deleted : csv/Sample3.csv deleted : csv/tips.csv Picked python-csv python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Python | os.path.join() method How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | datetime.timedelta() function Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2021" }, { "code": null, "e": 326, "s": 28, "text": "In this article, we are going to delete a CSV file in Python. CSV (Comma-separated values file) is the most commonly used file format to handle tabular data. The data values are separated by, (comma). The first line gives the names of the columns and after the next line the values of each column." }, { "code": null, "e": 337, "s": 326, "text": "Approach :" }, { "code": null, "e": 352, "s": 337, "text": "Import module." }, { "code": null, "e": 380, "s": 352, "text": "Check the path of the file." }, { "code": null, "e": 445, "s": 380, "text": "If the file is existing then we will delete it with os.remove()." }, { "code": null, "e": 471, "s": 445, "text": "Syntax : os.remove(‘Path)" }, { "code": null, "e": 510, "s": 471, "text": "Example 1: Deleting specific csv file." }, { "code": null, "e": 518, "s": 510, "text": "Python3" }, { "code": "# Python program to delete a csv file # csv file present in same directoryimport os # first check whether file exists or not# calling remove method to delete the csv file# in remove method you need to pass file name and typefile = 'word.csv'if(os.path.exists(file) and os.path.isfile(file)): os.remove(file) print(\"file deleted\")else: print(\"file not found\")", "e": 881, "s": 518, "text": null }, { "code": null, "e": 889, "s": 881, "text": "Output:" }, { "code": null, "e": 902, "s": 889, "text": "file deleted" }, { "code": null, "e": 951, "s": 902, "text": "Example 2: Deleting all csv files in a directory" }, { "code": null, "e": 1118, "s": 951, "text": "We can use the os.walk() function to walk through a directory and delete specific files. In the example below, we will delete all ‘.csv’ files in the given directory." }, { "code": null, "e": 1126, "s": 1118, "text": "Python3" }, { "code": "import osfor folder, subfolders, files in os.walk('csv/'): for file in files: # checking if file is # of .txt type if file.endswith('.csv'): path = os.path.join(folder, file) # printing the path of the file # to be deleted print('deleted : ', path ) # deleting the csv file os.remove(path)", "e": 1563, "s": 1126, "text": null }, { "code": null, "e": 1571, "s": 1563, "text": "Output:" }, { "code": null, "e": 1676, "s": 1571, "text": "deleted : csv/Sample1.csv\ndeleted : csv/Sample2.csv\ndeleted : csv/Sample3.csv\ndeleted : csv/tips.csv" }, { "code": null, "e": 1683, "s": 1676, "text": "Picked" }, { "code": null, "e": 1694, "s": 1683, "text": "python-csv" }, { "code": null, "e": 1711, "s": 1694, "text": "python-os-module" }, { "code": null, "e": 1718, "s": 1711, "text": "Python" }, { "code": null, "e": 1816, "s": 1718, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1848, "s": 1816, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1875, "s": 1848, "text": "Python Classes and Objects" }, { "code": null, "e": 1896, "s": 1875, "text": "Python OOPs Concepts" }, { "code": null, "e": 1919, "s": 1896, "text": "Introduction To PYTHON" }, { "code": null, "e": 1975, "s": 1919, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2006, "s": 1975, "text": "Python | os.path.join() method" }, { "code": null, "e": 2048, "s": 2006, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2090, "s": 2048, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2129, "s": 2090, "text": "Python | datetime.timedelta() function" } ]
Shortest Common Supersequence
22 Jun, 2022 Given two strings str1 and str2, the task is to find the length of the shortest string that has both str1 and str2 as subsequences. Examples : Input: str1 = "geek", str2 = "eke" Output: 5 Explanation: String "geeke" has both string "geek" and "eke" as subsequences. Input: str1 = "AGGTAB", str2 = "GXTXAYB" Output: 9 Explanation: String "AGXGTXAYB" has both string "AGGTAB" and "GXTXAYB" as subsequences. This problem is closely related to longest common subsequence problem. Below are steps.1) Find Longest Common Subsequence (lcs) of two given strings. For example, lcs of “geek” and “eke” is “ek”. 2) Insert non-lcs characters (in their original order in strings) to the lcs found above, and return the result. So “ek” becomes “geeke” which is shortest common supersequence.Let us consider another example, str1 = “AGGTAB” and str2 = “GXTXAYB”. LCS of str1 and str2 is “GTAB”. Once we find LCS, we insert characters of both strings in order and we get “AGXGTXAYB”How does this work? We need to find a string that has both strings as subsequences and is shortest such string. If both strings have all characters different, then result is sum of lengths of two given strings. If there are common characters, then we don’t want them multiple times as the task is to minimize length. Therefore, we first find the longest common subsequence, take one occurrence of this subsequence and add extra characters. Length of the shortest supersequence = (Sum of lengths of given two strings) - (Length of LCS of two given strings) Below is the implementation of above idea. The below implementation only finds length of the shortest super sequence. C++ C Java Python3 C# PHP Javascript // C++ program to find length of the// shortest supersequence#include <bits/stdc++.h>using namespace std; // Utility function to get max// of 2 integersint max(int a, int b) { return (a > b) ? a : b; } // Returns length of LCS for// X[0..m - 1], Y[0..n - 1]int lcs(char* X, char* Y, int m, int n); // Function to find length of the// shortest supersequence of X and Y.int shortestSuperSequence(char* X, char* Y){ int m = strlen(X), n = strlen(Y); // find lcs int l = lcs(X, Y, m, n); // Result is sum of input string // lengths - length of lcs return (m + n - l);} // Returns length of LCS// for X[0..m - 1], Y[0..n - 1]int lcs(char* X, char* Y, int m, int n){ int L[m + 1][n + 1]; int i, j; // Following steps build L[m + 1][n + 1] // in bottom up fashion. Note that // L[i][j] contains length of LCS of // X[0..i - 1] and Y[0..j - 1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n - 1] and Y[0..m - 1] return L[m][n];} // Driver codeint main(){ char X[] = "AGGTAB"; char Y[] = "GXTXAYB"; cout << "Length of the shortest supersequence is " << shortestSuperSequence(X, Y) << endl; return 0;} // This code is contributed by Akanksha Rai // C program to find length of// the shortest supersequence#include <stdio.h>#include <string.h> // Utility function to get// max of 2 integersint max(int a, int b) { return (a > b) ? a : b; } // Returns length of LCS for// X[0..m - 1], Y[0..n - 1]int lcs(char* X, char* Y, int m, int n); // Function to find length of the// shortest supersequence of X and Y.int shortestSuperSequence(char* X, char* Y){ int m = strlen(X), n = strlen(Y); // find lcs int l = lcs(X, Y, m, n); // Result is sum of input string // lengths - length of lcs return (m + n - l);} // Returns length of LCS// for X[0..m - 1], Y[0..n - 1]int lcs(char* X, char* Y, int m, int n){ int L[m + 1][n + 1]; int i, j; // Following steps build L[m + 1][n + 1] // in bottom up fashion. Note that // L[i][j] contains length of LCS of // X[0..i - 1] and Y[0..j - 1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n - 1] and Y[0..m - 1] return L[m][n];} // Driver codeint main(){ char X[] = "AGGTAB"; char Y[] = "GXTXAYB"; printf("Length of the shortest supersequence is %d\n", shortestSuperSequence(X, Y)); return 0;} // Java program to find length of// the shortest supersequenceclass GFG { // Function to find length of the // shortest supersequence of X and Y. static int shortestSuperSequence(String X, String Y) { int m = X.length(); int n = Y.length(); // find lcs int l = lcs(X, Y, m, n); // Result is sum of input string // lengths - length of lcs return (m + n - l); } // Returns length of LCS // for X[0..m - 1], Y[0..n - 1] static int lcs(String X, String Y, int m, int n) { int[][] L = new int[m + 1][n + 1]; int i, j; // Following steps build L[m + 1][n + 1] // in bottom up fashion. Note that // L[i][j] contains length of LCS // of X[0..i - 1]and Y[0..j - 1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X.charAt(i - 1) == Y.charAt(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n - 1] and Y[0..m - 1] return L[m][n]; } // Driver code public static void main(String args[]) { String X = "AGGTAB"; String Y = "GXTXAYB"; System.out.println("Length of the shortest " + "supersequence is " + shortestSuperSequence(X, Y)); }} // This article is contributed by Sumit Ghosh # Python program to find length# of the shortest supersequence # Function to find length of the# shortest supersequence of X and Y. def shortestSuperSequence(X, Y): m = len(X) n = len(Y) l = lcs(X, Y, m, n) # Result is sum of input string # lengths - length of lcs return (m + n - l) # Returns length of LCS for# X[0..m - 1], Y[0..n - 1] def lcs(X, Y, m, n): L = [[0] * (n + 2) for i in range(m + 2)] # Following steps build L[m + 1][n + 1] # in bottom up fashion. Note that L[i][j] # contains length of LCS of X[0..i - 1] # and Y[0..j - 1] for i in range(m + 1): for j in range(n + 1): if (i == 0 or j == 0): L[i][j] = 0 elif (X[i - 1] == Y[j - 1]): L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) # L[m][n] contains length of # LCS for X[0..n - 1] and Y[0..m - 1] return L[m][n] # Driver codeX = "AGGTAB"Y = "GXTXAYB" print("Length of the shortest supersequence is %d" % shortestSuperSequence(X, Y)) # This code is contributed by Ansu Kumari // C# program to find length of// the shortest supersequenceusing System; class GFG { // Function to find length of the // shortest supersequence of X and Y. static int shortestSuperSequence(String X, String Y) { int m = X.Length; int n = Y.Length; // find lcs int l = lcs(X, Y, m, n); // Result is sum of input string // lengths - length of lcs return (m + n - l); } // Returns length of LCS for // X[0..m - 1], Y[0..n - 1] static int lcs(String X, String Y, int m, int n) { int[, ] L = new int[m + 1, n + 1]; int i, j; // Following steps build L[m + 1][n + 1] // in bottom up fashion.Note that // L[i][j] contains length of LCS of // X[0..i - 1] and Y[0..j - 1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i, j] = 0; else if (X[i - 1] == Y[j - 1]) L[i, j] = L[i - 1, j - 1] + 1; else L[i, j] = Math.Max(L[i - 1, j], L[i, j - 1]); } } // L[m][n] contains length of LCS // for X[0..n - 1] and Y[0..m - 1] return L[m, n]; } // Driver code public static void Main() { String X = "AGGTAB"; String Y = "GXTXAYB"; Console.WriteLine("Length of the shortest" + "supersequence is " + shortestSuperSequence(X, Y)); }} // This code is contributed by Sam007 <?php// PHP program to find length of the// shortest supersequence // Function to find length of the// shortest supersequence of X and Y.function shortestSuperSequence($X, $Y){ $m = strlen($X); $n = strlen($Y); // find lcs $l = lcs($X, $Y, $m, $n); // Result is sum of input string // lengths - length of lcs return ($m + $n - $l);} // Returns length of LCS// for X[0..m - 1], Y[0..n - 1]function lcs( $X, $Y, $m, $n){ $L=array_fill(0, $m + 1, array_fill(0, $n + 1, 0)); // Following steps build $L[m + 1][n + 1] // in bottom up fashion. Note that // $L[i][j] contains length of LCS of // X[0..i - 1] and Y[0..j - 1] for ($i = 0; $i <= $m; $i++) { for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $L[$i][$j] = 0; else if ($X[$i - 1] == $Y[$j - 1]) $L[$i][$j] = $L[$i - 1][$j - 1] + 1; else $L[$i][$j] = max($L[$i - 1][$j], $L[$i][$j - 1]); } } // $L[m][n] contains length of LCS // for X[0..n - 1] and Y[0..m - 1] return $L[$m][$n];} // Driver code $X = "AGGTAB"; $Y = "GXTXAYB"; echo "Length of the shortest supersequence is ". shortestSuperSequence($X, $Y)."\n"; // This code is contributed by mits?> <script>// javascript program to find length of// the shortest supersequence // Function to find length of the// shortest supersequence of X and Y.function shortestSuperSequence(X, Y){ var m = X.length; var n = Y.length; // find lcs var l = lcs(X, Y, m, n); // Result is sum of input string // lengths - length of lcs return (m + n - l);} // Returns length of LCS// for X[0..m - 1], Y[0..n - 1]function lcs(X, Y , m , n){ var L = Array(m+1).fill(0).map(x => Array(n+1).fill(0)); var i, j; // Following steps build L[m + 1][n + 1] // in bottom up fashion. Note that // L[i][j] contains length of LCS // of X[0..i - 1]and Y[0..j - 1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X.charAt(i - 1) == Y.charAt(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n - 1] and Y[0..m - 1] return L[m][n];} // Driver codevar X = "AGGTAB";var Y = "GXTXAYB"; document.write("Length of the shortest " + "supersequence is " + shortestSuperSequence(X, Y)); // This code contributed by shikhasingrajput</script> Output: Length of the shortest supersequence is 9 Time Complexity: O(m*n). Below is Another Method to solve the above problem. A simple analysis yields below simple recursive solution. Let X[0..m - 1] and Y[0..n - 1] be two strings and m and n be respective lengths. if (m == 0) return n; if (n == 0) return m; // If last characters are same, then // add 1 to result and // recur for X[] if (X[m - 1] == Y[n - 1]) return 1 + SCS(X, Y, m - 1, n - 1); // Else find shortest of following two // a) Remove last character from X and recur // b) Remove last character from Y and recur else return 1 + min( SCS(X, Y, m - 1, n), SCS(X, Y, m, n - 1) ); Below is simple naive recursive solution based on above recursive formula. C++ Java Python3 C# PHP Javascript // A Naive recursive C++ program to find// length of the shortest supersequence#include <bits/stdc++.h>using namespace std; int superSeq(char* X, char* Y, int m, int n){ if (!m) return n; if (!n) return m; if (X[m - 1] == Y[n - 1]) return 1 + superSeq(X, Y, m - 1, n - 1); return 1 + min(superSeq(X, Y, m - 1, n), superSeq(X, Y, m, n - 1));} // Driver Codeint main(){ char X[] = "AGGTAB"; char Y[] = "GXTXAYB"; cout << "Length of the shortest supersequence is " << superSeq(X, Y, strlen(X), strlen(Y)); return 0;} // A Naive recursive Java program to find// length of the shortest supersequenceclass GFG { static int superSeq(String X, String Y, int m, int n) { if (m == 0) return n; if (n == 0) return m; if (X.charAt(m - 1) == Y.charAt(n - 1)) return 1 + superSeq(X, Y, m - 1, n - 1); return 1 + Math.min(superSeq(X, Y, m - 1, n), superSeq(X, Y, m, n - 1)); } // Driver code public static void main(String args[]) { String X = "AGGTAB"; String Y = "GXTXAYB"; System.out.println( "Length of the shortest" + "supersequence is: " + superSeq(X, Y, X.length(), Y.length())); }} // This article is contributed by Sumit Ghosh # A Naive recursive python program to find# length of the shortest supersequence def superSeq(X, Y, m, n): if (not m): return n if (not n): return m if (X[m - 1] == Y[n - 1]): return 1 + superSeq(X, Y, m - 1, n - 1) return 1 + min(superSeq(X, Y, m - 1, n), superSeq(X, Y, m, n - 1)) # Driver CodeX = "AGGTAB"Y = "GXTXAYB"print("Length of the shortest supersequence is %d" % superSeq(X, Y, len(X), len(Y))) # This code is contributed by Ansu Kumari // A Naive recursive C# program to find// length of the shortest supersequenceusing System; class GFG { static int superSeq(String X, String Y, int m, int n) { if (m == 0) return n; if (n == 0) return m; if (X[m - 1] == Y[n - 1]) return 1 + superSeq(X, Y, m - 1, n - 1); return 1 + Math.Min(superSeq(X, Y, m - 1, n), superSeq(X, Y, m, n - 1)); } // Driver Code public static void Main() { String X = "AGGTAB"; String Y = "GXTXAYB"; Console.WriteLine( "Length of the shortest supersequence is: " + superSeq(X, Y, X.Length, Y.Length)); }} // This code is contributed by Sam007 <?php// A Naive recursive PHP program to find// length of the shortest supersequence function superSeq($X, $Y, $m, $n){ if (!$m) return $n; if (!$n) return $m; if ($X[$m - 1] == $Y[$n - 1]) return 1 + superSeq($X, $Y, $m - 1, $n - 1); return 1 + min(superSeq($X, $Y, $m - 1, $n), superSeq($X, $Y, $m, $n - 1));} // Driver Code$X = "AGGTAB";$Y = "GXTXAYB";echo "Length of the shortest supersequence is ", superSeq($X, $Y, strlen($X), strlen($Y)); // This code is contributed by Ryuga?> <script>// A Naive recursive javascript program to find// length of the shortest supersequence function superSeq(X, Y , m , n){ if (m == 0) return n; if (n == 0) return m; if (X.charAt(m - 1) == Y.charAt(n - 1)) return 1 + superSeq(X, Y, m - 1, n - 1); return 1 + Math.min(superSeq(X, Y, m - 1, n), superSeq(X, Y, m, n - 1));} // Driver codevar X = "AGGTAB";var Y = "GXTXAYB";document.write( "Length of the shortest" + "supersequence is " + superSeq(X, Y, X.length, Y.length)); // This code contributed by Princi Singh </script> Output: Length of the shortest supersequence is 9 Time complexity: O(2min(m, n)). Since there are overlapping subproblems, we can efficiently solve this recursive problem using Dynamic Programming. Below is Dynamic Programming based implementation. C++ Java Python3 C# PHP Javascript // A dynamic programming based C program to// find length of the shortest supersequence#include <bits/stdc++.h>using namespace std; // Returns length of the shortest// supersequence of X and Yint superSeq(char* X, char* Y, int m, int n){ int dp[m + 1][n + 1]; // Fill table in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // Below steps follow above recurrence if (!i) dp[i][j] = j; else if (!j) dp[i][j] = i; else if (X[i - 1] == Y[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]); } } return dp[m][n];} // Driver Codeint main(){ char X[] = "AGGTAB"; char Y[] = "GXTXAYB"; cout << "Length of the shortest supersequence is " << superSeq(X, Y, strlen(X), strlen(Y)); return 0;} // A dynamic programming based Java program to// find length of the shortest supersequenceclass GFG { // Returns length of the shortest // supersequence of X and Y static int superSeq(String X, String Y, int m, int n) { int[][] dp = new int[m + 1][n + 1]; // Fill table in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // Below steps follow above recurrence if (i == 0) dp[i][j] = j; else if (j == 0) dp[i][j] = i; else if (X.charAt(i - 1) == Y.charAt(j - 1)) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]); } } return dp[m][n]; } // Driver Code public static void main(String args[]) { String X = "AGGTAB"; String Y = "GXTXAYB"; System.out.println( "Length of the shortest supersequence is " + superSeq(X, Y, X.length(), Y.length())); }} // This article is contributed by Sumit Ghosh # A dynamic programming based python program# to find length of the shortest supersequence # Returns length of the shortest supersequence of X and Y def superSeq(X, Y, m, n): dp = [[0] * (n + 2) for i in range(m + 2)] # Fill table in bottom up manner for i in range(m + 1): for j in range(n + 1): # Below steps follow above recurrence if (not i): dp[i][j] = j elif (not j): dp[i][j] = i elif (X[i - 1] == Y[j - 1]): dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]) return dp[m][n] # Driver CodeX = "AGGTAB"Y = "GXTXAYB"print("Length of the shortest supersequence is %d" % superSeq(X, Y, len(X), len(Y))) # This code is contributed by Ansu Kumari // A dynamic programming based C# program to// find length of the shortest supersequenceusing System; class GFG { // Returns length of the shortest // supersequence of X and Y static int superSeq(String X, String Y, int m, int n) { int[, ] dp = new int[m + 1, n + 1]; // Fill table in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // Below steps follow above recurrence if (i == 0) dp[i, j] = j; else if (j == 0) dp[i, j] = i; else if (X[i - 1] == Y[j - 1]) dp[i, j] = 1 + dp[i - 1, j - 1]; else dp[i, j] = 1 + Math.Min(dp[i - 1, j], dp[i, j - 1]); } } return dp[m, n]; } // Driver code public static void Main() { String X = "AGGTAB"; String Y = "GXTXAYB"; Console.WriteLine( "Length of the shortest supersequence is " + superSeq(X, Y, X.Length, Y.Length)); }} // This code is contributed by Sam007 <?php// A dynamic programming based PHP program to// find length of the shortest supersequence // Returns length of the shortest// supersequence of X and Yfunction superSeq($X, $Y, $m, $n){ $dp = array_fill(0, $m + 1, array_fill(0, $n + 1, 0)); // Fill table in bottom up manner for ($i = 0; $i <= $m; $i++) { for ($j = 0; $j <= $n; $j++) { // Below steps follow above recurrence if (!$i) $dp[$i][$j] = $j; else if (!$j) $dp[$i][$j] = $i; else if ($X[$i - 1] == $Y[$j - 1]) $dp[$i][$j] = 1 + $dp[$i - 1][$j - 1]; else $dp[$i][$j] = 1 + min($dp[$i - 1][$j], $dp[$i][$j - 1]); } } return $dp[$m][$n];} // Driver Code$X = "AGGTAB";$Y = "GXTXAYB";echo "Length of the shortest supersequence is " . superSeq($X, $Y, strlen($X), strlen($Y)); // This code is contributed by mits?> <script>// A dynamic programming based javascript program to// find length of the shortest supersequence // Returns length of the shortest // supersequence of X and Y function superSeq(X, Y, m, n) { var dp = Array(m+1).fill(0).map(x => Array(n+1).fill(0)); // Fill table in bottom up manner for (var i = 0; i <= m; i++) { for (var j = 0; j <= n; j++) { // Below steps follow above recurrence if (i == 0) dp[i][j] = j; else if (j == 0) dp[i][j] = i; else if (X.charAt(i - 1) == Y.charAt(j - 1)) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]); } } return dp[m][n]; } // Driver Code var X = "AGGTAB"; var Y = "GXTXAYB"; document.write( "Length of the shortest supersequence is " + superSeq(X, Y, X.length, Y.length)); // This code is contributed by 29AjayKumar</script> Output: Length of the shortest supersequence is 9 Time complexity: O(m*n). Thanks to Gaurav Ahirwar for suggesting this solution. Top Down Memoization Approach : The idea is to follow the simple recursive solution, use a lookup table to avoid re-computations. Before computing result for an input, we check if the result is already computed or not. If already computed, we return that result. C++ Java Python3 C# Javascript // A dynamic programming based python program// to find length of the shortest supersequence // Returns length of the// shortest supersequence of X and Y#include <bits/stdc++.h>using namespace std; int superSeq(string X, string Y, int n, int m, vector<vector<int> > lookup){ if (m == 0 || n == 0) { lookup[n][m] = n + m; } if (lookup[n][m] == 0) if (X[n - 1] == Y[m - 1]) { lookup[n][m] = superSeq(X, Y, n - 1, m - 1, lookup) + 1; } else { lookup[n][m] = min(superSeq(X, Y, n - 1, m, lookup) + 1, superSeq(X, Y, n, m - 1, lookup) + 1); } return lookup[n][m];} // Driver Codeint main(){ string X = "AGGTB"; string Y = "GXTXAYB"; vector<vector<int> > lookup( X.size() + 1, vector<int>(Y.size() + 1, 0)); cout << "Length of the shortest supersequence is " << superSeq(X, Y, X.size(), Y.size(), lookup) << endl; return 0;} // This code is contributed by niraj gusain // A dynamic programming based python program// to find length of the shortest supersequence // Returns length of the// shortest supersequence of X and Yimport java.util.*; class GFG { static int superSeq(String X, String Y, int n, int m, int[][] lookup) { if (m == 0 || n == 0) { lookup[n][m] = n + m; } if (lookup[n][m] == 0) if (X.charAt(n - 1) == Y.charAt(m - 1)) { lookup[n][m] = superSeq(X, Y, n - 1, m - 1, lookup) + 1; } else { lookup[n][m] = Math.min( superSeq(X, Y, n - 1, m, lookup) + 1, superSeq(X, Y, n, m - 1, lookup) + 1); } return lookup[n][m]; } // Driver Code public static void main(String[] args) { String X = "AGGTB"; String Y = "GXTXAYB"; int[][] lookup = new int[X.length() + 1][Y.length() + 1]; System.out.print( "Length of the shortest supersequence is " + superSeq(X, Y, X.length(), Y.length(), lookup) + "\n"); }} // This code contributed by umadevi9616 # A dynamic programming based python program# to find length of the shortest supersequence # Returns length of the# shortest supersequence of X and Y def superSeq(X,Y,n,m,lookup): if m==0 or n==0: lookup[n][m] = n+m if (lookup[n][m] == 0): if X[n-1]==Y[m-1]: lookup[n][m] = superSeq(X,Y,n-1,m-1,lookup)+1 else: lookup[n][m] = min(superSeq(X,Y,n-1,m,lookup)+1, superSeq(X,Y,n,m-1,lookup)+1) return lookup[n][m] # Driver CodeX = "AGGTAB"Y = "GXTXAYB" lookup = [[0 for j in range(len(Y)+1)]for i in range(len(X)+1)]print("Length of the shortest supersequence is {}" .format(superSeq(X,Y,len(X),len(Y),lookup))) # This code is contributed by Tanmay Ambadkar // A dynamic programming based python program// to find length of the shortest supersequence // Returns length of the// shortest supersequence of X and Yusing System; public class GFG { static int superSeq(String X, String Y, int n, int m, int[,] lookup) { if (m == 0 || n == 0) { lookup[n, m] = n + m; } if (lookup[n, m] == 0) if (X[n - 1] == Y[m - 1]) { lookup[n, m] = superSeq(X, Y, n - 1, m - 1, lookup) + 1; } else { lookup[n, m] = Math.Min(superSeq(X, Y, n - 1, m, lookup) + 1, superSeq(X, Y, n, m - 1, lookup) + 1); } return lookup[n, m]; } // Driver Code public static void Main(String[] args) { String X = "AGGTB"; String Y = "GXTXAYB"; int[,] lookup = new int[X.Length + 1,Y.Length + 1]; Console.Write( "Length of the shortest supersequence is " + superSeq(X, Y, X.Length, Y.Length, lookup) + "\n"); }} // This code is contributed by gauravrajput1 <script>// A dynamic programming based python program// to find length of the shortest supersequence // Returns length of the// shortest supersequence of X and Y function superSeq( X, Y , n , m, lookup) { if (m == 0 || n == 0) { lookup[n][m] = n + m; } if (lookup[n][m] == 0) if (X.charAt(n - 1) == Y.charAt(m - 1)) { lookup[n][m] = superSeq(X, Y, n - 1, m - 1, lookup) + 1; } else { lookup[n][m] = Math.min(superSeq(X, Y, n - 1, m, lookup) + 1, superSeq(X, Y, n, m - 1, lookup) + 1); } return lookup[n][m]; } // Driver Code var X = "AGGTB"; var Y = "GXTXAYB"; var lookup = Array(X.length + 1).fill().map(()=>Array(Y.length + 1).fill(0)); document.write( "Length of the shortest supersequence is " + superSeq(X, Y, X.length, Y.length, lookup) + "\n"); // This code is contributed by gauravrajput1</script> Output: Length of the shortest supersequence is 9.0 Time Complexity: O(n2) Auxiliary Space: O(n2) Exercise: Extend the above program to print shortest super sequence also using function to print LCS. Please refer Printing Shortest Common Supersequence for solutionReferences: https://en.wikipedia.org/wiki/Shortest_common_supersequencePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above Sam007 Vipin Sharma ankthon Akanksha_Rai Mithun Kumar tanmayambadkar abhijitgeeksforgeeks princi singh shikhasingrajput 29AjayKumar nirajgusain5 abhishek0719kadiyan umadevi9616 GauravRajput1 amartyaghoshgfg kanheremahesh1729 LCS subsequence Dynamic Programming Dynamic Programming LCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Subset Sum Problem | DP-25 Longest Palindromic Substring | Set 1 Floyd Warshall Algorithm | DP-16 Coin Change | DP-7 Find if there is a path between two vertices in an undirected graph Matrix Chain Multiplication | DP-8 Bellman–Ford Algorithm | DP-23 Sieve of Eratosthenes Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Find minimum number of coins that make a given value
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Jun, 2022" }, { "code": null, "e": 186, "s": 54, "text": "Given two strings str1 and str2, the task is to find the length of the shortest string that has both str1 and str2 as subsequences." }, { "code": null, "e": 198, "s": 186, "text": "Examples : " }, { "code": null, "e": 472, "s": 198, "text": "Input: str1 = \"geek\", str2 = \"eke\"\nOutput: 5\nExplanation: \nString \"geeke\" has both string \"geek\" \nand \"eke\" as subsequences.\n\nInput: str1 = \"AGGTAB\", str2 = \"GXTXAYB\"\nOutput: 9\nExplanation: \nString \"AGXGTXAYB\" has both string \n\"AGGTAB\" and \"GXTXAYB\" as subsequences." }, { "code": null, "e": 1474, "s": 472, "text": "This problem is closely related to longest common subsequence problem. Below are steps.1) Find Longest Common Subsequence (lcs) of two given strings. For example, lcs of “geek” and “eke” is “ek”. 2) Insert non-lcs characters (in their original order in strings) to the lcs found above, and return the result. So “ek” becomes “geeke” which is shortest common supersequence.Let us consider another example, str1 = “AGGTAB” and str2 = “GXTXAYB”. LCS of str1 and str2 is “GTAB”. Once we find LCS, we insert characters of both strings in order and we get “AGXGTXAYB”How does this work? We need to find a string that has both strings as subsequences and is shortest such string. If both strings have all characters different, then result is sum of lengths of two given strings. If there are common characters, then we don’t want them multiple times as the task is to minimize length. Therefore, we first find the longest common subsequence, take one occurrence of this subsequence and add extra characters. " }, { "code": null, "e": 1594, "s": 1474, "text": "Length of the shortest supersequence \n= (Sum of lengths of given two strings) \n- (Length of LCS of two given strings) " }, { "code": null, "e": 1714, "s": 1594, "text": "Below is the implementation of above idea. The below implementation only finds length of the shortest super sequence. " }, { "code": null, "e": 1718, "s": 1714, "text": "C++" }, { "code": null, "e": 1720, "s": 1718, "text": "C" }, { "code": null, "e": 1725, "s": 1720, "text": "Java" }, { "code": null, "e": 1733, "s": 1725, "text": "Python3" }, { "code": null, "e": 1736, "s": 1733, "text": "C#" }, { "code": null, "e": 1740, "s": 1736, "text": "PHP" }, { "code": null, "e": 1751, "s": 1740, "text": "Javascript" }, { "code": "// C++ program to find length of the// shortest supersequence#include <bits/stdc++.h>using namespace std; // Utility function to get max// of 2 integersint max(int a, int b) { return (a > b) ? a : b; } // Returns length of LCS for// X[0..m - 1], Y[0..n - 1]int lcs(char* X, char* Y, int m, int n); // Function to find length of the// shortest supersequence of X and Y.int shortestSuperSequence(char* X, char* Y){ int m = strlen(X), n = strlen(Y); // find lcs int l = lcs(X, Y, m, n); // Result is sum of input string // lengths - length of lcs return (m + n - l);} // Returns length of LCS// for X[0..m - 1], Y[0..n - 1]int lcs(char* X, char* Y, int m, int n){ int L[m + 1][n + 1]; int i, j; // Following steps build L[m + 1][n + 1] // in bottom up fashion. Note that // L[i][j] contains length of LCS of // X[0..i - 1] and Y[0..j - 1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n - 1] and Y[0..m - 1] return L[m][n];} // Driver codeint main(){ char X[] = \"AGGTAB\"; char Y[] = \"GXTXAYB\"; cout << \"Length of the shortest supersequence is \" << shortestSuperSequence(X, Y) << endl; return 0;} // This code is contributed by Akanksha Rai", "e": 3260, "s": 1751, "text": null }, { "code": "// C program to find length of// the shortest supersequence#include <stdio.h>#include <string.h> // Utility function to get// max of 2 integersint max(int a, int b) { return (a > b) ? a : b; } // Returns length of LCS for// X[0..m - 1], Y[0..n - 1]int lcs(char* X, char* Y, int m, int n); // Function to find length of the// shortest supersequence of X and Y.int shortestSuperSequence(char* X, char* Y){ int m = strlen(X), n = strlen(Y); // find lcs int l = lcs(X, Y, m, n); // Result is sum of input string // lengths - length of lcs return (m + n - l);} // Returns length of LCS// for X[0..m - 1], Y[0..n - 1]int lcs(char* X, char* Y, int m, int n){ int L[m + 1][n + 1]; int i, j; // Following steps build L[m + 1][n + 1] // in bottom up fashion. Note that // L[i][j] contains length of LCS of // X[0..i - 1] and Y[0..j - 1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X[i - 1] == Y[j - 1]) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n - 1] and Y[0..m - 1] return L[m][n];} // Driver codeint main(){ char X[] = \"AGGTAB\"; char Y[] = \"GXTXAYB\"; printf(\"Length of the shortest supersequence is %d\\n\", shortestSuperSequence(X, Y)); return 0;}", "e": 4712, "s": 3260, "text": null }, { "code": "// Java program to find length of// the shortest supersequenceclass GFG { // Function to find length of the // shortest supersequence of X and Y. static int shortestSuperSequence(String X, String Y) { int m = X.length(); int n = Y.length(); // find lcs int l = lcs(X, Y, m, n); // Result is sum of input string // lengths - length of lcs return (m + n - l); } // Returns length of LCS // for X[0..m - 1], Y[0..n - 1] static int lcs(String X, String Y, int m, int n) { int[][] L = new int[m + 1][n + 1]; int i, j; // Following steps build L[m + 1][n + 1] // in bottom up fashion. Note that // L[i][j] contains length of LCS // of X[0..i - 1]and Y[0..j - 1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X.charAt(i - 1) == Y.charAt(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n - 1] and Y[0..m - 1] return L[m][n]; } // Driver code public static void main(String args[]) { String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; System.out.println(\"Length of the shortest \" + \"supersequence is \" + shortestSuperSequence(X, Y)); }} // This article is contributed by Sumit Ghosh", "e": 6335, "s": 4712, "text": null }, { "code": "# Python program to find length# of the shortest supersequence # Function to find length of the# shortest supersequence of X and Y. def shortestSuperSequence(X, Y): m = len(X) n = len(Y) l = lcs(X, Y, m, n) # Result is sum of input string # lengths - length of lcs return (m + n - l) # Returns length of LCS for# X[0..m - 1], Y[0..n - 1] def lcs(X, Y, m, n): L = [[0] * (n + 2) for i in range(m + 2)] # Following steps build L[m + 1][n + 1] # in bottom up fashion. Note that L[i][j] # contains length of LCS of X[0..i - 1] # and Y[0..j - 1] for i in range(m + 1): for j in range(n + 1): if (i == 0 or j == 0): L[i][j] = 0 elif (X[i - 1] == Y[j - 1]): L[i][j] = L[i - 1][j - 1] + 1 else: L[i][j] = max(L[i - 1][j], L[i][j - 1]) # L[m][n] contains length of # LCS for X[0..n - 1] and Y[0..m - 1] return L[m][n] # Driver codeX = \"AGGTAB\"Y = \"GXTXAYB\" print(\"Length of the shortest supersequence is %d\" % shortestSuperSequence(X, Y)) # This code is contributed by Ansu Kumari", "e": 7489, "s": 6335, "text": null }, { "code": "// C# program to find length of// the shortest supersequenceusing System; class GFG { // Function to find length of the // shortest supersequence of X and Y. static int shortestSuperSequence(String X, String Y) { int m = X.Length; int n = Y.Length; // find lcs int l = lcs(X, Y, m, n); // Result is sum of input string // lengths - length of lcs return (m + n - l); } // Returns length of LCS for // X[0..m - 1], Y[0..n - 1] static int lcs(String X, String Y, int m, int n) { int[, ] L = new int[m + 1, n + 1]; int i, j; // Following steps build L[m + 1][n + 1] // in bottom up fashion.Note that // L[i][j] contains length of LCS of // X[0..i - 1] and Y[0..j - 1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i, j] = 0; else if (X[i - 1] == Y[j - 1]) L[i, j] = L[i - 1, j - 1] + 1; else L[i, j] = Math.Max(L[i - 1, j], L[i, j - 1]); } } // L[m][n] contains length of LCS // for X[0..n - 1] and Y[0..m - 1] return L[m, n]; } // Driver code public static void Main() { String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; Console.WriteLine(\"Length of the shortest\" + \"supersequence is \" + shortestSuperSequence(X, Y)); }} // This code is contributed by Sam007", "e": 9080, "s": 7489, "text": null }, { "code": "<?php// PHP program to find length of the// shortest supersequence // Function to find length of the// shortest supersequence of X and Y.function shortestSuperSequence($X, $Y){ $m = strlen($X); $n = strlen($Y); // find lcs $l = lcs($X, $Y, $m, $n); // Result is sum of input string // lengths - length of lcs return ($m + $n - $l);} // Returns length of LCS// for X[0..m - 1], Y[0..n - 1]function lcs( $X, $Y, $m, $n){ $L=array_fill(0, $m + 1, array_fill(0, $n + 1, 0)); // Following steps build $L[m + 1][n + 1] // in bottom up fashion. Note that // $L[i][j] contains length of LCS of // X[0..i - 1] and Y[0..j - 1] for ($i = 0; $i <= $m; $i++) { for ($j = 0; $j <= $n; $j++) { if ($i == 0 || $j == 0) $L[$i][$j] = 0; else if ($X[$i - 1] == $Y[$j - 1]) $L[$i][$j] = $L[$i - 1][$j - 1] + 1; else $L[$i][$j] = max($L[$i - 1][$j], $L[$i][$j - 1]); } } // $L[m][n] contains length of LCS // for X[0..n - 1] and Y[0..m - 1] return $L[$m][$n];} // Driver code $X = \"AGGTAB\"; $Y = \"GXTXAYB\"; echo \"Length of the shortest supersequence is \". shortestSuperSequence($X, $Y).\"\\n\"; // This code is contributed by mits?>", "e": 10408, "s": 9080, "text": null }, { "code": "<script>// javascript program to find length of// the shortest supersequence // Function to find length of the// shortest supersequence of X and Y.function shortestSuperSequence(X, Y){ var m = X.length; var n = Y.length; // find lcs var l = lcs(X, Y, m, n); // Result is sum of input string // lengths - length of lcs return (m + n - l);} // Returns length of LCS// for X[0..m - 1], Y[0..n - 1]function lcs(X, Y , m , n){ var L = Array(m+1).fill(0).map(x => Array(n+1).fill(0)); var i, j; // Following steps build L[m + 1][n + 1] // in bottom up fashion. Note that // L[i][j] contains length of LCS // of X[0..i - 1]and Y[0..j - 1] for (i = 0; i <= m; i++) { for (j = 0; j <= n; j++) { if (i == 0 || j == 0) L[i][j] = 0; else if (X.charAt(i - 1) == Y.charAt(j - 1)) L[i][j] = L[i - 1][j - 1] + 1; else L[i][j] = Math.max(L[i - 1][j], L[i][j - 1]); } } // L[m][n] contains length of LCS // for X[0..n - 1] and Y[0..m - 1] return L[m][n];} // Driver codevar X = \"AGGTAB\";var Y = \"GXTXAYB\"; document.write(\"Length of the shortest \" + \"supersequence is \" + shortestSuperSequence(X, Y)); // This code contributed by shikhasingrajput</script>", "e": 11769, "s": 10408, "text": null }, { "code": null, "e": 11778, "s": 11769, "text": "Output: " }, { "code": null, "e": 11820, "s": 11778, "text": "Length of the shortest supersequence is 9" }, { "code": null, "e": 11845, "s": 11820, "text": "Time Complexity: O(m*n)." }, { "code": null, "e": 11955, "s": 11845, "text": "Below is Another Method to solve the above problem. A simple analysis yields below simple recursive solution." }, { "code": null, "e": 12451, "s": 11955, "text": "Let X[0..m - 1] and Y[0..n - 1] be two \nstrings and m and n be respective\nlengths.\n\n if (m == 0) return n;\n if (n == 0) return m;\n\n // If last characters are same, then \n // add 1 to result and\n // recur for X[]\n if (X[m - 1] == Y[n - 1])\n return 1 + SCS(X, Y, m - 1, n - 1);\n\n // Else find shortest of following two\n // a) Remove last character from X and recur\n // b) Remove last character from Y and recur\n else \n return 1 + min( SCS(X, Y, m - 1, n), SCS(X, Y, m, n - 1) );" }, { "code": null, "e": 12527, "s": 12451, "text": "Below is simple naive recursive solution based on above recursive formula. " }, { "code": null, "e": 12531, "s": 12527, "text": "C++" }, { "code": null, "e": 12536, "s": 12531, "text": "Java" }, { "code": null, "e": 12544, "s": 12536, "text": "Python3" }, { "code": null, "e": 12547, "s": 12544, "text": "C#" }, { "code": null, "e": 12551, "s": 12547, "text": "PHP" }, { "code": null, "e": 12562, "s": 12551, "text": "Javascript" }, { "code": "// A Naive recursive C++ program to find// length of the shortest supersequence#include <bits/stdc++.h>using namespace std; int superSeq(char* X, char* Y, int m, int n){ if (!m) return n; if (!n) return m; if (X[m - 1] == Y[n - 1]) return 1 + superSeq(X, Y, m - 1, n - 1); return 1 + min(superSeq(X, Y, m - 1, n), superSeq(X, Y, m, n - 1));} // Driver Codeint main(){ char X[] = \"AGGTAB\"; char Y[] = \"GXTXAYB\"; cout << \"Length of the shortest supersequence is \" << superSeq(X, Y, strlen(X), strlen(Y)); return 0;}", "e": 13157, "s": 12562, "text": null }, { "code": "// A Naive recursive Java program to find// length of the shortest supersequenceclass GFG { static int superSeq(String X, String Y, int m, int n) { if (m == 0) return n; if (n == 0) return m; if (X.charAt(m - 1) == Y.charAt(n - 1)) return 1 + superSeq(X, Y, m - 1, n - 1); return 1 + Math.min(superSeq(X, Y, m - 1, n), superSeq(X, Y, m, n - 1)); } // Driver code public static void main(String args[]) { String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; System.out.println( \"Length of the shortest\" + \"supersequence is: \" + superSeq(X, Y, X.length(), Y.length())); }} // This article is contributed by Sumit Ghosh", "e": 13936, "s": 13157, "text": null }, { "code": "# A Naive recursive python program to find# length of the shortest supersequence def superSeq(X, Y, m, n): if (not m): return n if (not n): return m if (X[m - 1] == Y[n - 1]): return 1 + superSeq(X, Y, m - 1, n - 1) return 1 + min(superSeq(X, Y, m - 1, n), superSeq(X, Y, m, n - 1)) # Driver CodeX = \"AGGTAB\"Y = \"GXTXAYB\"print(\"Length of the shortest supersequence is %d\" % superSeq(X, Y, len(X), len(Y))) # This code is contributed by Ansu Kumari", "e": 14444, "s": 13936, "text": null }, { "code": "// A Naive recursive C# program to find// length of the shortest supersequenceusing System; class GFG { static int superSeq(String X, String Y, int m, int n) { if (m == 0) return n; if (n == 0) return m; if (X[m - 1] == Y[n - 1]) return 1 + superSeq(X, Y, m - 1, n - 1); return 1 + Math.Min(superSeq(X, Y, m - 1, n), superSeq(X, Y, m, n - 1)); } // Driver Code public static void Main() { String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; Console.WriteLine( \"Length of the shortest supersequence is: \" + superSeq(X, Y, X.Length, Y.Length)); }} // This code is contributed by Sam007", "e": 15180, "s": 14444, "text": null }, { "code": "<?php// A Naive recursive PHP program to find// length of the shortest supersequence function superSeq($X, $Y, $m, $n){ if (!$m) return $n; if (!$n) return $m; if ($X[$m - 1] == $Y[$n - 1]) return 1 + superSeq($X, $Y, $m - 1, $n - 1); return 1 + min(superSeq($X, $Y, $m - 1, $n), superSeq($X, $Y, $m, $n - 1));} // Driver Code$X = \"AGGTAB\";$Y = \"GXTXAYB\";echo \"Length of the shortest supersequence is \", superSeq($X, $Y, strlen($X), strlen($Y)); // This code is contributed by Ryuga?>", "e": 15724, "s": 15180, "text": null }, { "code": "<script>// A Naive recursive javascript program to find// length of the shortest supersequence function superSeq(X, Y , m , n){ if (m == 0) return n; if (n == 0) return m; if (X.charAt(m - 1) == Y.charAt(n - 1)) return 1 + superSeq(X, Y, m - 1, n - 1); return 1 + Math.min(superSeq(X, Y, m - 1, n), superSeq(X, Y, m, n - 1));} // Driver codevar X = \"AGGTAB\";var Y = \"GXTXAYB\";document.write( \"Length of the shortest\" + \"supersequence is \" + superSeq(X, Y, X.length, Y.length)); // This code contributed by Princi Singh </script>", "e": 16322, "s": 15724, "text": null }, { "code": null, "e": 16331, "s": 16322, "text": "Output: " }, { "code": null, "e": 16373, "s": 16331, "text": "Length of the shortest supersequence is 9" }, { "code": null, "e": 16573, "s": 16373, "text": "Time complexity: O(2min(m, n)). Since there are overlapping subproblems, we can efficiently solve this recursive problem using Dynamic Programming. Below is Dynamic Programming based implementation. " }, { "code": null, "e": 16577, "s": 16573, "text": "C++" }, { "code": null, "e": 16582, "s": 16577, "text": "Java" }, { "code": null, "e": 16590, "s": 16582, "text": "Python3" }, { "code": null, "e": 16593, "s": 16590, "text": "C#" }, { "code": null, "e": 16597, "s": 16593, "text": "PHP" }, { "code": null, "e": 16608, "s": 16597, "text": "Javascript" }, { "code": "// A dynamic programming based C program to// find length of the shortest supersequence#include <bits/stdc++.h>using namespace std; // Returns length of the shortest// supersequence of X and Yint superSeq(char* X, char* Y, int m, int n){ int dp[m + 1][n + 1]; // Fill table in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // Below steps follow above recurrence if (!i) dp[i][j] = j; else if (!j) dp[i][j] = i; else if (X[i - 1] == Y[j - 1]) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]); } } return dp[m][n];} // Driver Codeint main(){ char X[] = \"AGGTAB\"; char Y[] = \"GXTXAYB\"; cout << \"Length of the shortest supersequence is \" << superSeq(X, Y, strlen(X), strlen(Y)); return 0;}", "e": 17548, "s": 16608, "text": null }, { "code": "// A dynamic programming based Java program to// find length of the shortest supersequenceclass GFG { // Returns length of the shortest // supersequence of X and Y static int superSeq(String X, String Y, int m, int n) { int[][] dp = new int[m + 1][n + 1]; // Fill table in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // Below steps follow above recurrence if (i == 0) dp[i][j] = j; else if (j == 0) dp[i][j] = i; else if (X.charAt(i - 1) == Y.charAt(j - 1)) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]); } } return dp[m][n]; } // Driver Code public static void main(String args[]) { String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; System.out.println( \"Length of the shortest supersequence is \" + superSeq(X, Y, X.length(), Y.length())); }} // This article is contributed by Sumit Ghosh", "e": 18762, "s": 17548, "text": null }, { "code": "# A dynamic programming based python program# to find length of the shortest supersequence # Returns length of the shortest supersequence of X and Y def superSeq(X, Y, m, n): dp = [[0] * (n + 2) for i in range(m + 2)] # Fill table in bottom up manner for i in range(m + 1): for j in range(n + 1): # Below steps follow above recurrence if (not i): dp[i][j] = j elif (not j): dp[i][j] = i elif (X[i - 1] == Y[j - 1]): dp[i][j] = 1 + dp[i - 1][j - 1] else: dp[i][j] = 1 + min(dp[i - 1][j], dp[i][j - 1]) return dp[m][n] # Driver CodeX = \"AGGTAB\"Y = \"GXTXAYB\"print(\"Length of the shortest supersequence is %d\" % superSeq(X, Y, len(X), len(Y))) # This code is contributed by Ansu Kumari", "e": 19624, "s": 18762, "text": null }, { "code": "// A dynamic programming based C# program to// find length of the shortest supersequenceusing System; class GFG { // Returns length of the shortest // supersequence of X and Y static int superSeq(String X, String Y, int m, int n) { int[, ] dp = new int[m + 1, n + 1]; // Fill table in bottom up manner for (int i = 0; i <= m; i++) { for (int j = 0; j <= n; j++) { // Below steps follow above recurrence if (i == 0) dp[i, j] = j; else if (j == 0) dp[i, j] = i; else if (X[i - 1] == Y[j - 1]) dp[i, j] = 1 + dp[i - 1, j - 1]; else dp[i, j] = 1 + Math.Min(dp[i - 1, j], dp[i, j - 1]); } } return dp[m, n]; } // Driver code public static void Main() { String X = \"AGGTAB\"; String Y = \"GXTXAYB\"; Console.WriteLine( \"Length of the shortest supersequence is \" + superSeq(X, Y, X.Length, Y.Length)); }} // This code is contributed by Sam007", "e": 20809, "s": 19624, "text": null }, { "code": "<?php// A dynamic programming based PHP program to// find length of the shortest supersequence // Returns length of the shortest// supersequence of X and Yfunction superSeq($X, $Y, $m, $n){ $dp = array_fill(0, $m + 1, array_fill(0, $n + 1, 0)); // Fill table in bottom up manner for ($i = 0; $i <= $m; $i++) { for ($j = 0; $j <= $n; $j++) { // Below steps follow above recurrence if (!$i) $dp[$i][$j] = $j; else if (!$j) $dp[$i][$j] = $i; else if ($X[$i - 1] == $Y[$j - 1]) $dp[$i][$j] = 1 + $dp[$i - 1][$j - 1]; else $dp[$i][$j] = 1 + min($dp[$i - 1][$j], $dp[$i][$j - 1]); } } return $dp[$m][$n];} // Driver Code$X = \"AGGTAB\";$Y = \"GXTXAYB\";echo \"Length of the shortest supersequence is \" . superSeq($X, $Y, strlen($X), strlen($Y)); // This code is contributed by mits?>", "e": 21814, "s": 20809, "text": null }, { "code": "<script>// A dynamic programming based javascript program to// find length of the shortest supersequence // Returns length of the shortest // supersequence of X and Y function superSeq(X, Y, m, n) { var dp = Array(m+1).fill(0).map(x => Array(n+1).fill(0)); // Fill table in bottom up manner for (var i = 0; i <= m; i++) { for (var j = 0; j <= n; j++) { // Below steps follow above recurrence if (i == 0) dp[i][j] = j; else if (j == 0) dp[i][j] = i; else if (X.charAt(i - 1) == Y.charAt(j - 1)) dp[i][j] = 1 + dp[i - 1][j - 1]; else dp[i][j] = 1 + Math.min(dp[i - 1][j], dp[i][j - 1]); } } return dp[m][n]; } // Driver Code var X = \"AGGTAB\"; var Y = \"GXTXAYB\"; document.write( \"Length of the shortest supersequence is \" + superSeq(X, Y, X.length, Y.length)); // This code is contributed by 29AjayKumar</script>", "e": 22975, "s": 21814, "text": null }, { "code": null, "e": 22985, "s": 22975, "text": "Output: " }, { "code": null, "e": 23027, "s": 22985, "text": "Length of the shortest supersequence is 9" }, { "code": null, "e": 23053, "s": 23027, "text": "Time complexity: O(m*n). " }, { "code": null, "e": 23109, "s": 23053, "text": "Thanks to Gaurav Ahirwar for suggesting this solution. " }, { "code": null, "e": 23372, "s": 23109, "text": "Top Down Memoization Approach : The idea is to follow the simple recursive solution, use a lookup table to avoid re-computations. Before computing result for an input, we check if the result is already computed or not. If already computed, we return that result." }, { "code": null, "e": 23376, "s": 23372, "text": "C++" }, { "code": null, "e": 23381, "s": 23376, "text": "Java" }, { "code": null, "e": 23389, "s": 23381, "text": "Python3" }, { "code": null, "e": 23392, "s": 23389, "text": "C#" }, { "code": null, "e": 23403, "s": 23392, "text": "Javascript" }, { "code": "// A dynamic programming based python program// to find length of the shortest supersequence // Returns length of the// shortest supersequence of X and Y#include <bits/stdc++.h>using namespace std; int superSeq(string X, string Y, int n, int m, vector<vector<int> > lookup){ if (m == 0 || n == 0) { lookup[n][m] = n + m; } if (lookup[n][m] == 0) if (X[n - 1] == Y[m - 1]) { lookup[n][m] = superSeq(X, Y, n - 1, m - 1, lookup) + 1; } else { lookup[n][m] = min(superSeq(X, Y, n - 1, m, lookup) + 1, superSeq(X, Y, n, m - 1, lookup) + 1); } return lookup[n][m];} // Driver Codeint main(){ string X = \"AGGTB\"; string Y = \"GXTXAYB\"; vector<vector<int> > lookup( X.size() + 1, vector<int>(Y.size() + 1, 0)); cout << \"Length of the shortest supersequence is \" << superSeq(X, Y, X.size(), Y.size(), lookup) << endl; return 0;} // This code is contributed by niraj gusain", "e": 24447, "s": 23403, "text": null }, { "code": "// A dynamic programming based python program// to find length of the shortest supersequence // Returns length of the// shortest supersequence of X and Yimport java.util.*; class GFG { static int superSeq(String X, String Y, int n, int m, int[][] lookup) { if (m == 0 || n == 0) { lookup[n][m] = n + m; } if (lookup[n][m] == 0) if (X.charAt(n - 1) == Y.charAt(m - 1)) { lookup[n][m] = superSeq(X, Y, n - 1, m - 1, lookup) + 1; } else { lookup[n][m] = Math.min( superSeq(X, Y, n - 1, m, lookup) + 1, superSeq(X, Y, n, m - 1, lookup) + 1); } return lookup[n][m]; } // Driver Code public static void main(String[] args) { String X = \"AGGTB\"; String Y = \"GXTXAYB\"; int[][] lookup = new int[X.length() + 1][Y.length() + 1]; System.out.print( \"Length of the shortest supersequence is \" + superSeq(X, Y, X.length(), Y.length(), lookup) + \"\\n\"); }} // This code contributed by umadevi9616", "e": 25643, "s": 24447, "text": null }, { "code": "# A dynamic programming based python program# to find length of the shortest supersequence # Returns length of the# shortest supersequence of X and Y def superSeq(X,Y,n,m,lookup): if m==0 or n==0: lookup[n][m] = n+m if (lookup[n][m] == 0): if X[n-1]==Y[m-1]: lookup[n][m] = superSeq(X,Y,n-1,m-1,lookup)+1 else: lookup[n][m] = min(superSeq(X,Y,n-1,m,lookup)+1, superSeq(X,Y,n,m-1,lookup)+1) return lookup[n][m] # Driver CodeX = \"AGGTAB\"Y = \"GXTXAYB\" lookup = [[0 for j in range(len(Y)+1)]for i in range(len(X)+1)]print(\"Length of the shortest supersequence is {}\" .format(superSeq(X,Y,len(X),len(Y),lookup))) # This code is contributed by Tanmay Ambadkar", "e": 26410, "s": 25643, "text": null }, { "code": "// A dynamic programming based python program// to find length of the shortest supersequence // Returns length of the// shortest supersequence of X and Yusing System; public class GFG { static int superSeq(String X, String Y, int n, int m, int[,] lookup) { if (m == 0 || n == 0) { lookup[n, m] = n + m; } if (lookup[n, m] == 0) if (X[n - 1] == Y[m - 1]) { lookup[n, m] = superSeq(X, Y, n - 1, m - 1, lookup) + 1; } else { lookup[n, m] = Math.Min(superSeq(X, Y, n - 1, m, lookup) + 1, superSeq(X, Y, n, m - 1, lookup) + 1); } return lookup[n, m]; } // Driver Code public static void Main(String[] args) { String X = \"AGGTB\"; String Y = \"GXTXAYB\"; int[,] lookup = new int[X.Length + 1,Y.Length + 1]; Console.Write( \"Length of the shortest supersequence is \" + superSeq(X, Y, X.Length, Y.Length, lookup) + \"\\n\"); }} // This code is contributed by gauravrajput1", "e": 27596, "s": 26410, "text": null }, { "code": "<script>// A dynamic programming based python program// to find length of the shortest supersequence // Returns length of the// shortest supersequence of X and Y function superSeq( X, Y , n , m, lookup) { if (m == 0 || n == 0) { lookup[n][m] = n + m; } if (lookup[n][m] == 0) if (X.charAt(n - 1) == Y.charAt(m - 1)) { lookup[n][m] = superSeq(X, Y, n - 1, m - 1, lookup) + 1; } else { lookup[n][m] = Math.min(superSeq(X, Y, n - 1, m, lookup) + 1, superSeq(X, Y, n, m - 1, lookup) + 1); } return lookup[n][m]; } // Driver Code var X = \"AGGTB\"; var Y = \"GXTXAYB\"; var lookup = Array(X.length + 1).fill().map(()=>Array(Y.length + 1).fill(0)); document.write( \"Length of the shortest supersequence is \" + superSeq(X, Y, X.length, Y.length, lookup) + \"\\n\"); // This code is contributed by gauravrajput1</script>", "e": 28597, "s": 27596, "text": null }, { "code": null, "e": 28606, "s": 28597, "text": "Output: " }, { "code": null, "e": 28650, "s": 28606, "text": "Length of the shortest supersequence is 9.0" }, { "code": null, "e": 28673, "s": 28650, "text": "Time Complexity: O(n2)" }, { "code": null, "e": 28696, "s": 28673, "text": "Auxiliary Space: O(n2)" }, { "code": null, "e": 29058, "s": 28696, "text": "Exercise: Extend the above program to print shortest super sequence also using function to print LCS. Please refer Printing Shortest Common Supersequence for solutionReferences: https://en.wikipedia.org/wiki/Shortest_common_supersequencePlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 29065, "s": 29058, "text": "Sam007" }, { "code": null, "e": 29078, "s": 29065, "text": "Vipin Sharma" }, { "code": null, "e": 29086, "s": 29078, "text": "ankthon" }, { "code": null, "e": 29099, "s": 29086, "text": "Akanksha_Rai" }, { "code": null, "e": 29112, "s": 29099, "text": "Mithun Kumar" }, { "code": null, "e": 29127, "s": 29112, "text": "tanmayambadkar" }, { "code": null, "e": 29148, "s": 29127, "text": "abhijitgeeksforgeeks" }, { "code": null, "e": 29161, "s": 29148, "text": "princi singh" }, { "code": null, "e": 29178, "s": 29161, "text": "shikhasingrajput" }, { "code": null, "e": 29190, "s": 29178, "text": "29AjayKumar" }, { "code": null, "e": 29203, "s": 29190, "text": "nirajgusain5" }, { "code": null, "e": 29223, "s": 29203, "text": "abhishek0719kadiyan" }, { "code": null, "e": 29235, "s": 29223, "text": "umadevi9616" }, { "code": null, "e": 29249, "s": 29235, "text": "GauravRajput1" }, { "code": null, "e": 29265, "s": 29249, "text": "amartyaghoshgfg" }, { "code": null, "e": 29283, "s": 29265, "text": "kanheremahesh1729" }, { "code": null, "e": 29287, "s": 29283, "text": "LCS" }, { "code": null, "e": 29299, "s": 29287, "text": "subsequence" }, { "code": null, "e": 29319, "s": 29299, "text": "Dynamic Programming" }, { "code": null, "e": 29339, "s": 29319, "text": "Dynamic Programming" }, { "code": null, "e": 29343, "s": 29339, "text": "LCS" }, { "code": null, "e": 29441, "s": 29343, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29468, "s": 29441, "text": "Subset Sum Problem | DP-25" }, { "code": null, "e": 29506, "s": 29468, "text": "Longest Palindromic Substring | Set 1" }, { "code": null, "e": 29539, "s": 29506, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 29558, "s": 29539, "text": "Coin Change | DP-7" }, { "code": null, "e": 29626, "s": 29558, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 29661, "s": 29626, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 29692, "s": 29661, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 29714, "s": 29692, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 29782, "s": 29714, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" } ]
Minimum swaps required to make a binary string alternating in C++
Given a binary string of even length and equal number of 0’s and 1’s. What is the minimum number of swaps to make the string alternating? A binary string is alternating if no two consecutive elements are equal If str = 11110000 then 2 swaps are required. Count number of zeroes at odd position and even position of the string. Let their count be oddZeroCnt and evenZeroCnt respectively Count number of ones at odd position and even position of the string. Let their count be oddOneCnt and evenOneCnt respectively We will always swap a 1 with a 0. So we just check if our alternating string starts with 0 then the number of swaps is min (evenZeroCnt, oddOneCnt) and if our alternating string starts with 1 then the number of swaps is min (evenOneCnt, oddZeroCnt). The answer is min of these two Live Demo #include <bits/stdc++.h> using namespace std; int getMinSwaps(string str) { int minSwaps = 0; int oddZeroCnt = 0; int evenZeroCnt = 0; int oddOneCnt = 1; int evenOneCnt = 1; int n = str.length(); for (int i = 0; i < n; ++i) { if (i % 2 == 0) { if (str[i] == '1') { ++evenOneCnt; } else { ++evenZeroCnt; } } else { if (str[i] == '1') { ++oddOneCnt; } else { ++oddZeroCnt; } } } int zeroSwapCnt = min(evenZeroCnt, oddOneCnt); int oneSwapCnt = min(evenOneCnt, oddZeroCnt); return min(zeroSwapCnt, oneSwapCnt); } int main() { string str = "11110000"; cout << "Minimum swaps = " << getMinSwaps(str) << endl; return 0; } When you compile and execute above program. It generates following output − Minimum swaps = 2
[ { "code": null, "e": 1397, "s": 1187, "text": "Given a binary string of even length and equal number of 0’s and 1’s. What is the minimum number of swaps to make the string alternating? A binary string is alternating if no two consecutive elements are equal" }, { "code": null, "e": 1442, "s": 1397, "text": "If str = 11110000 then 2 swaps are required." }, { "code": null, "e": 1573, "s": 1442, "text": "Count number of zeroes at odd position and even position of the string. Let their count be oddZeroCnt and evenZeroCnt respectively" }, { "code": null, "e": 1700, "s": 1573, "text": "Count number of ones at odd position and even position of the string. Let their count be oddOneCnt and evenOneCnt respectively" }, { "code": null, "e": 1981, "s": 1700, "text": "We will always swap a 1 with a 0. So we just check if our alternating string starts with 0 then the number of swaps is min (evenZeroCnt, oddOneCnt) and if our alternating string starts with 1 then the number of swaps is min (evenOneCnt, oddZeroCnt). The answer is min of these two" }, { "code": null, "e": 1992, "s": 1981, "text": " Live Demo" }, { "code": null, "e": 2769, "s": 1992, "text": "#include <bits/stdc++.h>\nusing namespace std;\nint getMinSwaps(string str) {\n int minSwaps = 0;\n int oddZeroCnt = 0;\n int evenZeroCnt = 0;\n int oddOneCnt = 1;\n int evenOneCnt = 1;\n int n = str.length();\n for (int i = 0; i < n; ++i) {\n if (i % 2 == 0) {\n if (str[i] == '1') {\n ++evenOneCnt;\n } else {\n ++evenZeroCnt;\n }\n } else {\n if (str[i] == '1') {\n ++oddOneCnt;\n } else {\n ++oddZeroCnt;\n }\n }\n }\n int zeroSwapCnt = min(evenZeroCnt, oddOneCnt);\n int oneSwapCnt = min(evenOneCnt, oddZeroCnt);\n return min(zeroSwapCnt, oneSwapCnt);\n}\nint main() {\n string str = \"11110000\";\n cout << \"Minimum swaps = \" << getMinSwaps(str) << endl;\n return 0;\n}" }, { "code": null, "e": 2845, "s": 2769, "text": "When you compile and execute above program. It generates following output −" }, { "code": null, "e": 2863, "s": 2845, "text": "Minimum swaps = 2" } ]
MySQL query to display databases sorted by creation date?
You can display databases sorted by creation date with ORDER BY clause. Following is the query to display all databases − mysql> show databases; This will produce the following output − +---------------------------+ | Database | +---------------------------+ | bothinnodbandmyisam | | business | | commandline | | customer_tracker_database | | customertracker | | database1 | | databasesample | | demo | | education | | hb_student_tracker | | hello | | information_schema | | javadatabase2 | | javasampledatabase | | mybusiness | | mydatabase | | mysql | | onetomanyrelationship | | performance_schema | | rdb | | sample | | sampledatabase | | schemasample | | sys | | test | | test3 | | tracker | | universitydatabase | | web | | webtracker | +---------------------------+ 30 rows in set (0.00 sec) Following is the query to show databases sorted by creation date − mysql> SELECT -> TABLE_SCHEMA AS ALL_DATABASE_NAME, -> MAX(create_time) AS creationTime, -> MAX(update_time) updatingTime -> FROM INFORMATION_SCHEMA.TABLES -> GROUP BY ALL_DATABASE_NAME -> ORDER BY creationTime DESC; This will produce the following output − +---------------------+---------------------+---------------------+ | ALL_DATABASE_NAME | creationTime | updatingTime | +---------------------+---------------------+---------------------+ | test | 2019-04-03 11:37:58 | 2019-04-03 11:38:55 | | hb_student_tracker | 2019-03-19 03:54:32 | NULL | | sample | 2019-03-15 00:04:29 | 2019-03-08 16:06:09 | | test3 | 2019-03-12 20:29:12 | NULL | | mysql | 2019-02-26 07:10:49 | 2019-04-03 11:38:56 | | demo | 2019-02-19 03:27:40 | NULL | | tracker | 2019-02-14 19:49:55 | NULL | | bothinnodbandmyisam | 2019-02-06 14:32:26 | 2019-02-05 18:11:14 | | commandline | 2019-01-30 21:21:56 | NULL | | rdb | 2019-01-03 19:37:43 | NULL | | business | 2019-01-02 17:32:17 | 2018-12-10 17:53:02 | | education | 2018-10-06 15:07:29 | NULL | | information_schema | 2018-09-23 02:09:14 | NULL | | sys | 2018-09-23 02:09:03 | NULL | | performance_schema | 2018-09-23 02:08:01 | NULL | +---------------------+---------------------+---------------------+ 15 rows in set (0.05 sec)
[ { "code": null, "e": 1184, "s": 1062, "text": "You can display databases sorted by creation date with ORDER BY clause. Following is the query to display all databases −" }, { "code": null, "e": 1207, "s": 1184, "text": "mysql> show databases;" }, { "code": null, "e": 1248, "s": 1207, "text": "This will produce the following output −" }, { "code": null, "e": 2294, "s": 1248, "text": "+---------------------------+\n| Database |\n+---------------------------+\n| bothinnodbandmyisam |\n| business |\n| commandline |\n| customer_tracker_database |\n| customertracker |\n| database1 |\n| databasesample |\n| demo |\n| education |\n| hb_student_tracker |\n| hello |\n| information_schema |\n| javadatabase2 |\n| javasampledatabase |\n| mybusiness |\n| mydatabase |\n| mysql |\n| onetomanyrelationship |\n| performance_schema |\n| rdb |\n| sample |\n| sampledatabase |\n| schemasample |\n| sys |\n| test |\n| test3 |\n| tracker |\n| universitydatabase |\n| web |\n| webtracker |\n+---------------------------+\n30 rows in set (0.00 sec)" }, { "code": null, "e": 2361, "s": 2294, "text": "Following is the query to show databases sorted by creation date −" }, { "code": null, "e": 2596, "s": 2361, "text": "mysql> SELECT\n -> TABLE_SCHEMA AS ALL_DATABASE_NAME,\n -> MAX(create_time) AS creationTime,\n -> MAX(update_time) updatingTime\n -> FROM INFORMATION_SCHEMA.TABLES\n -> GROUP BY ALL_DATABASE_NAME\n -> ORDER BY creationTime DESC;" }, { "code": null, "e": 2637, "s": 2596, "text": "This will produce the following output −" }, { "code": null, "e": 3955, "s": 2637, "text": "+---------------------+---------------------+---------------------+\n| ALL_DATABASE_NAME | creationTime | updatingTime |\n+---------------------+---------------------+---------------------+\n| test | 2019-04-03 11:37:58 | 2019-04-03 11:38:55 |\n| hb_student_tracker | 2019-03-19 03:54:32 | NULL |\n| sample | 2019-03-15 00:04:29 | 2019-03-08 16:06:09 |\n| test3 | 2019-03-12 20:29:12 | NULL |\n| mysql | 2019-02-26 07:10:49 | 2019-04-03 11:38:56 |\n| demo | 2019-02-19 03:27:40 | NULL |\n| tracker | 2019-02-14 19:49:55 | NULL |\n| bothinnodbandmyisam | 2019-02-06 14:32:26 | 2019-02-05 18:11:14 |\n| commandline | 2019-01-30 21:21:56 | NULL |\n| rdb | 2019-01-03 19:37:43 | NULL |\n| business | 2019-01-02 17:32:17 | 2018-12-10 17:53:02 |\n| education | 2018-10-06 15:07:29 | NULL |\n| information_schema | 2018-09-23 02:09:14 | NULL |\n| sys | 2018-09-23 02:09:03 | NULL |\n| performance_schema | 2018-09-23 02:08:01 | NULL |\n+---------------------+---------------------+---------------------+\n15 rows in set (0.05 sec)" } ]
Find the product of sum of two diagonals of a square Matrix - GeeksforGeeks
20 Apr, 2021 Given a square matrix mat consisting of integers of size NxN, the task is to calculate the product between the sums of its diagonal.Examples: Input: mat[][] = {{5, 8, 1}, {5, 10, 3}, {-6, 17, -9}} Output: 30 Sum of primary diagonal = 5 + 10 + (-9) = 6. Sum of secondary diagonal = 1 + 10 + (-6) = 5. Product = 6 * 5 = 30. Input: mat[][] = {{22, -8, 11}, {55, 87, -1}, {-61, 69, 19}} Output: 4736 Naive approach: Traverse the entire matrix and find the diagonal elements. Calculate the sums across the two diagonals of a square matrix. Then, just take the product of the two sums obtained. Time complexity: O(N2)Naive approach: Traverse just the diagonal elements instead of the entire matrix by observing the pattern in the indices of the diagonal elements. Below is the implementation of this approach: CPP Java Python3 C# Javascript // C++ program to find the product// of the sum of diagonals. #include <bits/stdc++.h>using namespace std; // Function to find the product// of the sum of diagonals.long long product(vector<vector<int>> &mat, int n){ // Initialize sums of diagonals long long d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += mat[i][i]; d2 += mat[i][n - i - 1]; } // Return the answer return 1LL * d1 * d2;} // Driven codeint main(){ vector<vector<int>> mat = {{ 5, 8, 1}, { 5, 10, 3}, { -6, 17, -9}}; int n = mat.size(); // Function call cout << product(mat, n); return 0;} // Java program to find the product// of the sum of diagonals. class GFG{ // Function to find the product// of the sum of diagonals.static long product(int [][]mat, int n){ // Initialize sums of diagonals long d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += mat[i][i]; d2 += mat[i][n - i - 1]; } // Return the answer return 1L * d1 * d2;} // Driven codepublic static void main(String[] args){ int [][]mat = {{ 5, 8, 1}, { 5, 10, 3}, { -6, 17, -9}}; int n = mat.length; // Function call System.out.print(product(mat, n)); }} // This code is contributed by 29AjayKumar # Python3 program to find the product# of the sum of diagonals. # Function to find the product# of the sum of diagonals.def product(mat,n): # Initialize sums of diagonals d1 = 0 d2 = 0 for i in range(n): d1 += mat[i][i] d2 += mat[i][n - i - 1] # Return the answer return d1 * d2 # Driven codeif __name__ == '__main__': mat = [[5, 8, 1], [5, 10, 3], [-6, 17, -9]] n = len(mat) # Function call print(product(mat, n)) # This code is contributed by mohit kumar 29 // C# program to find the product// of the sum of diagonals.using System; class GFG{ // Function to find the product// of the sum of diagonals.static long product(int [,]mat, int n){ // Initialize sums of diagonals long d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += mat[i, i]; d2 += mat[i, n - i - 1]; } // Return the answer return 1L * d1 * d2;} // Driven codepublic static void Main(String[] args){ int [,]mat = {{ 5, 8, 1}, { 5, 10, 3}, { -6, 17, -9}}; int n = mat.GetLength(0); // Function call Console.Write(product(mat, n));}} // This code is contributed by Princi Singh <script>// Javascript program to find the product// of the sum of diagonals. // Function to find the product// of the sum of diagonals.function product(mat, n){ // Initialize sums of diagonals let d1 = 0, d2 = 0; for (let i = 0; i < n; i++) { d1 += mat[i][i]; d2 += mat[i][n - i - 1]; } // Return the answer return d1 * d2;} // Driven code let mat = [[ 5, 8, 1], [ 5, 10, 3], [ -6, 17, -9]]; let n = mat.length; // Function call document.write(product(mat, n)); // This code is contributed by rishavmahato348.</script> 30 Time complexity: O(N) mohit kumar 29 29AjayKumar princi singh rishavmahato348 Mathematical Matrix School Programming Write From Home Mathematical Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Algorithm to solve Rubik's Cube Modular multiplicative inverse Program to multiply two matrices Program to convert a given number to words Count ways to reach the n'th stair Matrix Chain Multiplication | DP-8 Program to find largest element in an array Print a given matrix in spiral form Sudoku | Backtracking-7 Rat in a Maze | Backtracking-2
[ { "code": null, "e": 24636, "s": 24608, "text": "\n20 Apr, 2021" }, { "code": null, "e": 24780, "s": 24636, "text": "Given a square matrix mat consisting of integers of size NxN, the task is to calculate the product between the sums of its diagonal.Examples: " }, { "code": null, "e": 25115, "s": 24780, "text": "Input: mat[][] = {{5, 8, 1}, \n {5, 10, 3}, \n {-6, 17, -9}}\nOutput: 30\nSum of primary diagonal = 5 + 10 + (-9) = 6.\nSum of secondary diagonal = 1 + 10 + (-6) = 5.\nProduct = 6 * 5 = 30.\n\nInput: mat[][] = {{22, -8, 11}, \n {55, 87, -1}, \n {-61, 69, 19}}\nOutput: 4736" }, { "code": null, "e": 25527, "s": 25117, "text": "Naive approach: Traverse the entire matrix and find the diagonal elements. Calculate the sums across the two diagonals of a square matrix. Then, just take the product of the two sums obtained. Time complexity: O(N2)Naive approach: Traverse just the diagonal elements instead of the entire matrix by observing the pattern in the indices of the diagonal elements. Below is the implementation of this approach: " }, { "code": null, "e": 25531, "s": 25527, "text": "CPP" }, { "code": null, "e": 25536, "s": 25531, "text": "Java" }, { "code": null, "e": 25544, "s": 25536, "text": "Python3" }, { "code": null, "e": 25547, "s": 25544, "text": "C#" }, { "code": null, "e": 25558, "s": 25547, "text": "Javascript" }, { "code": "// C++ program to find the product// of the sum of diagonals. #include <bits/stdc++.h>using namespace std; // Function to find the product// of the sum of diagonals.long long product(vector<vector<int>> &mat, int n){ // Initialize sums of diagonals long long d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += mat[i][i]; d2 += mat[i][n - i - 1]; } // Return the answer return 1LL * d1 * d2;} // Driven codeint main(){ vector<vector<int>> mat = {{ 5, 8, 1}, { 5, 10, 3}, { -6, 17, -9}}; int n = mat.size(); // Function call cout << product(mat, n); return 0;}", "e": 26276, "s": 25558, "text": null }, { "code": "// Java program to find the product// of the sum of diagonals. class GFG{ // Function to find the product// of the sum of diagonals.static long product(int [][]mat, int n){ // Initialize sums of diagonals long d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += mat[i][i]; d2 += mat[i][n - i - 1]; } // Return the answer return 1L * d1 * d2;} // Driven codepublic static void main(String[] args){ int [][]mat = {{ 5, 8, 1}, { 5, 10, 3}, { -6, 17, -9}}; int n = mat.length; // Function call System.out.print(product(mat, n)); }} // This code is contributed by 29AjayKumar", "e": 27009, "s": 26276, "text": null }, { "code": "# Python3 program to find the product# of the sum of diagonals. # Function to find the product# of the sum of diagonals.def product(mat,n): # Initialize sums of diagonals d1 = 0 d2 = 0 for i in range(n): d1 += mat[i][i] d2 += mat[i][n - i - 1] # Return the answer return d1 * d2 # Driven codeif __name__ == '__main__': mat = [[5, 8, 1], [5, 10, 3], [-6, 17, -9]] n = len(mat) # Function call print(product(mat, n)) # This code is contributed by mohit kumar 29 ", "e": 27541, "s": 27009, "text": null }, { "code": "// C# program to find the product// of the sum of diagonals.using System; class GFG{ // Function to find the product// of the sum of diagonals.static long product(int [,]mat, int n){ // Initialize sums of diagonals long d1 = 0, d2 = 0; for (int i = 0; i < n; i++) { d1 += mat[i, i]; d2 += mat[i, n - i - 1]; } // Return the answer return 1L * d1 * d2;} // Driven codepublic static void Main(String[] args){ int [,]mat = {{ 5, 8, 1}, { 5, 10, 3}, { -6, 17, -9}}; int n = mat.GetLength(0); // Function call Console.Write(product(mat, n));}} // This code is contributed by Princi Singh", "e": 28253, "s": 27541, "text": null }, { "code": "<script>// Javascript program to find the product// of the sum of diagonals. // Function to find the product// of the sum of diagonals.function product(mat, n){ // Initialize sums of diagonals let d1 = 0, d2 = 0; for (let i = 0; i < n; i++) { d1 += mat[i][i]; d2 += mat[i][n - i - 1]; } // Return the answer return d1 * d2;} // Driven code let mat = [[ 5, 8, 1], [ 5, 10, 3], [ -6, 17, -9]]; let n = mat.length; // Function call document.write(product(mat, n)); // This code is contributed by rishavmahato348.</script>", "e": 28922, "s": 28253, "text": null }, { "code": null, "e": 28925, "s": 28922, "text": "30" }, { "code": null, "e": 28950, "s": 28927, "text": "Time complexity: O(N) " }, { "code": null, "e": 28965, "s": 28950, "text": "mohit kumar 29" }, { "code": null, "e": 28977, "s": 28965, "text": "29AjayKumar" }, { "code": null, "e": 28990, "s": 28977, "text": "princi singh" }, { "code": null, "e": 29006, "s": 28990, "text": "rishavmahato348" }, { "code": null, "e": 29019, "s": 29006, "text": "Mathematical" }, { "code": null, "e": 29026, "s": 29019, "text": "Matrix" }, { "code": null, "e": 29045, "s": 29026, "text": "School Programming" }, { "code": null, "e": 29061, "s": 29045, "text": "Write From Home" }, { "code": null, "e": 29074, "s": 29061, "text": "Mathematical" }, { "code": null, "e": 29081, "s": 29074, "text": "Matrix" }, { "code": null, "e": 29179, "s": 29081, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29188, "s": 29179, "text": "Comments" }, { "code": null, "e": 29201, "s": 29188, "text": "Old Comments" }, { "code": null, "e": 29233, "s": 29201, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 29264, "s": 29233, "text": "Modular multiplicative inverse" }, { "code": null, "e": 29297, "s": 29264, "text": "Program to multiply two matrices" }, { "code": null, "e": 29340, "s": 29297, "text": "Program to convert a given number to words" }, { "code": null, "e": 29375, "s": 29340, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 29410, "s": 29375, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 29454, "s": 29410, "text": "Program to find largest element in an array" }, { "code": null, "e": 29490, "s": 29454, "text": "Print a given matrix in spiral form" }, { "code": null, "e": 29514, "s": 29490, "text": "Sudoku | Backtracking-7" } ]
How to check in R whether a matrix element is present in another matrix or not?
We can use %in% to check whether a matrix element is present in another matrix or not. For example, suppose we have two matrices defined as − M1 1 2 3 1 2 3 1 2 3 M2 1 2 3 4 5 6 7 8 9 Then M1%in%M2 will return − [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE But M2%in%M1 will return − [1] TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE Live Demo M1<−matrix(1:25,ncol=5,byrow=TRUE) M1 [,1] [,2] [,3] [,4] [,5] [1,] 1 2 3 4 5 [2,] 6 7 8 9 10 [3,] 11 12 13 14 15 [4,] 16 17 18 19 20 [5,] 21 22 23 24 25 M2<−matrix(1:50,ncol=5,byrow=TRUE) M2 [,1] [,2] [,3] [,4] [,5] [1,] 1 2 3 4 5 [2,] 6 7 8 9 10 [3,] 11 12 13 14 15 [4,] 16 17 18 19 20 [5,] 21 22 23 24 25 [6,] 26 27 28 29 30 [7,] 31 32 33 34 35 [8,] 36 37 38 39 40 [9,] 41 42 43 44 45 [10,] 46 47 48 49 50 M1%in%M2 [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE [16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE M2%in%M1 [1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE [13] TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE [25] TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE FALSE [37] FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE [49] FALSE FALSE Live Demo M3<−matrix(rpois(40,5),ncol=4,byrow=TRUE) M3 [,1] [,2] [,3] [,4] [1,] 4 7 7 6 [2,] 5 4 5 2 [3,] 6 3 5 5 [4,] 8 6 6 6 [5,] 3 6 3 6 [6,] 5 3 7 8 [7,] 9 4 6 2 [8,] 4 6 2 4 [9,] 3 2 4 7 [10,] 6 10 3 2 M4<−matrix(rpois(24,5),ncol=4,byrow=TRUE) M4 [,1] [,2] [,3] [,4] [1,] 4 8 7 5 [2,] 9 3 8 9 [3,] 6 2 1 5 [4,] 2 10 7 1 [5,] 5 4 7 7 [6,] 4 5 12 6 M3%in%M4 [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE [16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE [31] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE M4%in%M3 [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE [13] TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE FALSE TRUE TRUE Live Demo M6<−matrix(rpois(35,6),ncol=7,byrow=TRUE) M6 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 6 5 9 5 2 4 7 [2,] 7 5 8 8 8 7 5 [3,] 10 4 6 9 8 10 4 [4,] 7 8 9 5 7 6 8 [5,] 6 3 5 8 9 7 6 M7<−matrix(rpois(63,8),ncol=7,byrow=TRUE) M7 [,1] [,2] [,3] [,4] [,5] [,6] [,7] [1,] 7 10 7 10 12 7 8 [2,] 6 7 6 6 7 10 9 [3,] 12 11 7 8 12 6 6 [4,] 6 6 8 13 6 10 5 [5,] 7 7 11 12 10 3 8 [6,] 14 3 11 10 10 3 8 [7,] 9 12 6 8 4 13 7 [8,] 8 10 12 3 4 4 7 [9,] 8 9 10 9 7 7 9 M6%in%M7 [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE [13] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE [25] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE M7%in%M6 [1] TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE [13] TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE [25] TRUE FALSE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE [37] FALSE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE [49] TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE [61] TRUE TRUE TRUE
[ { "code": null, "e": 1204, "s": 1062, "text": "We can use %in% to check whether a matrix element is present in another matrix or not. For example, suppose we have two matrices defined as −" }, { "code": null, "e": 1252, "s": 1204, "text": " M1\n1 2 3\n1 2 3\n1 2 3\n M2\n1 2 3\n4 5 6\n7 8 9" }, { "code": null, "e": 1280, "s": 1252, "text": "Then M1%in%M2 will return −" }, { "code": null, "e": 1329, "s": 1280, "text": "[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE" }, { "code": null, "e": 1356, "s": 1329, "text": "But M2%in%M1 will return −" }, { "code": null, "e": 1411, "s": 1356, "text": "[1] TRUE FALSE FALSE TRUE FALSE FALSE TRUE FALSE FALSE" }, { "code": null, "e": 1422, "s": 1411, "text": " Live Demo" }, { "code": null, "e": 2282, "s": 1422, "text": "M1<−matrix(1:25,ncol=5,byrow=TRUE)\nM1\n[,1] [,2] [,3] [,4] [,5]\n[1,] 1 2 3 4 5\n[2,] 6 7 8 9 10\n[3,] 11 12 13 14 15\n[4,] 16 17 18 19 20\n[5,] 21 22 23 24 25\nM2<−matrix(1:50,ncol=5,byrow=TRUE)\nM2\n[,1] [,2] [,3] [,4] [,5]\n[1,] 1 2 3 4 5\n[2,] 6 7 8 9 10\n[3,] 11 12 13 14 15\n[4,] 16 17 18 19 20\n[5,] 21 22 23 24 25\n[6,] 26 27 28 29 30\n[7,] 31 32 33 34 35\n[8,] 36 37 38 39 40\n[9,] 41 42 43 44 45\n[10,] 46 47 48 49 50\nM1%in%M2\n[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\n[16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\nM2%in%M1\n[1] TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE\n[13] TRUE TRUE TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE\n[25] TRUE FALSE FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE FALSE\n[37] FALSE FALSE FALSE FALSE TRUE TRUE TRUE TRUE TRUE FALSE FALSE FALSE\n[49] FALSE FALSE" }, { "code": null, "e": 2293, "s": 2282, "text": " Live Demo" }, { "code": null, "e": 2999, "s": 2293, "text": "M3<−matrix(rpois(40,5),ncol=4,byrow=TRUE)\nM3\n[,1] [,2] [,3] [,4]\n[1,] 4 7 7 6\n[2,] 5 4 5 2\n[3,] 6 3 5 5\n[4,] 8 6 6 6\n[5,] 3 6 3 6\n[6,] 5 3 7 8\n[7,] 9 4 6 2\n[8,] 4 6 2 4\n[9,] 3 2 4 7\n[10,] 6 10 3 2\nM4<−matrix(rpois(24,5),ncol=4,byrow=TRUE)\nM4\n[,1] [,2] [,3] [,4]\n[1,] 4 8 7 5\n[2,] 9 3 8 9\n[3,] 6 2 1 5\n[4,] 2 10 7 1\n[5,] 5 4 7 7\n[6,] 4 5 12 6\nM3%in%M4\n[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\n[16] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\n[31] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\nM4%in%M3\n[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\n[13] TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE FALSE TRUE TRUE" }, { "code": null, "e": 3010, "s": 2999, "text": " Live Demo" }, { "code": null, "e": 4023, "s": 3010, "text": "M6<−matrix(rpois(35,6),ncol=7,byrow=TRUE)\nM6\n[,1] [,2] [,3] [,4] [,5] [,6] [,7]\n[1,] 6 5 9 5 2 4 7\n[2,] 7 5 8 8 8 7 5\n[3,] 10 4 6 9 8 10 4\n[4,] 7 8 9 5 7 6 8\n[5,] 6 3 5 8 9 7 6\nM7<−matrix(rpois(63,8),ncol=7,byrow=TRUE)\nM7\n[,1] [,2] [,3] [,4] [,5] [,6] [,7]\n[1,] 7 10 7 10 12 7 8\n[2,] 6 7 6 6 7 10 9\n[3,] 12 11 7 8 12 6 6\n[4,] 6 6 8 13 6 10 5\n[5,] 7 7 11 12 10 3 8\n[6,] 14 3 11 10 10 3 8\n[7,] 9 12 6 8 4 13 7\n[8,] 8 10 12 3 4 4 7\n[9,] 8 9 10 9 7 7 9\nM6%in%M7\n[1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\n[13] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE FALSE TRUE TRUE TRUE\n[25] TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\nM7%in%M6\n[1] TRUE TRUE FALSE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE FALSE\n[13] TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE FALSE FALSE\n[25] TRUE FALSE TRUE TRUE TRUE TRUE FALSE FALSE TRUE TRUE TRUE TRUE\n[37] FALSE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\n[49] TRUE TRUE TRUE FALSE TRUE TRUE TRUE TRUE TRUE TRUE TRUE TRUE\n[61] TRUE TRUE TRUE" } ]
Prefix to Postfix Conversion in C++
In this problem, we are given a prefix expression. Our task is to print the postfix conversion of the given expression. Prefix expression is those expressions which have operators before the operands. Example: +AB. Postfix expressions are those expressions which have operators after operands in the expressions. Example: AB/ The conversion of prefix to postfix should not involve the conversion to infix. Let’s take an example to understand the problem, Input: /+XY+NM Output: XY+NM+/ Explanation: infix -> (X+Y)/(N+M) To solve this problem, we will first traverse the whole postfix expression in an reverse order. And we will be using the stack data structure for our processing. And do the following for cases of elements found of traversal Case: if the symbol is operand -> push(element) in stack. Case: if symbol is operator -> 2*pop(element) from stack. And then push sequence of operand - operand - operator. Program to show the implementation of our algorithm Live Demo #include <iostream> #include <stack> using namespace std; bool isOperator(char x) { switch (x) { case '+': case '-': case '/': case '*': return true; } return false; } string convertToPostfix(string prefix) { stack<string> expression; int length = prefix.size(); for (int i = length - 1; i >= 0; i--) { if (isOperator(prefix[i])) { string op1 = expression.top(); expression.pop(); string op2 = expression.top(); expression.pop(); string temp = op1 + op2 + prefix[i]; expression.push(temp); } else expression.push(string(1, prefix[i])); } return expression.top(); } int main() { string prefix = "*-AB/+CD*XY"; cout<<"Prefix expression : "<<prefix<<endl; cout<<"Postfix expression : "<<convertToPostfix(prefix); return 0; } Prefix expression : *-AB/+CD*XY Postfix expression : AB-CD+XY*/*
[ { "code": null, "e": 1182, "s": 1062, "text": "In this problem, we are given a prefix expression. Our task is to print the postfix conversion of the given expression." }, { "code": null, "e": 1263, "s": 1182, "text": "Prefix expression is those expressions which have operators before the operands." }, { "code": null, "e": 1277, "s": 1263, "text": "Example: +AB." }, { "code": null, "e": 1375, "s": 1277, "text": "Postfix expressions are those expressions which have operators after operands in the expressions." }, { "code": null, "e": 1388, "s": 1375, "text": "Example: AB/" }, { "code": null, "e": 1468, "s": 1388, "text": "The conversion of prefix to postfix should not involve the conversion to infix." }, { "code": null, "e": 1517, "s": 1468, "text": "Let’s take an example to understand the problem," }, { "code": null, "e": 1582, "s": 1517, "text": "Input: /+XY+NM\nOutput: XY+NM+/\nExplanation: infix -> (X+Y)/(N+M)" }, { "code": null, "e": 1806, "s": 1582, "text": "To solve this problem, we will first traverse the whole postfix expression in an reverse order. And we will be using the stack data structure for our processing. And do the following for cases of elements found of traversal" }, { "code": null, "e": 1864, "s": 1806, "text": "Case: if the symbol is operand -> push(element) in stack." }, { "code": null, "e": 1978, "s": 1864, "text": "Case: if symbol is operator -> 2*pop(element) from stack. And then push sequence of operand - operand - operator." }, { "code": null, "e": 2030, "s": 1978, "text": "Program to show the implementation of our algorithm" }, { "code": null, "e": 2041, "s": 2030, "text": " Live Demo" }, { "code": null, "e": 2910, "s": 2041, "text": "#include <iostream>\n#include <stack>\nusing namespace std;\nbool isOperator(char x) {\n switch (x) {\n case '+':\n case '-':\n case '/':\n case '*':\n return true;\n }\n return false;\n}\nstring convertToPostfix(string prefix) {\n stack<string> expression;\n int length = prefix.size();\n for (int i = length - 1; i >= 0; i--) {\n if (isOperator(prefix[i])) {\n string op1 = expression.top();\n expression.pop();\n string op2 = expression.top();\n expression.pop();\n string temp = op1 + op2 + prefix[i];\n expression.push(temp);\n }\n else\n expression.push(string(1, prefix[i]));\n }\n return expression.top();\n}\nint main() {\n string prefix = \"*-AB/+CD*XY\";\n cout<<\"Prefix expression : \"<<prefix<<endl;\n cout<<\"Postfix expression : \"<<convertToPostfix(prefix);\n return 0;\n}" }, { "code": null, "e": 2975, "s": 2910, "text": "Prefix expression : *-AB/+CD*XY\nPostfix expression : AB-CD+XY*/*" } ]
JDBC - Drop Database Example
This chapter provides an example on how to drop an existing Database using JDBC application. Before executing the following example, make sure you have the following in place − To execute the following example you need to replace the username and password with your actual user name and password. To execute the following example you need to replace the username and password with your actual user name and password. Your MySQL is up and running. Your MySQL is up and running. NOTE: This is a serious operation and you have to make a firm decision before proceeding to delete a database because everything you have in your database would be lost. The following steps are required to create a new Database using JDBC application − Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. Deleting a database does not require database name to be in your database URL. Following example would delete STUDENTS database. Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server. Deleting a database does not require database name to be in your database URL. Following example would delete STUDENTS database. Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete the database. Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete the database. Clean up the environment − try with resources automatically closes the resources. Clean up the environment − try with resources automatically closes the resources. Copy and paste the following example in JDBCExample.java, compile and run as follows − import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; public class JDBCExample { static final String DB_URL = "jdbc:mysql://localhost/"; static final String USER = "guest"; static final String PASS = "guest123"; public static void main(String[] args) { // Open a connection try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS); Statement stmt = conn.createStatement(); ) { String sql = "DROP DATABASE STUDENTS"; stmt.executeUpdate(sql); System.out.println("Database dropped successfully..."); } catch (SQLException e) { e.printStackTrace(); } } } Now let us compile the above example as follows − C:\>javac JDBCExample.java C:\> When you run JDBCExample, it produces the following result − C:\>java JDBCExample Database dropped successfully... C:\> 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2339, "s": 2162, "text": "This chapter provides an example on how to drop an existing Database using JDBC application. Before executing the following example, make sure you have the following in place −" }, { "code": null, "e": 2459, "s": 2339, "text": "To execute the following example you need to replace the username and password with your actual user name and password." }, { "code": null, "e": 2579, "s": 2459, "text": "To execute the following example you need to replace the username and password with your actual user name and password." }, { "code": null, "e": 2609, "s": 2579, "text": "Your MySQL is up and running." }, { "code": null, "e": 2639, "s": 2609, "text": "Your MySQL is up and running." }, { "code": null, "e": 2809, "s": 2639, "text": "NOTE: This is a serious operation and you have to make a firm decision before proceeding to delete a database because everything you have in your database would be lost." }, { "code": null, "e": 2892, "s": 2809, "text": "The following steps are required to create a new Database using JDBC application −" }, { "code": null, "e": 3064, "s": 2892, "text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice." }, { "code": null, "e": 3236, "s": 3064, "text": "Import the packages − Requires that you include the packages containing the JDBC classes needed for database programming. Most often, using import java.sql.* will suffice." }, { "code": null, "e": 3535, "s": 3236, "text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server.\nDeleting a database does not require database name to be in your database URL. Following example would delete STUDENTS database." }, { "code": null, "e": 3705, "s": 3535, "text": "Open a connection − Requires using the DriverManager.getConnection() method to create a Connection object, which represents a physical connection with a database server." }, { "code": null, "e": 3834, "s": 3705, "text": "Deleting a database does not require database name to be in your database URL. Following example would delete STUDENTS database." }, { "code": null, "e": 3964, "s": 3834, "text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete the database." }, { "code": null, "e": 4094, "s": 3964, "text": "Execute a query − Requires using an object of type Statement for building and submitting an SQL statement to delete the database." }, { "code": null, "e": 4177, "s": 4094, "text": "Clean up the environment − try with resources automatically closes the resources.\n" }, { "code": null, "e": 4259, "s": 4177, "text": "Clean up the environment − try with resources automatically closes the resources." }, { "code": null, "e": 4346, "s": 4259, "text": "Copy and paste the following example in JDBCExample.java, compile and run as follows −" }, { "code": null, "e": 5079, "s": 4346, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\n\npublic class JDBCExample {\n static final String DB_URL = \"jdbc:mysql://localhost/\";\n static final String USER = \"guest\";\n static final String PASS = \"guest123\";\n\n public static void main(String[] args) {\n // Open a connection\n try(Connection conn = DriverManager.getConnection(DB_URL, USER, PASS);\n Statement stmt = conn.createStatement();\n ) {\t\t \n String sql = \"DROP DATABASE STUDENTS\";\n stmt.executeUpdate(sql);\n System.out.println(\"Database dropped successfully...\"); \t \n } catch (SQLException e) {\n e.printStackTrace();\n } \n }\n}" }, { "code": null, "e": 5129, "s": 5079, "text": "Now let us compile the above example as follows −" }, { "code": null, "e": 5161, "s": 5129, "text": "C:\\>javac JDBCExample.java\nC:\\>" }, { "code": null, "e": 5222, "s": 5161, "text": "When you run JDBCExample, it produces the following result −" }, { "code": null, "e": 5282, "s": 5222, "text": "C:\\>java JDBCExample\nDatabase dropped successfully...\nC:\\>\n" }, { "code": null, "e": 5315, "s": 5282, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 5331, "s": 5315, "text": " Malhar Lathkar" }, { "code": null, "e": 5364, "s": 5331, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 5380, "s": 5364, "text": " Malhar Lathkar" }, { "code": null, "e": 5415, "s": 5380, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5429, "s": 5415, "text": " Anadi Sharma" }, { "code": null, "e": 5463, "s": 5429, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 5477, "s": 5463, "text": " Tushar Kale" }, { "code": null, "e": 5514, "s": 5477, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 5529, "s": 5514, "text": " Monica Mittal" }, { "code": null, "e": 5562, "s": 5529, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 5581, "s": 5562, "text": " Arnab Chakraborty" }, { "code": null, "e": 5588, "s": 5581, "text": " Print" }, { "code": null, "e": 5599, "s": 5588, "text": " Add Notes" } ]
Getting Started with the Yelp API | by Raymond Willey | Towards Data Science
This post is part one of a series in which we explore how small businesses can leverage Yelp data to better understand their position in local markets. Before diving into the nitty-gritty, I would like to start by telling you a bit about the inspiration and objectives of this project. Of course, if you are just interested in the technical part, you can skip to it here. I moved to New York City in 2012, and in the last seven years, I have already seen some of my favorite local businesses go under. Slowly but surely, the big-name brands start moving-in. Sure, we could talk all day about economies of scale and rising rents, but the power of the purse also allows large corporations to take advantage of massive quantities of data in ways that small firms can’t. It’s time we start closing that gap. Through this series, we are going to perform an analysis of one of my favorite Mexican restaurants in Astoria: Chano’s Cantina. Unlike other, more prominent neighborhoods of New York City, Astoria maintains a unique identity that is freckled with an array of local cuisines. No doubt, it benefits from being a neighborhood of the most diverse borough in the city. But this also means that every restaurant has a wide array of competitors, making it that much more difficult for any local restaurant to differentiate itself. Indeed, a quick search of Yelp for Mexican restaurants in Astoria yields 24 pages of results. Our goal is simple: to identify the top five to ten competitors to the business of interest, then use natural language processing and sentiment analysis to determine what the firm does well and what it needs to work on. To do this will require a host of data science techniques, which we will go through one at a time through each part of this series. These include, but are not limited to: Accessing data using the Yelp API K-Means Clustering Web Scraping Sentiment Analysis/NLP Supervised Machine Learning Neural Networks Now, you may be asking yourself, how is a small business that is not well-versed in this type of analysis supposed to implement all of this? Ultimately we want to deploy this in a clean module that requires little more than a few basic inputs: Company Name (as it appears on Yelp): Chano’s Cantina Location (Zip or City, St): Astoria, NY Search Terms (any phrase or combination of phrases that a potential customer might use to find the business on Yelp): Mexican restaurant bar Without further adieu, let’s start building and get set up with the Yelp API. First things first: if you want to access data using the Yelp API, Yelp needs to be able to authenticate your identity. This is accomplished by generating an access token through your Yelp account. If you don’t already have a Yelp account, you will need to create one. By clicking on the link above, you should end up on a page that looks like this: It’s a good idea to create a new token with a different App Name for each, separate project. The mandatory fields are: App Name Industry Contact Email Description No need to overthink these, simply fill them out as best you can, agree to the terms and conditions (don’t worry, I checked, and there’s no HumancentiPad clause), and then confirm for the robot that you are not a robot. On the next page, you’ll be provided with a Client ID and Token. You’ll notice that I have mine blurred out, and that’s because you don’t want to share your token with others. If someone with malintent were to get ahold of your token, they could potentially use it in ways that would get your account suspended, or worse. In other words: Ideally, you’ll want to save these as environment variables. For more detailed information on this topic, this piece is a great place to start. For now, you can hardcode these into your Jupyter Notebook as follows: client_id = your_unique_client_idapi_key = your_unique_api_key Now that we have that out of the way, we can start making calls to the Yelp API for new data. In our case, we want to search for Mexican restaurants & bars in Astoria, NY, and save the results to a dataframe. The first step is to install the Yelp API via the command line. pip install yelpapi With the API installed, you can now load it into any Jupyter Notebook with: from yelpapi import YelpAPIyelp_api = YelpAPI(api_key) Easy peasy! Now, a request to the Yelp API is going to require three parts: Search Term: Search terms used in a standard Yelp search. Location: City, St or Zip Code Search Limit: How many results do you want (max 50)? We want to find Mexican restaurants & bars in Astoria, NY, so we pass the required data into a search query like this: term = 'Mexican restaurant bar'location = 'Astoria, NY'search_limit = 50response = yelp_api.search_query(term = term, location = location, limit = search_limit)type(response)--------------OUTPUT:dict As you can see, we save the search results to a response variable, and it is a dictionary. With further inspection, we would see that this dictionary has three keys: Businesses Total Region For our purposes, we are interested in businesses data. With further evaluation, you will find that the data in this key is a list of dictionaries, each of which represents a different business, and all of which have the same keys. This allows us to set the list of keys as column names, and use the values as data in a dataframe. We can accomplish this with a few lines of code: cols = list(response['businesses'][0].keys())data = pd.DataFrame(columns=cols)for biz in response['businesses']: data = data.append(biz, ignore_index=True)data.head() And voila! We have a dataframe that contains all the information we would typically see when using the traditional Yelp search, but in a format that we can use for analysis. As you can see, accessing data using the Yelp API is very simple and quite handy. In the next post, we’ll have a look at the categorical tags, and use K-Means Clustering to find out which restaurants present themselves most similarly to Chano’s Cantina. We will treat these as the most direct competitors for a more in-depth analysis. For more information on the broader functionality of the Yelp API, check out the documentation.
[ { "code": null, "e": 544, "s": 172, "text": "This post is part one of a series in which we explore how small businesses can leverage Yelp data to better understand their position in local markets. Before diving into the nitty-gritty, I would like to start by telling you a bit about the inspiration and objectives of this project. Of course, if you are just interested in the technical part, you can skip to it here." }, { "code": null, "e": 976, "s": 544, "text": "I moved to New York City in 2012, and in the last seven years, I have already seen some of my favorite local businesses go under. Slowly but surely, the big-name brands start moving-in. Sure, we could talk all day about economies of scale and rising rents, but the power of the purse also allows large corporations to take advantage of massive quantities of data in ways that small firms can’t. It’s time we start closing that gap." }, { "code": null, "e": 1104, "s": 976, "text": "Through this series, we are going to perform an analysis of one of my favorite Mexican restaurants in Astoria: Chano’s Cantina." }, { "code": null, "e": 1594, "s": 1104, "text": "Unlike other, more prominent neighborhoods of New York City, Astoria maintains a unique identity that is freckled with an array of local cuisines. No doubt, it benefits from being a neighborhood of the most diverse borough in the city. But this also means that every restaurant has a wide array of competitors, making it that much more difficult for any local restaurant to differentiate itself. Indeed, a quick search of Yelp for Mexican restaurants in Astoria yields 24 pages of results." }, { "code": null, "e": 1985, "s": 1594, "text": "Our goal is simple: to identify the top five to ten competitors to the business of interest, then use natural language processing and sentiment analysis to determine what the firm does well and what it needs to work on. To do this will require a host of data science techniques, which we will go through one at a time through each part of this series. These include, but are not limited to:" }, { "code": null, "e": 2019, "s": 1985, "text": "Accessing data using the Yelp API" }, { "code": null, "e": 2038, "s": 2019, "text": "K-Means Clustering" }, { "code": null, "e": 2051, "s": 2038, "text": "Web Scraping" }, { "code": null, "e": 2074, "s": 2051, "text": "Sentiment Analysis/NLP" }, { "code": null, "e": 2102, "s": 2074, "text": "Supervised Machine Learning" }, { "code": null, "e": 2118, "s": 2102, "text": "Neural Networks" }, { "code": null, "e": 2362, "s": 2118, "text": "Now, you may be asking yourself, how is a small business that is not well-versed in this type of analysis supposed to implement all of this? Ultimately we want to deploy this in a clean module that requires little more than a few basic inputs:" }, { "code": null, "e": 2416, "s": 2362, "text": "Company Name (as it appears on Yelp): Chano’s Cantina" }, { "code": null, "e": 2456, "s": 2416, "text": "Location (Zip or City, St): Astoria, NY" }, { "code": null, "e": 2597, "s": 2456, "text": "Search Terms (any phrase or combination of phrases that a potential customer might use to find the business on Yelp): Mexican restaurant bar" }, { "code": null, "e": 2675, "s": 2597, "text": "Without further adieu, let’s start building and get set up with the Yelp API." }, { "code": null, "e": 3025, "s": 2675, "text": "First things first: if you want to access data using the Yelp API, Yelp needs to be able to authenticate your identity. This is accomplished by generating an access token through your Yelp account. If you don’t already have a Yelp account, you will need to create one. By clicking on the link above, you should end up on a page that looks like this:" }, { "code": null, "e": 3144, "s": 3025, "text": "It’s a good idea to create a new token with a different App Name for each, separate project. The mandatory fields are:" }, { "code": null, "e": 3153, "s": 3144, "text": "App Name" }, { "code": null, "e": 3162, "s": 3153, "text": "Industry" }, { "code": null, "e": 3176, "s": 3162, "text": "Contact Email" }, { "code": null, "e": 3188, "s": 3176, "text": "Description" }, { "code": null, "e": 3473, "s": 3188, "text": "No need to overthink these, simply fill them out as best you can, agree to the terms and conditions (don’t worry, I checked, and there’s no HumancentiPad clause), and then confirm for the robot that you are not a robot. On the next page, you’ll be provided with a Client ID and Token." }, { "code": null, "e": 3746, "s": 3473, "text": "You’ll notice that I have mine blurred out, and that’s because you don’t want to share your token with others. If someone with malintent were to get ahold of your token, they could potentially use it in ways that would get your account suspended, or worse. In other words:" }, { "code": null, "e": 3890, "s": 3746, "text": "Ideally, you’ll want to save these as environment variables. For more detailed information on this topic, this piece is a great place to start." }, { "code": null, "e": 3961, "s": 3890, "text": "For now, you can hardcode these into your Jupyter Notebook as follows:" }, { "code": null, "e": 4024, "s": 3961, "text": "client_id = your_unique_client_idapi_key = your_unique_api_key" }, { "code": null, "e": 4297, "s": 4024, "text": "Now that we have that out of the way, we can start making calls to the Yelp API for new data. In our case, we want to search for Mexican restaurants & bars in Astoria, NY, and save the results to a dataframe. The first step is to install the Yelp API via the command line." }, { "code": null, "e": 4317, "s": 4297, "text": "pip install yelpapi" }, { "code": null, "e": 4393, "s": 4317, "text": "With the API installed, you can now load it into any Jupyter Notebook with:" }, { "code": null, "e": 4448, "s": 4393, "text": "from yelpapi import YelpAPIyelp_api = YelpAPI(api_key)" }, { "code": null, "e": 4524, "s": 4448, "text": "Easy peasy! Now, a request to the Yelp API is going to require three parts:" }, { "code": null, "e": 4582, "s": 4524, "text": "Search Term: Search terms used in a standard Yelp search." }, { "code": null, "e": 4613, "s": 4582, "text": "Location: City, St or Zip Code" }, { "code": null, "e": 4666, "s": 4613, "text": "Search Limit: How many results do you want (max 50)?" }, { "code": null, "e": 4785, "s": 4666, "text": "We want to find Mexican restaurants & bars in Astoria, NY, so we pass the required data into a search query like this:" }, { "code": null, "e": 5049, "s": 4785, "text": "term = 'Mexican restaurant bar'location = 'Astoria, NY'search_limit = 50response = yelp_api.search_query(term = term, location = location, limit = search_limit)type(response)--------------OUTPUT:dict" }, { "code": null, "e": 5140, "s": 5049, "text": "As you can see, we save the search results to a response variable, and it is a dictionary." }, { "code": null, "e": 5215, "s": 5140, "text": "With further inspection, we would see that this dictionary has three keys:" }, { "code": null, "e": 5226, "s": 5215, "text": "Businesses" }, { "code": null, "e": 5232, "s": 5226, "text": "Total" }, { "code": null, "e": 5239, "s": 5232, "text": "Region" }, { "code": null, "e": 5619, "s": 5239, "text": "For our purposes, we are interested in businesses data. With further evaluation, you will find that the data in this key is a list of dictionaries, each of which represents a different business, and all of which have the same keys. This allows us to set the list of keys as column names, and use the values as data in a dataframe. We can accomplish this with a few lines of code:" }, { "code": null, "e": 5789, "s": 5619, "text": "cols = list(response['businesses'][0].keys())data = pd.DataFrame(columns=cols)for biz in response['businesses']: data = data.append(biz, ignore_index=True)data.head()" }, { "code": null, "e": 5963, "s": 5789, "text": "And voila! We have a dataframe that contains all the information we would typically see when using the traditional Yelp search, but in a format that we can use for analysis." }, { "code": null, "e": 6298, "s": 5963, "text": "As you can see, accessing data using the Yelp API is very simple and quite handy. In the next post, we’ll have a look at the categorical tags, and use K-Means Clustering to find out which restaurants present themselves most similarly to Chano’s Cantina. We will treat these as the most direct competitors for a more in-depth analysis." } ]
jQuery - Plugins
A plug-in is piece of code written in a standard JavaScript file. These files provide useful jQuery methods which can be used along with jQuery library methods. There are plenty of jQuery plug-in available which you can download from repository link at https://jquery.com/plugins. To make a plug-in's methods available to us, we include plug-in file very similar to jQuery library file in the <head> of the document. We must ensure that it appears after the main jQuery source file, and before our custom JavaScript code. Following example shows how to include jquery.plug-in.js plugin − <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script src = "jquery.plug-in.js" type = "text/javascript"></script> <script src = "custom.js" type = "text/javascript"></script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { .......your custom code..... }); </script> </head> <body> ............................. </body> </html> This is very simple to write your own plug-in. Following is the syntax to create a a method − jQuery.fn.methodName = methodDefinition; Here methodNameM is the name of new method and methodDefinition is actual method definition. The guideline recommended by the jQuery team is as follows − Any methods or functions you attach must have a semicolon (;) at the end. Any methods or functions you attach must have a semicolon (;) at the end. Your method must return the jQuery object, unless explicity noted otherwise. Your method must return the jQuery object, unless explicity noted otherwise. You should use this.each to iterate over the current set of matched elements - it produces clean and compatible code that way. You should use this.each to iterate over the current set of matched elements - it produces clean and compatible code that way. Prefix the filename with jquery, follow that with the name of the plugin and conclude with .js. Prefix the filename with jquery, follow that with the name of the plugin and conclude with .js. Always attach the plugin to jQuery directly instead of $, so users can use a custom alias via noConflict() method. Always attach the plugin to jQuery directly instead of $, so users can use a custom alias via noConflict() method. For example, if we write a plugin that we want to name debug, our JavaScript filename for this plugin is − jquery.debug.js The use of the jquery. prefix eliminates any possible name collisions with files intended for use with other libraries. Following is a small plug-in to have warning method for debugging purpose. Keep this code in jquery.debug.js file − jQuery.fn.warning = function() { return this.each(function() { alert('Tag Name:"' + $(this).prop("tagName") + '".'); }); }; Here is the example showing usage of warning() method. Assuming we put jquery.debug.js file in same directory of html page. <html> <head> <title>The jQuery Example</title> <script type = "text/javascript" src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script src = "jquery.debug.js" type = "text/javascript"> </script> <script type = "text/javascript" language = "javascript"> $(document).ready(function() { $("div").warning(); $("p").warning(); }); </script> </head> <body> <p>This is paragraph</p> <div>This is division</div> </body> </html> This would alert you with following result − This is paragraph This is division 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2483, "s": 2322, "text": "A plug-in is piece of code written in a standard JavaScript file. These files provide useful jQuery methods which can be used along with jQuery library methods." }, { "code": null, "e": 2603, "s": 2483, "text": "There are plenty of jQuery plug-in available which you can download from repository link at https://jquery.com/plugins." }, { "code": null, "e": 2739, "s": 2603, "text": "To make a plug-in's methods available to us, we include plug-in file very similar to jQuery library file in the <head> of the document." }, { "code": null, "e": 2844, "s": 2739, "text": "We must ensure that it appears after the main jQuery source file, and before our custom JavaScript code." }, { "code": null, "e": 2910, "s": 2844, "text": "Following example shows how to include jquery.plug-in.js plugin −" }, { "code": null, "e": 3511, "s": 2910, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\n <script src = \"jquery.plug-in.js\" type = \"text/javascript\"></script>\n <script src = \"custom.js\" type = \"text/javascript\"></script>\n \n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n .......your custom code.....\n });\n </script>\n </head>\n\t\n <body>\n .............................\n </body>\n</html>" }, { "code": null, "e": 3605, "s": 3511, "text": "This is very simple to write your own plug-in. Following is the syntax to create a a method −" }, { "code": null, "e": 3647, "s": 3605, "text": "jQuery.fn.methodName = methodDefinition;\n" }, { "code": null, "e": 3741, "s": 3647, "text": "Here methodNameM is the name of new method and methodDefinition is actual method definition." }, { "code": null, "e": 3802, "s": 3741, "text": "The guideline recommended by the jQuery team is as follows −" }, { "code": null, "e": 3876, "s": 3802, "text": "Any methods or functions you attach must have a semicolon (;) at the end." }, { "code": null, "e": 3950, "s": 3876, "text": "Any methods or functions you attach must have a semicolon (;) at the end." }, { "code": null, "e": 4027, "s": 3950, "text": "Your method must return the jQuery object, unless explicity noted otherwise." }, { "code": null, "e": 4104, "s": 4027, "text": "Your method must return the jQuery object, unless explicity noted otherwise." }, { "code": null, "e": 4231, "s": 4104, "text": "You should use this.each to iterate over the current set of matched elements - it produces clean and compatible code that way." }, { "code": null, "e": 4358, "s": 4231, "text": "You should use this.each to iterate over the current set of matched elements - it produces clean and compatible code that way." }, { "code": null, "e": 4454, "s": 4358, "text": "Prefix the filename with jquery, follow that with the name of the plugin and conclude with .js." }, { "code": null, "e": 4550, "s": 4454, "text": "Prefix the filename with jquery, follow that with the name of the plugin and conclude with .js." }, { "code": null, "e": 4665, "s": 4550, "text": "Always attach the plugin to jQuery directly instead of $, so users can use a custom alias via noConflict() method." }, { "code": null, "e": 4780, "s": 4665, "text": "Always attach the plugin to jQuery directly instead of $, so users can use a custom alias via noConflict() method." }, { "code": null, "e": 4887, "s": 4780, "text": "For example, if we write a plugin that we want to name debug, our JavaScript filename for this plugin is −" }, { "code": null, "e": 4904, "s": 4887, "text": "jquery.debug.js\n" }, { "code": null, "e": 5024, "s": 4904, "text": "The use of the jquery. prefix eliminates any possible name collisions with files intended for use with other libraries." }, { "code": null, "e": 5140, "s": 5024, "text": "Following is a small plug-in to have warning method for debugging purpose. Keep this code in jquery.debug.js file −" }, { "code": null, "e": 5276, "s": 5140, "text": "jQuery.fn.warning = function() {\n return this.each(function() {\n alert('Tag Name:\"' + $(this).prop(\"tagName\") + '\".');\n });\n};" }, { "code": null, "e": 5400, "s": 5276, "text": "Here is the example showing usage of warning() method. Assuming we put jquery.debug.js file in same directory of html page." }, { "code": null, "e": 5986, "s": 5400, "text": "<html>\n <head>\n <title>The jQuery Example</title>\n\t\t\n <script type = \"text/javascript\" \n src = \"https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n\t\t\n <script src = \"jquery.debug.js\" type = \"text/javascript\">\n </script>\n\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n $(\"div\").warning();\n $(\"p\").warning();\n });\n </script>\t\n </head>\n\t\n <body>\n <p>This is paragraph</p>\n <div>This is division</div>\n </body>\n</html>" }, { "code": null, "e": 6031, "s": 5986, "text": "This would alert you with following result −" }, { "code": null, "e": 6067, "s": 6031, "text": "This is paragraph\nThis is division\n" }, { "code": null, "e": 6100, "s": 6067, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 6114, "s": 6100, "text": " Mahesh Kumar" }, { "code": null, "e": 6149, "s": 6114, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6163, "s": 6149, "text": " Pratik Singh" }, { "code": null, "e": 6198, "s": 6163, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6215, "s": 6198, "text": " Frahaan Hussain" }, { "code": null, "e": 6248, "s": 6215, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 6276, "s": 6248, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6309, "s": 6276, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 6330, "s": 6309, "text": " Sandip Bhattacharya" }, { "code": null, "e": 6362, "s": 6330, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 6379, "s": 6362, "text": " Laurence Svekis" }, { "code": null, "e": 6386, "s": 6379, "text": " Print" }, { "code": null, "e": 6397, "s": 6386, "text": " Add Notes" } ]
Map containsValue() method in Java with Examples - GeeksforGeeks
31 Dec, 2018 The java.util.Map.containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the Map. It takes the value as a parameter and returns True if that value is mapped by any of the key in the map. Syntax: boolean containsValue(Object Value) Parameters: The method takes just one parameter Value of Object type and refers to the value whose mapping is supposed to be checked by any key inside the map. Return Value: The method returns boolean true if the mapping of the value is detected else false. Below programs illustrate the java.util.Map.containsValue() method: Program 1: Mapping String Values to Integer Keys. // Java code to illustrate the containsValue() method import java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<Integer, String> map = new HashMap<Integer, String>(); // Mapping string values to int keys map.put(10, "Geeks"); map.put(15, "4"); map.put(20, "Geeks"); map.put(25, "Welcomes"); map.put(30, "You"); // Displaying the Map System.out.println("Initial Mappings are: " + map); // Checking for the Value 'Geeks' System.out.println("Is the value 'Geeks' present? " + map.containsValue("Geeks")); // Checking for the Value 'World' System.out.println("Is the value 'World' present? " + map.containsValue("World")); }} Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4} Is the value 'Geeks' present? true Is the value 'World' present? false Program 2: Mapping Integer Values to String Keys. // Java code to illustrate the containsValue() method import java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<String, Integer> map = new HashMap<String, Integer>(); // Mapping int values to string keys map.put("Geeks", 10); map.put("4", 15); map.put("Geeks", 20); map.put("Welcomes", 25); map.put("You", 30); // Displaying the Map System.out.println("Initial Mappings are: " + map); // Checking for the Value '10' System.out.println("Is the value '10' present? " + map.containsValue(10)); // Checking for the Value '30' System.out.println("Is the value '30' present? " + map.containsValue(30)); // Checking for the Value '40' System.out.println("Is the value '40' present? " + map.containsValue(40)); }} Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25} Is the value '10' present? false Is the value '30' present? true Is the value '40' present? false Note: The same operation can be performed with any type of Mappings with variation and combination of different data types. Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#containsValue(java.lang.Object) Java-Collections Java-Functions java-map Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in Java Stream In Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Internal Working of HashMap in Java Checked vs Unchecked Exceptions in Java Strings in Java StringBuilder Class in Java with Examples
[ { "code": null, "e": 23868, "s": 23840, "text": "\n31 Dec, 2018" }, { "code": null, "e": 24119, "s": 23868, "text": "The java.util.Map.containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the Map. It takes the value as a parameter and returns True if that value is mapped by any of the key in the map." }, { "code": null, "e": 24127, "s": 24119, "text": "Syntax:" }, { "code": null, "e": 24163, "s": 24127, "text": "boolean containsValue(Object Value)" }, { "code": null, "e": 24323, "s": 24163, "text": "Parameters: The method takes just one parameter Value of Object type and refers to the value whose mapping is supposed to be checked by any key inside the map." }, { "code": null, "e": 24421, "s": 24323, "text": "Return Value: The method returns boolean true if the mapping of the value is detected else false." }, { "code": null, "e": 24489, "s": 24421, "text": "Below programs illustrate the java.util.Map.containsValue() method:" }, { "code": null, "e": 24539, "s": 24489, "text": "Program 1: Mapping String Values to Integer Keys." }, { "code": "// Java code to illustrate the containsValue() method import java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<Integer, String> map = new HashMap<Integer, String>(); // Mapping string values to int keys map.put(10, \"Geeks\"); map.put(15, \"4\"); map.put(20, \"Geeks\"); map.put(25, \"Welcomes\"); map.put(30, \"You\"); // Displaying the Map System.out.println(\"Initial Mappings are: \" + map); // Checking for the Value 'Geeks' System.out.println(\"Is the value 'Geeks' present? \" + map.containsValue(\"Geeks\")); // Checking for the Value 'World' System.out.println(\"Is the value 'World' present? \" + map.containsValue(\"World\")); }}", "e": 25334, "s": 24539, "text": null }, { "code": null, "e": 25476, "s": 25334, "text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nIs the value 'Geeks' present? true\nIs the value 'World' present? false\n" }, { "code": null, "e": 25526, "s": 25476, "text": "Program 2: Mapping Integer Values to String Keys." }, { "code": "// Java code to illustrate the containsValue() method import java.util.*; public class Map_Demo { public static void main(String[] args) { // Creating an empty Map Map<String, Integer> map = new HashMap<String, Integer>(); // Mapping int values to string keys map.put(\"Geeks\", 10); map.put(\"4\", 15); map.put(\"Geeks\", 20); map.put(\"Welcomes\", 25); map.put(\"You\", 30); // Displaying the Map System.out.println(\"Initial Mappings are: \" + map); // Checking for the Value '10' System.out.println(\"Is the value '10' present? \" + map.containsValue(10)); // Checking for the Value '30' System.out.println(\"Is the value '30' present? \" + map.containsValue(30)); // Checking for the Value '40' System.out.println(\"Is the value '40' present? \" + map.containsValue(40)); }}", "e": 26421, "s": 25526, "text": null }, { "code": null, "e": 26580, "s": 26421, "text": "Initial Mappings are: {4=15, Geeks=20, You=30, Welcomes=25}\nIs the value '10' present? false\nIs the value '30' present? true\nIs the value '40' present? false\n" }, { "code": null, "e": 26704, "s": 26580, "text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types." }, { "code": null, "e": 26808, "s": 26704, "text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Map.html#containsValue(java.lang.Object)" }, { "code": null, "e": 26825, "s": 26808, "text": "Java-Collections" }, { "code": null, "e": 26840, "s": 26825, "text": "Java-Functions" }, { "code": null, "e": 26849, "s": 26840, "text": "java-map" }, { "code": null, "e": 26854, "s": 26849, "text": "Java" }, { "code": null, "e": 26859, "s": 26854, "text": "Java" }, { "code": null, "e": 26876, "s": 26859, "text": "Java-Collections" }, { "code": null, "e": 26974, "s": 26876, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26983, "s": 26974, "text": "Comments" }, { "code": null, "e": 26996, "s": 26983, "text": "Old Comments" }, { "code": null, "e": 27017, "s": 26996, "text": "Constructors in Java" }, { "code": null, "e": 27032, "s": 27017, "text": "Stream In Java" }, { "code": null, "e": 27051, "s": 27032, "text": "Exceptions in Java" }, { "code": null, "e": 27081, "s": 27051, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27127, "s": 27081, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27153, "s": 27127, "text": "Java Programming Examples" }, { "code": null, "e": 27189, "s": 27153, "text": "Internal Working of HashMap in Java" }, { "code": null, "e": 27229, "s": 27189, "text": "Checked vs Unchecked Exceptions in Java" }, { "code": null, "e": 27245, "s": 27229, "text": "Strings in Java" } ]
5 Awesome NumPy Functions That Can Save You in a Pinch | by Eirik Berge | Towards Data Science
Setting the Stage 1 — Quick Filtering 2 — Reshaping Yourself Out of Trouble 3 — Restructuring Your Shape 4 — Find Unique Values 5 — Combine Arrays Wrapping Up When doing data science in Python, the package NumPy is omnipresent. Whether you are developing machine learning models with Scikit-Learn or plotting in Matplotlib, you’re sure to have a few NumPy arrays laying around in your code. When I started with data science in Python, I had a poor grasp of what could be done with NumPy. Over the years, I have sharpened my NumPy skills and become a better data scientist because of it. Being good at manipulating NumPy arrays can save your life...or at least an hour of frustrating searching. The five NumPy functions I give you here can help you when things get tough 🔥 Throughout the blog post, I assume you have installed NumPy and have already imported NumPy with the alias np : import numpy as np I recommend having seen NumPy previously before reading this blog. If you are completely new to NumPy, then you can check out NumPy’s Beginners Guide or this YouTube video series on NumPy. You can use the where function to quickly filter an array based on a condition. Say you have an audio signal represented as a one-dimensional array: # Audio Signal (in Hz)signal = np.array([23, 50, 900, 12, 1100, 10, 2746, 9, 8]) Let’s say that you want to remove everything in signal that has a Hz of less than 20. To efficiently do this in NumPy you can write: # Filter the signalfiltered_signal = np.where(signal >= 20, signal, 0)# Print out the resultprint(filtered_signal)>>> np.array([23, 50, 900, 0, 1100, 0, 2746, 0, 0]) The where function takes three arguments: The first argument (in our example signal >= 20 ) gives the condition you want to use for the filtering. The second argument (in our example signal ) specifies what you want to happen when the condition is satisfied. The third argument (in our example 0 ) specifies what you want to happen when the condition is not satisfied. As a second example, assume you have an array high-pitch indicating whether the pitch of the sounds should be raised: # Audio Signal (in Hz)signal = np.array([23, 50, 900, 760, 12])# Rasing pitchhigh_pitch = np.array([True, False, True, True, False]) To raise the pitch of signal whenever the corresponding high-pitch variable says so, you can simply write: # Creating a high-pitch signalhigh_pitch_signal = np.where(high_pitch, signal + 1000, signal)# Printing out the resultprint(high_pitch_signal)>>> np.array([1023, 50, 1900, 1760, 12]) That was easy 😃 Often one has an array with the correct elements, but with the wrong form. More specifically, assume you have the following one-dimensional array: my_array = np.array([5, 3, 17, 4, 3])print(my_array.shape)>>> (5,) Here you can see that the array is one-dimensional. You want to feed my_array into another function that expects a two-dimensional input? This happens surprisingly often with libraries like Scikit-Learn! To do this, you can use the reshape function: my_array = np.array([5, 3, 17, 4, 3]).reshape(5, 1)print(my_array.shape)>>> (5, 1) Now my_array is properly two-dimensional. You can think of my_array as a matrix with five rows and a single column. If you want to go back to my_array being one-dimensional, then you can write: my_array = my_array.reshape(5)print(my_array.shape)>>> (5,) Pro Tip: As a shorthand, you can use the NumPy function squeeze to remove all dimensions that have length one. Hence you could have used the squeeze function instead of the reshape function above. You will sometimes need to reshuffle the dimensions you already have. An example will make this clear: Say you have represented an RGB image of size 1280x720 (this is the size of YouTube thumbnails) as a NumPy array called my_image . Your image has the shape (720, 1280, 3) . The number 3 comes from the fact that there are 3 colour channels: red, green, and blue. How do you rearrange my_image so that the RGB channels populate the first dimension? You can do that easily with the moveaxis function: restructured = np.moveaxis(my_image, [0, 1, 2], [2, 0, 1])print(restrctured.shape)>>> (3, 720, 1280) With this simple command you have restructured the image. The two lists in moveaxis specify the source and destination positions of the axes. Pro Tip: NumPy has other functions such as swapaxes and transpose that also deal with restructuring arrays. The moveaxis function is the most general, and the one I use most of the time. Many people think that reshaping with the reshape function and restructuring with the moveaxis function is the same. Yet, they work in different ways 😦 The best way to see this is with an example: Say that you have the matrix: matrix = np.array([[1, 2], [3, 4], [5, 6]])# The matrix looks like this:1 23 45 6 If you use the moveaxis function to switch the two axes, then you get: restructured_matrix = np.moveaxis(matrix, [0, 1], [1, 0])# The restructured matrix looks like this:1 3 52 4 6 However, if you use the reshape function, then you get: reshaped_matrix = matrix.reshape(2, 3)# The reshaped matrix looks like this:1 2 34 5 6 The reshape function simply proceeds row-wise and makes new rows whenever appropriate. The unique function is a sweet utility function for finding the unique elements of an array. Say that you have an array representing the favourite cities of people sampled from a poll: # Favorite citiescities = np.array(["Paris", "London", "Vienna", "Paris", "Oslo", "London", "Paris"]) Then you can use the unique function to get the unique values in the array cities : unique_cities = np.unique(cities)print(unique_cities)>>> ['London' 'Oslo' 'Paris' 'Vienna'] Notice that the unique cities are not necessarily in the order they originally appeared in (e.g. Oslo is before Paris). With polls, it is really common to draw bar charts. In those charts, the categories are the poll options while the height of the bars represent the number of votes each option got. To get that information, you can use the optional argument return_counts as follows: unique_cities, counts = np.unique(cities, return_counts=True)print(unique_cities)>>> ['London' 'Oslo' 'Paris' 'Vienna']print(counts)>>> [2 1 3 1] The unique function saves you from writing a lot of annoying loops 😍 Sometimes, you will be working with many arrays at the same time. Then it is often convenient to combine the arrays into a single “master” array. Doing this in NumPy is easy with the concatenate function. Let's say that you have two one-dimensional arrays: array1 = np.arange(10)array2 = np.arange(10, 20) Then you can combine them into a longer one-dimensional array with concatenate : # Need to put the arrays into a tuplelong_array = np.concatenate((array1, array2))print(long_array)>>> [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19] What if you wanted to stack array1 and array2 on top of each other? You are hence looking to create a two-dimensional vector that looks like this: [[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19]] You can first reshape array1 and array2 into two-dimensional arrays with the reshape function: array1 = array1.reshape(10, 1)array2 = array2.reshape(10, 1) Now you can use the optional axis parameter in the concatenate function to combine them correctly: stacked_array = np.concatenate((array1, array2), axis=1)print(stacked_array)>>> [[ 0 10] [ 1 11] [ 2 12] [ 3 13] [ 4 14] [ 5 15] [ 6 16] [ 7 17] [ 8 18] [ 9 19]] Almost there...You can now use the moveaxis function to finish the job: stacked_array = np.moveaxis(stacked_array, [0, 1], [1, 0])print(stacked_array)>>> [[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19]] Awesome! I hope this example showed you how some of the different tools you have just learned can come together. You should now feel comfortable using NumPy for a few tricky situations. If you need to learn more about NumPy, then check out the NumPy documentation. Like my writing? Check out my blog posts Type Hints, Formatting with Black, Underscores in Python, and 5 Dictionary Tips for more Python content. If you are interested in data science, programming, or anything in between, then feel free to add me on LinkedIn and say hi ✋
[ { "code": null, "e": 189, "s": 171, "text": "Setting the Stage" }, { "code": null, "e": 209, "s": 189, "text": "1 — Quick Filtering" }, { "code": null, "e": 247, "s": 209, "text": "2 — Reshaping Yourself Out of Trouble" }, { "code": null, "e": 276, "s": 247, "text": "3 — Restructuring Your Shape" }, { "code": null, "e": 299, "s": 276, "text": "4 — Find Unique Values" }, { "code": null, "e": 318, "s": 299, "text": "5 — Combine Arrays" }, { "code": null, "e": 330, "s": 318, "text": "Wrapping Up" }, { "code": null, "e": 562, "s": 330, "text": "When doing data science in Python, the package NumPy is omnipresent. Whether you are developing machine learning models with Scikit-Learn or plotting in Matplotlib, you’re sure to have a few NumPy arrays laying around in your code." }, { "code": null, "e": 758, "s": 562, "text": "When I started with data science in Python, I had a poor grasp of what could be done with NumPy. Over the years, I have sharpened my NumPy skills and become a better data scientist because of it." }, { "code": null, "e": 943, "s": 758, "text": "Being good at manipulating NumPy arrays can save your life...or at least an hour of frustrating searching. The five NumPy functions I give you here can help you when things get tough 🔥" }, { "code": null, "e": 1055, "s": 943, "text": "Throughout the blog post, I assume you have installed NumPy and have already imported NumPy with the alias np :" }, { "code": null, "e": 1074, "s": 1055, "text": "import numpy as np" }, { "code": null, "e": 1263, "s": 1074, "text": "I recommend having seen NumPy previously before reading this blog. If you are completely new to NumPy, then you can check out NumPy’s Beginners Guide or this YouTube video series on NumPy." }, { "code": null, "e": 1412, "s": 1263, "text": "You can use the where function to quickly filter an array based on a condition. Say you have an audio signal represented as a one-dimensional array:" }, { "code": null, "e": 1493, "s": 1412, "text": "# Audio Signal (in Hz)signal = np.array([23, 50, 900, 12, 1100, 10, 2746, 9, 8])" }, { "code": null, "e": 1626, "s": 1493, "text": "Let’s say that you want to remove everything in signal that has a Hz of less than 20. To efficiently do this in NumPy you can write:" }, { "code": null, "e": 1792, "s": 1626, "text": "# Filter the signalfiltered_signal = np.where(signal >= 20, signal, 0)# Print out the resultprint(filtered_signal)>>> np.array([23, 50, 900, 0, 1100, 0, 2746, 0, 0])" }, { "code": null, "e": 1834, "s": 1792, "text": "The where function takes three arguments:" }, { "code": null, "e": 1939, "s": 1834, "text": "The first argument (in our example signal >= 20 ) gives the condition you want to use for the filtering." }, { "code": null, "e": 2051, "s": 1939, "text": "The second argument (in our example signal ) specifies what you want to happen when the condition is satisfied." }, { "code": null, "e": 2161, "s": 2051, "text": "The third argument (in our example 0 ) specifies what you want to happen when the condition is not satisfied." }, { "code": null, "e": 2279, "s": 2161, "text": "As a second example, assume you have an array high-pitch indicating whether the pitch of the sounds should be raised:" }, { "code": null, "e": 2412, "s": 2279, "text": "# Audio Signal (in Hz)signal = np.array([23, 50, 900, 760, 12])# Rasing pitchhigh_pitch = np.array([True, False, True, True, False])" }, { "code": null, "e": 2519, "s": 2412, "text": "To raise the pitch of signal whenever the corresponding high-pitch variable says so, you can simply write:" }, { "code": null, "e": 2702, "s": 2519, "text": "# Creating a high-pitch signalhigh_pitch_signal = np.where(high_pitch, signal + 1000, signal)# Printing out the resultprint(high_pitch_signal)>>> np.array([1023, 50, 1900, 1760, 12])" }, { "code": null, "e": 2718, "s": 2702, "text": "That was easy 😃" }, { "code": null, "e": 2865, "s": 2718, "text": "Often one has an array with the correct elements, but with the wrong form. More specifically, assume you have the following one-dimensional array:" }, { "code": null, "e": 2932, "s": 2865, "text": "my_array = np.array([5, 3, 17, 4, 3])print(my_array.shape)>>> (5,)" }, { "code": null, "e": 3182, "s": 2932, "text": "Here you can see that the array is one-dimensional. You want to feed my_array into another function that expects a two-dimensional input? This happens surprisingly often with libraries like Scikit-Learn! To do this, you can use the reshape function:" }, { "code": null, "e": 3265, "s": 3182, "text": "my_array = np.array([5, 3, 17, 4, 3]).reshape(5, 1)print(my_array.shape)>>> (5, 1)" }, { "code": null, "e": 3381, "s": 3265, "text": "Now my_array is properly two-dimensional. You can think of my_array as a matrix with five rows and a single column." }, { "code": null, "e": 3459, "s": 3381, "text": "If you want to go back to my_array being one-dimensional, then you can write:" }, { "code": null, "e": 3519, "s": 3459, "text": "my_array = my_array.reshape(5)print(my_array.shape)>>> (5,)" }, { "code": null, "e": 3716, "s": 3519, "text": "Pro Tip: As a shorthand, you can use the NumPy function squeeze to remove all dimensions that have length one. Hence you could have used the squeeze function instead of the reshape function above." }, { "code": null, "e": 3819, "s": 3716, "text": "You will sometimes need to reshuffle the dimensions you already have. An example will make this clear:" }, { "code": null, "e": 4081, "s": 3819, "text": "Say you have represented an RGB image of size 1280x720 (this is the size of YouTube thumbnails) as a NumPy array called my_image . Your image has the shape (720, 1280, 3) . The number 3 comes from the fact that there are 3 colour channels: red, green, and blue." }, { "code": null, "e": 4217, "s": 4081, "text": "How do you rearrange my_image so that the RGB channels populate the first dimension? You can do that easily with the moveaxis function:" }, { "code": null, "e": 4318, "s": 4217, "text": "restructured = np.moveaxis(my_image, [0, 1, 2], [2, 0, 1])print(restrctured.shape)>>> (3, 720, 1280)" }, { "code": null, "e": 4460, "s": 4318, "text": "With this simple command you have restructured the image. The two lists in moveaxis specify the source and destination positions of the axes." }, { "code": null, "e": 4647, "s": 4460, "text": "Pro Tip: NumPy has other functions such as swapaxes and transpose that also deal with restructuring arrays. The moveaxis function is the most general, and the one I use most of the time." }, { "code": null, "e": 4799, "s": 4647, "text": "Many people think that reshaping with the reshape function and restructuring with the moveaxis function is the same. Yet, they work in different ways 😦" }, { "code": null, "e": 4874, "s": 4799, "text": "The best way to see this is with an example: Say that you have the matrix:" }, { "code": null, "e": 4956, "s": 4874, "text": "matrix = np.array([[1, 2], [3, 4], [5, 6]])# The matrix looks like this:1 23 45 6" }, { "code": null, "e": 5027, "s": 4956, "text": "If you use the moveaxis function to switch the two axes, then you get:" }, { "code": null, "e": 5137, "s": 5027, "text": "restructured_matrix = np.moveaxis(matrix, [0, 1], [1, 0])# The restructured matrix looks like this:1 3 52 4 6" }, { "code": null, "e": 5193, "s": 5137, "text": "However, if you use the reshape function, then you get:" }, { "code": null, "e": 5280, "s": 5193, "text": "reshaped_matrix = matrix.reshape(2, 3)# The reshaped matrix looks like this:1 2 34 5 6" }, { "code": null, "e": 5367, "s": 5280, "text": "The reshape function simply proceeds row-wise and makes new rows whenever appropriate." }, { "code": null, "e": 5552, "s": 5367, "text": "The unique function is a sweet utility function for finding the unique elements of an array. Say that you have an array representing the favourite cities of people sampled from a poll:" }, { "code": null, "e": 5654, "s": 5552, "text": "# Favorite citiescities = np.array([\"Paris\", \"London\", \"Vienna\", \"Paris\", \"Oslo\", \"London\", \"Paris\"])" }, { "code": null, "e": 5738, "s": 5654, "text": "Then you can use the unique function to get the unique values in the array cities :" }, { "code": null, "e": 5830, "s": 5738, "text": "unique_cities = np.unique(cities)print(unique_cities)>>> ['London' 'Oslo' 'Paris' 'Vienna']" }, { "code": null, "e": 5950, "s": 5830, "text": "Notice that the unique cities are not necessarily in the order they originally appeared in (e.g. Oslo is before Paris)." }, { "code": null, "e": 6216, "s": 5950, "text": "With polls, it is really common to draw bar charts. In those charts, the categories are the poll options while the height of the bars represent the number of votes each option got. To get that information, you can use the optional argument return_counts as follows:" }, { "code": null, "e": 6362, "s": 6216, "text": "unique_cities, counts = np.unique(cities, return_counts=True)print(unique_cities)>>> ['London' 'Oslo' 'Paris' 'Vienna']print(counts)>>> [2 1 3 1]" }, { "code": null, "e": 6431, "s": 6362, "text": "The unique function saves you from writing a lot of annoying loops 😍" }, { "code": null, "e": 6636, "s": 6431, "text": "Sometimes, you will be working with many arrays at the same time. Then it is often convenient to combine the arrays into a single “master” array. Doing this in NumPy is easy with the concatenate function." }, { "code": null, "e": 6688, "s": 6636, "text": "Let's say that you have two one-dimensional arrays:" }, { "code": null, "e": 6737, "s": 6688, "text": "array1 = np.arange(10)array2 = np.arange(10, 20)" }, { "code": null, "e": 6818, "s": 6737, "text": "Then you can combine them into a longer one-dimensional array with concatenate :" }, { "code": null, "e": 6973, "s": 6818, "text": "# Need to put the arrays into a tuplelong_array = np.concatenate((array1, array2))print(long_array)>>> [0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]" }, { "code": null, "e": 7120, "s": 6973, "text": "What if you wanted to stack array1 and array2 on top of each other? You are hence looking to create a two-dimensional vector that looks like this:" }, { "code": null, "e": 7186, "s": 7120, "text": "[[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19]]" }, { "code": null, "e": 7281, "s": 7186, "text": "You can first reshape array1 and array2 into two-dimensional arrays with the reshape function:" }, { "code": null, "e": 7342, "s": 7281, "text": "array1 = array1.reshape(10, 1)array2 = array2.reshape(10, 1)" }, { "code": null, "e": 7441, "s": 7342, "text": "Now you can use the optional axis parameter in the concatenate function to combine them correctly:" }, { "code": null, "e": 7603, "s": 7441, "text": "stacked_array = np.concatenate((array1, array2), axis=1)print(stacked_array)>>> [[ 0 10] [ 1 11] [ 2 12] [ 3 13] [ 4 14] [ 5 15] [ 6 16] [ 7 17] [ 8 18] [ 9 19]]" }, { "code": null, "e": 7675, "s": 7603, "text": "Almost there...You can now use the moveaxis function to finish the job:" }, { "code": null, "e": 7823, "s": 7675, "text": "stacked_array = np.moveaxis(stacked_array, [0, 1], [1, 0])print(stacked_array)>>> [[ 0 1 2 3 4 5 6 7 8 9] [10 11 12 13 14 15 16 17 18 19]]" }, { "code": null, "e": 7936, "s": 7823, "text": "Awesome! I hope this example showed you how some of the different tools you have just learned can come together." }, { "code": null, "e": 8088, "s": 7936, "text": "You should now feel comfortable using NumPy for a few tricky situations. If you need to learn more about NumPy, then check out the NumPy documentation." } ]
Python | Pandas Series.corr() - GeeksforGeeks
17 Feb, 2019 Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index. Pandas Series.corr() function compute the correlation with other Series, excluding missing values. Syntax: Series.corr(other, method=’pearson’, min_periods=None) Parameter :other : Seriesmethod : {‘pearson’, ‘kendall’, ‘spearman’} or callablemin_periods : Minimum number of observations needed to have a valid result Returns : correlation : float Example #1: Use Series.corr() function to find the correlation of the given series object with the other. # importing pandas as pdimport pandas as pd # Creating the first Seriessr1 = pd.Series([80, 25, 3, 25, 24, 6]) # Creating the second Seriessr2 = pd.Series([34, 5, 13, 32, 4, 15]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the first indexsr1.index = index_ # set the second indexsr2.index = index_ # Print the first seriesprint(sr1) # Print the second seriesprint(sr2) Output : Now we will use Series.corr() function to find the correlation between the underlying data of the given series object with the others. # find the correlationresult = sr1.corr(sr2) # Print the resultprint(result) Output :As we can see in the output, the Series.corr() function has successfully returned the correlation between the underlying data of the given series objects. Example #2 : Use Series.corr() function to find the correlation of the given series object with the other. The series object contains some missing values. # importing pandas as pdimport pandas as pd # Creating the first Seriessr1 = pd.Series([51, 10, 24, 18, None, 84, 12, 10, 5, 24, 2]) # Creating the second Seriessr2 = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the first indexsr1.index = index_ # set the second indexsr2.index = index_ # Print the first seriesprint(sr1) # Print the second seriesprint(sr2) Output : Now we will use Series.corr() function to find the correlation between the underlying data of the given series object with the others. # find the correlationresult = sr1.corr(sr2) # Print the resultprint(result) Output :As we can see in the output, the Series.corr() function has successfully returned the correlation between the underlying data of the given series objects. Missing values are skipped while calculating the correlation between the objects. Python pandas-series Python pandas-series-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n17 Feb, 2019" }, { "code": null, "e": 25794, "s": 25537, "text": "Pandas series is a One-dimensional ndarray with axis labels. The labels need not be unique but must be a hashable type. The object supports both integer- and label-based indexing and provides a host of methods for performing operations involving the index." }, { "code": null, "e": 25893, "s": 25794, "text": "Pandas Series.corr() function compute the correlation with other Series, excluding missing values." }, { "code": null, "e": 25956, "s": 25893, "text": "Syntax: Series.corr(other, method=’pearson’, min_periods=None)" }, { "code": null, "e": 26111, "s": 25956, "text": "Parameter :other : Seriesmethod : {‘pearson’, ‘kendall’, ‘spearman’} or callablemin_periods : Minimum number of observations needed to have a valid result" }, { "code": null, "e": 26141, "s": 26111, "text": "Returns : correlation : float" }, { "code": null, "e": 26247, "s": 26141, "text": "Example #1: Use Series.corr() function to find the correlation of the given series object with the other." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the first Seriessr1 = pd.Series([80, 25, 3, 25, 24, 6]) # Creating the second Seriessr2 = pd.Series([34, 5, 13, 32, 4, 15]) # Create the Indexindex_ = ['Coca Cola', 'Sprite', 'Coke', 'Fanta', 'Dew', 'ThumbsUp'] # set the first indexsr1.index = index_ # set the second indexsr2.index = index_ # Print the first seriesprint(sr1) # Print the second seriesprint(sr2)", "e": 26672, "s": 26247, "text": null }, { "code": null, "e": 26681, "s": 26672, "text": "Output :" }, { "code": null, "e": 26816, "s": 26681, "text": "Now we will use Series.corr() function to find the correlation between the underlying data of the given series object with the others." }, { "code": "# find the correlationresult = sr1.corr(sr2) # Print the resultprint(result)", "e": 26894, "s": 26816, "text": null }, { "code": null, "e": 27212, "s": 26894, "text": "Output :As we can see in the output, the Series.corr() function has successfully returned the correlation between the underlying data of the given series objects. Example #2 : Use Series.corr() function to find the correlation of the given series object with the other. The series object contains some missing values." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the first Seriessr1 = pd.Series([51, 10, 24, 18, None, 84, 12, 10, 5, 24, 2]) # Creating the second Seriessr2 = pd.Series([11, 21, 8, 18, 65, 18, 32, 10, 5, 32, None]) # Create the Indexindex_ = pd.date_range('2010-10-09', periods = 11, freq ='M') # set the first indexsr1.index = index_ # set the second indexsr2.index = index_ # Print the first seriesprint(sr1) # Print the second seriesprint(sr2)", "e": 27674, "s": 27212, "text": null }, { "code": null, "e": 27683, "s": 27674, "text": "Output :" }, { "code": null, "e": 27818, "s": 27683, "text": "Now we will use Series.corr() function to find the correlation between the underlying data of the given series object with the others." }, { "code": "# find the correlationresult = sr1.corr(sr2) # Print the resultprint(result)", "e": 27896, "s": 27818, "text": null }, { "code": null, "e": 28141, "s": 27896, "text": "Output :As we can see in the output, the Series.corr() function has successfully returned the correlation between the underlying data of the given series objects. Missing values are skipped while calculating the correlation between the objects." }, { "code": null, "e": 28162, "s": 28141, "text": "Python pandas-series" }, { "code": null, "e": 28191, "s": 28162, "text": "Python pandas-series-methods" }, { "code": null, "e": 28205, "s": 28191, "text": "Python-pandas" }, { "code": null, "e": 28212, "s": 28205, "text": "Python" }, { "code": null, "e": 28310, "s": 28212, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28342, "s": 28310, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28384, "s": 28342, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28426, "s": 28384, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28453, "s": 28426, "text": "Python Classes and Objects" }, { "code": null, "e": 28509, "s": 28453, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28531, "s": 28509, "text": "Defaultdict in Python" }, { "code": null, "e": 28570, "s": 28531, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28601, "s": 28570, "text": "Python | os.path.join() method" }, { "code": null, "e": 28630, "s": 28601, "text": "Create a directory in Python" } ]
JavaScript String includes() Method - GeeksforGeeks
07 Oct, 2021 Below is the example of the String includes() Method. Example: javascript <!DOCTYPE html><html> <body> <p id="GFG"></p> <script> var str = "Welcome to GeeksforGeeks."; var check = str.includes("Geeks"); document.getElementById("GFG").innerHTML = check; </script> </body></html> Output: true In JavaScript, includes() method determines whether a string contains the given characters within it or not. This method returns true if the string contains the characters, otherwise, it returns false. Note: The includes() method is case sensitive i.e, it will treat the Uppercase characters and Lowercase characters differently.Syntax: string.includes(searchvalue, start) Parameters Used: search value: It is the string in which the search will take place. start: This is the position from where the search will be processed (although this parameter is not necessary if this is not mentioned the search will begin from the start of the string). Returns either a Boolean true indicating the presence or it returns a false indicating the absence. Examples: Input : Welcome to GeeksforGeeks. str.includes("Geeks"); Output : true Explanation: Since the second parameter is not defined, the search will take place from the starting index. And it will search for Geeks, as it is present in the string, it will return a true. Input: Welcome to GeeksforGeeks. Output: false Explanation: Even in this case the second parameter is not defined, so the search will take place from the starting index. But as this method is case sensitive it will treat the two strings differently, hence returning a boolean false. Since it is case sensitive. Codes for the above function are provided below.Code 1: javascript <!DOCTYPE html><html> <body> <p id="GFG"></p> <script> var str = "Welcome to GeeksforGeeks."; var check = str.includes("Geeks"); document.getElementById("GFG").innerHTML = check; </script> </body></html> Output: false Code 2: javascript <!DOCTYPE html><html> <body> <p id="GFG"></p> <script> var str = "Welcome to GeeksforGeeks."; var check = str.includes("geeks"); document.getElementById("GFG").innerHTML = check; </script> </body></html> Output: false Code 3: javascript <!DOCTYPE html><html> <body> <p id="GFG"></p> <script> var str = "Welcome to GeeksforGeeks."; var check = str.includes("o", 17); document.getElementById("GFG").innerHTML = check; </script> </body></html> Output: true Code 4: javascript <!DOCTYPE html><html> <body> <p id="GFG"></p> <script> var str = "Welcome to GeeksforGeeks."; var check = str.includes("o", 18); document.getElementById("GFG").innerHTML = check; </script> </body></html> Output: false Exceptions : The search will not be processed if the second parameter i.e computed index(starting index) is greater than or equal to the string length and hence return false. javascript <!DOCTYPE html><html> <body> <p id="GFG"></p> <script> var str = "Welcome to GeeksforGeeks."; var check = str.includes("o", 25); document.getElementById("GFG").innerHTML = check; </script> </body></html> Output: false If the computed index(starting index) i.e the position from which the search will begin is less than 0, the entire array will be searched. javascript <!DOCTYPE html><html> <body> <p id="GFG"></p> <script> var str = "Welcome to GeeksforGeeks."; var check = str.includes("o", -2); document.getElementById("GFG").innerHTML = check; </script> </body></html> Output: true Supported Browser: Chrome 41 and above Edge 12 and above Firefox 40 and above Opera 28 and above Safari 9 and above JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. ysachin2314 JavaScript-Methods javascript-string JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26683, "s": 26655, "text": "\n07 Oct, 2021" }, { "code": null, "e": 26739, "s": 26683, "text": "Below is the example of the String includes() Method. " }, { "code": null, "e": 26750, "s": 26739, "text": "Example: " }, { "code": null, "e": 26761, "s": 26750, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"GFG\"></p> <script> var str = \"Welcome to GeeksforGeeks.\"; var check = str.includes(\"Geeks\"); document.getElementById(\"GFG\").innerHTML = check; </script> </body></html>", "e": 27026, "s": 26761, "text": null }, { "code": null, "e": 27035, "s": 27026, "text": "Output: " }, { "code": null, "e": 27040, "s": 27035, "text": "true" }, { "code": null, "e": 27379, "s": 27040, "text": "In JavaScript, includes() method determines whether a string contains the given characters within it or not. This method returns true if the string contains the characters, otherwise, it returns false. Note: The includes() method is case sensitive i.e, it will treat the Uppercase characters and Lowercase characters differently.Syntax: " }, { "code": null, "e": 27415, "s": 27379, "text": "string.includes(searchvalue, start)" }, { "code": null, "e": 27434, "s": 27415, "text": "Parameters Used: " }, { "code": null, "e": 27502, "s": 27434, "text": "search value: It is the string in which the search will take place." }, { "code": null, "e": 27690, "s": 27502, "text": "start: This is the position from where the search will be processed (although this parameter is not necessary if this is not mentioned the search will begin from the start of the string)." }, { "code": null, "e": 27790, "s": 27690, "text": "Returns either a Boolean true indicating the presence or it returns a false indicating the absence." }, { "code": null, "e": 27802, "s": 27790, "text": "Examples: " }, { "code": null, "e": 27883, "s": 27802, "text": "Input : Welcome to GeeksforGeeks.\n str.includes(\"Geeks\");\n\n\nOutput : true" }, { "code": null, "e": 28077, "s": 27883, "text": "Explanation: Since the second parameter is not defined, the search will take place from the starting index. And it will search for Geeks, as it is present in the string, it will return a true. " }, { "code": null, "e": 28126, "s": 28077, "text": "Input: Welcome to GeeksforGeeks.\n\n\nOutput: false" }, { "code": null, "e": 28448, "s": 28126, "text": "Explanation: Even in this case the second parameter is not defined, so the search will take place from the starting index. But as this method is case sensitive it will treat the two strings differently, hence returning a boolean false. Since it is case sensitive. Codes for the above function are provided below.Code 1: " }, { "code": null, "e": 28459, "s": 28448, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"GFG\"></p> <script> var str = \"Welcome to GeeksforGeeks.\"; var check = str.includes(\"Geeks\"); document.getElementById(\"GFG\").innerHTML = check; </script> </body></html>", "e": 28724, "s": 28459, "text": null }, { "code": null, "e": 28734, "s": 28724, "text": "Output: " }, { "code": null, "e": 28740, "s": 28734, "text": "false" }, { "code": null, "e": 28750, "s": 28740, "text": "Code 2: " }, { "code": null, "e": 28761, "s": 28750, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"GFG\"></p> <script> var str = \"Welcome to GeeksforGeeks.\"; var check = str.includes(\"geeks\"); document.getElementById(\"GFG\").innerHTML = check; </script> </body></html>", "e": 29026, "s": 28761, "text": null }, { "code": null, "e": 29036, "s": 29026, "text": "Output: " }, { "code": null, "e": 29042, "s": 29036, "text": "false" }, { "code": null, "e": 29052, "s": 29042, "text": "Code 3: " }, { "code": null, "e": 29063, "s": 29052, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"GFG\"></p> <script> var str = \"Welcome to GeeksforGeeks.\"; var check = str.includes(\"o\", 17); document.getElementById(\"GFG\").innerHTML = check; </script> </body></html>", "e": 29328, "s": 29063, "text": null }, { "code": null, "e": 29338, "s": 29328, "text": "Output: " }, { "code": null, "e": 29343, "s": 29338, "text": "true" }, { "code": null, "e": 29353, "s": 29343, "text": "Code 4: " }, { "code": null, "e": 29364, "s": 29353, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"GFG\"></p> <script> var str = \"Welcome to GeeksforGeeks.\"; var check = str.includes(\"o\", 18); document.getElementById(\"GFG\").innerHTML = check; </script> </body></html>", "e": 29629, "s": 29364, "text": null }, { "code": null, "e": 29639, "s": 29629, "text": "Output: " }, { "code": null, "e": 29645, "s": 29639, "text": "false" }, { "code": null, "e": 29660, "s": 29645, "text": "Exceptions : " }, { "code": null, "e": 29824, "s": 29660, "text": "The search will not be processed if the second parameter i.e computed index(starting index) is greater than or equal to the string length and hence return false. " }, { "code": null, "e": 29835, "s": 29824, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"GFG\"></p> <script> var str = \"Welcome to GeeksforGeeks.\"; var check = str.includes(\"o\", 25); document.getElementById(\"GFG\").innerHTML = check; </script> </body></html>", "e": 30100, "s": 29835, "text": null }, { "code": null, "e": 30110, "s": 30100, "text": "Output: " }, { "code": null, "e": 30116, "s": 30110, "text": "false" }, { "code": null, "e": 30259, "s": 30118, "text": "If the computed index(starting index) i.e the position from which the search will begin is less than 0, the entire array will be searched. " }, { "code": null, "e": 30270, "s": 30259, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <p id=\"GFG\"></p> <script> var str = \"Welcome to GeeksforGeeks.\"; var check = str.includes(\"o\", -2); document.getElementById(\"GFG\").innerHTML = check; </script> </body></html>", "e": 30535, "s": 30270, "text": null }, { "code": null, "e": 30545, "s": 30535, "text": "Output: " }, { "code": null, "e": 30550, "s": 30545, "text": "true" }, { "code": null, "e": 30571, "s": 30552, "text": "Supported Browser:" }, { "code": null, "e": 30591, "s": 30571, "text": "Chrome 41 and above" }, { "code": null, "e": 30609, "s": 30591, "text": "Edge 12 and above" }, { "code": null, "e": 30630, "s": 30609, "text": "Firefox 40 and above" }, { "code": null, "e": 30649, "s": 30630, "text": "Opera 28 and above" }, { "code": null, "e": 30668, "s": 30649, "text": "Safari 9 and above" }, { "code": null, "e": 30887, "s": 30668, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 30901, "s": 30889, "text": "ysachin2314" }, { "code": null, "e": 30920, "s": 30901, "text": "JavaScript-Methods" }, { "code": null, "e": 30938, "s": 30920, "text": "javascript-string" }, { "code": null, "e": 30949, "s": 30938, "text": "JavaScript" }, { "code": null, "e": 30966, "s": 30949, "text": "Web Technologies" }, { "code": null, "e": 31064, "s": 30966, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31104, "s": 31064, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31149, "s": 31104, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31210, "s": 31149, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31282, "s": 31210, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 31334, "s": 31282, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 31374, "s": 31334, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31407, "s": 31374, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31452, "s": 31407, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31495, "s": 31452, "text": "How to fetch data from an API in ReactJS ?" } ]
D3.js | d3.scaleBand() Function - GeeksforGeeks
30 Jul, 2019 The d3.scaleBand() function in D3.js is used to construct a new band scale with the domain specified as an array of values and the range as the minimum and maximum extents of the bands. This function splits the range into n bands where n is the number of values in the domain array. Syntax: d3.scaleBand().domain(array of values).range(array of values); Parameters: This function does not accept any parameters. Return Value: This function returns the corresponding range for the domain’s value. Below programs illustrate the d3.scaleBand() function in D3.js: Example 1: <!DOCTYPE html><html> <head> <title> D3.js | d3.scaleBand() Function </title> <script src = "https://d3js.org/d3.v4.min.js"> </script></head> <body> <script> // Calling the scaleBand() function var A = d3.scaleBand() .domain(['January', 'February', 'March', 'April', 'May']) .range([10, 50]); // Getting the corresponding range for // the domain value console.log(A('January')); console.log(A('February')); console.log(A('March')); console.log(A('April')); console.log(A('May')); </script></body> </html> Output: 10 18 26 34 42 Example 2: <!DOCTYPE html><html> <head> <title> D3.js | d3.scaleBand() Function </title> <script src = "https://d3js.org/d3.v4.min.js"> </script></head> <body> <script> // Calling the scaleBand() function var A = d3.scaleBand() .domain(['January', 'February', 'March', 'April', 'May']) .range([1, 2]); // Getting the corresponding range for // the domain value console.log(A('January')); console.log(A('February')); console.log(A('March')); console.log(A('April')); console.log(A('May')); </script></body> </html> Output: 1 1.2 1.4 1.6 1.8 Reference: https://devdocs.io/d3~5/d3-scale#scaleBand D3.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to Open URL in New Tab using JavaScript ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 25467, "s": 25439, "text": "\n30 Jul, 2019" }, { "code": null, "e": 25750, "s": 25467, "text": "The d3.scaleBand() function in D3.js is used to construct a new band scale with the domain specified as an array of values and the range as the minimum and maximum extents of the bands. This function splits the range into n bands where n is the number of values in the domain array." }, { "code": null, "e": 25758, "s": 25750, "text": "Syntax:" }, { "code": null, "e": 25821, "s": 25758, "text": "d3.scaleBand().domain(array of values).range(array of values);" }, { "code": null, "e": 25879, "s": 25821, "text": "Parameters: This function does not accept any parameters." }, { "code": null, "e": 25963, "s": 25879, "text": "Return Value: This function returns the corresponding range for the domain’s value." }, { "code": null, "e": 26027, "s": 25963, "text": "Below programs illustrate the d3.scaleBand() function in D3.js:" }, { "code": null, "e": 26038, "s": 26027, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title> D3.js | d3.scaleBand() Function </title> <script src = \"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <script> // Calling the scaleBand() function var A = d3.scaleBand() .domain(['January', 'February', 'March', 'April', 'May']) .range([10, 50]); // Getting the corresponding range for // the domain value console.log(A('January')); console.log(A('February')); console.log(A('March')); console.log(A('April')); console.log(A('May')); </script></body> </html>", "e": 26689, "s": 26038, "text": null }, { "code": null, "e": 26697, "s": 26689, "text": "Output:" }, { "code": null, "e": 26713, "s": 26697, "text": "10\n18\n26\n34\n42\n" }, { "code": null, "e": 26724, "s": 26713, "text": "Example 2:" }, { "code": "<!DOCTYPE html><html> <head> <title> D3.js | d3.scaleBand() Function </title> <script src = \"https://d3js.org/d3.v4.min.js\"> </script></head> <body> <script> // Calling the scaleBand() function var A = d3.scaleBand() .domain(['January', 'February', 'March', 'April', 'May']) .range([1, 2]); // Getting the corresponding range for // the domain value console.log(A('January')); console.log(A('February')); console.log(A('March')); console.log(A('April')); console.log(A('May')); </script></body> </html>", "e": 27374, "s": 26724, "text": null }, { "code": null, "e": 27382, "s": 27374, "text": "Output:" }, { "code": null, "e": 27401, "s": 27382, "text": "1\n1.2\n1.4\n1.6\n1.8\n" }, { "code": null, "e": 27455, "s": 27401, "text": "Reference: https://devdocs.io/d3~5/d3-scale#scaleBand" }, { "code": null, "e": 27461, "s": 27455, "text": "D3.js" }, { "code": null, "e": 27472, "s": 27461, "text": "JavaScript" }, { "code": null, "e": 27489, "s": 27472, "text": "Web Technologies" }, { "code": null, "e": 27587, "s": 27489, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27627, "s": 27587, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27672, "s": 27627, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27733, "s": 27672, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27805, "s": 27733, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27851, "s": 27805, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 27891, "s": 27851, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27924, "s": 27891, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27969, "s": 27924, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28012, "s": 27969, "text": "How to fetch data from an API in ReactJS ?" } ]
SubBrute – Tool For Subdomain Brute Force - GeeksforGeeks
14 Sep, 2021 SubBrute is a free and open-source tool available on GitHub. SubBrute uses DNS Scan for finding subdomains of the target domain. This feature of SubBrute provides an extra layer of anonymity for security researchers. This tool is free means you can download and use this tool free of cost. SubBrute is used for reconnaissance of subdomains. SubBrute is used for finding the subdomain of the target website. This tool is used to find subdomains from a website/web application. SubBrute tool is written in python language you must have python language installed into your Kali Linux in order to use this tool. Step1: Open your kali Linux operating system and use the following command to install the tool from GitHub. git clone https://github.com/TheRook/subbrute.git Step 2: The tool has been downloaded into your Kali Linux. Use the following command to move into the directory of the tool. cd subbrute Step 3: Now you are in the directory of the tool. Use the following command to run the tool. ./subbrute.py --help The tool is running successfully. Now we will see examples to run the tool. Use the SubBrute tool to find subdomains of a domain. ./subbrute.py <domain> You can see that the tool is giving all the subdomains of the domain google.com. You can use your own domain to find subdomains. Kali-Linux Linux-Tools 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": 25651, "s": 25623, "text": "\n14 Sep, 2021" }, { "code": null, "e": 26261, "s": 25651, "text": "SubBrute is a free and open-source tool available on GitHub. SubBrute uses DNS Scan for finding subdomains of the target domain. This feature of SubBrute provides an extra layer of anonymity for security researchers. This tool is free means you can download and use this tool free of cost. SubBrute is used for reconnaissance of subdomains. SubBrute is used for finding the subdomain of the target website. This tool is used to find subdomains from a website/web application. SubBrute tool is written in python language you must have python language installed into your Kali Linux in order to use this tool. " }, { "code": null, "e": 26369, "s": 26261, "text": "Step1: Open your kali Linux operating system and use the following command to install the tool from GitHub." }, { "code": null, "e": 26419, "s": 26369, "text": "git clone https://github.com/TheRook/subbrute.git" }, { "code": null, "e": 26544, "s": 26419, "text": "Step 2: The tool has been downloaded into your Kali Linux. Use the following command to move into the directory of the tool." }, { "code": null, "e": 26556, "s": 26544, "text": "cd subbrute" }, { "code": null, "e": 26649, "s": 26556, "text": "Step 3: Now you are in the directory of the tool. Use the following command to run the tool." }, { "code": null, "e": 26670, "s": 26649, "text": "./subbrute.py --help" }, { "code": null, "e": 26746, "s": 26670, "text": "The tool is running successfully. Now we will see examples to run the tool." }, { "code": null, "e": 26801, "s": 26746, "text": " Use the SubBrute tool to find subdomains of a domain." }, { "code": null, "e": 26824, "s": 26801, "text": "./subbrute.py <domain>" }, { "code": null, "e": 26953, "s": 26824, "text": "You can see that the tool is giving all the subdomains of the domain google.com. You can use your own domain to find subdomains." }, { "code": null, "e": 26964, "s": 26953, "text": "Kali-Linux" }, { "code": null, "e": 26976, "s": 26964, "text": "Linux-Tools" }, { "code": null, "e": 26987, "s": 26976, "text": "Linux-Unix" }, { "code": null, "e": 27085, "s": 26987, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27120, "s": 27085, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27154, "s": 27120, "text": "mv command in Linux with examples" }, { "code": null, "e": 27180, "s": 27154, "text": "Docker - COPY Instruction" }, { "code": null, "e": 27209, "s": 27180, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27246, "s": 27209, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27283, "s": 27246, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27325, "s": 27283, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27351, "s": 27325, "text": "Thread functions in C/C++" }, { "code": null, "e": 27387, "s": 27351, "text": "uniq Command in LINUX with examples" } ]
Print a matrix in Reverse Wave Form - GeeksforGeeks
03 Feb, 2022 Given a matrix, print it in Reverse Wave Form. Examples : Input : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 Output : 4 8 12 16 15 11 7 3 2 6 10 14 13 9 5 1 Input : 1 9 4 10 3 6 90 11 2 30 85 72 6 31 99 15 Output : 10 11 72 15 99 85 90 4 9 6 30 31 6 2 3 1 Approach :To get the reverse wave form for a given matrix, we first print the elements of the last column of the matrix in downward direction then print the elements of the 2nd last column in the upward direction, then print the elements in third last column in downward direction and so on. For example 1, the flow goes like : Below is the implementation to print reverse wave form of a matrix : C++ Java Python3 C# PHP Javascript // C++ implementation to print// reverse wave form of matrix#include<bits/stdc++.h>using namespace std; #define R 4#define C 4 // function to print reverse wave// form for a given matrixvoid WavePrint(int m, int n, int arr[R][C]){ int i, j = n - 1, wave = 1; /* m - Ending row index n - Ending column index i, j - Iterator wave - for Direction wave = 1 - Wave direction down wave = 0 - Wave direction up */ while (j >= 0) { // Check whether to go in // upward or downward if (wave == 1) { // Print the element of the matrix // downward since the value of wave = 1 for (i = 0; i < m; i++) cout << arr[i][j] << " "; wave = 0; j--; } else { // Print the elements of the // matrix upward since the value // of wave = 0 for (i = m - 1; i >= 0; i--) cout << arr[i][j] << " "; wave = 1; j--; } }} // driver functionint main(){ int arr[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; WavePrint(R, C, arr); return 0;} // Java implementation to print// reverse wave form of matriximport java.io.*; class GFG{ static int R = 4; static int C = 4; // function to print reverse wave // form for a given matrix static void WavePrint(int m, int n, int arr[][]) { int i, j = n - 1, wave = 1; // m- Ending row index //n - Ending column index //i, j - Iterator //wave - for Direction //wave = 1 - Wave direction down //wave = 0 - Wave direction up */ while (j >= 0) { // Check whether to go in // upward or downward if (wave == 1) { // Print the element of the matrix // downward since the value of wave = 1 for (i = 0; i < m; i++) System.out.print(arr[i][j] +" "); wave = 0; j--; } else { // Print the elements of the // matrix upward since the value // of wave = 0 for (i = m - 1; i >= 0; i--) System.out.print( arr[i][j] + " "); wave = 1; j--; } } } // Driver function public static void main (String[] args) { int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; WavePrint(R, C, arr); }} // This code is contributed by vt_m # Python3 implementation to print# reverse wave form of matrix R = 4C = 4 # function to print reverse wave# form for a given matrixdef wavePrint(m, n, arr): j = n - 1 wave = 1 # m - Ending row index # n - Ending column index # i, j - Iterator # wave - for Direction # wave = 1 - Wave direction down # wave = 0 - Wave direction up while j >= 0: # Check whether to go in # upward or downward if wave == 1: # Print the element of the # matrix downward since the # value of wave = 1 for i in range(m): print(arr[i][j], end = " "), wave = 0 j -= 1 else: # Print the elements of the # matrix upward since the # value of wave = 0 for i in range(m - 1, -1, -1): print(arr[i][j], end = " "), wave = 1 j -= 1 # Driver codearr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ] wavePrint(R, C, arr) # This code is contributed by# Upendra Singh Bartwal // C# implementation to print// reverse wave form of matrixusing System; class GFG { static int R = 4; static int C = 4; // function to print reverse wave // form for a given matrix static void WavePrint(int m, int n, int [,]arr) { int i, j = n - 1, wave = 1; // m- Ending row index // n - Ending column index // i, j - Iterator // wave - for Direction // wave = 1 - Wave direction down // wave = 0 - Wave direction up */ while (j >= 0) { // Check whether to go in // upward or downward if (wave == 1) { // Print the element of the // matrix downward since the // value of wave = 1 for (i = 0; i < m; i++) Console.Write(arr[i,j] + " "); wave = 0; j--; } else { // Print the elements of the // matrix upward since the value // of wave = 0 for (i = m - 1; i >= 0; i--) Console.Write( arr[i,j] + " "); wave = 1; j--; } } } // Driver function public static void Main () { int [,]arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; WavePrint(R, C, arr); }} // This code is contributed by vt_m. <?php// PHP implementation to print// reverse wave form of matrix$R = 4;$C = 4; // function to print reverse// wave form for a given matrixfunction WavePrint($m, $n, $arr){ global $R; global $C; $i; $j = $n - 1; $wave = 1; /* m - Ending row index n - Ending column index i, j - Iterator wave - for Direction wave = 1 - Wave direction down wave = 0 - Wave direction up */ while ($j >= 0) { // Check whether to go in // upward or downward if ($wave == 1) { // Print the element of the // matrix downward since the // value of wave = 1 for ($i = 0; $i < $m; $i++) echo $arr[$i][$j] , " "; $wave = 0; $j--; } else { // Print the elements of // the matrix upward since // the value of wave = 0 for ($i = $m - 1; $i >= 0; $i--) echo $arr[$i][$j] , " "; $wave = 1; $j--; } }} // Driver Code$arr = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16)); WavePrint($R, $C, $arr); // This code is contributed by ajit?> <script> // Javascript implementation to print// reverse wave form of matrixR = 4C = 4 // Function to print reverse wave// form for a given matrixfunction WavePrint(m, n, arr){ var i, j = n - 1, wave = 1; /* m - Ending row index n - Ending column index i, j - Iterator wave - for Direction wave = 1 - Wave direction down wave = 0 - Wave direction up */ while (j >= 0) { // Check whether to go in // upward or downward if (wave == 1) { // Print the element of the matrix // downward since the value of wave = 1 for(i = 0; i < m; i++) document.write( arr[i][j] + " "); wave = 0; j--; } else { // Print the elements of the // matrix upward since the value // of wave = 0 for(i = m - 1; i >= 0; i--) document.write( arr[i][j] + " "); wave = 1; j--; } }} // Driver codevar arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; WavePrint(R, C, arr); // This code is contributed by itsok </script> Output: 4 8 12 16 15 11 7 3 2 6 10 14 13 9 5 1 Complexity Analysis Time Complexity: O(N2) Auxiliary Space: O(1) jit_t itsok prasanna1995 pattern-printing Matrix School Programming pattern-printing Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Count all possible paths from top left to bottom right of a mXn matrix Program to multiply two matrices Min Cost Path | DP-6 Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 26215, "s": 26187, "text": "\n03 Feb, 2022" }, { "code": null, "e": 26263, "s": 26215, "text": "Given a matrix, print it in Reverse Wave Form. " }, { "code": null, "e": 26275, "s": 26263, "text": "Examples : " }, { "code": null, "e": 26541, "s": 26275, "text": "Input : 1 2 3 4\n 5 6 7 8\n 9 10 11 12\n 13 14 15 16\nOutput : 4 8 12 16 15 11 7 3 2 6 10 14 13 9 5 1\n\nInput : 1 9 4 10\n 3 6 90 11\n 2 30 85 72\n 6 31 99 15 \nOutput : 10 11 72 15 99 85 90 4 9 6 30 31 6 2 3 1" }, { "code": null, "e": 26871, "s": 26541, "text": "Approach :To get the reverse wave form for a given matrix, we first print the elements of the last column of the matrix in downward direction then print the elements of the 2nd last column in the upward direction, then print the elements in third last column in downward direction and so on. For example 1, the flow goes like : " }, { "code": null, "e": 26942, "s": 26871, "text": "Below is the implementation to print reverse wave form of a matrix : " }, { "code": null, "e": 26946, "s": 26942, "text": "C++" }, { "code": null, "e": 26951, "s": 26946, "text": "Java" }, { "code": null, "e": 26959, "s": 26951, "text": "Python3" }, { "code": null, "e": 26962, "s": 26959, "text": "C#" }, { "code": null, "e": 26966, "s": 26962, "text": "PHP" }, { "code": null, "e": 26977, "s": 26966, "text": "Javascript" }, { "code": "// C++ implementation to print// reverse wave form of matrix#include<bits/stdc++.h>using namespace std; #define R 4#define C 4 // function to print reverse wave// form for a given matrixvoid WavePrint(int m, int n, int arr[R][C]){ int i, j = n - 1, wave = 1; /* m - Ending row index n - Ending column index i, j - Iterator wave - for Direction wave = 1 - Wave direction down wave = 0 - Wave direction up */ while (j >= 0) { // Check whether to go in // upward or downward if (wave == 1) { // Print the element of the matrix // downward since the value of wave = 1 for (i = 0; i < m; i++) cout << arr[i][j] << \" \"; wave = 0; j--; } else { // Print the elements of the // matrix upward since the value // of wave = 0 for (i = m - 1; i >= 0; i--) cout << arr[i][j] << \" \"; wave = 1; j--; } }} // driver functionint main(){ int arr[R][C] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; WavePrint(R, C, arr); return 0;}", "e": 28336, "s": 26977, "text": null }, { "code": "// Java implementation to print// reverse wave form of matriximport java.io.*; class GFG{ static int R = 4; static int C = 4; // function to print reverse wave // form for a given matrix static void WavePrint(int m, int n, int arr[][]) { int i, j = n - 1, wave = 1; // m- Ending row index //n - Ending column index //i, j - Iterator //wave - for Direction //wave = 1 - Wave direction down //wave = 0 - Wave direction up */ while (j >= 0) { // Check whether to go in // upward or downward if (wave == 1) { // Print the element of the matrix // downward since the value of wave = 1 for (i = 0; i < m; i++) System.out.print(arr[i][j] +\" \"); wave = 0; j--; } else { // Print the elements of the // matrix upward since the value // of wave = 0 for (i = m - 1; i >= 0; i--) System.out.print( arr[i][j] + \" \"); wave = 1; j--; } } } // Driver function public static void main (String[] args) { int arr[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; WavePrint(R, C, arr); }} // This code is contributed by vt_m", "e": 29928, "s": 28336, "text": null }, { "code": "# Python3 implementation to print# reverse wave form of matrix R = 4C = 4 # function to print reverse wave# form for a given matrixdef wavePrint(m, n, arr): j = n - 1 wave = 1 # m - Ending row index # n - Ending column index # i, j - Iterator # wave - for Direction # wave = 1 - Wave direction down # wave = 0 - Wave direction up while j >= 0: # Check whether to go in # upward or downward if wave == 1: # Print the element of the # matrix downward since the # value of wave = 1 for i in range(m): print(arr[i][j], end = \" \"), wave = 0 j -= 1 else: # Print the elements of the # matrix upward since the # value of wave = 0 for i in range(m - 1, -1, -1): print(arr[i][j], end = \" \"), wave = 1 j -= 1 # Driver codearr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ] wavePrint(R, C, arr) # This code is contributed by# Upendra Singh Bartwal", "e": 31130, "s": 29928, "text": null }, { "code": "// C# implementation to print// reverse wave form of matrixusing System; class GFG { static int R = 4; static int C = 4; // function to print reverse wave // form for a given matrix static void WavePrint(int m, int n, int [,]arr) { int i, j = n - 1, wave = 1; // m- Ending row index // n - Ending column index // i, j - Iterator // wave - for Direction // wave = 1 - Wave direction down // wave = 0 - Wave direction up */ while (j >= 0) { // Check whether to go in // upward or downward if (wave == 1) { // Print the element of the // matrix downward since the // value of wave = 1 for (i = 0; i < m; i++) Console.Write(arr[i,j] + \" \"); wave = 0; j--; } else { // Print the elements of the // matrix upward since the value // of wave = 0 for (i = m - 1; i >= 0; i--) Console.Write( arr[i,j] + \" \"); wave = 1; j--; } } } // Driver function public static void Main () { int [,]arr = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; WavePrint(R, C, arr); }} // This code is contributed by vt_m.", "e": 32763, "s": 31130, "text": null }, { "code": "<?php// PHP implementation to print// reverse wave form of matrix$R = 4;$C = 4; // function to print reverse// wave form for a given matrixfunction WavePrint($m, $n, $arr){ global $R; global $C; $i; $j = $n - 1; $wave = 1; /* m - Ending row index n - Ending column index i, j - Iterator wave - for Direction wave = 1 - Wave direction down wave = 0 - Wave direction up */ while ($j >= 0) { // Check whether to go in // upward or downward if ($wave == 1) { // Print the element of the // matrix downward since the // value of wave = 1 for ($i = 0; $i < $m; $i++) echo $arr[$i][$j] , \" \"; $wave = 0; $j--; } else { // Print the elements of // the matrix upward since // the value of wave = 0 for ($i = $m - 1; $i >= 0; $i--) echo $arr[$i][$j] , \" \"; $wave = 1; $j--; } }} // Driver Code$arr = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16)); WavePrint($R, $C, $arr); // This code is contributed by ajit?>", "e": 34103, "s": 32763, "text": null }, { "code": "<script> // Javascript implementation to print// reverse wave form of matrixR = 4C = 4 // Function to print reverse wave// form for a given matrixfunction WavePrint(m, n, arr){ var i, j = n - 1, wave = 1; /* m - Ending row index n - Ending column index i, j - Iterator wave - for Direction wave = 1 - Wave direction down wave = 0 - Wave direction up */ while (j >= 0) { // Check whether to go in // upward or downward if (wave == 1) { // Print the element of the matrix // downward since the value of wave = 1 for(i = 0; i < m; i++) document.write( arr[i][j] + \" \"); wave = 0; j--; } else { // Print the elements of the // matrix upward since the value // of wave = 0 for(i = m - 1; i >= 0; i--) document.write( arr[i][j] + \" \"); wave = 1; j--; } }} // Driver codevar arr = [ [ 1, 2, 3, 4 ], [ 5, 6, 7, 8 ], [ 9, 10, 11, 12 ], [ 13, 14, 15, 16 ] ]; WavePrint(R, C, arr); // This code is contributed by itsok </script>", "e": 35406, "s": 34103, "text": null }, { "code": null, "e": 35416, "s": 35406, "text": "Output: " }, { "code": null, "e": 35456, "s": 35416, "text": "4 8 12 16 15 11 7 3 2 6 10 14 13 9 5 1 " }, { "code": null, "e": 35476, "s": 35456, "text": "Complexity Analysis" }, { "code": null, "e": 35499, "s": 35476, "text": "Time Complexity: O(N2)" }, { "code": null, "e": 35522, "s": 35499, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 35528, "s": 35522, "text": "jit_t" }, { "code": null, "e": 35534, "s": 35528, "text": "itsok" }, { "code": null, "e": 35547, "s": 35534, "text": "prasanna1995" }, { "code": null, "e": 35564, "s": 35547, "text": "pattern-printing" }, { "code": null, "e": 35571, "s": 35564, "text": "Matrix" }, { "code": null, "e": 35590, "s": 35571, "text": "School Programming" }, { "code": null, "e": 35607, "s": 35590, "text": "pattern-printing" }, { "code": null, "e": 35614, "s": 35607, "text": "Matrix" }, { "code": null, "e": 35712, "s": 35614, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35736, "s": 35712, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 35798, "s": 35736, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 35869, "s": 35798, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 35902, "s": 35869, "text": "Program to multiply two matrices" }, { "code": null, "e": 35923, "s": 35902, "text": "Min Cost Path | DP-6" }, { "code": null, "e": 35941, "s": 35923, "text": "Python Dictionary" }, { "code": null, "e": 35957, "s": 35941, "text": "Arrays in C/C++" }, { "code": null, "e": 35976, "s": 35957, "text": "Inheritance in C++" }, { "code": null, "e": 36001, "s": 35976, "text": "Reverse a string in Java" } ]
Python - assertGreaterEqual() function in unittest - GeeksforGeeks
24 Oct, 2020 assertGreaterEqual() in Python is an unittest library function that is used in unit testing to check whether the first given value is greater than or equal to the second value or not. This function will take three parameters as input and return a boolean value depending upon the assert condition. This function check that if the first given value is greater than or equal to the second value and returns true if it is so, else return false if the first value is not greater than or equal to the second value. Syntax: assertGreaterEqual(first, second, message=None) Parameters: assertGreaterEqual() accept three parameters which are listed below with explanation: first: first input value (integer) second: second input value (integer) message: a string sentence as a message which got displayed when the test case got failed. Listed below is an example illustrating the positive and negative test case for a given assert function: Example : Python3 # test suiteimport unittest class TestStringMethods(unittest.TestCase): # negative test function to test if values1 is greater or equal than value2 def test_negativeForGreaterEqual(self): first = 4 second = 5 # error message in case if test case got failed message = "first value is not greater or equal than second value." # assert function() to check if values1 is greater or equal than value2 self.assertGreaterEqual(first, second, message) if __name__ == '__main__': unittest.main() Output: F======================================================================FAIL: test_negativeForGreaterEqual (__main__.TestStringMethods)———————————————————————-Traceback (most recent call last):File “p1.py”, line 13, in test_negativeForGreaterEqual self.assertGreaterEqual(first, second, message)AssertionError: 4 not greater than or equal to 5 : first value is not greater or equal than second value. ———————————————————————-Ran 1 tests in 0.000s FAILED (failures=1) Example 2: Python # test suiteimport unittest class TestStringMethods(unittest.TestCase): # positive test function to test if values1 is greater than or equal to value2 def test_positiveForGreaterEqual(self): first = 4 second = 4 # error message in case if test case got failed message = "first value is not greater or equal than second value." # assert function() to check if values1 is greater or equal than value2 self.assertGreaterEqual(first, second, message) if __name__ == '__main__': unittest.main() Output: .———————————————————————-Ran 1 test in 0.000s OK Python unittest-library Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n24 Oct, 2020" }, { "code": null, "e": 25835, "s": 25537, "text": "assertGreaterEqual() in Python is an unittest library function that is used in unit testing to check whether the first given value is greater than or equal to the second value or not. This function will take three parameters as input and return a boolean value depending upon the assert condition." }, { "code": null, "e": 26047, "s": 25835, "text": "This function check that if the first given value is greater than or equal to the second value and returns true if it is so, else return false if the first value is not greater than or equal to the second value." }, { "code": null, "e": 26103, "s": 26047, "text": "Syntax: assertGreaterEqual(first, second, message=None)" }, { "code": null, "e": 26201, "s": 26103, "text": "Parameters: assertGreaterEqual() accept three parameters which are listed below with explanation:" }, { "code": null, "e": 26236, "s": 26201, "text": "first: first input value (integer)" }, { "code": null, "e": 26274, "s": 26236, "text": "second: second input value (integer)" }, { "code": null, "e": 26365, "s": 26274, "text": "message: a string sentence as a message which got displayed when the test case got failed." }, { "code": null, "e": 26470, "s": 26365, "text": "Listed below is an example illustrating the positive and negative test case for a given assert function:" }, { "code": null, "e": 26480, "s": 26470, "text": "Example :" }, { "code": null, "e": 26488, "s": 26480, "text": "Python3" }, { "code": "# test suiteimport unittest class TestStringMethods(unittest.TestCase): # negative test function to test if values1 is greater or equal than value2 def test_negativeForGreaterEqual(self): first = 4 second = 5 # error message in case if test case got failed message = \"first value is not greater or equal than second value.\" # assert function() to check if values1 is greater or equal than value2 self.assertGreaterEqual(first, second, message) if __name__ == '__main__': unittest.main()", "e": 27052, "s": 26488, "text": null }, { "code": null, "e": 27060, "s": 27052, "text": "Output:" }, { "code": null, "e": 27461, "s": 27060, "text": "F======================================================================FAIL: test_negativeForGreaterEqual (__main__.TestStringMethods)———————————————————————-Traceback (most recent call last):File “p1.py”, line 13, in test_negativeForGreaterEqual self.assertGreaterEqual(first, second, message)AssertionError: 4 not greater than or equal to 5 : first value is not greater or equal than second value." }, { "code": null, "e": 27507, "s": 27461, "text": "———————————————————————-Ran 1 tests in 0.000s" }, { "code": null, "e": 27527, "s": 27507, "text": "FAILED (failures=1)" }, { "code": null, "e": 27538, "s": 27527, "text": "Example 2:" }, { "code": null, "e": 27545, "s": 27538, "text": "Python" }, { "code": "# test suiteimport unittest class TestStringMethods(unittest.TestCase): # positive test function to test if values1 is greater than or equal to value2 def test_positiveForGreaterEqual(self): first = 4 second = 4 # error message in case if test case got failed message = \"first value is not greater or equal than second value.\" # assert function() to check if values1 is greater or equal than value2 self.assertGreaterEqual(first, second, message) if __name__ == '__main__': unittest.main()", "e": 28112, "s": 27545, "text": null }, { "code": null, "e": 28120, "s": 28112, "text": "Output:" }, { "code": null, "e": 28166, "s": 28120, "text": ".———————————————————————-Ran 1 test in 0.000s" }, { "code": null, "e": 28169, "s": 28166, "text": "OK" }, { "code": null, "e": 28193, "s": 28169, "text": "Python unittest-library" }, { "code": null, "e": 28200, "s": 28193, "text": "Python" }, { "code": null, "e": 28298, "s": 28200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28330, "s": 28298, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28372, "s": 28330, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28414, "s": 28372, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28441, "s": 28414, "text": "Python Classes and Objects" }, { "code": null, "e": 28497, "s": 28441, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28536, "s": 28497, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28558, "s": 28536, "text": "Defaultdict in Python" }, { "code": null, "e": 28589, "s": 28558, "text": "Python | os.path.join() method" }, { "code": null, "e": 28618, "s": 28589, "text": "Create a directory in Python" } ]
How to export Pandas DataFrame to a CSV file? - GeeksforGeeks
10 Jul, 2020 Let us see how to export a Pandas DataFrame to a CSV file. We will be using the to_csv() function to save a DataFrame as a CSV file. Syntax : to_csv(parameters)Parameters : path_or_buf : File path or object, if None is provided the result is returned as a string. sep : String of length 1. Field delimiter for the output file. na_rep : Missing data representation. float_format : Format string for floating point numbers. columns : Columns to write. header : If a list of strings is given it is assumed to be aliases for the column names. index : Write row names (index). index_label : Column label for index column(s) if desired. If None is given, and header and index are True, then the index names are used. mode : Python write mode, default ‘w’. encoding : A string representing the encoding to use in the output file. compression : Compression mode among the following possible values: {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}. quoting : Defaults to csv.QUOTE_MINIMAL. quotechar : String of length 1. Character used to quote fields. line_terminator : The newline character or character sequence to use in the output file. chunksize : Rows to write at a time. date_format : Format string for datetime objects. doublequote : Control quoting of quotechar inside a field. escapechar : String of length 1. Character used to escape sep and quotechar when appropriate. decimal : Character recognized as decimal separator. E.g. use ‘,’ for European data. Returns : None or str # importing the moduleimport pandas as pd # creating the DataFramemy_df = {'Name': ['Rutuja', 'Anuja'], 'ID': [1, 2], 'Age': [20, 19]}df = pd.DataFrame(my_df) # displaying the DataFrameprint('DataFrame:\n', df) # saving the DataFrame as a CSV filegfg_csv_data = df.to_csv('GfG.csv', index = True)print('\nCSV String:\n', gfg_csv_data) Output :Before executing the code: After executing the code:We can clearly see the .csv file created. Also, the output of the above code includes the index, as follows. Example 2 : Converting to a CSV file without the index. If we wish not to include the index, then in the index parameter assign the value False. # importing the moduleimport pandas as pd # creating the DataFramemy_df = {'Name': ['Rutuja', 'Anuja'], 'ID': [1, 2], 'Age': [20, 19]}df = pd.DataFrame(my_df) # displaying the DataFrameprint('DataFrame:\n', df) # saving the DataFrame as a CSV filegfg_csv_data = df.to_csv('GfG.csv', index = False)print('\nCSV String:\n', gfg_csv_data) Output: Example 3 : Converting to a CSV file without the header of the rows. If we wish not to include the header, then in the headerparameter assign the value False. # importing the moduleimport pandas as pd # creating the DataFramemy_df = {'Name': ['Rutuja', 'Anuja'], 'ID': [1, 2], 'Age': [20, 19]}df = pd.DataFrame(my_df) # displaying the DataFrameprint('DataFrame:\n', df) # saving the DataFrame as a CSV filegfg_csv_data = df.to_csv('GfG.csv', header = False)print('\nCSV String:\n', gfg_csv_data) Output: Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 26093, "s": 26065, "text": "\n10 Jul, 2020" }, { "code": null, "e": 26226, "s": 26093, "text": "Let us see how to export a Pandas DataFrame to a CSV file. We will be using the to_csv() function to save a DataFrame as a CSV file." }, { "code": null, "e": 26266, "s": 26226, "text": "Syntax : to_csv(parameters)Parameters :" }, { "code": null, "e": 26357, "s": 26266, "text": "path_or_buf : File path or object, if None is provided the result is returned as a string." }, { "code": null, "e": 26420, "s": 26357, "text": "sep : String of length 1. Field delimiter for the output file." }, { "code": null, "e": 26458, "s": 26420, "text": "na_rep : Missing data representation." }, { "code": null, "e": 26515, "s": 26458, "text": "float_format : Format string for floating point numbers." }, { "code": null, "e": 26543, "s": 26515, "text": "columns : Columns to write." }, { "code": null, "e": 26632, "s": 26543, "text": "header : If a list of strings is given it is assumed to be aliases for the column names." }, { "code": null, "e": 26665, "s": 26632, "text": "index : Write row names (index)." }, { "code": null, "e": 26804, "s": 26665, "text": "index_label : Column label for index column(s) if desired. If None is given, and header and index are True, then the index names are used." }, { "code": null, "e": 26843, "s": 26804, "text": "mode : Python write mode, default ‘w’." }, { "code": null, "e": 26916, "s": 26843, "text": "encoding : A string representing the encoding to use in the output file." }, { "code": null, "e": 27029, "s": 26916, "text": "compression : Compression mode among the following possible values: {‘infer’, ‘gzip’, ‘bz2’, ‘zip’, ‘xz’, None}." }, { "code": null, "e": 27070, "s": 27029, "text": "quoting : Defaults to csv.QUOTE_MINIMAL." }, { "code": null, "e": 27134, "s": 27070, "text": "quotechar : String of length 1. Character used to quote fields." }, { "code": null, "e": 27223, "s": 27134, "text": "line_terminator : The newline character or character sequence to use in the output file." }, { "code": null, "e": 27260, "s": 27223, "text": "chunksize : Rows to write at a time." }, { "code": null, "e": 27310, "s": 27260, "text": "date_format : Format string for datetime objects." }, { "code": null, "e": 27369, "s": 27310, "text": "doublequote : Control quoting of quotechar inside a field." }, { "code": null, "e": 27463, "s": 27369, "text": "escapechar : String of length 1. Character used to escape sep and quotechar when appropriate." }, { "code": null, "e": 27548, "s": 27463, "text": "decimal : Character recognized as decimal separator. E.g. use ‘,’ for European data." }, { "code": null, "e": 27570, "s": 27548, "text": "Returns : None or str" }, { "code": "# importing the moduleimport pandas as pd # creating the DataFramemy_df = {'Name': ['Rutuja', 'Anuja'], 'ID': [1, 2], 'Age': [20, 19]}df = pd.DataFrame(my_df) # displaying the DataFrameprint('DataFrame:\\n', df) # saving the DataFrame as a CSV filegfg_csv_data = df.to_csv('GfG.csv', index = True)print('\\nCSV String:\\n', gfg_csv_data)", "e": 27927, "s": 27570, "text": null }, { "code": null, "e": 27962, "s": 27927, "text": "Output :Before executing the code:" }, { "code": null, "e": 28029, "s": 27962, "text": "After executing the code:We can clearly see the .csv file created." }, { "code": null, "e": 28096, "s": 28029, "text": "Also, the output of the above code includes the index, as follows." }, { "code": null, "e": 28241, "s": 28096, "text": "Example 2 : Converting to a CSV file without the index. If we wish not to include the index, then in the index parameter assign the value False." }, { "code": "# importing the moduleimport pandas as pd # creating the DataFramemy_df = {'Name': ['Rutuja', 'Anuja'], 'ID': [1, 2], 'Age': [20, 19]}df = pd.DataFrame(my_df) # displaying the DataFrameprint('DataFrame:\\n', df) # saving the DataFrame as a CSV filegfg_csv_data = df.to_csv('GfG.csv', index = False)print('\\nCSV String:\\n', gfg_csv_data)", "e": 28599, "s": 28241, "text": null }, { "code": null, "e": 28607, "s": 28599, "text": "Output:" }, { "code": null, "e": 28766, "s": 28607, "text": "Example 3 : Converting to a CSV file without the header of the rows. If we wish not to include the header, then in the headerparameter assign the value False." }, { "code": "# importing the moduleimport pandas as pd # creating the DataFramemy_df = {'Name': ['Rutuja', 'Anuja'], 'ID': [1, 2], 'Age': [20, 19]}df = pd.DataFrame(my_df) # displaying the DataFrameprint('DataFrame:\\n', df) # saving the DataFrame as a CSV filegfg_csv_data = df.to_csv('GfG.csv', header = False)print('\\nCSV String:\\n', gfg_csv_data)", "e": 29125, "s": 28766, "text": null }, { "code": null, "e": 29133, "s": 29125, "text": "Output:" }, { "code": null, "e": 29157, "s": 29133, "text": "Python pandas-dataFrame" }, { "code": null, "e": 29171, "s": 29157, "text": "Python-pandas" }, { "code": null, "e": 29178, "s": 29171, "text": "Python" }, { "code": null, "e": 29276, "s": 29178, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29294, "s": 29276, "text": "Python Dictionary" }, { "code": null, "e": 29326, "s": 29294, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29348, "s": 29326, "text": "Enumerate() in Python" }, { "code": null, "e": 29390, "s": 29348, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29419, "s": 29390, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29463, "s": 29419, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29500, "s": 29463, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29536, "s": 29500, "text": "Convert integer to string in Python" }, { "code": null, "e": 29578, "s": 29536, "text": "Check if element exists in list in Python" } ]
Lexicographically smallest string after M operations - GeeksforGeeks
27 Aug, 2021 Given a string S and integer M. The task is to perform exactly M operations to get lexicographical smallest string. In each operation, select one character optimally from the string and update it with immediate next character ( aaa -> aab ), so that string remain lexicographical smallest. Multiple operations are allowed over single character of the string. Note: Consider next of ‘z’ as ‘a’.Examples: Input: S = “aazzx”, M = 6 Output: aaaab Explanation: We try to form lexicographical smallest string for each operations. For m = 1: update “aazzx” to “aaazx” for m = 2: update “aaazx” to “aaaax” for m = 3: update “aaaax” to “aaaay” for m = 4: update “aaaay” to “aaaaz” for m = 5: update “aaaaz” to “aaaaa” for m = 6: update “aaaaa” to “aaaab” which is lexicographical smallest than “aaaba”, “aabaa”, “abaaa”, “baaaa”. Final string after 6 operations: “aaaab”.Input: S = “z”, M = 27 Output: a Explanation: Try to form lexicographical smallest string for each operations, since there is only single character so all 27 operations have to performed over it. Final string after 27 operation is “a”. Approach: The idea is to implement a simple greedy approach, to iterate the string from the starting of the string and while iterating focus on the current element of the string to make it as small as possible. Suppose, current element is r, to make r smallest i.e. a, it require 9 operations, let call the value as distance. Now, check if M is greater than equal to the distance, then update current character to ‘a’ and decrease the value of M by distance. Otherwise continue with next iteration. As next of z is a, cycle of 26 is formed. So the last character of the string, can be updated with last character + (M % 26). Below is the implementation of the above approach: C++ Java Python3 C# // C++ implementation to find the// lexicographical smallest string// after performing M operations #include <bits/stdc++.h>using namespace std; // Function to find the// lexicographical smallest string// after performing M operationsvoid smallest_string(string s, int m){ // Size of the given string int n = s.size(); // Declare an array a int a[n]; // For each i, a[i] contain number // of operations to update s[i] to 'a' for (int i = 0; i < n; i++) { int distance = s[i] - 'a'; if (distance == 0) a[i] = 0; else a[i] = 26 - distance; } for (int i = 0; i < n; i++) { // Check if m >= ar[i], // then update s[i] to 'a' // decrement k by a[i] if (m >= a[i]) { s[i] = 'a'; m = m - a[i]; } } // Form a cycle of 26 m = m % 26; // update last element of // string with the value // s[i] + (k % 26) s[n - 1] = s[n - 1] + m; // Return the answer cout << s;} // Driver codeint main(){ string str = "aazzx"; int m = 6; smallest_string(str, m); return 0;} // Java implementation to find the// lexicographical smallest String// after performing M operationsclass GFG{ // Function to find the// lexicographical smallest String// after performing M operationsstatic void smallest_String(char []s, int m){ // Size of the given String int n = s.length; // Declare an array a int []a = new int[n]; // For each i, a[i] contain number // of operations to update s[i] to 'a' for (int i = 0; i < n; i++) { int distance = s[i] - 'a'; if (distance == 0) a[i] = 0; else a[i] = 26 - distance; } for (int i = 0; i < n; i++) { // Check if m >= ar[i], // then update s[i] to 'a' // decrement k by a[i] if (m >= a[i]) { s[i] = 'a'; m = m - a[i]; } } // Form a cycle of 26 m = m % 26; // update last element of // String with the value // s[i] + (k % 26) s[n - 1] = (char) (s[n - 1] + m); // Return the answer System.out.print(String.valueOf(s));} // Driver codepublic static void main(String[] args){ String str = "aazzx"; int m = 6; smallest_String(str.toCharArray(), m);}} // This code is contributed by Princi Singh # Python3 implementation to find the# lexicographical smallest string# after performing M operations # Function to find the# lexicographical smallest string# after performing M operationsdef smallest_string(s, m): # Size of the given string n = len(s); l = list(s) # Declare an array a a = [0] * n; # For each i, a[i] contain number # of operations to update s[i] to 'a' for i in range(n): distance = ord(s[i]) - ord('a'); if (distance == 0): a[i] = 0; else: a[i] = 26 - distance; for i in range(n): # Check if m >= ar[i], # then update s[i] to 'a' # decrement k by a[i] if (m >= a[i]): l[i] = 'a'; m = m - a[i]; # Form a cycle of 26 m = m % 26; # update last element of # with the value # s[i] + (k % 26) # Return the answer for i in range(len(l) - 1): print(l[i], end = "") print(chr(ord(l[n - 1]) + m)) # Driver codestr = "aazzx";m = 6; smallest_string(str, m); # This code is contributed by grand_master // C# implementation to find the// lexicographical smallest String// after performing M operationsusing System; class GFG{ // Function to find the// lexicographical smallest String// after performing M operationsstatic void smallest_String(char []s, int m){ // Size of the given String int n = s.Length; // Declare an array a int []a = new int[n]; // For each i, a[i] contain number // of operations to update s[i] to 'a' for(int i = 0; i < n; i++) { int distance = s[i] - 'a'; if (distance == 0) a[i] = 0; else a[i] = 26 - distance; } for(int i = 0; i < n; i++) { // Check if m >= ar[i], // then update s[i] to 'a' // decrement k by a[i] if (m >= a[i]) { s[i] = 'a'; m = m - a[i]; } } // Form a cycle of 26 m = m % 26; // Update last element of // String with the value // s[i] + (k % 26) s[n - 1] = (char)(s[n - 1] + m); // Return the answer Console.Write(String.Join("", s));} // Driver codepublic static void Main(String[] args){ String str = "aazzx"; int m = 6; smallest_String(str.ToCharArray(), m);}} // This code is contributed by Princi Singh aaaab Time Complexity: O(N), where N is the length of given string Auxiliary Space: O(N), where N is the length of given string princi singh grand_master anikaseth98 lexicographic-ordering Greedy Sorting Strings Strings Greedy Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimal Page Replacement Algorithm Program for Best Fit algorithm in Memory Management Program for First Fit algorithm in Memory Management Bin Packing Problem (Minimize number of used Bins) Max Flow Problem Introduction
[ { "code": null, "e": 26561, "s": 26533, "text": "\n27 Aug, 2021" }, { "code": null, "e": 26677, "s": 26561, "text": "Given a string S and integer M. The task is to perform exactly M operations to get lexicographical smallest string." }, { "code": null, "e": 26851, "s": 26677, "text": "In each operation, select one character optimally from the string and update it with immediate next character ( aaa -> aab ), so that string remain lexicographical smallest." }, { "code": null, "e": 26920, "s": 26851, "text": "Multiple operations are allowed over single character of the string." }, { "code": null, "e": 26964, "s": 26920, "text": "Note: Consider next of ‘z’ as ‘a’.Examples:" }, { "code": null, "e": 27659, "s": 26964, "text": "Input: S = “aazzx”, M = 6 Output: aaaab Explanation: We try to form lexicographical smallest string for each operations. For m = 1: update “aazzx” to “aaazx” for m = 2: update “aaazx” to “aaaax” for m = 3: update “aaaax” to “aaaay” for m = 4: update “aaaay” to “aaaaz” for m = 5: update “aaaaz” to “aaaaa” for m = 6: update “aaaaa” to “aaaab” which is lexicographical smallest than “aaaba”, “aabaa”, “abaaa”, “baaaa”. Final string after 6 operations: “aaaab”.Input: S = “z”, M = 27 Output: a Explanation: Try to form lexicographical smallest string for each operations, since there is only single character so all 27 operations have to performed over it. Final string after 27 operation is “a”." }, { "code": null, "e": 27870, "s": 27659, "text": "Approach: The idea is to implement a simple greedy approach, to iterate the string from the starting of the string and while iterating focus on the current element of the string to make it as small as possible." }, { "code": null, "e": 27985, "s": 27870, "text": "Suppose, current element is r, to make r smallest i.e. a, it require 9 operations, let call the value as distance." }, { "code": null, "e": 28158, "s": 27985, "text": "Now, check if M is greater than equal to the distance, then update current character to ‘a’ and decrease the value of M by distance. Otherwise continue with next iteration." }, { "code": null, "e": 28284, "s": 28158, "text": "As next of z is a, cycle of 26 is formed. So the last character of the string, can be updated with last character + (M % 26)." }, { "code": null, "e": 28335, "s": 28284, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28339, "s": 28335, "text": "C++" }, { "code": null, "e": 28344, "s": 28339, "text": "Java" }, { "code": null, "e": 28352, "s": 28344, "text": "Python3" }, { "code": null, "e": 28355, "s": 28352, "text": "C#" }, { "code": "// C++ implementation to find the// lexicographical smallest string// after performing M operations #include <bits/stdc++.h>using namespace std; // Function to find the// lexicographical smallest string// after performing M operationsvoid smallest_string(string s, int m){ // Size of the given string int n = s.size(); // Declare an array a int a[n]; // For each i, a[i] contain number // of operations to update s[i] to 'a' for (int i = 0; i < n; i++) { int distance = s[i] - 'a'; if (distance == 0) a[i] = 0; else a[i] = 26 - distance; } for (int i = 0; i < n; i++) { // Check if m >= ar[i], // then update s[i] to 'a' // decrement k by a[i] if (m >= a[i]) { s[i] = 'a'; m = m - a[i]; } } // Form a cycle of 26 m = m % 26; // update last element of // string with the value // s[i] + (k % 26) s[n - 1] = s[n - 1] + m; // Return the answer cout << s;} // Driver codeint main(){ string str = \"aazzx\"; int m = 6; smallest_string(str, m); return 0;}", "e": 29477, "s": 28355, "text": null }, { "code": "// Java implementation to find the// lexicographical smallest String// after performing M operationsclass GFG{ // Function to find the// lexicographical smallest String// after performing M operationsstatic void smallest_String(char []s, int m){ // Size of the given String int n = s.length; // Declare an array a int []a = new int[n]; // For each i, a[i] contain number // of operations to update s[i] to 'a' for (int i = 0; i < n; i++) { int distance = s[i] - 'a'; if (distance == 0) a[i] = 0; else a[i] = 26 - distance; } for (int i = 0; i < n; i++) { // Check if m >= ar[i], // then update s[i] to 'a' // decrement k by a[i] if (m >= a[i]) { s[i] = 'a'; m = m - a[i]; } } // Form a cycle of 26 m = m % 26; // update last element of // String with the value // s[i] + (k % 26) s[n - 1] = (char) (s[n - 1] + m); // Return the answer System.out.print(String.valueOf(s));} // Driver codepublic static void main(String[] args){ String str = \"aazzx\"; int m = 6; smallest_String(str.toCharArray(), m);}} // This code is contributed by Princi Singh", "e": 30706, "s": 29477, "text": null }, { "code": "# Python3 implementation to find the# lexicographical smallest string# after performing M operations # Function to find the# lexicographical smallest string# after performing M operationsdef smallest_string(s, m): # Size of the given string n = len(s); l = list(s) # Declare an array a a = [0] * n; # For each i, a[i] contain number # of operations to update s[i] to 'a' for i in range(n): distance = ord(s[i]) - ord('a'); if (distance == 0): a[i] = 0; else: a[i] = 26 - distance; for i in range(n): # Check if m >= ar[i], # then update s[i] to 'a' # decrement k by a[i] if (m >= a[i]): l[i] = 'a'; m = m - a[i]; # Form a cycle of 26 m = m % 26; # update last element of # with the value # s[i] + (k % 26) # Return the answer for i in range(len(l) - 1): print(l[i], end = \"\") print(chr(ord(l[n - 1]) + m)) # Driver codestr = \"aazzx\";m = 6; smallest_string(str, m); # This code is contributed by grand_master", "e": 31820, "s": 30706, "text": null }, { "code": "// C# implementation to find the// lexicographical smallest String// after performing M operationsusing System; class GFG{ // Function to find the// lexicographical smallest String// after performing M operationsstatic void smallest_String(char []s, int m){ // Size of the given String int n = s.Length; // Declare an array a int []a = new int[n]; // For each i, a[i] contain number // of operations to update s[i] to 'a' for(int i = 0; i < n; i++) { int distance = s[i] - 'a'; if (distance == 0) a[i] = 0; else a[i] = 26 - distance; } for(int i = 0; i < n; i++) { // Check if m >= ar[i], // then update s[i] to 'a' // decrement k by a[i] if (m >= a[i]) { s[i] = 'a'; m = m - a[i]; } } // Form a cycle of 26 m = m % 26; // Update last element of // String with the value // s[i] + (k % 26) s[n - 1] = (char)(s[n - 1] + m); // Return the answer Console.Write(String.Join(\"\", s));} // Driver codepublic static void Main(String[] args){ String str = \"aazzx\"; int m = 6; smallest_String(str.ToCharArray(), m);}} // This code is contributed by Princi Singh", "e": 33073, "s": 31820, "text": null }, { "code": null, "e": 33079, "s": 33073, "text": "aaaab" }, { "code": null, "e": 33202, "s": 33079, "text": "Time Complexity: O(N), where N is the length of given string Auxiliary Space: O(N), where N is the length of given string " }, { "code": null, "e": 33215, "s": 33202, "text": "princi singh" }, { "code": null, "e": 33228, "s": 33215, "text": "grand_master" }, { "code": null, "e": 33240, "s": 33228, "text": "anikaseth98" }, { "code": null, "e": 33263, "s": 33240, "text": "lexicographic-ordering" }, { "code": null, "e": 33270, "s": 33263, "text": "Greedy" }, { "code": null, "e": 33278, "s": 33270, "text": "Sorting" }, { "code": null, "e": 33286, "s": 33278, "text": "Strings" }, { "code": null, "e": 33294, "s": 33286, "text": "Strings" }, { "code": null, "e": 33301, "s": 33294, "text": "Greedy" }, { "code": null, "e": 33309, "s": 33301, "text": "Sorting" }, { "code": null, "e": 33407, "s": 33309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33442, "s": 33407, "text": "Optimal Page Replacement Algorithm" }, { "code": null, "e": 33494, "s": 33442, "text": "Program for Best Fit algorithm in Memory Management" }, { "code": null, "e": 33547, "s": 33494, "text": "Program for First Fit algorithm in Memory Management" }, { "code": null, "e": 33598, "s": 33547, "text": "Bin Packing Problem (Minimize number of used Bins)" } ]
Difference Between Collection.stream().forEach() and Collection.forEach() in Java - GeeksforGeeks
02 Feb, 2021 Collection.forEach() and Collection.stream().forEach() are used for iterating over the collections, there is no such major difference between the two, as both of them give the same result, though there are some differences in their internal working. Collection.stream().forEach() is basically used for iteration in a group of objects by converting a collection into the stream and then iterate over the stream of collection. While iterating over the collection, if any structural changes are made to collections, then it will throw the concurrent modification exception. Collection.forEach() uses the collection’s iterator(whichever is specified). The majority of the collections do not allow modifications in the structure while iterating over that collection. If any changes happen to that collection, i.e. addition of an element or the removal of the element, then they will throw the concurrent modification error. If collection.forEach() is iterating over a synchronized collection, then they will lock the segment of collection and hold it over all the calls that can be made w.r.t to that collection. Collection.stream().forEach() Below is a Java program to show the usage of the Collection.stream.forEach(): Java // Java Program to show the demonstration of// Collection.stream().forEach()import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(5); list.add(6); list.add(3); list.add(4); // printing each element of list using forEach loop list.stream().forEach(System.out::print); }} 5634 Below is a Java program to show the usage of Collection.forEach() Method: Java // Java Program to show the demonstration of// Collection.forEach()import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(5); list.add(6); list.add(3); list.add(4); // printing each element of list list.forEach(System.out::print); }} 5634 Java-Collections Picked Technical Scripter 2020 Difference Between Java Technical Scripter Java Java-Collections 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 Difference Between Method Overloading and Method Overriding in Java Difference between Prim's and Kruskal's algorithm for MST Difference between Internal and External fragmentation Difference between Compile-time and Run-time Polymorphism in Java Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26103, "s": 26075, "text": "\n02 Feb, 2021" }, { "code": null, "e": 26353, "s": 26103, "text": "Collection.forEach() and Collection.stream().forEach() are used for iterating over the collections, there is no such major difference between the two, as both of them give the same result, though there are some differences in their internal working." }, { "code": null, "e": 26674, "s": 26353, "text": "Collection.stream().forEach() is basically used for iteration in a group of objects by converting a collection into the stream and then iterate over the stream of collection. While iterating over the collection, if any structural changes are made to collections, then it will throw the concurrent modification exception." }, { "code": null, "e": 27211, "s": 26674, "text": "Collection.forEach() uses the collection’s iterator(whichever is specified). The majority of the collections do not allow modifications in the structure while iterating over that collection. If any changes happen to that collection, i.e. addition of an element or the removal of the element, then they will throw the concurrent modification error. If collection.forEach() is iterating over a synchronized collection, then they will lock the segment of collection and hold it over all the calls that can be made w.r.t to that collection." }, { "code": null, "e": 27243, "s": 27211, "text": " Collection.stream().forEach()" }, { "code": null, "e": 27321, "s": 27243, "text": "Below is a Java program to show the usage of the Collection.stream.forEach():" }, { "code": null, "e": 27326, "s": 27321, "text": "Java" }, { "code": "// Java Program to show the demonstration of// Collection.stream().forEach()import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(5); list.add(6); list.add(3); list.add(4); // printing each element of list using forEach loop list.stream().forEach(System.out::print); }}", "e": 27742, "s": 27326, "text": null }, { "code": null, "e": 27747, "s": 27742, "text": "5634" }, { "code": null, "e": 27821, "s": 27747, "text": "Below is a Java program to show the usage of Collection.forEach() Method:" }, { "code": null, "e": 27826, "s": 27821, "text": "Java" }, { "code": "// Java Program to show the demonstration of// Collection.forEach()import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { List<Integer> list = new ArrayList<>(); list.add(5); list.add(6); list.add(3); list.add(4); // printing each element of list list.forEach(System.out::print); }}", "e": 28205, "s": 27826, "text": null }, { "code": null, "e": 28210, "s": 28205, "text": "5634" }, { "code": null, "e": 28227, "s": 28210, "text": "Java-Collections" }, { "code": null, "e": 28234, "s": 28227, "text": "Picked" }, { "code": null, "e": 28258, "s": 28234, "text": "Technical Scripter 2020" }, { "code": null, "e": 28277, "s": 28258, "text": "Difference Between" }, { "code": null, "e": 28282, "s": 28277, "text": "Java" }, { "code": null, "e": 28301, "s": 28282, "text": "Technical Scripter" }, { "code": null, "e": 28306, "s": 28301, "text": "Java" }, { "code": null, "e": 28323, "s": 28306, "text": "Java-Collections" }, { "code": null, "e": 28421, "s": 28323, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28482, "s": 28421, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28550, "s": 28482, "text": "Difference Between Method Overloading and Method Overriding in Java" }, { "code": null, "e": 28608, "s": 28550, "text": "Difference between Prim's and Kruskal's algorithm for MST" }, { "code": null, "e": 28663, "s": 28608, "text": "Difference between Internal and External fragmentation" }, { "code": null, "e": 28729, "s": 28663, "text": "Difference between Compile-time and Run-time Polymorphism in Java" }, { "code": null, "e": 28744, "s": 28729, "text": "Arrays in Java" }, { "code": null, "e": 28788, "s": 28744, "text": "Split() String method in Java with examples" }, { "code": null, "e": 28810, "s": 28788, "text": "For-each loop in Java" }, { "code": null, "e": 28861, "s": 28810, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Python | Merge two list of lists according to first element - GeeksforGeeks
20 May, 2019 Given two list of lists of equal length, write a Python program to merge the given two list of lists, according to the first common element of each sublist. Examples: Input : lst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']] lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']] Output : [[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']] Input : lst1 = [ ['c', 'class'], ['g', 'greek'], ] lst2 = [['c', 'coder'], ['g', 'god'], ] Output : [['c', 'class', 'coder'], ['g', 'greek', 'god']] Method #1 : Python zip() with list comprehension # Python3 program to Merge two list of # lists according to first element def merge(lst1, lst2): return [a + [b[1]] for (a, b) in zip(lst1, lst2)] # Driver codelst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]print(merge(lst1, lst2)) [[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']] Method #2 : Python enumerate() with list comprehension # Python3 program to Merge two list of # lists according to first elementimport collections def merge(lst1, lst2): return [(sub + [lst2[i][-1]]) for i, sub in enumerate(lst1)] # Driver codelst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]print(merge(lst1, lst2)) [[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']] Method #3 : Python dictionaryIn this method, we initialise ‘dict1’ with collections.defaultdict and traverse through ‘lst1’+’lst2’ and append the first element of ‘lst1’ as key and tupled second element of both respective sublists as value. Finally we traverse through ‘dict1’ and initialize ‘dictlist’ with the desired output. # Python3 program to Merge two list of # lists according to first elementimport collections def merge(lst1, lst2): dict1 = collections.defaultdict(list) for e in lst1 + lst2: dict1[e[0]].append(e[1]) dictlist = list() for key, value in dict1.items(): dictlist.append([key]+value) return dictlist # Driver codelst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]print(merge(lst1, lst2)) [[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25645, "s": 25617, "text": "\n20 May, 2019" }, { "code": null, "e": 25802, "s": 25645, "text": "Given two list of lists of equal length, write a Python program to merge the given two list of lists, according to the first common element of each sublist." }, { "code": null, "e": 25812, "s": 25802, "text": "Examples:" }, { "code": null, "e": 26166, "s": 25812, "text": "Input : lst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]\n lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]\nOutput : [[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]\n\nInput : lst1 = [ ['c', 'class'], ['g', 'greek'], ]\n lst2 = [['c', 'coder'], ['g', 'god'], ]\nOutput : [['c', 'class', 'coder'], ['g', 'greek', 'god']]\n" }, { "code": null, "e": 26216, "s": 26166, "text": " Method #1 : Python zip() with list comprehension" }, { "code": "# Python3 program to Merge two list of # lists according to first element def merge(lst1, lst2): return [a + [b[1]] for (a, b) in zip(lst1, lst2)] # Driver codelst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]print(merge(lst1, lst2))", "e": 26508, "s": 26216, "text": null }, { "code": null, "e": 26579, "s": 26508, "text": "[[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]\n" }, { "code": null, "e": 26635, "s": 26579, "text": " Method #2 : Python enumerate() with list comprehension" }, { "code": "# Python3 program to Merge two list of # lists according to first elementimport collections def merge(lst1, lst2): return [(sub + [lst2[i][-1]]) for i, sub in enumerate(lst1)] # Driver codelst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]print(merge(lst1, lst2))", "e": 26956, "s": 26635, "text": null }, { "code": null, "e": 27027, "s": 26956, "text": "[[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]\n" }, { "code": null, "e": 27356, "s": 27027, "text": " Method #3 : Python dictionaryIn this method, we initialise ‘dict1’ with collections.defaultdict and traverse through ‘lst1’+’lst2’ and append the first element of ‘lst1’ as key and tupled second element of both respective sublists as value. Finally we traverse through ‘dict1’ and initialize ‘dictlist’ with the desired output." }, { "code": "# Python3 program to Merge two list of # lists according to first elementimport collections def merge(lst1, lst2): dict1 = collections.defaultdict(list) for e in lst1 + lst2: dict1[e[0]].append(e[1]) dictlist = list() for key, value in dict1.items(): dictlist.append([key]+value) return dictlist # Driver codelst1 = [[1, 'Alice'], [2, 'Bob'], [3, 'Cara']]lst2 = [[1, 'Delhi'], [2, 'Mumbai'], [3, 'Chennai']]print(merge(lst1, lst2))", "e": 27841, "s": 27356, "text": null }, { "code": null, "e": 27912, "s": 27841, "text": "[[1, 'Alice', 'Delhi'], [2, 'Bob', 'Mumbai'], [3, 'Cara', 'Chennai']]\n" }, { "code": null, "e": 27933, "s": 27912, "text": "Python list-programs" }, { "code": null, "e": 27940, "s": 27933, "text": "Python" }, { "code": null, "e": 27956, "s": 27940, "text": "Python Programs" }, { "code": null, "e": 28054, "s": 27956, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28072, "s": 28054, "text": "Python Dictionary" }, { "code": null, "e": 28107, "s": 28072, "text": "Read a file line by line in Python" }, { "code": null, "e": 28139, "s": 28107, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28181, "s": 28139, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28207, "s": 28181, "text": "Python String | replace()" }, { "code": null, "e": 28250, "s": 28207, "text": "Python program to convert a list to string" }, { "code": null, "e": 28272, "s": 28250, "text": "Defaultdict in Python" }, { "code": null, "e": 28311, "s": 28272, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 28357, "s": 28311, "text": "Python | Split string into list of characters" } ]
Node.js fs.open() Method - GeeksforGeeks
21 Jan, 2022 Introduction: To create file, to write to a file or to read a file fs.open() method is used. fs.readFile() is only for reading the file and similarly fs.writeFile() is only for writing to a file, whereas fs.open() method does several operations on a file. First we need to load the fs class which is module to access physical file system. For it require method is used. For example: var fs = require(‘fs’); Syntax: fs.open( filename, flags, mode, callback ) Parameter: This method accept four parameters as mentioned above and described below: filename: It holds the name of the file to read or the entire path if stored at other location. flag: The operation in which file has to be opened. 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: err: If any error occurs.data: A file descriptor, used by subsequent file operations. A file descriptor is a handle used to access a file. It is a non-negative integer uniquely referencing a specific file. err: If any error occurs. data: A file descriptor, used by subsequent file operations. A file descriptor is a handle used to access a file. It is a non-negative integer uniquely referencing a specific file. All the types of flags are described below: Below examples illustrate the fs.open() method in Node.js:Example 1: javascript // Node.js program to demonstrate the // fs.open() Method // Include the fs modulevar fs = require('fs'); // Open file demo.txt in read modefs.open('demo.txt', 'r', function (err, f) { console.log('Saved!');}); Output: Saved! Explanation: The file is opened and the flag is set to read mode. After opening of file function is called to read the contents of file and store in memory. As there are no errors ‘saved’ is printed.Example 2: javascript // Node.js program to demonstrate the // fs.open() Method // Include the fs modulevar fs = require('fs'); console.log("Open file!"); // To open file in write and read mode,// create file if doesn't exists.fs.open('demo.txt', 'w+', function (err, f) { if (err) { return console.error(err); } console.log(f); console.log("File opened!!"); }); Output: Open file! 10 File Opened! Explanation: The file ‘demo.txt’ is opened in read and write mode, then the function is called. Output shows a number in file when we print value of ‘f’. Reference: https://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback Akanksha_Rai dshaikh900 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 install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Mongoose | findByIdAndUpdate() Function Express.js res.render() Function 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": 25743, "s": 25715, "text": "\n21 Jan, 2022" }, { "code": null, "e": 26160, "s": 25743, "text": "Introduction: To create file, to write to a file or to read a file fs.open() method is used. fs.readFile() is only for reading the file and similarly fs.writeFile() is only for writing to a file, whereas fs.open() method does several operations on a file. First we need to load the fs class which is module to access physical file system. For it require method is used. For example: var fs = require(‘fs’); Syntax: " }, { "code": null, "e": 26203, "s": 26160, "text": "fs.open( filename, flags, mode, callback )" }, { "code": null, "e": 26291, "s": 26203, "text": "Parameter: This method accept four parameters as mentioned above and described below: " }, { "code": null, "e": 26387, "s": 26291, "text": "filename: It holds the name of the file to read or the entire path if stored at other location." }, { "code": null, "e": 26439, "s": 26387, "text": "flag: The operation in which file has to be opened." }, { "code": null, "e": 26537, "s": 26439, "text": "mode: Sets the mode of file i.e. r-read, w-write, r+ -readwrite. It sets to default as readwrite." }, { "code": null, "e": 26841, "s": 26537, "text": "callback: It is a callback function that is called after reading a file. It takes two parameters: err: If any error occurs.data: A file descriptor, used by subsequent file operations. A file descriptor is a handle used to access a file. It is a non-negative integer uniquely referencing a specific file." }, { "code": null, "e": 26867, "s": 26841, "text": "err: If any error occurs." }, { "code": null, "e": 27048, "s": 26867, "text": "data: A file descriptor, used by subsequent file operations. A file descriptor is a handle used to access a file. It is a non-negative integer uniquely referencing a specific file." }, { "code": null, "e": 27094, "s": 27048, "text": "All the types of flags are described below: " }, { "code": null, "e": 27165, "s": 27094, "text": "Below examples illustrate the fs.open() method in Node.js:Example 1: " }, { "code": null, "e": 27176, "s": 27165, "text": "javascript" }, { "code": "// Node.js program to demonstrate the // fs.open() Method // Include the fs modulevar fs = require('fs'); // Open file demo.txt in read modefs.open('demo.txt', 'r', function (err, f) { console.log('Saved!');});", "e": 27391, "s": 27176, "text": null }, { "code": null, "e": 27401, "s": 27391, "text": "Output: " }, { "code": null, "e": 27409, "s": 27401, "text": "Saved! " }, { "code": null, "e": 27621, "s": 27409, "text": "Explanation: The file is opened and the flag is set to read mode. After opening of file function is called to read the contents of file and store in memory. As there are no errors ‘saved’ is printed.Example 2: " }, { "code": null, "e": 27632, "s": 27621, "text": "javascript" }, { "code": "// Node.js program to demonstrate the // fs.open() Method // Include the fs modulevar fs = require('fs'); console.log(\"Open file!\"); // To open file in write and read mode,// create file if doesn't exists.fs.open('demo.txt', 'w+', function (err, f) { if (err) { return console.error(err); } console.log(f); console.log(\"File opened!!\"); });", "e": 27992, "s": 27632, "text": null }, { "code": null, "e": 28002, "s": 27992, "text": "Output: " }, { "code": null, "e": 28029, "s": 28002, "text": "Open file!\n10\nFile Opened!" }, { "code": null, "e": 28262, "s": 28029, "text": "Explanation: The file ‘demo.txt’ is opened in read and write mode, then the function is called. Output shows a number in file when we print value of ‘f’. Reference: https://nodejs.org/api/fs.html#fs_fs_open_path_flags_mode_callback " }, { "code": null, "e": 28275, "s": 28262, "text": "Akanksha_Rai" }, { "code": null, "e": 28286, "s": 28275, "text": "dshaikh900" }, { "code": null, "e": 28304, "s": 28286, "text": "Node.js-fs-module" }, { "code": null, "e": 28311, "s": 28304, "text": "Picked" }, { "code": null, "e": 28319, "s": 28311, "text": "Node.js" }, { "code": null, "e": 28336, "s": 28319, "text": "Web Technologies" }, { "code": null, "e": 28434, "s": 28336, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28491, "s": 28434, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 28545, "s": 28491, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 28582, "s": 28545, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 28622, "s": 28582, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 28655, "s": 28622, "text": "Express.js res.render() Function" }, { "code": null, "e": 28695, "s": 28655, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28740, "s": 28695, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 28783, "s": 28740, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 28833, "s": 28783, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to Unnest dataframe in R ? - GeeksforGeeks
18 Jul, 2021 In this article, we will discuss how to unnest dataframes in R Programming Language. Unnesting of dataframe refers to flattening it. The do.call() method in base R constructs and executes a function call from a function using its corresponding argument list. Syntax: do.call(what, args) Parameter : what – The name of the function to execute args – Additional arguments to invoke the function upon. We invoke the function “data.frame” which transforms the object specified as the second argument into the data frame. The output is returned to the form of a data.frame object which contains the rows and corresponding columns’ information. Example: R # creating a data framedata_frame <- data.frame(col1 = sample(letters[1:5]), col2 = 1:5 ) print ("Original DataFrame")print (data_frame) # unnesting data frameunnest_df <- do.call(data.frame, data_frame) # printing unnesting data framestr(unnest_df) Output [1] "Original DataFrame" col1 col2 1 c 1 2 e 2 3 a 3 4 b 4 5 d 5 'data.frame': 5 obs. of 2 variables: $ col1: chr "c" "e" "a" "b" ... $ col2: int 1 2 3 4 5 The purrr package in the R programming language is used to simulate easy working with functions as well as vectors. The bind_cols() method in R is used to bind columns of two or more data frames. The reduce() method is used to reduce a vector, x , to a single value by recursively calling a function. The reduce() method here is used to create second data frame object, which takes as input the last row of the data frame and uses “tibble” as the function. The output is obtained in the form of unnested data frame. Example: R library(purrr) # creating a data framedata_frame <- data.frame(col1 = sample(letters[6:10]), col2 = 1:5 ) print ("Original DataFrame")print (data_frame) # unnesting data frameunnest_df <- bind_cols(data_frame[1], reduce(data_frame[-1], tibble))str(unnest_df) Output [1] "Original DataFrame" col1 col2 1 g 1 2 i 2 3 j 3 4 h 4 5 f 5 'data.frame': 5 obs. of 2 variables: $ col1: chr "g" "i" "j" "h" ... $ ...2: int 1 2 3 4 5 The tidyr package in R is used to “tidy” up the data. The unnest() method in the package can be used to convert the data frame into an unnested object by specifying the input data and its corresponding columns to use in unnesting. The output is produced in the form of a tibble in R. Syntax: unnest (data, cols ) Parameters : data – The data frame to be unnested cols – The columns to use for unnesting Example: R library(tidyr) # creating a data framedata_frame <- data.frame(col1 = sample(letters[6:10]), col2 = 1:5 ) print ("Original DataFrame")print (data_frame) # unnesting data frameunnest_df <- unnest( data_frame , cols = c('col1','col2'))str(unnest_df) Output [1] "Original DataFrame" col1 col2 1 i 1 2 j 2 3 g 3 4 h 4 5 f 5 tibble [5 × 2] (S3: tbl_df/tbl/data.frame) $ col1: chr [1:5] "i" "j" "g" "h" ... $ col2: int [1:5] 1 2 3 4 5 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to filter R dataframe by multiple conditions? Convert Matrix to Dataframe in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n18 Jul, 2021" }, { "code": null, "e": 26620, "s": 26487, "text": "In this article, we will discuss how to unnest dataframes in R Programming Language. Unnesting of dataframe refers to flattening it." }, { "code": null, "e": 26747, "s": 26620, "text": "The do.call() method in base R constructs and executes a function call from a function using its corresponding argument list. " }, { "code": null, "e": 26755, "s": 26747, "text": "Syntax:" }, { "code": null, "e": 26775, "s": 26755, "text": "do.call(what, args)" }, { "code": null, "e": 26788, "s": 26775, "text": "Parameter : " }, { "code": null, "e": 26831, "s": 26788, "text": "what – The name of the function to execute" }, { "code": null, "e": 26889, "s": 26831, "text": "args – Additional arguments to invoke the function upon. " }, { "code": null, "e": 27130, "s": 26889, "text": "We invoke the function “data.frame” which transforms the object specified as the second argument into the data frame. The output is returned to the form of a data.frame object which contains the rows and corresponding columns’ information. " }, { "code": null, "e": 27139, "s": 27130, "text": "Example:" }, { "code": null, "e": 27141, "s": 27139, "text": "R" }, { "code": "# creating a data framedata_frame <- data.frame(col1 = sample(letters[1:5]), col2 = 1:5 ) print (\"Original DataFrame\")print (data_frame) # unnesting data frameunnest_df <- do.call(data.frame, data_frame) # printing unnesting data framestr(unnest_df)", "e": 27442, "s": 27141, "text": null }, { "code": null, "e": 27449, "s": 27442, "text": "Output" }, { "code": null, "e": 27648, "s": 27449, "text": "[1] \"Original DataFrame\" \ncol1 col2 \n1 c 1 \n2 e 2 \n3 a 3 \n4 b 4 \n5 d 5\n'data.frame': 5 obs. of 2 variables: \n$ col1: chr \"c\" \"e\" \"a\" \"b\" ... \n$ col2: int 1 2 3 4 5" }, { "code": null, "e": 28106, "s": 27648, "text": "The purrr package in the R programming language is used to simulate easy working with functions as well as vectors. The bind_cols() method in R is used to bind columns of two or more data frames. The reduce() method is used to reduce a vector, x , to a single value by recursively calling a function. The reduce() method here is used to create second data frame object, which takes as input the last row of the data frame and uses “tibble” as the function. " }, { "code": null, "e": 28166, "s": 28106, "text": "The output is obtained in the form of unnested data frame. " }, { "code": null, "e": 28175, "s": 28166, "text": "Example:" }, { "code": null, "e": 28177, "s": 28175, "text": "R" }, { "code": "library(purrr) # creating a data framedata_frame <- data.frame(col1 = sample(letters[6:10]), col2 = 1:5 ) print (\"Original DataFrame\")print (data_frame) # unnesting data frameunnest_df <- bind_cols(data_frame[1], reduce(data_frame[-1], tibble))str(unnest_df)", "e": 28487, "s": 28177, "text": null }, { "code": null, "e": 28494, "s": 28487, "text": "Output" }, { "code": null, "e": 28696, "s": 28494, "text": "[1] \"Original DataFrame\" \n col1 col2 \n1 g 1 \n2 i 2 \n3 j 3 \n4 h 4 \n5 f 5 \n'data.frame': 5 obs. of 2 variables: \n$ col1: chr \"g\" \"i\" \"j\" \"h\" ... \n$ ...2: int 1 2 3 4 5" }, { "code": null, "e": 28981, "s": 28696, "text": "The tidyr package in R is used to “tidy” up the data. The unnest() method in the package can be used to convert the data frame into an unnested object by specifying the input data and its corresponding columns to use in unnesting. The output is produced in the form of a tibble in R. " }, { "code": null, "e": 28989, "s": 28981, "text": "Syntax:" }, { "code": null, "e": 29010, "s": 28989, "text": "unnest (data, cols )" }, { "code": null, "e": 29024, "s": 29010, "text": "Parameters : " }, { "code": null, "e": 29061, "s": 29024, "text": "data – The data frame to be unnested" }, { "code": null, "e": 29101, "s": 29061, "text": "cols – The columns to use for unnesting" }, { "code": null, "e": 29110, "s": 29101, "text": "Example:" }, { "code": null, "e": 29112, "s": 29110, "text": "R" }, { "code": "library(tidyr) # creating a data framedata_frame <- data.frame(col1 = sample(letters[6:10]), col2 = 1:5 ) print (\"Original DataFrame\")print (data_frame) # unnesting data frameunnest_df <- unnest( data_frame , cols = c('col1','col2'))str(unnest_df)", "e": 29412, "s": 29112, "text": null }, { "code": null, "e": 29419, "s": 29412, "text": "Output" }, { "code": null, "e": 29633, "s": 29419, "text": "[1] \"Original DataFrame\" \ncol1 col2 \n1 i 1 \n2 j 2 \n3 g 3 \n4 h 4 \n5 f 5\ntibble [5 × 2] (S3: tbl_df/tbl/data.frame) \n$ col1: chr [1:5] \"i\" \"j\" \"g\" \"h\" ... \n$ col2: int [1:5] 1 2 3 4 5" }, { "code": null, "e": 29640, "s": 29633, "text": "Picked" }, { "code": null, "e": 29661, "s": 29640, "text": "R DataFrame-Programs" }, { "code": null, "e": 29673, "s": 29661, "text": "R-DataFrame" }, { "code": null, "e": 29684, "s": 29673, "text": "R Language" }, { "code": null, "e": 29695, "s": 29684, "text": "R Programs" }, { "code": null, "e": 29793, "s": 29695, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29845, "s": 29793, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 29880, "s": 29845, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 29918, "s": 29880, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 29976, "s": 29918, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30019, "s": 29976, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30077, "s": 30019, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30120, "s": 30077, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30169, "s": 30120, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30219, "s": 30169, "text": "How to filter R dataframe by multiple conditions?" } ]
Python - Append Multiple elements in set - GeeksforGeeks
02 Feb, 2021 In this article given a set and list of elements, the task is to write a Python program to append multiple elements in set at once. Example: Input : test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 10] Output : {1, 2, 4, 5, 6, 7, 9, 10} Explanation : All elements are updated and reordered. (5 at 3rd position). Input : test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 8] Output : {1, 2, 4, 5, 6, 7, 8, 9, 10} Explanation : All elements are updated and reordered. (8 at 7th position). Method #1 : Using update() In this, we use in built update() to get all the elements in list aligned with the existing set. Python3 # Python3 code to demonstrate working of# Append Multiple elements in set# Using update() # initializing settest_set = {6, 4, 2, 7, 9} # printing original setprint("The original set is : " + str(test_set)) # initializing adding elementsup_ele = [1, 5, 10] # update() appends element in set# internally reorderstest_set.update(up_ele) # printing resultprint("Set after adding elements : " + str(test_set)) Output: The original set is : {2, 4, 6, 7, 9} Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10} Method #2 : Using | operator ( Pipe operator ) The pipe operator internally calls union(), which can be used to perform task of updating set with newer elements. Python3 # Python3 code to demonstrate working of# Append Multiple elements in set# Using | operator ( Pipe operator ) # initializing settest_set = {6, 4, 2, 7, 9} # printing original setprint("The original set is : " + str(test_set)) # initializing adding elementsup_ele = [1, 5, 10] # | performing task of updatingtest_set |= set(up_ele) # printing resultprint("Set after adding elements : " + str(test_set)) Output: The original set is : {2, 4, 6, 7, 9} Set after adding elements : {1, 2, 4, 5, 6, 7, 9, 10} Python set-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n02 Feb, 2021" }, { "code": null, "e": 25669, "s": 25537, "text": "In this article given a set and list of elements, the task is to write a Python program to append multiple elements in set at once." }, { "code": null, "e": 25678, "s": 25669, "text": "Example:" }, { "code": null, "e": 25734, "s": 25678, "text": "Input : test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 10]" }, { "code": null, "e": 25769, "s": 25734, "text": "Output : {1, 2, 4, 5, 6, 7, 9, 10}" }, { "code": null, "e": 25844, "s": 25769, "text": "Explanation : All elements are updated and reordered. (5 at 3rd position)." }, { "code": null, "e": 25899, "s": 25844, "text": "Input : test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 8]" }, { "code": null, "e": 25937, "s": 25899, "text": "Output : {1, 2, 4, 5, 6, 7, 8, 9, 10}" }, { "code": null, "e": 26012, "s": 25937, "text": "Explanation : All elements are updated and reordered. (8 at 7th position)." }, { "code": null, "e": 26039, "s": 26012, "text": "Method #1 : Using update()" }, { "code": null, "e": 26136, "s": 26039, "text": "In this, we use in built update() to get all the elements in list aligned with the existing set." }, { "code": null, "e": 26144, "s": 26136, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Append Multiple elements in set# Using update() # initializing settest_set = {6, 4, 2, 7, 9} # printing original setprint(\"The original set is : \" + str(test_set)) # initializing adding elementsup_ele = [1, 5, 10] # update() appends element in set# internally reorderstest_set.update(up_ele) # printing resultprint(\"Set after adding elements : \" + str(test_set))", "e": 26554, "s": 26144, "text": null }, { "code": null, "e": 26562, "s": 26554, "text": "Output:" }, { "code": null, "e": 26654, "s": 26562, "text": "The original set is : {2, 4, 6, 7, 9}\nSet after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}" }, { "code": null, "e": 26701, "s": 26654, "text": "Method #2 : Using | operator ( Pipe operator )" }, { "code": null, "e": 26817, "s": 26701, "text": "The pipe operator internally calls union(), which can be used to perform task of updating set with newer elements. " }, { "code": null, "e": 26825, "s": 26817, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Append Multiple elements in set# Using | operator ( Pipe operator ) # initializing settest_set = {6, 4, 2, 7, 9} # printing original setprint(\"The original set is : \" + str(test_set)) # initializing adding elementsup_ele = [1, 5, 10] # | performing task of updatingtest_set |= set(up_ele) # printing resultprint(\"Set after adding elements : \" + str(test_set))", "e": 27232, "s": 26825, "text": null }, { "code": null, "e": 27240, "s": 27232, "text": "Output:" }, { "code": null, "e": 27332, "s": 27240, "text": "The original set is : {2, 4, 6, 7, 9}\nSet after adding elements : {1, 2, 4, 5, 6, 7, 9, 10}" }, { "code": null, "e": 27352, "s": 27332, "text": "Python set-programs" }, { "code": null, "e": 27359, "s": 27352, "text": "Python" }, { "code": null, "e": 27375, "s": 27359, "text": "Python Programs" }, { "code": null, "e": 27473, "s": 27375, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27505, "s": 27473, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27547, "s": 27505, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27589, "s": 27547, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27645, "s": 27589, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27672, "s": 27645, "text": "Python Classes and Objects" }, { "code": null, "e": 27694, "s": 27672, "text": "Defaultdict in Python" }, { "code": null, "e": 27733, "s": 27694, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27779, "s": 27733, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27817, "s": 27779, "text": "Python | Convert a list to dictionary" } ]
Rotten Oranges | Practice | GeeksforGeeks
Given a grid of dimension nxm where each cell in the grid can have values 0, 1 or 2 which has the following meaning: 0 : Empty cell 1 : Cells have fresh oranges 2 : Cells have rotten oranges We have to determine what is the minimum time required to rot all oranges. A rotten orange at index [i,j] can rot other fresh orange at indexes [i-1,j], [i+1,j], [i,j-1], [i,j+1] (up, down, left and right) in unit time. Example 1: Input: grid = {{0,1,2},{0,1,2},{2,1,1}} Output: 1 Explanation: The grid is- 0 1 2 0 1 2 2 1 1 Oranges at positions (0,2), (1,2), (2,0) will rot oranges at (0,1), (1,1), (2,2) and (2,1) in unit time. Example 2: Input: grid = {{2,2,0,1}} Output: -1 Explanation: The grid is- 2 2 0 1 Oranges at (0,0) and (0,1) can't rot orange at (0,3). Your Task: You don't need to read or print anything, Your task is to complete the function orangesRotting() which takes grid as input parameter and returns the minimum time to rot all the fresh oranges. If not possible returns -1. Expected Time Complexity: O(n*m) Expected Auxiliary Space: O(n) Constraints: 1 ≤ n, m ≤ 500 -1 danish_nitdgp1 week ago C++ Approach without using delimiter. bool isvalid(int i, int j,vector<vector<int>>& grid) { int R = grid.size(); int C = grid[0].size(); return (i >= 0 && j >= 0 && i < R && j < C) && grid[i][j] == 1; } struct Oranges{ int timeframe; int x; int y; }; bool checkIfFreshOrangeIsRemaining(vector<vector<int>>& grid) { int R = grid.size(); int C = grid[0].size(); for (int i=0; i<R; i++) for (int j=0; j<C; j++) if (grid[i][j] == 1) return true; return false; } int orangesRotting(vector<vector<int>>& grid) { int R = grid.size(); int C = grid[0].size(); int ans = 0; queue<Oranges> q; Oranges temp; for (int i=0; i<R; i++) { for (int j=0; j<C; j++) { if (grid[i][j] == 2) { temp.x = i; temp.y = j; temp.timeframe = 0; q.push(temp); } } } while(!q.empty()){ temp = q.front(); if(isvalid(temp.x+1,temp.y,grid)){ grid[temp.x+1][temp.y] = 2; temp.x++; temp.timeframe++; q.push(temp); temp.x--; temp.timeframe--; } if(isvalid(temp.x-1,temp.y,grid)){ grid[temp.x-1][temp.y] = 2; temp.x--; temp.timeframe++; q.push(temp); temp.x++; temp.timeframe--; } if(isvalid(temp.x,temp.y+1,grid)){ grid[temp.x][temp.y+1] = 2; temp.y++; temp.timeframe++; q.push(temp); temp.y--; temp.timeframe--; } if(isvalid(temp.x,temp.y-1,grid)){ grid[temp.x][temp.y-1] = 2; temp.y--; temp.timeframe++; q.push(temp); temp.y++; temp.timeframe--; } Oranges last; last = q.front(); ans = last.timeframe; q.pop(); } if(checkIfFreshOrangeIsRemaining(grid)) return -1; return ans; } 0 sanjeevranjan12091 week ago Easy python solution by BFS def orangesRotting(self, grid): def rotting(rotten): temp = [] for i,j in rotten: if i>0 and grid[i-1][j] == 1: temp.append((i-1,j)) grid[i-1][j]=2 if i<len(grid)-1 and grid[i+1][j] == 1: temp.append((i+1,j)) grid[i+1][j]=2 if j>0 and grid[i][j-1] == 1: temp.append((i,j-1)) grid[i][j-1]=2 if j<len(grid[0])-1 and grid[i][j+1] == 1: temp.append((i,j+1)) grid[i][j+1]=2 return temp q=deque() count = 0 for row in range(len(grid)): for col in range(len(grid[row])): if grid[row][col] == 2: q.append((row,col)) while q: q = rotting(q) if len(q) == 0: break count+=1 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == 1: return -1 return count +2 gaurabhkumarjha271020012 weeks ago // c++ if (g.empty()) return -1; int n= g.size(); int m= g[0].size(); queue <pair <int,int>> q; int freshorange=0; for (int i=0; i< n; i++){ for (int j=0; j< m; j++){ if (g[i][j] == 1) freshorange++; else if (g[i][j] == 2) q.push({i,j}); } } int time=0; vector <pair <int,int> > v= {{0, 1}, {1, 0}, {-1, 0}, {0, -1}}; while (freshorange!=0 and !q.empty()){ int sz= q.size(); for (int i=0; i< sz; i++){ int row= q.front().first; int col= q.front().second; q.pop(); for (auto d: v){ int rowx= row+d.first; int coly= col+d.second; if (rowx >= 0 and rowx < n and coly >=0 and coly < m and g[rowx][coly] == 1){ g[rowx][coly]= 2; freshorange--; q.push({rowx,coly}); } } } time ++; } return freshorange==0?time:-1; 0 19bcs13143 weeks ago class Pair{ int i, j; Pair(int i,int j){ this.i=i; this.j=j; } } class Solution { //Function to find minimum time required to rot all oranges. public int orangesRotting(int[][] g) { // Code here int r=g.length,c=g[0].length; Queue<Pair> q= new ArrayDeque<>(); for(int i=0;i<g.length;i++){ for(int j=0;j<g[0].length;j++){ if(g[i][j]==2){ q.add(new Pair(i,j)); } } } int time=0; while(q.size()!=0){ boolean flag=false; int siz=q.size(); for(int k=0;k<siz;k++){ Pair temp=q.remove(); int i=temp.i,j=temp.j; for(int z=0;z<4;z++){ if(isValid(g,r,c,i+dx[z],j+dy[z])){ flag=true; q.add(new Pair(i+dx[z],j+dy[z])); g[i+dx[z]][j+dy[z]]=2; } } } if(flag==true){ time++; } } for(int i=0;i<g.length;i++){ for(int j=0;j<g[0].length;j++){ if(g[i][j]==1){ return -1; } } } return time; } int[] dx={0,0,1,-1}; int[] dy={1,-1,0,0}; public boolean isValid(int[][] g,int r,int c,int x,int y){ if(x>=r || x<0 || y<0 || y>=c || g[x][y]==2 || g[x][y]==0){ return false; } return true; } } +1 amarrajsmart1973 weeks ago C++ Solution. int orangesRotting(vector<vector<int>>& grid) { // Code here queue<pair<int,int>> q; int r=grid.size(); int c=grid[0].size(); int i,j; int count=0; for( i=0;i<r;i++) { for( j=0;j<c;j++) { if(grid[i][j]==2) q.push({i,j}); } } q.push({-1,-1}); while(!q.empty()) { i=q.front().first; j=q.front().second; if(i==-1&&j==-1&&q.size()==1) { q.pop(); break; } else if(i==-1&&j==-1&&q.size()>1) { count++; q.pop(); q.push({-1,-1}); } else { if(i-1>=0&&grid[i-1][j]==1) { grid[i-1][j]=2; q.push({i-1,j}); } if(i+1<r&&grid[i+1][j]==1) { grid[i+1][j]=2; q.push({i+1,j}); } if(j-1>=0&&grid[i][j-1]==1) { grid[i][j-1]=2; q.push({i,j-1}); } if(j+1<c&&grid[i][j+1]==1) { grid[i][j+1]=2; q.push({i,j+1}); } q.pop(); } } for( i=0;i<r;i++) { for( j=0;j<c;j++) { if(grid[i][j]==1) return -1; } } return count; } 0 hamidnourashraf4 weeks ago Time: 1.4/14.9 class Solution: def is_valid_index(self, i, j, n, m): if i < 0 or i >= n or j < 0 or j >= m: return False return True def update_grid(self, grid, n, m, aux_dict): cnt = 0 aux_set = set() for i in range(n): for j in range(m): if grid[i][j] == 1: if self.is_valid_index(i-1, j, n, m) and grid[i-1][j] == 2 and ((i-1, j) not in aux_set): aux_set.add((i,j)) grid[i][j] = 2 cnt += 1 del aux_dict[(i,j)] elif self.is_valid_index(i+1, j, n, m) and grid[i+1][j] == 2 and ((i+1, j) not in aux_set): aux_set.add((i,j)) grid[i][j] = 2 cnt += 1 del aux_dict[(i,j)] elif self.is_valid_index(i, j-1, n, m) and grid[i][j-1] == 2 and ((i, j-1) not in aux_set): aux_set.add((i,j)) grid[i][j] = 2 cnt += 1 del aux_dict[(i,j)] elif self.is_valid_index(i, j+1, n, m) and grid[i][j+1] == 2 and ((i, j+1) not in aux_set): aux_set.add((i,j)) grid[i][j] = 2 cnt += 1 del aux_dict[(i,j)] return cnt def orangesRotting(self, grid): aux_dict = dict() n = len(grid) m = len(grid[0]) for i in range(n): for j in range(m): if grid[i][j] == 1: aux_dict[(i,j)]= 1 time = 0 while len(aux_dict) > 0: time += 1 changes = self.update_grid(grid, n, m, aux_dict) if changes == 0 and len(aux_dict) > 0: return -1 return time 0 krishnachitlangi2 This comment was deleted. 0 milindprajapatmst191 month ago HELP!! Why segmentation fault?? I tried to ran it in my local machine via visual studio community, which uses microsoft c++. Also, I tried at some random online ide, which uses gcc compiler. On both the platforms, it is working fine!! int dx[] = {-1, 0, 1, 0}; int dy[] = { 0, -1, 0, 1}; class Node { public: int i, j, dist; Node(int i, int j, int dist) { this->i = i; this->j = j; this->dist = dist; } }; class Solution { public: // multi-source bfs int orangesRotting(vector<vector<int>>& grid) { int n = grid.size(), m = grid[0].size(), cnt = 0, dist = 0; queue<Node> q; for (int i = 0; i < n; i++) { for (int j = 0; j < m; j++) { if (grid[i][j] == 1) cnt++; else if (grid[i][j] == 2) q.push(Node(i, j, dist)); } } while (!q.empty()) { int sz = q.size(); while(sz--) { Node& p = q.front(); q.pop(); for (int k = 0; k < 4; k++) { int i = p.i + dx[k], j = p.j + dy[k]; if (0 <= i && i < n && 0 <= j && j < m && grid[i][j] == 1) { cnt--; q.push(Node(i, j, p.dist + 1)); grid[i][j] = 2; } } dist = max(dist, p.dist); } } return (cnt == 0) ? dist : -1; } }; 0 rahulgupta067891 month ago int orangesRotting(vector<vector<int>>& grid) { // Code here queue<pair<int,int>> q; int r = grid.size(); int c = grid[0].size(); int level = 0,rtemp,ctemp,size; for(int i=0;i<r;++i){ for(int j=0;j<c;++j){ if(grid[i][j]==2) q.push({i,j}); } } while(!q.empty()){ ++level; size=q.size(); while(size-->0){ rtemp = q.front().first; ctemp = q.front().second; q.pop(); if(rtemp>0 && grid[rtemp-1][ctemp]==1){ q.push({rtemp-1,ctemp}); grid[rtemp-1][ctemp]=2; } if(ctemp>0 && grid[rtemp][ctemp-1]==1){ q.push({rtemp,ctemp-1}); grid[rtemp][ctemp-1]=2; } if(rtemp<r-1 && grid[rtemp+1][ctemp]==1){ q.push({rtemp+1,ctemp}); grid[rtemp+1][ctemp]=2; } if(ctemp<c-1 && grid[rtemp][ctemp+1]==1){ q.push({rtemp,ctemp+1}); grid[rtemp][ctemp+1]=2; } } } for(int i=0;i<r;++i){ for(int j=0;j<c;++j){ if(grid[i][j]==1){ return -1; } } } return max(0,level-1); } -1 sanketgharatkar1231 month ago // CPP best solution -- 0.5 sec int orangesRotting(vector<vector<int>>& grid) { int m=grid.size(); int n=grid[0].size(); queue<pair<int,int>> qu; for(int i=0;i<grid.size();i++) { for(int j=0;j<grid[0].size();j++) { if(grid[i][j]==2) { qu.push({i,j}); } } } int count=0; while(qu.empty()==false) { int siz=qu.size(); while(siz--) { pair<int,int> p1=qu.front(); qu.pop(); if(p1.first+1<m and grid[p1.first+1][p1.second]==1) { grid[p1.first+1][p1.second]=2; qu.push({p1.first+1,p1.second}); } if(p1.first-1>=0 and grid[p1.first-1][p1.second]==1) { grid[p1.first-1][p1.second]=2; qu.push({p1.first-1,p1.second}); } if(p1.second+1<n and grid[p1.first][p1.second+1]==1) { grid[p1.first][p1.second+1]=2; qu.push({p1.first,p1.second+1}); } if(p1.second-1>=0 and grid[p1.first][p1.second-1]==1) { grid[p1.first][p1.second-1]=2; qu.push({p1.first,p1.second-1}); } } if(qu.size()==0) { if(count==0) { count=-1; } break; } count++; } for(int i=0;i<grid.size();i++) { for(int j=0;j<grid[0].size();j++) { if(grid[i][j]==1) { return -1; } } } return count; } 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": 432, "s": 238, "text": "Given a grid of dimension nxm where each cell in the grid can have values 0, 1 or 2 which has the following meaning:\n0 : Empty cell \n1 : Cells have fresh oranges \n2 : Cells have rotten oranges " }, { "code": null, "e": 655, "s": 432, "text": "We have to determine what is the minimum time required to rot all oranges. A rotten orange at index [i,j] can rot other fresh orange at indexes [i-1,j], [i+1,j], [i,j-1], [i,j+1] (up, down, left and right) in unit time. \n " }, { "code": null, "e": 666, "s": 655, "text": "Example 1:" }, { "code": null, "e": 867, "s": 666, "text": "Input: grid = {{0,1,2},{0,1,2},{2,1,1}}\nOutput: 1\nExplanation: The grid is-\n0 1 2\n0 1 2\n2 1 1\nOranges at positions (0,2), (1,2), (2,0)\nwill rot oranges at (0,1), (1,1), (2,2) and \n(2,1) in unit time.\n" }, { "code": null, "e": 878, "s": 867, "text": "Example 2:" }, { "code": null, "e": 1004, "s": 878, "text": "Input: grid = {{2,2,0,1}}\nOutput: -1\nExplanation: The grid is-\n2 2 0 1\nOranges at (0,0) and (0,1) can't rot orange at\n(0,3).\n" }, { "code": null, "e": 1239, "s": 1006, "text": "Your Task:\nYou don't need to read or print anything, Your task is to complete the function orangesRotting() which takes grid as input parameter and returns the minimum time to rot all the fresh oranges. If not possible returns -1.\n " }, { "code": null, "e": 1305, "s": 1239, "text": "Expected Time Complexity: O(n*m)\nExpected Auxiliary Space: O(n)\n " }, { "code": null, "e": 1333, "s": 1305, "text": "Constraints:\n1 ≤ n, m ≤ 500" }, { "code": null, "e": 1336, "s": 1333, "text": "-1" }, { "code": null, "e": 1360, "s": 1336, "text": "danish_nitdgp1 week ago" }, { "code": null, "e": 3414, "s": 1360, "text": "C++ Approach without using delimiter. bool isvalid(int i, int j,vector<vector<int>>& grid) { int R = grid.size(); int C = grid[0].size(); return (i >= 0 && j >= 0 && i < R && j < C) && grid[i][j] == 1; } struct Oranges{ int timeframe; int x; int y; }; bool checkIfFreshOrangeIsRemaining(vector<vector<int>>& grid) { int R = grid.size(); int C = grid[0].size(); for (int i=0; i<R; i++) for (int j=0; j<C; j++) if (grid[i][j] == 1) return true; return false; } int orangesRotting(vector<vector<int>>& grid) { int R = grid.size(); int C = grid[0].size(); int ans = 0; queue<Oranges> q; Oranges temp; for (int i=0; i<R; i++) { for (int j=0; j<C; j++) { if (grid[i][j] == 2) { temp.x = i; temp.y = j; temp.timeframe = 0; q.push(temp); } } } while(!q.empty()){ temp = q.front(); if(isvalid(temp.x+1,temp.y,grid)){ grid[temp.x+1][temp.y] = 2; temp.x++; temp.timeframe++; q.push(temp); temp.x--; temp.timeframe--; } if(isvalid(temp.x-1,temp.y,grid)){ grid[temp.x-1][temp.y] = 2; temp.x--; temp.timeframe++; q.push(temp); temp.x++; temp.timeframe--; } if(isvalid(temp.x,temp.y+1,grid)){ grid[temp.x][temp.y+1] = 2; temp.y++; temp.timeframe++; q.push(temp); temp.y--; temp.timeframe--; } if(isvalid(temp.x,temp.y-1,grid)){ grid[temp.x][temp.y-1] = 2; temp.y--; temp.timeframe++; q.push(temp); temp.y++; temp.timeframe--; } Oranges last; last = q.front(); ans = last.timeframe; q.pop(); } if(checkIfFreshOrangeIsRemaining(grid)) return -1; return ans; }" }, { "code": null, "e": 3416, "s": 3414, "text": "0" }, { "code": null, "e": 3444, "s": 3416, "text": "sanjeevranjan12091 week ago" }, { "code": null, "e": 3472, "s": 3444, "text": "Easy python solution by BFS" }, { "code": null, "e": 4538, "s": 3474, "text": "def orangesRotting(self, grid): def rotting(rotten): temp = [] for i,j in rotten: if i>0 and grid[i-1][j] == 1: temp.append((i-1,j)) grid[i-1][j]=2 if i<len(grid)-1 and grid[i+1][j] == 1: temp.append((i+1,j)) grid[i+1][j]=2 if j>0 and grid[i][j-1] == 1: temp.append((i,j-1)) grid[i][j-1]=2 if j<len(grid[0])-1 and grid[i][j+1] == 1: temp.append((i,j+1)) grid[i][j+1]=2 return temp q=deque() count = 0 for row in range(len(grid)): for col in range(len(grid[row])): if grid[row][col] == 2: q.append((row,col)) while q: q = rotting(q) if len(q) == 0: break count+=1 for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == 1: return -1 return count" }, { "code": null, "e": 4541, "s": 4538, "text": "+2" }, { "code": null, "e": 4576, "s": 4541, "text": "gaurabhkumarjha271020012 weeks ago" }, { "code": null, "e": 5907, "s": 4576, "text": "// c++\n if (g.empty()) return -1;\n \n int n= g.size();\n int m= g[0].size();\n \n queue <pair <int,int>> q; \n int freshorange=0;\n for (int i=0; i< n; i++){\n \n for (int j=0; j< m; j++){\n \n if (g[i][j] == 1) freshorange++;\n else if (g[i][j] == 2) q.push({i,j});\n }\n }\n int time=0;\n vector <pair <int,int> > v= {{0, 1}, {1, 0}, {-1, 0}, {0, -1}};\n while (freshorange!=0 and !q.empty()){\n \n int sz= q.size();\n for (int i=0; i< sz; i++){\n \n int row= q.front().first;\n int col= q.front().second;\n q.pop();\n \n for (auto d: v){\n \n int rowx= row+d.first;\n int coly= col+d.second; \n if (rowx >= 0 and rowx < n and coly >=0 and coly < m and g[rowx][coly] == 1){\n \n g[rowx][coly]= 2;\n freshorange--;\n q.push({rowx,coly});\n }\n }\n \n }\n time ++;\n }\n \n return freshorange==0?time:-1;" }, { "code": null, "e": 5909, "s": 5907, "text": "0" }, { "code": null, "e": 5930, "s": 5909, "text": "19bcs13143 weeks ago" }, { "code": null, "e": 7737, "s": 5930, "text": "class Pair{\n int i, j;\n Pair(int i,int j){\n this.i=i;\n this.j=j;\n }\n}\nclass Solution\n{\n //Function to find minimum time required to rot all oranges. \n public int orangesRotting(int[][] g)\n {\n // Code here\n int r=g.length,c=g[0].length;\n Queue<Pair> q= new ArrayDeque<>();\n \n \n for(int i=0;i<g.length;i++){\n for(int j=0;j<g[0].length;j++){\n if(g[i][j]==2){\n q.add(new Pair(i,j));\n \n }\n }\n }\n \n int time=0;\n while(q.size()!=0){\n \n boolean flag=false;\n int siz=q.size();\n \n for(int k=0;k<siz;k++){\n Pair temp=q.remove();\n int i=temp.i,j=temp.j;\n \n for(int z=0;z<4;z++){\n \n if(isValid(g,r,c,i+dx[z],j+dy[z])){\n flag=true;\n q.add(new Pair(i+dx[z],j+dy[z]));\n g[i+dx[z]][j+dy[z]]=2;\n \n }\n }\n \n }\n \n if(flag==true){\n time++;\n }\n \n }\n \n for(int i=0;i<g.length;i++){\n for(int j=0;j<g[0].length;j++){\n if(g[i][j]==1){\n return -1;\n \n }\n }\n }\n return time;\n }\n \n \n int[] dx={0,0,1,-1};\n int[] dy={1,-1,0,0};\n \n public boolean isValid(int[][] g,int r,int c,int x,int y){\n if(x>=r || x<0 || y<0 || y>=c || g[x][y]==2 || g[x][y]==0){\n return false;\n }\n return true;\n }\n \n \n \n}" }, { "code": null, "e": 7740, "s": 7737, "text": "+1" }, { "code": null, "e": 7767, "s": 7740, "text": "amarrajsmart1973 weeks ago" }, { "code": null, "e": 7781, "s": 7767, "text": "C++ Solution." }, { "code": null, "e": 9374, "s": 7783, "text": " int orangesRotting(vector<vector<int>>& grid) { // Code here queue<pair<int,int>> q; int r=grid.size(); int c=grid[0].size(); int i,j; int count=0; for( i=0;i<r;i++) { for( j=0;j<c;j++) { if(grid[i][j]==2) q.push({i,j}); } } q.push({-1,-1}); while(!q.empty()) { i=q.front().first; j=q.front().second; if(i==-1&&j==-1&&q.size()==1) { q.pop(); break; } else if(i==-1&&j==-1&&q.size()>1) { count++; q.pop(); q.push({-1,-1}); } else { if(i-1>=0&&grid[i-1][j]==1) { grid[i-1][j]=2; q.push({i-1,j}); } if(i+1<r&&grid[i+1][j]==1) { grid[i+1][j]=2; q.push({i+1,j}); } if(j-1>=0&&grid[i][j-1]==1) { grid[i][j-1]=2; q.push({i,j-1}); } if(j+1<c&&grid[i][j+1]==1) { grid[i][j+1]=2; q.push({i,j+1}); } q.pop(); } } for( i=0;i<r;i++) { for( j=0;j<c;j++) { if(grid[i][j]==1) return -1; } } return count; }" }, { "code": null, "e": 9376, "s": 9374, "text": "0" }, { "code": null, "e": 9403, "s": 9376, "text": "hamidnourashraf4 weeks ago" }, { "code": null, "e": 9418, "s": 9403, "text": "Time: 1.4/14.9" }, { "code": null, "e": 11328, "s": 9420, "text": "class Solution:\n def is_valid_index(self, i, j, n, m):\n if i < 0 or i >= n or j < 0 or j >= m:\n return False\n return True\n def update_grid(self, grid, n, m, aux_dict):\n cnt = 0\n aux_set = set()\n for i in range(n):\n for j in range(m):\n if grid[i][j] == 1:\n if self.is_valid_index(i-1, j, n, m) and grid[i-1][j] == 2 and ((i-1, j) not in aux_set):\n aux_set.add((i,j))\n grid[i][j] = 2\n cnt += 1\n del aux_dict[(i,j)]\n elif self.is_valid_index(i+1, j, n, m) and grid[i+1][j] == 2 and ((i+1, j) not in aux_set):\n aux_set.add((i,j))\n grid[i][j] = 2\n cnt += 1\n del aux_dict[(i,j)]\n elif self.is_valid_index(i, j-1, n, m) and grid[i][j-1] == 2 and ((i, j-1) not in aux_set):\n aux_set.add((i,j))\n grid[i][j] = 2\n cnt += 1\n del aux_dict[(i,j)]\n elif self.is_valid_index(i, j+1, n, m) and grid[i][j+1] == 2 and ((i, j+1) not in aux_set):\n aux_set.add((i,j))\n grid[i][j] = 2\n cnt += 1\n del aux_dict[(i,j)]\n return cnt\n\n def orangesRotting(self, grid):\n aux_dict = dict()\n n = len(grid)\n m = len(grid[0])\n for i in range(n):\n for j in range(m):\n if grid[i][j] == 1:\n aux_dict[(i,j)]= 1\n time = 0\n while len(aux_dict) > 0:\n time += 1\n changes = self.update_grid(grid, n, m, aux_dict)\n if changes == 0 and len(aux_dict) > 0:\n return -1\n return time\n" }, { "code": null, "e": 11330, "s": 11328, "text": "0" }, { "code": null, "e": 11348, "s": 11330, "text": "krishnachitlangi2" }, { "code": null, "e": 11374, "s": 11348, "text": "This comment was deleted." }, { "code": null, "e": 11376, "s": 11374, "text": "0" }, { "code": null, "e": 11407, "s": 11376, "text": "milindprajapatmst191 month ago" }, { "code": null, "e": 12908, "s": 11407, "text": "HELP!! Why segmentation fault?? I tried to ran it in my local machine via visual studio community, which uses microsoft c++. Also, I tried at some random online ide, which uses gcc compiler. On both the platforms, it is working fine!!\n\nint dx[] = {-1, 0, 1, 0};\nint dy[] = { 0, -1, 0, 1};\n\nclass Node {\n public:\n int i, j, dist;\n Node(int i, int j, int dist) {\n this->i = i; this->j = j; this->dist = dist;\n }\n};\n\nclass Solution {\n public:\n // multi-source bfs \n int orangesRotting(vector<vector<int>>& grid) {\n int n = grid.size(), m = grid[0].size(), cnt = 0, dist = 0;\n queue<Node> q;\n for (int i = 0; i < n; i++) {\n for (int j = 0; j < m; j++) {\n if (grid[i][j] == 1)\n cnt++;\n else if (grid[i][j] == 2)\n q.push(Node(i, j, dist));\n }\n }\n while (!q.empty()) {\n int sz = q.size();\n while(sz--) {\n Node& p = q.front();\n q.pop();\n for (int k = 0; k < 4; k++) {\n int i = p.i + dx[k], j = p.j + dy[k];\n if (0 <= i && i < n && 0 <= j && j < m && grid[i][j] == 1) {\n cnt--;\n q.push(Node(i, j, p.dist + 1));\n grid[i][j] = 2;\n }\n }\n dist = max(dist, p.dist);\n }\n }\n return (cnt == 0) ? dist : -1;\n }\n};" }, { "code": null, "e": 12910, "s": 12908, "text": "0" }, { "code": null, "e": 12937, "s": 12910, "text": "rahulgupta067891 month ago" }, { "code": null, "e": 14327, "s": 12937, "text": "int orangesRotting(vector<vector<int>>& grid) { // Code here queue<pair<int,int>> q; int r = grid.size(); int c = grid[0].size(); int level = 0,rtemp,ctemp,size; for(int i=0;i<r;++i){ for(int j=0;j<c;++j){ if(grid[i][j]==2) q.push({i,j}); } } while(!q.empty()){ ++level; size=q.size(); while(size-->0){ rtemp = q.front().first; ctemp = q.front().second; q.pop(); if(rtemp>0 && grid[rtemp-1][ctemp]==1){ q.push({rtemp-1,ctemp}); grid[rtemp-1][ctemp]=2; } if(ctemp>0 && grid[rtemp][ctemp-1]==1){ q.push({rtemp,ctemp-1}); grid[rtemp][ctemp-1]=2; } if(rtemp<r-1 && grid[rtemp+1][ctemp]==1){ q.push({rtemp+1,ctemp}); grid[rtemp+1][ctemp]=2; } if(ctemp<c-1 && grid[rtemp][ctemp+1]==1){ q.push({rtemp,ctemp+1}); grid[rtemp][ctemp+1]=2; } } } for(int i=0;i<r;++i){ for(int j=0;j<c;++j){ if(grid[i][j]==1){ return -1; } } } return max(0,level-1); }" }, { "code": null, "e": 14330, "s": 14327, "text": "-1" }, { "code": null, "e": 14360, "s": 14330, "text": "sanketgharatkar1231 month ago" }, { "code": null, "e": 16490, "s": 14360, "text": "// CPP best solution -- 0.5 sec\n \n \n int orangesRotting(vector<vector<int>>& grid) {\n int m=grid.size();\n int n=grid[0].size();\n queue<pair<int,int>> qu;\n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[0].size();j++)\n {\n if(grid[i][j]==2)\n {\n qu.push({i,j});\n }\n }\n }\n int count=0;\n while(qu.empty()==false)\n {\n int siz=qu.size();\n \n while(siz--)\n {\n pair<int,int> p1=qu.front();\n qu.pop();\n \n if(p1.first+1<m and grid[p1.first+1][p1.second]==1)\n {\n grid[p1.first+1][p1.second]=2;\n qu.push({p1.first+1,p1.second});\n }\n if(p1.first-1>=0 and grid[p1.first-1][p1.second]==1)\n {\n grid[p1.first-1][p1.second]=2;\n qu.push({p1.first-1,p1.second});\n }\n if(p1.second+1<n and grid[p1.first][p1.second+1]==1)\n {\n grid[p1.first][p1.second+1]=2;\n qu.push({p1.first,p1.second+1});\n }\n if(p1.second-1>=0 and grid[p1.first][p1.second-1]==1)\n {\n grid[p1.first][p1.second-1]=2;\n qu.push({p1.first,p1.second-1});\n } \n }\n \n if(qu.size()==0)\n {\n if(count==0)\n { count=-1;\n \n }\n \n break;\n }\n \n \n count++;\n }\n \n \n for(int i=0;i<grid.size();i++)\n {\n for(int j=0;j<grid[0].size();j++)\n {\n if(grid[i][j]==1)\n {\n return -1;\n }\n }\n } \n \n \n \n \n return count;\n \n \n }" }, { "code": null, "e": 16636, "s": 16490, "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": 16672, "s": 16636, "text": " Login to access your submissions. " }, { "code": null, "e": 16682, "s": 16672, "text": "\nProblem\n" }, { "code": null, "e": 16692, "s": 16682, "text": "\nContest\n" }, { "code": null, "e": 16755, "s": 16692, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 16903, "s": 16755, "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": 17111, "s": 16903, "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": 17217, "s": 17111, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
keras.fit() and keras.fit_generator() - GeeksforGeeks
25 Jun, 2020 keras.fit() and keras.fit_generator() in Python are two separate deep learning libraries which can be used to train our machine learning and deep learning models. Both these functions can do the same task, but when to use which function is the main question. Keras.fit() Syntax: fit(object, x = NULL, y = NULL, batch_size = NULL, epochs = 10, verbose = getOption("keras.fit_verbose", default = 1), callbacks = NULL, view_metrics = getOption("keras.view_metrics", default = "auto"), validation_split = 0, validation_data = NULL, shuffle = TRUE, class_weight = NULL, sample_weight = NULL, initial_epoch = 0, steps_per_epoch = NULL, validation_steps = NULL, ...) Understanding few important arguments: -> object : the model to train. -> X : our training data. Can be Vector, array or matrix -> Y : our training labels. Can be Vector, array or matrix -> Batch_size : it can take any integer value or NULL and by default, it will be set to 32. It specifies no. of samples per gradient. -> Epochs : an integer and number of epochs we want to train our model for. -> Verbose : specifies verbosity mode(0 = silent, 1= progress bar, 2 = one line per epoch). -> Shuffle : whether we want to shuffle our training data before each epoch. -> steps_per_epoch : it specifies the total number of steps taken before one epoch has finished and started the next epoch. By default it values is set to NULL. How to use Keras fit: model.fit(Xtrain, Ytrain, batch_size = 32, epochs = 100) Here we are first feeding the training data(Xtrain) and training labels(Ytrain). We then use Keras to allow our model to train for 100 epochs on a batch_size of 32. When we call the .fit() function it makes assumptions: The entire training set can fit into the Random Access Memory (RAM) of the computer. Calling the model. fit method for a second time is not going to reinitialize our already trained weights, which means we can actually make consecutive calls to fit if we want to and then manage it properly. There is no need for using the Keras generators(i.e no data argumentation) Raw data is itself used for training our network and our raw data will only fit into the memory. The Keras.fit_generator(): Syntax: fit_generator(object, generator, steps_per_epoch, epochs = 1, verbose = getOption("keras.fit_verbose", default = 1), callbacks = NULL, view_metrics = getOption("keras.view_metrics", default = "auto"), validation_data = NULL, validation_steps = NULL, class_weight = NULL, max_queue_size = 10, workers = 1, initial_epoch = 0) Understanding few important arguments: -> object : the Keras Object model. -> generator : a generator whose output must be a list of the form: - (inputs, targets) - (input, targets, sample_weights) a single output of the generator makes a single batch and hence all arrays in the list must be having the length equal to the size of the batch. The generator is expected to loop over its data infinite no. of times, it should never return or exit. -> steps_per_epoch : it specifies the total number of steps taken from the generator as soon as one epoch is finished and next epoch has started. We can calculate the value of steps_per_epoch as the total number of samples in your dataset divided by the batch size. -> Epochs : an integer and number of epochs we want to train our model for. -> Verbose : specifies verbosity mode(0 = silent, 1= progress bar, 2 = one line per epoch). -> callbacks : a list of callback functions applied during the training of our model. -> validation_data can be either: - an inputs and targets list - a generator - an inputs, targets, and sample_weights list which can be used to evaluate the loss and metrics for any model after any epoch has ended. -> validation_steps :only if the validation_data is a generator then only this argument can be used. It specifies the total number of steps taken from the generator before it is stopped at every epoch and its value is calculated as the total number of validation data points in your dataset divided by the validation batch size. How to use Keras fit_generator: # performing data argumentation by training image generator dataAugmentaion = ImageDataGenerator(rotation_range = 30, zoom_range = 0.20, fill_mode = "nearest", shear_range = 0.20, horizontal_flip = True, width_shift_range = 0.1, height_shift_range = 0.1) # training the model model.fit_generator(dataAugmentaion.flow(trainX, trainY, batch_size = 32), validation_data = (testX, testY), steps_per_epoch = len(trainX) // 32, epochs = 10) Here we are training our network for 10 epochs along with the default batch size of 32. For small and less complex datasets it is recommended to use keras.fit function whereas while dealing with real-world datasets it is not that simple because real-world datasets are huge in size and are much harder to fit into the computer memory.It is more challenging to deal with those datasets and an important step to deal with those datasets is to perform data augmentation to avoid the overfitting of a model and also to increase the ability of our model to generalize. Data Augmentation is a method of artificially creating a new dataset for training from the existing training dataset to improve the performance of deep learning neural networks with the amount of data available. It is a form of regularization which makes our model generalize better than before.Here we have used a Keras ImageDataGenerator object to apply data augmentation for randomly translating, resizing, rotating, etc the images. Each new batch of our data is randomly adjusting according to the parameters supplied to ImageDataGenerator. When we call the .fit_generator() function it makes assumptions: Keras is first calling the generator function(dataAugmentaion) Generator function(dataAugmentaion) provides a batch_size of 32 to our .fit_generator() function. our .fit_generator() function first accepts a batch of the dataset, then performs backpropagation on it, and then updates the weights in our model. For the number of epochs specified(10 in our case) the process is repeated. Summary :So, we have learned the difference between Keras.fit and Keras.fit_generator functions used to train a deep learning neural network.fit is used when the entire training dataset can fit into the memory and no data augmentation is applied..fit_generator is used when either we have a huge dataset to fit into our memory or when data augmentation needs to be applied. parammirani nidhi_biet 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 Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Create a Pandas DataFrame from Lists Reading and Writing to text files in Python
[ { "code": null, "e": 24708, "s": 24680, "text": "\n25 Jun, 2020" }, { "code": null, "e": 24967, "s": 24708, "text": "keras.fit() and keras.fit_generator() in Python are two separate deep learning libraries which can be used to train our machine learning and deep learning models. Both these functions can do the same task, but when to use which function is the main question." }, { "code": null, "e": 24979, "s": 24967, "text": "Keras.fit()" }, { "code": null, "e": 24987, "s": 24979, "text": "Syntax:" }, { "code": null, "e": 25380, "s": 24987, "text": "fit(object, x = NULL, y = NULL, batch_size = NULL, epochs = 10,\n verbose = getOption(\"keras.fit_verbose\", default = 1),\n callbacks = NULL, view_metrics = getOption(\"keras.view_metrics\",\n default = \"auto\"), validation_split = 0, validation_data = NULL,\n shuffle = TRUE, class_weight = NULL, sample_weight = NULL,\n initial_epoch = 0, steps_per_epoch = NULL, validation_steps = NULL,\n ...)" }, { "code": null, "e": 25419, "s": 25380, "text": "Understanding few important arguments:" }, { "code": null, "e": 26158, "s": 25419, "text": " \n-> object : the model to train. \n-> X : our training data. Can be Vector, array or matrix \n-> Y : our training labels. Can be Vector, array or matrix \n-> Batch_size : it can take any integer value or NULL and by default, it will\nbe set to 32. It specifies no. of samples per gradient. \n-> Epochs : an integer and number of epochs we want to train our model for. \n-> Verbose : specifies verbosity mode(0 = silent, 1= progress bar, 2 = one\nline per epoch). \n-> Shuffle : whether we want to shuffle our training data before each epoch. \n-> steps_per_epoch : it specifies the total number of steps taken before\none epoch has finished and started the next epoch. By default it values is set to NULL.\n" }, { "code": null, "e": 26180, "s": 26158, "text": "How to use Keras fit:" }, { "code": null, "e": 26237, "s": 26180, "text": "model.fit(Xtrain, Ytrain, batch_size = 32, epochs = 100)" }, { "code": null, "e": 26402, "s": 26237, "text": "Here we are first feeding the training data(Xtrain) and training labels(Ytrain). We then use Keras to allow our model to train for 100 epochs on a batch_size of 32." }, { "code": null, "e": 26457, "s": 26402, "text": "When we call the .fit() function it makes assumptions:" }, { "code": null, "e": 26542, "s": 26457, "text": "The entire training set can fit into the Random Access Memory (RAM) of the computer." }, { "code": null, "e": 26749, "s": 26542, "text": "Calling the model. fit method for a second time is not going to reinitialize our already trained weights, which means we can actually make consecutive calls to fit if we want to and then manage it properly." }, { "code": null, "e": 26824, "s": 26749, "text": "There is no need for using the Keras generators(i.e no data argumentation)" }, { "code": null, "e": 26921, "s": 26824, "text": "Raw data is itself used for training our network and our raw data will only fit into the memory." }, { "code": null, "e": 26948, "s": 26921, "text": "The Keras.fit_generator():" }, { "code": null, "e": 26956, "s": 26948, "text": "Syntax:" }, { "code": null, "e": 27290, "s": 26956, "text": "fit_generator(object, generator, steps_per_epoch, epochs = 1,\n verbose = getOption(\"keras.fit_verbose\", default = 1),\n callbacks = NULL, view_metrics = getOption(\"keras.view_metrics\",\n default = \"auto\"), validation_data = NULL, validation_steps = NULL,\n class_weight = NULL, max_queue_size = 10, workers = 1,\n initial_epoch = 0)" }, { "code": null, "e": 27329, "s": 27290, "text": "Understanding few important arguments:" }, { "code": null, "e": 28950, "s": 27329, "text": " \n-> object : the Keras Object model.\n-> generator : a generator whose output must be a list of the form:\n - (inputs, targets) \n - (input, targets, sample_weights)\na single output of the generator makes a single batch and hence all arrays in the list \nmust be having the length equal to the size of the batch. The generator is expected \nto loop over its data infinite no. of times, it should never return or exit.\n-> steps_per_epoch : it specifies the total number of steps taken from the generator\n as soon as one epoch is finished and next epoch has started. We can calculate the value\nof steps_per_epoch as the total number of samples in your dataset divided by the batch size.\n-> Epochs : an integer and number of epochs we want to train our model for.\n-> Verbose : specifies verbosity mode(0 = silent, 1= progress bar, 2 = one line per epoch).\n-> callbacks : a list of callback functions applied during the training of our model.\n-> validation_data can be either:\n - an inputs and targets list\n - a generator\n - an inputs, targets, and sample_weights list which can be used to evaluate\n the loss and metrics for any model after any epoch has ended.\n-> validation_steps :only if the validation_data is a generator then only this argument\ncan be used. It specifies the total number of steps taken from the generator before it is \nstopped at every epoch and its value is calculated as the total number of validation data points\nin your dataset divided by the validation batch size.\n" }, { "code": null, "e": 28982, "s": 28950, "text": "How to use Keras fit_generator:" }, { "code": null, "e": 29423, "s": 28982, "text": "# performing data argumentation by training image generator\ndataAugmentaion = ImageDataGenerator(rotation_range = 30, zoom_range = 0.20, \nfill_mode = \"nearest\", shear_range = 0.20, horizontal_flip = True, \nwidth_shift_range = 0.1, height_shift_range = 0.1)\n\n# training the model\nmodel.fit_generator(dataAugmentaion.flow(trainX, trainY, batch_size = 32),\n validation_data = (testX, testY), steps_per_epoch = len(trainX) // 32,\n epochs = 10)\n" }, { "code": null, "e": 29511, "s": 29423, "text": "Here we are training our network for 10 epochs along with the default batch size of 32." }, { "code": null, "e": 29987, "s": 29511, "text": "For small and less complex datasets it is recommended to use keras.fit function whereas while dealing with real-world datasets it is not that simple because real-world datasets are huge in size and are much harder to fit into the computer memory.It is more challenging to deal with those datasets and an important step to deal with those datasets is to perform data augmentation to avoid the overfitting of a model and also to increase the ability of our model to generalize." }, { "code": null, "e": 30532, "s": 29987, "text": "Data Augmentation is a method of artificially creating a new dataset for training from the existing training dataset to improve the performance of deep learning neural networks with the amount of data available. It is a form of regularization which makes our model generalize better than before.Here we have used a Keras ImageDataGenerator object to apply data augmentation for randomly translating, resizing, rotating, etc the images. Each new batch of our data is randomly adjusting according to the parameters supplied to ImageDataGenerator." }, { "code": null, "e": 30597, "s": 30532, "text": "When we call the .fit_generator() function it makes assumptions:" }, { "code": null, "e": 30660, "s": 30597, "text": "Keras is first calling the generator function(dataAugmentaion)" }, { "code": null, "e": 30758, "s": 30660, "text": "Generator function(dataAugmentaion) provides a batch_size of 32 to our .fit_generator() function." }, { "code": null, "e": 30906, "s": 30758, "text": "our .fit_generator() function first accepts a batch of the dataset, then performs backpropagation on it, and then updates the weights in our model." }, { "code": null, "e": 30982, "s": 30906, "text": "For the number of epochs specified(10 in our case) the process is repeated." }, { "code": null, "e": 31356, "s": 30982, "text": "Summary :So, we have learned the difference between Keras.fit and Keras.fit_generator functions used to train a deep learning neural network.fit is used when the entire training dataset can fit into the memory and no data augmentation is applied..fit_generator is used when either we have a huge dataset to fit into our memory or when data augmentation needs to be applied." }, { "code": null, "e": 31368, "s": 31356, "text": "parammirani" }, { "code": null, "e": 31379, "s": 31368, "text": "nidhi_biet" }, { "code": null, "e": 31386, "s": 31379, "text": "Python" }, { "code": null, "e": 31484, "s": 31386, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31502, "s": 31484, "text": "Python Dictionary" }, { "code": null, "e": 31537, "s": 31502, "text": "Read a file line by line in Python" }, { "code": null, "e": 31559, "s": 31537, "text": "Enumerate() in Python" }, { "code": null, "e": 31591, "s": 31559, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31621, "s": 31591, "text": "Iterate over a list in Python" }, { "code": null, "e": 31663, "s": 31621, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 31689, "s": 31663, "text": "Python String | replace()" }, { "code": null, "e": 31732, "s": 31689, "text": "Python program to convert a list to string" }, { "code": null, "e": 31769, "s": 31732, "text": "Create a Pandas DataFrame from Lists" } ]
How to convert the content of the file into uppercase or lowercase?
To convert the content of the file into the upper case, you need to use the method ToUpper() and to convert into lower case, you need to use ToLower() method. (Get-Content D:\Temp\PowerShellaliases.txt).ToUpper() PS C:\WINDOWS\system32> (Get-Content D:\Temp\PowerShellaliases.txt).ToUpper() COMMANDTYPE NAME VERSION SOURCE ----------- ---- ------- ------ ALIAS % -> FOREACH-OBJECT ALIAS ? -> WHERE-OBJECT ALIAS AC -> ADD-CONTENT ALIAS ASNP -> ADD-PSSNAPIN ALIAS CAT -> GET-CONTENT ALIAS CD -> SET-LOCATION ALIAS CFS -> CONVERTFROM-STRING 3.1.0.0 MICROSOFT.POWERSHELL.UTILITY ALIAS CHDIR -> SET-LOCATION ALIAS CLC -> CLEAR-CONTENT ALIAS CLEAR -> CLEAR-HOST ALIAS CLHY -> CLEAR-HISTORY ALIAS CLI -> CLEAR-ITEM ALIAS CLP -> CLEAR-ITEMPROPERTY ALIAS CLS -> CLEAR-HOST (Get-Content D:\Temp\PowerShellaliases.txt).ToLower() PS C:\WINDOWS\system32> (Get-Content D:\Temp\PowerShellaliases.txt).ToLower() commandtype name version ----------- ---- ------- alias % -> foreach-object alias ? -> where-object alias ac -> add-content alias asnp -> add-pssnapin alias cat -> get-content alias cd -> set-location alias cfs -> convertfrom-string 3.1.0.0 alias chdir -> set-location alias clc -> clear-content alias clear -> clear-host alias clhy -> clear-history alias cli -> clear-item alias clp -> clear-itemproperty alias cls -> clear-host alias clv -> clear-variable alias cnsn -> connect-pssession alias compare -> compare-object alias copy -> copy-item alias cp -> copy-item alias cpi -> copy-item alias cpp -> copy-itemproperty alias curl -> invoke-webrequest alias cvpa -> convert-path alias dbp -> disable-psbreakpoint alias del -> remove-item alias diff -> compare-object alias dir -> get-childitem
[ { "code": null, "e": 1221, "s": 1062, "text": "To convert the content of the file into the upper case, you need to use the method ToUpper() and to convert into lower case, you need to use ToLower() method." }, { "code": null, "e": 1275, "s": 1221, "text": "(Get-Content D:\\Temp\\PowerShellaliases.txt).ToUpper()" }, { "code": null, "e": 2100, "s": 1275, "text": "PS C:\\WINDOWS\\system32> (Get-Content D:\\Temp\\PowerShellaliases.txt).ToUpper()\nCOMMANDTYPE NAME VERSION SOURCE\n----------- ---- ------- ------\nALIAS % -> FOREACH-OBJECT\nALIAS ? -> WHERE-OBJECT\nALIAS AC -> ADD-CONTENT\nALIAS ASNP -> ADD-PSSNAPIN\nALIAS CAT -> GET-CONTENT\nALIAS CD -> SET-LOCATION\nALIAS CFS -> CONVERTFROM-STRING 3.1.0.0 MICROSOFT.POWERSHELL.UTILITY\nALIAS CHDIR -> SET-LOCATION\nALIAS CLC -> CLEAR-CONTENT\nALIAS CLEAR -> CLEAR-HOST\nALIAS CLHY -> CLEAR-HISTORY\nALIAS CLI -> CLEAR-ITEM\nALIAS CLP -> CLEAR-ITEMPROPERTY\nALIAS CLS -> CLEAR-HOST" }, { "code": null, "e": 2154, "s": 2100, "text": "(Get-Content D:\\Temp\\PowerShellaliases.txt).ToLower()" }, { "code": null, "e": 3423, "s": 2154, "text": "PS C:\\WINDOWS\\system32> (Get-Content D:\\Temp\\PowerShellaliases.txt).ToLower()\ncommandtype name version\n----------- ---- -------\nalias % -> foreach-object\nalias ? -> where-object\nalias ac -> add-content\nalias asnp -> add-pssnapin\nalias cat -> get-content\nalias cd -> set-location\nalias cfs -> convertfrom-string 3.1.0.0\nalias chdir -> set-location\nalias clc -> clear-content\nalias clear -> clear-host\nalias clhy -> clear-history\nalias cli -> clear-item\nalias clp -> clear-itemproperty\nalias cls -> clear-host\nalias clv -> clear-variable\nalias cnsn -> connect-pssession\nalias compare -> compare-object\nalias copy -> copy-item\nalias cp -> copy-item\nalias cpi -> copy-item\nalias cpp -> copy-itemproperty\nalias curl -> invoke-webrequest\nalias cvpa -> convert-path\nalias dbp -> disable-psbreakpoint\nalias del -> remove-item\nalias diff -> compare-object\nalias dir -> get-childitem" } ]
Strictly increasing sequence JavaScript
Given a sequence of integers as an array, we have to determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element from the array. For example − For sequence = [1, 3, 2, 1], the output should be function(sequence) = false. There is no one element in this array that can be removed in order to get a strictly increasing sequence. For sequence = [1, 3, 2], the output should be function(sequence) = true. You can remove 3 from the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get the strictly increasing sequence [1, 3]. It is a mathematical term that represents an arrangement of numbers where every succeeding number is greater than its preceding number. Other than this there exists increasing sequence where the succeeding element is greater than or equal to the preceding element. The same logic applies for decreasing sequence and strictly decreasing sequence. We will loop over the array checking whether the succeeding element is greater than preceding element or not. If it’s greater, then it’s fine with us, but if it is not greater (remember it has to be greater and not greater or equal because we want to form a strictly increasing sequence.) we will keep a count of unwantedElements and increase it by 1 every time this happens. If during iteration, the count exceeds 1, we return false then and there otherwise if we go through the whole with unwantedElements <= 1, we return true. Therefore, let’s write the code for this function − const isStrictlyIncreasing = (arr) => { let unwantedElements = 0; for(let i = 0; i < arr.length - 1; i++){ if(arr[i] >= arr[i+1]){ unwantedElements++; if(unwantedElements > 1){ return false; }; }; }; return true; }; console.log(isStrictlyIncreasing([1, 3, 2, 1])); console.log(isStrictlyIncreasing([1, 3, 2])); The output in the console will be − false true
[ { "code": null, "e": 1242, "s": 1062, "text": "Given a sequence of integers as an array, we have to determine whether it is possible to obtain\na strictly increasing sequence by removing no more than one element from the array." }, { "code": null, "e": 1256, "s": 1242, "text": "For example −" }, { "code": null, "e": 1440, "s": 1256, "text": "For sequence = [1, 3, 2, 1], the output should be function(sequence) = false. There is no one\nelement in this array that can be removed in order to get a strictly increasing sequence." }, { "code": null, "e": 1672, "s": 1440, "text": "For sequence = [1, 3, 2], the output should be function(sequence) = true. You can remove 3\nfrom the array to get the strictly increasing sequence [1, 2]. Alternately, you can remove 2 to get\nthe strictly increasing sequence [1, 3]." }, { "code": null, "e": 1937, "s": 1672, "text": "It is a mathematical term that represents an arrangement of numbers where every succeeding\nnumber is greater than its preceding number. Other than this there exists increasing sequence\nwhere the succeeding element is greater than or equal to the preceding element." }, { "code": null, "e": 2018, "s": 1937, "text": "The same logic applies for decreasing sequence and strictly decreasing sequence." }, { "code": null, "e": 2394, "s": 2018, "text": "We will loop over the array checking whether the succeeding element is greater than preceding\nelement or not. If it’s greater, then it’s fine with us, but if it is not greater (remember it has to be\ngreater and not greater or equal because we want to form a strictly increasing sequence.) we\nwill keep a count of unwantedElements and increase it by 1 every time this happens." }, { "code": null, "e": 2548, "s": 2394, "text": "If during iteration, the count exceeds 1, we return false then and there otherwise if we go\nthrough the whole with unwantedElements <= 1, we return true." }, { "code": null, "e": 2600, "s": 2548, "text": "Therefore, let’s write the code for this function −" }, { "code": null, "e": 2974, "s": 2600, "text": "const isStrictlyIncreasing = (arr) => {\n let unwantedElements = 0;\n for(let i = 0; i < arr.length - 1; i++){\n if(arr[i] >= arr[i+1]){\n unwantedElements++;\n if(unwantedElements > 1){\n return false;\n };\n };\n };\n return true;\n};\nconsole.log(isStrictlyIncreasing([1, 3, 2, 1]));\nconsole.log(isStrictlyIncreasing([1, 3, 2]));" }, { "code": null, "e": 3010, "s": 2974, "text": "The output in the console will be −" }, { "code": null, "e": 3021, "s": 3010, "text": "false\ntrue" } ]
jQuery - Basics
Before we start learning about jQuery Syntax, let's have a quick look on basic concepts of Javascript. This is because, jQuery is a framework built using JavaScript capabilities. So while doing in jQuery, you can use all the functions and other capabilities available in JavaScript. So let's quickly have a look at the most basic concepts but the most frequently used in jQuery. A string in JavaScript (jQuery) is an immutable object that contains none, one or many characters. Following are the valid examples of a JavaScript String − "This is JavaScript String" 'This is JavaScript String' 'This is "really" a JavaScript String' "This is 'really' a JavaScript String" Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable, just as strings. Following are the valid examples of a JavaScript Numbers − 5350 120.27 0.26 A boolean in JavaScript (jQuery) can be either true or false. If a number is zero, it defaults to false. If an empty string defaults to false. Following are the valid examples of a JavaScript Boolean − true // true false // false 0 // false 1 // true "" // false "hello" // true JavaScript (jQuery) supports Object concept very well. You can create an object using the object literal as follows − var emp = { name: "Zara", age: 10 }; You can write and read properties of an object using the dot notation as follows − // Getting object properties emp.name // ==> Zara emp.age // ==> 10 // Setting object properties emp.name = "Daisy" // <== Daisy emp.age = 20 // <== 20 You can define arrays using the array literal as follows − var x = []; var y = [1, 2, 3, 4, 5]; An array has a length property that is useful for iteration − var x = [1, 2, 3, 4, 5]; for (var i = 0; i < x.length; i++) { // Do something with x[i] } A function in JavaScript (jQuery) can be either named or anonymous. A named function can be defined using function keyword as follows − function named(){ // do some stuff here } An anonymous function can be defined in similar way as a normal function but it would not have any name. A anonymous function can be assigned to a variable or passed to a method as shown below. var handler = function (){ // do some stuff here } JQuery makes a use of anonymous functions very frequently as follows − $(document).ready(function(){ // do some stuff here }); JavaScript (jQuery) variable arguments is a kind of array which has length property. Following example explains it very well − function func(x){ console.log(typeof x, arguments.length); } func(); //==> "undefined", 0 func(1); //==> "number", 1 func("1", "2", "3"); //==> "string", 3 The arguments object also has a callee property, which refers to the function you're inside of. For example − function func() { return arguments.callee; } func(); // ==> func JavaScript (jQuery) famous keyword this always refers to the current context. Within a function this context can change, depending on how the function is called − $(document).ready(function() { // this refers to window.document }); $("div").click(function() { // this refers to a div DOM element }); You can specify the context for a function call using the function-built-in methods call() and apply() methods. The difference between them is how they pass arguments. Call passes all arguments through as arguments to the function, while apply accepts an array as the arguments. function scope() { console.log(this, arguments.length); } scope() // window, 0 scope.call("foobar", [1,2]); //==> "foobar", 1 scope.apply("foobar", [1,2]); //==> "foobar", 2 The scope of a variable is the region of your program in which it is defined. JavaScript (jQuery) variable will have only two scopes. Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code. Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function. Within the body of a function, a local variable takes precedence over a global variable with the same name − var myVar = "global"; // ==> Declare a global variable function ( ) { var myVar = "local"; // ==> Declare a local variable document.write(myVar); // ==> local } A callback is a plain JavaScript (jQuery) function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered. jQuery's event system uses such callbacks everywhere for example − $("body").click(function(event) { console.log("clicked: " + event.target); }); Most callbacks provide arguments and a context. In the event-handler example, the callback is called with one argument, an Event. Some callbacks are required to return something, others make that return value optional. To prevent a form submission, a submit event handler can return false as follows − $("#myform").submit(function() { return false; }); JavaScript (jQuery) closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope. Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them − function create() { var counter = 0; return { increment: function() { counter++; }, print: function() { console.log(counter); } } } var c = create(); c.increment(); c.print(); // ==> 1 This pattern allows you to create objects with methods that operate on data that isn't visible to the outside world. It should be noted that data hiding is the very basis of object-oriented programming. A proxy is an object that can be used to control access to another object. It implements the same interface as this other object and passes on any method invocations to it. This other object is often called the real subject. A proxy can be instantiated in place of this real subject and allow it to be accessed remotely. We can saves jQuery's setArray method in a closure and overwrites it as follows − (function() { // log all calls to setArray var proxied = jQuery.fn.setArray; jQuery.fn.setArray = function() { console.log(this, arguments); return proxied.apply(this, arguments); }; })(); The above wraps its code in a function to hide the proxied variable. The proxy then logs all calls to the method and delegates the call to the original method. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method. JavaScript comes along with a useful set of built-in functions. These methods can be used to manipulate Strings, Numbers and Dates. Following are important JavaScript functions − charAt() Returns the character at the specified index. concat() Combines the text of two strings and returns a new string. forEach() Calls a function for each element in the array. indexOf() Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found. length() Returns the length of the string. pop() Removes the last element from an array and returns that element. push() Adds one or more elements to the end of an array and returns the new length of the array. reverse() Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first. sort() Sorts the elements of an array. substr() Returns the characters in a string beginning at the specified location through the specified number of characters. toLowerCase() Returns the calling string value converted to lower case. toString() Returns the string representation of the number's value. toUpperCase() Returns the calling string value converted to uppercase. The Document Object Model is a tree structure of various elements of HTML as follows. Try to click the icon to run the following jQuery code − <html> <head> <title>The DOM Example</title> </head> <body> <div> <p>This is a paragraph.</p> <p>This is second paragraph.</p> <p>This is third paragraph.</p> </div> </body> </html> Following are the important points about the above tree structure − The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>. The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>. The <head> and <body> elements are not only descendants, but children of <html>, as well. The <head> and <body> elements are not only descendants, but children of <html>, as well. Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent. Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent. The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements. The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements. While learning jQuery concepts, it will be helpful to have understanding on DOM, if you are not aware of DOM then I would suggest to go through our simple tutorial on DOM Tutorial. 27 Lectures 1 hours Mahesh Kumar 27 Lectures 1.5 hours Pratik Singh 72 Lectures 4.5 hours Frahaan Hussain 60 Lectures 9 hours Eduonix Learning Solutions 17 Lectures 2 hours Sandip Bhattacharya 12 Lectures 53 mins Laurence Svekis Print Add Notes Bookmark this page
[ { "code": null, "e": 2701, "s": 2322, "text": "Before we start learning about jQuery Syntax, let's have a quick look on basic concepts of Javascript. This is because, jQuery is a framework built using JavaScript capabilities. So while doing in jQuery, you can use all the functions and other capabilities available in JavaScript. So let's quickly have a look at the most basic concepts but the most frequently used in jQuery." }, { "code": null, "e": 2858, "s": 2701, "text": "A string in JavaScript (jQuery) is an immutable object that contains none, one or many characters. Following are the valid examples of a JavaScript String −" }, { "code": null, "e": 2993, "s": 2858, "text": "\"This is JavaScript String\"\n'This is JavaScript String'\n'This is \"really\" a JavaScript String'\n\"This is 'really' a JavaScript String\"\n" }, { "code": null, "e": 3163, "s": 2993, "text": "Numbers in JavaScript are double-precision 64-bit format IEEE 754 values. They are immutable, just as strings. Following are the valid examples of a JavaScript Numbers −" }, { "code": null, "e": 3181, "s": 3163, "text": "5350\n120.27\n0.26\n" }, { "code": null, "e": 3324, "s": 3181, "text": "A boolean in JavaScript (jQuery) can be either true or false. If a number is zero, it defaults to false. If an empty string defaults to false." }, { "code": null, "e": 3383, "s": 3324, "text": "Following are the valid examples of a JavaScript Boolean −" }, { "code": null, "e": 3495, "s": 3383, "text": "true // true\nfalse // false\n0 // false\n1 // true\n\"\" // false\n\"hello\" // true\n" }, { "code": null, "e": 3613, "s": 3495, "text": "JavaScript (jQuery) supports Object concept very well. You can create an object using the object literal as follows −" }, { "code": null, "e": 3657, "s": 3613, "text": "var emp = {\n name: \"Zara\",\n age: 10\n};\n" }, { "code": null, "e": 3740, "s": 3657, "text": "You can write and read properties of an object using the dot notation as follows −" }, { "code": null, "e": 3905, "s": 3740, "text": "// Getting object properties\nemp.name // ==> Zara\nemp.age // ==> 10\n\n// Setting object properties\nemp.name = \"Daisy\" // <== Daisy\nemp.age = 20 // <== 20\n" }, { "code": null, "e": 3964, "s": 3905, "text": "You can define arrays using the array literal as follows −" }, { "code": null, "e": 4002, "s": 3964, "text": "var x = [];\nvar y = [1, 2, 3, 4, 5];\n" }, { "code": null, "e": 4064, "s": 4002, "text": "An array has a length property that is useful for iteration −" }, { "code": null, "e": 4159, "s": 4064, "text": "var x = [1, 2, 3, 4, 5];\n\nfor (var i = 0; i < x.length; i++) {\n // Do something with x[i]\n}\n" }, { "code": null, "e": 4295, "s": 4159, "text": "A function in JavaScript (jQuery) can be either named or anonymous. A named function can be defined using function keyword as follows −" }, { "code": null, "e": 4341, "s": 4295, "text": "function named(){\n // do some stuff here\n}\n" }, { "code": null, "e": 4446, "s": 4341, "text": "An anonymous function can be defined in similar way as a normal function but it would not have any name." }, { "code": null, "e": 4535, "s": 4446, "text": "A anonymous function can be assigned to a variable or passed to a method as shown below." }, { "code": null, "e": 4590, "s": 4535, "text": "var handler = function (){\n // do some stuff here\n}\n" }, { "code": null, "e": 4661, "s": 4590, "text": "JQuery makes a use of anonymous functions very frequently as follows −" }, { "code": null, "e": 4721, "s": 4661, "text": "$(document).ready(function(){\n // do some stuff here\n});\n" }, { "code": null, "e": 4848, "s": 4721, "text": "JavaScript (jQuery) variable arguments is a kind of array which has length property. Following example explains it very well −" }, { "code": null, "e": 5040, "s": 4848, "text": "function func(x){\n console.log(typeof x, arguments.length);\n}\n\nfunc(); //==> \"undefined\", 0\nfunc(1); //==> \"number\", 1\nfunc(\"1\", \"2\", \"3\"); //==> \"string\", 3\n" }, { "code": null, "e": 5150, "s": 5040, "text": "The arguments object also has a callee property, which refers to the function you're inside of. For example −" }, { "code": null, "e": 5235, "s": 5150, "text": "function func() {\n return arguments.callee;\n}\n\nfunc(); // ==> func\n" }, { "code": null, "e": 5399, "s": 5235, "text": "JavaScript (jQuery) famous keyword this always refers to the current context. Within a function this context can change, depending on how the function is called −" }, { "code": null, "e": 5544, "s": 5399, "text": "$(document).ready(function() {\n // this refers to window.document\n});\n\n$(\"div\").click(function() {\n // this refers to a div DOM element\n});\n" }, { "code": null, "e": 5656, "s": 5544, "text": "You can specify the context for a function call using the function-built-in methods call() and apply() methods." }, { "code": null, "e": 5823, "s": 5656, "text": "The difference between them is how they pass arguments. Call passes all arguments through as arguments to the function, while apply accepts an array as the arguments." }, { "code": null, "e": 6003, "s": 5823, "text": "function scope() {\n console.log(this, arguments.length);\n}\n\nscope() // window, 0\nscope.call(\"foobar\", [1,2]); //==> \"foobar\", 1\nscope.apply(\"foobar\", [1,2]); //==> \"foobar\", 2\n" }, { "code": null, "e": 6137, "s": 6003, "text": "The scope of a variable is the region of your program in which it is defined. JavaScript (jQuery) variable will have only two scopes." }, { "code": null, "e": 6253, "s": 6137, "text": "Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code." }, { "code": null, "e": 6369, "s": 6253, "text": "Global Variables − A global variable has global scope which means it is defined everywhere in your JavaScript code." }, { "code": null, "e": 6519, "s": 6369, "text": "Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function." }, { "code": null, "e": 6669, "s": 6519, "text": "Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function." }, { "code": null, "e": 6778, "s": 6669, "text": "Within the body of a function, a local variable takes precedence over a global variable with the same name −" }, { "code": null, "e": 6953, "s": 6778, "text": "var myVar = \"global\"; // ==> Declare a global variable\n\nfunction ( ) {\n var myVar = \"local\"; // ==> Declare a local variable\n document.write(myVar); // ==> local\n}\n" }, { "code": null, "e": 7161, "s": 6953, "text": "A callback is a plain JavaScript (jQuery) function passed to some method as an argument or option. Some callbacks are just events, called to give the user a chance to react when a certain state is triggered." }, { "code": null, "e": 7228, "s": 7161, "text": "jQuery's event system uses such callbacks everywhere for example −" }, { "code": null, "e": 7311, "s": 7228, "text": "$(\"body\").click(function(event) {\n console.log(\"clicked: \" + event.target);\n});\n" }, { "code": null, "e": 7441, "s": 7311, "text": "Most callbacks provide arguments and a context. In the event-handler example, the callback is called with one argument, an Event." }, { "code": null, "e": 7613, "s": 7441, "text": "Some callbacks are required to return something, others make that return value optional. To prevent a form submission, a submit event handler can return false as follows −" }, { "code": null, "e": 7668, "s": 7613, "text": "$(\"#myform\").submit(function() {\n return false;\n});\n" }, { "code": null, "e": 7813, "s": 7668, "text": "JavaScript (jQuery) closures are created whenever a variable that is defined outside the current scope is accessed from within some inner scope." }, { "code": null, "e": 7950, "s": 7813, "text": "Following example shows how the variable counter is visible within the create, increment, and print functions, but not outside of them −" }, { "code": null, "e": 8191, "s": 7950, "text": "function create() {\n var counter = 0;\n\n return {\n increment: function() {\n counter++;\n },\n\t print: function() {\n console.log(counter);\n }\n }\n}\n\nvar c = create();\nc.increment();\nc.print(); // ==> 1\n" }, { "code": null, "e": 8394, "s": 8191, "text": "This pattern allows you to create objects with methods that operate on data that isn't visible to the outside world. It should be noted that data hiding is the very basis of object-oriented programming." }, { "code": null, "e": 8619, "s": 8394, "text": "A proxy is an object that can be used to control access to another object. It implements the same interface as this other object and passes on any method invocations to it. This other object is often called the real subject." }, { "code": null, "e": 8797, "s": 8619, "text": "A proxy can be instantiated in place of this real subject and allow it to be accessed remotely. We can saves jQuery's setArray method in a closure and overwrites it as follows −" }, { "code": null, "e": 9013, "s": 8797, "text": "(function() {\n // log all calls to setArray\n var proxied = jQuery.fn.setArray;\n\n jQuery.fn.setArray = function() {\n console.log(this, arguments);\n return proxied.apply(this, arguments);\n };\n\n})();\n" }, { "code": null, "e": 9313, "s": 9013, "text": "The above wraps its code in a function to hide the proxied variable. The proxy then logs all calls to the method and delegates the call to the original method. Using apply(this, arguments) guarantees that the caller won't be able to notice the difference between the original and the proxied method." }, { "code": null, "e": 9445, "s": 9313, "text": "JavaScript comes along with a useful set of built-in functions. These methods can be used to manipulate Strings, Numbers and Dates." }, { "code": null, "e": 9492, "s": 9445, "text": "Following are important JavaScript functions −" }, { "code": null, "e": 9501, "s": 9492, "text": "charAt()" }, { "code": null, "e": 9547, "s": 9501, "text": "Returns the character at the specified index." }, { "code": null, "e": 9556, "s": 9547, "text": "concat()" }, { "code": null, "e": 9615, "s": 9556, "text": "Combines the text of two strings and returns a new string." }, { "code": null, "e": 9625, "s": 9615, "text": "forEach()" }, { "code": null, "e": 9673, "s": 9625, "text": "Calls a function for each element in the array." }, { "code": null, "e": 9683, "s": 9673, "text": "indexOf()" }, { "code": null, "e": 9802, "s": 9683, "text": "Returns the index within the calling String object of the first occurrence of the specified value, or -1 if not found." }, { "code": null, "e": 9811, "s": 9802, "text": "length()" }, { "code": null, "e": 9845, "s": 9811, "text": "Returns the length of the string." }, { "code": null, "e": 9851, "s": 9845, "text": "pop()" }, { "code": null, "e": 9916, "s": 9851, "text": "Removes the last element from an array and returns that element." }, { "code": null, "e": 9923, "s": 9916, "text": "push()" }, { "code": null, "e": 10013, "s": 9923, "text": "Adds one or more elements to the end of an array and returns the new length of the array." }, { "code": null, "e": 10023, "s": 10013, "text": "reverse()" }, { "code": null, "e": 10133, "s": 10023, "text": "Reverses the order of the elements of an array -- the first becomes the last, and the last becomes the first." }, { "code": null, "e": 10140, "s": 10133, "text": "sort()" }, { "code": null, "e": 10172, "s": 10140, "text": "Sorts the elements of an array." }, { "code": null, "e": 10181, "s": 10172, "text": "substr()" }, { "code": null, "e": 10296, "s": 10181, "text": "Returns the characters in a string beginning at the specified location through the specified number of characters." }, { "code": null, "e": 10310, "s": 10296, "text": "toLowerCase()" }, { "code": null, "e": 10368, "s": 10310, "text": "Returns the calling string value converted to lower case." }, { "code": null, "e": 10379, "s": 10368, "text": "toString()" }, { "code": null, "e": 10436, "s": 10379, "text": "Returns the string representation of the number's value." }, { "code": null, "e": 10450, "s": 10436, "text": "toUpperCase()" }, { "code": null, "e": 10507, "s": 10450, "text": "Returns the calling string value converted to uppercase." }, { "code": null, "e": 10652, "s": 10507, "text": "The Document Object Model is a tree structure of various elements of HTML as follows. Try to click the icon to run the following jQuery code −" }, { "code": null, "e": 10893, "s": 10652, "text": "<html>\n <head>\n <title>The DOM Example</title>\n </head>\n\n <body>\n <div>\n <p>This is a paragraph.</p>\n <p>This is second paragraph.</p>\n <p>This is third paragraph.</p>\n </div>\n </body>\n</html>\n" }, { "code": null, "e": 10961, "s": 10893, "text": "Following are the important points about the above tree structure −" }, { "code": null, "e": 11081, "s": 10961, "text": "The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>." }, { "code": null, "e": 11201, "s": 11081, "text": "The <html> is the ancestor of all the other elements; in other words, all the other elements are descendants of <html>." }, { "code": null, "e": 11291, "s": 11201, "text": "The <head> and <body> elements are not only descendants, but children of <html>, as well." }, { "code": null, "e": 11381, "s": 11291, "text": "The <head> and <body> elements are not only descendants, but children of <html>, as well." }, { "code": null, "e": 11476, "s": 11381, "text": "Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent." }, { "code": null, "e": 11571, "s": 11476, "text": "Likewise, in addition to being the ancestor of <head> and <body>, <html> is also their parent." }, { "code": null, "e": 11704, "s": 11571, "text": "The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements." }, { "code": null, "e": 11837, "s": 11704, "text": "The <p> elements are children (and descendants) of <div>, descendants of <body> and <html>, and siblings of each other <p> elements." }, { "code": null, "e": 12018, "s": 11837, "text": "While learning jQuery concepts, it will be helpful to have understanding on DOM, if you are not aware of DOM then I would suggest to go through our simple tutorial on DOM Tutorial." }, { "code": null, "e": 12051, "s": 12018, "text": "\n 27 Lectures \n 1 hours \n" }, { "code": null, "e": 12065, "s": 12051, "text": " Mahesh Kumar" }, { "code": null, "e": 12100, "s": 12065, "text": "\n 27 Lectures \n 1.5 hours \n" }, { "code": null, "e": 12114, "s": 12100, "text": " Pratik Singh" }, { "code": null, "e": 12149, "s": 12114, "text": "\n 72 Lectures \n 4.5 hours \n" }, { "code": null, "e": 12166, "s": 12149, "text": " Frahaan Hussain" }, { "code": null, "e": 12199, "s": 12166, "text": "\n 60 Lectures \n 9 hours \n" }, { "code": null, "e": 12227, "s": 12199, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 12260, "s": 12227, "text": "\n 17 Lectures \n 2 hours \n" }, { "code": null, "e": 12281, "s": 12260, "text": " Sandip Bhattacharya" }, { "code": null, "e": 12313, "s": 12281, "text": "\n 12 Lectures \n 53 mins\n" }, { "code": null, "e": 12330, "s": 12313, "text": " Laurence Svekis" }, { "code": null, "e": 12337, "s": 12330, "text": " Print" }, { "code": null, "e": 12348, "s": 12337, "text": " Add Notes" } ]
Different Methods to find Prime Number in Python
First we need to know what a prime number is. A prime number always a positive integer number and divisible by exactly 2 integers (1 and the number itself), 1 is not a prime number. Now we shall discuss some methods to find Prime Number. Using For loops Example def primemethod1(number): # Initialize a list my_primes = [] for pr in range(2, number): isPrime = True for i in range(2, pr): if pr % i == 0: isPrime = False if isPrime: my_primes.append(pr) print(my_primes) primemethod1(50) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] For Loops with Break Example def primemethod2(number): # Initialize a list my_primes = [] for pr in range(2, number + 1): isPrime = True for num in range(2, pr): if pr % num == 0: isPrime = False break if isPrime: my_primes.append(pr) return(my_primes) print(primemethod2(50)) [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47] For Loop, Break, and Square Root Example def primemethod3(number): # Initialize a list primes = [] for pr in range(2, number): isPrime = True for num in range(2, int(pr ** 0.5) + 1): if pr % num == 0: isPrime = False break if (isPrime): print("Prime number: ",pr) primemethod3(50) Prime number: 2 Prime number: 3 Prime number: 5 Prime number: 7 Prime number: 11 Prime number: 13 Prime number: 17 Prime number: 19 Prime number: 23 Prime number: 29 Prime number: 31 Prime number: 37 Prime number: 41 Prime number: 43 Prime number: 47
[ { "code": null, "e": 1108, "s": 1062, "text": "First we need to know what a prime number is." }, { "code": null, "e": 1244, "s": 1108, "text": "A prime number always a positive integer number and divisible by exactly 2 integers (1 and the number itself), 1 is not a prime number." }, { "code": null, "e": 1300, "s": 1244, "text": "Now we shall discuss some methods to find Prime Number." }, { "code": null, "e": 1316, "s": 1300, "text": "Using For loops" }, { "code": null, "e": 1324, "s": 1316, "text": "Example" }, { "code": null, "e": 1589, "s": 1324, "text": "def primemethod1(number):\n # Initialize a list\n my_primes = []\n for pr in range(2, number):\n isPrime = True\n for i in range(2, pr):\n if pr % i == 0:\n isPrime = False\n if isPrime:\n my_primes.append(pr)\n print(my_primes)\nprimemethod1(50)" }, { "code": null, "e": 1646, "s": 1589, "text": "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]" }, { "code": null, "e": 1667, "s": 1646, "text": "For Loops with Break" }, { "code": null, "e": 1675, "s": 1667, "text": "Example" }, { "code": null, "e": 1962, "s": 1675, "text": "def primemethod2(number):\n # Initialize a list\n my_primes = []\n for pr in range(2, number + 1):\n isPrime = True\n for num in range(2, pr):\n if pr % num == 0:\n isPrime = False\n break\n if isPrime:\n my_primes.append(pr)\nreturn(my_primes)\nprint(primemethod2(50))" }, { "code": null, "e": 2019, "s": 1962, "text": "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47]" }, { "code": null, "e": 2052, "s": 2019, "text": "For Loop, Break, and Square Root" }, { "code": null, "e": 2060, "s": 2052, "text": "Example" }, { "code": null, "e": 2336, "s": 2060, "text": "def primemethod3(number):\n # Initialize a list\n primes = []\n for pr in range(2, number):\n isPrime = True\n for num in range(2, int(pr ** 0.5) + 1):\n if pr % num == 0:\n isPrime = False\n break\n if (isPrime):\nprint(\"Prime number: \",pr)\nprimemethod3(50)" }, { "code": null, "e": 2587, "s": 2336, "text": "Prime number: 2\nPrime number: 3\nPrime number: 5\nPrime number: 7\nPrime number: 11\nPrime number: 13\nPrime number: 17\nPrime number: 19\nPrime number: 23\nPrime number: 29\nPrime number: 31\nPrime number: 37\nPrime number: 41\nPrime number: 43\nPrime number: 47" } ]
C++ Program to Solve N-Queen Problem
This problem is to find an arrangement of N queens on a chess board, such that no queen can attack any other queens on the board. The chess queens can attack in any direction as horizontal, vertical, horizontal and diagonal way. A binary matrix is used to display the positions of N Queens, where no queens can attack other queens. Here, we solve 8 queens problem. The size of a chess board. it is 8 here as (8 x 8 is the size of a normal chess board). The matrix that represents in which row and column the N Queens can be placed. If the solution does not exist, it will return false. 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0 In this output, the value 1 indicates the correct place for the queens. The 0 denotes the blank spaces on the chess board. Begin if there is a queen at the left of current col, then return false if there is a queen at the left upper diagonal, then return false if there is a queen at the left lower diagonal, then return false; return true //otherwise it is valid place End Begin if all columns are filled, then return true for each row of the board, do if isValid(board, i, col), then set queen at place (i, col) in the board if solveNQueen(board, col+1) = true, then return true otherwise remove queen from place (i, col) from board. done return false End #include<iostream> using namespace std; #define N 4 void printBoard(int board[N][N]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) cout << board[i][j] << " "; cout << endl; } } bool isValid(int board[N][N], int row, int col) { for (int i = 0; i < col; i++) //check whether there is queen in the left or not if (board[row][i]) return false; for (int i=row, j=col; i>=0 && j>=0; i--, j--) if (board[i][j]) //check whether there is queen in the left upper diagonal or not return false; for (int i=row, j=col; j>=0 && i<N; i++, j--) if (board[i][j]) //check whether there is queen in the left lower diagonal or not return false; return true; } bool solveNQueen(int board[N][N], int col) { if (col >= N) //when N queens are placed successfully return true; for (int i = 0; i < N; i++) { //for each row, check placing of queen is possible or not if (isValid(board, i, col) ) { board[i][col] = 1; //if validate, place the queen at place (i, col) if ( solveNQueen(board, col + 1)) //Go for the other columns recursively return true; board[i][col] = 0; //When no place is vacant remove that queen } } return false; //when no possible order is found } bool checkSolution() { int board[N][N]; for(int i = 0; i<N; i++) for(int j = 0; j<N; j++) board[i][j] = 0; //set all elements to 0 if ( solveNQueen(board, 0) == false ) { //starting from 0th column cout << "Solution does not exist"; return false; } printBoard(board); return true; } int main() { checkSolution(); } 1 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 1 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 0 0 0 0 0
[ { "code": null, "e": 1192, "s": 1062, "text": "This problem is to find an arrangement of N queens on a chess board, such that no queen can attack any other queens on the board." }, { "code": null, "e": 1291, "s": 1192, "text": "The chess queens can attack in any direction as horizontal, vertical, horizontal and diagonal way." }, { "code": null, "e": 1427, "s": 1291, "text": "A binary matrix is used to display the positions of N Queens, where no queens can attack other queens. Here, we solve 8 queens problem." }, { "code": null, "e": 1515, "s": 1427, "text": "The size of a chess board. it is 8 here as (8 x 8 is the size of a normal chess board)." }, { "code": null, "e": 1594, "s": 1515, "text": "The matrix that represents in which row and column the N Queens can be placed." }, { "code": null, "e": 1648, "s": 1594, "text": "If the solution does not exist, it will return false." }, { "code": null, "e": 1776, "s": 1648, "text": "1 0 0 0 0 0 0 0\n0 0 0 0 0 0 1 0\n0 0 0 0 1 0 0 0\n0 0 0 0 0 0 0 1\n0 1 0 0 0 0 0 0\n0 0 0 1 0 0 0 0\n0 0 0 0 0 1 0 0\n0 0 1 0 0 0 0 0" }, { "code": null, "e": 1848, "s": 1776, "text": "In this output, the value 1 indicates the correct place for the queens." }, { "code": null, "e": 1899, "s": 1848, "text": "The 0 denotes the blank spaces on the chess board." }, { "code": null, "e": 2180, "s": 1899, "text": "Begin\n if there is a queen at the left of current col, then\n return false\n if there is a queen at the left upper diagonal, then\n return false\n if there is a queen at the left lower diagonal, then\n return false;\n return true //otherwise it is valid place\nEnd" }, { "code": null, "e": 2530, "s": 2180, "text": "Begin\n if all columns are filled, then\n return true\n for each row of the board, do\n if isValid(board, i, col), then\n set queen at place (i, col) in the board\n if solveNQueen(board, col+1) = true, then\n return true\n otherwise remove queen from place (i, col) from board.\n done\n return false\nEnd" }, { "code": null, "e": 4196, "s": 2530, "text": "#include<iostream>\nusing namespace std;\n#define N 4\nvoid printBoard(int board[N][N]) {\n for (int i = 0; i < N; i++) {\n for (int j = 0; j < N; j++)\n cout << board[i][j] << \" \";\n cout << endl;\n }\n}\nbool isValid(int board[N][N], int row, int col) {\n for (int i = 0; i < col; i++) //check whether there is queen in the left or not\n if (board[row][i])\n return false;\n for (int i=row, j=col; i>=0 && j>=0; i--, j--)\n if (board[i][j]) //check whether there is queen in the left upper diagonal or not\n return false;\n for (int i=row, j=col; j>=0 && i<N; i++, j--)\n if (board[i][j]) //check whether there is queen in the left lower diagonal or not\n return false;\n return true;\n}\nbool solveNQueen(int board[N][N], int col) {\n if (col >= N) //when N queens are placed successfully\n return true;\n for (int i = 0; i < N; i++) { //for each row, check placing of queen is possible or not\n if (isValid(board, i, col) ) {\n board[i][col] = 1; //if validate, place the queen at place (i, col)\n if ( solveNQueen(board, col + 1)) //Go for the other columns recursively\n return true;\n board[i][col] = 0; //When no place is vacant remove that queen\n }\n }\n return false; //when no possible order is found\n}\nbool checkSolution() {\n int board[N][N];\n for(int i = 0; i<N; i++)\n for(int j = 0; j<N; j++)\n board[i][j] = 0; //set all elements to 0\n if ( solveNQueen(board, 0) == false ) { //starting from 0th column\n cout << \"Solution does not exist\";\n return false;\n }\n printBoard(board);\n return true;\n}\nint main() {\n checkSolution();\n}" }, { "code": null, "e": 4324, "s": 4196, "text": "1 0 0 0 0 0 0 0\n0 0 0 0 0 0 1 0\n0 0 0 0 1 0 0 0\n0 0 0 0 0 0 0 1\n0 1 0 0 0 0 0 0\n0 0 0 1 0 0 0 0\n0 0 0 0 0 1 0 0\n0 0 1 0 0 0 0 0" } ]
Manual compression of a table in SAP HANA
It is also possible to compress a table in SAP HANA system manually by executing the following SQL statement. UPDATE "table_name" WITH PARAMETERS ('OPTIMIZE_COMPRESSION' = 'YES') This results in deciding whether a compression is required or an existing compression can be optimized. In this scenario, HANA system uses most suitable compression algorithm. When you run the above SQL command, compression status remains the same. You can also force the database to reevaluate compression using the following SQL status UPDATE "AA_HANA11"."SHOP_FACTS" WITH PARAMETERS ('OPTIMIZE_COMPRESSION' = 'FORCE')
[ { "code": null, "e": 1172, "s": 1062, "text": "It is also possible to compress a table in SAP HANA system manually by executing the following SQL statement." }, { "code": null, "e": 1241, "s": 1172, "text": "UPDATE \"table_name\" WITH PARAMETERS ('OPTIMIZE_COMPRESSION' = 'YES')" }, { "code": null, "e": 1417, "s": 1241, "text": "This results in deciding whether a compression is required or an existing compression can be optimized. In this scenario, HANA system uses most suitable compression algorithm." }, { "code": null, "e": 1580, "s": 1417, "text": "When you run the above SQL command, compression status remains the same. You can also force the database to reevaluate compression using the following SQL status " }, { "code": null, "e": 1663, "s": 1580, "text": "UPDATE \"AA_HANA11\".\"SHOP_FACTS\" WITH PARAMETERS ('OPTIMIZE_COMPRESSION' = 'FORCE')" } ]
How to get a value from the cell of a Pandas DataFrame?
To get a value from the cell of a DataFrame, we can use the index and col variables. Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df. Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df. Print the input DataFrame, df. Print the input DataFrame, df. Initialize the index variable. Initialize the index variable. Initialize the col variable. Initialize the col variable. Get the cell value corresponding to index and col variable. Get the cell value corresponding to index and col variable. Print the cell value. Print the cell value. Live Demo import pandas as pd df = pd.DataFrame( { "x": [5, 2, 1, 9], "y": [4, 1, 5, 10], "z": [4, 1, 5, 0] } ) print("Input DataFrame is:\n", df) index = 2 col = "y" cell_val = df.iloc[index][col] print "Cell value at ", index, "for column ", col, " : ", cell_val index = 0 col = "x" cell_val = df.iloc[index][col] print "Cell value at ", index, "for column ", col, " : ", cell_val index = 1 col = "z" cell_val = df.iloc[index][col] print "Cell value at ", index, "for column ", col, " : ", cell_val Input DataFrame is: x y z 0 5 4 4 1 2 1 1 2 1 5 5 3 9 10 0 Cell value at 2 for column y: 5 Cell value at 0 for column x: 5 Cell value at 1 for column z: 1
[ { "code": null, "e": 1147, "s": 1062, "text": "To get a value from the cell of a DataFrame, we can use the index and col variables." }, { "code": null, "e": 1231, "s": 1147, "text": "Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df." }, { "code": null, "e": 1315, "s": 1231, "text": "Create a two-dimensional, size-mutable, potentially heterogeneous tabular data, df." }, { "code": null, "e": 1346, "s": 1315, "text": "Print the input DataFrame, df." }, { "code": null, "e": 1377, "s": 1346, "text": "Print the input DataFrame, df." }, { "code": null, "e": 1408, "s": 1377, "text": "Initialize the index variable." }, { "code": null, "e": 1439, "s": 1408, "text": "Initialize the index variable." }, { "code": null, "e": 1468, "s": 1439, "text": "Initialize the col variable." }, { "code": null, "e": 1497, "s": 1468, "text": "Initialize the col variable." }, { "code": null, "e": 1557, "s": 1497, "text": "Get the cell value corresponding to index and col variable." }, { "code": null, "e": 1617, "s": 1557, "text": "Get the cell value corresponding to index and col variable." }, { "code": null, "e": 1639, "s": 1617, "text": "Print the cell value." }, { "code": null, "e": 1661, "s": 1639, "text": "Print the cell value." }, { "code": null, "e": 1672, "s": 1661, "text": " Live Demo" }, { "code": null, "e": 2191, "s": 1672, "text": "import pandas as pd\n\ndf = pd.DataFrame(\n {\n \"x\": [5, 2, 1, 9],\n \"y\": [4, 1, 5, 10],\n \"z\": [4, 1, 5, 0]\n }\n)\nprint(\"Input DataFrame is:\\n\", df)\n\nindex = 2\ncol = \"y\"\ncell_val = df.iloc[index][col]\nprint \"Cell value at \", index, \"for column \", col, \" : \", cell_val\n\nindex = 0\ncol = \"x\"\ncell_val = df.iloc[index][col]\nprint \"Cell value at \", index, \"for column \", col, \" : \", cell_val\n\nindex = 1\ncol = \"z\"\ncell_val = df.iloc[index][col]\nprint \"Cell value at \", index, \"for column \", col, \" : \", cell_val" }, { "code": null, "e": 2363, "s": 2191, "text": "Input DataFrame is:\n x y z\n0 5 4 4\n1 2 1 1\n2 1 5 5\n3 9 10 0\n\nCell value at 2 for column y: 5\nCell value at 0 for column x: 5\nCell value at 1 for column z: 1" } ]
Python | Group tuples in list with same first value - GeeksforGeeks
08 Apr, 2019 Given a list of tuples, the task is to print another list containing tuple of same first element. Below are some ways to achieve above tasks. Example: Input : [('x', 'y'), ('x', 'z'), ('w', 't')] Output: [('w', 't'), ('x', 'y', 'z')] Method #1: Using extend # Python code to find common # first element in list of tuple # Function to solve the taskdef find(Input): out = {} for elem in Input: try: out[elem[0]].extend(elem[1:]) except KeyError: out[elem[0]] = list(elem) return [tuple(values) for values in out.values()] # List initializationInput = [('x', 'y'), ('x', 'z'), ('w', 't')] # Calling functionOutput = (find(Input)) # Printingprint("Initial list of tuple is :", Input)print("List showing common first element", Output) Initial list of tuple is : [('x', 'y'), ('x', 'z'), ('w', 't')] List showing common first element [('w', 't'), ('x', 'y', 'z')] Method #2: Using defaultdict # Python code to find common first# element in list of tuple # Importingfrom collections import defaultdict # Function to solve the taskdef find(pairs): mapp = defaultdict(list) for x, y in pairs: mapp[x].append(y) return [(x, *y) for x, y in mapp.items()] # Input list initializationInput = [('p', 'q'), ('p', 'r'), ('p', 's'), ('m', 't')] # calling functionOutput = find(Input) # Printingprint("Initial list of tuple is :", Input)print("List showing common first element", Output) Initial list of tuple is : [('p', 'q'), ('p', 'r'), ('p', 's'), ('m', 't')] List showing common first element [('m', 't'), ('p', 'q', 'r', 's')] Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Defaultdict in Python Python | Split string into list of characters Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not
[ { "code": null, "e": 24292, "s": 24264, "text": "\n08 Apr, 2019" }, { "code": null, "e": 24434, "s": 24292, "text": "Given a list of tuples, the task is to print another list containing tuple of same first element. Below are some ways to achieve above tasks." }, { "code": null, "e": 24443, "s": 24434, "text": "Example:" }, { "code": null, "e": 24528, "s": 24443, "text": "Input : [('x', 'y'), ('x', 'z'), ('w', 't')]\n\nOutput: [('w', 't'), ('x', 'y', 'z')]\n" }, { "code": null, "e": 24552, "s": 24528, "text": "Method #1: Using extend" }, { "code": "# Python code to find common # first element in list of tuple # Function to solve the taskdef find(Input): out = {} for elem in Input: try: out[elem[0]].extend(elem[1:]) except KeyError: out[elem[0]] = list(elem) return [tuple(values) for values in out.values()] # List initializationInput = [('x', 'y'), ('x', 'z'), ('w', 't')] # Calling functionOutput = (find(Input)) # Printingprint(\"Initial list of tuple is :\", Input)print(\"List showing common first element\", Output)", "e": 25074, "s": 24552, "text": null }, { "code": null, "e": 25203, "s": 25074, "text": "Initial list of tuple is : [('x', 'y'), ('x', 'z'), ('w', 't')]\nList showing common first element [('w', 't'), ('x', 'y', 'z')]\n" }, { "code": null, "e": 25234, "s": 25205, "text": "Method #2: Using defaultdict" }, { "code": "# Python code to find common first# element in list of tuple # Importingfrom collections import defaultdict # Function to solve the taskdef find(pairs): mapp = defaultdict(list) for x, y in pairs: mapp[x].append(y) return [(x, *y) for x, y in mapp.items()] # Input list initializationInput = [('p', 'q'), ('p', 'r'), ('p', 's'), ('m', 't')] # calling functionOutput = find(Input) # Printingprint(\"Initial list of tuple is :\", Input)print(\"List showing common first element\", Output)", "e": 25746, "s": 25234, "text": null }, { "code": null, "e": 25892, "s": 25746, "text": "Initial list of tuple is : [('p', 'q'), ('p', 'r'), ('p', 's'), ('m', 't')]\nList showing common first element [('m', 't'), ('p', 'q', 'r', 's')]\n" }, { "code": null, "e": 25914, "s": 25892, "text": "Python tuple-programs" }, { "code": null, "e": 25921, "s": 25914, "text": "Python" }, { "code": null, "e": 25937, "s": 25921, "text": "Python Programs" }, { "code": null, "e": 26035, "s": 25937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26067, "s": 26035, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26123, "s": 26067, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26165, "s": 26123, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26207, "s": 26165, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26229, "s": 26207, "text": "Defaultdict in Python" }, { "code": null, "e": 26251, "s": 26229, "text": "Defaultdict in Python" }, { "code": null, "e": 26297, "s": 26251, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26336, "s": 26297, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26374, "s": 26336, "text": "Python | Convert a list to dictionary" } ]
TensorFlow — A hands-on approach. This is the first article in the series... | by Avinash Kadimisetty | Towards Data Science
This is the first article in the series of articles I am going to pen down giving an introduction to TensorFlow and diving deep into to the myriad Math and Machine Learning libraries it offers. To begin with, I would describe, in this article, the idea behind the TensorFlow framework, the way its structured, its key components etc. By the end of this article, you will be able to write simple numerical solver code snippets in TensorFlow. For those who are not aware, TensorFlow is a computational framework for building machine learning models. It is the second generation system from Google Brain headed by Jeff Dean. Launched in early 2017, it has disrupted the ML world by bringing in numerous capabilities from scalability to building production ready models. [Credits: Wikipedia] TensorFlow provides a variety of different tool kits that allow you to write code at your preferred level of abstraction. For instance, you can write code in the Core TensorFlow (C++) and call that method from Python code. You can also define the architecture on which your code should run (CPU, GPU etc.). In the above hierarchy, the lowest level in which you can write your code is C++ or Python. These two levels allow you to write numerical programs to solve mathematical operations and equations. Although this is not highly recommended for building Machine Learning models, it offers a wide range of math libraries that ease your tasks. The next level in which you can write your code is using the TF specific abstract methods which are highly optimised for model components. For example, using the tf.layers method abstract you can play with the layers of a neural net. You can build a model and evaluate the model performance using the tf.metrics method. The most widely used level is the tf.estimator API, which allows you to build (train and predict) production ready models with easy. The estimator API is insanely easy to use and well optimised. Although it offers less flexibility, it has all that is needed to train and test your model. Let’s see an application of the estimator API to build a classifier using just three lines of code. In this article, I am going to use the Core TensorFlow (Python) to write code. But before doing so, let me discuss about the available data types in TensorFlow. The basic data type in this framework is a Tensor. A Tensor is an N-dimensional array of data. For instance, you can call a Scalar (a constant value such as integer 2) as a 0-dimension tensor. A vector is a 1-dimensional tensor and a matrix is a 2-dimensional tensor. The following graphic describes each of the dimensions of a tensor in detail. Observe the preceding graphic. The variable x is the declared tensor using the tf.constant class. Constants: A constant is a tensor whose value cannot be changed at all. In the first example, x takes a constant value 3 and hence the shape is None. You can declare any dimensional tensors by stacking up tensors on an existing tensor using the tf.stack function which can be seen from the example for nD Tensor. Now that we have seen how to declare constants in TensorFlow, let’s look at declaring variables. Variables: A variable is a tensor whose value is initialised and then typically changed as the program runs. In TensorFlow variables are manipulated by the tf.Variable class. The best way to create a variable is by calling the tf.get_variable function. This function requires you to specify the Variable’s name. This name will be used by other replicas to access the same variable, as well as to name this variable’s value when check pointing and exporting models. tf.get_variable also allows you to reuse a previously created variable of the same name, making it easy to define models which reuse layers. my_variable = tf.get_variable("my_variable", [1, 2, 3]) Initialising Variables: As theCore Tensorflow, which is a low level API, is being used, the variables need to be explicitly initialised. If a high level framework like tf.Estimator or Keras are being used, the variables will be automatically be initialised for you. To initialise the variables, the tf.global_variables_initializer needs to be called. You can initialise all the variables in a session using the following line of code. session.run(tf.global_variables_initializer()) But what is session.run?? What are sessions? A session encapsulates the state of the TensorFlow runtime, and runs TensorFlow operations. Every line of code you write using TensorFlow is represented by an underlying graph. Let’s understand this with an example below. I have created two 1D tensors x and y. I added them and stored it in a variable called z1. I multiplied them and stored it in a variable z2. I created another variable z3 by subtracting z1 from z2. When this particular code snippet is executed, TensorFlow does not compute the results but creates a graph (shown below) representing the above code. The idea behind utilising graphs is to create portable code. Yes, this graph can be exported and used by anybody on any type of architecture. But, why does TensorFlow not compute the results? Because, it follows the lazy evaluation paradigm. All graphs created are tied to a session and we have to tell TensorFlow to compute the results using session.run. session.run(z3) Remember this, If a tf.Graph is like a .py file, a tf.Session is like the python executable. Now that we know the basics of Sessions, Graphs, Data Types and how to create variable, lets get our hands dirty by writing some TensorFlow code. Mostly TensorFlow is used as a backend framework whose modules are called through Keras API. Typically, TensorFlow is used to solve complex problems like Image Classification, Object Recognition, Sound Recognition, etc. In this article, we have learnt about the structure and components of TensorFlow. In the next article, we shall dive into Machine Learning and build our first Linear Regression model using TensorFlow. A few resources to learn about TensorFlow in depth: TensorFlow documentation.Introduction to TensorFlow MOOC on Coursera. TensorFlow documentation. Introduction to TensorFlow MOOC on Coursera. Stay tuned and follow me for notifications on my further articles. Github: LinkLinkedin: Link
[ { "code": null, "e": 612, "s": 171, "text": "This is the first article in the series of articles I am going to pen down giving an introduction to TensorFlow and diving deep into to the myriad Math and Machine Learning libraries it offers. To begin with, I would describe, in this article, the idea behind the TensorFlow framework, the way its structured, its key components etc. By the end of this article, you will be able to write simple numerical solver code snippets in TensorFlow." }, { "code": null, "e": 641, "s": 612, "text": "For those who are not aware," }, { "code": null, "e": 959, "s": 641, "text": "TensorFlow is a computational framework for building machine learning models. It is the second generation system from Google Brain headed by Jeff Dean. Launched in early 2017, it has disrupted the ML world by bringing in numerous capabilities from scalability to building production ready models. [Credits: Wikipedia]" }, { "code": null, "e": 2310, "s": 959, "text": "TensorFlow provides a variety of different tool kits that allow you to write code at your preferred level of abstraction. For instance, you can write code in the Core TensorFlow (C++) and call that method from Python code. You can also define the architecture on which your code should run (CPU, GPU etc.). In the above hierarchy, the lowest level in which you can write your code is C++ or Python. These two levels allow you to write numerical programs to solve mathematical operations and equations. Although this is not highly recommended for building Machine Learning models, it offers a wide range of math libraries that ease your tasks. The next level in which you can write your code is using the TF specific abstract methods which are highly optimised for model components. For example, using the tf.layers method abstract you can play with the layers of a neural net. You can build a model and evaluate the model performance using the tf.metrics method. The most widely used level is the tf.estimator API, which allows you to build (train and predict) production ready models with easy. The estimator API is insanely easy to use and well optimised. Although it offers less flexibility, it has all that is needed to train and test your model. Let’s see an application of the estimator API to build a classifier using just three lines of code." }, { "code": null, "e": 2471, "s": 2310, "text": "In this article, I am going to use the Core TensorFlow (Python) to write code. But before doing so, let me discuss about the available data types in TensorFlow." }, { "code": null, "e": 2817, "s": 2471, "text": "The basic data type in this framework is a Tensor. A Tensor is an N-dimensional array of data. For instance, you can call a Scalar (a constant value such as integer 2) as a 0-dimension tensor. A vector is a 1-dimensional tensor and a matrix is a 2-dimensional tensor. The following graphic describes each of the dimensions of a tensor in detail." }, { "code": null, "e": 2915, "s": 2817, "text": "Observe the preceding graphic. The variable x is the declared tensor using the tf.constant class." }, { "code": null, "e": 3228, "s": 2915, "text": "Constants: A constant is a tensor whose value cannot be changed at all. In the first example, x takes a constant value 3 and hence the shape is None. You can declare any dimensional tensors by stacking up tensors on an existing tensor using the tf.stack function which can be seen from the example for nD Tensor." }, { "code": null, "e": 3325, "s": 3228, "text": "Now that we have seen how to declare constants in TensorFlow, let’s look at declaring variables." }, { "code": null, "e": 3931, "s": 3325, "text": "Variables: A variable is a tensor whose value is initialised and then typically changed as the program runs. In TensorFlow variables are manipulated by the tf.Variable class. The best way to create a variable is by calling the tf.get_variable function. This function requires you to specify the Variable’s name. This name will be used by other replicas to access the same variable, as well as to name this variable’s value when check pointing and exporting models. tf.get_variable also allows you to reuse a previously created variable of the same name, making it easy to define models which reuse layers." }, { "code": null, "e": 3987, "s": 3931, "text": "my_variable = tf.get_variable(\"my_variable\", [1, 2, 3])" }, { "code": null, "e": 4422, "s": 3987, "text": "Initialising Variables: As theCore Tensorflow, which is a low level API, is being used, the variables need to be explicitly initialised. If a high level framework like tf.Estimator or Keras are being used, the variables will be automatically be initialised for you. To initialise the variables, the tf.global_variables_initializer needs to be called. You can initialise all the variables in a session using the following line of code." }, { "code": null, "e": 4469, "s": 4422, "text": "session.run(tf.global_variables_initializer())" }, { "code": null, "e": 4514, "s": 4469, "text": "But what is session.run?? What are sessions?" }, { "code": null, "e": 4736, "s": 4514, "text": "A session encapsulates the state of the TensorFlow runtime, and runs TensorFlow operations. Every line of code you write using TensorFlow is represented by an underlying graph. Let’s understand this with an example below." }, { "code": null, "e": 5084, "s": 4736, "text": "I have created two 1D tensors x and y. I added them and stored it in a variable called z1. I multiplied them and stored it in a variable z2. I created another variable z3 by subtracting z1 from z2. When this particular code snippet is executed, TensorFlow does not compute the results but creates a graph (shown below) representing the above code." }, { "code": null, "e": 5440, "s": 5084, "text": "The idea behind utilising graphs is to create portable code. Yes, this graph can be exported and used by anybody on any type of architecture. But, why does TensorFlow not compute the results? Because, it follows the lazy evaluation paradigm. All graphs created are tied to a session and we have to tell TensorFlow to compute the results using session.run." }, { "code": null, "e": 5456, "s": 5440, "text": "session.run(z3)" }, { "code": null, "e": 5549, "s": 5456, "text": "Remember this, If a tf.Graph is like a .py file, a tf.Session is like the python executable." }, { "code": null, "e": 5695, "s": 5549, "text": "Now that we know the basics of Sessions, Graphs, Data Types and how to create variable, lets get our hands dirty by writing some TensorFlow code." }, { "code": null, "e": 6116, "s": 5695, "text": "Mostly TensorFlow is used as a backend framework whose modules are called through Keras API. Typically, TensorFlow is used to solve complex problems like Image Classification, Object Recognition, Sound Recognition, etc. In this article, we have learnt about the structure and components of TensorFlow. In the next article, we shall dive into Machine Learning and build our first Linear Regression model using TensorFlow." }, { "code": null, "e": 6168, "s": 6116, "text": "A few resources to learn about TensorFlow in depth:" }, { "code": null, "e": 6238, "s": 6168, "text": "TensorFlow documentation.Introduction to TensorFlow MOOC on Coursera." }, { "code": null, "e": 6264, "s": 6238, "text": "TensorFlow documentation." }, { "code": null, "e": 6309, "s": 6264, "text": "Introduction to TensorFlow MOOC on Coursera." }, { "code": null, "e": 6376, "s": 6309, "text": "Stay tuned and follow me for notifications on my further articles." } ]
How to make Matplotlib show all X coordinates?
To show all X coordinates (or Y coordinates), we can use xticks() method (or yticks()). Set the figure size and adjust the padding between and around the subplots. Set the figure size and adjust the padding between and around the subplots. Create x and y data points using numpy. Create x and y data points using numpy. Set x=0 and y=0 margins on the axes. Set x=0 and y=0 margins on the axes. Plot x and y data points using plot() method. Plot x and y data points using plot() method. Use xticks() method to show all the X-coordinates in the plot. Use xticks() method to show all the X-coordinates in the plot. Use yticks() method to show all the Y-coordinates in the plot. Use yticks() method to show all the Y-coordinates in the plot. To display the figure, use show() method. To display the figure, use show() method. import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] plt.rcParams["figure.autolayout"] = True x = np.arange(0, 10, 1) y =np.arange(0, 10, 1) plt.margins(x=0, y=0) plt.plot(x, y) plt.xticks(x) plt.yticks(y) plt.show()
[ { "code": null, "e": 1150, "s": 1062, "text": "To show all X coordinates (or Y coordinates), we can use xticks() method (or yticks())." }, { "code": null, "e": 1226, "s": 1150, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1302, "s": 1226, "text": "Set the figure size and adjust the padding between and around the subplots." }, { "code": null, "e": 1342, "s": 1302, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1382, "s": 1342, "text": "Create x and y data points using numpy." }, { "code": null, "e": 1419, "s": 1382, "text": "Set x=0 and y=0 margins on the axes." }, { "code": null, "e": 1456, "s": 1419, "text": "Set x=0 and y=0 margins on the axes." }, { "code": null, "e": 1502, "s": 1456, "text": "Plot x and y data points using plot() method." }, { "code": null, "e": 1548, "s": 1502, "text": "Plot x and y data points using plot() method." }, { "code": null, "e": 1611, "s": 1548, "text": "Use xticks() method to show all the X-coordinates in the plot." }, { "code": null, "e": 1674, "s": 1611, "text": "Use xticks() method to show all the X-coordinates in the plot." }, { "code": null, "e": 1737, "s": 1674, "text": "Use yticks() method to show all the Y-coordinates in the plot." }, { "code": null, "e": 1800, "s": 1737, "text": "Use yticks() method to show all the Y-coordinates in the plot." }, { "code": null, "e": 1842, "s": 1800, "text": "To display the figure, use show() method." }, { "code": null, "e": 1884, "s": 1842, "text": "To display the figure, use show() method." }, { "code": null, "e": 2145, "s": 1884, "text": "import numpy as np\nimport matplotlib.pyplot as plt\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nx = np.arange(0, 10, 1)\ny =np.arange(0, 10, 1)\nplt.margins(x=0, y=0)\nplt.plot(x, y)\nplt.xticks(x)\nplt.yticks(y)\nplt.show()" } ]
ByteBuffer slice() method in Java with Examples - GeeksforGeeks
07 Aug, 2021 The slice() method of java.nio.ByteBuffer Class is used to creates a new byte buffer whose content is a shared subsequence of the given buffer’s content. The content of the new buffer will start at this buffer’s current position. Changes to this buffer’s content will be visible in the new buffer, and vice versa. The two buffers’ position, limit, and mark values will be independent. The new buffer’s position will be zero, its capacity and its limit will be the number of floats remaining in this buffer, and its mark will be undefined. The new buffer will be direct if, and only if, this buffer is direct, and it will be read-only if, and only if, this buffer is read-only. Syntax : public abstract ByteBuffer slice() Return Value: This method returns the new byte buffer. Below are the examples to illustrate the slice() method: Examples 1: Java // Java program to demonstrate// slice() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 5; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb1 = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer bb1.put((byte)10); bb1.put((byte)20); // print the ByteBuffer System.out.println("Original ByteBuffer: " + Arrays.toString(bb1.array())); // print the ByteBuffer position System.out.println("\nposition: " + bb1.position()); // print the ByteBuffer capacity System.out.println("\ncapacity: " + bb1.capacity()); // Creating a shared subsequence buffer // of given ByteBuffer // using slice() method ByteBuffer bb2 = bb1.slice(); // print the shared subsequence buffer System.out.println("\nshared subsequence ByteBuffer: " + Arrays.toString(bb2.array())); // print the ByteBuffer position System.out.println("\nposition: " + bb2.position()); // print the ByteBuffer capacity System.out.println("\ncapacity: " + bb2.capacity()); } catch (IllegalArgumentException e) { System.out.println("IllegalArgumentException catched"); } catch (ReadOnlyBufferException e) { System.out.println("ReadOnlyBufferException catched"); } }} Original ByteBuffer: [10, 20, 0, 0, 0] position: 2 capacity: 5 shared subsequence ByteBuffer: [10, 20, 0, 0, 0] position: 0 capacity: 3 Examples 2: Java // Java program to demonstrate// slice() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 5; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb1 = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer bb1.put((byte)10) .put((byte)20) .put((byte)30) .put((byte)40) .put((byte)50); // print the ByteBuffer System.out.println("Original ByteBuffer: " + Arrays.toString(bb1.array())); // print the ByteBuffer position System.out.println("\nposition: " + bb1.position()); // print the ByteBuffer capacity System.out.println("\ncapacity: " + bb1.capacity()); // Creating a shared subsequence buffer // of given ByteBuffer // using slice() method ByteBuffer bb2 = bb1.slice(); // print the shared subsequence buffer System.out.println("\nshared subsequence ByteBuffer: " + Arrays.toString(bb2.array())); // print the ByteBuffer position System.out.println("\nposition: " + bb2.position()); // print the ByteBuffer capacity System.out.println("\ncapacity: " + bb2.capacity()); } catch (IllegalArgumentException e) { System.out.println("IllegalArgumentException catched"); } catch (ReadOnlyBufferException e) { System.out.println("ReadOnlyBufferException catched"); } }} Original ByteBuffer: [10, 20, 30, 40, 50] position: 5 capacity: 5 shared subsequence ByteBuffer: [10, 20, 30, 40, 50] position: 0 capacity: 0 Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#slice– ruhelaa48 Java-ByteBuffer Java-Functions Java-NIO package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Initialize an ArrayList in Java HashMap in Java with Examples Interfaces in Java Object Oriented Programming (OOPs) Concept in Java ArrayList in Java How to iterate any Map in Java Multidimensional Arrays in Java LinkedList in Java Stack Class in Java Overriding in Java
[ { "code": null, "e": 24614, "s": 24586, "text": "\n07 Aug, 2021" }, { "code": null, "e": 24768, "s": 24614, "text": "The slice() method of java.nio.ByteBuffer Class is used to creates a new byte buffer whose content is a shared subsequence of the given buffer’s content." }, { "code": null, "e": 24999, "s": 24768, "text": "The content of the new buffer will start at this buffer’s current position. Changes to this buffer’s content will be visible in the new buffer, and vice versa. The two buffers’ position, limit, and mark values will be independent." }, { "code": null, "e": 25291, "s": 24999, "text": "The new buffer’s position will be zero, its capacity and its limit will be the number of floats remaining in this buffer, and its mark will be undefined. The new buffer will be direct if, and only if, this buffer is direct, and it will be read-only if, and only if, this buffer is read-only." }, { "code": null, "e": 25301, "s": 25291, "text": "Syntax : " }, { "code": null, "e": 25336, "s": 25301, "text": "public abstract ByteBuffer slice()" }, { "code": null, "e": 25391, "s": 25336, "text": "Return Value: This method returns the new byte buffer." }, { "code": null, "e": 25448, "s": 25391, "text": "Below are the examples to illustrate the slice() method:" }, { "code": null, "e": 25461, "s": 25448, "text": "Examples 1: " }, { "code": null, "e": 25466, "s": 25461, "text": "Java" }, { "code": "// Java program to demonstrate// slice() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 5; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb1 = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer bb1.put((byte)10); bb1.put((byte)20); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \" + Arrays.toString(bb1.array())); // print the ByteBuffer position System.out.println(\"\\nposition: \" + bb1.position()); // print the ByteBuffer capacity System.out.println(\"\\ncapacity: \" + bb1.capacity()); // Creating a shared subsequence buffer // of given ByteBuffer // using slice() method ByteBuffer bb2 = bb1.slice(); // print the shared subsequence buffer System.out.println(\"\\nshared subsequence ByteBuffer: \" + Arrays.toString(bb2.array())); // print the ByteBuffer position System.out.println(\"\\nposition: \" + bb2.position()); // print the ByteBuffer capacity System.out.println(\"\\ncapacity: \" + bb2.capacity()); } catch (IllegalArgumentException e) { System.out.println(\"IllegalArgumentException catched\"); } catch (ReadOnlyBufferException e) { System.out.println(\"ReadOnlyBufferException catched\"); } }}", "e": 27265, "s": 25466, "text": null }, { "code": null, "e": 27410, "s": 27265, "text": "Original ByteBuffer: [10, 20, 0, 0, 0]\n\nposition: 2\n\ncapacity: 5\n\nshared subsequence ByteBuffer: [10, 20, 0, 0, 0]\n\nposition: 0\n\ncapacity: 3" }, { "code": null, "e": 27422, "s": 27410, "text": "Examples 2:" }, { "code": null, "e": 27427, "s": 27422, "text": "Java" }, { "code": "// Java program to demonstrate// slice() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 5; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb1 = ByteBuffer.allocate(capacity); // putting the value in ByteBuffer bb1.put((byte)10) .put((byte)20) .put((byte)30) .put((byte)40) .put((byte)50); // print the ByteBuffer System.out.println(\"Original ByteBuffer: \" + Arrays.toString(bb1.array())); // print the ByteBuffer position System.out.println(\"\\nposition: \" + bb1.position()); // print the ByteBuffer capacity System.out.println(\"\\ncapacity: \" + bb1.capacity()); // Creating a shared subsequence buffer // of given ByteBuffer // using slice() method ByteBuffer bb2 = bb1.slice(); // print the shared subsequence buffer System.out.println(\"\\nshared subsequence ByteBuffer: \" + Arrays.toString(bb2.array())); // print the ByteBuffer position System.out.println(\"\\nposition: \" + bb2.position()); // print the ByteBuffer capacity System.out.println(\"\\ncapacity: \" + bb2.capacity()); } catch (IllegalArgumentException e) { System.out.println(\"IllegalArgumentException catched\"); } catch (ReadOnlyBufferException e) { System.out.println(\"ReadOnlyBufferException catched\"); } }}", "e": 29301, "s": 27427, "text": null }, { "code": null, "e": 29452, "s": 29301, "text": "Original ByteBuffer: [10, 20, 30, 40, 50]\n\nposition: 5\n\ncapacity: 5\n\nshared subsequence ByteBuffer: [10, 20, 30, 40, 50]\n\nposition: 0\n\ncapacity: 0" }, { "code": null, "e": 29538, "s": 29452, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/nio/ByteBuffer.html#slice– " }, { "code": null, "e": 29548, "s": 29538, "text": "ruhelaa48" }, { "code": null, "e": 29564, "s": 29548, "text": "Java-ByteBuffer" }, { "code": null, "e": 29579, "s": 29564, "text": "Java-Functions" }, { "code": null, "e": 29596, "s": 29579, "text": "Java-NIO package" }, { "code": null, "e": 29601, "s": 29596, "text": "Java" }, { "code": null, "e": 29606, "s": 29601, "text": "Java" }, { "code": null, "e": 29704, "s": 29606, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29713, "s": 29704, "text": "Comments" }, { "code": null, "e": 29726, "s": 29713, "text": "Old Comments" }, { "code": null, "e": 29758, "s": 29726, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29788, "s": 29758, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29807, "s": 29788, "text": "Interfaces in Java" }, { "code": null, "e": 29858, "s": 29807, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29876, "s": 29858, "text": "ArrayList in Java" }, { "code": null, "e": 29907, "s": 29876, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29939, "s": 29907, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 29958, "s": 29939, "text": "LinkedList in Java" }, { "code": null, "e": 29978, "s": 29958, "text": "Stack Class in Java" } ]