title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How do we add bold text in HTML?
To display bold text, use the <strong> tag. The HTML <strong> tag is used for emphasizing an important text. You can try to run the following code to implement <strong> tag in HTML − <!Doctype html> <html> <head> <title>HTML strong Tag</title> </head> <body> <p>This is an <strong>important</strong> text</p> </body> </html>
[ { "code": null, "e": 1171, "s": 1062, "text": "To display bold text, use the <strong> tag. The HTML <strong> tag is used for emphasizing an important text." }, { "code": null, "e": 1245, "s": 1171, "text": "You can try to run the following code to implement <strong> tag in HTML −" }, { "code": null, "e": 1411, "s": 1245, "text": "<!Doctype html>\n<html>\n <head>\n <title>HTML strong Tag</title>\n </head>\n <body>\n <p>This is an <strong>important</strong> text</p>\n </body>\n</html>" } ]
Python Pillow - Flip and Rotate Images
While working on images using python image processing library, there are instances where you need to flip an existing image to get some more insights out of it, to enhance its visibility or because of your requirement. Image module of the pillow library allows us to flip an image very easily. We are going to use the transpose (method) function from the Image module for flipping the images. Some of the mostly commonly used methods supported by ‘transpose()’ are − Image.FLIP_LEFT_RIGHT − For flipping the image horizontally Image.FLIP_LEFT_RIGHT − For flipping the image horizontally Image.FLIP_TOP_BOTTOM − For flipping the image vertically Image.FLIP_TOP_BOTTOM − For flipping the image vertically Image.ROTATE_90 − For rotating the image by specifying degree Image.ROTATE_90 − For rotating the image by specifying degree Following Python example reads an image, flips it horizontally, and displays the original and flipped image using standard PNG display utility − # import required image module from PIL import Image # Open an already existing image imageObject = Image.open("images/spiderman.jpg") # Do a flip of left and right hori_flippedImage = imageObject.transpose(Image.FLIP_LEFT_RIGHT) # Show the original image imageObject.show() # Show the horizontal flipped image hori_flippedImage.show() Original image Flipped image Following Python example reads an image, flips it vertically, and displays the original and flipped image using standard PNG display utility − # import required image module from PIL import Image # Open an already existing image imageObject = Image.open("images/spiderman.jpg") # Do a flip of left and right hori_flippedImage = imageObject.transpose(Image.FLIP_LEFT_RIGHT) # Show the original image imageObject.show() # Show vertically flipped image Vert_flippedImage = imageObject.transpose(Image.FLIP_TOP_BOTTOM) Vert_flippedImage.show() Original Image Flipped Image Following Python example reads an image, rotates to a specified degree, and displays the original and rotated image using standard PNG display utility − # import required image module from PIL import Image # Open an already existing image imageObject = Image.open("images/spiderman.jpg") # Do a flip of left and right hori_flippedImage = imageObject.transpose(Image.FLIP_LEFT_RIGHT) # Show the original image imageObject.show() #show 90 degree flipped image degree_flippedImage = imageObject.transpose(Image.ROTATE_90) degree_flippedImage.show() Original Image Rotated Image 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2419, "s": 2200, "text": "While working on images using python image processing library, there are instances where you need to flip an existing image to get some more insights out of it, to enhance its visibility or because of your requirement." }, { "code": null, "e": 2668, "s": 2419, "text": "Image module of the pillow library allows us to flip an image very easily. We are going to use the transpose (method) function from the Image module for flipping the images. Some of the mostly commonly used methods supported by ‘transpose()’ are − " }, { "code": null, "e": 2728, "s": 2668, "text": "Image.FLIP_LEFT_RIGHT − For flipping the image horizontally" }, { "code": null, "e": 2788, "s": 2728, "text": "Image.FLIP_LEFT_RIGHT − For flipping the image horizontally" }, { "code": null, "e": 2846, "s": 2788, "text": "Image.FLIP_TOP_BOTTOM − For flipping the image vertically" }, { "code": null, "e": 2904, "s": 2846, "text": "Image.FLIP_TOP_BOTTOM − For flipping the image vertically" }, { "code": null, "e": 2966, "s": 2904, "text": "Image.ROTATE_90 − For rotating the image by specifying degree" }, { "code": null, "e": 3028, "s": 2966, "text": "Image.ROTATE_90 − For rotating the image by specifying degree" }, { "code": null, "e": 3173, "s": 3028, "text": "Following Python example reads an image, flips it horizontally, and displays the original and flipped image using standard PNG display utility −" }, { "code": null, "e": 3513, "s": 3173, "text": "# import required image module\nfrom PIL import Image\n\n# Open an already existing image\nimageObject = Image.open(\"images/spiderman.jpg\")\n\n# Do a flip of left and right\nhori_flippedImage = imageObject.transpose(Image.FLIP_LEFT_RIGHT)\n\n# Show the original image\nimageObject.show()\n\n# Show the horizontal flipped image\nhori_flippedImage.show()" }, { "code": null, "e": 3528, "s": 3513, "text": "Original image" }, { "code": null, "e": 3542, "s": 3528, "text": "Flipped image" }, { "code": null, "e": 3685, "s": 3542, "text": "Following Python example reads an image, flips it vertically, and displays the original and flipped image using standard PNG display utility −" }, { "code": null, "e": 4086, "s": 3685, "text": "# import required image module\nfrom PIL import Image\n\n# Open an already existing image\nimageObject = Image.open(\"images/spiderman.jpg\")\n\n# Do a flip of left and right\nhori_flippedImage = imageObject.transpose(Image.FLIP_LEFT_RIGHT)\n\n# Show the original image\nimageObject.show()\n\n# Show vertically flipped image\nVert_flippedImage = imageObject.transpose(Image.FLIP_TOP_BOTTOM)\nVert_flippedImage.show()" }, { "code": null, "e": 4101, "s": 4086, "text": "Original Image" }, { "code": null, "e": 4115, "s": 4101, "text": "Flipped Image" }, { "code": null, "e": 4268, "s": 4115, "text": "Following Python example reads an image, rotates to a specified degree, and displays the original and rotated image using standard PNG display utility −" }, { "code": null, "e": 4665, "s": 4268, "text": "# import required image module\nfrom PIL import Image\n\n# Open an already existing image\nimageObject = Image.open(\"images/spiderman.jpg\")\n\n# Do a flip of left and right\nhori_flippedImage = imageObject.transpose(Image.FLIP_LEFT_RIGHT)\n\n# Show the original image\nimageObject.show()\n\n#show 90 degree flipped image\ndegree_flippedImage = imageObject.transpose(Image.ROTATE_90)\ndegree_flippedImage.show()" }, { "code": null, "e": 4680, "s": 4665, "text": "Original Image" }, { "code": null, "e": 4694, "s": 4680, "text": "Rotated Image" }, { "code": null, "e": 4731, "s": 4694, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4747, "s": 4731, "text": " Malhar Lathkar" }, { "code": null, "e": 4780, "s": 4747, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 4799, "s": 4780, "text": " Arnab Chakraborty" }, { "code": null, "e": 4834, "s": 4799, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 4856, "s": 4834, "text": " In28Minutes Official" }, { "code": null, "e": 4890, "s": 4856, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 4918, "s": 4890, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 4953, "s": 4918, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4967, "s": 4953, "text": " Lets Kode It" }, { "code": null, "e": 5000, "s": 4967, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 5017, "s": 5000, "text": " Abhilash Nelson" }, { "code": null, "e": 5024, "s": 5017, "text": " Print" }, { "code": null, "e": 5035, "s": 5024, "text": " Add Notes" } ]
Convert string of time to time object in Java
Here is our string. String strTime = "20:15:40"; Now, use the DateFormat to set the format for date. DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss"); Parse the string of time to time object. Date d = dateFormat.parse(strTime); The following is the complete example. Live Demo import java.text.DateFormat; import java.util.Date; import java.text.SimpleDateFormat; public class Demo { public static void main(String[] args) throws Exception { String strTime = "20:15:40"; DateFormat dateFormat = new SimpleDateFormat("hh:mm:ss"); Date d = dateFormat.parse(strTime); System.out.println("Resultant Date and Time = " + d); } } Resultant Date and Time = Thu Jan 01 20:15:40 UTC 1970
[ { "code": null, "e": 1082, "s": 1062, "text": "Here is our string." }, { "code": null, "e": 1111, "s": 1082, "text": "String strTime = \"20:15:40\";" }, { "code": null, "e": 1163, "s": 1111, "text": "Now, use the DateFormat to set the format for date." }, { "code": null, "e": 1221, "s": 1163, "text": "DateFormat dateFormat = new SimpleDateFormat(\"hh:mm:ss\");" }, { "code": null, "e": 1262, "s": 1221, "text": "Parse the string of time to time object." }, { "code": null, "e": 1298, "s": 1262, "text": "Date d = dateFormat.parse(strTime);" }, { "code": null, "e": 1337, "s": 1298, "text": "The following is the complete example." }, { "code": null, "e": 1348, "s": 1337, "text": " Live Demo" }, { "code": null, "e": 1730, "s": 1348, "text": "import java.text.DateFormat;\nimport java.util.Date;\nimport java.text.SimpleDateFormat;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n String strTime = \"20:15:40\";\n DateFormat dateFormat = new SimpleDateFormat(\"hh:mm:ss\");\n Date d = dateFormat.parse(strTime);\n System.out.println(\"Resultant Date and Time = \" + d);\n }\n}" }, { "code": null, "e": 1785, "s": 1730, "text": "Resultant Date and Time = Thu Jan 01 20:15:40 UTC 1970" } ]
How to add HTTP headers 'X-Frame-Options' on iframe ? - GeeksforGeeks
28 Feb, 2020 Inline frame tag in HTML: The iframe tag is used to displaying or embedding another document within an HTML document. One of its attributes ‘src’ is used to specify the URL of the document which is to be displayed. A site’s X-frame Options can prevent allowing the display of one HTML document within another. X-Frame Options: The X-Frame Options are not an attribute of the iframe or frame or any other HTML tags. It is a response header and is also referred to as HTTP security headers. This header tells the browser whether to render the HTML document in the specified URL or not. This plays an important role to prevent clickjacking attacks. Thus the X-Frame options cannot be set in the body of an HTML document. It is set by the domain from which the resource is requested. The X-Frame options available are: deny: It prevents any URL being rendered within the containers like iframe, frame, objects, applets. Even if the page is from same site, when the X-Frame option is set to ‘deny’, it is not rendered. SAMEORIGIN: It allows pages of same origin to be rendered. The page from the same site will be allowed to be displayed. ALLOW-FROM uri: It allows the HTML documents from the specified uri only. One can set the X-Frame Options in the web-config of the site which is to be loaded in an iframe. For configuring in IIS write: <httpProtocol> <customHeaders> <add name="X-Frame-Options" value="sameorigin"/> </customHeaders></httpProtocol> For configuring Apache: Header always set X-Frame-Options "sameorigin" Note: The browsers Edge (version 12 and above), Internet Explorer (version 8 and above) support ALLOW-FROM uri in X-Frame-Options. HTTP-headers Picked Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 10 Front End Developer Skills That You Need in 2022 How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? File uploading in React.js How to Open URL in New Tab using JavaScript ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 24191, "s": 24163, "text": "\n28 Feb, 2020" }, { "code": null, "e": 24501, "s": 24191, "text": "Inline frame tag in HTML: The iframe tag is used to displaying or embedding another document within an HTML document. One of its attributes ‘src’ is used to specify the URL of the document which is to be displayed. A site’s X-frame Options can prevent allowing the display of one HTML document within another." }, { "code": null, "e": 25006, "s": 24501, "text": "X-Frame Options: The X-Frame Options are not an attribute of the iframe or frame or any other HTML tags. It is a response header and is also referred to as HTTP security headers. This header tells the browser whether to render the HTML document in the specified URL or not. This plays an important role to prevent clickjacking attacks. Thus the X-Frame options cannot be set in the body of an HTML document. It is set by the domain from which the resource is requested. The X-Frame options available are:" }, { "code": null, "e": 25205, "s": 25006, "text": "deny: It prevents any URL being rendered within the containers like iframe, frame, objects, applets. Even if the page is from same site, when the X-Frame option is set to ‘deny’, it is not rendered." }, { "code": null, "e": 25325, "s": 25205, "text": "SAMEORIGIN: It allows pages of same origin to be rendered. The page from the same site will be allowed to be displayed." }, { "code": null, "e": 25399, "s": 25325, "text": "ALLOW-FROM uri: It allows the HTML documents from the specified uri only." }, { "code": null, "e": 25497, "s": 25399, "text": "One can set the X-Frame Options in the web-config of the site which is to be loaded in an iframe." }, { "code": null, "e": 25527, "s": 25497, "text": "For configuring in IIS write:" }, { "code": "<httpProtocol> <customHeaders> <add name=\"X-Frame-Options\" value=\"sameorigin\"/> </customHeaders></httpProtocol>", "e": 25646, "s": 25527, "text": null }, { "code": null, "e": 25670, "s": 25646, "text": "For configuring Apache:" }, { "code": null, "e": 25717, "s": 25670, "text": "Header always set X-Frame-Options \"sameorigin\"" }, { "code": null, "e": 25848, "s": 25717, "text": "Note: The browsers Edge (version 12 and above), Internet Explorer (version 8 and above) support ALLOW-FROM uri in X-Frame-Options." }, { "code": null, "e": 25861, "s": 25848, "text": "HTTP-headers" }, { "code": null, "e": 25868, "s": 25861, "text": "Picked" }, { "code": null, "e": 25885, "s": 25868, "text": "Web Technologies" }, { "code": null, "e": 25912, "s": 25885, "text": "Web technologies Questions" }, { "code": null, "e": 26010, "s": 25912, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26019, "s": 26010, "text": "Comments" }, { "code": null, "e": 26032, "s": 26019, "text": "Old Comments" }, { "code": null, "e": 26088, "s": 26032, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26131, "s": 26088, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 26192, "s": 26131, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 26237, "s": 26192, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 26309, "s": 26237, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 26369, "s": 26309, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 26430, "s": 26369, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 26457, "s": 26430, "text": "File uploading in React.js" }, { "code": null, "e": 26503, "s": 26457, "text": "How to Open URL in New Tab using JavaScript ?" } ]
Ridgeline Plots: The Perfect Way to Visualize Data Distributions with Python | by Dario Radečić | Towards Data Science
Aren’t you tired of drawing histograms or density plots for every variable segment? There’s an easier solution. Ridgeline plots are a go-to visualization for this type of problem. Yes, even for multiple variables at the same time. Here’s what you’ll make today: Reading feels like a nightmare? There’s an easy solution: Let’s get straight to the business. Here’s how the article is structured: Dataset loading and preparation Ridgeline plot for a single variable Ridgeline plot for multiple variables Conclusion The dataset you’ll use today is called Rain in Australia, so please download it. You won’t use it to predict rain, as it says in the description, but to make visualizations. You’ll use only four columns: Date – useful for extracting month information Location – you’ll work only with Sydney data MinTemp– minimum temperature for the day MaxTemp– maximum temperature for the day Before proceeding to dataset loading, there’s one library you need to install — joypy. It is used to make joyplots or ridgeline plots in Python: pip install joypy Here’s how to load in the dataset. Keep in mind that you only want the four mentioned columns: The first couple of rows should look like this: Onto the preparation now. The to-do list is quite short: Create a data frame sydney which has data only for this town Ditch the Location column Convert Date column to datetime64 type Extract month names from the date Here’s the code: The dataset now looks like this: It’s starting to look good, but you’re not done yet. The dataset isn’t aware of the relationship between the months. As a result, ordering them on a chart is a nightmare. Pandas has a CategoricalDtype class that can help you with this. You have to specify the ordering of the categories and make the conversion afterward. Here’s how: Accessing the dtypes informs you the transformation was successful: You’re done, preparation-wise! Time to make some ridgeline plots. Drawing a chart boils down to a single function call. Here’s the code you’ll need to make a ridgeline plot of maximum temperatures in Sydney: You could ditch the first and last two lines if you don’t care about the title. A call to joyplot() is enough. Here’s how the visualization looks like: It took me a moment to realize nothing is wrong with the visualization. The dataset contains temperature data for Australia. The seasons there are opposite from the ones in the northern hemisphere. Let’s see how to make things more complex by introducing a second variable to the plot. In addition to plotting distributions for max temperatures, you’ll now include the min temperature. Once again, thejoyplot library makes it easy: Here’s how the visualization looks like: Take a moment to appreciate how much information is shown on this single chart. It would take you 24 density plots for the most naive approach, and comparisons wouldn’t be nearly as easy. Let’s wrap things up next. And that’s ridgeline plots in a nutshell. You could do more — like coloring the area under the curve by some variable. The official documentation is packed with examples — explore it if you have the time. To summarize — use ridgeline plots whenever you need to visualize distributions of variables and their segments in a compact way. Drawing histograms and density plots manually for variable segments is something you should avoid. Loved the article? Become a Medium member to continue learning without limits. I’ll receive a portion of your membership fee if you use the following link, with no extra cost to you.
[ { "code": null, "e": 402, "s": 171, "text": "Aren’t you tired of drawing histograms or density plots for every variable segment? There’s an easier solution. Ridgeline plots are a go-to visualization for this type of problem. Yes, even for multiple variables at the same time." }, { "code": null, "e": 433, "s": 402, "text": "Here’s what you’ll make today:" }, { "code": null, "e": 491, "s": 433, "text": "Reading feels like a nightmare? There’s an easy solution:" }, { "code": null, "e": 565, "s": 491, "text": "Let’s get straight to the business. Here’s how the article is structured:" }, { "code": null, "e": 597, "s": 565, "text": "Dataset loading and preparation" }, { "code": null, "e": 634, "s": 597, "text": "Ridgeline plot for a single variable" }, { "code": null, "e": 672, "s": 634, "text": "Ridgeline plot for multiple variables" }, { "code": null, "e": 683, "s": 672, "text": "Conclusion" }, { "code": null, "e": 857, "s": 683, "text": "The dataset you’ll use today is called Rain in Australia, so please download it. You won’t use it to predict rain, as it says in the description, but to make visualizations." }, { "code": null, "e": 887, "s": 857, "text": "You’ll use only four columns:" }, { "code": null, "e": 934, "s": 887, "text": "Date – useful for extracting month information" }, { "code": null, "e": 979, "s": 934, "text": "Location – you’ll work only with Sydney data" }, { "code": null, "e": 1020, "s": 979, "text": "MinTemp– minimum temperature for the day" }, { "code": null, "e": 1061, "s": 1020, "text": "MaxTemp– maximum temperature for the day" }, { "code": null, "e": 1206, "s": 1061, "text": "Before proceeding to dataset loading, there’s one library you need to install — joypy. It is used to make joyplots or ridgeline plots in Python:" }, { "code": null, "e": 1224, "s": 1206, "text": "pip install joypy" }, { "code": null, "e": 1319, "s": 1224, "text": "Here’s how to load in the dataset. Keep in mind that you only want the four mentioned columns:" }, { "code": null, "e": 1367, "s": 1319, "text": "The first couple of rows should look like this:" }, { "code": null, "e": 1424, "s": 1367, "text": "Onto the preparation now. The to-do list is quite short:" }, { "code": null, "e": 1485, "s": 1424, "text": "Create a data frame sydney which has data only for this town" }, { "code": null, "e": 1511, "s": 1485, "text": "Ditch the Location column" }, { "code": null, "e": 1550, "s": 1511, "text": "Convert Date column to datetime64 type" }, { "code": null, "e": 1584, "s": 1550, "text": "Extract month names from the date" }, { "code": null, "e": 1601, "s": 1584, "text": "Here’s the code:" }, { "code": null, "e": 1634, "s": 1601, "text": "The dataset now looks like this:" }, { "code": null, "e": 1805, "s": 1634, "text": "It’s starting to look good, but you’re not done yet. The dataset isn’t aware of the relationship between the months. As a result, ordering them on a chart is a nightmare." }, { "code": null, "e": 1968, "s": 1805, "text": "Pandas has a CategoricalDtype class that can help you with this. You have to specify the ordering of the categories and make the conversion afterward. Here’s how:" }, { "code": null, "e": 2036, "s": 1968, "text": "Accessing the dtypes informs you the transformation was successful:" }, { "code": null, "e": 2102, "s": 2036, "text": "You’re done, preparation-wise! Time to make some ridgeline plots." }, { "code": null, "e": 2244, "s": 2102, "text": "Drawing a chart boils down to a single function call. Here’s the code you’ll need to make a ridgeline plot of maximum temperatures in Sydney:" }, { "code": null, "e": 2355, "s": 2244, "text": "You could ditch the first and last two lines if you don’t care about the title. A call to joyplot() is enough." }, { "code": null, "e": 2396, "s": 2355, "text": "Here’s how the visualization looks like:" }, { "code": null, "e": 2594, "s": 2396, "text": "It took me a moment to realize nothing is wrong with the visualization. The dataset contains temperature data for Australia. The seasons there are opposite from the ones in the northern hemisphere." }, { "code": null, "e": 2682, "s": 2594, "text": "Let’s see how to make things more complex by introducing a second variable to the plot." }, { "code": null, "e": 2828, "s": 2682, "text": "In addition to plotting distributions for max temperatures, you’ll now include the min temperature. Once again, thejoyplot library makes it easy:" }, { "code": null, "e": 2869, "s": 2828, "text": "Here’s how the visualization looks like:" }, { "code": null, "e": 3057, "s": 2869, "text": "Take a moment to appreciate how much information is shown on this single chart. It would take you 24 density plots for the most naive approach, and comparisons wouldn’t be nearly as easy." }, { "code": null, "e": 3084, "s": 3057, "text": "Let’s wrap things up next." }, { "code": null, "e": 3289, "s": 3084, "text": "And that’s ridgeline plots in a nutshell. You could do more — like coloring the area under the curve by some variable. The official documentation is packed with examples — explore it if you have the time." }, { "code": null, "e": 3518, "s": 3289, "text": "To summarize — use ridgeline plots whenever you need to visualize distributions of variables and their segments in a compact way. Drawing histograms and density plots manually for variable segments is something you should avoid." } ]
How to write binary data to a file using Python?
"Binary" files are any files where the format isn't made up of readable characters. Binary files can range from image files like JPEGs or GIFs, audio files like MP3s or binary document formats like Word or PDF. In Python, files are opened in text mode by default. To open files in binary mode, when specifying a mode, add 'b' to it. f = open('my_file', 'w+b') byte_arr = [120, 3, 255, 0, 100] binary_format = bytearray(byte_arr) f.write(binary_format) f.close() This opens a file in binary write mode and writes the byte_arr array contents as bytes in the binary file, my_file.
[ { "code": null, "e": 1395, "s": 1062, "text": "\"Binary\" files are any files where the format isn't made up of readable characters. Binary files can range from image files like JPEGs or GIFs, audio files like MP3s or binary document formats like Word or PDF. In Python, files are opened in text mode by default. To open files in binary mode, when specifying a mode, add 'b' to it." }, { "code": null, "e": 1524, "s": 1395, "text": "f = open('my_file', 'w+b')\nbyte_arr = [120, 3, 255, 0, 100]\nbinary_format = bytearray(byte_arr)\nf.write(binary_format)\nf.close()" }, { "code": null, "e": 1640, "s": 1524, "text": "This opens a file in binary write mode and writes the byte_arr array contents as bytes in the binary file, my_file." } ]
Display MongoDB with document and subdocument example and update
Following is the syntax showing document and subdocument − db.yourCollectionName.insertOne( { yourFiledName:yourValue, yourFieldName : [ { yourFiledName1, yourFiledName2, . . . N } ] } ); Let us see an example create a collection with documents − > db.demo706.insertOne( ... { ... PortalName: "GameApplication", ... ApplicationConfiguration : [ ... { ... "URL": "jdbc:mysql://localhost/customer_tracker?autoReconnect=true", ... "USERNAME": "root", ... "PASSWORD": "root" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea6f557551299a9f98c93c6") } > > db.demo706.insertOne( ... { ... PortalName: "WebMyBusinessApplication", ... ApplicationConfiguration : [ ... { ... "URL": "jdbc:oracle:thin:@localhost:1521:xe", ... "USERNAME": "App", ... "PASSWORD": "App" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5ea6f558551299a9f98c93c7") } Display all documents from a collection with the help of find() method − > db.demo706.find(); This will produce the following output − { "_id" : ObjectId("5ea6f557551299a9f98c93c6"), "PortalName" : "GameApplication", "ApplicationConfiguration" : [ { "URL" : "jdbc:mysql://localhost/customer_tracker?autoReconnect=true", "USERNAME" : "root", "PASSWORD" : "root" } ] } { "_id" : ObjectId("5ea6f558551299a9f98c93c7"), "PortalName" : "WebMyBusinessApplication", "ApplicationConfiguration" : [ { "URL" : "jdbc:oracle:thin:@localhost:1521:xe", "USERNAME" : "App", "PASSWORD" : "App" } ] } Following is the query to update − > db.demo706.update({PortalName: "WebMyBusinessApplication"},{$set:{"PortalName":"OnlineCustomerTracker"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 }) Display all documents from a collection with the help of find() method − > db.demo706.find(); This will produce the following output − { "_id" : ObjectId("5ea6f557551299a9f98c93c6"), "PortalName" : "GameApplication", "ApplicationConfiguration" : [ { "URL" : "jdbc:mysql://localhost/customer_tracker?autoReconnect=true", "USERNAME" : "root", "PASSWORD" : "root" } ] } { "_id" : ObjectId("5ea6f558551299a9f98c93c7"), "PortalName" : "OnlineCustomerTracker", "ApplicationConfiguration" : [ { "URL" : "jdbc:oracle:thin:@localhost:1521:xe", "USERNAME" : "App", "PASSWORD" : "App" } ] }
[ { "code": null, "e": 1121, "s": 1062, "text": "Following is the syntax showing document and subdocument −" }, { "code": null, "e": 1364, "s": 1121, "text": "db.yourCollectionName.insertOne(\n {\n yourFiledName:yourValue,\n yourFieldName : [\n {\n yourFiledName1,\n yourFiledName2,\n .\n .\n .\n N\n }\n ]\n }\n);" }, { "code": null, "e": 1423, "s": 1364, "text": "Let us see an example create a collection with documents −" }, { "code": null, "e": 2233, "s": 1423, "text": "> db.demo706.insertOne(\n... {\n... PortalName: \"GameApplication\",\n... ApplicationConfiguration : [\n... {\n... \"URL\": \"jdbc:mysql://localhost/customer_tracker?autoReconnect=true\",\n... \"USERNAME\": \"root\",\n... \"PASSWORD\": \"root\"\n... }\n... ]\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea6f557551299a9f98c93c6\")\n}\n>\n> db.demo706.insertOne(\n... {\n... PortalName: \"WebMyBusinessApplication\",\n... ApplicationConfiguration : [\n... {\n... \"URL\": \"jdbc:oracle:thin:@localhost:1521:xe\",\n... \"USERNAME\": \"App\",\n... \"PASSWORD\": \"App\"\n... }\n... ]\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5ea6f558551299a9f98c93c7\")\n}" }, { "code": null, "e": 2306, "s": 2233, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 2327, "s": 2306, "text": "> db.demo706.find();" }, { "code": null, "e": 2368, "s": 2327, "text": "This will produce the following output −" }, { "code": null, "e": 2816, "s": 2368, "text": "{ \"_id\" : ObjectId(\"5ea6f557551299a9f98c93c6\"), \"PortalName\" : \"GameApplication\", \"ApplicationConfiguration\" : [ { \"URL\" : \"jdbc:mysql://localhost/customer_tracker?autoReconnect=true\", \"USERNAME\" : \"root\", \"PASSWORD\" : \"root\" } ] }\n{ \"_id\" : ObjectId(\"5ea6f558551299a9f98c93c7\"), \"PortalName\" : \"WebMyBusinessApplication\", \"ApplicationConfiguration\" : [ { \"URL\" : \"jdbc:oracle:thin:@localhost:1521:xe\", \"USERNAME\" : \"App\", \"PASSWORD\" : \"App\" } ] }" }, { "code": null, "e": 2851, "s": 2816, "text": "Following is the query to update −" }, { "code": null, "e": 3026, "s": 2851, "text": "> db.demo706.update({PortalName: \"WebMyBusinessApplication\"},{$set:{\"PortalName\":\"OnlineCustomerTracker\"}});\nWriteResult({ \"nMatched\" : 1, \"nUpserted\" : 0, \"nModified\" : 1 })" }, { "code": null, "e": 3099, "s": 3026, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 3120, "s": 3099, "text": "> db.demo706.find();" }, { "code": null, "e": 3161, "s": 3120, "text": "This will produce the following output −" }, { "code": null, "e": 3606, "s": 3161, "text": "{ \"_id\" : ObjectId(\"5ea6f557551299a9f98c93c6\"), \"PortalName\" : \"GameApplication\", \"ApplicationConfiguration\" : [ { \"URL\" : \"jdbc:mysql://localhost/customer_tracker?autoReconnect=true\", \"USERNAME\" : \"root\", \"PASSWORD\" : \"root\" } ] }\n{ \"_id\" : ObjectId(\"5ea6f558551299a9f98c93c7\"), \"PortalName\" : \"OnlineCustomerTracker\", \"ApplicationConfiguration\" : [ { \"URL\" : \"jdbc:oracle:thin:@localhost:1521:xe\", \"USERNAME\" : \"App\", \"PASSWORD\" : \"App\" } ] }" } ]
AWK - Logical Operators
AWK supports the following logical operators − It is represented by &&. Its syntax is as follows − expr1 && expr2 It evaluates to true if both expr1 and expr2 evaluate to true; otherwise it returns false. expr2 is evaluated if and only if expr1 evaluates to true. For instance, the following example checks whether the given single digit number is in octal format or not. [jerry]$ awk 'BEGIN { num = 5; if (num >= 0 && num <= 7) printf "%d is in octal format\n", num }' On executing this code, you get the following result − 5 is in octal format It is represented by ||. The syntax of Logical OR is − expr1 || expr2 It evaluates to true if either expr1 or expr2 evaluates to true; otherwise it returns false. expr2 is evaluated if and only if expr1 evaluates to false. The following example demonstrates this − [jerry]$ awk 'BEGIN { ch = "\n"; if (ch == " " || ch == "\t" || ch == "\n") print "Current character is whitespace." }' On executing this code, you get the following result − Current character is whitespace It is represented by exclamation mark (!). The following example demonstrates this − ! expr1 It returns the logical compliment of expr1. If expr1 evaluates to true, it returns 0; otherwise it returns 1. For instance, the following example checks whether a string is empty or not. [jerry]$ awk 'BEGIN { name = ""; if (! length(name)) print "name is empty string." }' On executing this code, you get the following result − name is empty string. Print Add Notes Bookmark this page
[ { "code": null, "e": 1904, "s": 1857, "text": "AWK supports the following logical operators −" }, { "code": null, "e": 1956, "s": 1904, "text": "It is represented by &&. Its syntax is as follows −" }, { "code": null, "e": 1972, "s": 1956, "text": "expr1 && expr2\n" }, { "code": null, "e": 2230, "s": 1972, "text": "It evaluates to true if both expr1 and expr2 evaluate to true; otherwise it returns false. expr2 is evaluated if and only if expr1 evaluates to true. For instance, the following example checks whether the given single digit number is in octal format or not." }, { "code": null, "e": 2332, "s": 2230, "text": "[jerry]$ awk 'BEGIN {\n num = 5; if (num >= 0 && num <= 7) printf \"%d is in octal format\\n\", num \n}'" }, { "code": null, "e": 2387, "s": 2332, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2409, "s": 2387, "text": "5 is in octal format\n" }, { "code": null, "e": 2464, "s": 2409, "text": "It is represented by ||. The syntax of Logical OR is −" }, { "code": null, "e": 2480, "s": 2464, "text": "expr1 || expr2\n" }, { "code": null, "e": 2675, "s": 2480, "text": "It evaluates to true if either expr1 or expr2 evaluates to true; otherwise it returns false. expr2 is evaluated if and only if expr1 evaluates to false. The following example demonstrates this −" }, { "code": null, "e": 2803, "s": 2675, "text": "[jerry]$ awk 'BEGIN {\n ch = \"\\n\"; if (ch == \" \" || ch == \"\\t\" || ch == \"\\n\") \n print \"Current character is whitespace.\" \n}'" }, { "code": null, "e": 2858, "s": 2803, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 2891, "s": 2858, "text": "Current character is whitespace\n" }, { "code": null, "e": 2976, "s": 2891, "text": "It is represented by exclamation mark (!). The following example demonstrates this −" }, { "code": null, "e": 2984, "s": 2976, "text": "! expr1" }, { "code": null, "e": 3171, "s": 2984, "text": "It returns the logical compliment of expr1. If expr1 evaluates to true, it returns 0; otherwise it returns 1. For instance, the following example checks whether a string is empty or not." }, { "code": null, "e": 3257, "s": 3171, "text": "[jerry]$ awk 'BEGIN { name = \"\"; if (! length(name)) print \"name is empty string.\" }'" }, { "code": null, "e": 3312, "s": 3257, "text": "On executing this code, you get the following result −" }, { "code": null, "e": 3335, "s": 3312, "text": "name is empty string.\n" }, { "code": null, "e": 3342, "s": 3335, "text": " Print" }, { "code": null, "e": 3353, "s": 3342, "text": " Add Notes" } ]
Enrich your Jupyter Notebook with these tips | by Zolzaya Luvsandorj | Towards Data Science
One beautiful feature of Jupyter Notebook (Notebook from here onwards) is the ability to use markdown cells alongside code cells. These markdown cells enable us to document more expressively and clearly so that it’s easier for future users to understand the workflow of the Notebook. In this post, I share a few of my tips to enrich documentation in the markdown cells without having to install any extensions. If you have been using Notebook, you probably already know the basics of Markdown. In case you need a refresher, here’s a one-minute introduction to Markdown on its commonly used syntax: #### Headers# Header 1 ## Header 2#### Styles*Italic*, **bold**, _underscore_, ~~strikethrough~~#### Hyperlink[hyperlink](https://www.markdownguide.org/)#### Table| Default | Left-aligned | Center-aligned | Right-aligned ||---------|:-------------|:--------------:|--------------:|| Default | Left | Center | Right |#### Others* Bulleted item 1 * Bulleted subitem 1* Bulleted item 2***1. Ordered item 1 1.1. Ordered subitem 1 2. Ordered item 2***- [ ] Unchecked box- [x] Checked box Its rendered output: Italic, bold, underscore, strikethrough hyperlink Bulleted item 1 Bulleted subitem 1 Bulleted subitem 1 Bulleted item 2 Ordered item 1 1.1. Ordered subitem 1 Ordered item 2 Ordered item 1 1.1. Ordered subitem 1 Ordered item 2 Unchecked box Checked box Having refreshed the basics, it’s time to look at more sophisticated features of Markdown cells to enrich documentation for improved readability. Big chunk of text in black and white can be discouraging to read. One way to enrich black and white text and improve readability of the text is to add colours to highlight and pop key parts. Here are three different ways to add colour to the text: We can change the colour of the text using the html <font> tag. We can use colour names or hexadecimal colour code: Example: <font color=green>green text</font>, <font color=blue>*blue italised text*</font> and <font color=#FF0000>**red bold text**</font>. If you would like to explore more colour names, this may come in handy. If colour names don’t quite capture what you are after, you can explore hexadecimal colours to access a wider range of options. Here’s my favourite resource to explore hexadecimal colours. We can also highlight text with the html <mark> tag: In addition, we can also <mark>highlight text</mark>. It’s now easier to draw attention to the highlighted part of the text. Lastly, we can format the background and font colour using bootstrap alert to make the text documentation more engaging to read: <div class="alert alert-info">Example text highlighted in blue background.</div><div class="alert alert-success">Example text highlighted in green background.</div><div class="alert alert-warning">Example text highlighted in yellow background.</div><div class="alert alert-danger">Example text highlighted in red background.</div> These formats are beautiful! Adding colours can immediately improve the readability of your Notebook documentation by making key points stand out and making the documentation less boring. This way, it becomes easier to skim and get the main points quickly. Another way to enrich documentation is to use suitable richer formats of texts. Let’s look at three different ways to format text: There is often a need to reference mathematical equations in Notebook documentations. With $, we can use LaTeX to show nicely formatted math formulas: $$logloss(\theta) = - {1 \over m} \sum_{i=1}^m (y_i \ln(\hat p(y_i=1)) + (1-y_i) \ln(1-\hat p(y_i=1)))$$ When the equation is wrapped with double $, it will be centre-aligned. If we use single $ , it will be left-aligned. Alternatively, we can also use this syntax to write the formula: \begin{equation} logloss(\theta) = - {1 \over m} \sum_{i=1}^m (y_i \ln(\hat p(y_i=1)) + (1-y_i) \ln(1-\hat p(y_i=1))) \end{equation} If you are not familiar with LaTeX, check out this guide or this one to get started. At times, it’s useful to show code references in markdown cells instead of running them in code cells. We can use single backticks ` to show a code block inline: If you haven't installed textblob, you can install it with: `pip install texblob`. For a bigger chunk of code, we can use triple backticks ``` : If you haven't installed libraries, you can install them with the following command:```conda install pandas, numpy, sklearn -ypip install textblob``` If we specify the language name after the first triple `, code block gets formatted colourfully where applicable: ```python{"minimum": 10, "maximum": 50, "name": "optimiser"}``` Indentation is another way to format text to improve readability. We can add indentation with >: Sample non-indented sentence here.> **Note:** Indented text. ‘A picture is worth a thousand words.’ Documentation doesn’t always have to be in words. Images and other media can help us communicate ideas that are otherwise difficult to express with text. Adding relevant media is another great way to enrich documentation with the necessary information for future users. We can add images to markdown cells using the html <img> tag: <img src="example.jpeg"> Here, example.jpeg is saved in the same folder as the notebook. We can change the size of the image use width or height arguments. For instance, <img src=”example.jpeg” width=500> will resize the image displayed to the desired width while maintaining the width to height ratio. If adding diagrams, charts or other data visualisations in static image doesn’t quite capture what we want to convey, we can embed GIF, an animated image using the exact same syntax structure: <img src="example.gif"/> The path of the file can be a web link too: <img src="https://media.giphy.com/media/XtdLpKOzoxJCzlFY4n/giphy.gif"> ‘A (one-minute) video is worth 1.8 million words.’ If GIFs are not enough, the next level is to use videos. We can use the html <video> tag to display a video: <video controls src="example.mp4" width=600/> For instance, screen recording how to complete a task, saving it as video file and embedding the video in the Notebook can be useful for future users. A long paragraph of plain text can be boring and not appealing to read. Adding shapes and emojis tastefully can make text more interesting and appealing to read: &#10148; Bullet point one</br>&#10148; Bullet point two</br>&#10148; Bullet point three ✅ Sample text A</br>✅ Sample text B</br>✅ Sample text C Check out this to explore more shapes (and emojis). This emoji cheat-sheet is useful when searching emoji by name. Voila! These were my tips for enriching Jupyter Notebook documentation.✨ We may not use all of these features at once. But knowing how to use these prepares you when the right opportunity arises. Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me. Thank you for reading my post. If you want to learn more about Markdown, check out this guide. If you are interested, here are links to some of my posts: ◼️ Organise your Jupyter Notebook with these tips◼️ Useful IPython magic commands◼️ Introduction to Python Virtual Environment for Data Science◼️ Introduction to Git for Data Science◼️ Simple data visualisations in Python that you will find useful◼️ 6 simple tips for prettier and customised plots in Seaborn (Python)◼️️ 5 tips for pandas users◼️️ Writing 5 common SQL queries in pandas Bye for now 🏃💨
[ { "code": null, "e": 583, "s": 172, "text": "One beautiful feature of Jupyter Notebook (Notebook from here onwards) is the ability to use markdown cells alongside code cells. These markdown cells enable us to document more expressively and clearly so that it’s easier for future users to understand the workflow of the Notebook. In this post, I share a few of my tips to enrich documentation in the markdown cells without having to install any extensions." }, { "code": null, "e": 770, "s": 583, "text": "If you have been using Notebook, you probably already know the basics of Markdown. In case you need a refresher, here’s a one-minute introduction to Markdown on its commonly used syntax:" }, { "code": null, "e": 1262, "s": 770, "text": "#### Headers# Header 1 ## Header 2#### Styles*Italic*, **bold**, _underscore_, ~~strikethrough~~#### Hyperlink[hyperlink](https://www.markdownguide.org/)#### Table| Default | Left-aligned | Center-aligned | Right-aligned ||---------|:-------------|:--------------:|--------------:|| Default | Left | Center | Right |#### Others* Bulleted item 1 * Bulleted subitem 1* Bulleted item 2***1. Ordered item 1 1.1. Ordered subitem 1 2. Ordered item 2***- [ ] Unchecked box- [x] Checked box" }, { "code": null, "e": 1283, "s": 1262, "text": "Its rendered output:" }, { "code": null, "e": 1323, "s": 1283, "text": "Italic, bold, underscore, strikethrough" }, { "code": null, "e": 1333, "s": 1323, "text": "hyperlink" }, { "code": null, "e": 1371, "s": 1333, "text": "Bulleted item 1\n\nBulleted subitem 1\n\n" }, { "code": null, "e": 1390, "s": 1371, "text": "Bulleted subitem 1" }, { "code": null, "e": 1406, "s": 1390, "text": "Bulleted item 2" }, { "code": null, "e": 1461, "s": 1406, "text": "\nOrdered item 1\n1.1. Ordered subitem 1\nOrdered item 2\n" }, { "code": null, "e": 1499, "s": 1461, "text": "Ordered item 1\n1.1. Ordered subitem 1" }, { "code": null, "e": 1514, "s": 1499, "text": "Ordered item 2" }, { "code": null, "e": 1529, "s": 1514, "text": " Unchecked box" }, { "code": null, "e": 1542, "s": 1529, "text": " Checked box" }, { "code": null, "e": 1688, "s": 1542, "text": "Having refreshed the basics, it’s time to look at more sophisticated features of Markdown cells to enrich documentation for improved readability." }, { "code": null, "e": 1936, "s": 1688, "text": "Big chunk of text in black and white can be discouraging to read. One way to enrich black and white text and improve readability of the text is to add colours to highlight and pop key parts. Here are three different ways to add colour to the text:" }, { "code": null, "e": 2052, "s": 1936, "text": "We can change the colour of the text using the html <font> tag. We can use colour names or hexadecimal colour code:" }, { "code": null, "e": 2193, "s": 2052, "text": "Example: <font color=green>green text</font>, <font color=blue>*blue italised text*</font> and <font color=#FF0000>**red bold text**</font>." }, { "code": null, "e": 2454, "s": 2193, "text": "If you would like to explore more colour names, this may come in handy. If colour names don’t quite capture what you are after, you can explore hexadecimal colours to access a wider range of options. Here’s my favourite resource to explore hexadecimal colours." }, { "code": null, "e": 2507, "s": 2454, "text": "We can also highlight text with the html <mark> tag:" }, { "code": null, "e": 2561, "s": 2507, "text": "In addition, we can also <mark>highlight text</mark>." }, { "code": null, "e": 2632, "s": 2561, "text": "It’s now easier to draw attention to the highlighted part of the text." }, { "code": null, "e": 2761, "s": 2632, "text": "Lastly, we can format the background and font colour using bootstrap alert to make the text documentation more engaging to read:" }, { "code": null, "e": 3092, "s": 2761, "text": "<div class=\"alert alert-info\">Example text highlighted in blue background.</div><div class=\"alert alert-success\">Example text highlighted in green background.</div><div class=\"alert alert-warning\">Example text highlighted in yellow background.</div><div class=\"alert alert-danger\">Example text highlighted in red background.</div>" }, { "code": null, "e": 3349, "s": 3092, "text": "These formats are beautiful! Adding colours can immediately improve the readability of your Notebook documentation by making key points stand out and making the documentation less boring. This way, it becomes easier to skim and get the main points quickly." }, { "code": null, "e": 3480, "s": 3349, "text": "Another way to enrich documentation is to use suitable richer formats of texts. Let’s look at three different ways to format text:" }, { "code": null, "e": 3631, "s": 3480, "text": "There is often a need to reference mathematical equations in Notebook documentations. With $, we can use LaTeX to show nicely formatted math formulas:" }, { "code": null, "e": 3738, "s": 3631, "text": "$$logloss(\\theta) = - {1 \\over m} \\sum_{i=1}^m (y_i \\ln(\\hat p(y_i=1)) + (1-y_i) \\ln(1-\\hat p(y_i=1)))$$" }, { "code": null, "e": 3920, "s": 3738, "text": "When the equation is wrapped with double $, it will be centre-aligned. If we use single $ , it will be left-aligned. Alternatively, we can also use this syntax to write the formula:" }, { "code": null, "e": 4055, "s": 3920, "text": "\\begin{equation} logloss(\\theta) = - {1 \\over m} \\sum_{i=1}^m (y_i \\ln(\\hat p(y_i=1)) + (1-y_i) \\ln(1-\\hat p(y_i=1))) \\end{equation}" }, { "code": null, "e": 4140, "s": 4055, "text": "If you are not familiar with LaTeX, check out this guide or this one to get started." }, { "code": null, "e": 4302, "s": 4140, "text": "At times, it’s useful to show code references in markdown cells instead of running them in code cells. We can use single backticks ` to show a code block inline:" }, { "code": null, "e": 4385, "s": 4302, "text": "If you haven't installed textblob, you can install it with: `pip install texblob`." }, { "code": null, "e": 4447, "s": 4385, "text": "For a bigger chunk of code, we can use triple backticks ``` :" }, { "code": null, "e": 4597, "s": 4447, "text": "If you haven't installed libraries, you can install them with the following command:```conda install pandas, numpy, sklearn -ypip install textblob```" }, { "code": null, "e": 4711, "s": 4597, "text": "If we specify the language name after the first triple `, code block gets formatted colourfully where applicable:" }, { "code": null, "e": 4775, "s": 4711, "text": "```python{\"minimum\": 10, \"maximum\": 50, \"name\": \"optimiser\"}```" }, { "code": null, "e": 4872, "s": 4775, "text": "Indentation is another way to format text to improve readability. We can add indentation with >:" }, { "code": null, "e": 4933, "s": 4872, "text": "Sample non-indented sentence here.> **Note:** Indented text." }, { "code": null, "e": 4972, "s": 4933, "text": "‘A picture is worth a thousand words.’" }, { "code": null, "e": 5242, "s": 4972, "text": "Documentation doesn’t always have to be in words. Images and other media can help us communicate ideas that are otherwise difficult to express with text. Adding relevant media is another great way to enrich documentation with the necessary information for future users." }, { "code": null, "e": 5304, "s": 5242, "text": "We can add images to markdown cells using the html <img> tag:" }, { "code": null, "e": 5329, "s": 5304, "text": "<img src=\"example.jpeg\">" }, { "code": null, "e": 5607, "s": 5329, "text": "Here, example.jpeg is saved in the same folder as the notebook. We can change the size of the image use width or height arguments. For instance, <img src=”example.jpeg” width=500> will resize the image displayed to the desired width while maintaining the width to height ratio." }, { "code": null, "e": 5800, "s": 5607, "text": "If adding diagrams, charts or other data visualisations in static image doesn’t quite capture what we want to convey, we can embed GIF, an animated image using the exact same syntax structure:" }, { "code": null, "e": 5825, "s": 5800, "text": "<img src=\"example.gif\"/>" }, { "code": null, "e": 5869, "s": 5825, "text": "The path of the file can be a web link too:" }, { "code": null, "e": 5940, "s": 5869, "text": "<img src=\"https://media.giphy.com/media/XtdLpKOzoxJCzlFY4n/giphy.gif\">" }, { "code": null, "e": 5991, "s": 5940, "text": "‘A (one-minute) video is worth 1.8 million words.’" }, { "code": null, "e": 6100, "s": 5991, "text": "If GIFs are not enough, the next level is to use videos. We can use the html <video> tag to display a video:" }, { "code": null, "e": 6147, "s": 6100, "text": "<video controls src=\"example.mp4\" width=600/>" }, { "code": null, "e": 6298, "s": 6147, "text": "For instance, screen recording how to complete a task, saving it as video file and embedding the video in the Notebook can be useful for future users." }, { "code": null, "e": 6460, "s": 6298, "text": "A long paragraph of plain text can be boring and not appealing to read. Adding shapes and emojis tastefully can make text more interesting and appealing to read:" }, { "code": null, "e": 6548, "s": 6460, "text": "&#10148; Bullet point one</br>&#10148; Bullet point two</br>&#10148; Bullet point three" }, { "code": null, "e": 6604, "s": 6548, "text": "✅ Sample text A</br>✅ Sample text B</br>✅ Sample text C" }, { "code": null, "e": 6719, "s": 6604, "text": "Check out this to explore more shapes (and emojis). This emoji cheat-sheet is useful when searching emoji by name." }, { "code": null, "e": 6915, "s": 6719, "text": "Voila! These were my tips for enriching Jupyter Notebook documentation.✨ We may not use all of these features at once. But knowing how to use these prepares you when the right opportunity arises." }, { "code": null, "e": 7139, "s": 6915, "text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me." }, { "code": null, "e": 7293, "s": 7139, "text": "Thank you for reading my post. If you want to learn more about Markdown, check out this guide. If you are interested, here are links to some of my posts:" }, { "code": null, "e": 7680, "s": 7293, "text": "◼️ Organise your Jupyter Notebook with these tips◼️ Useful IPython magic commands◼️ Introduction to Python Virtual Environment for Data Science◼️ Introduction to Git for Data Science◼️ Simple data visualisations in Python that you will find useful◼️ 6 simple tips for prettier and customised plots in Seaborn (Python)◼️️ 5 tips for pandas users◼️️ Writing 5 common SQL queries in pandas" } ]
Scala Collections - Flatten Method
flatten() method is a member GenericTraversableTemplate trait, it returns a single collection of elements by merging child collections. The following is the syntax of flatten method. def flatten[B]: Traversable[B] Here, f: (A) ? GenTraversableOnce[B] is a predicate or condition to be applied on each element of the collection. This method returns the Option element containing the matched element of iterator which satisfiles the given condition. Below is an example program of showing how to use flatten method − object Demo { def main(args: Array[String]) = { val list = List(List(1,2), List(3,4)) //apply operation val result = list.flatten //print result println(result) } } Save the above program in Demo.scala. The following commands are used to compile and execute this program. \>scalac Demo.scala \>scala Demo List(1, 2, 3, 4) 82 Lectures 7 hours Arnab Chakraborty 23 Lectures 1.5 hours Mukund Kumar Mishra 52 Lectures 1.5 hours Bigdata Engineer 76 Lectures 5.5 hours Bigdata Engineer 69 Lectures 7.5 hours Bigdata Engineer 46 Lectures 4.5 hours Stone River ELearning Print Add Notes Bookmark this page
[ { "code": null, "e": 3019, "s": 2882, "text": "flatten() method is a member GenericTraversableTemplate trait, it returns a single collection of elements by merging child collections." }, { "code": null, "e": 3066, "s": 3019, "text": "The following is the syntax of flatten method." }, { "code": null, "e": 3098, "s": 3066, "text": "def flatten[B]: Traversable[B]\n" }, { "code": null, "e": 3332, "s": 3098, "text": "Here, f: (A) ? GenTraversableOnce[B] is a predicate or condition to be applied on each element of the collection. This method returns the Option element containing the matched element of iterator which satisfiles the given condition." }, { "code": null, "e": 3399, "s": 3332, "text": "Below is an example program of showing how to use flatten method −" }, { "code": null, "e": 3606, "s": 3399, "text": "object Demo {\n def main(args: Array[String]) = {\n val list = List(List(1,2), List(3,4))\n //apply operation\n val result = list.flatten\n //print result\n println(result) \n }\n}" }, { "code": null, "e": 3713, "s": 3606, "text": "Save the above program in Demo.scala. The following commands are used to compile and execute this program." }, { "code": null, "e": 3747, "s": 3713, "text": "\\>scalac Demo.scala\n\\>scala Demo\n" }, { "code": null, "e": 3765, "s": 3747, "text": "List(1, 2, 3, 4)\n" }, { "code": null, "e": 3798, "s": 3765, "text": "\n 82 Lectures \n 7 hours \n" }, { "code": null, "e": 3817, "s": 3798, "text": " Arnab Chakraborty" }, { "code": null, "e": 3852, "s": 3817, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3873, "s": 3852, "text": " Mukund Kumar Mishra" }, { "code": null, "e": 3908, "s": 3873, "text": "\n 52 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3926, "s": 3908, "text": " Bigdata Engineer" }, { "code": null, "e": 3961, "s": 3926, "text": "\n 76 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3979, "s": 3961, "text": " Bigdata Engineer" }, { "code": null, "e": 4014, "s": 3979, "text": "\n 69 Lectures \n 7.5 hours \n" }, { "code": null, "e": 4032, "s": 4014, "text": " Bigdata Engineer" }, { "code": null, "e": 4067, "s": 4032, "text": "\n 46 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4090, "s": 4067, "text": " Stone River ELearning" }, { "code": null, "e": 4097, "s": 4090, "text": " Print" }, { "code": null, "e": 4108, "s": 4097, "text": " Add Notes" } ]
Lodash _.findIndex() Method - GeeksforGeeks
14 Jul, 2020 Lodash is a module in Node.js that works on the top of Underscore.js. Lodash helps in working with arrays, strings, objects, numbers etc.The Loadsh.findIndex() method is used to find the index of the first occurrence of the element. It is different from indexOf because it takes the predicate function that iterates through each element of the array. Syntax: findIndex(array, [predicate=_.identity], fromIndex) Parameter: This method accepts three parameters as mentioned above and described below: array: It is the array in which the value is to be searched. predicate: It is the function that iterate through each element. fromIndex: It is the index after which the element is to be searched. If from index is not given by default it will be 0. Return Value: It return the index of the element if found else -1 is returned. Note: Please install lodash module by using command npm install lodash before using the code given below. Example 1: When element is search start from index 0. Javascript // Requiring the lodash libraryconst _ = require('lodash'); // Original arraylet array1 = [4, 2, 3, 1, 4, 2] // Using lodash.findIndexlet index = _.findIndex(array1, (e) => { return e == 1;}, 0); // Print original Arrayconsole.log("original Array: ", array1) // Printing the indexconsole.log("index: ", index) Output : Example 2: When element is looked after some index “i”. Here element is present in the array but still the output is -1 because it is present at index 3 and the searching starts from index 5. Javascript // Requiring the lodash libraryconst _ = require('lodash'); // Original arraylet array1 = [4, 2, 3, 1, 4, 2] // Using lodash.findIndexlet index = _.findIndex(array1, (e) => { return e == 1;}, 5); // Print original Arrayconsole.log("original Array: ", array1) // Printing the indexconsole.log("index: ", index) Output: JavaScript-Lodash JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React File uploading in React.js Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 37356, "s": 37328, "text": "\n14 Jul, 2020" }, { "code": null, "e": 37707, "s": 37356, "text": "Lodash is a module in Node.js that works on the top of Underscore.js. Lodash helps in working with arrays, strings, objects, numbers etc.The Loadsh.findIndex() method is used to find the index of the first occurrence of the element. It is different from indexOf because it takes the predicate function that iterates through each element of the array." }, { "code": null, "e": 37715, "s": 37707, "text": "Syntax:" }, { "code": null, "e": 37767, "s": 37715, "text": "findIndex(array, [predicate=_.identity], fromIndex)" }, { "code": null, "e": 37855, "s": 37767, "text": "Parameter: This method accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 37916, "s": 37855, "text": "array: It is the array in which the value is to be searched." }, { "code": null, "e": 37981, "s": 37916, "text": "predicate: It is the function that iterate through each element." }, { "code": null, "e": 38103, "s": 37981, "text": "fromIndex: It is the index after which the element is to be searched. If from index is not given by default it will be 0." }, { "code": null, "e": 38182, "s": 38103, "text": "Return Value: It return the index of the element if found else -1 is returned." }, { "code": null, "e": 38288, "s": 38182, "text": "Note: Please install lodash module by using command npm install lodash before using the code given below." }, { "code": null, "e": 38342, "s": 38288, "text": "Example 1: When element is search start from index 0." }, { "code": null, "e": 38353, "s": 38342, "text": "Javascript" }, { "code": "// Requiring the lodash libraryconst _ = require('lodash'); // Original arraylet array1 = [4, 2, 3, 1, 4, 2] // Using lodash.findIndexlet index = _.findIndex(array1, (e) => { return e == 1;}, 0); // Print original Arrayconsole.log(\"original Array: \", array1) // Printing the indexconsole.log(\"index: \", index)", "e": 38670, "s": 38353, "text": null }, { "code": null, "e": 38679, "s": 38670, "text": "Output :" }, { "code": null, "e": 38871, "s": 38679, "text": "Example 2: When element is looked after some index “i”. Here element is present in the array but still the output is -1 because it is present at index 3 and the searching starts from index 5." }, { "code": null, "e": 38882, "s": 38871, "text": "Javascript" }, { "code": "// Requiring the lodash libraryconst _ = require('lodash'); // Original arraylet array1 = [4, 2, 3, 1, 4, 2] // Using lodash.findIndexlet index = _.findIndex(array1, (e) => { return e == 1;}, 5); // Print original Arrayconsole.log(\"original Array: \", array1) // Printing the indexconsole.log(\"index: \", index)", "e": 39199, "s": 38882, "text": null }, { "code": null, "e": 39207, "s": 39199, "text": "Output:" }, { "code": null, "e": 39225, "s": 39207, "text": "JavaScript-Lodash" }, { "code": null, "e": 39236, "s": 39225, "text": "JavaScript" }, { "code": null, "e": 39253, "s": 39236, "text": "Web Technologies" }, { "code": null, "e": 39351, "s": 39253, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39360, "s": 39351, "text": "Comments" }, { "code": null, "e": 39373, "s": 39360, "text": "Old Comments" }, { "code": null, "e": 39418, "s": 39373, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 39487, "s": 39418, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 39548, "s": 39487, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 39620, "s": 39548, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 39647, "s": 39620, "text": "File uploading in React.js" }, { "code": null, "e": 39689, "s": 39647, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 39722, "s": 39689, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39784, "s": 39722, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 39827, "s": 39784, "text": "How to fetch data from an API in ReactJS ?" } ]
Tryit Editor v3.7
Tryit: HTML table rows
[]
Program for Volume and Surface Area of Cuboid in C++
Cuboid is a three-dimensional object with six faces of rectangle shape which means it has sides of different length and breadth. The difference between a cube and cuboid is that a cube has equal length, height and breadth whereas in cuboids these three are not same Properties of cuboid are − six faces 12 edges 8 vertices Given below is the figure of cube Given with the length, width and volume, the task is to find the total surface area and volume of a cuboid where surface area is the space occupied by the faces and volume is the space that a shape can contain. To calculate surface area and volume of a cuboid there is a formula Surface Area = 2(|*w + w * h + |*h ) Volume = L* W * H Input-: L=3 H=2 W=3 Output-: Volume of cuboid is: 18 Total Surface Area of cuboid is: 42 Start Step 1 -> declare function to find volume of cuboid double volume(double l, double h, double w) return (l*h*w) Step 2 -> declare function to find area of cuboid double surface_area(double l, double h, double w) return (2 * l * w + 2 * w * h + 2 * l * h) Step 3 -> In main() Declare variable double l=3, h=2 and w=3 Print volume(l,h,w) Print surface_area(l, h ,w) Stop #include <bits/stdc++.h> using namespace std; //function for volume of cuboid double volume(double l, double h, double w){ return (l * h * w); } //function for total surface area of cuboid double surface_area(double l, double h, double w){ return (2 * l * w + 2 * w * h + 2 * l * h); } int main(){ double l = 3; double h = 2; double w = 3; cout << "Volume of cuboid is: " <<volume(l, h, w) << endl; cout << "Total Surface Area of cuboid is: "<< surface_area(l, h, w); return 0; } Volume of cuboid is: 18 Total Surface Area of cuboid is: 42
[ { "code": null, "e": 1328, "s": 1062, "text": "Cuboid is a three-dimensional object with six faces of rectangle shape which means it has sides of different length and breadth. The difference between a cube and cuboid is that a cube has equal length, height and breadth whereas in cuboids these three are not same" }, { "code": null, "e": 1355, "s": 1328, "text": "Properties of cuboid are −" }, { "code": null, "e": 1365, "s": 1355, "text": "six faces" }, { "code": null, "e": 1374, "s": 1365, "text": "12 edges" }, { "code": null, "e": 1385, "s": 1374, "text": "8 vertices" }, { "code": null, "e": 1419, "s": 1385, "text": "Given below is the figure of cube" }, { "code": null, "e": 1630, "s": 1419, "text": "Given with the length, width and volume, the task is to find the total surface area and volume of a cuboid where surface area is the space occupied by the faces and volume is the space that a shape can contain." }, { "code": null, "e": 1698, "s": 1630, "text": "To calculate surface area and volume of a cuboid there is a formula" }, { "code": null, "e": 1735, "s": 1698, "text": "Surface Area = 2(|*w + w * h + |*h )" }, { "code": null, "e": 1753, "s": 1735, "text": "Volume = L* W * H" }, { "code": null, "e": 1845, "s": 1753, "text": "Input-: L=3 H=2 W=3\nOutput-: Volume of cuboid is: 18\n Total Surface Area of cuboid is: 42" }, { "code": null, "e": 2246, "s": 1845, "text": "Start\nStep 1 -> declare function to find volume of cuboid\n double volume(double l, double h, double w)\n return (l*h*w)\nStep 2 -> declare function to find area of cuboid\n double surface_area(double l, double h, double w)\n return (2 * l * w + 2 * w * h + 2 * l * h)\nStep 3 -> In main()\n Declare variable double l=3, h=2 and w=3\n Print volume(l,h,w)\n Print surface_area(l, h ,w)\nStop" }, { "code": null, "e": 2750, "s": 2246, "text": "#include <bits/stdc++.h>\nusing namespace std;\n//function for volume of cuboid\ndouble volume(double l, double h, double w){\n return (l * h * w);\n}\n//function for total surface area of cuboid\ndouble surface_area(double l, double h, double w){\n return (2 * l * w + 2 * w * h + 2 * l * h);\n}\nint main(){\n double l = 3;\n double h = 2;\n double w = 3;\n cout << \"Volume of cuboid is: \" <<volume(l, h, w) << endl;\n cout << \"Total Surface Area of cuboid is: \"<< surface_area(l, h, w);\n return 0;\n}" }, { "code": null, "e": 2810, "s": 2750, "text": "Volume of cuboid is: 18\nTotal Surface Area of cuboid is: 42" } ]
Underscore.js - GeeksforGeeks
17 Dec, 2021 Underscore.js is a lightweight JavaScript library and not a complete framework that was written by Jeremy Ashkenas. It provides utility functions for a variety of use cases in our day-to-day common programming tasks. Underscore.js provides a lot of features that make our task easy to work with objects. It can be used directly inside a browser and also with Node.js. With just under six kilobytes in size, this library basically provides us with a whole bunch of useful JavaScript functions for making our life easier. There are literally hundreds of different functions available that support both our workaday functional helpers such as the map and filter functions, as well as more specialized ones such as JavaScript templating, function binding, deep equality testing, creating quick indexes, and many more. Underscore functions basically falls under four major categories which are functions that can be used for manipulating arrays, functions that can be used for manipulating objects, functions that can be used for manipulating both arrays as well as objects, and functions that can be used for manipulating other functions itself. Installation Process: We can use Underscore.js directly inside the browser and also with node.js. We will discuss both of these methods. Method 1: Use directly inside the browser. Visit the official website (https://underscorejs.org/) and download the latest underscore-min.js file UMD available. After that include the following CDN link inside your code in order to run the underscore.js code inside the browser. Method 2: We can install it with npm. Make sure that you have Node.js and npm installed. npm install underscore You can also install with yarn yarn install underscore Now let’s understand the working of code through an example. Example: In this example, we will simply see how to find the maximum element from the array list passed. For this, we will use _.max() Function. HTML Output: Features of Underscore: Perform common operations of data like arrays, objects, JSON files, etc. Compatible with other JS libraries like jQuery to perform DOM operations. Contains function for data manipulation. Learn more about Underscore.js: Introduction Collections Complete Reference Array Complete Reference Functions Complete Reference Objects Complete Reference Utility Complete Reference Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Program for Breadth First Search or BFS for a Graph Python Program for Find the number of islands | Set 1 (Using DFS) Pandas - Number of Months Between Two Dates 7 Reasons Why You Should Learn SQL in 2022 Psycopg2 - Return dictionary like values Java Program to Rotate bits of a number How to connect MongoDB with ReactJS ? How to use Material-UI with Next.js ? Packaged Task | Advanced C++ (Multithreading & Multiprocessing) How to Fix: ValueError: Operands could not be broadcast together with shapes?
[ { "code": null, "e": 33520, "s": 33492, "text": "\n17 Dec, 2021" }, { "code": null, "e": 33888, "s": 33520, "text": "Underscore.js is a lightweight JavaScript library and not a complete framework that was written by Jeremy Ashkenas. It provides utility functions for a variety of use cases in our day-to-day common programming tasks. Underscore.js provides a lot of features that make our task easy to work with objects. It can be used directly inside a browser and also with Node.js." }, { "code": null, "e": 34662, "s": 33888, "text": "With just under six kilobytes in size, this library basically provides us with a whole bunch of useful JavaScript functions for making our life easier. There are literally hundreds of different functions available that support both our workaday functional helpers such as the map and filter functions, as well as more specialized ones such as JavaScript templating, function binding, deep equality testing, creating quick indexes, and many more. Underscore functions basically falls under four major categories which are functions that can be used for manipulating arrays, functions that can be used for manipulating objects, functions that can be used for manipulating both arrays as well as objects, and functions that can be used for manipulating other functions itself." }, { "code": null, "e": 34799, "s": 34662, "text": "Installation Process: We can use Underscore.js directly inside the browser and also with node.js. We will discuss both of these methods." }, { "code": null, "e": 34845, "s": 34801, "text": "Method 1: Use directly inside the browser. " }, { "code": null, "e": 35080, "s": 34845, "text": "Visit the official website (https://underscorejs.org/) and download the latest underscore-min.js file UMD available. After that include the following CDN link inside your code in order to run the underscore.js code inside the browser." }, { "code": null, "e": 35169, "s": 35080, "text": "Method 2: We can install it with npm. Make sure that you have Node.js and npm installed." }, { "code": null, "e": 35192, "s": 35169, "text": "npm install underscore" }, { "code": null, "e": 35223, "s": 35192, "text": "You can also install with yarn" }, { "code": null, "e": 35247, "s": 35223, "text": "yarn install underscore" }, { "code": null, "e": 35308, "s": 35247, "text": "Now let’s understand the working of code through an example." }, { "code": null, "e": 35453, "s": 35308, "text": "Example: In this example, we will simply see how to find the maximum element from the array list passed. For this, we will use _.max() Function." }, { "code": null, "e": 35458, "s": 35453, "text": "HTML" }, { "code": null, "e": 35466, "s": 35458, "text": "Output:" }, { "code": null, "e": 35490, "s": 35466, "text": "Features of Underscore:" }, { "code": null, "e": 35563, "s": 35490, "text": "Perform common operations of data like arrays, objects, JSON files, etc." }, { "code": null, "e": 35637, "s": 35563, "text": "Compatible with other JS libraries like jQuery to perform DOM operations." }, { "code": null, "e": 35678, "s": 35637, "text": "Contains function for data manipulation." }, { "code": null, "e": 35710, "s": 35678, "text": "Learn more about Underscore.js:" }, { "code": null, "e": 35723, "s": 35710, "text": "Introduction" }, { "code": null, "e": 35754, "s": 35723, "text": "Collections Complete Reference" }, { "code": null, "e": 35779, "s": 35754, "text": "Array Complete Reference" }, { "code": null, "e": 35808, "s": 35779, "text": "Functions Complete Reference" }, { "code": null, "e": 35835, "s": 35808, "text": "Objects Complete Reference" }, { "code": null, "e": 35862, "s": 35835, "text": "Utility Complete Reference" }, { "code": null, "e": 35986, "s": 35862, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 36084, "s": 35986, "text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here." }, { "code": null, "e": 36093, "s": 36084, "text": "Comments" }, { "code": null, "e": 36106, "s": 36093, "text": "Old Comments" }, { "code": null, "e": 36165, "s": 36106, "text": "Python Program for Breadth First Search or BFS for a Graph" }, { "code": null, "e": 36231, "s": 36165, "text": "Python Program for Find the number of islands | Set 1 (Using DFS)" }, { "code": null, "e": 36275, "s": 36231, "text": "Pandas - Number of Months Between Two Dates" }, { "code": null, "e": 36318, "s": 36275, "text": "7 Reasons Why You Should Learn SQL in 2022" }, { "code": null, "e": 36359, "s": 36318, "text": "Psycopg2 - Return dictionary like values" }, { "code": null, "e": 36399, "s": 36359, "text": "Java Program to Rotate bits of a number" }, { "code": null, "e": 36437, "s": 36399, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 36475, "s": 36437, "text": "How to use Material-UI with Next.js ?" }, { "code": null, "e": 36539, "s": 36475, "text": "Packaged Task | Advanced C++ (Multithreading & Multiprocessing)" } ]
How to store array values in MongoDB?
Let us first create a collection with documents wherein we are storing array values − >db.demo321.insertOne({"UserDetails":[{"UserId":101,"UserName":"Chris"},{"UserId":102,"UserName":"Mike"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e511248f8647eb59e56206a") } >db.demo321.insertOne({"UserDetails":[{"UserId":103,"UserName":"Bob"},{"UserId":104,"UserName":"Sam"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e511259f8647eb59e56206b") } Display all documents from a collection with the help of find() method − > db.demo321.find(); This will produce the following output − { "_id" : ObjectId("5e511248f8647eb59e56206a"), "UserDetails" : [ { "UserId" : 101, "UserName" : "Chris" }, { "UserId" : 102, "UserName" : "Mike" } ] } { "_id" : ObjectId("5e511259f8647eb59e56206b"), "UserDetails" : [ { "UserId" : 103, "UserName" : "Bob" }, { "UserId" : 104, "UserName" : "Sam" } ] }
[ { "code": null, "e": 1148, "s": 1062, "text": "Let us first create a collection with documents wherein we are storing array values −" }, { "code": null, "e": 1533, "s": 1148, "text": ">db.demo321.insertOne({\"UserDetails\":[{\"UserId\":101,\"UserName\":\"Chris\"},{\"UserId\":102,\"UserName\":\"Mike\"}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e511248f8647eb59e56206a\")\n}\n>db.demo321.insertOne({\"UserDetails\":[{\"UserId\":103,\"UserName\":\"Bob\"},{\"UserId\":104,\"UserName\":\"Sam\"}]});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5e511259f8647eb59e56206b\")\n}" }, { "code": null, "e": 1606, "s": 1533, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1627, "s": 1606, "text": "> db.demo321.find();" }, { "code": null, "e": 1668, "s": 1627, "text": "This will produce the following output −" }, { "code": null, "e": 1969, "s": 1668, "text": "{ \"_id\" : ObjectId(\"5e511248f8647eb59e56206a\"), \"UserDetails\" : [ { \"UserId\" : 101, \"UserName\" : \"Chris\" }, { \"UserId\" : 102, \"UserName\" : \"Mike\" } ] }\n{ \"_id\" : ObjectId(\"5e511259f8647eb59e56206b\"), \"UserDetails\" : [ { \"UserId\" : 103, \"UserName\" : \"Bob\" }, { \"UserId\" : 104, \"UserName\" : \"Sam\" } ] }" } ]
How to Set the Visibility of the GroupBox in C#? - GeeksforGeeks
02 Aug, 2019 In Windows Forms, GroupBox is a container which contains multiple controls in it and the controls are related to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a GroupBox is used to categorize the related controls in a group. In GroupBox, you can set the visibility of the GroupBox in the form using Visible Property.If the value of this property is set to true, then the GroupBox is visible on the screen, and if the value of this property is set to false, then the GroupBox does not visible on the screen. The default value of this property is true. You can set this property in two different ways: 1. Design-Time: It is the easiest way to set the visibility of the GroupBox as shown in the following steps: Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp Step 2: Next, drag and drop the GroupBox control from the toolbox on the form as shown in the below image: Step 3: After drag and drop you will go to the properties of the GroupBox and set the visibility of the GroupBox as shown in the below image:Output: Output: 2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the visibility of the GroupBox control programmatically with the help of given syntax: public override string Text { get; set; } The following steps show how to set the visibility of the GroupBox dynamically: Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox class.// Creating a GroupBox GroupBox gbox = new GroupBox(); // Creating a GroupBox GroupBox gbox = new GroupBox(); Step 2: After creating GroupBox, set the Visible property of the GroupBox provided by the GroupBox class.// Setting visibility gbox.Visible = true; // Setting visibility gbox.Visible = true; Step 3: And last add this GroupBox control to the form and also add other controls on the GroupBox using the following statements:// Adding groupbox in the form this.Controls.Add(gbox); and // Adding this control // to the GroupBox gbox.Controls.Add(c2); Example:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp46 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // properties of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Text = "Select Gender"; gbox.Name = "Mybox"; gbox.Font = new Font("Colonna MT", 12); gbox.Visible = true; gbox.AutoSize = true; gbox.AutoSizeMode = AutoSizeMode.GrowAndShrink; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(69, 20); c1.Text = "Male"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting // properties of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(79, 20); c2.Text = "Female"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}Output: // Adding groupbox in the form this.Controls.Add(gbox); and // Adding this control // to the GroupBox gbox.Controls.Add(c2); Example: using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp46 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // properties of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Text = "Select Gender"; gbox.Name = "Mybox"; gbox.Font = new Font("Colonna MT", 12); gbox.Visible = true; gbox.AutoSize = true; gbox.AutoSizeMode = AutoSizeMode.GrowAndShrink; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(69, 20); c1.Text = "Male"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting // properties of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(79, 20); c2.Text = "Female"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}} Output: CSharp-Windows-Forms-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Top 50 C# Interview Questions & Answers Extension Method in C# HashSet in C# with Examples Partial Classes in C# C# | Inheritance Convert String to Character Array in C# Linked List Implementation in C# C# | How to insert an element in an Array? C# | List Class Difference between Hashtable and Dictionary in C#
[ { "code": null, "e": 23911, "s": 23883, "text": "\n02 Aug, 2019" }, { "code": null, "e": 24586, "s": 23911, "text": "In Windows Forms, GroupBox is a container which contains multiple controls in it and the controls are related to each other. Or in other words, GroupBox is a frame display around a group of controls with a suitable optional title. Or a GroupBox is used to categorize the related controls in a group. In GroupBox, you can set the visibility of the GroupBox in the form using Visible Property.If the value of this property is set to true, then the GroupBox is visible on the screen, and if the value of this property is set to false, then the GroupBox does not visible on the screen. The default value of this property is true. You can set this property in two different ways:" }, { "code": null, "e": 24695, "s": 24586, "text": "1. Design-Time: It is the easiest way to set the visibility of the GroupBox as shown in the following steps:" }, { "code": null, "e": 24811, "s": 24695, "text": "Step 1: Create a windows form as shown in the below image:Visual Studio -> File -> New -> Project -> WindowsFormApp" }, { "code": null, "e": 24918, "s": 24811, "text": "Step 2: Next, drag and drop the GroupBox control from the toolbox on the form as shown in the below image:" }, { "code": null, "e": 25067, "s": 24918, "text": "Step 3: After drag and drop you will go to the properties of the GroupBox and set the visibility of the GroupBox as shown in the below image:Output:" }, { "code": null, "e": 25075, "s": 25067, "text": "Output:" }, { "code": null, "e": 25254, "s": 25075, "text": "2. Run-Time: It is a little bit trickier than the above method. In this method, you can set the visibility of the GroupBox control programmatically with the help of given syntax:" }, { "code": null, "e": 25296, "s": 25254, "text": "public override string Text { get; set; }" }, { "code": null, "e": 25376, "s": 25296, "text": "The following steps show how to set the visibility of the GroupBox dynamically:" }, { "code": null, "e": 25526, "s": 25376, "text": "Step 1: Create a GroupBox using the GroupBox() constructor is provided by the GroupBox class.// Creating a GroupBox\nGroupBox gbox = new GroupBox(); \n" }, { "code": null, "e": 25583, "s": 25526, "text": "// Creating a GroupBox\nGroupBox gbox = new GroupBox(); \n" }, { "code": null, "e": 25732, "s": 25583, "text": "Step 2: After creating GroupBox, set the Visible property of the GroupBox provided by the GroupBox class.// Setting visibility\ngbox.Visible = true;\n" }, { "code": null, "e": 25776, "s": 25732, "text": "// Setting visibility\ngbox.Visible = true;\n" }, { "code": null, "e": 27497, "s": 25776, "text": "Step 3: And last add this GroupBox control to the form and also add other controls on the GroupBox using the following statements:// Adding groupbox in the form\nthis.Controls.Add(gbox);\n\nand \n\n// Adding this control \n// to the GroupBox\ngbox.Controls.Add(c2);\nExample:using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp46 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // properties of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Text = \"Select Gender\"; gbox.Name = \"Mybox\"; gbox.Font = new Font(\"Colonna MT\", 12); gbox.Visible = true; gbox.AutoSize = true; gbox.AutoSizeMode = AutoSizeMode.GrowAndShrink; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(69, 20); c1.Text = \"Male\"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting // properties of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(79, 20); c2.Text = \"Female\"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}Output:" }, { "code": null, "e": 27627, "s": 27497, "text": "// Adding groupbox in the form\nthis.Controls.Add(gbox);\n\nand \n\n// Adding this control \n// to the GroupBox\ngbox.Controls.Add(c2);\n" }, { "code": null, "e": 27636, "s": 27627, "text": "Example:" }, { "code": "using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows.Forms; namespace WindowsFormsApp46 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { // Creating and setting // properties of the GroupBox GroupBox gbox = new GroupBox(); gbox.Location = new Point(179, 145); gbox.Text = \"Select Gender\"; gbox.Name = \"Mybox\"; gbox.Font = new Font(\"Colonna MT\", 12); gbox.Visible = true; gbox.AutoSize = true; gbox.AutoSizeMode = AutoSizeMode.GrowAndShrink; // Adding groupbox in the form this.Controls.Add(gbox); // Creating and setting // properties of the CheckBox CheckBox c1 = new CheckBox(); c1.Location = new Point(40, 42); c1.Size = new Size(69, 20); c1.Text = \"Male\"; // Adding this control // to the GroupBox gbox.Controls.Add(c1); // Creating and setting // properties of the CheckBox CheckBox c2 = new CheckBox(); c2.Location = new Point(183, 39); c2.Size = new Size(79, 20); c2.Text = \"Female\"; // Adding this control // to the GroupBox gbox.Controls.Add(c2); }}}", "e": 29083, "s": 27636, "text": null }, { "code": null, "e": 29091, "s": 29083, "text": "Output:" }, { "code": null, "e": 29122, "s": 29091, "text": "CSharp-Windows-Forms-Namespace" }, { "code": null, "e": 29125, "s": 29122, "text": "C#" }, { "code": null, "e": 29223, "s": 29125, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29232, "s": 29223, "text": "Comments" }, { "code": null, "e": 29245, "s": 29232, "text": "Old Comments" }, { "code": null, "e": 29285, "s": 29245, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 29308, "s": 29285, "text": "Extension Method in C#" }, { "code": null, "e": 29336, "s": 29308, "text": "HashSet in C# with Examples" }, { "code": null, "e": 29358, "s": 29336, "text": "Partial Classes in C#" }, { "code": null, "e": 29375, "s": 29358, "text": "C# | Inheritance" }, { "code": null, "e": 29415, "s": 29375, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 29448, "s": 29415, "text": "Linked List Implementation in C#" }, { "code": null, "e": 29491, "s": 29448, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 29507, "s": 29491, "text": "C# | List Class" } ]
Program to calculate age - GeeksforGeeks
29 Oct, 2021 Given current date and birth date, find the present age. Examples: Input : Birth date = 07/09/1996 Present date = 07/12/2017 Output : Present Age = Years: 21 Months: 3 Days: 0 t Age = Years: 7 Months: 11 Days: 21 While calculating the difference in two dates we need to just keep track of two conditions that will do. If the current date is less than that of the birth date, then that month is not counted, and for subtracting dates we add number of month days to the current date so as to get the difference in the dates. If the current month is less than the birth month, then the current year is not taken into count as this year has not been completed and for getting the difference of months, we subtract by adding 12 to the current month. At the end we just need to subtract the days, months and years to get the difference after the two conditions are dealt with. Below is the implementation of the above approach : C++ Java Python C# PHP Javascript // c program for age calculator#include <stdio.h>#include <stdlib.h> // function to calculate current agevoid findAge(int current_date, int current_month, int current_year, int birth_date, int birth_month, int birth_year){ // days of every month int month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // if birth date is greater then current birth // month then do not count this month and add 30 // to the date so as to subtract the date and // get the remaining days if (birth_date > current_date) { current_date = current_date + month[birth_month - 1]; current_month = current_month - 1; } // if birth month exceeds current month, then do // not count this year and add 12 to the month so // that we can subtract and find out the difference if (birth_month > current_month) { current_year = current_year - 1; current_month = current_month + 12; } // calculate date, month, year int calculated_date = current_date - birth_date; int calculated_month = current_month - birth_month; int calculated_year = current_year - birth_year; // print the present age printf("Present Age\nYears: %d Months: %d Days:" " %d\n", calculated_year, calculated_month, calculated_date);} // driver code to check the above functionint main(){ // current dd// mm/yyyy int current_date = 7; int current_month = 12; int current_year = 2017; // birth dd// mm// yyyy int birth_date = 16; int birth_month = 12; int birth_year = 2009; // function call to print age findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year); return 0;} // Java program for age calculatorimport java.io.*; class GFG { static void findAge(int current_date, int current_month, int current_year, int birth_date, int birth_month, int birth_year) { int month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // if birth date is greater then current // birth_month, then donot count this month // and add 30 to the date so as to subtract // the date and get the remaining days if (birth_date > current_date) { current_month = current_month - 1; current_date = current_date + month[birth_month - 1]; } // if birth month exceeds current month, // then do not count this year and add // 12 to the month so that we can subtract // and find out the difference if (birth_month > current_month) { current_year = current_year - 1; current_month = current_month + 12; } // calculate date, month, year int calculated_date = current_date - birth_date; int calculated_month = current_month - birth_month; int calculated_year = current_year - birth_year; // print the present age System.out.println("Present Age"); System.out.println("Years: " + calculated_year + " Months: " + calculated_month + " Days: " + calculated_date); } public static void main(String[] args) { // present date int current_date = 7; int current_month = 12; int current_year = 2017; // birth dd// mm// yyyy int birth_date = 16; int birth_month = 12; int birth_year = 2009; // function call to print age findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year); }} # Python program to calculate range def findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year): # if birth date is greater then current birth_month # then donot count this month and add 30 to the date so # as to subtract the date and get the remaining days month =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if (birth_date > current_date): current_month = current_month - 1 current_date = current_date + month[birth_month-1] # if birth month exceeds current month, then # donot count this year and add 12 to the # month so that we can subtract and find out # the difference if (birth_month > current_month): current_year = current_year - 1; current_month = current_month + 12; # calculate date, month, year calculated_date = current_date - birth_date; calculated_month = current_month - birth_month; calculated_year = current_year - birth_year; # print present age print"Present Age" print("Years:", calculated_year, "Months:", calculated_month, "Days:", calculated_date) # driver codecurrent_date = 7current_month = 12current_year = 2017 # birth dd//mm//yyyybirth_date = 16birth_month = 12birth_year = 2009 findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year) // C# program for age calculatorusing System; class GFG { static void findAge(int current_date, int current_month, int current_year, int birth_date, int birth_month, int birth_year) { int []month = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // if birth date is greater then // current birth_month, then donot // count this month and add 30 to the // date so as to subtract the date and // get the remaining days if (birth_date > current_date) { current_month = current_month - 1; current_date = current_date + month[birth_month - 1]; } // if birth month exceeds current month, // then do not count this year and add // 12 to the month so that we can // subtract and find out the difference if (birth_month > current_month) { current_year = current_year - 1; current_month = current_month + 12; } // calculate date, month, year int calculated_date = current_date - birth_date; int calculated_month = current_month - birth_month; int calculated_year = current_year - birth_year; // print the present age Console.WriteLine("Present Age"); Console.WriteLine("Years: " + calculated_year + " Months: " + calculated_month + " Days: " + calculated_date); } // driver code to check the above function public static void Main() { // present date int current_date = 7; int current_month = 12; int current_year = 2017; // birth dd// mm// yyyy int birth_date = 16; int birth_month = 12; int birth_year = 2009; // function call to print age findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year); }} //This code is contributed by vt_m. <?php// PHP program for// age calculator // function to calculate// current agefunction findAge(int $current_date, int $current_month, int $current_year, int $birth_date, int $birth_month, int $birth_year){ // days of every month $month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ); // if birth date is greater // then current birth month // then do not count this // month and add 30 to the // date so as to subtract // the date and get the // remaining days if ($birth_date > $current_date) { $current_date = $current_date + $month[$birth_month - 1]; $current_month = $current_month - 1; } // if birth month exceeds // current month, then do // not count this year and // add 12 to the month so // that we can subtract and // find out the difference if ($birth_month > $current_month) { $current_year = $current_year - 1; $current_month = $current_month + 12; } // calculate date, month, year $calculated_date = $current_date - $birth_date; $calculated_month = $current_month - $birth_month; $calculated_year = $current_year - $birth_year; // print the present age echo "Present Age\nYears:",$calculated_year, " " , "Months:", $calculated_month, " ", "Days:", $calculated_date; } // Driver Code // current dd// mm/yyyy $current_date = 7; $current_month = 12; $current_year = 2017; // birth dd// mm// yyyy $birth_date = 16; $birth_month = 12; $birth_year = 2009; // function call to print age findAge($current_date, $current_month, $current_year, $birth_date, $birth_month, $birth_year); // This code is contributed by anuj_67.?> <script> // Javascript program for age calculator // function to calculate current agefunction findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year){ // days of every month month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] // if birth date is greater then current birth // month then do not count this month and add 30 // to the date so as to subtract the date and // get the remaining days if (birth_date > current_date) { current_date = current_date + month[birth_month - 1]; current_month = current_month - 1; } // if birth month exceeds current month, then do // not count this year and add 12 to the month so // that we can subtract and find out the difference if (birth_month > current_month) { current_year = current_year - 1; current_month = current_month + 12; } // calculate date, month, year var calculated_date = current_date - birth_date; var calculated_month = current_month - birth_month; var calculated_year = current_year - birth_year; // print the present age document.write("Present Age<br>Years: "+(calculated_year)+" "); document.write("Months: "+calculated_month+" "); document.write("Days: "+calculated_date+" ");} // driver code to check the above function// current dd// mm/yyyyvar current_date = 7;var current_month = 12;var current_year = 2017;// birth dd// mm// yyyyvar birth_date = 16;var birth_month = 12;var birth_year = 2009;// function call to print agefindAge(current_date, current_month, current_year, birth_date, birth_month, birth_year); </script> Output: Present Age Years: 7 Months: 11 Days: 22 vt_m rutvik_56 ankita_saini date-time-program School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Constructors in C++ Interfaces in Java Operator Overloading in C++ Copy Constructor in C++ Overriding in Java Friend class and function in C++ Polymorphism in C++ Types of Operating Systems Python program to check if a string is palindrome or not Inheritance in Java
[ { "code": null, "e": 24413, "s": 24385, "text": "\n29 Oct, 2021" }, { "code": null, "e": 24482, "s": 24413, "text": "Given current date and birth date, find the present age. Examples: " }, { "code": null, "e": 24641, "s": 24482, "text": "Input : Birth date = 07/09/1996 \n Present date = 07/12/2017\nOutput : Present Age = Years: 21 Months: 3 Days: 0\nt Age = Years: 7 Months: 11 Days: 21" }, { "code": null, "e": 24750, "s": 24643, "text": "While calculating the difference in two dates we need to just keep track of two conditions that will do. " }, { "code": null, "e": 24955, "s": 24750, "text": "If the current date is less than that of the birth date, then that month is not counted, and for subtracting dates we add number of month days to the current date so as to get the difference in the dates." }, { "code": null, "e": 25177, "s": 24955, "text": "If the current month is less than the birth month, then the current year is not taken into count as this year has not been completed and for getting the difference of months, we subtract by adding 12 to the current month." }, { "code": null, "e": 25303, "s": 25177, "text": "At the end we just need to subtract the days, months and years to get the difference after the two conditions are dealt with." }, { "code": null, "e": 25357, "s": 25303, "text": "Below is the implementation of the above approach : " }, { "code": null, "e": 25361, "s": 25357, "text": "C++" }, { "code": null, "e": 25366, "s": 25361, "text": "Java" }, { "code": null, "e": 25373, "s": 25366, "text": "Python" }, { "code": null, "e": 25376, "s": 25373, "text": "C#" }, { "code": null, "e": 25380, "s": 25376, "text": "PHP" }, { "code": null, "e": 25391, "s": 25380, "text": "Javascript" }, { "code": "// c program for age calculator#include <stdio.h>#include <stdlib.h> // function to calculate current agevoid findAge(int current_date, int current_month, int current_year, int birth_date, int birth_month, int birth_year){ // days of every month int month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // if birth date is greater then current birth // month then do not count this month and add 30 // to the date so as to subtract the date and // get the remaining days if (birth_date > current_date) { current_date = current_date + month[birth_month - 1]; current_month = current_month - 1; } // if birth month exceeds current month, then do // not count this year and add 12 to the month so // that we can subtract and find out the difference if (birth_month > current_month) { current_year = current_year - 1; current_month = current_month + 12; } // calculate date, month, year int calculated_date = current_date - birth_date; int calculated_month = current_month - birth_month; int calculated_year = current_year - birth_year; // print the present age printf(\"Present Age\\nYears: %d Months: %d Days:\" \" %d\\n\", calculated_year, calculated_month, calculated_date);} // driver code to check the above functionint main(){ // current dd// mm/yyyy int current_date = 7; int current_month = 12; int current_year = 2017; // birth dd// mm// yyyy int birth_date = 16; int birth_month = 12; int birth_year = 2009; // function call to print age findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year); return 0;}", "e": 27172, "s": 25391, "text": null }, { "code": "// Java program for age calculatorimport java.io.*; class GFG { static void findAge(int current_date, int current_month, int current_year, int birth_date, int birth_month, int birth_year) { int month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // if birth date is greater then current // birth_month, then donot count this month // and add 30 to the date so as to subtract // the date and get the remaining days if (birth_date > current_date) { current_month = current_month - 1; current_date = current_date + month[birth_month - 1]; } // if birth month exceeds current month, // then do not count this year and add // 12 to the month so that we can subtract // and find out the difference if (birth_month > current_month) { current_year = current_year - 1; current_month = current_month + 12; } // calculate date, month, year int calculated_date = current_date - birth_date; int calculated_month = current_month - birth_month; int calculated_year = current_year - birth_year; // print the present age System.out.println(\"Present Age\"); System.out.println(\"Years: \" + calculated_year + \" Months: \" + calculated_month + \" Days: \" + calculated_date); } public static void main(String[] args) { // present date int current_date = 7; int current_month = 12; int current_year = 2017; // birth dd// mm// yyyy int birth_date = 16; int birth_month = 12; int birth_year = 2009; // function call to print age findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year); }}", "e": 29058, "s": 27172, "text": null }, { "code": "# Python program to calculate range def findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year): # if birth date is greater then current birth_month # then donot count this month and add 30 to the date so # as to subtract the date and get the remaining days month =[31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] if (birth_date > current_date): current_month = current_month - 1 current_date = current_date + month[birth_month-1] # if birth month exceeds current month, then # donot count this year and add 12 to the # month so that we can subtract and find out # the difference if (birth_month > current_month): current_year = current_year - 1; current_month = current_month + 12; # calculate date, month, year calculated_date = current_date - birth_date; calculated_month = current_month - birth_month; calculated_year = current_year - birth_year; # print present age print\"Present Age\" print(\"Years:\", calculated_year, \"Months:\", calculated_month, \"Days:\", calculated_date) # driver codecurrent_date = 7current_month = 12current_year = 2017 # birth dd//mm//yyyybirth_date = 16birth_month = 12birth_year = 2009 findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year)", "e": 30456, "s": 29058, "text": null }, { "code": "// C# program for age calculatorusing System; class GFG { static void findAge(int current_date, int current_month, int current_year, int birth_date, int birth_month, int birth_year) { int []month = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; // if birth date is greater then // current birth_month, then donot // count this month and add 30 to the // date so as to subtract the date and // get the remaining days if (birth_date > current_date) { current_month = current_month - 1; current_date = current_date + month[birth_month - 1]; } // if birth month exceeds current month, // then do not count this year and add // 12 to the month so that we can // subtract and find out the difference if (birth_month > current_month) { current_year = current_year - 1; current_month = current_month + 12; } // calculate date, month, year int calculated_date = current_date - birth_date; int calculated_month = current_month - birth_month; int calculated_year = current_year - birth_year; // print the present age Console.WriteLine(\"Present Age\"); Console.WriteLine(\"Years: \" + calculated_year + \" Months: \" + calculated_month + \" Days: \" + calculated_date); } // driver code to check the above function public static void Main() { // present date int current_date = 7; int current_month = 12; int current_year = 2017; // birth dd// mm// yyyy int birth_date = 16; int birth_month = 12; int birth_year = 2009; // function call to print age findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year); }} //This code is contributed by vt_m.", "e": 32765, "s": 30456, "text": null }, { "code": "<?php// PHP program for// age calculator // function to calculate// current agefunction findAge(int $current_date, int $current_month, int $current_year, int $birth_date, int $birth_month, int $birth_year){ // days of every month $month = array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ); // if birth date is greater // then current birth month // then do not count this // month and add 30 to the // date so as to subtract // the date and get the // remaining days if ($birth_date > $current_date) { $current_date = $current_date + $month[$birth_month - 1]; $current_month = $current_month - 1; } // if birth month exceeds // current month, then do // not count this year and // add 12 to the month so // that we can subtract and // find out the difference if ($birth_month > $current_month) { $current_year = $current_year - 1; $current_month = $current_month + 12; } // calculate date, month, year $calculated_date = $current_date - $birth_date; $calculated_month = $current_month - $birth_month; $calculated_year = $current_year - $birth_year; // print the present age echo \"Present Age\\nYears:\",$calculated_year, \" \" , \"Months:\", $calculated_month, \" \", \"Days:\", $calculated_date; } // Driver Code // current dd// mm/yyyy $current_date = 7; $current_month = 12; $current_year = 2017; // birth dd// mm// yyyy $birth_date = 16; $birth_month = 12; $birth_year = 2009; // function call to print age findAge($current_date, $current_month, $current_year, $birth_date, $birth_month, $birth_year); // This code is contributed by anuj_67.?>", "e": 34698, "s": 32765, "text": null }, { "code": "<script> // Javascript program for age calculator // function to calculate current agefunction findAge(current_date, current_month, current_year, birth_date, birth_month, birth_year){ // days of every month month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ] // if birth date is greater then current birth // month then do not count this month and add 30 // to the date so as to subtract the date and // get the remaining days if (birth_date > current_date) { current_date = current_date + month[birth_month - 1]; current_month = current_month - 1; } // if birth month exceeds current month, then do // not count this year and add 12 to the month so // that we can subtract and find out the difference if (birth_month > current_month) { current_year = current_year - 1; current_month = current_month + 12; } // calculate date, month, year var calculated_date = current_date - birth_date; var calculated_month = current_month - birth_month; var calculated_year = current_year - birth_year; // print the present age document.write(\"Present Age<br>Years: \"+(calculated_year)+\" \"); document.write(\"Months: \"+calculated_month+\" \"); document.write(\"Days: \"+calculated_date+\" \");} // driver code to check the above function// current dd// mm/yyyyvar current_date = 7;var current_month = 12;var current_year = 2017;// birth dd// mm// yyyyvar birth_date = 16;var birth_month = 12;var birth_year = 2009;// function call to print agefindAge(current_date, current_month, current_year, birth_date, birth_month, birth_year); </script>", "e": 36366, "s": 34698, "text": null }, { "code": null, "e": 36376, "s": 36366, "text": "Output: " }, { "code": null, "e": 36419, "s": 36376, "text": "Present Age\nYears: 7 Months: 11 Days: 22" }, { "code": null, "e": 36426, "s": 36421, "text": "vt_m" }, { "code": null, "e": 36436, "s": 36426, "text": "rutvik_56" }, { "code": null, "e": 36449, "s": 36436, "text": "ankita_saini" }, { "code": null, "e": 36467, "s": 36449, "text": "date-time-program" }, { "code": null, "e": 36486, "s": 36467, "text": "School Programming" }, { "code": null, "e": 36584, "s": 36486, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36593, "s": 36584, "text": "Comments" }, { "code": null, "e": 36606, "s": 36593, "text": "Old Comments" }, { "code": null, "e": 36626, "s": 36606, "text": "Constructors in C++" }, { "code": null, "e": 36645, "s": 36626, "text": "Interfaces in Java" }, { "code": null, "e": 36673, "s": 36645, "text": "Operator Overloading in C++" }, { "code": null, "e": 36697, "s": 36673, "text": "Copy Constructor in C++" }, { "code": null, "e": 36716, "s": 36697, "text": "Overriding in Java" }, { "code": null, "e": 36749, "s": 36716, "text": "Friend class and function in C++" }, { "code": null, "e": 36769, "s": 36749, "text": "Polymorphism in C++" }, { "code": null, "e": 36796, "s": 36769, "text": "Types of Operating Systems" }, { "code": null, "e": 36853, "s": 36796, "text": "Python program to check if a string is palindrome or not" } ]
C program to compare the structure variables
In C programming language, a structure is a collection of different datatype variables, which are grouped together under a single name. Declaration and initialization of structures The general form of a structure declaration is as follows − datatype member1; struct tagname{ datatype member2; datatype member n; }; Here, struct is a keyword. tagname specifies the name of structure. member1, member2 specifies the data items that make up structure. For example, struct book{ int pages; char author [30]; float price; }; There are three methods of declaring structure variables, which are as follows − First method struct book{ int pages; char author[30]; float price; }b; Second method struct{ int pages; char author[30]; float price; }b; Third method struct book{ int pages; char author[30]; float price; }; struct book b; Initialization and accessing of structures The link between a member and a structure variable is established by using a member operator (or) a dot operator. Initialization can be done in the following methods − First method struct book{ int pages; char author[30]; float price; } b = {100, “balu”, 325.75}; Second method struct book{ int pages; char author[30]; float price; }; struct book b = {100, “balu”, 325.75}; Third method by using a member operator struct book{ int pages; char author[30]; float price; } ; struct book b; b. pages = 100; strcpy (b.author, “balu”); b.price = 325.75; Following is the C program for the comparison of structure variables − Live Demo struct class{ int number; char name[20]; float marks; }; main(){ int x; struct class student1 = {001,"Hari",172.50}; struct class student2 = {002,"Bobby", 167.00}; struct class student3; student3 = student2; x = ((student3.number == student2.number) && (student3.marks == student2.marks)) ? 1 : 0; if(x == 1){ printf("\nstudent2 and student3 are same\n\n"); printf("%d %s %f\n", student3.number, student3.name, student3.marks); } else printf("\nstudent2 and student3 are different\n\n"); } When the above program is executed, it produces the following output − student2 and student3 are same 2 Bobby 167.000000
[ { "code": null, "e": 1198, "s": 1062, "text": "In C programming language, a structure is a collection of different datatype variables, which are grouped together under a single name." }, { "code": null, "e": 1243, "s": 1198, "text": "Declaration and initialization of structures" }, { "code": null, "e": 1303, "s": 1243, "text": "The general form of a structure declaration is as follows −" }, { "code": null, "e": 1383, "s": 1303, "text": "datatype member1;\nstruct tagname{\n datatype member2;\n datatype member n;\n};" }, { "code": null, "e": 1389, "s": 1383, "text": "Here," }, { "code": null, "e": 1410, "s": 1389, "text": "struct is a keyword." }, { "code": null, "e": 1451, "s": 1410, "text": "tagname specifies the name of structure." }, { "code": null, "e": 1517, "s": 1451, "text": "member1, member2 specifies the data items that make up structure." }, { "code": null, "e": 1530, "s": 1517, "text": "For example," }, { "code": null, "e": 1597, "s": 1530, "text": "struct book{\n int pages;\n char author [30];\n float price;\n};" }, { "code": null, "e": 1678, "s": 1597, "text": "There are three methods of declaring structure variables, which are as follows −" }, { "code": null, "e": 1691, "s": 1678, "text": "First method" }, { "code": null, "e": 1758, "s": 1691, "text": "struct book{\n int pages;\n char author[30];\n float price;\n}b;" }, { "code": null, "e": 1772, "s": 1758, "text": "Second method" }, { "code": null, "e": 1834, "s": 1772, "text": "struct{\n int pages;\n char author[30];\n float price;\n}b;" }, { "code": null, "e": 1847, "s": 1834, "text": "Third method" }, { "code": null, "e": 1928, "s": 1847, "text": "struct book{\n int pages;\n char author[30];\n float price;\n};\nstruct book b;" }, { "code": null, "e": 1971, "s": 1928, "text": "Initialization and accessing of structures" }, { "code": null, "e": 2085, "s": 1971, "text": "The link between a member and a structure variable is established by using a member operator (or) a dot operator." }, { "code": null, "e": 2139, "s": 2085, "text": "Initialization can be done in the following methods −" }, { "code": null, "e": 2152, "s": 2139, "text": "First method" }, { "code": null, "e": 2244, "s": 2152, "text": "struct book{\n int pages;\n char author[30];\n float price;\n} b = {100, “balu”, 325.75};" }, { "code": null, "e": 2258, "s": 2244, "text": "Second method" }, { "code": null, "e": 2363, "s": 2258, "text": "struct book{\n int pages;\n char author[30];\n float price;\n};\nstruct book b = {100, “balu”, 325.75};" }, { "code": null, "e": 2403, "s": 2363, "text": "Third method by using a member operator" }, { "code": null, "e": 2546, "s": 2403, "text": "struct book{\n int pages;\n char author[30];\n float price;\n} ;\nstruct book b;\nb. pages = 100;\nstrcpy (b.author, “balu”);\nb.price = 325.75;" }, { "code": null, "e": 2617, "s": 2546, "text": "Following is the C program for the comparison of structure variables −" }, { "code": null, "e": 2628, "s": 2617, "text": " Live Demo" }, { "code": null, "e": 3184, "s": 2628, "text": "struct class{\n int number;\n char name[20];\n float marks;\n};\nmain(){\n int x;\n struct class student1 = {001,\"Hari\",172.50};\n struct class student2 = {002,\"Bobby\", 167.00};\n struct class student3;\n student3 = student2;\n x = ((student3.number == student2.number) &&\n (student3.marks == student2.marks)) ? 1 : 0;\n if(x == 1){\n printf(\"\\nstudent2 and student3 are same\\n\\n\");\n printf(\"%d %s %f\\n\", student3.number,\n student3.name,\n student3.marks);\n }\n else\n printf(\"\\nstudent2 and student3 are different\\n\\n\");\n}" }, { "code": null, "e": 3255, "s": 3184, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 3305, "s": 3255, "text": "student2 and student3 are same\n2 Bobby 167.000000" } ]
Delete duplicates in a Pandas Dataframe based on two columns - GeeksforGeeks
11 Dec, 2020 A dataframe is a two-dimensional, size-mutable tabular data structure with labeled axes (rows and columns). It can contain duplicate entries and to delete them there are several ways. Let us consider the following dataset. The dataframe contains duplicate values in column order_id and customer_id. Below are the methods to remove duplicate values from a dataframe based on two columns. Method 1: using drop_duplicates() Approach: We will drop duplicate columns based on two columns Let those columns be ‘order_id’ and ‘customer_id’ Keep the latest entry only Reset the index of dataframe Below is the python code for the above approach. Python3 # import pandas libraryimport pandas as pd # load datadf1 = pd.read_csv("super.csv") # drop rows which have same order_id# and customer_id and keep latest entrynewdf = df1.drop_duplicates( subset = ['order_id', 'customer_id'], keep = 'last').reset_index(drop = True) # print latest dataframedisplay(newdf) Output: Method 2: using groupby() Approach: We will group rows based on two columns Let those columns be ‘order_id’ and ‘customer_id’ Keep the first entry only The python code for the above approach is given below. Python3 # import pandas libraryimport pandas as pd # read datadf1 = pd.read_csv("super.csv") # group data over columns 'order_id'# and 'customer_id' and keep first entry onlynewdf1 = df1.groupby(['order_id', 'customer_id']).first() # print new dataframeprint(newdf1) Output: Python pandas-dataFrame 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? How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Defaultdict in Python Create a directory in Python Python | os.path.join() method Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 26088, "s": 26060, "text": "\n11 Dec, 2020" }, { "code": null, "e": 26273, "s": 26088, "text": "A dataframe is a two-dimensional, size-mutable tabular data structure with labeled axes (rows and columns). It can contain duplicate entries and to delete them there are several ways. " }, { "code": null, "e": 26312, "s": 26273, "text": "Let us consider the following dataset." }, { "code": null, "e": 26476, "s": 26312, "text": "The dataframe contains duplicate values in column order_id and customer_id. Below are the methods to remove duplicate values from a dataframe based on two columns." }, { "code": null, "e": 26511, "s": 26476, "text": "Method 1: using drop_duplicates() " }, { "code": null, "e": 26521, "s": 26511, "text": "Approach:" }, { "code": null, "e": 26573, "s": 26521, "text": "We will drop duplicate columns based on two columns" }, { "code": null, "e": 26623, "s": 26573, "text": "Let those columns be ‘order_id’ and ‘customer_id’" }, { "code": null, "e": 26650, "s": 26623, "text": "Keep the latest entry only" }, { "code": null, "e": 26679, "s": 26650, "text": "Reset the index of dataframe" }, { "code": null, "e": 26728, "s": 26679, "text": "Below is the python code for the above approach." }, { "code": null, "e": 26736, "s": 26728, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # load datadf1 = pd.read_csv(\"super.csv\") # drop rows which have same order_id# and customer_id and keep latest entrynewdf = df1.drop_duplicates( subset = ['order_id', 'customer_id'], keep = 'last').reset_index(drop = True) # print latest dataframedisplay(newdf)", "e": 27047, "s": 26736, "text": null }, { "code": null, "e": 27055, "s": 27047, "text": "Output:" }, { "code": null, "e": 27081, "s": 27055, "text": "Method 2: using groupby()" }, { "code": null, "e": 27091, "s": 27081, "text": "Approach:" }, { "code": null, "e": 27131, "s": 27091, "text": "We will group rows based on two columns" }, { "code": null, "e": 27181, "s": 27131, "text": "Let those columns be ‘order_id’ and ‘customer_id’" }, { "code": null, "e": 27207, "s": 27181, "text": "Keep the first entry only" }, { "code": null, "e": 27262, "s": 27207, "text": "The python code for the above approach is given below." }, { "code": null, "e": 27270, "s": 27262, "text": "Python3" }, { "code": "# import pandas libraryimport pandas as pd # read datadf1 = pd.read_csv(\"super.csv\") # group data over columns 'order_id'# and 'customer_id' and keep first entry onlynewdf1 = df1.groupby(['order_id', 'customer_id']).first() # print new dataframeprint(newdf1)", "e": 27532, "s": 27270, "text": null }, { "code": null, "e": 27540, "s": 27532, "text": "Output:" }, { "code": null, "e": 27564, "s": 27540, "text": "Python pandas-dataFrame" }, { "code": null, "e": 27578, "s": 27564, "text": "Python-pandas" }, { "code": null, "e": 27585, "s": 27578, "text": "Python" }, { "code": null, "e": 27683, "s": 27585, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27715, "s": 27683, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27757, "s": 27715, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27799, "s": 27757, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27855, "s": 27799, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27882, "s": 27855, "text": "Python Classes and Objects" }, { "code": null, "e": 27904, "s": 27882, "text": "Defaultdict in Python" }, { "code": null, "e": 27933, "s": 27904, "text": "Create a directory in Python" }, { "code": null, "e": 27964, "s": 27933, "text": "Python | os.path.join() method" }, { "code": null, "e": 28000, "s": 27964, "text": "Python | Pandas dataframe.groupby()" } ]
Transforming XML file into fixed length flat file in SAP
This is an EDIfact invoice. Try using the script, and it can help − <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:output method="text" encoding="ISO-8859-1"/> <xsl:template match="/"> <!-- EDI_DC40 --> <xsl:for-each select="IDataXMLCoder/record/idatacodable/array/idatacodable/record/value"> <xsl:value-of select="text()"/> <xsl:choose> <!-- TABNAM (10) --> <xsl:when test="@name = 'TABNAM'"> <xsl:choose> <xsl:when test="string-length(text()) = 0"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 1"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 2"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 3"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 4"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 5"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 6"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 7"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 8"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 9"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) &gt; 10"> <xsl:message terminate="yes">ERROR: The maximum length of "TABNAM" is 10 characters.</xsl:message> </xsl:when> <xsl:otherwise/> </xsl:choose> </xsl:when> <!-- MANDT (3)--> <xsl:when test="MANDT"> <xsl:choose> <xsl:when test="string-length(text()) = 0"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 1"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 2"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) &gt; 3"> <xsl:message terminate="yes">ERROR: The maximum length of "MANDT" is 3 characters.</xsl:message> </xsl:when> <xsl:otherwise/> </xsl:choose> </xsl:when> <!-- DOCNUM (16) --> <!-- DOCREL (4) --> <!-- STATUS (4) --> <!-- etc. --> </xsl:choose> </xsl:for-each> <xsl:text>&#x0D;&#x0A;</xsl:text> <!-- E1EDK01 --> <xsl:for-each select="IDataXMLCoder/record/idatacodable/array/idatacodable/array/idatacodable/record/value"> <xsl:value-of select="text()"/> <xsl:choose> <!-- ACTION (3) --> <xsl:when test="@name = 'ACTION'"> <xsl:choose> <xsl:when test="string-length(text()) = 0"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 1"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) = 2"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) &gt; 3"> <xsl:message terminate="yes">ERROR: The maximum length of "ACTION" is 3 characters.</xsl:message> </xsl:when> <xsl:otherwise/> </xsl:choose> </xsl:when> <!-- KZABS (1)--> <xsl:when test="KZABS"> <xsl:choose> <xsl:when test="string-length(text()) = 0"> <xsl:text></xsl:text> </xsl:when> <xsl:when test="string-length(text()) &gt; 1"> <xsl:message terminate="yes">ERROR: The maximum length of "KZABS" is 1 character.</xsl:message> </xsl:when> <xsl:otherwise/> </xsl:choose> </xsl:when> <!-- CURCY (3) --> <!-- HWAER (3) --> <!-- WKURS (12) --> <!-- etc. --> </xsl:choose> </xsl:for-each> </xsl:template> </xsl:stylesheet> There are various sites which provide a built-in script to convert your EDIfact to XSLT. Check this site and it may also help − https://www.codeproject.com/Articles/11278/EDIFACT-to-XML-to-Anything-You-Want
[ { "code": null, "e": 1130, "s": 1062, "text": "This is an EDIfact invoice. Try using the script, and it can help −" }, { "code": null, "e": 5792, "s": 1130, "text": "<xsl:stylesheet version=\"1.0\" xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"text\" encoding=\"ISO-8859-1\"/>\n <xsl:template match=\"/\">\n <!-- EDI_DC40 -->\n <xsl:for-each select=\"IDataXMLCoder/record/idatacodable/array/idatacodable/record/value\">\n <xsl:value-of select=\"text()\"/>\n <xsl:choose>\n <!-- TABNAM (10) -->\n <xsl:when test=\"@name = 'TABNAM'\">\n <xsl:choose>\n <xsl:when test=\"string-length(text()) = 0\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 1\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 2\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 3\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 4\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 5\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 6\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 7\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 8\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 9\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) &gt; 10\">\n <xsl:message terminate=\"yes\">ERROR: The maximum length of \"TABNAM\" is 10 characters.</xsl:message>\n </xsl:when>\n <xsl:otherwise/>\n </xsl:choose>\n </xsl:when>\n <!-- MANDT (3)-->\n <xsl:when test=\"MANDT\">\n <xsl:choose>\n <xsl:when test=\"string-length(text()) = 0\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 1\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 2\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) &gt; 3\">\n <xsl:message terminate=\"yes\">ERROR: The maximum length of \"MANDT\" is 3 characters.</xsl:message>\n </xsl:when>\n <xsl:otherwise/>\n </xsl:choose>\n </xsl:when>\n <!-- DOCNUM (16) -->\n <!-- DOCREL (4) -->\n <!-- STATUS (4) -->\n <!-- etc. -->\n </xsl:choose>\n </xsl:for-each>\n <xsl:text>&#x0D;&#x0A;</xsl:text>\n <!-- E1EDK01 -->\n <xsl:for-each select=\"IDataXMLCoder/record/idatacodable/array/idatacodable/array/idatacodable/record/value\">\n <xsl:value-of select=\"text()\"/>\n <xsl:choose>\n <!-- ACTION (3) -->\n <xsl:when test=\"@name = 'ACTION'\">\n <xsl:choose>\n <xsl:when test=\"string-length(text()) = 0\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 1\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) = 2\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) &gt; 3\">\n <xsl:message terminate=\"yes\">ERROR: The maximum length of \"ACTION\" is 3 characters.</xsl:message>\n </xsl:when>\n <xsl:otherwise/>\n </xsl:choose>\n </xsl:when>\n <!-- KZABS (1)-->\n <xsl:when test=\"KZABS\">\n <xsl:choose>\n <xsl:when test=\"string-length(text()) = 0\">\n <xsl:text></xsl:text>\n </xsl:when>\n <xsl:when test=\"string-length(text()) &gt; 1\">\n <xsl:message terminate=\"yes\">ERROR: The maximum length of \"KZABS\" is 1 character.</xsl:message>\n </xsl:when>\n <xsl:otherwise/>\n </xsl:choose>\n </xsl:when>\n <!-- CURCY (3) -->\n <!-- HWAER (3) -->\n <!-- WKURS (12) -->\n <!-- etc. -->\n </xsl:choose>\n </xsl:for-each>\n </xsl:template>\n</xsl:stylesheet>" }, { "code": null, "e": 5921, "s": 5792, "text": "There are various sites which provide a built-in script to convert your EDIfact to XSLT. Check this site and it may also help −" }, { "code": null, "e": 6000, "s": 5921, "text": "https://www.codeproject.com/Articles/11278/EDIFACT-to-XML-to-Anything-You-Want" } ]
DAX Aggregation - TOPN function
Returns the top specified number of rows of the table. TOPN (<n_value>, <table>, <orderBy_expression>, [<order>], [<orderBy_expression>, [<order>]] ...) n_value The number of rows to return. It is any DAX expression that returns a single scalar value, where the expression is to be evaluated multiple times (for each row/context). table Any DAX expression that returns a table of data from where to extract the top n_value number of rows. orderBy_expression Any DAX expression where the result value is used to sort the table and it is evaluated for each row of table. order Optional. A value that specifies how to sort orderBy_expression values, ascending or descending − 0 (zero) or FALSE − Sorts in a descending order of values of orderBy_expression. 1 or TRUE − Sorts in an ascending order of orderBy_expression. If omitted, default is 0. Returns a table with the top n_value number of rows of table, if n_value > 0. Returns an empty table, if n_value <= 0. Rows are not necessarily sorted in any particular order. If there is a tie, in orderBy_expression values, at the Nth row of the table, then all tied rows are returned. The function might return more than n_value number of rows. If there is a tie, in orderBy_expression values, at the Nth row of the table, then all tied rows are returned. The function might return more than n_value number of rows. TOPN does not guarantee any sort order for the results. TOPN does not guarantee any sort order for the results. = SUMX (TOPN (15,Sales,Sales[Salesperson],ASC),Sales[Sales Amount]) 53 Lectures 5.5 hours Abhay Gadiya 24 Lectures 2 hours Randy Minder 26 Lectures 4.5 hours Randy Minder Print Add Notes Bookmark this page
[ { "code": null, "e": 2056, "s": 2001, "text": "Returns the top specified number of rows of the table." }, { "code": null, "e": 2159, "s": 2056, "text": "TOPN (<n_value>, <table>, <orderBy_expression>, [<order>],\n [<orderBy_expression>, [<order>]] ...) \n" }, { "code": null, "e": 2167, "s": 2159, "text": "n_value" }, { "code": null, "e": 2197, "s": 2167, "text": "The number of rows to return." }, { "code": null, "e": 2337, "s": 2197, "text": "It is any DAX expression that returns a single scalar value, where the expression is to be evaluated multiple times (for each row/context)." }, { "code": null, "e": 2343, "s": 2337, "text": "table" }, { "code": null, "e": 2445, "s": 2343, "text": "Any DAX expression that returns a table of data from where to extract the top n_value number of rows." }, { "code": null, "e": 2464, "s": 2445, "text": "orderBy_expression" }, { "code": null, "e": 2575, "s": 2464, "text": "Any DAX expression where the result value is used to sort the table and it is evaluated for each row of table." }, { "code": null, "e": 2581, "s": 2575, "text": "order" }, { "code": null, "e": 2591, "s": 2581, "text": "Optional." }, { "code": null, "e": 2679, "s": 2591, "text": "A value that specifies how to sort orderBy_expression values, ascending or descending −" }, { "code": null, "e": 2760, "s": 2679, "text": "0 (zero) or FALSE − Sorts in a descending order of values of orderBy_expression." }, { "code": null, "e": 2849, "s": 2760, "text": "1 or TRUE − Sorts in an ascending order of orderBy_expression. If omitted, default is 0." }, { "code": null, "e": 2927, "s": 2849, "text": "Returns a table with the top n_value number of rows of table, if n_value > 0." }, { "code": null, "e": 2968, "s": 2927, "text": "Returns an empty table, if n_value <= 0." }, { "code": null, "e": 3025, "s": 2968, "text": "Rows are not necessarily sorted in any particular order." }, { "code": null, "e": 3196, "s": 3025, "text": "If there is a tie, in orderBy_expression values, at the Nth row of the table, then all tied rows are returned. The function might return more than n_value number of rows." }, { "code": null, "e": 3367, "s": 3196, "text": "If there is a tie, in orderBy_expression values, at the Nth row of the table, then all tied rows are returned. The function might return more than n_value number of rows." }, { "code": null, "e": 3423, "s": 3367, "text": "TOPN does not guarantee any sort order for the results." }, { "code": null, "e": 3479, "s": 3423, "text": "TOPN does not guarantee any sort order for the results." }, { "code": null, "e": 3548, "s": 3479, "text": "= SUMX (TOPN (15,Sales,Sales[Salesperson],ASC),Sales[Sales Amount]) " }, { "code": null, "e": 3583, "s": 3548, "text": "\n 53 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3597, "s": 3583, "text": " Abhay Gadiya" }, { "code": null, "e": 3630, "s": 3597, "text": "\n 24 Lectures \n 2 hours \n" }, { "code": null, "e": 3644, "s": 3630, "text": " Randy Minder" }, { "code": null, "e": 3679, "s": 3644, "text": "\n 26 Lectures \n 4.5 hours \n" }, { "code": null, "e": 3693, "s": 3679, "text": " Randy Minder" }, { "code": null, "e": 3700, "s": 3693, "text": " Print" }, { "code": null, "e": 3711, "s": 3700, "text": " Add Notes" } ]
BareCode scanning in Android?
This example demonstrates how do I use barcode scanning in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/relativeLayout" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="4dp" tools:context=".MainActivity"> <TextView android:layout_below="@id/button" android:layout_centerInParent="true" android:layout_marginBottom="10dp" android:text=" code reader" android:textSize="16sp" android:textStyle="bold" android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/txtContent"/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Process" android:layout_marginTop="50dp" android:layout_centerHorizontal="true" android:id="@+id/button" /> </RelativeLayout> Step 3 − Add the following dependency in Gradle implementation 'com.google.zxing:core:3.2.1' implementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar' Step 4 − Add the following code to src/MainActivity.java import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import com.google.zxing.integration.android.IntentIntegrator; import com.google.zxing.integration.android.IntentResult; public class MainActivity extends AppCompatActivity { Button btnBarcode; TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); btnBarcode = findViewById(R.id.button); textView = findViewById(R.id.txtContent); btnBarcode.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { IntentIntegrator intentIntegrator = new IntentIntegrator(MainActivity.this); intentIntegrator.setDesiredBarcodeFormats(intentIntegrator.ALL_CODE_TYPES); intentIntegrator.setBeepEnabled(false); intentIntegrator.setCameraId(0); intentIntegrator.setPrompt("SCAN"); intentIntegrator.setBarcodeImageEnabled(false); intentIntegrator.initiateScan(); } }); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { IntentResult Result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data); if (Result != null) { if (Result.getContents() == null) { Toast.makeText(this, "cancelled", Toast.LENGTH_SHORT).show(); } else { Log.d("MainActivity", "Scanned"); Toast.makeText(this, "Scanned -> " + Result.getContents(), Toast.LENGTH_SHORT).show(); textView.setText(String.format("Scanned Result: %s", Result)); } } else { super.onActivityResult(requestCode, resultCode, data); } } } Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> <uses-feature android:name="android.hardware.camera.autoFocus" /> <uses-feature android:name="android.hardware.camera" /> <uses-permission android:name="android.permission.CAMERA" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen − Check with real device for better result.
[ { "code": null, "e": 1130, "s": 1062, "text": "This example demonstrates how do I use barcode scanning in android." }, { "code": null, "e": 1259, "s": 1130, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1324, "s": 1259, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2226, "s": 1324, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:id=\"@+id/relativeLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"4dp\"\n tools:context=\".MainActivity\">\n<TextView\n android:layout_below=\"@id/button\"\n android:layout_centerInParent=\"true\"\n android:layout_marginBottom=\"10dp\"\n android:text=\" code reader\"\n android:textSize=\"16sp\"\n android:textStyle=\"bold\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/txtContent\"/>\n<Button\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Process\"\n android:layout_marginTop=\"50dp\"\n android:layout_centerHorizontal=\"true\"\n android:id=\"@+id/button\" />\n</RelativeLayout>\n" }, { "code": null, "e": 2274, "s": 2226, "text": "Step 3 − Add the following dependency in Gradle" }, { "code": null, "e": 2385, "s": 2274, "text": "implementation 'com.google.zxing:core:3.2.1'\nimplementation 'com.journeyapps:zxing-android-embedded:3.2.0@aar'" }, { "code": null, "e": 2442, "s": 2385, "text": "Step 4 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4407, "s": 2442, "text": "import androidx.appcompat.app.AppCompatActivity;\nimport android.content.Intent;\nimport android.os.Bundle;\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.TextView;\nimport android.widget.Toast;\nimport com.google.zxing.integration.android.IntentIntegrator;\nimport com.google.zxing.integration.android.IntentResult;\npublic class MainActivity extends AppCompatActivity {\n Button btnBarcode;\n TextView textView;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n btnBarcode = findViewById(R.id.button);\n textView = findViewById(R.id.txtContent);\n btnBarcode.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n IntentIntegrator intentIntegrator = new IntentIntegrator(MainActivity.this);\n intentIntegrator.setDesiredBarcodeFormats(intentIntegrator.ALL_CODE_TYPES);\n intentIntegrator.setBeepEnabled(false);\n intentIntegrator.setCameraId(0);\n intentIntegrator.setPrompt(\"SCAN\");\n intentIntegrator.setBarcodeImageEnabled(false);\n intentIntegrator.initiateScan();\n }\n });\n }\n @Override\n protected void onActivityResult(int requestCode, int resultCode, Intent data) {\n IntentResult Result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);\n if (Result != null) {\n if (Result.getContents() == null) {\n Toast.makeText(this, \"cancelled\", Toast.LENGTH_SHORT).show();\n } else {\n Log.d(\"MainActivity\", \"Scanned\");\n Toast.makeText(this, \"Scanned -> \" + Result.getContents(), Toast.LENGTH_SHORT).show();\ntextView.setText(String.format(\"Scanned Result: %s\", Result));\n }\n } else {\n super.onActivityResult(requestCode, resultCode, data);\n }\n }\n}\n" }, { "code": null, "e": 4462, "s": 4407, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5390, "s": 4462, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n</application>\n<uses-feature android:name=\"android.hardware.camera.autoFocus\" />\n<uses-feature android:name=\"android.hardware.camera\" />\n<uses-permission android:name=\"android.permission.CAMERA\" />\n<uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />\n</manifest>" }, { "code": null, "e": 5744, "s": 5390, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from the android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" }, { "code": null, "e": 5786, "s": 5744, "text": "Check with real device for better result." } ]
Max Chunks To Make Sorted II in C++
Suppose we have an array arr of integers, we have to split the array into some number of partitions, and individually sort each partition. Now after concatenating them we will get one sorted array. We have to find the maximum number of partitions we could have made? So, if the input is like [3,2,4,5,5], then the output will be 4, as we can make partitions like [3,2], [4], [5], [5]. To solve this, we will follow these steps − cnt := 1 cnt := 1 n := size of arr n := size of arr Define an array maxOfLeft of size n Define an array maxOfLeft of size n Define an array minOfRight of size n Define an array minOfRight of size n maxOfLeft[0] := arr[0] maxOfLeft[0] := arr[0] for initialize i := 1, when i < n, update (increase i by 1), do −maxOfLeft[i] := maximum of maxOfLeft[i - 1] and arr[i] for initialize i := 1, when i < n, update (increase i by 1), do − maxOfLeft[i] := maximum of maxOfLeft[i - 1] and arr[i] maxOfLeft[i] := maximum of maxOfLeft[i - 1] and arr[i] minOfRight[n - 1] = arr[n - 1] minOfRight[n - 1] = arr[n - 1] for initialize i := n - 2, when i >= 0, update (decrease i by 1), do −minOfRight[i] := minimum of minOfRight[i + 1] and arr[i] for initialize i := n - 2, when i >= 0, update (decrease i by 1), do − minOfRight[i] := minimum of minOfRight[i + 1] and arr[i] minOfRight[i] := minimum of minOfRight[i + 1] and arr[i] for initialize i := 0, when i < n - 1, update (increase i by 1), do −if minOfRight[i + 1] >= maxOfLeft[i], then −(increase cnt by 1) for initialize i := 0, when i < n - 1, update (increase i by 1), do − if minOfRight[i + 1] >= maxOfLeft[i], then −(increase cnt by 1) if minOfRight[i + 1] >= maxOfLeft[i], then − (increase cnt by 1) (increase cnt by 1) return cnt return cnt Let us see the following implementation to get better understanding − Live Demo #include <bits/stdc++.h> using namespace std; class Solution { public: int maxChunksToSorted(vector<int>& arr) { int cnt = 1; int n = arr.size(); vector<int> maxOfLeft(n); vector<int> minOfRight(n); maxOfLeft[0] = arr[0]; for (int i = 1; i < n; i++) maxOfLeft[i] = max(maxOfLeft[i - 1], arr[i]); minOfRight[n - 1] = arr[n - 1]; for (int i = n - 2; i >= 0; i--) minOfRight[i] = min(minOfRight[i + 1], arr[i]); for (int i = 0; i < n - 1; i++) { if (minOfRight[i + 1] >= maxOfLeft[i]) cnt++; } return cnt; } }; main(){ Solution ob; vector<int> v = {3,2,4,5,5}; cout << (ob.maxChunksToSorted(v)); } {3,2,4,5,5} 4
[ { "code": null, "e": 1329, "s": 1062, "text": "Suppose we have an array arr of integers, we have to split the array into some number of partitions, and individually sort each partition. Now after concatenating them we will get one sorted array. We have to find the maximum number of partitions we could have made?" }, { "code": null, "e": 1447, "s": 1329, "text": "So, if the input is like [3,2,4,5,5], then the output will be 4, as we can make partitions like [3,2], [4], [5], [5]." }, { "code": null, "e": 1491, "s": 1447, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1500, "s": 1491, "text": "cnt := 1" }, { "code": null, "e": 1509, "s": 1500, "text": "cnt := 1" }, { "code": null, "e": 1526, "s": 1509, "text": "n := size of arr" }, { "code": null, "e": 1543, "s": 1526, "text": "n := size of arr" }, { "code": null, "e": 1579, "s": 1543, "text": "Define an array maxOfLeft of size n" }, { "code": null, "e": 1615, "s": 1579, "text": "Define an array maxOfLeft of size n" }, { "code": null, "e": 1652, "s": 1615, "text": "Define an array minOfRight of size n" }, { "code": null, "e": 1689, "s": 1652, "text": "Define an array minOfRight of size n" }, { "code": null, "e": 1712, "s": 1689, "text": "maxOfLeft[0] := arr[0]" }, { "code": null, "e": 1735, "s": 1712, "text": "maxOfLeft[0] := arr[0]" }, { "code": null, "e": 1855, "s": 1735, "text": "for initialize i := 1, when i < n, update (increase i by 1), do −maxOfLeft[i] := maximum of maxOfLeft[i - 1] and arr[i]" }, { "code": null, "e": 1921, "s": 1855, "text": "for initialize i := 1, when i < n, update (increase i by 1), do −" }, { "code": null, "e": 1976, "s": 1921, "text": "maxOfLeft[i] := maximum of maxOfLeft[i - 1] and arr[i]" }, { "code": null, "e": 2031, "s": 1976, "text": "maxOfLeft[i] := maximum of maxOfLeft[i - 1] and arr[i]" }, { "code": null, "e": 2062, "s": 2031, "text": "minOfRight[n - 1] = arr[n - 1]" }, { "code": null, "e": 2093, "s": 2062, "text": "minOfRight[n - 1] = arr[n - 1]" }, { "code": null, "e": 2220, "s": 2093, "text": "for initialize i := n - 2, when i >= 0, update (decrease i by 1), do −minOfRight[i] := minimum of minOfRight[i + 1] and arr[i]" }, { "code": null, "e": 2291, "s": 2220, "text": "for initialize i := n - 2, when i >= 0, update (decrease i by 1), do −" }, { "code": null, "e": 2348, "s": 2291, "text": "minOfRight[i] := minimum of minOfRight[i + 1] and arr[i]" }, { "code": null, "e": 2405, "s": 2348, "text": "minOfRight[i] := minimum of minOfRight[i + 1] and arr[i]" }, { "code": null, "e": 2538, "s": 2405, "text": "for initialize i := 0, when i < n - 1, update (increase i by 1), do −if minOfRight[i + 1] >= maxOfLeft[i], then −(increase cnt by 1)" }, { "code": null, "e": 2608, "s": 2538, "text": "for initialize i := 0, when i < n - 1, update (increase i by 1), do −" }, { "code": null, "e": 2672, "s": 2608, "text": "if minOfRight[i + 1] >= maxOfLeft[i], then −(increase cnt by 1)" }, { "code": null, "e": 2717, "s": 2672, "text": "if minOfRight[i + 1] >= maxOfLeft[i], then −" }, { "code": null, "e": 2737, "s": 2717, "text": "(increase cnt by 1)" }, { "code": null, "e": 2757, "s": 2737, "text": "(increase cnt by 1)" }, { "code": null, "e": 2768, "s": 2757, "text": "return cnt" }, { "code": null, "e": 2779, "s": 2768, "text": "return cnt" }, { "code": null, "e": 2849, "s": 2779, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2860, "s": 2849, "text": " Live Demo" }, { "code": null, "e": 3578, "s": 2860, "text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int maxChunksToSorted(vector<int>& arr) {\n int cnt = 1;\n int n = arr.size();\n vector<int> maxOfLeft(n);\n vector<int> minOfRight(n);\n maxOfLeft[0] = arr[0];\n for (int i = 1; i < n; i++)\n maxOfLeft[i] = max(maxOfLeft[i - 1], arr[i]);\n minOfRight[n - 1] = arr[n - 1];\n for (int i = n - 2; i >= 0; i--)\n minOfRight[i] = min(minOfRight[i + 1], arr[i]);\n for (int i = 0; i < n - 1; i++) {\n if (minOfRight[i + 1] >= maxOfLeft[i])\n cnt++;\n }\n return cnt;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {3,2,4,5,5};\n cout << (ob.maxChunksToSorted(v));\n}" }, { "code": null, "e": 3590, "s": 3578, "text": "{3,2,4,5,5}" }, { "code": null, "e": 3592, "s": 3590, "text": "4" } ]
Is Python object-oriented?. This tutorial answers the question of... | by Tanu N Prabhu | Towards Data Science
This tutorial answers the question of whether python is objected oriented or not? Well Is Python an object oriented programming language? Yes, it is. With the exception of control flow, everything in Python is an object. By Max Fischer, who answers this question in Quora. Yes, python is an objected oriented programming language. Everything in python is an object. Using python we can create classes and objects. Here in this tutorial, I would be discussing only classes and objects. The entire source code can be found in my GitHub Repository below: github.com Classes: Class is like a blueprint that helps to create an object. In other words, a class comprises variables, methods, functions. Or you can refer class which contains properties and behavior. For example Consider a class “Ball” now the properties of Ball might be color, diameter, price and the behavior of the ball might be rolling, bouncing. Objects: Objects are an instance of a class. With the help of objects, we can access the method and function of a class. Now let us see how to create a class and an object in python Creating a class in Python is trivial, all you have to do is use a keyword called “class” along with a name which is often referred to as the name of the class. Inside the class, we can either declare functions or variables. class python: def designer(): print(“Guido van Rossum”) def first_appeared(): print(“1990; 29 years ago”) In order to access the function inside the class all you have to do call the class with its class name and with the “.” dot operator call its function. We can access the class in two ways: Without creating the object and creating an object. Without creating an Object Just use the class name along with the dot operator to access the functions inside the class. python.designer()Guido van Rossumpython.first_appeared()1990; 29 years ago Creating an object p = pythonp.designer()Guido van Rossump.first_appeared()1990; 29 years ago Now creating an object is not a hard task all you have to do is just use a variable named “p” in this case and assign it to the class “python” and then with the help of a dot operator you can invoke the functions inside the class. The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class. Credits — w3schools You can name the self parameter anything you like, its not mandatory to call it as self. class Dog: def __init__(self, name, age): self.name = name self.age = age def func(a): print(“Hello my dog’s name is “ + a.name + “ and its age is “ + a.age)p1 = Dog(“Danny”, “10”)p1.func()Hello my dog's name is Danny and its age is 10 Here in the above example, I am using the init() which is executed when the class is being initiated. Here every class contains the init() function. As seen above with the help of the self parameter we can access the variables inside the class. class Dog: breed = "Alaskan Malamute" age = 10d = Dog()print(d.breed)print("--------------------")d.breed = "Labrador"print(d.breed)Alaskan Malamute -------------------- Labrador You can delete an object by using the del keyword: class Dog: print(“Alaskan Malamute”) print(“10”)Alaskan Malamute 10d = Dog()print(d)<__main__.Dog object at 0x7f1cb938ceb8>del dprint(d)--------------------------------------------------------------------NameError Traceback (most recent call last)<ipython-input-53-85549cb1de5f> in <module>()----> 1 print(d)NameError: name 'd' is not defined You can delete properties on objects by using the del keyword: class Dog: name_of_the_dog = "Danny"d = Dogdel d.name_of_the_dogprint(d.name_of_the_dog)--------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-38-e6d330ce7a18> in <module>()----> 1 print(d.name_of_the_dog)AttributeError: type object 'Dog' has no attribute 'name_of_the_dog' To do this all you have to do is create an object of class type and using the dot operator access the name of the variable and the function of the class. class dog: age = 10 def name(): print("Danny")d = dogd.age10d.name()Danny I think now you guys believe that python is an objected oriented programming language. This is the end of the tutorial, I know this is a short tutorial, but this is enough for a good start to know more classes and objects. To read the official documentation of python classes I would recommend you guys to go through below: docs.python.org In the upcoming tutorials, I will provide documentation about Inheritance, Parent and Child class and many more. Until then see you, Have a great day.
[ { "code": null, "e": 253, "s": 171, "text": "This tutorial answers the question of whether python is objected oriented or not?" }, { "code": null, "e": 444, "s": 253, "text": "Well Is Python an object oriented programming language? Yes, it is. With the exception of control flow, everything in Python is an object. By Max Fischer, who answers this question in Quora." }, { "code": null, "e": 723, "s": 444, "text": "Yes, python is an objected oriented programming language. Everything in python is an object. Using python we can create classes and objects. Here in this tutorial, I would be discussing only classes and objects. The entire source code can be found in my GitHub Repository below:" }, { "code": null, "e": 734, "s": 723, "text": "github.com" }, { "code": null, "e": 1081, "s": 734, "text": "Classes: Class is like a blueprint that helps to create an object. In other words, a class comprises variables, methods, functions. Or you can refer class which contains properties and behavior. For example Consider a class “Ball” now the properties of Ball might be color, diameter, price and the behavior of the ball might be rolling, bouncing." }, { "code": null, "e": 1202, "s": 1081, "text": "Objects: Objects are an instance of a class. With the help of objects, we can access the method and function of a class." }, { "code": null, "e": 1263, "s": 1202, "text": "Now let us see how to create a class and an object in python" }, { "code": null, "e": 1488, "s": 1263, "text": "Creating a class in Python is trivial, all you have to do is use a keyword called “class” along with a name which is often referred to as the name of the class. Inside the class, we can either declare functions or variables." }, { "code": null, "e": 1614, "s": 1488, "text": "class python: def designer(): print(“Guido van Rossum”) def first_appeared(): print(“1990; 29 years ago”)" }, { "code": null, "e": 1855, "s": 1614, "text": "In order to access the function inside the class all you have to do call the class with its class name and with the “.” dot operator call its function. We can access the class in two ways: Without creating the object and creating an object." }, { "code": null, "e": 1882, "s": 1855, "text": "Without creating an Object" }, { "code": null, "e": 1976, "s": 1882, "text": "Just use the class name along with the dot operator to access the functions inside the class." }, { "code": null, "e": 2051, "s": 1976, "text": "python.designer()Guido van Rossumpython.first_appeared()1990; 29 years ago" }, { "code": null, "e": 2070, "s": 2051, "text": "Creating an object" }, { "code": null, "e": 2145, "s": 2070, "text": "p = pythonp.designer()Guido van Rossump.first_appeared()1990; 29 years ago" }, { "code": null, "e": 2376, "s": 2145, "text": "Now creating an object is not a hard task all you have to do is just use a variable named “p” in this case and assign it to the class “python” and then with the help of a dot operator you can invoke the functions inside the class." }, { "code": null, "e": 2526, "s": 2376, "text": "The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class. Credits — w3schools" }, { "code": null, "e": 2615, "s": 2526, "text": "You can name the self parameter anything you like, its not mandatory to call it as self." }, { "code": null, "e": 2885, "s": 2615, "text": "class Dog: def __init__(self, name, age): self.name = name self.age = age def func(a): print(“Hello my dog’s name is “ + a.name + “ and its age is “ + a.age)p1 = Dog(“Danny”, “10”)p1.func()Hello my dog's name is Danny and its age is 10" }, { "code": null, "e": 3130, "s": 2885, "text": "Here in the above example, I am using the init() which is executed when the class is being initiated. Here every class contains the init() function. As seen above with the help of the self parameter we can access the variables inside the class." }, { "code": null, "e": 3315, "s": 3130, "text": "class Dog: breed = \"Alaskan Malamute\" age = 10d = Dog()print(d.breed)print(\"--------------------\")d.breed = \"Labrador\"print(d.breed)Alaskan Malamute -------------------- Labrador" }, { "code": null, "e": 3366, "s": 3315, "text": "You can delete an object by using the del keyword:" }, { "code": null, "e": 3731, "s": 3366, "text": "class Dog: print(“Alaskan Malamute”) print(“10”)Alaskan Malamute 10d = Dog()print(d)<__main__.Dog object at 0x7f1cb938ceb8>del dprint(d)--------------------------------------------------------------------NameError Traceback (most recent call last)<ipython-input-53-85549cb1de5f> in <module>()----> 1 print(d)NameError: name 'd' is not defined" }, { "code": null, "e": 3794, "s": 3731, "text": "You can delete properties on objects by using the del keyword:" }, { "code": null, "e": 4153, "s": 3794, "text": "class Dog: name_of_the_dog = \"Danny\"d = Dogdel d.name_of_the_dogprint(d.name_of_the_dog)--------------------------------------------------------------------AttributeError Traceback (most recent call last)<ipython-input-38-e6d330ce7a18> in <module>()----> 1 print(d.name_of_the_dog)AttributeError: type object 'Dog' has no attribute 'name_of_the_dog'" }, { "code": null, "e": 4307, "s": 4153, "text": "To do this all you have to do is create an object of class type and using the dot operator access the name of the variable and the function of the class." }, { "code": null, "e": 4394, "s": 4307, "text": "class dog: age = 10 def name(): print(\"Danny\")d = dogd.age10d.name()Danny" }, { "code": null, "e": 4718, "s": 4394, "text": "I think now you guys believe that python is an objected oriented programming language. This is the end of the tutorial, I know this is a short tutorial, but this is enough for a good start to know more classes and objects. To read the official documentation of python classes I would recommend you guys to go through below:" }, { "code": null, "e": 4734, "s": 4718, "text": "docs.python.org" } ]
Ensembling ConvNets using Keras. Use multiple neural nets to obtain... | by Maxim Mikhaylov | Towards Data Science
Edit: February 2019 Minor code changes. Improved experience of Jupyter notebook version of the article. In statistics and machine learning, ensemble methods use multiple learning algorithms to obtain better predictive performance than could be obtained from any of the constituent learning algorithms alone. Unlike a statistical ensemble in statistical mechanics, which is usually infinite, a machine learning ensemble consists of only a concrete finite set of alternative models, but typically allows for much more flexible structure to exist among those alternatives. [1] The main motivation for using an ensemble is to find a hypothesis that is not necessarily contained within the hypothesis space of the models from which it is built. Empirically, ensembles tend to yield better results when there is a significant diversity among the models. [2] If you look at results of a big machine learning competition, you will most likely find that the top results are achieved by an ensemble of models rather than a single model. For instance, the top-scoring single model architecture at ILSVRC2015 is on place 13. Places 1–12 are taken by various ensembles. I haven’t seen a tutorial or documentation on how to use multiple neural networks in an ensemble, so I decided to make a practical guide on this topic. I will be using Keras, specifically its Functional API, to recreate three small CNNs (compared to ResNet50, Inception etc.) from relatively well-known papers. I will train each model separately on CIFAR-10 training dataset. [3] Then each model will be evaluated using the test set. After that, I will put all three models in an ensemble and evaluate it. It is expected that the ensemble will perform better on a test set than any single model in the ensemble separately. There are many different types of ensembles; stacking is one of them. It is one of the more general types and can theoretically represent any other ensemble technique. Stacking involves training a learning algorithm to combine the predictions of several other learning algorithms. [1] For the sake of this example, I will use one of the simplest forms of Stacking, which involves taking an average of outputs of models in the ensemble. Since averaging doesn’t take any parameters, there is no need to train this ensemble (only its models). First, import dependencies. from keras.callbacks import Historyfrom keras.callbacks import ModelCheckpoint, TensorBoardfrom keras.datasets import cifar10from keras.engine import trainingfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, Dropout, Activation, Averagefrom keras.losses import categorical_crossentropyfrom keras.models import Model, Inputfrom keras.optimizers import Adamfrom keras.utils import to_categoricalfrom tensorflow.python.framework.ops import Tensorfrom typing import Tuple, Listimport globimport numpy as npimport os I am using CIFAR-10, since it is relatively easy to find papers describing architectures that work well on this dataset. Using a popular dataset also makes this example easily reproducible. Here the dataset is imported. Both train and test image data is normalized. The training label vector is converted to a one-hot-matrix. Don’t need to convert the test label vector, since it won’t be used during training. def load_data() -> Tuple [np.ndarray, np.ndarray, np.ndarray, np.ndarray]: (x_train, y_train), (x_test, y_test) = cifar10.load_data() x_train = x_train / 255. x_test = x_test / 255. y_train = to_categorical(y_train, num_classes=10) return x_train, x_test, y_train, y_testx_train, x_test, y_train, y_test = load_data() The dataset consists of 60000 32x32 RGB images from 10 classes. 50000 images are used for training/validation and the other 10000 for testing. print('x_train shape: {} | y_train shape: {}\nx_test shape : {} | y_test shape : {}'.format(x_train.shape, y_train.shape, x_test.shape, y_test.shape)) >>> x_train shape: (50000, 32, 32, 3) | y_train shape: (50000, 10) >>> x_test shape : (10000, 32, 32, 3) | y_test shape : (10000, 1) Since all three models work with the data of the same shape, it makes sense to define a single input layer that will be used by every model. input_shape = x_train[0,:,:,:].shapemodel_input = Input(shape=input_shape) The first model that I am going to train is ConvPool-CNN-C . [4] Its descritption appears on page 4 of the linked paper. The model is pretty straightforward. It features a common pattern where several convolutional layers are followed by a pooling layer. The only thing about this model that might be unfamiliar to some people is its final layers. Instead of using several fully-connected layers, a global average pooling layer is used. Here is a brief overview of how global pooling layer works. The last convolutional layer Conv2D(10, (1, 1)) outputs 10 feature maps corresponding to ten output classes. Then the GlobalAveragePooling2D() layer computes spatial average of these 10 feature maps, which means that its output is just a vector with a lenght 10. After that, a softmax activation is applied to that vector. As you can see, this method is in some way analogous to using FC layers at the top of the model. You can read more about global pooling layers and their advantages in Network in Network paper. [5] One important thing to note: there’s no activation function applied to the output of the final Conv2D(10, (1, 1)) layer, since the output of this layer has to go through GlobalAveragePooling2D() first. def conv_pool_cnn(model_input: Tensor) -> training.Model: x = Conv2D(96, kernel_size=(3, 3), activation='relu', padding = 'same')(model_input) x = Conv2D(96, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(96, (3, 3), activation='relu', padding = 'same')(x) x = MaxPooling2D(pool_size=(3, 3), strides = 2)(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = MaxPooling2D(pool_size=(3, 3), strides = 2)(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(192, (1, 1), activation='relu')(x) x = Conv2D(10, (1, 1))(x) x = GlobalAveragePooling2D()(x) x = Activation(activation='softmax')(x) model = Model(model_input, x, name='conv_pool_cnn') return model Instantiate the model. conv_pool_cnn_model = conv_pool_cnn(model_input) For simplicity’s sake, each model is compiled and trained using the same parameters. Using 20 epochs with a batch size of 32 (1250 steps per epoch) seems sufficient for any of the three models to get to some local minima. Randomly chosen 20% of the training dataset is used for validation. NUM_EPOCHS = 20def compile_and_train(model: training.Model, num_epochs: int) -> Tuple [History, str]: model.compile(loss=categorical_crossentropy, optimizer=Adam(), metrics=['acc']) filepath = 'weights/' + model.name + '.{epoch:02d}-{loss:.2f}.hdf5' checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=0, save_weights_only=True, save_best_only=True, mode='auto', period=1) tensor_board = TensorBoard(log_dir='logs/', histogram_freq=0, batch_size=32) history = model.fit(x=x_train, y=y_train, batch_size=32, epochs=num_epochs, verbose=1, callbacks=[checkpoint, tensor_board], validation_split=0.2) weight_files = glob.glob(os.path.join(os.getcwd(), 'weights/*')) weight_file = max(weight_files, key=os.path.getctime) # most recent file return history, weight_file It takes about 1 min to train this and the next model for one epoch using a single Tesla K80 GPU. Training might take a while if you are using a CPU. _, conv_pool_cnn_weight_file = compile_and_train(conv_pool_cnn_model, NUM_EPOCHS) The model achieves ~79% validation accuracy. Evaluate the model by calculating the error rate on the test set. def evaluate_error(model: training.Model) -> np.float64: pred = model.predict(x_test, batch_size = 32) pred = np.argmax(pred, axis=1) pred = np.expand_dims(pred, axis=1) # make same shape as y_test error = np.sum(np.not_equal(pred, y_test)) / y_test.shape[0] return errorevaluate_error(conv_pool_cnn_model) >>> 0.2414 The next CNN, ALL-CNN-C, comes from the same paper. [4] This model is very similar to the previous one. Really, the only difference is that convolutional layers with a stride of 2 are used in place of max pooling layers. Again, note that there is no activation function used immediately after the Conv2D(10, (1, 1)) layer. The model will fail to train if a ReLU activation is used immediately after that layer. def all_cnn(model_input: Tensor) -> training.Model: x = Conv2D(96, kernel_size=(3, 3), activation='relu', padding = 'same')(model_input) x = Conv2D(96, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(96, (3, 3), activation='relu', padding = 'same', strides = 2)(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same', strides = 2)(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(192, (1, 1), activation='relu')(x) x = Conv2D(10, (1, 1))(x) x = GlobalAveragePooling2D()(x) x = Activation(activation='softmax')(x) model = Model(model_input, x, name='all_cnn') return modelall_cnn_model = all_cnn(model_input)_, all_cnn_weight_file = compile_and_train(all_cnn_model, NUM_EPOCHS) The model converges to ~75% validation accuracy. Since two models are very similar to each other, the error rate doesn’t differ much. evaluate_error(all_cnn_model) >>> 0.26090000000000002 The third CNN is Network in Network CNN. [5] This is a CNN from the paper that introduced global pooling layers. It’s smaller than previous two models, therefore is much faster to train. No relu after the final convolutional layer! Instead of using multilayer perceptron inside MLP convolution layer, I used convolutional layers with 1x1 kernel. This way there are less parameters to optimize, the training goes faster and I could achieve better results (couldn’t get validation accuracy higher than 50% when using FC layers). The paper says that the function applied by mlpconv layer is equivalent to cascaded cross channel parametric pooling on a normal convolution layer, which in turn is equivalent to a convolution layer with 1x1 convolution kernel. Please correct me if I my interpretation of the architecture is incorrect. def nin_cnn(model_input: Tensor) -> training.Model: #mlpconv block 1 x = Conv2D(32, (5, 5), activation='relu',padding='valid')(model_input) x = Conv2D(32, (1, 1), activation='relu')(x) x = Conv2D(32, (1, 1), activation='relu')(x) x = MaxPooling2D((2,2))(x) x = Dropout(0.5)(x) #mlpconv block2 x = Conv2D(64, (3, 3), activation='relu',padding='valid')(x) x = Conv2D(64, (1, 1), activation='relu')(x) x = Conv2D(64, (1, 1), activation='relu')(x) x = MaxPooling2D((2,2))(x) x = Dropout(0.5)(x) #mlpconv block3 x = Conv2D(128, (3, 3), activation='relu',padding='valid')(x) x = Conv2D(32, (1, 1), activation='relu')(x) x = Conv2D(10, (1, 1))(x) x = GlobalAveragePooling2D()(x) x = Activation(activation='softmax')(x) model = Model(model_input, x, name='nin_cnn') return modelnin_cnn_model = nin_cnn(model_input) This model trains much faster — 15 seconds per epoch on my machine. _, nin_cnn_weight_file = compile_and_train(nin_cnn_model, NUM_EPOCHS) The model achieves ~65% validation accuracy. This model is more simple than the other two, so the error rate is a bit higher. evaluate_error(nin_cnn_model) >>> 0. 0.31640000000000001 Now all three models will be combined in an ensemble. Here, all three models are reinstantiated and the best saved weights are loaded. CONV_POOL_CNN_WEIGHT_FILE = os.path.join(os.getcwd(), 'weights', 'conv_pool_cnn_pretrained_weights.hdf5')ALL_CNN_WEIGHT_FILE = os.path.join(os.getcwd(), 'weights', 'all_cnn_pretrained_weights.hdf5')NIN_CNN_WEIGHT_FILE = os.path.join(os.getcwd(), 'weights', 'nin_cnn_pretrained_weights.hdf5')conv_pool_cnn_model = conv_pool_cnn(model_input)all_cnn_model = all_cnn(model_input)nin_cnn_model = nin_cnn(model_input)conv_pool_cnn_model.load_weights(CONV_POOL_CNN_WEIGHT_FILE)all_cnn_model.load_weights(ALL_CNN_WEIGHT_FILE)nin_cnn_model.load_weights(NIN_CNN_WEIGHT_FILE)models = [conv_pool_cnn_model, all_cnn_model, nin_cnn_model] Ensemble model definition is very straightforward. It uses the same input layer that is shared between all previous models. In the top layer, the ensemble computes the average of three models’ outputs by using Average() merge layer. def ensemble(models: List [training.Model], model_input: Tensor) -> training.Model: outputs = [model.outputs[0] for model in models] y = Average()(outputs) model = Model(model_input, y, name='ensemble') return model As expected, the ensemble has a lower error rate than any single model. evaluate_error(ensemble_model) >>> 0.2049 Just for completeness, we can check performance of ensembles that consist of 2 model combinations. Two of them have lower error rate than single models. pair_A = [conv_pool_cnn_model, all_cnn_model]pair_B = [conv_pool_cnn_model, nin_cnn_model]pair_C = [all_cnn_model, nin_cnn_model]pair_A_ensemble_model = ensemble(pair_A, model_input)evaluate_error(pair_A_ensemble_model) >>> 0.21199999999999999 pair_B_ensemble_model = ensemble(pair_B, model_input)evaluate_error(pair_B_ensemble_model) >>> 0.22819999999999999 pair_C_ensemble_model = ensemble(pair_C, model_input)evaluate_error(pair_C_ensemble_model) >>> 0.2447 To reiterate what was said in the introduction: every model has its own weaknesses. The reasoning behind using an ensemble is that by stacking different models representing different hypotheses about the data, we can find a better hypothesis that is not in the hypothesis space of the models from which the ensemble is built. By using a very basic ensemble, a lower error rate was achieved than when a single model was used in most cases. This proves effectiveness of ensembling. Of course, there are some practical considerations to keep in mind when using an ensemble for your machine learning task. Since ensembling means stacking multiple models together, it also means that the input data needs to be forward-propagated for each model. This increases the amount of compute that needs to be performed and, consequently, evaluation (predicition) time. Increased evaluation time is not critical if you use an ensemble in research or in a Kaggle competition. However, it is a very critical factor when designing a commercial product. Another consideration is increased size of the final model which, again, might be a limiting factor for ensemble use in a commercial product. You can get the Jupyter notebook source code from my GitHub. Ensemble Learning. (n.d.). In Wikipedia. Retrieved December 12, 2017, from https://en.wikipedia.org/wiki/Ensemble_learningD. Opitz and R. Maclin (1999) “Popular Ensemble Methods: An Empirical Study”, Volume 11, pages 169–198 (available at http://jair.org/papers/paper614.html)Learning Multiple Layers of Features from Tiny Images, Alex Krizhevsky, 2009.arXiv:1412.6806v3 [cs.LG]arXiv:1312.4400v3 [cs.NE] Ensemble Learning. (n.d.). In Wikipedia. Retrieved December 12, 2017, from https://en.wikipedia.org/wiki/Ensemble_learning D. Opitz and R. Maclin (1999) “Popular Ensemble Methods: An Empirical Study”, Volume 11, pages 169–198 (available at http://jair.org/papers/paper614.html) Learning Multiple Layers of Features from Tiny Images, Alex Krizhevsky, 2009.
[ { "code": null, "e": 192, "s": 172, "text": "Edit: February 2019" }, { "code": null, "e": 276, "s": 192, "text": "Minor code changes. Improved experience of Jupyter notebook version of the article." }, { "code": null, "e": 746, "s": 276, "text": "In statistics and machine learning, ensemble methods use multiple learning algorithms to obtain better predictive performance than could be obtained from any of the constituent learning algorithms alone. Unlike a statistical ensemble in statistical mechanics, which is usually infinite, a machine learning ensemble consists of only a concrete finite set of alternative models, but typically allows for much more flexible structure to exist among those alternatives. [1]" }, { "code": null, "e": 1024, "s": 746, "text": "The main motivation for using an ensemble is to find a hypothesis that is not necessarily contained within the hypothesis space of the models from which it is built. Empirically, ensembles tend to yield better results when there is a significant diversity among the models. [2]" }, { "code": null, "e": 1329, "s": 1024, "text": "If you look at results of a big machine learning competition, you will most likely find that the top results are achieved by an ensemble of models rather than a single model. For instance, the top-scoring single model architecture at ILSVRC2015 is on place 13. Places 1–12 are taken by various ensembles." }, { "code": null, "e": 1481, "s": 1329, "text": "I haven’t seen a tutorial or documentation on how to use multiple neural networks in an ensemble, so I decided to make a practical guide on this topic." }, { "code": null, "e": 1952, "s": 1481, "text": "I will be using Keras, specifically its Functional API, to recreate three small CNNs (compared to ResNet50, Inception etc.) from relatively well-known papers. I will train each model separately on CIFAR-10 training dataset. [3] Then each model will be evaluated using the test set. After that, I will put all three models in an ensemble and evaluate it. It is expected that the ensemble will perform better on a test set than any single model in the ensemble separately." }, { "code": null, "e": 2492, "s": 1952, "text": "There are many different types of ensembles; stacking is one of them. It is one of the more general types and can theoretically represent any other ensemble technique. Stacking involves training a learning algorithm to combine the predictions of several other learning algorithms. [1] For the sake of this example, I will use one of the simplest forms of Stacking, which involves taking an average of outputs of models in the ensemble. Since averaging doesn’t take any parameters, there is no need to train this ensemble (only its models)." }, { "code": null, "e": 2520, "s": 2492, "text": "First, import dependencies." }, { "code": null, "e": 3053, "s": 2520, "text": "from keras.callbacks import Historyfrom keras.callbacks import ModelCheckpoint, TensorBoardfrom keras.datasets import cifar10from keras.engine import trainingfrom keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D, Dropout, Activation, Averagefrom keras.losses import categorical_crossentropyfrom keras.models import Model, Inputfrom keras.optimizers import Adamfrom keras.utils import to_categoricalfrom tensorflow.python.framework.ops import Tensorfrom typing import Tuple, Listimport globimport numpy as npimport os" }, { "code": null, "e": 3243, "s": 3053, "text": "I am using CIFAR-10, since it is relatively easy to find papers describing architectures that work well on this dataset. Using a popular dataset also makes this example easily reproducible." }, { "code": null, "e": 3464, "s": 3243, "text": "Here the dataset is imported. Both train and test image data is normalized. The training label vector is converted to a one-hot-matrix. Don’t need to convert the test label vector, since it won’t be used during training." }, { "code": null, "e": 3823, "s": 3464, "text": "def load_data() -> Tuple [np.ndarray, np.ndarray, np.ndarray, np.ndarray]: (x_train, y_train), (x_test, y_test) = cifar10.load_data() x_train = x_train / 255. x_test = x_test / 255. y_train = to_categorical(y_train, num_classes=10) return x_train, x_test, y_train, y_testx_train, x_test, y_train, y_test = load_data()" }, { "code": null, "e": 3966, "s": 3823, "text": "The dataset consists of 60000 32x32 RGB images from 10 classes. 50000 images are used for training/validation and the other 10000 for testing." }, { "code": null, "e": 4202, "s": 3966, "text": "print('x_train shape: {} | y_train shape: {}\\nx_test shape : {} | y_test shape : {}'.format(x_train.shape, y_train.shape, x_test.shape, y_test.shape))" }, { "code": null, "e": 4269, "s": 4202, "text": ">>> x_train shape: (50000, 32, 32, 3) | y_train shape: (50000, 10)" }, { "code": null, "e": 4335, "s": 4269, "text": ">>> x_test shape : (10000, 32, 32, 3) | y_test shape : (10000, 1)" }, { "code": null, "e": 4476, "s": 4335, "text": "Since all three models work with the data of the same shape, it makes sense to define a single input layer that will be used by every model." }, { "code": null, "e": 4551, "s": 4476, "text": "input_shape = x_train[0,:,:,:].shapemodel_input = Input(shape=input_shape)" }, { "code": null, "e": 4672, "s": 4551, "text": "The first model that I am going to train is ConvPool-CNN-C . [4] Its descritption appears on page 4 of the linked paper." }, { "code": null, "e": 4988, "s": 4672, "text": "The model is pretty straightforward. It features a common pattern where several convolutional layers are followed by a pooling layer. The only thing about this model that might be unfamiliar to some people is its final layers. Instead of using several fully-connected layers, a global average pooling layer is used." }, { "code": null, "e": 5568, "s": 4988, "text": "Here is a brief overview of how global pooling layer works. The last convolutional layer Conv2D(10, (1, 1)) outputs 10 feature maps corresponding to ten output classes. Then the GlobalAveragePooling2D() layer computes spatial average of these 10 feature maps, which means that its output is just a vector with a lenght 10. After that, a softmax activation is applied to that vector. As you can see, this method is in some way analogous to using FC layers at the top of the model. You can read more about global pooling layers and their advantages in Network in Network paper. [5]" }, { "code": null, "e": 5770, "s": 5568, "text": "One important thing to note: there’s no activation function applied to the output of the final Conv2D(10, (1, 1)) layer, since the output of this layer has to go through GlobalAveragePooling2D() first." }, { "code": null, "e": 6663, "s": 5770, "text": "def conv_pool_cnn(model_input: Tensor) -> training.Model: x = Conv2D(96, kernel_size=(3, 3), activation='relu', padding = 'same')(model_input) x = Conv2D(96, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(96, (3, 3), activation='relu', padding = 'same')(x) x = MaxPooling2D(pool_size=(3, 3), strides = 2)(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = MaxPooling2D(pool_size=(3, 3), strides = 2)(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(192, (1, 1), activation='relu')(x) x = Conv2D(10, (1, 1))(x) x = GlobalAveragePooling2D()(x) x = Activation(activation='softmax')(x) model = Model(model_input, x, name='conv_pool_cnn') return model" }, { "code": null, "e": 6686, "s": 6663, "text": "Instantiate the model." }, { "code": null, "e": 6735, "s": 6686, "text": "conv_pool_cnn_model = conv_pool_cnn(model_input)" }, { "code": null, "e": 7025, "s": 6735, "text": "For simplicity’s sake, each model is compiled and trained using the same parameters. Using 20 epochs with a batch size of 32 (1250 steps per epoch) seems sufficient for any of the three models to get to some local minima. Randomly chosen 20% of the training dataset is used for validation." }, { "code": null, "e": 7898, "s": 7025, "text": "NUM_EPOCHS = 20def compile_and_train(model: training.Model, num_epochs: int) -> Tuple [History, str]: model.compile(loss=categorical_crossentropy, optimizer=Adam(), metrics=['acc']) filepath = 'weights/' + model.name + '.{epoch:02d}-{loss:.2f}.hdf5' checkpoint = ModelCheckpoint(filepath, monitor='loss', verbose=0, save_weights_only=True, save_best_only=True, mode='auto', period=1) tensor_board = TensorBoard(log_dir='logs/', histogram_freq=0, batch_size=32) history = model.fit(x=x_train, y=y_train, batch_size=32, epochs=num_epochs, verbose=1, callbacks=[checkpoint, tensor_board], validation_split=0.2) weight_files = glob.glob(os.path.join(os.getcwd(), 'weights/*')) weight_file = max(weight_files, key=os.path.getctime) # most recent file return history, weight_file" }, { "code": null, "e": 8048, "s": 7898, "text": "It takes about 1 min to train this and the next model for one epoch using a single Tesla K80 GPU. Training might take a while if you are using a CPU." }, { "code": null, "e": 8130, "s": 8048, "text": "_, conv_pool_cnn_weight_file = compile_and_train(conv_pool_cnn_model, NUM_EPOCHS)" }, { "code": null, "e": 8175, "s": 8130, "text": "The model achieves ~79% validation accuracy." }, { "code": null, "e": 8241, "s": 8175, "text": "Evaluate the model by calculating the error rate on the test set." }, { "code": null, "e": 8567, "s": 8241, "text": "def evaluate_error(model: training.Model) -> np.float64: pred = model.predict(x_test, batch_size = 32) pred = np.argmax(pred, axis=1) pred = np.expand_dims(pred, axis=1) # make same shape as y_test error = np.sum(np.not_equal(pred, y_test)) / y_test.shape[0] return errorevaluate_error(conv_pool_cnn_model)" }, { "code": null, "e": 8578, "s": 8567, "text": ">>> 0.2414" }, { "code": null, "e": 8989, "s": 8578, "text": "The next CNN, ALL-CNN-C, comes from the same paper. [4] This model is very similar to the previous one. Really, the only difference is that convolutional layers with a stride of 2 are used in place of max pooling layers. Again, note that there is no activation function used immediately after the Conv2D(10, (1, 1)) layer. The model will fail to train if a ReLU activation is used immediately after that layer." }, { "code": null, "e": 9897, "s": 8989, "text": "def all_cnn(model_input: Tensor) -> training.Model: x = Conv2D(96, kernel_size=(3, 3), activation='relu', padding = 'same')(model_input) x = Conv2D(96, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(96, (3, 3), activation='relu', padding = 'same', strides = 2)(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same', strides = 2)(x) x = Conv2D(192, (3, 3), activation='relu', padding = 'same')(x) x = Conv2D(192, (1, 1), activation='relu')(x) x = Conv2D(10, (1, 1))(x) x = GlobalAveragePooling2D()(x) x = Activation(activation='softmax')(x) model = Model(model_input, x, name='all_cnn') return modelall_cnn_model = all_cnn(model_input)_, all_cnn_weight_file = compile_and_train(all_cnn_model, NUM_EPOCHS)" }, { "code": null, "e": 9946, "s": 9897, "text": "The model converges to ~75% validation accuracy." }, { "code": null, "e": 10031, "s": 9946, "text": "Since two models are very similar to each other, the error rate doesn’t differ much." }, { "code": null, "e": 10061, "s": 10031, "text": "evaluate_error(all_cnn_model)" }, { "code": null, "e": 10085, "s": 10061, "text": ">>> 0.26090000000000002" }, { "code": null, "e": 10317, "s": 10085, "text": "The third CNN is Network in Network CNN. [5] This is a CNN from the paper that introduced global pooling layers. It’s smaller than previous two models, therefore is much faster to train. No relu after the final convolutional layer!" }, { "code": null, "e": 10915, "s": 10317, "text": "Instead of using multilayer perceptron inside MLP convolution layer, I used convolutional layers with 1x1 kernel. This way there are less parameters to optimize, the training goes faster and I could achieve better results (couldn’t get validation accuracy higher than 50% when using FC layers). The paper says that the function applied by mlpconv layer is equivalent to cascaded cross channel parametric pooling on a normal convolution layer, which in turn is equivalent to a convolution layer with 1x1 convolution kernel. Please correct me if I my interpretation of the architecture is incorrect." }, { "code": null, "e": 11806, "s": 10915, "text": "def nin_cnn(model_input: Tensor) -> training.Model: #mlpconv block 1 x = Conv2D(32, (5, 5), activation='relu',padding='valid')(model_input) x = Conv2D(32, (1, 1), activation='relu')(x) x = Conv2D(32, (1, 1), activation='relu')(x) x = MaxPooling2D((2,2))(x) x = Dropout(0.5)(x) #mlpconv block2 x = Conv2D(64, (3, 3), activation='relu',padding='valid')(x) x = Conv2D(64, (1, 1), activation='relu')(x) x = Conv2D(64, (1, 1), activation='relu')(x) x = MaxPooling2D((2,2))(x) x = Dropout(0.5)(x) #mlpconv block3 x = Conv2D(128, (3, 3), activation='relu',padding='valid')(x) x = Conv2D(32, (1, 1), activation='relu')(x) x = Conv2D(10, (1, 1))(x) x = GlobalAveragePooling2D()(x) x = Activation(activation='softmax')(x) model = Model(model_input, x, name='nin_cnn') return modelnin_cnn_model = nin_cnn(model_input)" }, { "code": null, "e": 11874, "s": 11806, "text": "This model trains much faster — 15 seconds per epoch on my machine." }, { "code": null, "e": 11944, "s": 11874, "text": "_, nin_cnn_weight_file = compile_and_train(nin_cnn_model, NUM_EPOCHS)" }, { "code": null, "e": 11989, "s": 11944, "text": "The model achieves ~65% validation accuracy." }, { "code": null, "e": 12070, "s": 11989, "text": "This model is more simple than the other two, so the error rate is a bit higher." }, { "code": null, "e": 12100, "s": 12070, "text": "evaluate_error(nin_cnn_model)" }, { "code": null, "e": 12127, "s": 12100, "text": ">>> 0. 0.31640000000000001" }, { "code": null, "e": 12181, "s": 12127, "text": "Now all three models will be combined in an ensemble." }, { "code": null, "e": 12262, "s": 12181, "text": "Here, all three models are reinstantiated and the best saved weights are loaded." }, { "code": null, "e": 12887, "s": 12262, "text": "CONV_POOL_CNN_WEIGHT_FILE = os.path.join(os.getcwd(), 'weights', 'conv_pool_cnn_pretrained_weights.hdf5')ALL_CNN_WEIGHT_FILE = os.path.join(os.getcwd(), 'weights', 'all_cnn_pretrained_weights.hdf5')NIN_CNN_WEIGHT_FILE = os.path.join(os.getcwd(), 'weights', 'nin_cnn_pretrained_weights.hdf5')conv_pool_cnn_model = conv_pool_cnn(model_input)all_cnn_model = all_cnn(model_input)nin_cnn_model = nin_cnn(model_input)conv_pool_cnn_model.load_weights(CONV_POOL_CNN_WEIGHT_FILE)all_cnn_model.load_weights(ALL_CNN_WEIGHT_FILE)nin_cnn_model.load_weights(NIN_CNN_WEIGHT_FILE)models = [conv_pool_cnn_model, all_cnn_model, nin_cnn_model]" }, { "code": null, "e": 13120, "s": 12887, "text": "Ensemble model definition is very straightforward. It uses the same input layer that is shared between all previous models. In the top layer, the ensemble computes the average of three models’ outputs by using Average() merge layer." }, { "code": null, "e": 13360, "s": 13120, "text": "def ensemble(models: List [training.Model], model_input: Tensor) -> training.Model: outputs = [model.outputs[0] for model in models] y = Average()(outputs) model = Model(model_input, y, name='ensemble') return model" }, { "code": null, "e": 13432, "s": 13360, "text": "As expected, the ensemble has a lower error rate than any single model." }, { "code": null, "e": 13463, "s": 13432, "text": "evaluate_error(ensemble_model)" }, { "code": null, "e": 13474, "s": 13463, "text": ">>> 0.2049" }, { "code": null, "e": 13627, "s": 13474, "text": "Just for completeness, we can check performance of ensembles that consist of 2 model combinations. Two of them have lower error rate than single models." }, { "code": null, "e": 13847, "s": 13627, "text": "pair_A = [conv_pool_cnn_model, all_cnn_model]pair_B = [conv_pool_cnn_model, nin_cnn_model]pair_C = [all_cnn_model, nin_cnn_model]pair_A_ensemble_model = ensemble(pair_A, model_input)evaluate_error(pair_A_ensemble_model)" }, { "code": null, "e": 13871, "s": 13847, "text": ">>> 0.21199999999999999" }, { "code": null, "e": 13962, "s": 13871, "text": "pair_B_ensemble_model = ensemble(pair_B, model_input)evaluate_error(pair_B_ensemble_model)" }, { "code": null, "e": 13986, "s": 13962, "text": ">>> 0.22819999999999999" }, { "code": null, "e": 14077, "s": 13986, "text": "pair_C_ensemble_model = ensemble(pair_C, model_input)evaluate_error(pair_C_ensemble_model)" }, { "code": null, "e": 14088, "s": 14077, "text": ">>> 0.2447" }, { "code": null, "e": 14414, "s": 14088, "text": "To reiterate what was said in the introduction: every model has its own weaknesses. The reasoning behind using an ensemble is that by stacking different models representing different hypotheses about the data, we can find a better hypothesis that is not in the hypothesis space of the models from which the ensemble is built." }, { "code": null, "e": 14568, "s": 14414, "text": "By using a very basic ensemble, a lower error rate was achieved than when a single model was used in most cases. This proves effectiveness of ensembling." }, { "code": null, "e": 15265, "s": 14568, "text": "Of course, there are some practical considerations to keep in mind when using an ensemble for your machine learning task. Since ensembling means stacking multiple models together, it also means that the input data needs to be forward-propagated for each model. This increases the amount of compute that needs to be performed and, consequently, evaluation (predicition) time. Increased evaluation time is not critical if you use an ensemble in research or in a Kaggle competition. However, it is a very critical factor when designing a commercial product. Another consideration is increased size of the final model which, again, might be a limiting factor for ensemble use in a commercial product." }, { "code": null, "e": 15326, "s": 15265, "text": "You can get the Jupyter notebook source code from my GitHub." }, { "code": null, "e": 15730, "s": 15326, "text": "Ensemble Learning. (n.d.). In Wikipedia. Retrieved December 12, 2017, from https://en.wikipedia.org/wiki/Ensemble_learningD. Opitz and R. Maclin (1999) “Popular Ensemble Methods: An Empirical Study”, Volume 11, pages 169–198 (available at http://jair.org/papers/paper614.html)Learning Multiple Layers of Features from Tiny Images, Alex Krizhevsky, 2009.arXiv:1412.6806v3 [cs.LG]arXiv:1312.4400v3 [cs.NE]" }, { "code": null, "e": 15853, "s": 15730, "text": "Ensemble Learning. (n.d.). In Wikipedia. Retrieved December 12, 2017, from https://en.wikipedia.org/wiki/Ensemble_learning" }, { "code": null, "e": 16008, "s": 15853, "text": "D. Opitz and R. Maclin (1999) “Popular Ensemble Methods: An Empirical Study”, Volume 11, pages 169–198 (available at http://jair.org/papers/paper614.html)" } ]
Largest even number that can be formed by any number of swaps
07 Jun, 2022 Given an integer N in the form of string, the task is to find the largest even number from the given number when you are allowed to do any number of swaps (swapping the digits of the number). If no even number can be formed then print -1. Examples: Input: N = 1324 Output: 4312 Input: N = 135 Output: -1 No even number can be formed using odd digits. Approach: Sort the string in descending order then we will get the largest number possible with the given digit but it may or may not be an even number. In order to make it even (if it not already), an even digit from the number must be swapped with the last digit and in order to maximize the even number, the even digit which is to be swapped must the smallest even digit from the number. Note that the sorting can be done in linear time using frequency array for the digits of the number as the number of distinct elements that are needed to be sorted can be at most 10 in the worst case. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std;const int MAX = 10; // Function to return the maximum// even number that can be formed// with any number of digit swapsstring getMaxEven(string str, int len){ // To store the frequencies of // all the digits int freq[MAX] = { 0 }; // To store the minimum even digit // and the minimum overall digit int i, minEvenDigit = MAX; for (i = 0; i < len; i++) { int digit = str[i] - '0'; freq[digit]++; // If digit is even then update // the minimum even digit if (digit % 2 == 0) minEvenDigit = min(digit, minEvenDigit); } // If there is no even digit then // it is not possible to generate // an even number with swaps if (minEvenDigit == MAX) return "-1"; // Decrease the frequency of the // digits that need to be swapped freq[minEvenDigit]--; i = 0; // Take every digit starting from the maximum // in order to maximize the number for (int j = MAX - 1; j >= 0; j--) { // Take current digit number of times // it appeared in the original number for (int k = 0; k < freq[j]; k++) str[i++] = (char)(j + '0'); } // Append once instance of the minimum // even digit in the end to make the number even str[i] = (char)(minEvenDigit + '0'); return str;} // Driver codeint main(){ string str = "1023422"; int len = str.length(); // Function call cout << getMaxEven(str, len); return 0;} // Java implementation of the approachclass GFG { static int MAX = 10; // Function to return the maximum // even number that can be formed // with any number of digit swaps static String getMaxEven(String str, int len) { //To store the max even number String maxEven=""; // To store the frequencies of // all the digits int[] freq = new int[MAX]; // To store the minimum even digit int i, minEvenDigit = MAX; for (i = 0; i < len; i++) { int digit = str.charAt(i) - '0'; freq[digit]++; // If digit is even then update // the minimum even digit if (digit % 2 == 0) minEvenDigit = Math.min(digit, minEvenDigit); } // If there is no even digit then // it is not possible to generate // an even number with swaps if (minEvenDigit == MAX) return "-1"; // Decrease the frequency of the // minEvenDigit freq[minEvenDigit]--; i = MAX-1; // Take every digit starting from the maximum // in order to maximize the number while(i>=0) { // Take current digit number of times // it appeared in the original number if(freq[i]>0) { maxEven= maxEven+i; freq[i]--; }else i--; } // Append the minimum even digit // in the end to make the number even maxEven= maxEven+minEvenDigit; return maxEven; } // Driver code public static void main(String[] args) { String str = "1023422"; int len = str.length(); // Function call System.out.println(getMaxEven(str, len)); }} # Python3 implementation of the approach MAX = 10 # Function to return the maximum# even number that can be formed# with any number of digit swaps def getMaxEven(string, length): string = list(string) # To store the frequencies of # all the digits freq = [0]*MAX # To store the minimum even digit # and the minimum overall digit minEvenDigit = MAX minDigit = MAX for i in range(length): digit = ord(string[i]) - ord('0') freq[digit] += 1 # If digit is even then update # the minimum even digit if (digit % 2 == 0): minEvenDigit = min(digit, minEvenDigit) # Update the overall minimum digit minDigit = min(digit, minDigit) # If there is no even digit then # it is not possible to generate # an even number with swaps if (minEvenDigit == MAX): return "-1" # Decrease the frequency of the # digits that need to be swapped freq[minEvenDigit] -= 1 freq[minDigit] -= 1 i = 0 # Take every digit starting from the maximum # in order to maximize the number for j in range(MAX - 1, -1, -1): # Take current digit number of times # it appeared in the original number for k in range(freq[j]): string[i] = chr(j + ord('0')) i += 1 # If current digit equals to the # minimum even digit then one instance of it # needs to be swapped with the minimum overall digit # i.e. append the minimum digit here if (j == minEvenDigit): string[i] = chr(minDigit + ord('0')) i += 1 # Append once instance of the minimum # even digit in the end to make the number even string[-1] = chr(minEvenDigit + ord('0')) return "".join(string) # Driver codeif __name__ == "__main__": string = "1023422" length = len(string) # Function call print(getMaxEven(string, length)) # This code is contributed by AnkitRai01 // C# implementation of the approachusing System; class GFG { static int MAX = 10; // Function to return the maximum // even number that can be formed // with any number of digit swaps static String getMaxEven(char[] str, int len) { // To store the frequencies of // all the digits int[] freq = new int[MAX]; // To store the minimum even digit // and the minimum overall digit int i, minEvenDigit = MAX, minDigit = MAX; for (i = 0; i < len; i++) { int digit = str[i] - '0'; freq[digit]++; // If digit is even then update // the minimum even digit if (digit % 2 == 0) minEvenDigit = Math.Min(digit, minEvenDigit); // Update the overall minimum digit minDigit = Math.Min(digit, minDigit); } // If there is no even digit then // it is not possible to generate // an even number with swaps if (minEvenDigit == MAX) return "-1"; // Decrease the frequency of the // digits that need to be swapped freq[minEvenDigit]--; freq[minDigit]--; i = 0; // Take every digit starting from the maximum // in order to maximize the number for (int j = MAX - 1; j >= 0; j--) { // Take current digit number of times // it appeared in the original number for (int k = 0; k < freq[j]; k++) str[i++] = (char)(j + '0'); // If current digit equals to the // minimum even digit then one instance of it // needs to be swapped with the minimum overall // digit i.e. append the minimum digit here if (j == minEvenDigit) str[i++] = (char)(minDigit + '0'); } // Append once instance of the minimum // even digit in the end to make the number even str[i - 1] = (char)(minEvenDigit + '0'); return String.Join("", str); } // Driver code public static void Main(String[] args) { char[] str = "1023422".ToCharArray(); int len = str.Length; // Function call Console.WriteLine(getMaxEven(str, len)); }} // This code has been contributed by 29AjayKumar <script> // Javascript implementation of the approach let MAX = 10; // Function to return the maximum // even number that can be formed // with any number of digit swaps function getMaxEven(str, len) { // To store the frequencies of // all the digits let freq = new Array(MAX); freq.fill(0); // To store the minimum even digit // and the minimum overall digit let i, minEvenDigit = MAX, minDigit = MAX; for (i = 0; i < len; i++) { let digit = str[i].charCodeAt() - '0'.charCodeAt(); freq[digit]++; // If digit is even then update // the minimum even digit if (digit % 2 == 0) minEvenDigit = Math.min(digit, minEvenDigit); // Update the overall minimum digit minDigit = Math.min(digit, minDigit); } // If there is no even digit then // it is not possible to generate // an even number with swaps if (minEvenDigit == MAX) return "-1"; // Decrease the frequency of the // digits that need to be swapped freq[minEvenDigit]--; freq[minDigit]--; i = 0; // Take every digit starting from the maximum // in order to maximize the number for (let j = MAX - 1; j >= 0; j--) { // Take current digit number of times // it appeared in the original number for (let k = 0; k < freq[j]; k++) str[i++] = String.fromCharCode(j + '0'.charCodeAt()); // If current digit equals to the // minimum even digit then one instance of it // needs to be swapped with the minimum overall // digit i.e. append the minimum digit here if (j == minEvenDigit) str[i++] = String.fromCharCode(minDigit + '0'.charCodeAt()); } // Append once instance of the minimum // even digit in the end to make the number even str[i - 1] = String.fromCharCode(minEvenDigit + '0'.charCodeAt()); return str.join(""); } let str = "1023422".split(''); let len = str.length; // Function call document.write(getMaxEven(str, len)); </script> 4322210 Time Complexity: O(n + MAX) Auxiliary Space: O(MAX) ankthon princiraj1992 29AjayKumar jainss vaibhavrabadiya117 albert402060727 deksha24ranakoti souravkumar29 frequency-counting Mathematical Sorting Strings Strings Mathematical Sorting Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Sieve of Eratosthenes Prime Numbers Program to find GCD or HCF of two numbers Merge Sort Bubble Sort Algorithm QuickSort Insertion Sort Selection Sort Algorithm
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jun, 2022" }, { "code": null, "e": 293, "s": 54, "text": "Given an integer N in the form of string, the task is to find the largest even number from the given number when you are allowed to do any number of swaps (swapping the digits of the number). If no even number can be formed then print -1." }, { "code": null, "e": 304, "s": 293, "text": "Examples: " }, { "code": null, "e": 333, "s": 304, "text": "Input: N = 1324 Output: 4312" }, { "code": null, "e": 406, "s": 333, "text": "Input: N = 135 Output: -1 No even number can be formed using odd digits." }, { "code": null, "e": 798, "s": 406, "text": "Approach: Sort the string in descending order then we will get the largest number possible with the given digit but it may or may not be an even number. In order to make it even (if it not already), an even digit from the number must be swapped with the last digit and in order to maximize the even number, the even digit which is to be swapped must the smallest even digit from the number. " }, { "code": null, "e": 999, "s": 798, "text": "Note that the sorting can be done in linear time using frequency array for the digits of the number as the number of distinct elements that are needed to be sorted can be at most 10 in the worst case." }, { "code": null, "e": 1051, "s": 999, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 1055, "s": 1051, "text": "C++" }, { "code": null, "e": 1060, "s": 1055, "text": "Java" }, { "code": null, "e": 1068, "s": 1060, "text": "Python3" }, { "code": null, "e": 1071, "s": 1068, "text": "C#" }, { "code": null, "e": 1082, "s": 1071, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std;const int MAX = 10; // Function to return the maximum// even number that can be formed// with any number of digit swapsstring getMaxEven(string str, int len){ // To store the frequencies of // all the digits int freq[MAX] = { 0 }; // To store the minimum even digit // and the minimum overall digit int i, minEvenDigit = MAX; for (i = 0; i < len; i++) { int digit = str[i] - '0'; freq[digit]++; // If digit is even then update // the minimum even digit if (digit % 2 == 0) minEvenDigit = min(digit, minEvenDigit); } // If there is no even digit then // it is not possible to generate // an even number with swaps if (minEvenDigit == MAX) return \"-1\"; // Decrease the frequency of the // digits that need to be swapped freq[minEvenDigit]--; i = 0; // Take every digit starting from the maximum // in order to maximize the number for (int j = MAX - 1; j >= 0; j--) { // Take current digit number of times // it appeared in the original number for (int k = 0; k < freq[j]; k++) str[i++] = (char)(j + '0'); } // Append once instance of the minimum // even digit in the end to make the number even str[i] = (char)(minEvenDigit + '0'); return str;} // Driver codeint main(){ string str = \"1023422\"; int len = str.length(); // Function call cout << getMaxEven(str, len); return 0;}", "e": 2621, "s": 1082, "text": null }, { "code": "// Java implementation of the approachclass GFG { static int MAX = 10; // Function to return the maximum // even number that can be formed // with any number of digit swaps static String getMaxEven(String str, int len) { //To store the max even number String maxEven=\"\"; // To store the frequencies of // all the digits int[] freq = new int[MAX]; // To store the minimum even digit int i, minEvenDigit = MAX; for (i = 0; i < len; i++) { int digit = str.charAt(i) - '0'; freq[digit]++; // If digit is even then update // the minimum even digit if (digit % 2 == 0) minEvenDigit = Math.min(digit, minEvenDigit); } // If there is no even digit then // it is not possible to generate // an even number with swaps if (minEvenDigit == MAX) return \"-1\"; // Decrease the frequency of the // minEvenDigit freq[minEvenDigit]--; i = MAX-1; // Take every digit starting from the maximum // in order to maximize the number while(i>=0) { // Take current digit number of times // it appeared in the original number if(freq[i]>0) { maxEven= maxEven+i; freq[i]--; }else i--; } // Append the minimum even digit // in the end to make the number even maxEven= maxEven+minEvenDigit; return maxEven; } // Driver code public static void main(String[] args) { String str = \"1023422\"; int len = str.length(); // Function call System.out.println(getMaxEven(str, len)); }}", "e": 4428, "s": 2621, "text": null }, { "code": "# Python3 implementation of the approach MAX = 10 # Function to return the maximum# even number that can be formed# with any number of digit swaps def getMaxEven(string, length): string = list(string) # To store the frequencies of # all the digits freq = [0]*MAX # To store the minimum even digit # and the minimum overall digit minEvenDigit = MAX minDigit = MAX for i in range(length): digit = ord(string[i]) - ord('0') freq[digit] += 1 # If digit is even then update # the minimum even digit if (digit % 2 == 0): minEvenDigit = min(digit, minEvenDigit) # Update the overall minimum digit minDigit = min(digit, minDigit) # If there is no even digit then # it is not possible to generate # an even number with swaps if (minEvenDigit == MAX): return \"-1\" # Decrease the frequency of the # digits that need to be swapped freq[minEvenDigit] -= 1 freq[minDigit] -= 1 i = 0 # Take every digit starting from the maximum # in order to maximize the number for j in range(MAX - 1, -1, -1): # Take current digit number of times # it appeared in the original number for k in range(freq[j]): string[i] = chr(j + ord('0')) i += 1 # If current digit equals to the # minimum even digit then one instance of it # needs to be swapped with the minimum overall digit # i.e. append the minimum digit here if (j == minEvenDigit): string[i] = chr(minDigit + ord('0')) i += 1 # Append once instance of the minimum # even digit in the end to make the number even string[-1] = chr(minEvenDigit + ord('0')) return \"\".join(string) # Driver codeif __name__ == \"__main__\": string = \"1023422\" length = len(string) # Function call print(getMaxEven(string, length)) # This code is contributed by AnkitRai01", "e": 6373, "s": 4428, "text": null }, { "code": "// C# implementation of the approachusing System; class GFG { static int MAX = 10; // Function to return the maximum // even number that can be formed // with any number of digit swaps static String getMaxEven(char[] str, int len) { // To store the frequencies of // all the digits int[] freq = new int[MAX]; // To store the minimum even digit // and the minimum overall digit int i, minEvenDigit = MAX, minDigit = MAX; for (i = 0; i < len; i++) { int digit = str[i] - '0'; freq[digit]++; // If digit is even then update // the minimum even digit if (digit % 2 == 0) minEvenDigit = Math.Min(digit, minEvenDigit); // Update the overall minimum digit minDigit = Math.Min(digit, minDigit); } // If there is no even digit then // it is not possible to generate // an even number with swaps if (minEvenDigit == MAX) return \"-1\"; // Decrease the frequency of the // digits that need to be swapped freq[minEvenDigit]--; freq[minDigit]--; i = 0; // Take every digit starting from the maximum // in order to maximize the number for (int j = MAX - 1; j >= 0; j--) { // Take current digit number of times // it appeared in the original number for (int k = 0; k < freq[j]; k++) str[i++] = (char)(j + '0'); // If current digit equals to the // minimum even digit then one instance of it // needs to be swapped with the minimum overall // digit i.e. append the minimum digit here if (j == minEvenDigit) str[i++] = (char)(minDigit + '0'); } // Append once instance of the minimum // even digit in the end to make the number even str[i - 1] = (char)(minEvenDigit + '0'); return String.Join(\"\", str); } // Driver code public static void Main(String[] args) { char[] str = \"1023422\".ToCharArray(); int len = str.Length; // Function call Console.WriteLine(getMaxEven(str, len)); }} // This code has been contributed by 29AjayKumar", "e": 8677, "s": 6373, "text": null }, { "code": "<script> // Javascript implementation of the approach let MAX = 10; // Function to return the maximum // even number that can be formed // with any number of digit swaps function getMaxEven(str, len) { // To store the frequencies of // all the digits let freq = new Array(MAX); freq.fill(0); // To store the minimum even digit // and the minimum overall digit let i, minEvenDigit = MAX, minDigit = MAX; for (i = 0; i < len; i++) { let digit = str[i].charCodeAt() - '0'.charCodeAt(); freq[digit]++; // If digit is even then update // the minimum even digit if (digit % 2 == 0) minEvenDigit = Math.min(digit, minEvenDigit); // Update the overall minimum digit minDigit = Math.min(digit, minDigit); } // If there is no even digit then // it is not possible to generate // an even number with swaps if (minEvenDigit == MAX) return \"-1\"; // Decrease the frequency of the // digits that need to be swapped freq[minEvenDigit]--; freq[minDigit]--; i = 0; // Take every digit starting from the maximum // in order to maximize the number for (let j = MAX - 1; j >= 0; j--) { // Take current digit number of times // it appeared in the original number for (let k = 0; k < freq[j]; k++) str[i++] = String.fromCharCode(j + '0'.charCodeAt()); // If current digit equals to the // minimum even digit then one instance of it // needs to be swapped with the minimum overall // digit i.e. append the minimum digit here if (j == minEvenDigit) str[i++] = String.fromCharCode(minDigit + '0'.charCodeAt()); } // Append once instance of the minimum // even digit in the end to make the number even str[i - 1] = String.fromCharCode(minEvenDigit + '0'.charCodeAt()); return str.join(\"\"); } let str = \"1023422\".split(''); let len = str.length; // Function call document.write(getMaxEven(str, len)); </script>", "e": 10959, "s": 8677, "text": null }, { "code": null, "e": 10967, "s": 10959, "text": "4322210" }, { "code": null, "e": 10997, "s": 10969, "text": "Time Complexity: O(n + MAX)" }, { "code": null, "e": 11022, "s": 10997, "text": "Auxiliary Space: O(MAX) " }, { "code": null, "e": 11030, "s": 11022, "text": "ankthon" }, { "code": null, "e": 11044, "s": 11030, "text": "princiraj1992" }, { "code": null, "e": 11056, "s": 11044, "text": "29AjayKumar" }, { "code": null, "e": 11063, "s": 11056, "text": "jainss" }, { "code": null, "e": 11082, "s": 11063, "text": "vaibhavrabadiya117" }, { "code": null, "e": 11098, "s": 11082, "text": "albert402060727" }, { "code": null, "e": 11115, "s": 11098, "text": "deksha24ranakoti" }, { "code": null, "e": 11129, "s": 11115, "text": "souravkumar29" }, { "code": null, "e": 11148, "s": 11129, "text": "frequency-counting" }, { "code": null, "e": 11161, "s": 11148, "text": "Mathematical" }, { "code": null, "e": 11169, "s": 11161, "text": "Sorting" }, { "code": null, "e": 11177, "s": 11169, "text": "Strings" }, { "code": null, "e": 11185, "s": 11177, "text": "Strings" }, { "code": null, "e": 11198, "s": 11185, "text": "Mathematical" }, { "code": null, "e": 11206, "s": 11198, "text": "Sorting" }, { "code": null, "e": 11304, "s": 11206, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11328, "s": 11304, "text": "Merge two sorted arrays" }, { "code": null, "e": 11349, "s": 11328, "text": "Operators in C / C++" }, { "code": null, "e": 11371, "s": 11349, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 11385, "s": 11371, "text": "Prime Numbers" }, { "code": null, "e": 11427, "s": 11385, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 11438, "s": 11427, "text": "Merge Sort" }, { "code": null, "e": 11460, "s": 11438, "text": "Bubble Sort Algorithm" }, { "code": null, "e": 11470, "s": 11460, "text": "QuickSort" }, { "code": null, "e": 11485, "s": 11470, "text": "Insertion Sort" } ]
PyQtGraph – Plot Window
06 Sep, 2021 In this article we will see how we can create plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).Plot windows consist of two main parts: the Plot Panel containing the actual plotted graphics (by default, at the top), and the Control Panel (by default, at the bottom). The Control Panel is where you configure what will be plotted. For a simple scatter plot it may just be a case of selecting what columns to plot against each other, but it can get quite detailed. In order to do this we use plot method with the pyqtgraphSyntax : pg.plot() Argument : It takes no argumentReturn : It returns PlotWindow object Below is the implementation Python3 # importing pyqtgraph as pgimport pyqtgraph as pg # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui # importing numpy as npimport numpy as np # define the datatitle = "GeeksforGeeks PyQtGraph" # y values to plot by line 1y = [2, 8, 6, 8, 6, 11, 14, 13, 18, 19] # y values to plot by line 2y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16]x = range(0, 10) # create plot window objectplt = pg.plot() # showing x and y gridsplt.showGrid(x = True, y = True) # adding legendplt.addLegend() # set properties of the label for y axisplt.setLabel('left', 'Vertical Values', units ='y') # set properties of the label for x axisplt.setLabel('bottom', 'Horizontal Values', units ='s') # setting horizontal rangeplt.setXRange(0, 10) # setting vertical rangeplt.setYRange(0, 20) # setting window titleplt.setWindowTitle(title) # ploting line in green colorline1 = plt.plot(x, y, pen ='g', symbol ='x', symbolPen ='g', symbolBrush = 0.2, name ='green') # ploting line2 with blue colorline2 = plt.plot(x, y2, pen ='b', symbol ='o', symbolPen ='b', symbolBrush = 0.2, name ='blue') # main methodif __name__ == '__main__': # importing system import sys # Start Qt event loop unless running in interactive mode or using if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() Output : sagar0719kumar Python-gui Python-PyQtGraph Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n06 Sep, 2021" }, { "code": null, "e": 856, "s": 28, "text": "In this article we will see how we can create plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).Plot windows consist of two main parts: the Plot Panel containing the actual plotted graphics (by default, at the top), and the Control Panel (by default, at the bottom). The Control Panel is where you configure what will be plotted. For a simple scatter plot it may just be a case of selecting what columns to plot against each other, but it can get quite detailed. " }, { "code": null, "e": 1003, "s": 856, "text": "In order to do this we use plot method with the pyqtgraphSyntax : pg.plot() Argument : It takes no argumentReturn : It returns PlotWindow object " }, { "code": null, "e": 1033, "s": 1003, "text": "Below is the implementation " }, { "code": null, "e": 1041, "s": 1033, "text": "Python3" }, { "code": "# importing pyqtgraph as pgimport pyqtgraph as pg # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui # importing numpy as npimport numpy as np # define the datatitle = \"GeeksforGeeks PyQtGraph\" # y values to plot by line 1y = [2, 8, 6, 8, 6, 11, 14, 13, 18, 19] # y values to plot by line 2y2 = [3, 1, 5, 8, 9, 11, 16, 17, 14, 16]x = range(0, 10) # create plot window objectplt = pg.plot() # showing x and y gridsplt.showGrid(x = True, y = True) # adding legendplt.addLegend() # set properties of the label for y axisplt.setLabel('left', 'Vertical Values', units ='y') # set properties of the label for x axisplt.setLabel('bottom', 'Horizontal Values', units ='s') # setting horizontal rangeplt.setXRange(0, 10) # setting vertical rangeplt.setYRange(0, 20) # setting window titleplt.setWindowTitle(title) # ploting line in green colorline1 = plt.plot(x, y, pen ='g', symbol ='x', symbolPen ='g', symbolBrush = 0.2, name ='green') # ploting line2 with blue colorline2 = plt.plot(x, y2, pen ='b', symbol ='o', symbolPen ='b', symbolBrush = 0.2, name ='blue') # main methodif __name__ == '__main__': # importing system import sys # Start Qt event loop unless running in interactive mode or using if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()", "e": 2471, "s": 1041, "text": null }, { "code": null, "e": 2482, "s": 2471, "text": "Output : " }, { "code": null, "e": 2499, "s": 2484, "text": "sagar0719kumar" }, { "code": null, "e": 2510, "s": 2499, "text": "Python-gui" }, { "code": null, "e": 2527, "s": 2510, "text": "Python-PyQtGraph" }, { "code": null, "e": 2534, "s": 2527, "text": "Python" }, { "code": null, "e": 2632, "s": 2534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2650, "s": 2632, "text": "Python Dictionary" }, { "code": null, "e": 2692, "s": 2650, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2714, "s": 2692, "text": "Enumerate() in Python" }, { "code": null, "e": 2749, "s": 2714, "text": "Read a file line by line in Python" }, { "code": null, "e": 2775, "s": 2749, "text": "Python String | replace()" }, { "code": null, "e": 2807, "s": 2775, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2836, "s": 2807, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2863, "s": 2836, "text": "Python Classes and Objects" }, { "code": null, "e": 2893, "s": 2863, "text": "Iterate over a list in Python" } ]
Maskphish – Hide Phishing Link Behind Real Domain
24 Jun, 2021 Maskphish tool is used to hide the phishing links or URL behind the original link. This tool is a free and open-source tool you can download this tool from Github. This tool can perform social engineering attacks on victims. This tool can hide all types of URL links such as ngrok links. Maskphish is a very useful tool and easy to use. This tool is written in bash language. This tool is a bash script. The tool gives you the flexibility in order to use the tool according to requirements. This tool is a lightweight tool means small. You can add a custom URL behind the original URL of the phishing link. This tool is developed by the JayKali group of ethical hackers. Maskphish is available as a console script. The user interface of this tool is very similar to Metasploitable 1 and Metasploitable 2 which makes it easy to use. MaskPhish Features and uses of Maskphish :- Maskphish is a free tool. This means you don’t have to pay any amount to the developers. You can download this tool free of cost. Maskphish is open source tool. This means its source code is available you can contribute to the tool. Maskphish hides the phishing link into the original link. Maskphish is a tool that is used to hide the ngrok<links> to the original links of the websites. Maskphish tool can convert a phishing link to a normal web link like Google or YouTube. Maskphish tool is a very simple and easy tool. Maskphish tool is a lightweight tool. This does not take extra space. Maskphish is written in bash language. Installation and step-by-step tutorial of Maskphish tool:- Step 1. Open your Kali Linux operating system. Move to desktop. Here you have to create a directory called Maskphish. In this directory, you have to install the tool. To move to the desktop use the following command. cd Desktop Step 2. Now you are on the desktop. Here you have to create a directory called Maskphish. To create Maskphish directory use the following command. mkdir Maskphish Step 3. You have created a directory. Now use the following command to move into that directory. cd Maskphish Step 4. Now you are in Maskphish directory. In this directory you have to download the tool means you have to clone the tool from Github. Use the following command to clone the tool from Github. git clone https://github.com/jaykali/maskphish Step 5. The tool has been downloaded in the directory Maskphish. Now to list out the contents of the tool that has been downloaded use the following command. ls Step 6. When you listed out the contents of the tool you can see that a new directory has been generated by the tool that is maskphish. You have to move to this directory to view the contents of the tool. To move in this directory using the following command. cd maskphish Step 7. To list out the contents of this directory using the following command. ls Step 8. Now you can run the tool using the following command. This command will open the help menu of the tool. ./maskphish.sh Step 9. Now the tool is asking for a phishing link that you generated using any phishing link generator copy that links from that tool and paste that link to here. Step 10. Now you have to give the link that you want to be shown to the victim. Step 11. We have taken instagram.com here. We want instagram.com must be shown to the victim that’s we have taken this. We also want to give social engineering words like we are given to get followers. Step 12. Press enter and then the link will be generated. You can see an Instagram link has been generated by the tool. You can send this link to the victim. Similarly, you can use the tool to attack your victim. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 mv command in Linux with examples chmod command in Linux with examples nohup Command in Linux with Examples Introduction to Linux Operating System Array Basics in Shell Scripting | Set 1 Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Jun, 2021" }, { "code": null, "e": 861, "s": 28, "text": "Maskphish tool is used to hide the phishing links or URL behind the original link. This tool is a free and open-source tool you can download this tool from Github. This tool can perform social engineering attacks on victims. This tool can hide all types of URL links such as ngrok links. Maskphish is a very useful tool and easy to use. This tool is written in bash language. This tool is a bash script. The tool gives you the flexibility in order to use the tool according to requirements. This tool is a lightweight tool means small. You can add a custom URL behind the original URL of the phishing link. This tool is developed by the JayKali group of ethical hackers. Maskphish is available as a console script. The user interface of this tool is very similar to Metasploitable 1 and Metasploitable 2 which makes it easy to use. " }, { "code": null, "e": 871, "s": 861, "text": "MaskPhish" }, { "code": null, "e": 905, "s": 871, "text": "Features and uses of Maskphish :-" }, { "code": null, "e": 1035, "s": 905, "text": "Maskphish is a free tool. This means you don’t have to pay any amount to the developers. You can download this tool free of cost." }, { "code": null, "e": 1138, "s": 1035, "text": "Maskphish is open source tool. This means its source code is available you can contribute to the tool." }, { "code": null, "e": 1196, "s": 1138, "text": "Maskphish hides the phishing link into the original link." }, { "code": null, "e": 1293, "s": 1196, "text": "Maskphish is a tool that is used to hide the ngrok<links> to the original links of the websites." }, { "code": null, "e": 1381, "s": 1293, "text": "Maskphish tool can convert a phishing link to a normal web link like Google or YouTube." }, { "code": null, "e": 1428, "s": 1381, "text": "Maskphish tool is a very simple and easy tool." }, { "code": null, "e": 1498, "s": 1428, "text": "Maskphish tool is a lightweight tool. This does not take extra space." }, { "code": null, "e": 1537, "s": 1498, "text": "Maskphish is written in bash language." }, { "code": null, "e": 1596, "s": 1537, "text": "Installation and step-by-step tutorial of Maskphish tool:-" }, { "code": null, "e": 1763, "s": 1596, "text": "Step 1. Open your Kali Linux operating system. Move to desktop. Here you have to create a directory called Maskphish. In this directory, you have to install the tool." }, { "code": null, "e": 1813, "s": 1763, "text": "To move to the desktop use the following command." }, { "code": null, "e": 1824, "s": 1813, "text": "cd Desktop" }, { "code": null, "e": 1971, "s": 1824, "text": "Step 2. Now you are on the desktop. Here you have to create a directory called Maskphish. To create Maskphish directory use the following command." }, { "code": null, "e": 1987, "s": 1971, "text": "mkdir Maskphish" }, { "code": null, "e": 2084, "s": 1987, "text": "Step 3. You have created a directory. Now use the following command to move into that directory." }, { "code": null, "e": 2097, "s": 2084, "text": "cd Maskphish" }, { "code": null, "e": 2292, "s": 2097, "text": "Step 4. Now you are in Maskphish directory. In this directory you have to download the tool means you have to clone the tool from Github. Use the following command to clone the tool from Github." }, { "code": null, "e": 2339, "s": 2292, "text": "git clone https://github.com/jaykali/maskphish" }, { "code": null, "e": 2497, "s": 2339, "text": "Step 5. The tool has been downloaded in the directory Maskphish. Now to list out the contents of the tool that has been downloaded use the following command." }, { "code": null, "e": 2500, "s": 2497, "text": "ls" }, { "code": null, "e": 2760, "s": 2500, "text": "Step 6. When you listed out the contents of the tool you can see that a new directory has been generated by the tool that is maskphish. You have to move to this directory to view the contents of the tool. To move in this directory using the following command." }, { "code": null, "e": 2773, "s": 2760, "text": "cd maskphish" }, { "code": null, "e": 2853, "s": 2773, "text": "Step 7. To list out the contents of this directory using the following command." }, { "code": null, "e": 2856, "s": 2853, "text": "ls" }, { "code": null, "e": 2969, "s": 2856, "text": "Step 8. Now you can run the tool using the following command. This command will open the help menu of the tool." }, { "code": null, "e": 2984, "s": 2969, "text": "./maskphish.sh" }, { "code": null, "e": 3148, "s": 2984, "text": "Step 9. Now the tool is asking for a phishing link that you generated using any phishing link generator copy that links from that tool and paste that link to here." }, { "code": null, "e": 3228, "s": 3148, "text": "Step 10. Now you have to give the link that you want to be shown to the victim." }, { "code": null, "e": 3430, "s": 3228, "text": "Step 11. We have taken instagram.com here. We want instagram.com must be shown to the victim that’s we have taken this. We also want to give social engineering words like we are given to get followers." }, { "code": null, "e": 3489, "s": 3430, "text": "Step 12. Press enter and then the link will be generated." }, { "code": null, "e": 3645, "s": 3489, "text": "You can see an Instagram link has been generated by the tool. You can send this link to the victim. Similarly, you can use the tool to attack your victim. " }, { "code": null, "e": 3656, "s": 3645, "text": "Kali-Linux" }, { "code": null, "e": 3668, "s": 3656, "text": "Linux-Tools" }, { "code": null, "e": 3679, "s": 3668, "text": "Linux-Unix" }, { "code": null, "e": 3777, "s": 3679, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3803, "s": 3777, "text": "Docker - COPY Instruction" }, { "code": null, "e": 3838, "s": 3803, "text": "scp command in Linux with Examples" }, { "code": null, "e": 3875, "s": 3838, "text": "chown command in Linux with Examples" }, { "code": null, "e": 3904, "s": 3875, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 3938, "s": 3904, "text": "mv command in Linux with examples" }, { "code": null, "e": 3975, "s": 3938, "text": "chmod command in Linux with examples" }, { "code": null, "e": 4012, "s": 3975, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 4051, "s": 4012, "text": "Introduction to Linux Operating System" }, { "code": null, "e": 4091, "s": 4051, "text": "Array Basics in Shell Scripting | Set 1" } ]
Python | Group Anagrams from given list
20 Jun, 2022 Anagrams are the words that are formed by similar elements but the orders in which these characters occur differ. Sometimes, we may encounter a problem in which we need to group the anagrams and hence solution to above problem always helps. Let’s discuss certain ways in which this can be done.Method #1 : Using defaultdict() + sorted() + values()The combination of above functions can be used to get the solution of above problem. In this, we first get the anagrams grouped using defaultdict and use sorted function to get each anagram root value to group anagrams. Python3 # Python3 code to demonstrate# Grouping Anagrams# using defaultdict() + sorted() + values()from collections import defaultdict # initializing listtest_list = ['lump', 'eat', 'me', 'tea', 'em', 'plum'] # printing original listprint("The original list : " + str(test_list)) # using defaultdict() + sorted() + values()# Grouping Anagramstemp = defaultdict(list)for ele in test_list: temp[str(sorted(ele))].append(ele)res = list(temp.values()) # print resultprint("The grouped Anagrams : " + str(res)) The original list : ['lump', 'eat', 'me', 'tea', 'em', 'plum'] The grouped Anagrams : [['me', 'em'], ['lump', 'plum'], ['eat', 'tea']] Method #2 : Using list comprehension + sorted() + lambda + groupby()The combination of above function can also be used to perform this particular task. The groupby function performs the necessary grouping together. The lambda function helps to group alike anagrams. Python3 # Python3 code to demonstrate# Grouping Anagrams# using list comprehension + sorted() + lambda + groupby()from itertools import groupby # initializing listtest_list = ['lump', 'eat', 'me', 'tea', 'em', 'plum'] # printing original listprint("The original list : " + str(test_list)) # using list comprehension + sorted() + lambda + groupby()# Grouping Anagramstemp = lambda test_list: sorted(test_list)res = [list(val) for key, val in groupby(sorted(test_list, key = temp), temp)] # print resultprint("The grouped Anagrams : " + str(res)) The original list : ['lump', 'eat', 'me', 'tea', 'em', 'plum'] The grouped Anagrams : [['me', 'em'], ['lump', 'plum'], ['eat', 'tea']] Method3: Using Simple Python Programming Below is the program to group anagram words together in a simple python programming way. Without using list comprehension or lambda or imported methods. The method followed is simple – 1. Sort each word and use the sorted word as a dictionary key 2. Keep adding new word into dictionary against sorted key Python3 data = ['eat', 'ate', 'tea', 'ant', 'tan', 'bat', 'adobe', 'abode', 'listen', 'silent'] def createAnagramKey(string): key = '' for ch in sorted(string): key += ch return str(key) def groupAnagramWords(data): group = dict() for ele in data: if group.get(createAnagramKey(ele)) == None: group[createAnagramKey(ele)] = [ele] else: group[createAnagramKey(ele)].append(ele) return group anagram_grouped = groupAnagramWords(data) # Anagram in dictionary formatprint('In dictionary format')print(anagram_grouped) anagram_grouped_list = list() for k, v in anagram_grouped.items(): anagram_grouped_list.append(v)print('In list format')print(anagram_grouped_list) Output: In dictionary format {'aet': ['eat', 'ate', 'tea'], 'ant': ['ant', 'tan'], 'abt': ['bat'], 'abdeo': ['adobe', 'abode'], 'eilnst': ['listen', 'silent']} In list format [['eat', 'ate', 'tea'], ['ant', 'tan'], ['bat'], ['adobe', 'abode'], ['listen', 'silent']] nagendrakallihal vinayedula Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n20 Jun, 2022" }, { "code": null, "e": 622, "s": 53, "text": "Anagrams are the words that are formed by similar elements but the orders in which these characters occur differ. Sometimes, we may encounter a problem in which we need to group the anagrams and hence solution to above problem always helps. Let’s discuss certain ways in which this can be done.Method #1 : Using defaultdict() + sorted() + values()The combination of above functions can be used to get the solution of above problem. In this, we first get the anagrams grouped using defaultdict and use sorted function to get each anagram root value to group anagrams. " }, { "code": null, "e": 630, "s": 622, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Grouping Anagrams# using defaultdict() + sorted() + values()from collections import defaultdict # initializing listtest_list = ['lump', 'eat', 'me', 'tea', 'em', 'plum'] # printing original listprint(\"The original list : \" + str(test_list)) # using defaultdict() + sorted() + values()# Grouping Anagramstemp = defaultdict(list)for ele in test_list: temp[str(sorted(ele))].append(ele)res = list(temp.values()) # print resultprint(\"The grouped Anagrams : \" + str(res))", "e": 1133, "s": 630, "text": null }, { "code": null, "e": 1268, "s": 1133, "text": "The original list : ['lump', 'eat', 'me', 'tea', 'em', 'plum']\nThe grouped Anagrams : [['me', 'em'], ['lump', 'plum'], ['eat', 'tea']]" }, { "code": null, "e": 1537, "s": 1270, "text": " Method #2 : Using list comprehension + sorted() + lambda + groupby()The combination of above function can also be used to perform this particular task. The groupby function performs the necessary grouping together. The lambda function helps to group alike anagrams." }, { "code": null, "e": 1545, "s": 1537, "text": "Python3" }, { "code": "# Python3 code to demonstrate# Grouping Anagrams# using list comprehension + sorted() + lambda + groupby()from itertools import groupby # initializing listtest_list = ['lump', 'eat', 'me', 'tea', 'em', 'plum'] # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + sorted() + lambda + groupby()# Grouping Anagramstemp = lambda test_list: sorted(test_list)res = [list(val) for key, val in groupby(sorted(test_list, key = temp), temp)] # print resultprint(\"The grouped Anagrams : \" + str(res))", "e": 2084, "s": 1545, "text": null }, { "code": null, "e": 2219, "s": 2084, "text": "The original list : ['lump', 'eat', 'me', 'tea', 'em', 'plum']\nThe grouped Anagrams : [['me', 'em'], ['lump', 'plum'], ['eat', 'tea']]" }, { "code": null, "e": 2262, "s": 2221, "text": "Method3: Using Simple Python Programming" }, { "code": null, "e": 2415, "s": 2262, "text": "Below is the program to group anagram words together in a simple python programming way. Without using list comprehension or lambda or imported methods." }, { "code": null, "e": 2448, "s": 2415, "text": "The method followed is simple – " }, { "code": null, "e": 2511, "s": 2448, "text": " 1. Sort each word and use the sorted word as a dictionary key" }, { "code": null, "e": 2571, "s": 2511, "text": " 2. Keep adding new word into dictionary against sorted key" }, { "code": null, "e": 2579, "s": 2571, "text": "Python3" }, { "code": "data = ['eat', 'ate', 'tea', 'ant', 'tan', 'bat', 'adobe', 'abode', 'listen', 'silent'] def createAnagramKey(string): key = '' for ch in sorted(string): key += ch return str(key) def groupAnagramWords(data): group = dict() for ele in data: if group.get(createAnagramKey(ele)) == None: group[createAnagramKey(ele)] = [ele] else: group[createAnagramKey(ele)].append(ele) return group anagram_grouped = groupAnagramWords(data) # Anagram in dictionary formatprint('In dictionary format')print(anagram_grouped) anagram_grouped_list = list() for k, v in anagram_grouped.items(): anagram_grouped_list.append(v)print('In list format')print(anagram_grouped_list)", "e": 3307, "s": 2579, "text": null }, { "code": null, "e": 3315, "s": 3307, "text": "Output:" }, { "code": null, "e": 3576, "s": 3315, "text": "In dictionary format\n{'aet': ['eat', 'ate', 'tea'], 'ant': ['ant', 'tan'], 'abt': ['bat'],\n 'abdeo': ['adobe', 'abode'], 'eilnst': ['listen', 'silent']}\n \nIn list format\n[['eat', 'ate', 'tea'], ['ant', 'tan'], ['bat'], ['adobe', 'abode'], ['listen', 'silent']]" }, { "code": null, "e": 3593, "s": 3576, "text": "nagendrakallihal" }, { "code": null, "e": 3604, "s": 3593, "text": "vinayedula" }, { "code": null, "e": 3625, "s": 3604, "text": "Python list-programs" }, { "code": null, "e": 3632, "s": 3625, "text": "Python" }, { "code": null, "e": 3648, "s": 3632, "text": "Python Programs" } ]
How to add a Snackbar in Android
23 Feb, 2021 Snackbar provides lightweight feedback about an operation. The message appears at the bottom of the screen on mobile and lower left on larger devices. Snackbar appears above all the elements of the screen. But no component is affected by it. Having a CoordinatorLayout in your view hierarchy allows Snackbar to enable certain features, such as swipe-to-dismiss and automatically moving of widgets. Snackbar is similar to Toast but the only major difference is that an action can be added with Snackbar. Approach: Add the support Library in build.gradle file and add Material Design dependency in the dependencies section.It is a part of Material Design that’s why we have to add a dependency.dependencies { implementation 'com.google.android.material:material:1.1.0'}Now add the following code in the activity_main.xml file. It will create a button named Open Snackbar.activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/layout" tools:context=".MainActivity"> <Button android:layout_gravity="center" android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:textAllCaps="false" android:text="Open Snackbar" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>Now add the following code in the MainActivity.java file. This will define the button and add a onClickListener to the button. In the onClickListener a Snackbar is created and is called. So whenever the button is clicked, the onClickListener creates a snackbar and calls it and the user sees the message. This snackbar contains an action and if clicked will show a toast.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgsnackbar; import androidx.appcompat.app.AppCompatActivity;import androidx.coordinatorlayout .widget.CoordinatorLayout;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import com.google.android.material .snackbar .Snackbar; public class MainActivity extends AppCompatActivity { Button button; CoordinatorLayout layout; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); layout = findViewById(R.id.layout); button.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Create a snackbar Snackbar snackbar = Snackbar .make( layout, "Message is deleted", Snackbar.LENGTH_LONG) .setAction( "UNDO", // If the Undo button // is pressed, show // the message using Toast new View.OnClickListener() { @Override public void onClick(View view) { Toast .makeText( MainActivity.this, "Undo Clicked", Toast.LENGTH_SHORT) .show(); } }); snackbar.show(); } }); }} Add the support Library in build.gradle file and add Material Design dependency in the dependencies section.It is a part of Material Design that’s why we have to add a dependency.dependencies { implementation 'com.google.android.material:material:1.1.0'} dependencies { implementation 'com.google.android.material:material:1.1.0'} Now add the following code in the activity_main.xml file. It will create a button named Open Snackbar.activity_main.xmlactivity_main.xml<?xml version="1.0" encoding="utf-8"?><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/layout" tools:context=".MainActivity"> <Button android:layout_gravity="center" android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:textAllCaps="false" android:text="Open Snackbar" /> </androidx.coordinatorlayout.widget.CoordinatorLayout> activity_main.xml <?xml version="1.0" encoding="utf-8"?><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/layout" tools:context=".MainActivity"> <Button android:layout_gravity="center" android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:textAllCaps="false" android:text="Open Snackbar" /> </androidx.coordinatorlayout.widget.CoordinatorLayout> Now add the following code in the MainActivity.java file. This will define the button and add a onClickListener to the button. In the onClickListener a Snackbar is created and is called. So whenever the button is clicked, the onClickListener creates a snackbar and calls it and the user sees the message. This snackbar contains an action and if clicked will show a toast.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgsnackbar; import androidx.appcompat.app.AppCompatActivity;import androidx.coordinatorlayout .widget.CoordinatorLayout;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import com.google.android.material .snackbar .Snackbar; public class MainActivity extends AppCompatActivity { Button button; CoordinatorLayout layout; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); layout = findViewById(R.id.layout); button.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Create a snackbar Snackbar snackbar = Snackbar .make( layout, "Message is deleted", Snackbar.LENGTH_LONG) .setAction( "UNDO", // If the Undo button // is pressed, show // the message using Toast new View.OnClickListener() { @Override public void onClick(View view) { Toast .makeText( MainActivity.this, "Undo Clicked", Toast.LENGTH_SHORT) .show(); } }); snackbar.show(); } }); }} MainActivity.java package org.geeksforgeeks.gfgsnackbar; import androidx.appcompat.app.AppCompatActivity;import androidx.coordinatorlayout .widget.CoordinatorLayout;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import com.google.android.material .snackbar .Snackbar; public class MainActivity extends AppCompatActivity { Button button; CoordinatorLayout layout; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); layout = findViewById(R.id.layout); button.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Create a snackbar Snackbar snackbar = Snackbar .make( layout, "Message is deleted", Snackbar.LENGTH_LONG) .setAction( "UNDO", // If the Undo button // is pressed, show // the message using Toast new View.OnClickListener() { @Override public void onClick(View view) { Toast .makeText( MainActivity.this, "Undo Clicked", Toast.LENGTH_SHORT) .show(); } }); snackbar.show(); } }); }} Output: Android-Bars Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference Between Implicit Intent and Explicit Intent in Android How to Create and Add Data to SQLite Database in Android? Retrofit with Kotlin Coroutine in Android Navigation Drawer in Android Broadcast Receiver in Android With Example Arrays in Java Arrays.sort() in Java with examples Reverse a string in Java Split() String method in Java with examples Queue Interface In Java
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Feb, 2021" }, { "code": null, "e": 557, "s": 54, "text": "Snackbar provides lightweight feedback about an operation. The message appears at the bottom of the screen on mobile and lower left on larger devices. Snackbar appears above all the elements of the screen. But no component is affected by it. Having a CoordinatorLayout in your view hierarchy allows Snackbar to enable certain features, such as swipe-to-dismiss and automatically moving of widgets. Snackbar is similar to Toast but the only major difference is that an action can be added with Snackbar." }, { "code": null, "e": 567, "s": 557, "text": "Approach:" }, { "code": null, "e": 4177, "s": 567, "text": "Add the support Library in build.gradle file and add Material Design dependency in the dependencies section.It is a part of Material Design that’s why we have to add a dependency.dependencies { implementation 'com.google.android.material:material:1.1.0'}Now add the following code in the activity_main.xml file. It will create a button named Open Snackbar.activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/layout\" tools:context=\".MainActivity\"> <Button android:layout_gravity=\"center\" android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textSize=\"18sp\" android:textAllCaps=\"false\" android:text=\"Open Snackbar\" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>Now add the following code in the MainActivity.java file. This will define the button and add a onClickListener to the button. In the onClickListener a Snackbar is created and is called. So whenever the button is clicked, the onClickListener creates a snackbar and calls it and the user sees the message. This snackbar contains an action and if clicked will show a toast.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgsnackbar; import androidx.appcompat.app.AppCompatActivity;import androidx.coordinatorlayout .widget.CoordinatorLayout;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import com.google.android.material .snackbar .Snackbar; public class MainActivity extends AppCompatActivity { Button button; CoordinatorLayout layout; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); layout = findViewById(R.id.layout); button.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Create a snackbar Snackbar snackbar = Snackbar .make( layout, \"Message is deleted\", Snackbar.LENGTH_LONG) .setAction( \"UNDO\", // If the Undo button // is pressed, show // the message using Toast new View.OnClickListener() { @Override public void onClick(View view) { Toast .makeText( MainActivity.this, \"Undo Clicked\", Toast.LENGTH_SHORT) .show(); } }); snackbar.show(); } }); }}" }, { "code": null, "e": 4435, "s": 4177, "text": "Add the support Library in build.gradle file and add Material Design dependency in the dependencies section.It is a part of Material Design that’s why we have to add a dependency.dependencies { implementation 'com.google.android.material:material:1.1.0'}" }, { "code": "dependencies { implementation 'com.google.android.material:material:1.1.0'}", "e": 4514, "s": 4435, "text": null }, { "code": null, "e": 5334, "s": 4514, "text": "Now add the following code in the activity_main.xml file. It will create a button named Open Snackbar.activity_main.xmlactivity_main.xml<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/layout\" tools:context=\".MainActivity\"> <Button android:layout_gravity=\"center\" android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textSize=\"18sp\" android:textAllCaps=\"false\" android:text=\"Open Snackbar\" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>" }, { "code": null, "e": 5352, "s": 5334, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/layout\" tools:context=\".MainActivity\"> <Button android:layout_gravity=\"center\" android:id=\"@+id/button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:textSize=\"18sp\" android:textAllCaps=\"false\" android:text=\"Open Snackbar\" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>", "e": 6036, "s": 5352, "text": null }, { "code": null, "e": 8570, "s": 6036, "text": "Now add the following code in the MainActivity.java file. This will define the button and add a onClickListener to the button. In the onClickListener a Snackbar is created and is called. So whenever the button is clicked, the onClickListener creates a snackbar and calls it and the user sees the message. This snackbar contains an action and if clicked will show a toast.MainActivity.javaMainActivity.javapackage org.geeksforgeeks.gfgsnackbar; import androidx.appcompat.app.AppCompatActivity;import androidx.coordinatorlayout .widget.CoordinatorLayout;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import com.google.android.material .snackbar .Snackbar; public class MainActivity extends AppCompatActivity { Button button; CoordinatorLayout layout; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); layout = findViewById(R.id.layout); button.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Create a snackbar Snackbar snackbar = Snackbar .make( layout, \"Message is deleted\", Snackbar.LENGTH_LONG) .setAction( \"UNDO\", // If the Undo button // is pressed, show // the message using Toast new View.OnClickListener() { @Override public void onClick(View view) { Toast .makeText( MainActivity.this, \"Undo Clicked\", Toast.LENGTH_SHORT) .show(); } }); snackbar.show(); } }); }}" }, { "code": null, "e": 8588, "s": 8570, "text": "MainActivity.java" }, { "code": "package org.geeksforgeeks.gfgsnackbar; import androidx.appcompat.app.AppCompatActivity;import androidx.coordinatorlayout .widget.CoordinatorLayout;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.Toast; import com.google.android.material .snackbar .Snackbar; public class MainActivity extends AppCompatActivity { Button button; CoordinatorLayout layout; @Override protected void onCreate( Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); button = findViewById(R.id.button); layout = findViewById(R.id.layout); button.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // Create a snackbar Snackbar snackbar = Snackbar .make( layout, \"Message is deleted\", Snackbar.LENGTH_LONG) .setAction( \"UNDO\", // If the Undo button // is pressed, show // the message using Toast new View.OnClickListener() { @Override public void onClick(View view) { Toast .makeText( MainActivity.this, \"Undo Clicked\", Toast.LENGTH_SHORT) .show(); } }); snackbar.show(); } }); }}", "e": 10717, "s": 8588, "text": null }, { "code": null, "e": 10725, "s": 10717, "text": "Output:" }, { "code": null, "e": 10738, "s": 10725, "text": "Android-Bars" }, { "code": null, "e": 10746, "s": 10738, "text": "Android" }, { "code": null, "e": 10751, "s": 10746, "text": "Java" }, { "code": null, "e": 10756, "s": 10751, "text": "Java" }, { "code": null, "e": 10764, "s": 10756, "text": "Android" }, { "code": null, "e": 10862, "s": 10764, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 10928, "s": 10862, "text": "Difference Between Implicit Intent and Explicit Intent in Android" }, { "code": null, "e": 10986, "s": 10928, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 11028, "s": 10986, "text": "Retrofit with Kotlin Coroutine in Android" }, { "code": null, "e": 11057, "s": 11028, "text": "Navigation Drawer in Android" }, { "code": null, "e": 11100, "s": 11057, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 11115, "s": 11100, "text": "Arrays in Java" }, { "code": null, "e": 11151, "s": 11115, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 11176, "s": 11151, "text": "Reverse a string in Java" }, { "code": null, "e": 11220, "s": 11176, "text": "Split() String method in Java with examples" } ]
Main Thread in C#
13 May, 2019 C# provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called an thread, and each thread defines a separate path of execution. When a C# program starts up, one thread begins running immediately. This is usually called the main thread of our program. Properties: It is the thread under which other “child” threads will be created. Often, it must be the last thread to finish execution because it performs various shutdown actions. Example: // C# program to illustrate the working// of main thread and child threadusing System;using System.Threading; public class GFG { // Main thread static public void Main() { Console.WriteLine("Welcome to the Main thread"); // Child threads Thread thrA = new Thread(childthread); Thread thrB = new Thread(childthread); thrA.Start(); thrB.Start(); } public static void childthread() { Console.WriteLine("Welcome to the Child thread"); }} Output: Welcome to the Main thread Welcome to the Child thread Welcome to the Child thread Explanation: The above program consists of only one thread that is known as the main thread. The main thread works just like other thread but it starts automatically, you need not to require any Start() method to start the execution of the main thread. Both thrA and thrB are the child thread of main thread. First main thread starts its working after that child thread starts their working. For accessing main thread you require the Thread class object to refer it. You can create this by using the CurrentThread property of the Thread class. It will return the reference to the thread in which it used. So when you use CurrentThread property inside the main thread you will get the reference of the main thread. After that, you will get control over the main thread just like another thread. Example: // C# program to illustrate// how to access main threadusing System;using System.Threading; public class GFG { // Main Method static public void Main() { Thread thr; // Get the reference of main Thread // Using CurrentThread property thr = Thread.CurrentThread; // Display the name of // the main Thread if (thr.Name == null) { Console.WriteLine("Main thread does not have name"); } else { Console.WriteLine("The name of main "+ "thread is: {0}", thr.Name); } Console.WriteLine(); // Display the priority of main thread Console.WriteLine("The priority of main"+ " thread is: {0}", thr.Priority); // Set the name of main thread thr.Name = "Main Thread"; Console.WriteLine(); // Display the name of main thread Console.WriteLine("The name of main "+ "thread is: {0}", thr.Name); }} Output: Main thread does not have name The priority of main thread is: Normal The name of main thread is: Main Thread We can create a deadlock by just using Main thread, i.e. by just using a single thread. The following C# program demonstrates this. Example: // C# program to demonstrate deadlock// using the Main threadusing System;using System.Threading; public class GFG { // Main Method public static void Main() { try { Console.WriteLine("Enter into DEADLOCK!!"); Thread.CurrentThread.Join(); // the following statement // will never execute Console.WriteLine("This statement will never execute"); } catch (ThreadInterruptedException e) { e.ToString(); } }} Output: Enter into DEADLOCK!! Runtime Error: Max real time limit exceeded due to either by heavy load on server or by using sleep function Explanation: The statement “Thread.currentThread().join()“, will tell the Main thread to wait for this thread(i.e. wait for itself) to die. Thus the Main thread waits for itself to die, which is nothing but a deadlock. Akanksha_Rai CSharp Multithreading C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Lambda Expressions in C# Partial Classes in C# Hello World in C#
[ { "code": null, "e": 52, "s": 24, "text": "\n13 May, 2019" }, { "code": null, "e": 294, "s": 52, "text": "C# provides built-in support for multithreaded programming. A multi-threaded program contains two or more parts that can run concurrently. Each part of such a program is called an thread, and each thread defines a separate path of execution." }, { "code": null, "e": 417, "s": 294, "text": "When a C# program starts up, one thread begins running immediately. This is usually called the main thread of our program." }, { "code": null, "e": 429, "s": 417, "text": "Properties:" }, { "code": null, "e": 497, "s": 429, "text": "It is the thread under which other “child” threads will be created." }, { "code": null, "e": 597, "s": 497, "text": "Often, it must be the last thread to finish execution because it performs various shutdown actions." }, { "code": null, "e": 606, "s": 597, "text": "Example:" }, { "code": "// C# program to illustrate the working// of main thread and child threadusing System;using System.Threading; public class GFG { // Main thread static public void Main() { Console.WriteLine(\"Welcome to the Main thread\"); // Child threads Thread thrA = new Thread(childthread); Thread thrB = new Thread(childthread); thrA.Start(); thrB.Start(); } public static void childthread() { Console.WriteLine(\"Welcome to the Child thread\"); }}", "e": 1118, "s": 606, "text": null }, { "code": null, "e": 1126, "s": 1118, "text": "Output:" }, { "code": null, "e": 1210, "s": 1126, "text": "Welcome to the Main thread\nWelcome to the Child thread\nWelcome to the Child thread\n" }, { "code": null, "e": 1602, "s": 1210, "text": "Explanation: The above program consists of only one thread that is known as the main thread. The main thread works just like other thread but it starts automatically, you need not to require any Start() method to start the execution of the main thread. Both thrA and thrB are the child thread of main thread. First main thread starts its working after that child thread starts their working." }, { "code": null, "e": 2004, "s": 1602, "text": "For accessing main thread you require the Thread class object to refer it. You can create this by using the CurrentThread property of the Thread class. It will return the reference to the thread in which it used. So when you use CurrentThread property inside the main thread you will get the reference of the main thread. After that, you will get control over the main thread just like another thread." }, { "code": null, "e": 2013, "s": 2004, "text": "Example:" }, { "code": "// C# program to illustrate// how to access main threadusing System;using System.Threading; public class GFG { // Main Method static public void Main() { Thread thr; // Get the reference of main Thread // Using CurrentThread property thr = Thread.CurrentThread; // Display the name of // the main Thread if (thr.Name == null) { Console.WriteLine(\"Main thread does not have name\"); } else { Console.WriteLine(\"The name of main \"+ \"thread is: {0}\", thr.Name); } Console.WriteLine(); // Display the priority of main thread Console.WriteLine(\"The priority of main\"+ \" thread is: {0}\", thr.Priority); // Set the name of main thread thr.Name = \"Main Thread\"; Console.WriteLine(); // Display the name of main thread Console.WriteLine(\"The name of main \"+ \"thread is: {0}\", thr.Name); }}", "e": 3028, "s": 2013, "text": null }, { "code": null, "e": 3036, "s": 3028, "text": "Output:" }, { "code": null, "e": 3149, "s": 3036, "text": "Main thread does not have name\n\nThe priority of main thread is: Normal\n\nThe name of main thread is: Main Thread\n" }, { "code": null, "e": 3281, "s": 3149, "text": "We can create a deadlock by just using Main thread, i.e. by just using a single thread. The following C# program demonstrates this." }, { "code": null, "e": 3290, "s": 3281, "text": "Example:" }, { "code": "// C# program to demonstrate deadlock// using the Main threadusing System;using System.Threading; public class GFG { // Main Method public static void Main() { try { Console.WriteLine(\"Enter into DEADLOCK!!\"); Thread.CurrentThread.Join(); // the following statement // will never execute Console.WriteLine(\"This statement will never execute\"); } catch (ThreadInterruptedException e) { e.ToString(); } }}", "e": 3813, "s": 3290, "text": null }, { "code": null, "e": 3821, "s": 3813, "text": "Output:" }, { "code": null, "e": 3843, "s": 3821, "text": "Enter into DEADLOCK!!" }, { "code": null, "e": 3858, "s": 3843, "text": "Runtime Error:" }, { "code": null, "e": 3952, "s": 3858, "text": "Max real time limit exceeded due to either by heavy load on server or by using sleep function" }, { "code": null, "e": 4171, "s": 3952, "text": "Explanation: The statement “Thread.currentThread().join()“, will tell the Main thread to wait for this thread(i.e. wait for itself) to die. Thus the Main thread waits for itself to die, which is nothing but a deadlock." }, { "code": null, "e": 4184, "s": 4171, "text": "Akanksha_Rai" }, { "code": null, "e": 4206, "s": 4184, "text": "CSharp Multithreading" }, { "code": null, "e": 4209, "s": 4206, "text": "C#" }, { "code": null, "e": 4307, "s": 4209, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4350, "s": 4307, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 4399, "s": 4350, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 4422, "s": 4399, "text": "Extension Method in C#" }, { "code": null, "e": 4438, "s": 4422, "text": "C# | List Class" }, { "code": null, "e": 4466, "s": 4438, "text": "HashSet in C# with Examples" }, { "code": null, "e": 4527, "s": 4466, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 4550, "s": 4527, "text": "Switch Statement in C#" }, { "code": null, "e": 4575, "s": 4550, "text": "Lambda Expressions in C#" }, { "code": null, "e": 4597, "s": 4575, "text": "Partial Classes in C#" } ]
numpy.nan_to_num() in Python
28 Nov, 2018 numpy.nan_to_num() function is used when we want to replace nan(Not A Number) with zero and inf with finite numbers in an array. It returns (positive) infinity with a very large number and negative infinity with a very small (or negative) number. Syntax : numpy.nan_to_num(arr, copy=True) Parameters :arr : [array_like] Input data.copy : [bool, optional] Whether to create a copy of arr (True) or to replace values in-place (False). The in-place operation only occurs if casting to an array does not require a copy. Default is True. Return : [ndarray] New Array with the same shape as arr and dtype of the element in arr with the greatest precision. If arr is inexact, then NaN is replaced by zero, and infinity (-infinity) is replaced by the largest (smallest or most negative) floating point value that fits in the output dtype. If arr is not inexact, then a copy of arr is returned. Code #1 : Working # Python program explaining# numpy.nan_to_num() function import numpy as geekin_num = geek.nan print ("Input number : ", in_num) out_num = geek.nan_to_num(in_num) print ("output number : ", out_num) Output : Input number : nan output number : 0.0 Code #2 : # Python program explaining# numpy.nan_to_num function import numpy as geek in_arr = geek.array([[2, geek.inf, 2], [2, 2, geek.nan]]) print ("Input array : ", in_arr) out_arr = geek.nan_to_num(in_arr) print ("output array: ", out_arr) Output : Input array : [[ 2. inf 2.] [ 2. 2. nan]] output array: [[ 2.00000000e+000 1.79769313e+308 2.00000000e+000] [ 2.00000000e+000 2.00000000e+000 0.00000000e+000]] Code #3 : # Python program explaining# numpy.nan_to_num function import numpy as geek in_arr = geek.array([[2, 2, 2], [2, 2, 6]]) print ("Input array : ", in_arr) out_arr = geek.nan_to_num(in_arr) print ("Output array: ", out_arr) Output : Input array : Input array : [[2 2 2] [2 2 6]] Output array: [[2 2 2] [2 2 6]] Python numpy-Mathematical Function Python-numpy 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 Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Nov, 2018" }, { "code": null, "e": 275, "s": 28, "text": "numpy.nan_to_num() function is used when we want to replace nan(Not A Number) with zero and inf with finite numbers in an array. It returns (positive) infinity with a very large number and negative infinity with a very small (or negative) number." }, { "code": null, "e": 317, "s": 275, "text": "Syntax : numpy.nan_to_num(arr, copy=True)" }, { "code": null, "e": 561, "s": 317, "text": "Parameters :arr : [array_like] Input data.copy : [bool, optional] Whether to create a copy of arr (True) or to replace values in-place (False). The in-place operation only occurs if casting to an array does not require a copy. Default is True." }, { "code": null, "e": 914, "s": 561, "text": "Return : [ndarray] New Array with the same shape as arr and dtype of the element in arr with the greatest precision. If arr is inexact, then NaN is replaced by zero, and infinity (-infinity) is replaced by the largest (smallest or most negative) floating point value that fits in the output dtype. If arr is not inexact, then a copy of arr is returned." }, { "code": null, "e": 932, "s": 914, "text": "Code #1 : Working" }, { "code": "# Python program explaining# numpy.nan_to_num() function import numpy as geekin_num = geek.nan print (\"Input number : \", in_num) out_num = geek.nan_to_num(in_num) print (\"output number : \", out_num) ", "e": 1139, "s": 932, "text": null }, { "code": null, "e": 1148, "s": 1139, "text": "Output :" }, { "code": null, "e": 1192, "s": 1148, "text": "Input number : nan\noutput number : 0.0\n" }, { "code": null, "e": 1203, "s": 1192, "text": " Code #2 :" }, { "code": "# Python program explaining# numpy.nan_to_num function import numpy as geek in_arr = geek.array([[2, geek.inf, 2], [2, 2, geek.nan]]) print (\"Input array : \", in_arr) out_arr = geek.nan_to_num(in_arr) print (\"output array: \", out_arr) ", "e": 1447, "s": 1203, "text": null }, { "code": null, "e": 1456, "s": 1447, "text": "Output :" }, { "code": null, "e": 1639, "s": 1456, "text": "Input array : [[ 2. inf 2.]\n [ 2. 2. nan]]\noutput array: [[ 2.00000000e+000 1.79769313e+308 2.00000000e+000]\n [ 2.00000000e+000 2.00000000e+000 0.00000000e+000]]\n" }, { "code": null, "e": 1650, "s": 1639, "text": " Code #3 :" }, { "code": "# Python program explaining# numpy.nan_to_num function import numpy as geek in_arr = geek.array([[2, 2, 2], [2, 2, 6]]) print (\"Input array : \", in_arr) out_arr = geek.nan_to_num(in_arr) print (\"Output array: \", out_arr) ", "e": 1880, "s": 1650, "text": null }, { "code": null, "e": 1889, "s": 1880, "text": "Output :" }, { "code": null, "e": 1973, "s": 1889, "text": "Input array : Input array : [[2 2 2]\n [2 2 6]]\nOutput array: [[2 2 2]\n [2 2 6]]\n" }, { "code": null, "e": 2008, "s": 1973, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 2021, "s": 2008, "text": "Python-numpy" }, { "code": null, "e": 2028, "s": 2021, "text": "Python" }, { "code": null, "e": 2126, "s": 2028, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2144, "s": 2126, "text": "Python Dictionary" }, { "code": null, "e": 2186, "s": 2144, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2208, "s": 2186, "text": "Enumerate() in Python" }, { "code": null, "e": 2243, "s": 2208, "text": "Read a file line by line in Python" }, { "code": null, "e": 2269, "s": 2243, "text": "Python String | replace()" }, { "code": null, "e": 2301, "s": 2269, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2330, "s": 2301, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2360, "s": 2330, "text": "Iterate over a list in Python" }, { "code": null, "e": 2387, "s": 2360, "text": "Python Classes and Objects" } ]
Select rows of a matrix in R that meet a condition
26 Sep, 2021 A large dataset is often required to be filtered according to our requirements. In this article, we will be discussing how we can select a row from a matrix in R that meets the condition. For better understanding let’s understand the problem statement with the help of an example. Example: Data in use: 1 Maruti Diesel Red 2001 2 Hyundai Petrol Blue 2011 3 Tata Petrol Red 2013 4 Ford Diesel Red 2012 5 Nissan Petrol Blue 2021 6 Toyota Diesel Red 2021 Now, as the problem statement is that we want to select the rows of the matrix that meets the given condition. Suppose we want to select the rows from the matrix whose car_color = Red. Then, the output must look like this: car_models car_type car_color year 1 Maruti Diesel Red 2001 2 Tata Petrol Red 2013 3 Ford Diesel Red 2012 4 Toyota Diesel Red 2021 Approach: Create dataset Specify the condition Pass it to the matrix Select rows which specify this condition Syntax: dataset[condition] Example: mat[mat[,”car_color”]==”Red”,] Here, Comma(‘,’) is used to return all the matrix rows. Copy the resultant dataset to auxiliary dataset Display dataset Example: R # Creating Dataset car_models <- c('Maruti','Hyundai','Tata', 'Ford','Nissan','Toyota') car_type <- c('Diesel','Petrol','Petrol', 'Diesel','Petrol','Diesel') car_color <- c('Red','Blue','Red', 'Red','Blue','Red') year <- c(2001,2011,2013,2012,2021,2021) # Storing matrix in mat (variable)mat <- cbind(car_models,car_type,car_color,year) # condition to select only rows with# color = Redmat <- mat[mat[,"car_color"]=="Red",] # displaying the resultant matrixmat Output: Resultant Matrix akshaysingh98088 Picked R Matrix-Programs R-Matrix R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? R - if statement How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Sep, 2021" }, { "code": null, "e": 309, "s": 28, "text": "A large dataset is often required to be filtered according to our requirements. In this article, we will be discussing how we can select a row from a matrix in R that meets the condition. For better understanding let’s understand the problem statement with the help of an example." }, { "code": null, "e": 318, "s": 309, "text": "Example:" }, { "code": null, "e": 331, "s": 318, "text": "Data in use:" }, { "code": null, "e": 333, "s": 331, "text": "1" }, { "code": null, "e": 340, "s": 333, "text": "Maruti" }, { "code": null, "e": 347, "s": 340, "text": "Diesel" }, { "code": null, "e": 351, "s": 347, "text": "Red" }, { "code": null, "e": 356, "s": 351, "text": "2001" }, { "code": null, "e": 358, "s": 356, "text": "2" }, { "code": null, "e": 366, "s": 358, "text": "Hyundai" }, { "code": null, "e": 373, "s": 366, "text": "Petrol" }, { "code": null, "e": 378, "s": 373, "text": "Blue" }, { "code": null, "e": 383, "s": 378, "text": "2011" }, { "code": null, "e": 385, "s": 383, "text": "3" }, { "code": null, "e": 390, "s": 385, "text": "Tata" }, { "code": null, "e": 397, "s": 390, "text": "Petrol" }, { "code": null, "e": 401, "s": 397, "text": "Red" }, { "code": null, "e": 406, "s": 401, "text": "2013" }, { "code": null, "e": 408, "s": 406, "text": "4" }, { "code": null, "e": 413, "s": 408, "text": "Ford" }, { "code": null, "e": 420, "s": 413, "text": "Diesel" }, { "code": null, "e": 424, "s": 420, "text": "Red" }, { "code": null, "e": 429, "s": 424, "text": "2012" }, { "code": null, "e": 431, "s": 429, "text": "5" }, { "code": null, "e": 438, "s": 431, "text": "Nissan" }, { "code": null, "e": 445, "s": 438, "text": "Petrol" }, { "code": null, "e": 450, "s": 445, "text": "Blue" }, { "code": null, "e": 455, "s": 450, "text": "2021" }, { "code": null, "e": 457, "s": 455, "text": "6" }, { "code": null, "e": 464, "s": 457, "text": "Toyota" }, { "code": null, "e": 471, "s": 464, "text": "Diesel" }, { "code": null, "e": 475, "s": 471, "text": "Red" }, { "code": null, "e": 480, "s": 475, "text": "2021" }, { "code": null, "e": 665, "s": 480, "text": "Now, as the problem statement is that we want to select the rows of the matrix that meets the given condition. Suppose we want to select the rows from the matrix whose car_color = Red." }, { "code": null, "e": 703, "s": 665, "text": "Then, the output must look like this:" }, { "code": null, "e": 734, "s": 716, "text": " car_models " }, { "code": null, "e": 750, "s": 734, "text": " car_type " }, { "code": null, "e": 767, "s": 750, "text": " car_color " }, { "code": null, "e": 777, "s": 767, "text": " year " }, { "code": null, "e": 779, "s": 777, "text": "1" }, { "code": null, "e": 786, "s": 779, "text": "Maruti" }, { "code": null, "e": 793, "s": 786, "text": "Diesel" }, { "code": null, "e": 797, "s": 793, "text": "Red" }, { "code": null, "e": 802, "s": 797, "text": "2001" }, { "code": null, "e": 804, "s": 802, "text": "2" }, { "code": null, "e": 809, "s": 804, "text": "Tata" }, { "code": null, "e": 816, "s": 809, "text": "Petrol" }, { "code": null, "e": 820, "s": 816, "text": "Red" }, { "code": null, "e": 825, "s": 820, "text": "2013" }, { "code": null, "e": 827, "s": 825, "text": "3" }, { "code": null, "e": 832, "s": 827, "text": "Ford" }, { "code": null, "e": 839, "s": 832, "text": "Diesel" }, { "code": null, "e": 843, "s": 839, "text": "Red" }, { "code": null, "e": 848, "s": 843, "text": "2012" }, { "code": null, "e": 850, "s": 848, "text": "4" }, { "code": null, "e": 857, "s": 850, "text": "Toyota" }, { "code": null, "e": 864, "s": 857, "text": "Diesel" }, { "code": null, "e": 868, "s": 864, "text": "Red" }, { "code": null, "e": 873, "s": 868, "text": "2021" }, { "code": null, "e": 883, "s": 873, "text": "Approach:" }, { "code": null, "e": 898, "s": 883, "text": "Create dataset" }, { "code": null, "e": 920, "s": 898, "text": "Specify the condition" }, { "code": null, "e": 942, "s": 920, "text": "Pass it to the matrix" }, { "code": null, "e": 983, "s": 942, "text": "Select rows which specify this condition" }, { "code": null, "e": 991, "s": 983, "text": "Syntax:" }, { "code": null, "e": 1010, "s": 991, "text": "dataset[condition]" }, { "code": null, "e": 1019, "s": 1010, "text": "Example:" }, { "code": null, "e": 1050, "s": 1019, "text": "mat[mat[,”car_color”]==”Red”,]" }, { "code": null, "e": 1106, "s": 1050, "text": "Here, Comma(‘,’) is used to return all the matrix rows." }, { "code": null, "e": 1154, "s": 1106, "text": "Copy the resultant dataset to auxiliary dataset" }, { "code": null, "e": 1170, "s": 1154, "text": "Display dataset" }, { "code": null, "e": 1179, "s": 1170, "text": "Example:" }, { "code": null, "e": 1181, "s": 1179, "text": "R" }, { "code": "# Creating Dataset car_models <- c('Maruti','Hyundai','Tata', 'Ford','Nissan','Toyota') car_type <- c('Diesel','Petrol','Petrol', 'Diesel','Petrol','Diesel') car_color <- c('Red','Blue','Red', 'Red','Blue','Red') year <- c(2001,2011,2013,2012,2021,2021) # Storing matrix in mat (variable)mat <- cbind(car_models,car_type,car_color,year) # condition to select only rows with# color = Redmat <- mat[mat[,\"car_color\"]==\"Red\",] # displaying the resultant matrixmat", "e": 1684, "s": 1181, "text": null }, { "code": null, "e": 1692, "s": 1684, "text": "Output:" }, { "code": null, "e": 1709, "s": 1692, "text": "Resultant Matrix" }, { "code": null, "e": 1726, "s": 1709, "text": "akshaysingh98088" }, { "code": null, "e": 1733, "s": 1726, "text": "Picked" }, { "code": null, "e": 1751, "s": 1733, "text": "R Matrix-Programs" }, { "code": null, "e": 1760, "s": 1751, "text": "R-Matrix" }, { "code": null, "e": 1771, "s": 1760, "text": "R Language" }, { "code": null, "e": 1782, "s": 1771, "text": "R Programs" }, { "code": null, "e": 1880, "s": 1782, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1932, "s": 1880, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1990, "s": 1932, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2025, "s": 1990, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2063, "s": 2025, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2080, "s": 2063, "text": "R - if statement" }, { "code": null, "e": 2138, "s": 2080, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2187, "s": 2138, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2230, "s": 2187, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2268, "s": 2230, "text": "Merge DataFrames by Column Names in R" } ]
Google Colab - Graphical Outputs
Colab also supports rich outputs such as charts. Type in the following code in the Code cell. import numpy as np from matplotlib import pyplot as plt y = np.random.randn(100) x = [x for x in range(len(y))] plt.plot(x, y, '-') plt.fill_between(x, y, 200, where = (y > 195), facecolor='g', alpha=0.6) plt.title("Sample Plot") plt.show() Now, if you run the code, you will see the following output − Note that the graphical output is shown in the output section of the Code cell. Likewise, you will be able to create and display several types of charts throughout your program code. Now, as you have got familiar with the basics of Colab, let us move on to the features in Colab that makes your Python code development easier.
[ { "code": null, "e": 2269, "s": 2175, "text": "Colab also supports rich outputs such as charts. Type in the following code in the Code cell." }, { "code": null, "e": 2514, "s": 2269, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\n\ny = np.random.randn(100)\nx = [x for x in range(len(y))]\n\nplt.plot(x, y, '-')\nplt.fill_between(x, y, 200, where = (y > 195), facecolor='g', alpha=0.6)\n\nplt.title(\"Sample Plot\")\nplt.show()\n" }, { "code": null, "e": 2576, "s": 2514, "text": "Now, if you run the code, you will see the following output −" }, { "code": null, "e": 2759, "s": 2576, "text": "Note that the graphical output is shown in the output section of the Code cell. Likewise, you will be able to create and display several types of charts throughout your program code." } ]
Java Program to Sort Vector Using Collections.sort() Method
11 Dec, 2020 java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collection in ascending order. Syntax: Public void sort(Vector object); Parameters: Instance of the vector as an argument Illustration: Collection.sort() method Let us suppose that our list contains {"Geeks For Geeks", "Friends", "Dear", "Is", "Superb"} After using Collection.sort(), we obtain a sorted list as {"Dear", "Friends", "Geeks For Geeks", "Is", "Superb"} Create a vector instance.Add elements in the vector.Printing vector before function using the method to illustrate what the function is responsible for.Using Collection.sort() method.Print vector after sorting and it is seen sorting is ascending. Create a vector instance. Add elements in the vector. Printing vector before function using the method to illustrate what the function is responsible for. Using Collection.sort() method. Print vector after sorting and it is seen sorting is ascending. Example 1: Java // Java Program to Sort Vector// using Collections.sort() Method // Importing Collection and Vector classimport java.util.Collections;import java.util.Vector; public class GFG { // Main driver method public static void main(String args[]) { // Create a instance vector Vector<String> vec = new Vector<String>(); // Insert the values in vector vec.add("a"); vec.add("d"); vec.add("e"); vec.add("b"); vec.add("c"); // Display the vector System.out.println("original vector : " + vec); // Call sort() method Collections.sort(vec); // Display vector after replacing value System.out.println("\nsorted vector : " + vec); }} original vector : [a, d, e, b, c] sorted vector : [a, b, c, d, e] Example 2: Java // Java Program to Sort Vector// using Collections.sort() Method // Importing Collection and Vector classimport java.util.Collections;import java.util.Vector; public class GFG { // Main driver method public static void main(String args[]) { // Create a instance vector Vector<String> vec = new Vector<String>(); // Insert the values in vector vec.add("4"); vec.add("2"); vec.add("7"); vec.add("3"); vec.add("2"); // Display the vector System.out.println("\noriginal vector : " + vec); // Call sort() method Collections.sort(vec); // Display vector after replacing value System.out.println("\nsorted vector : " + vec); }} original vector : [4, 2, 7, 3, 2] sorted vector : [2, 2, 3, 4, 7] Java-Collections Java-Vector Picked Java Java Programs Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2020" }, { "code": null, "e": 203, "s": 28, "text": "java.util.Collections.sort() method is present in java.util.Collections class. It is used to sort the elements present in the specified list of Collection in ascending order." }, { "code": null, "e": 211, "s": 203, "text": "Syntax:" }, { "code": null, "e": 244, "s": 211, "text": "Public void sort(Vector object);" }, { "code": null, "e": 294, "s": 244, "text": "Parameters: Instance of the vector as an argument" }, { "code": null, "e": 333, "s": 294, "text": "Illustration: Collection.sort() method" }, { "code": null, "e": 540, "s": 333, "text": "Let us suppose that our list contains\n{\"Geeks For Geeks\", \"Friends\", \"Dear\", \"Is\", \"Superb\"}\n\nAfter using Collection.sort(), we obtain a sorted list as\n{\"Dear\", \"Friends\", \"Geeks For Geeks\", \"Is\", \"Superb\"}" }, { "code": null, "e": 787, "s": 540, "text": "Create a vector instance.Add elements in the vector.Printing vector before function using the method to illustrate what the function is responsible for.Using Collection.sort() method.Print vector after sorting and it is seen sorting is ascending." }, { "code": null, "e": 813, "s": 787, "text": "Create a vector instance." }, { "code": null, "e": 841, "s": 813, "text": "Add elements in the vector." }, { "code": null, "e": 942, "s": 841, "text": "Printing vector before function using the method to illustrate what the function is responsible for." }, { "code": null, "e": 974, "s": 942, "text": "Using Collection.sort() method." }, { "code": null, "e": 1038, "s": 974, "text": "Print vector after sorting and it is seen sorting is ascending." }, { "code": null, "e": 1049, "s": 1038, "text": "Example 1:" }, { "code": null, "e": 1054, "s": 1049, "text": "Java" }, { "code": "// Java Program to Sort Vector// using Collections.sort() Method // Importing Collection and Vector classimport java.util.Collections;import java.util.Vector; public class GFG { // Main driver method public static void main(String args[]) { // Create a instance vector Vector<String> vec = new Vector<String>(); // Insert the values in vector vec.add(\"a\"); vec.add(\"d\"); vec.add(\"e\"); vec.add(\"b\"); vec.add(\"c\"); // Display the vector System.out.println(\"original vector : \" + vec); // Call sort() method Collections.sort(vec); // Display vector after replacing value System.out.println(\"\\nsorted vector : \" + vec); }}", "e": 1795, "s": 1054, "text": null }, { "code": null, "e": 1863, "s": 1795, "text": "original vector : [a, d, e, b, c]\n\nsorted vector : [a, b, c, d, e]\n" }, { "code": null, "e": 1874, "s": 1863, "text": "Example 2:" }, { "code": null, "e": 1879, "s": 1874, "text": "Java" }, { "code": "// Java Program to Sort Vector// using Collections.sort() Method // Importing Collection and Vector classimport java.util.Collections;import java.util.Vector; public class GFG { // Main driver method public static void main(String args[]) { // Create a instance vector Vector<String> vec = new Vector<String>(); // Insert the values in vector vec.add(\"4\"); vec.add(\"2\"); vec.add(\"7\"); vec.add(\"3\"); vec.add(\"2\"); // Display the vector System.out.println(\"\\noriginal vector : \" + vec); // Call sort() method Collections.sort(vec); // Display vector after replacing value System.out.println(\"\\nsorted vector : \" + vec); }}", "e": 2622, "s": 1879, "text": null }, { "code": null, "e": 2690, "s": 2622, "text": "original vector : [4, 2, 7, 3, 2]\n\nsorted vector : [2, 2, 3, 4, 7]\n" }, { "code": null, "e": 2707, "s": 2690, "text": "Java-Collections" }, { "code": null, "e": 2719, "s": 2707, "text": "Java-Vector" }, { "code": null, "e": 2726, "s": 2719, "text": "Picked" }, { "code": null, "e": 2731, "s": 2726, "text": "Java" }, { "code": null, "e": 2745, "s": 2731, "text": "Java Programs" }, { "code": null, "e": 2750, "s": 2745, "text": "Java" }, { "code": null, "e": 2767, "s": 2750, "text": "Java-Collections" }, { "code": null, "e": 2865, "s": 2767, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2880, "s": 2865, "text": "Stream In Java" }, { "code": null, "e": 2901, "s": 2880, "text": "Introduction to Java" }, { "code": null, "e": 2922, "s": 2901, "text": "Constructors in Java" }, { "code": null, "e": 2941, "s": 2922, "text": "Exceptions in Java" }, { "code": null, "e": 2958, "s": 2941, "text": "Generics in Java" }, { "code": null, "e": 2984, "s": 2958, "text": "Java Programming Examples" }, { "code": null, "e": 3018, "s": 2984, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 3065, "s": 3018, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 3103, "s": 3065, "text": "Factory method design pattern in Java" } ]
Loops in C#
22 Apr, 2020 Looping in a programming language is a way to execute a statement or a set of statements multiple times depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops. Loops are mainly divided into two categories:Entry Controlled Loops: The loops in which condition to be tested is present in beginning of loop body are known as Entry Controlled Loops. while loop and for loop are entry controlled loops. 1. while loop The test condition is given in the beginning of the loop and all statements are executed till the given boolean condition satisfies when the condition becomes false, the control will be out from the while loop. Syntax: while (boolean condition) { loop statements... } Flowchart: Example: // C# program to illustrate while loopusing System; class whileLoopDemo{ public static void Main() { int x = 1; // Exit when x becomes greater than 4 while (x <= 4) { Console.WriteLine("GeeksforGeeks"); // Increment the value of x for // next iteration x++; } }} Output: GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks 2. for loopfor loop has similar functionality as while loop but with different syntax. for loops are preferred when the number of times loop statements are to be executed is known beforehand. The loop variable initialization, condition to be tested, and increment/decrement of the loop variable is done in one line in for loop thereby providing a shorter, easy to debug structure of looping. for (loop variable initialization ; testing condition; increment / decrement) { // statements to be executed } Flowchart: 1. Initialization of loop variable: Th expression / variable controlling the loop is initialized here. It is the starting point of for loop. An already declared variable can be used or a variable can be declared, local to loop only.2. Testing Condition: The testing condition to execute statements of loop. It is used for testing the exit condition for a loop. It must return a boolean value true or false. When the condition became false the control will be out from the loop and for loop ends.3. Increment / Decrement: The loop variable is incremented/decremented according to the requirement and the control then shifts to the testing condition again. Note: Initialization part is evaluated only once when the for loop starts. Example: // C# program to illustrate for loop.using System; class forLoopDemo{ public static void Main() { // for loop begins when x=1 // and runs till x <=4 for (int x = 1; x <= 4; x++) Console.WriteLine("GeeksforGeeks"); }} Output: GeeksforGeeks GeeksforGeeks GeeksforGeeks GeeksforGeeks Exit Controlled Loops: The loops in which the testing condition is present at the end of loop body are termed as Exit Controlled Loops. do-while is an exit controlled loop.Note: In Exit Controlled Loops, loop body will be evaluated for at-least one time as the testing condition is present at the end of loop body. 1. do-while loopdo while loop is similar to while loop with the only difference that it checks the condition after executing the statements, i.e it will execute the loop body one time for sure because it checks the condition after executing the statements. Syntax : do { statements.. }while (condition); Flowchart: Example: // C# program to illustrate do-while loopusing System; class dowhileloopDemo{ public static void Main() { int x = 21; do { // The line will be printed even // if the condition is false Console.WriteLine("GeeksforGeeks"); x++; } while (x < 20); }} Output: GeeksforGeeks Infinite Loops:The loops in which the test condition does not evaluate false ever tend to execute statements forever until an external force is used to end it and thus they are known as infinite loops. Example: // C# program to demonstrate infinite loopusing System; class infiniteLoop{ public static void Main() { // The statement will be printed // infinite times for(;;) Console.WriteLine("This is printed infinite times"); }} Output: This is printed infinite times This is printed infinite times This is printed infinite times This is printed infinite times This is printed infinite times This is printed infinite times This is printed infinite times .......... Nested Loops:When loops are present inside the other loops, it is known as nested loops. Example: // C# program to demonstrate nested loopsusing System; class nestedLoops{ public static void Main() { // loop within loop printing GeeksforGeeks for(int i = 2; i < 3; i++) for(int j = 1; j < i; j++) Console.WriteLine("GeeksforGeeks"); }} Output: GeeksforGeeks continue statement:continue statement is used to skip over the execution part of loop on a certain condition and move the flow to next updation part.Flowchart: Example: // C# program to demonstrate continue statementusing System; class demoContinue{ public static void Main() { // GeeksforGeeks is printed only 2 times // because of continue statement for(int i = 1; i < 3; i++) { if(i == 2) continue; Console.WriteLine("GeeksforGeeks"); } }} Output: GeeksforGeeks CSharp-Basics C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Abstract Class and Interface in C# C# | How to check whether a List contains a specified element C# | Arrays of Strings C# | IsNullOrEmpty() Method String.Split() Method in C# with Examples C# | Delegates C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework C# | String.IndexOf( ) Method | Set - 1 Extension Method in C#
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Apr, 2020" }, { "code": null, "e": 310, "s": 54, "text": "Looping in a programming language is a way to execute a statement or a set of statements multiple times depending on the result of the condition to be evaluated to execute statements. The result condition should be true to execute statements within loops." }, { "code": null, "e": 547, "s": 310, "text": "Loops are mainly divided into two categories:Entry Controlled Loops: The loops in which condition to be tested is present in beginning of loop body are known as Entry Controlled Loops. while loop and for loop are entry controlled loops." }, { "code": null, "e": 772, "s": 547, "text": "1. while loop The test condition is given in the beginning of the loop and all statements are executed till the given boolean condition satisfies when the condition becomes false, the control will be out from the while loop." }, { "code": null, "e": 780, "s": 772, "text": "Syntax:" }, { "code": null, "e": 832, "s": 780, "text": "while (boolean condition)\n{\n loop statements...\n}" }, { "code": null, "e": 843, "s": 832, "text": "Flowchart:" }, { "code": null, "e": 852, "s": 843, "text": "Example:" }, { "code": "// C# program to illustrate while loopusing System; class whileLoopDemo{ public static void Main() { int x = 1; // Exit when x becomes greater than 4 while (x <= 4) { Console.WriteLine(\"GeeksforGeeks\"); // Increment the value of x for // next iteration x++; } }}", "e": 1210, "s": 852, "text": null }, { "code": null, "e": 1218, "s": 1210, "text": "Output:" }, { "code": null, "e": 1275, "s": 1218, "text": "GeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\n" }, { "code": null, "e": 1667, "s": 1275, "text": "2. for loopfor loop has similar functionality as while loop but with different syntax. for loops are preferred when the number of times loop statements are to be executed is known beforehand. The loop variable initialization, condition to be tested, and increment/decrement of the loop variable is done in one line in for loop thereby providing a shorter, easy to debug structure of looping." }, { "code": null, "e": 1817, "s": 1667, "text": "for (loop variable initialization ; testing condition; \n increment / decrement)\n{ \n // statements to be executed\n}" }, { "code": null, "e": 1828, "s": 1817, "text": "Flowchart:" }, { "code": null, "e": 2483, "s": 1828, "text": "1. Initialization of loop variable: Th expression / variable controlling the loop is initialized here. It is the starting point of for loop. An already declared variable can be used or a variable can be declared, local to loop only.2. Testing Condition: The testing condition to execute statements of loop. It is used for testing the exit condition for a loop. It must return a boolean value true or false. When the condition became false the control will be out from the loop and for loop ends.3. Increment / Decrement: The loop variable is incremented/decremented according to the requirement and the control then shifts to the testing condition again." }, { "code": null, "e": 2558, "s": 2483, "text": "Note: Initialization part is evaluated only once when the for loop starts." }, { "code": null, "e": 2567, "s": 2558, "text": "Example:" }, { "code": "// C# program to illustrate for loop.using System; class forLoopDemo{ public static void Main() { // for loop begins when x=1 // and runs till x <=4 for (int x = 1; x <= 4; x++) Console.WriteLine(\"GeeksforGeeks\"); }}", "e": 2826, "s": 2567, "text": null }, { "code": null, "e": 2834, "s": 2826, "text": "Output:" }, { "code": null, "e": 2891, "s": 2834, "text": "GeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\nGeeksforGeeks\n" }, { "code": null, "e": 3206, "s": 2891, "text": "Exit Controlled Loops: The loops in which the testing condition is present at the end of loop body are termed as Exit Controlled Loops. do-while is an exit controlled loop.Note: In Exit Controlled Loops, loop body will be evaluated for at-least one time as the testing condition is present at the end of loop body." }, { "code": null, "e": 3463, "s": 3206, "text": "1. do-while loopdo while loop is similar to while loop with the only difference that it checks the condition after executing the statements, i.e it will execute the loop body one time for sure because it checks the condition after executing the statements." }, { "code": null, "e": 3472, "s": 3463, "text": "Syntax :" }, { "code": null, "e": 3515, "s": 3472, "text": "do\n{\n statements..\n}while (condition);\n" }, { "code": null, "e": 3526, "s": 3515, "text": "Flowchart:" }, { "code": null, "e": 3535, "s": 3526, "text": "Example:" }, { "code": "// C# program to illustrate do-while loopusing System; class dowhileloopDemo{ public static void Main() { int x = 21; do { // The line will be printed even // if the condition is false Console.WriteLine(\"GeeksforGeeks\"); x++; } while (x < 20); }}", "e": 3871, "s": 3535, "text": null }, { "code": null, "e": 3879, "s": 3871, "text": "Output:" }, { "code": null, "e": 3893, "s": 3879, "text": "GeeksforGeeks" }, { "code": null, "e": 4095, "s": 3893, "text": "Infinite Loops:The loops in which the test condition does not evaluate false ever tend to execute statements forever until an external force is used to end it and thus they are known as infinite loops." }, { "code": null, "e": 4104, "s": 4095, "text": "Example:" }, { "code": "// C# program to demonstrate infinite loopusing System; class infiniteLoop{ public static void Main() { // The statement will be printed // infinite times for(;;) Console.WriteLine(\"This is printed infinite times\"); }}", "e": 4362, "s": 4104, "text": null }, { "code": null, "e": 4370, "s": 4362, "text": "Output:" }, { "code": null, "e": 4598, "s": 4370, "text": "This is printed infinite times\nThis is printed infinite times\nThis is printed infinite times\nThis is printed infinite times\nThis is printed infinite times\nThis is printed infinite times\nThis is printed infinite times\n.........." }, { "code": null, "e": 4687, "s": 4598, "text": "Nested Loops:When loops are present inside the other loops, it is known as nested loops." }, { "code": null, "e": 4696, "s": 4687, "text": "Example:" }, { "code": "// C# program to demonstrate nested loopsusing System; class nestedLoops{ public static void Main() { // loop within loop printing GeeksforGeeks for(int i = 2; i < 3; i++) for(int j = 1; j < i; j++) Console.WriteLine(\"GeeksforGeeks\"); }}", "e": 4985, "s": 4696, "text": null }, { "code": null, "e": 4993, "s": 4985, "text": "Output:" }, { "code": null, "e": 5007, "s": 4993, "text": "GeeksforGeeks" }, { "code": null, "e": 5167, "s": 5007, "text": "continue statement:continue statement is used to skip over the execution part of loop on a certain condition and move the flow to next updation part.Flowchart:" }, { "code": null, "e": 5176, "s": 5167, "text": "Example:" }, { "code": "// C# program to demonstrate continue statementusing System; class demoContinue{ public static void Main() { // GeeksforGeeks is printed only 2 times // because of continue statement for(int i = 1; i < 3; i++) { if(i == 2) continue; Console.WriteLine(\"GeeksforGeeks\"); } }} ", "e": 5551, "s": 5176, "text": null }, { "code": null, "e": 5559, "s": 5551, "text": "Output:" }, { "code": null, "e": 5573, "s": 5559, "text": "GeeksforGeeks" }, { "code": null, "e": 5587, "s": 5573, "text": "CSharp-Basics" }, { "code": null, "e": 5590, "s": 5587, "text": "C#" }, { "code": null, "e": 5688, "s": 5590, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5742, "s": 5688, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 5804, "s": 5742, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 5827, "s": 5804, "text": "C# | Arrays of Strings" }, { "code": null, "e": 5855, "s": 5827, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 5897, "s": 5855, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 5912, "s": 5897, "text": "C# | Delegates" }, { "code": null, "e": 5955, "s": 5912, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 6004, "s": 5955, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 6044, "s": 6004, "text": "C# | String.IndexOf( ) Method | Set - 1" } ]
Java | Date format validation using Regex
30 Oct, 2018 We use java.util.regex.Pattern.compile(String regex) method which compiles the given regular expression into a pattern. Here regex is the expression to be compiled. // Java program to check if given date is// valid or not.import java.util.regex.Matcher;import java.util.regex.Pattern; public class GeeksforGeeks { // Returns true if d is in format // /dd/mm/yyyy public static boolean isValidDate(String d) { String regex = "^(1[0-2]|0[1-9])/(3[01]" + "|[12][0-9]|0[1-9])/[0-9]{4}$"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher((CharSequence)d); return matcher.matches(); } public static void main(String args[]) { System.out.println(isValidDate("10/12/2016")); System.out.println(isValidDate("10/02/18")); }} true false More ways to validate a date : SimpleDateFormat class. We can use parse method of this class to validate the date.Writing our own method to check if a date is valid. SimpleDateFormat class. We can use parse method of this class to validate the date. Writing our own method to check if a date is valid. date-time-program Java-Date-Time Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Oct, 2018" }, { "code": null, "e": 193, "s": 28, "text": "We use java.util.regex.Pattern.compile(String regex) method which compiles the given regular expression into a pattern. Here regex is the expression to be compiled." }, { "code": "// Java program to check if given date is// valid or not.import java.util.regex.Matcher;import java.util.regex.Pattern; public class GeeksforGeeks { // Returns true if d is in format // /dd/mm/yyyy public static boolean isValidDate(String d) { String regex = \"^(1[0-2]|0[1-9])/(3[01]\" + \"|[12][0-9]|0[1-9])/[0-9]{4}$\"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher((CharSequence)d); return matcher.matches(); } public static void main(String args[]) { System.out.println(isValidDate(\"10/12/2016\")); System.out.println(isValidDate(\"10/02/18\")); }}", "e": 863, "s": 193, "text": null }, { "code": null, "e": 875, "s": 863, "text": "true\nfalse\n" }, { "code": null, "e": 906, "s": 875, "text": "More ways to validate a date :" }, { "code": null, "e": 1041, "s": 906, "text": "SimpleDateFormat class. We can use parse method of this class to validate the date.Writing our own method to check if a date is valid." }, { "code": null, "e": 1125, "s": 1041, "text": "SimpleDateFormat class. We can use parse method of this class to validate the date." }, { "code": null, "e": 1177, "s": 1125, "text": "Writing our own method to check if a date is valid." }, { "code": null, "e": 1195, "s": 1177, "text": "date-time-program" }, { "code": null, "e": 1210, "s": 1195, "text": "Java-Date-Time" }, { "code": null, "e": 1215, "s": 1210, "text": "Java" }, { "code": null, "e": 1229, "s": 1215, "text": "Java Programs" }, { "code": null, "e": 1234, "s": 1229, "text": "Java" }, { "code": null, "e": 1332, "s": 1234, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1347, "s": 1332, "text": "Stream In Java" }, { "code": null, "e": 1368, "s": 1347, "text": "Introduction to Java" }, { "code": null, "e": 1389, "s": 1368, "text": "Constructors in Java" }, { "code": null, "e": 1408, "s": 1389, "text": "Exceptions in Java" }, { "code": null, "e": 1425, "s": 1408, "text": "Generics in Java" }, { "code": null, "e": 1451, "s": 1425, "text": "Java Programming Examples" }, { "code": null, "e": 1485, "s": 1451, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 1532, "s": 1485, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 1570, "s": 1532, "text": "Factory method design pattern in Java" } ]
Node.js http.globalAgent Property
30 Sep, 2020 The http.globalAgent (Added in v0.5.9) property is an inbuilt property of the ‘http’ module which is used as the default for all HTTP client requests. It is the global instance of Agent. An Agent maintains a queue of pending requests for a given host and port, reusing a single socket connection for each until the queue is empty, at which time the socket is either destroyed or put into a pool where it is kept to be used again for requests to the same host and port. In order to get a response and a proper result, we need to import ‘http’ module. Import: const http = require('http'); Syntax: http.globalAgent Parameters: This property does not accept any parameters as mentioned above. Return Value<http.Agent>: It is responsible for managing connection persistence and reuses for HTTP clients. The below example illustrates the use of http.globalAgent property in Node.js. Example 1: Filename: index.js // Node.js program to demonstrate the // http.globalAgent Method // Importing http modulevar http = require('http');const { globalAgent } = require('http'); const PORT = process.env.PORT || 3000; console.log(globalAgent); // Creating http Servervar httpServer = http.createServer( function(request, response) { console.log(globalAgent); var Output = "Hello Geeksforgeeks..., " + "Output of global agent is: " + JSON.stringify(globalAgent); // Prints Output on the browser in response response.write(Output); response.end('ok');}); // Listening to http ServerhttpServer.listen(PORT, ()=>{ console.log("Server is running at port 3000...");}); Run index.js file using the following command: node index.js Output: In Console >> Server is running at port 3000... Agent { _events: [Object: null prototype] { free: [Function (anonymous)], newListener: [Function: maybeEnableKeylog]}, _eventsCount: 2, _maxListeners: undefined, defaultPort: 80, protocol: ‘http:’, options: { path: null }, requests: {}, sockets: {}, freeSockets: {}, keepAliveMsecs: 1000, keepAlive: false, maxSockets: Infinity, maxFreeSockets: 256, scheduling: ‘fifo’, maxTotalSockets: Infinity, totalSocketCount: 0, [Symbol(kCapture)]: false} Now run http://localhost:3000/ in the browser. Output: In Browser Hello Geeksforgeeks..., global agents are: {“_events”:{}, “_eventsCount”:2, “defaultPort”:80, “protocol”:”http:”, “options”:{“path”:null}, “requests”:{}, “sockets”:{}, “freeSockets”:{}, “keepAliveMsecs”:1000, “keepAlive”:false, “maxSockets”:null, “maxFreeSockets”:256, “scheduling”:”fifo”, “maxTotalSockets”:null, “totalSocketCount”:0}ok Reference: https://nodejs.org/api/http.html#http_http_globalagent Node.js-Methods JavaScript Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request How to update Node.js and NPM to next version ? Installation of Node.js on Linux Node.js fs.readFileSync() Method How to install the previous version of node.js and npm ? Node.js fs.writeFile() Method
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Sep, 2020" }, { "code": null, "e": 240, "s": 53, "text": "The http.globalAgent (Added in v0.5.9) property is an inbuilt property of the ‘http’ module which is used as the default for all HTTP client requests. It is the global instance of Agent." }, { "code": null, "e": 523, "s": 240, "text": "An Agent maintains a queue of pending requests for a given host and port, reusing a single socket connection for each until the queue is empty, at which time the socket is either destroyed or put into a pool where it is kept to be used again for requests to the same host and port. " }, { "code": null, "e": 604, "s": 523, "text": "In order to get a response and a proper result, we need to import ‘http’ module." }, { "code": null, "e": 612, "s": 604, "text": "Import:" }, { "code": null, "e": 643, "s": 612, "text": "const http = require('http');\n" }, { "code": null, "e": 651, "s": 643, "text": "Syntax:" }, { "code": null, "e": 669, "s": 651, "text": "http.globalAgent\n" }, { "code": null, "e": 746, "s": 669, "text": "Parameters: This property does not accept any parameters as mentioned above." }, { "code": null, "e": 855, "s": 746, "text": "Return Value<http.Agent>: It is responsible for managing connection persistence and reuses for HTTP clients." }, { "code": null, "e": 934, "s": 855, "text": "The below example illustrates the use of http.globalAgent property in Node.js." }, { "code": null, "e": 965, "s": 934, "text": "Example 1: Filename: index.js" }, { "code": "// Node.js program to demonstrate the // http.globalAgent Method // Importing http modulevar http = require('http');const { globalAgent } = require('http'); const PORT = process.env.PORT || 3000; console.log(globalAgent); // Creating http Servervar httpServer = http.createServer( function(request, response) { console.log(globalAgent); var Output = \"Hello Geeksforgeeks..., \" + \"Output of global agent is: \" + JSON.stringify(globalAgent); // Prints Output on the browser in response response.write(Output); response.end('ok');}); // Listening to http ServerhttpServer.listen(PORT, ()=>{ console.log(\"Server is running at port 3000...\");});", "e": 1633, "s": 965, "text": null }, { "code": null, "e": 1680, "s": 1633, "text": "Run index.js file using the following command:" }, { "code": null, "e": 1695, "s": 1680, "text": "node index.js\n" }, { "code": null, "e": 1703, "s": 1695, "text": "Output:" }, { "code": null, "e": 1714, "s": 1703, "text": "In Console" }, { "code": null, "e": 1751, "s": 1714, "text": ">> Server is running at port 3000..." }, { "code": null, "e": 1795, "s": 1751, "text": "Agent { _events: [Object: null prototype] {" }, { "code": null, "e": 1828, "s": 1795, "text": " free: [Function (anonymous)]," }, { "code": null, "e": 1893, "s": 1828, "text": " newListener: [Function: maybeEnableKeylog]}, _eventsCount: 2," }, { "code": null, "e": 1937, "s": 1893, "text": " _maxListeners: undefined, defaultPort: 80," }, { "code": null, "e": 1982, "s": 1937, "text": " protocol: ‘http:’, options: { path: null }," }, { "code": null, "e": 2010, "s": 1982, "text": " requests: {}, sockets: {}," }, { "code": null, "e": 2050, "s": 2010, "text": " freeSockets: {}, keepAliveMsecs: 1000," }, { "code": null, "e": 2091, "s": 2050, "text": " keepAlive: false, maxSockets: Infinity," }, { "code": null, "e": 2133, "s": 2091, "text": " maxFreeSockets: 256, scheduling: ‘fifo’," }, { "code": null, "e": 2182, "s": 2133, "text": " maxTotalSockets: Infinity, totalSocketCount: 0," }, { "code": null, "e": 2210, "s": 2182, "text": " [Symbol(kCapture)]: false}" }, { "code": null, "e": 2257, "s": 2210, "text": "Now run http://localhost:3000/ in the browser." }, { "code": null, "e": 2276, "s": 2257, "text": "Output: In Browser" }, { "code": null, "e": 2370, "s": 2276, "text": "Hello Geeksforgeeks..., global agents are: {“_events”:{}, “_eventsCount”:2, “defaultPort”:80," }, { "code": null, "e": 2444, "s": 2370, "text": "“protocol”:”http:”, “options”:{“path”:null}, “requests”:{}, “sockets”:{}," }, { "code": null, "e": 2545, "s": 2444, "text": "“freeSockets”:{}, “keepAliveMsecs”:1000, “keepAlive”:false, “maxSockets”:null, “maxFreeSockets”:256," }, { "code": null, "e": 2614, "s": 2545, "text": "“scheduling”:”fifo”, “maxTotalSockets”:null, “totalSocketCount”:0}ok" }, { "code": null, "e": 2680, "s": 2614, "text": "Reference: https://nodejs.org/api/http.html#http_http_globalagent" }, { "code": null, "e": 2696, "s": 2680, "text": "Node.js-Methods" }, { "code": null, "e": 2707, "s": 2696, "text": "JavaScript" }, { "code": null, "e": 2715, "s": 2707, "text": "Node.js" }, { "code": null, "e": 2732, "s": 2715, "text": "Web Technologies" }, { "code": null, "e": 2830, "s": 2732, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2891, "s": 2830, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2963, "s": 2891, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3003, "s": 2963, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3045, "s": 3003, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 3086, "s": 3045, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3134, "s": 3086, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3167, "s": 3134, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3200, "s": 3167, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 3257, "s": 3200, "text": "How to install the previous version of node.js and npm ?" } ]
How to trim a string at beginning or ending in JavaScript ?
13 Dec, 2021 This article demonstrates how to trim a string at the beginning, end, and also from both sides. For various sorts of string trimming, JavaScript provides three functions. TrimLeft(), used to remove characters from the beginning of a string. TrimRight(), used to remove characters from the string’s end. Trim(), used to remove characters from both ends. JavaScript’s native functions, like those of many other languages, solely remove whitespace characters. We will discuss all these functions in detail, & understand them through the examples. Trimming a string at the beginning: In this case, we trim the string at the beginning using the trimLeft() function. JavaScript trimLeft() Function: This method is used to eliminate white space at the beginning of a string. The string’s value is not changed in any way, if any white space is present after the string, it’s not modified. Syntax: string.trimLeft(); Example 1: In this example, a variable var is declared with the string ” geeksforgeeks”. Notice the given string that has whitespace at the left end. The trimLeft() function will remove the whitespace at the beginning. HTML <!DOCTYPE html><html> <head> <title>Javascript trimLeft() Function</title></head> <body> <script> var word = " geeksforgeeks"; console.log("initial string:" + "'" + word + "'"); // Trimming the string at the Beginning var new_word = word.trimLeft(); console.log("modified string:" + "'" + new_word + "'"); </script></body> </html> Output: initial string:' geeksforgeeks' modified string:'geeksforgeeks' Example 2: In this example, a variable var is declared with the string ” geeksforgeeks “. Notice the given string that has whitespace at both ends. trimLeft() will only remove the whitespace at the beginning and leaves the whitespace at the end unchanged. HTML <!DOCTYPE html><html> <head> <title>Javascript trimLeft() Function</title></head> <body> <script> var word = " geeksforgeeks "; console.log("initial string:" + "'" + word + "'"); // Trimming the string at the start var new_word = word.trimLeft(); console.log("modified string:" + "'" + new_word + "'"); </script></body> </html> Output: initial string:' geeksforgeeks ' modified string:'geeksforgeeks ' Trimming the string at the end: In this case, we trim the string at the end using the trimRight() function. JavaScript trimRight() Function: This method is used to eliminate white-space from the end of a string. The string’s value is not changed in any way, if any white space is present before the string, it’s not modified. Syntax: string.trimRight(); Example 1: In this example, a variable var is declared and string “geeksforgeeks ” is given to it. Notice the given string which has whitespace at the right end, so trimRight() removes the whitespace at the end. HTML <!DOCTYPE html><html> <head> <title>Javascript trimRight() Function</title></head> <body> <script> var word = "geeksforgeeks "; console.log("initial string:" + "'" + word + "'"); // Trimming the string at the right end var new_word = word.trimRight(); console.log("modified string:" + "'" + new_word + "'"); </script></body> </html> Output: initial string:'geeksforgeeks ' modified string:'geeksforgeeks' Example 2: In this example, a variable var is declared and string ” geeksforgeeks ” is given to it. Notice the given string that has whitespace at both ends. The trimRight() function removes the whitespace at the end and not at the beginning. HTML <!DOCTYPE html><html> <head> <title>Javascript trimRight() Function</title></head> <body> <script> var word = " geeksforgeeks "; console.log("initial string:" + "'" + word + "'"); // Trimming the string at the right end var new_word = word.trimRight(); console.log("modified string:" + "'" + new_word + "'"); </script></body> </html> Output: initial string:' geeksforgeeks ' modified string:' geeksforgeeks' Trimming the string from both the ends: In this case, we trim the string at both ends using the trim() function. JavaScript trim() Function: Trim() eliminates whitespace from both ends of a string and produces a new string with no changes to the original. All whitespace characters and all line terminator characters are considered whitespace in this context. Syntax: string.trim(); Example: In this example, a variable var is declared and string ” geeksforgeeks ” is given to it. Notice the given string that has whitespace at both ends. The trim() removes the whitespace at both ends. HTML <!DOCTYPE html><html> <head> <title>Javascript trim() Function</title></head> <body> <script> var word = " geeksforgeeks "; console.log("initial string:" + "'" + word + "'"); // Trimming the string at both ends var new_word = word.trim(); console.log("modified string:" + "'" + new_word + "'"); </script></body> </html> Output: initial string:' geeksforgeeks ' modified string:'geeksforgeeks' Supported Browsers: Google Chrome 4.0 Firefox 3.5 Internet Explorer 10.0 Microsoft Edge 12.0 Opera 10.5 Safari 5.0 JavaScript-Methods JavaScript-Questions Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Dec, 2021" }, { "code": null, "e": 572, "s": 28, "text": "This article demonstrates how to trim a string at the beginning, end, and also from both sides. For various sorts of string trimming, JavaScript provides three functions. TrimLeft(), used to remove characters from the beginning of a string. TrimRight(), used to remove characters from the string’s end. Trim(), used to remove characters from both ends. JavaScript’s native functions, like those of many other languages, solely remove whitespace characters. We will discuss all these functions in detail, & understand them through the examples." }, { "code": null, "e": 690, "s": 572, "text": "Trimming a string at the beginning: In this case, we trim the string at the beginning using the trimLeft() function. " }, { "code": null, "e": 910, "s": 690, "text": "JavaScript trimLeft() Function: This method is used to eliminate white space at the beginning of a string. The string’s value is not changed in any way, if any white space is present after the string, it’s not modified." }, { "code": null, "e": 920, "s": 912, "text": "Syntax:" }, { "code": null, "e": 939, "s": 920, "text": "string.trimLeft();" }, { "code": null, "e": 1158, "s": 939, "text": "Example 1: In this example, a variable var is declared with the string ” geeksforgeeks”. Notice the given string that has whitespace at the left end. The trimLeft() function will remove the whitespace at the beginning." }, { "code": null, "e": 1163, "s": 1158, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Javascript trimLeft() Function</title></head> <body> <script> var word = \" geeksforgeeks\"; console.log(\"initial string:\" + \"'\" + word + \"'\"); // Trimming the string at the Beginning var new_word = word.trimLeft(); console.log(\"modified string:\" + \"'\" + new_word + \"'\"); </script></body> </html>", "e": 1528, "s": 1163, "text": null }, { "code": null, "e": 1536, "s": 1528, "text": "Output:" }, { "code": null, "e": 1600, "s": 1536, "text": "initial string:' geeksforgeeks'\nmodified string:'geeksforgeeks'" }, { "code": null, "e": 1856, "s": 1600, "text": "Example 2: In this example, a variable var is declared with the string ” geeksforgeeks “. Notice the given string that has whitespace at both ends. trimLeft() will only remove the whitespace at the beginning and leaves the whitespace at the end unchanged." }, { "code": null, "e": 1861, "s": 1856, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Javascript trimLeft() Function</title></head> <body> <script> var word = \" geeksforgeeks \"; console.log(\"initial string:\" + \"'\" + word + \"'\"); // Trimming the string at the start var new_word = word.trimLeft(); console.log(\"modified string:\" + \"'\" + new_word + \"'\"); </script></body> </html>", "e": 2222, "s": 1861, "text": null }, { "code": null, "e": 2230, "s": 2222, "text": "Output:" }, { "code": null, "e": 2296, "s": 2230, "text": "initial string:' geeksforgeeks '\nmodified string:'geeksforgeeks '" }, { "code": null, "e": 2404, "s": 2296, "text": "Trimming the string at the end: In this case, we trim the string at the end using the trimRight() function." }, { "code": null, "e": 2622, "s": 2404, "text": "JavaScript trimRight() Function: This method is used to eliminate white-space from the end of a string. The string’s value is not changed in any way, if any white space is present before the string, it’s not modified." }, { "code": null, "e": 2630, "s": 2622, "text": "Syntax:" }, { "code": null, "e": 2650, "s": 2630, "text": "string.trimRight();" }, { "code": null, "e": 2862, "s": 2650, "text": "Example 1: In this example, a variable var is declared and string “geeksforgeeks ” is given to it. Notice the given string which has whitespace at the right end, so trimRight() removes the whitespace at the end." }, { "code": null, "e": 2867, "s": 2862, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Javascript trimRight() Function</title></head> <body> <script> var word = \"geeksforgeeks \"; console.log(\"initial string:\" + \"'\" + word + \"'\"); // Trimming the string at the right end var new_word = word.trimRight(); console.log(\"modified string:\" + \"'\" + new_word + \"'\"); </script></body> </html>", "e": 3233, "s": 2867, "text": null }, { "code": null, "e": 3241, "s": 3233, "text": "Output:" }, { "code": null, "e": 3305, "s": 3241, "text": "initial string:'geeksforgeeks '\nmodified string:'geeksforgeeks'" }, { "code": null, "e": 3548, "s": 3305, "text": "Example 2: In this example, a variable var is declared and string ” geeksforgeeks ” is given to it. Notice the given string that has whitespace at both ends. The trimRight() function removes the whitespace at the end and not at the beginning." }, { "code": null, "e": 3553, "s": 3548, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Javascript trimRight() Function</title></head> <body> <script> var word = \" geeksforgeeks \"; console.log(\"initial string:\" + \"'\" + word + \"'\"); // Trimming the string at the right end var new_word = word.trimRight(); console.log(\"modified string:\" + \"'\" + new_word + \"'\"); </script></body> </html>", "e": 3920, "s": 3553, "text": null }, { "code": null, "e": 3928, "s": 3920, "text": "Output:" }, { "code": null, "e": 3994, "s": 3928, "text": "initial string:' geeksforgeeks '\nmodified string:' geeksforgeeks'" }, { "code": null, "e": 4107, "s": 3994, "text": "Trimming the string from both the ends: In this case, we trim the string at both ends using the trim() function." }, { "code": null, "e": 4354, "s": 4107, "text": "JavaScript trim() Function: Trim() eliminates whitespace from both ends of a string and produces a new string with no changes to the original. All whitespace characters and all line terminator characters are considered whitespace in this context." }, { "code": null, "e": 4362, "s": 4354, "text": "Syntax:" }, { "code": null, "e": 4377, "s": 4362, "text": "string.trim();" }, { "code": null, "e": 4582, "s": 4377, "text": "Example: In this example, a variable var is declared and string ” geeksforgeeks ” is given to it. Notice the given string that has whitespace at both ends. The trim() removes the whitespace at both ends. " }, { "code": null, "e": 4587, "s": 4582, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>Javascript trim() Function</title></head> <body> <script> var word = \" geeksforgeeks \"; console.log(\"initial string:\" + \"'\" + word + \"'\"); // Trimming the string at both ends var new_word = word.trim(); console.log(\"modified string:\" + \"'\" + new_word + \"'\"); </script></body> </html>", "e": 4940, "s": 4587, "text": null }, { "code": null, "e": 4948, "s": 4940, "text": "Output:" }, { "code": null, "e": 5013, "s": 4948, "text": "initial string:' geeksforgeeks '\nmodified string:'geeksforgeeks'" }, { "code": null, "e": 5033, "s": 5013, "text": "Supported Browsers:" }, { "code": null, "e": 5051, "s": 5033, "text": "Google Chrome 4.0" }, { "code": null, "e": 5063, "s": 5051, "text": "Firefox 3.5" }, { "code": null, "e": 5086, "s": 5063, "text": "Internet Explorer 10.0" }, { "code": null, "e": 5106, "s": 5086, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 5117, "s": 5106, "text": "Opera 10.5" }, { "code": null, "e": 5128, "s": 5117, "text": "Safari 5.0" }, { "code": null, "e": 5147, "s": 5128, "text": "JavaScript-Methods" }, { "code": null, "e": 5168, "s": 5147, "text": "JavaScript-Questions" }, { "code": null, "e": 5175, "s": 5168, "text": "Picked" }, { "code": null, "e": 5186, "s": 5175, "text": "JavaScript" }, { "code": null, "e": 5203, "s": 5186, "text": "Web Technologies" }, { "code": null, "e": 5301, "s": 5203, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5362, "s": 5301, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5402, "s": 5362, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5444, "s": 5402, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 5485, "s": 5444, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5507, "s": 5485, "text": "JavaScript | Promises" }, { "code": null, "e": 5540, "s": 5507, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 5602, "s": 5540, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5663, "s": 5602, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5713, "s": 5663, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
zip() in Python
30 Sep, 2021 Python zip() method takes iterable or containers and returns a single iterator object, having mapped values from all the containers. It is used to map the similar index of multiple containers so that they can be used just using a single entity. Syntax : zip(*iterators) Parameters : Python iterables or containers ( list, string etc ) Return Value : Returns a single iterator object, having mapped values from all the containers. Python3 name = [ "Manjeet", "Nikhil", "Shambhavi", "Astha" ]roll_no = [ 4, 1, 3, 2 ] # using zip() to map valuesmapped = zip(name, roll_no) print(set(mapped)) Output: {('Shambhavi', 3), ('Nikhil', 1), ('Astha', 2), ('Manjeet', 4)} Python3 names = ['Mukesh', 'Roni', 'Chari']ages = [24, 50, 18] for i, (name, age) in enumerate(zip(names, ages)): print(i, name, age) Output: 0 Mukesh 24 1 Roni 50 2 Chari 18 Python3 stocks = ['reliance', 'infosys', 'tcs']prices = [2175, 1127, 2750] new_dict = {stocks: prices for stocks, prices in zip(stocks, prices)}print(new_dict) Output: {'reliance': 2175, 'infosys': 1127, 'tcs': 2750} Unzipping means converting the zipped values back to the individual self as they were. This is done with the help of “*” operator. Python3 # Python code to demonstrate the working of# unzip # initializing listsname = ["Manjeet", "Nikhil", "Shambhavi", "Astha"]roll_no = [4, 1, 3, 2]marks = [40, 50, 60, 70] # using zip() to map valuesmapped = zip(name, roll_no, marks) # converting values to print as listmapped = list(mapped) # printing resultant valuesprint("The zipped result is : ", end="")print(mapped) print("\n") # unzipping valuesnamz, roll_noz, marksz = zip(*mapped) print("The unzipped result: \n", end="") # printing initial listsprint("The name list is : ", end="")print(namz) print("The roll_no list is : ", end="")print(roll_noz) print("The marks list is : ", end="")print(marksz) Output: The zipped result is : [('Manjeet', 4, 40), ('Nikhil', 1, 50), ('Shambhavi', 3, 60), ('Astha', 2, 70)] The unzipped result: The name list is : ('Manjeet', 'Nikhil', 'Shambhavi', 'Astha') The roll_no list is : (4, 1, 3, 2) The marks list is : (40, 50, 60, 70) There are many possible applications that can be said to be executed using zip, be it student database or scorecard or any other utility that requires mapping of groups. A small example of scorecard is demonstrated below. Python3 # Python code to demonstrate the application of# zip() # initializing list of players.players = ["Sachin", "Sehwag", "Gambhir", "Dravid", "Raina"] # initializing their scoresscores = [100, 15, 17, 28, 43] # printing players and scores.for pl, sc in zip(players, scores): print("Player : %s Score : %d" % (pl, sc)) Output: Player : Sachin Score : 100 Player : Sehwag Score : 15 Player : Gambhir Score : 17 Player : Dravid Score : 28 Player : Raina Score : 43 varshagumber28 kumar_satyam Python-Built-in-functions python-list python-list-functions Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe 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 Python OOPs Concepts Convert integer to string in Python Introduction To PYTHON
[ { "code": null, "e": 53, "s": 25, "text": "\n30 Sep, 2021" }, { "code": null, "e": 187, "s": 53, "text": "Python zip() method takes iterable or containers and returns a single iterator object, having mapped values from all the containers. " }, { "code": null, "e": 300, "s": 187, "text": "It is used to map the similar index of multiple containers so that they can be used just using a single entity. " }, { "code": null, "e": 327, "s": 300, "text": "Syntax : zip(*iterators) " }, { "code": null, "e": 487, "s": 327, "text": "Parameters : Python iterables or containers ( list, string etc ) Return Value : Returns a single iterator object, having mapped values from all the containers." }, { "code": null, "e": 495, "s": 487, "text": "Python3" }, { "code": "name = [ \"Manjeet\", \"Nikhil\", \"Shambhavi\", \"Astha\" ]roll_no = [ 4, 1, 3, 2 ] # using zip() to map valuesmapped = zip(name, roll_no) print(set(mapped))", "e": 646, "s": 495, "text": null }, { "code": null, "e": 654, "s": 646, "text": "Output:" }, { "code": null, "e": 718, "s": 654, "text": "{('Shambhavi', 3), ('Nikhil', 1), ('Astha', 2), ('Manjeet', 4)}" }, { "code": null, "e": 726, "s": 718, "text": "Python3" }, { "code": "names = ['Mukesh', 'Roni', 'Chari']ages = [24, 50, 18] for i, (name, age) in enumerate(zip(names, ages)): print(i, name, age)", "e": 855, "s": 726, "text": null }, { "code": null, "e": 863, "s": 855, "text": "Output:" }, { "code": null, "e": 896, "s": 863, "text": "0 Mukesh 24\n1 Roni 50\n2 Chari 18" }, { "code": null, "e": 904, "s": 896, "text": "Python3" }, { "code": "stocks = ['reliance', 'infosys', 'tcs']prices = [2175, 1127, 2750] new_dict = {stocks: prices for stocks, prices in zip(stocks, prices)}print(new_dict)", "e": 1067, "s": 904, "text": null }, { "code": null, "e": 1075, "s": 1067, "text": "Output:" }, { "code": null, "e": 1124, "s": 1075, "text": "{'reliance': 2175, 'infosys': 1127, 'tcs': 2750}" }, { "code": null, "e": 1255, "s": 1124, "text": "Unzipping means converting the zipped values back to the individual self as they were. This is done with the help of “*” operator." }, { "code": null, "e": 1263, "s": 1255, "text": "Python3" }, { "code": "# Python code to demonstrate the working of# unzip # initializing listsname = [\"Manjeet\", \"Nikhil\", \"Shambhavi\", \"Astha\"]roll_no = [4, 1, 3, 2]marks = [40, 50, 60, 70] # using zip() to map valuesmapped = zip(name, roll_no, marks) # converting values to print as listmapped = list(mapped) # printing resultant valuesprint(\"The zipped result is : \", end=\"\")print(mapped) print(\"\\n\") # unzipping valuesnamz, roll_noz, marksz = zip(*mapped) print(\"The unzipped result: \\n\", end=\"\") # printing initial listsprint(\"The name list is : \", end=\"\")print(namz) print(\"The roll_no list is : \", end=\"\")print(roll_noz) print(\"The marks list is : \", end=\"\")print(marksz)", "e": 1919, "s": 1263, "text": null }, { "code": null, "e": 1928, "s": 1919, "text": "Output: " }, { "code": null, "e": 2191, "s": 1928, "text": "The zipped result is : [('Manjeet', 4, 40), ('Nikhil', 1, 50), \n('Shambhavi', 3, 60), ('Astha', 2, 70)]\n\n\nThe unzipped result: \nThe name list is : ('Manjeet', 'Nikhil', 'Shambhavi', 'Astha')\nThe roll_no list is : (4, 1, 3, 2)\nThe marks list is : (40, 50, 60, 70)" }, { "code": null, "e": 2414, "s": 2191, "text": "There are many possible applications that can be said to be executed using zip, be it student database or scorecard or any other utility that requires mapping of groups. A small example of scorecard is demonstrated below. " }, { "code": null, "e": 2422, "s": 2414, "text": "Python3" }, { "code": "# Python code to demonstrate the application of# zip() # initializing list of players.players = [\"Sachin\", \"Sehwag\", \"Gambhir\", \"Dravid\", \"Raina\"] # initializing their scoresscores = [100, 15, 17, 28, 43] # printing players and scores.for pl, sc in zip(players, scores): print(\"Player : %s Score : %d\" % (pl, sc))", "e": 2744, "s": 2422, "text": null }, { "code": null, "e": 2753, "s": 2744, "text": "Output: " }, { "code": null, "e": 2914, "s": 2753, "text": "Player : Sachin Score : 100\nPlayer : Sehwag Score : 15\nPlayer : Gambhir Score : 17\nPlayer : Dravid Score : 28\nPlayer : Raina Score : 43" }, { "code": null, "e": 2929, "s": 2914, "text": "varshagumber28" }, { "code": null, "e": 2942, "s": 2929, "text": "kumar_satyam" }, { "code": null, "e": 2968, "s": 2942, "text": "Python-Built-in-functions" }, { "code": null, "e": 2980, "s": 2968, "text": "python-list" }, { "code": null, "e": 3002, "s": 2980, "text": "python-list-functions" }, { "code": null, "e": 3009, "s": 3002, "text": "Python" }, { "code": null, "e": 3021, "s": 3009, "text": "python-list" }, { "code": null, "e": 3119, "s": 3021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3137, "s": 3119, "text": "Python Dictionary" }, { "code": null, "e": 3179, "s": 3137, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3214, "s": 3179, "text": "Read a file line by line in Python" }, { "code": null, "e": 3240, "s": 3214, "text": "Python String | replace()" }, { "code": null, "e": 3272, "s": 3240, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3301, "s": 3272, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3328, "s": 3301, "text": "Python Classes and Objects" }, { "code": null, "e": 3349, "s": 3328, "text": "Python OOPs Concepts" }, { "code": null, "e": 3385, "s": 3349, "text": "Convert integer to string in Python" } ]
How to get nth occurrence of a string in JavaScript ?
02 Jun, 2020 The task is to get the nth occurrence of a substring in a string with the help of JavaScript. Approach 1: First, split the string into sub-strings using split() method by passing index also. Again join the substrings on passed substring using join() method. Returns the index of nth occurrence of string. Example:In this example, split() and join() method are used to get the index of substring. <!DOCTYPE HTML> <html> <head> <title> How to get nth occurrence of a string in JavaScript ? </title></head> <body style = "text-align:center;"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var string = "Geeks gfg Geeks Geek Geeks gfg"; var searchString = 'Geeks'; var occurrence = 3; el_up.innerHTML = "Click on the button to get the index of " + occurrence + "rd occurrence of a '" + searchString + "' in a <br>'" + string + "'."; function getPos(str, subStr, i) { return str.split(subStr, i).join(subStr).length; } function GFG_Fun() { el_down.innerHTML = getPos(string, searchString, occurrence); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: Approach 2: Go through each substring one by one and return the index of the last substring. This approach uses indexOf() method to return the index of nth occurrence of the string. Example: <!DOCTYPE HTML> <html> <head> <title> How to get nth occurrence of a string in JavaScript ? </title></head> <body style = "text-align:center;" id = "body"> <h1 style = "color:green;" > GeeksForGeeks </h1> <p id = "GFG_UP" style = "font-size: 19px; font-weight: bold;"> </p> <button onclick = "GFG_Fun()"> click here </button> <p id = "GFG_DOWN" style = "color: green; font-size: 24px; font-weight: bold;"> </p> <script> var el_up = document.getElementById("GFG_UP"); var el_down = document.getElementById("GFG_DOWN"); var string = "Geeks gfg Geeks Geek Geeks gfg"; var searchString = 'Geeks'; var occurrence = 3; el_up.innerHTML = "Click on the button to get the index of " + occurrence + "rd occurrence of a '" + searchString + "' in a <br>'" + string + "'."; function getIndex(str, substr, ind) { var Len = str.length, i = -1; while(ind-- && i++ < Len) { i = str.indexOf(substr, i); if (i < 0) break; } return i; } function GFG_Fun() { el_down.innerHTML = getIndex(string, searchString, occurrence); } </script> </body> </html> Output: Before clicking on the button: After clicking on the button: nidhi_biet Akanksha_Rai javascript-string JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array How to append HTML code to a div using JavaScript ? Difference Between PUT and PATCH Request Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jun, 2020" }, { "code": null, "e": 122, "s": 28, "text": "The task is to get the nth occurrence of a substring in a string with the help of JavaScript." }, { "code": null, "e": 134, "s": 122, "text": "Approach 1:" }, { "code": null, "e": 219, "s": 134, "text": "First, split the string into sub-strings using split() method by passing index also." }, { "code": null, "e": 286, "s": 219, "text": "Again join the substrings on passed substring using join() method." }, { "code": null, "e": 333, "s": 286, "text": "Returns the index of nth occurrence of string." }, { "code": null, "e": 424, "s": 333, "text": "Example:In this example, split() and join() method are used to get the index of substring." }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to get nth occurrence of a string in JavaScript ? </title></head> <body style = \"text-align:center;\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var string = \"Geeks gfg Geeks Geek Geeks gfg\"; var searchString = 'Geeks'; var occurrence = 3; el_up.innerHTML = \"Click on the button to get the index of \" + occurrence + \"rd occurrence of a '\" + searchString + \"' in a <br>'\" + string + \"'.\"; function getPos(str, subStr, i) { return str.split(subStr, i).join(subStr).length; } function GFG_Fun() { el_down.innerHTML = getPos(string, searchString, occurrence); } </script> </body> </html>", "e": 1649, "s": 424, "text": null }, { "code": null, "e": 1657, "s": 1649, "text": "Output:" }, { "code": null, "e": 1688, "s": 1657, "text": "Before clicking on the button:" }, { "code": null, "e": 1718, "s": 1688, "text": "After clicking on the button:" }, { "code": null, "e": 1900, "s": 1718, "text": "Approach 2: Go through each substring one by one and return the index of the last substring. This approach uses indexOf() method to return the index of nth occurrence of the string." }, { "code": null, "e": 1909, "s": 1900, "text": "Example:" }, { "code": "<!DOCTYPE HTML> <html> <head> <title> How to get nth occurrence of a string in JavaScript ? </title></head> <body style = \"text-align:center;\" id = \"body\"> <h1 style = \"color:green;\" > GeeksForGeeks </h1> <p id = \"GFG_UP\" style = \"font-size: 19px; font-weight: bold;\"> </p> <button onclick = \"GFG_Fun()\"> click here </button> <p id = \"GFG_DOWN\" style = \"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var el_up = document.getElementById(\"GFG_UP\"); var el_down = document.getElementById(\"GFG_DOWN\"); var string = \"Geeks gfg Geeks Geek Geeks gfg\"; var searchString = 'Geeks'; var occurrence = 3; el_up.innerHTML = \"Click on the button to get the index of \" + occurrence + \"rd occurrence of a '\" + searchString + \"' in a <br>'\" + string + \"'.\"; function getIndex(str, substr, ind) { var Len = str.length, i = -1; while(ind-- && i++ < Len) { i = str.indexOf(substr, i); if (i < 0) break; } return i; } function GFG_Fun() { el_down.innerHTML = getIndex(string, searchString, occurrence); } </script> </body> </html>", "e": 3282, "s": 1909, "text": null }, { "code": null, "e": 3290, "s": 3282, "text": "Output:" }, { "code": null, "e": 3321, "s": 3290, "text": "Before clicking on the button:" }, { "code": null, "e": 3351, "s": 3321, "text": "After clicking on the button:" }, { "code": null, "e": 3362, "s": 3351, "text": "nidhi_biet" }, { "code": null, "e": 3375, "s": 3362, "text": "Akanksha_Rai" }, { "code": null, "e": 3393, "s": 3375, "text": "javascript-string" }, { "code": null, "e": 3404, "s": 3393, "text": "JavaScript" }, { "code": null, "e": 3421, "s": 3404, "text": "Web Technologies" }, { "code": null, "e": 3448, "s": 3421, "text": "Web technologies Questions" }, { "code": null, "e": 3546, "s": 3448, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3607, "s": 3546, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3679, "s": 3607, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 3719, "s": 3679, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 3771, "s": 3719, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 3812, "s": 3771, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 3874, "s": 3812, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3907, "s": 3874, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3968, "s": 3907, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4018, "s": 3968, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Getting started with giotto-tda. A Python library for topological... | by Lewis Tunstall | Towards Data Science
Written by Lewis Tunstall, Colin Kälin, Francesco Palma, and Thomas Boys At L2F, one of the most common questions we get around giotto-tda and topological machine learning is “Where do I start?”. In this guide we present an overview of the basic concepts and workflow so that you can start using giotto-tda in your machine learning pipelines. The code to reproduce the analysis is available on GitHub. Topological machine learning refers to a set of techniques that combine elements from algebraic topology with statistical learning. By focusing on global properties of data such as shape and connectivity, these topological methods can capture patterns that may be missed by conventional machine learning approaches. For example, topological machine learning has produced state-of-the-art results in drug design and graph classification, and led to novel insights in protein binding. The main ingredient underlying these techniques is known as persistent homology. Persistent homology measures the presence of topological invariants like connected components, holes, and voids across varying length scales. The “birth” and “death” of these invariants is summarised via a persistence diagram, which is the most common and intuitive way to generate new types of features to feed to downstream machine learning tasks. For an excellent overview of these concepts, see Gary Koplik’s article or Matthew Wright’s video. To summarise, the key steps in topological machine learning are: Extract topological features from the input data using persistent homology. Combine these features with machine learning methods, using either supervised or unsupervised approaches. The giotto-tda library is designed to simplify these steps and make topological machine learning accessible to the wider data science community. It is based on the fit-transform paradigm of scikit-learn and provides tight integration with the popular framework. Getting started with giotto-tda is as simple as running: pip install giotto-tda To show giotto-tda in action, we will use the CHAMPS dataset from the Predicting Molecular Properties competition on Kaggle. Here the task is to predict the magnetic interaction or “scalar coupling constant” between two atoms in a molecule. Since these couplings take continuous values, the learning task is a regression one. The training data consists of atom-pairs in molecules, with each pair characterised by the type of scalar coupling and the (x,y,z) coordinates of each atom. To simplify the analysis, we’ll focus on the 100 largest molecules, i.e. those with the largest number of atoms. As shown in the figure below, these molecules have five different couplings, whose strength varies depending on the type of coupling. The first step in our topological machine learning pipeline is to construct persistence diagrams from the training data. In giotto-tda, there are two main ways to achieve this: Represent the data as a point cloud: treat each observation as a point in space, along with a metric to calculate distances between pairs of observations. In our context, the point cloud for a single molecule could simply be the (x, y, z) coordinates of each atom relative to the mean value (x̅, y̅, z̅) of all the atoms. In the code snippet below, homology_dimensions specifies the type of topological invariants to track (“0” for connected components, “1” for holes, and “2” for voids), while euclidean defines the metric we wish to apply in the persistent homology calculation. Represent the data as a distance matrix: calculate the pairwise distances between each observation, where “distance” does not necessarily have to be a metric. If we treat a single molecule as a graph, the distance between two atoms could be the number of edges along a shortest path connecting them. In the code snippet below, we simply need to specify that our metric is precomputed and ensure the input is a distance matrix. For each input point cloud or distance matrix, we get a single persistence diagram. In the training data, each observation is an atom-pair, so when these pairs are grouped to form the 100 molecules, we obtain 100 point clouds and thus 100 persistence diagrams. Points in the persistence diagram which are furthest away from the diagonal death = birth line correspond to the most persistent topological features. Although persistence diagrams are useful descriptors of the data, they cannot be used directly for machine learning applications. This is because different persistence diagrams may have different numbers of points, and basic operations like the addition and multiplication of diagrams are not well-defined. To overcome these limitations, a variety of proposals have been made to “vectorise” persistence diagrams via embeddings or kernels which are well-suited for machine learning. In giotto-tda, we provide access to the most common vectorisations via the gtda.diagrams module. For example, calculating the “amplitude” of a persistence diagram can be achieved by selecting a metric as shown in the following code snippet. Alternatively, you can create custom topological features of your own! Since persistence diagrams in giotto-tda are arrays of birth-death-dimension triples, it is straightforward to manipulate them with NumPy or Pandas. For example, the code snippet below shows how we can calculate the average lifetime of the points per homology_dimension. In our full analysis of the CHAMPS dataset we extracted a wide variety of topological features — see the accompanying code for details. With topological features at hand, the next step is to train a regressor. In the scikit-learn conventions, this amounts to combining all relevant features and the target variable into arrays X and y. For this guide, we adopt the approach taken in this Kaggle submission and use an XGBoostRegressor to make predictions. In order to evaluate the influence of the features on performance, we compare the results of a model trained with 5-fold cross-validation, both with and without topological features. The code snippet for this step is standard and reproduced below. The final step is to score the predictions from our models. The metric for the competition is the mean of the logarithm of the mean absolute error (yes, it’s a bit complicated — just think of it as multiple scores, one for each bond type. For each type calculate the mean absolute error, take the log of these results and in the end calculate the mean over all bond types): Here: T is the number of scalar coupling types (in our case five) nj is the number of observations of type j yi is the scalar coupling constant for the observation ŷi is the predicted scalar coupling constant Due to the logarithm we can get negative values, and thus a score of say -0.5 is better than a score of -0.3. The figure below shows the scores per coupling type and compares the model that includes topological features against those without. We can clearly see that the topological features help improve the score by up to 5.5%, and by 3.6% on average. In a Kaggle competition, these small improvements can make a big difference in the final leaderboard and provide a nice demonstration of how topology can provide complementary information to conventional feature extraction methods. This guide only scratches the surface of what is possible with giotto-tda. In addition to core machine learning tasks like our regression example, the library currently supports the application of persistent homology to graph and time series data. For example, giotto-tda has been used to detect stock market crashes, study the population dynamics of beetle populations, or predict whether a molecule inhibits the spreading of HIV. If you have questions on how to use giotto-tda, feel free to reach out to us on Slack. If you would like to learn more about topological machine learning, please consult the links below. Update 23/01/2020: The giotto-learn library has been renamed to giotto-tda! While the new name is meant to better convey the library's focus on topological machine learning, the commitment to seamless integration with scikit-learn will remain just as strong and a defining feature of the project. An introduction to topological data analysis: fundamental and practical aspects for data scientists Persistent-homology-based machine learning and its applications — a survey
[ { "code": null, "e": 245, "s": 171, "text": "Written by Lewis Tunstall, Colin Kälin, Francesco Palma, and Thomas Boys" }, { "code": null, "e": 368, "s": 245, "text": "At L2F, one of the most common questions we get around giotto-tda and topological machine learning is “Where do I start?”." }, { "code": null, "e": 574, "s": 368, "text": "In this guide we present an overview of the basic concepts and workflow so that you can start using giotto-tda in your machine learning pipelines. The code to reproduce the analysis is available on GitHub." }, { "code": null, "e": 890, "s": 574, "text": "Topological machine learning refers to a set of techniques that combine elements from algebraic topology with statistical learning. By focusing on global properties of data such as shape and connectivity, these topological methods can capture patterns that may be missed by conventional machine learning approaches." }, { "code": null, "e": 1057, "s": 890, "text": "For example, topological machine learning has produced state-of-the-art results in drug design and graph classification, and led to novel insights in protein binding." }, { "code": null, "e": 1586, "s": 1057, "text": "The main ingredient underlying these techniques is known as persistent homology. Persistent homology measures the presence of topological invariants like connected components, holes, and voids across varying length scales. The “birth” and “death” of these invariants is summarised via a persistence diagram, which is the most common and intuitive way to generate new types of features to feed to downstream machine learning tasks. For an excellent overview of these concepts, see Gary Koplik’s article or Matthew Wright’s video." }, { "code": null, "e": 1651, "s": 1586, "text": "To summarise, the key steps in topological machine learning are:" }, { "code": null, "e": 1727, "s": 1651, "text": "Extract topological features from the input data using persistent homology." }, { "code": null, "e": 1833, "s": 1727, "text": "Combine these features with machine learning methods, using either supervised or unsupervised approaches." }, { "code": null, "e": 2152, "s": 1833, "text": "The giotto-tda library is designed to simplify these steps and make topological machine learning accessible to the wider data science community. It is based on the fit-transform paradigm of scikit-learn and provides tight integration with the popular framework. Getting started with giotto-tda is as simple as running:" }, { "code": null, "e": 2175, "s": 2152, "text": "pip install giotto-tda" }, { "code": null, "e": 2501, "s": 2175, "text": "To show giotto-tda in action, we will use the CHAMPS dataset from the Predicting Molecular Properties competition on Kaggle. Here the task is to predict the magnetic interaction or “scalar coupling constant” between two atoms in a molecule. Since these couplings take continuous values, the learning task is a regression one." }, { "code": null, "e": 2905, "s": 2501, "text": "The training data consists of atom-pairs in molecules, with each pair characterised by the type of scalar coupling and the (x,y,z) coordinates of each atom. To simplify the analysis, we’ll focus on the 100 largest molecules, i.e. those with the largest number of atoms. As shown in the figure below, these molecules have five different couplings, whose strength varies depending on the type of coupling." }, { "code": null, "e": 3026, "s": 2905, "text": "The first step in our topological machine learning pipeline is to construct persistence diagrams from the training data." }, { "code": null, "e": 3082, "s": 3026, "text": "In giotto-tda, there are two main ways to achieve this:" }, { "code": null, "e": 3663, "s": 3082, "text": "Represent the data as a point cloud: treat each observation as a point in space, along with a metric to calculate distances between pairs of observations. In our context, the point cloud for a single molecule could simply be the (x, y, z) coordinates of each atom relative to the mean value (x̅, y̅, z̅) of all the atoms. In the code snippet below, homology_dimensions specifies the type of topological invariants to track (“0” for connected components, “1” for holes, and “2” for voids), while euclidean defines the metric we wish to apply in the persistent homology calculation." }, { "code": null, "e": 4090, "s": 3663, "text": "Represent the data as a distance matrix: calculate the pairwise distances between each observation, where “distance” does not necessarily have to be a metric. If we treat a single molecule as a graph, the distance between two atoms could be the number of edges along a shortest path connecting them. In the code snippet below, we simply need to specify that our metric is precomputed and ensure the input is a distance matrix." }, { "code": null, "e": 4351, "s": 4090, "text": "For each input point cloud or distance matrix, we get a single persistence diagram. In the training data, each observation is an atom-pair, so when these pairs are grouped to form the 100 molecules, we obtain 100 point clouds and thus 100 persistence diagrams." }, { "code": null, "e": 4502, "s": 4351, "text": "Points in the persistence diagram which are furthest away from the diagonal death = birth line correspond to the most persistent topological features." }, { "code": null, "e": 4809, "s": 4502, "text": "Although persistence diagrams are useful descriptors of the data, they cannot be used directly for machine learning applications. This is because different persistence diagrams may have different numbers of points, and basic operations like the addition and multiplication of diagrams are not well-defined." }, { "code": null, "e": 5081, "s": 4809, "text": "To overcome these limitations, a variety of proposals have been made to “vectorise” persistence diagrams via embeddings or kernels which are well-suited for machine learning. In giotto-tda, we provide access to the most common vectorisations via the gtda.diagrams module." }, { "code": null, "e": 5225, "s": 5081, "text": "For example, calculating the “amplitude” of a persistence diagram can be achieved by selecting a metric as shown in the following code snippet." }, { "code": null, "e": 5567, "s": 5225, "text": "Alternatively, you can create custom topological features of your own! Since persistence diagrams in giotto-tda are arrays of birth-death-dimension triples, it is straightforward to manipulate them with NumPy or Pandas. For example, the code snippet below shows how we can calculate the average lifetime of the points per homology_dimension." }, { "code": null, "e": 5703, "s": 5567, "text": "In our full analysis of the CHAMPS dataset we extracted a wide variety of topological features — see the accompanying code for details." }, { "code": null, "e": 6270, "s": 5703, "text": "With topological features at hand, the next step is to train a regressor. In the scikit-learn conventions, this amounts to combining all relevant features and the target variable into arrays X and y. For this guide, we adopt the approach taken in this Kaggle submission and use an XGBoostRegressor to make predictions. In order to evaluate the influence of the features on performance, we compare the results of a model trained with 5-fold cross-validation, both with and without topological features. The code snippet for this step is standard and reproduced below." }, { "code": null, "e": 6644, "s": 6270, "text": "The final step is to score the predictions from our models. The metric for the competition is the mean of the logarithm of the mean absolute error (yes, it’s a bit complicated — just think of it as multiple scores, one for each bond type. For each type calculate the mean absolute error, take the log of these results and in the end calculate the mean over all bond types):" }, { "code": null, "e": 6650, "s": 6644, "text": "Here:" }, { "code": null, "e": 6710, "s": 6650, "text": "T is the number of scalar coupling types (in our case five)" }, { "code": null, "e": 6753, "s": 6710, "text": "nj is the number of observations of type j" }, { "code": null, "e": 6808, "s": 6753, "text": "yi is the scalar coupling constant for the observation" }, { "code": null, "e": 6854, "s": 6808, "text": "ŷi is the predicted scalar coupling constant" }, { "code": null, "e": 6964, "s": 6854, "text": "Due to the logarithm we can get negative values, and thus a score of say -0.5 is better than a score of -0.3." }, { "code": null, "e": 7097, "s": 6964, "text": "The figure below shows the scores per coupling type and compares the model that includes topological features against those without." }, { "code": null, "e": 7440, "s": 7097, "text": "We can clearly see that the topological features help improve the score by up to 5.5%, and by 3.6% on average. In a Kaggle competition, these small improvements can make a big difference in the final leaderboard and provide a nice demonstration of how topology can provide complementary information to conventional feature extraction methods." }, { "code": null, "e": 7688, "s": 7440, "text": "This guide only scratches the surface of what is possible with giotto-tda. In addition to core machine learning tasks like our regression example, the library currently supports the application of persistent homology to graph and time series data." }, { "code": null, "e": 7872, "s": 7688, "text": "For example, giotto-tda has been used to detect stock market crashes, study the population dynamics of beetle populations, or predict whether a molecule inhibits the spreading of HIV." }, { "code": null, "e": 7959, "s": 7872, "text": "If you have questions on how to use giotto-tda, feel free to reach out to us on Slack." }, { "code": null, "e": 8059, "s": 7959, "text": "If you would like to learn more about topological machine learning, please consult the links below." }, { "code": null, "e": 8356, "s": 8059, "text": "Update 23/01/2020: The giotto-learn library has been renamed to giotto-tda! While the new name is meant to better convey the library's focus on topological machine learning, the commitment to seamless integration with scikit-learn will remain just as strong and a defining feature of the project." }, { "code": null, "e": 8456, "s": 8356, "text": "An introduction to topological data analysis: fundamental and practical aspects for data scientists" } ]
Node.js - RESTful API
REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol. It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST was first introduced by Roy Fielding in 2000. A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol. Here each resource is identified by URIs/ global IDs. REST uses various representation to represent a resource like text, JSON, XML but JSON is the most popular one. Following four HTTP methods are commonly used in REST based architecture. GET − This is used to provide a read only access to a resource. GET − This is used to provide a read only access to a resource. PUT − This is used to create a new resource. PUT − This is used to create a new resource. DELETE − This is used to remove a resource. DELETE − This is used to remove a resource. POST − This is used to update a existing resource or create a new resource. POST − This is used to update a existing resource or create a new resource. A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., communication between Java and Python, or Windows and Linux applications) is due to the use of open standards. Web services based on REST Architecture are known as RESTful web services. These webservices uses HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, which provides resource representation such as JSON and set of HTTP Methods. Consider we have a JSON based database of users having the following users in a file users.json: { "user1" : { "name" : "mahesh", "password" : "password1", "profession" : "teacher", "id": 1 }, "user2" : { "name" : "suresh", "password" : "password2", "profession" : "librarian", "id": 2 }, "user3" : { "name" : "ramesh", "password" : "password3", "profession" : "clerk", "id": 3 } } Based on this information we are going to provide following RESTful APIs. I'm keeping most of the part of all the examples in the form of hard coding assuming you already know how to pass values from front end using Ajax or simple form data and how to process them using express Request object. Let's implement our first RESTful API listUsers using the following code in a server.js file − server.js var express = require('express'); var app = express(); var fs = require("fs"); app.get('/listUsers', function (req, res) { fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { console.log( data ); res.end( data ); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Now try to access defined API using URL: http://127.0.0.1:8081/listUsers and HTTP Method : GET on local machine using any REST client. This should produce following result − You can change given IP address when you will put the solution in production environment. { "user1" : { "name" : "mahesh", "password" : "password1", "profession" : "teacher", "id": 1 }, "user2" : { "name" : "suresh", "password" : "password2", "profession" : "librarian", "id": 2 }, "user3" : { "name" : "ramesh", "password" : "password3", "profession" : "clerk", "id": 3 } } Following API will show you how to add new user in the list. Following is the detail of the new user − user = { "user4" : { "name" : "mohit", "password" : "password4", "profession" : "teacher", "id": 4 } } You can accept the same input in the form of JSON using Ajax call but for teaching point of view, we are making it hard coded here. Following is the addUser API to a new user in the database − server.js var express = require('express'); var app = express(); var fs = require("fs"); var user = { "user4" : { "name" : "mohit", "password" : "password4", "profession" : "teacher", "id": 4 } } app.post('/addUser', function (req, res) { // First read existing users. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { data = JSON.parse( data ); data["user4"] = user["user4"]; console.log( data ); res.end( JSON.stringify(data)); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Now try to access defined API using URL: http://127.0.0.1:8081/addUser and HTTP Method : POST on local machine using any REST client. This should produce following result − { "user1":{"name":"mahesh","password":"password1","profession":"teacher","id":1}, "user2":{"name":"suresh","password":"password2","profession":"librarian","id":2}, "user3":{"name":"ramesh","password":"password3","profession":"clerk","id":3}, "user4":{"name":"mohit","password":"password4","profession":"teacher","id":4} } Now we will implement an API which will be called using user ID and it will display the detail of the corresponding user. server.js var express = require('express'); var app = express(); var fs = require("fs"); app.get('/:id', function (req, res) { // First read existing users. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { var users = JSON.parse( data ); var user = users["user" + req.params.id] console.log( user ); res.end( JSON.stringify(user)); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Now try to access defined API using URL: http://127.0.0.1:8081/2 and HTTP Method : GET on local machine using any REST client. This should produce following result − {"name":"suresh","password":"password2","profession":"librarian","id":2} This API is very similar to addUser API where we receive input data through req.body and then based on user ID we delete that user from the database. To keep our program simple we assume we are going to delete user with ID 2. server.js var express = require('express'); var app = express(); var fs = require("fs"); var id = 2; app.delete('/deleteUser', function (req, res) { // First read existing users. fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) { data = JSON.parse( data ); delete data["user" + 2]; console.log( data ); res.end( JSON.stringify(data)); }); }) var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port) }) Now try to access defined API using URL: http://127.0.0.1:8081/deleteUser and HTTP Method : DELETE on local machine using any REST client. This should produce following result − {"user1":{"name":"mahesh","password":"password1","profession":"teacher","id":1}, "user3":{"name":"ramesh","password":"password3","profession":"clerk","id":3}} 44 Lectures 7.5 hours Eduonix Learning Solutions 88 Lectures 17 hours Eduonix Learning Solutions 32 Lectures 1.5 hours Richard Wells 8 Lectures 33 mins Anant Rungta 9 Lectures 2.5 hours SHIVPRASAD KOIRALA 97 Lectures 6 hours Skillbakerystudios Print Add Notes Bookmark this page
[ { "code": null, "e": 2325, "s": 2018, "text": "REST stands for REpresentational State Transfer. REST is web standards based architecture and uses HTTP Protocol. It revolves around resource where every component is a resource and a resource is accessed by a common interface using HTTP standard methods. REST was first introduced by Roy Fielding in 2000." }, { "code": null, "e": 2614, "s": 2325, "text": "A REST Server simply provides access to resources and REST client accesses and modifies the resources using HTTP protocol. Here each resource is identified by URIs/ global IDs. REST uses various representation to represent a resource like text, JSON, XML but JSON is the most popular one." }, { "code": null, "e": 2688, "s": 2614, "text": "Following four HTTP methods are commonly used in REST based architecture." }, { "code": null, "e": 2752, "s": 2688, "text": "GET − This is used to provide a read only access to a resource." }, { "code": null, "e": 2816, "s": 2752, "text": "GET − This is used to provide a read only access to a resource." }, { "code": null, "e": 2861, "s": 2816, "text": "PUT − This is used to create a new resource." }, { "code": null, "e": 2906, "s": 2861, "text": "PUT − This is used to create a new resource." }, { "code": null, "e": 2950, "s": 2906, "text": "DELETE − This is used to remove a resource." }, { "code": null, "e": 2994, "s": 2950, "text": "DELETE − This is used to remove a resource." }, { "code": null, "e": 3070, "s": 2994, "text": "POST − This is used to update a existing resource or create a new resource." }, { "code": null, "e": 3146, "s": 3070, "text": "POST − This is used to update a existing resource or create a new resource." }, { "code": null, "e": 3654, "s": 3146, "text": "A web service is a collection of open protocols and standards used for exchanging data between applications or systems. Software applications written in various programming languages and running on various platforms can use web services to exchange data over computer networks like the Internet in a manner similar to inter-process communication on a single computer. This interoperability (e.g., communication between Java and Python, or Windows and Linux applications) is due to the use of open standards." }, { "code": null, "e": 3973, "s": 3654, "text": "Web services based on REST Architecture are known as RESTful web services. These webservices uses HTTP methods to implement the concept of REST architecture. A RESTful web service usually defines a URI, Uniform Resource Identifier a service, which provides resource representation such as JSON and set of HTTP Methods." }, { "code": null, "e": 4070, "s": 3973, "text": "Consider we have a JSON based database of users having the following users in a file users.json:" }, { "code": null, "e": 4453, "s": 4070, "text": "{\n \"user1\" : {\n \"name\" : \"mahesh\",\n \"password\" : \"password1\",\n \"profession\" : \"teacher\",\n \"id\": 1\n },\n \n \"user2\" : {\n \"name\" : \"suresh\",\n \"password\" : \"password2\",\n \"profession\" : \"librarian\",\n \"id\": 2\n },\n \n \"user3\" : {\n \"name\" : \"ramesh\",\n \"password\" : \"password3\",\n \"profession\" : \"clerk\",\n \"id\": 3\n }\n}" }, { "code": null, "e": 4527, "s": 4453, "text": "Based on this information we are going to provide following RESTful APIs." }, { "code": null, "e": 4748, "s": 4527, "text": "I'm keeping most of the part of all the examples in the form of hard coding assuming you already know how to pass values from front end using Ajax or simple form data and how to process them using express Request object." }, { "code": null, "e": 4843, "s": 4748, "text": "Let's implement our first RESTful API listUsers using the following code in a server.js file −" }, { "code": null, "e": 4853, "s": 4843, "text": "server.js" }, { "code": null, "e": 5307, "s": 4853, "text": "var express = require('express');\nvar app = express();\nvar fs = require(\"fs\");\n\napp.get('/listUsers', function (req, res) {\n fs.readFile( __dirname + \"/\" + \"users.json\", 'utf8', function (err, data) {\n console.log( data );\n res.end( data );\n });\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 5482, "s": 5307, "text": "Now try to access defined API using URL: http://127.0.0.1:8081/listUsers and HTTP Method : GET on local machine using any REST client. This should produce following result −" }, { "code": null, "e": 5572, "s": 5482, "text": "You can change given IP address when you will put the solution in production environment." }, { "code": null, "e": 5955, "s": 5572, "text": "{\n \"user1\" : {\n \"name\" : \"mahesh\",\n \"password\" : \"password1\",\n \"profession\" : \"teacher\",\n \"id\": 1\n },\n \n \"user2\" : {\n \"name\" : \"suresh\",\n \"password\" : \"password2\",\n \"profession\" : \"librarian\",\n \"id\": 2\n },\n \n \"user3\" : {\n \"name\" : \"ramesh\",\n \"password\" : \"password3\",\n \"profession\" : \"clerk\",\n \"id\": 3\n }\n}" }, { "code": null, "e": 6058, "s": 5955, "text": "Following API will show you how to add new user in the list. Following is the detail of the new user −" }, { "code": null, "e": 6191, "s": 6058, "text": "user = {\n \"user4\" : {\n \"name\" : \"mohit\",\n \"password\" : \"password4\",\n \"profession\" : \"teacher\",\n \"id\": 4\n }\n}" }, { "code": null, "e": 6384, "s": 6191, "text": "You can accept the same input in the form of JSON using Ajax call but for teaching point of view, we are making it hard coded here. Following is the addUser API to a new user in the database −" }, { "code": null, "e": 6394, "s": 6384, "text": "server.js" }, { "code": null, "e": 7103, "s": 6394, "text": "var express = require('express');\nvar app = express();\nvar fs = require(\"fs\");\n\nvar user = {\n \"user4\" : {\n \"name\" : \"mohit\",\n \"password\" : \"password4\",\n \"profession\" : \"teacher\",\n \"id\": 4\n }\n}\n\napp.post('/addUser', function (req, res) {\n // First read existing users.\n fs.readFile( __dirname + \"/\" + \"users.json\", 'utf8', function (err, data) {\n data = JSON.parse( data );\n data[\"user4\"] = user[\"user4\"];\n console.log( data );\n res.end( JSON.stringify(data));\n });\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 7277, "s": 7103, "text": "Now try to access defined API using URL: http://127.0.0.1:8081/addUser and HTTP Method : POST on local machine using any REST client. This should produce following result −" }, { "code": null, "e": 7611, "s": 7277, "text": "{\n \"user1\":{\"name\":\"mahesh\",\"password\":\"password1\",\"profession\":\"teacher\",\"id\":1},\n \"user2\":{\"name\":\"suresh\",\"password\":\"password2\",\"profession\":\"librarian\",\"id\":2},\n \"user3\":{\"name\":\"ramesh\",\"password\":\"password3\",\"profession\":\"clerk\",\"id\":3},\n \"user4\":{\"name\":\"mohit\",\"password\":\"password4\",\"profession\":\"teacher\",\"id\":4}\n}" }, { "code": null, "e": 7733, "s": 7611, "text": "Now we will implement an API which will be called using user ID and it will display the detail of the corresponding user." }, { "code": null, "e": 7743, "s": 7733, "text": "server.js" }, { "code": null, "e": 8325, "s": 7743, "text": "var express = require('express');\nvar app = express();\nvar fs = require(\"fs\");\n\napp.get('/:id', function (req, res) {\n // First read existing users.\n fs.readFile( __dirname + \"/\" + \"users.json\", 'utf8', function (err, data) {\n var users = JSON.parse( data );\n var user = users[\"user\" + req.params.id] \n console.log( user );\n res.end( JSON.stringify(user));\n });\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 8491, "s": 8325, "text": "Now try to access defined API using URL: http://127.0.0.1:8081/2 and HTTP Method : GET on local machine using any REST client. This should produce following result −" }, { "code": null, "e": 8565, "s": 8491, "text": "{\"name\":\"suresh\",\"password\":\"password2\",\"profession\":\"librarian\",\"id\":2}\n" }, { "code": null, "e": 8791, "s": 8565, "text": "This API is very similar to addUser API where we receive input data through req.body and then based on user ID we delete that user from the database. To keep our program simple we assume we are going to delete user with ID 2." }, { "code": null, "e": 8801, "s": 8791, "text": "server.js" }, { "code": null, "e": 9392, "s": 8801, "text": "var express = require('express');\nvar app = express();\nvar fs = require(\"fs\");\n\nvar id = 2;\n\napp.delete('/deleteUser', function (req, res) {\n // First read existing users.\n fs.readFile( __dirname + \"/\" + \"users.json\", 'utf8', function (err, data) {\n data = JSON.parse( data );\n delete data[\"user\" + 2];\n \n console.log( data );\n res.end( JSON.stringify(data));\n });\n})\n\nvar server = app.listen(8081, function () {\n var host = server.address().address\n var port = server.address().port\n console.log(\"Example app listening at http://%s:%s\", host, port)\n})" }, { "code": null, "e": 9570, "s": 9392, "text": "Now try to access defined API using URL: http://127.0.0.1:8081/deleteUser and HTTP Method : DELETE on local machine using any REST client. This should produce following result −" }, { "code": null, "e": 9730, "s": 9570, "text": "{\"user1\":{\"name\":\"mahesh\",\"password\":\"password1\",\"profession\":\"teacher\",\"id\":1},\n\"user3\":{\"name\":\"ramesh\",\"password\":\"password3\",\"profession\":\"clerk\",\"id\":3}}\n" }, { "code": null, "e": 9765, "s": 9730, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 9793, "s": 9765, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9827, "s": 9793, "text": "\n 88 Lectures \n 17 hours \n" }, { "code": null, "e": 9855, "s": 9827, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 9890, "s": 9855, "text": "\n 32 Lectures \n 1.5 hours \n" }, { "code": null, "e": 9905, "s": 9890, "text": " Richard Wells" }, { "code": null, "e": 9936, "s": 9905, "text": "\n 8 Lectures \n 33 mins\n" }, { "code": null, "e": 9950, "s": 9936, "text": " Anant Rungta" }, { "code": null, "e": 9984, "s": 9950, "text": "\n 9 Lectures \n 2.5 hours \n" }, { "code": null, "e": 10004, "s": 9984, "text": " SHIVPRASAD KOIRALA" }, { "code": null, "e": 10037, "s": 10004, "text": "\n 97 Lectures \n 6 hours \n" }, { "code": null, "e": 10057, "s": 10037, "text": " Skillbakerystudios" }, { "code": null, "e": 10064, "s": 10057, "text": " Print" }, { "code": null, "e": 10075, "s": 10064, "text": " Add Notes" } ]
Express Cookie-Parser - Signed and Unsigned Cookies - GeeksforGeeks
28 May, 2020 A cookie is a piece of data that is sent to the client-side with a request and is stored on the client-side itself by the Web Browser the user is currently using. With the help of cookies – It is easy for websites to remember the user’s information It is easy to capture the user’s browsing history It is also useful in storing the user’s sessions The session makes requests to all the servers using a secret Id. The information is stored on the server that is linked to this secret ID.To make use of cookies in our application, cookie-parser middleware is used. To install it, write the following command – npm install cookie-parser@latest --save Also, to install express middleware write the following command – npm install express@latest --save These commands will install the latest versions of cookie-parser and express.Cookie-parser middleware is used to parse the cookies that are attached to the request made by the client to the server. Therefore, to use cookie-parser, we will write the following lines of code in our JavaScript file – const cookieParser = require('cookie-parser');const express = require('express') const app = express();app.use(cookieParser()); Let’s look at an example of how to setup a new cookie. Create a new file named “index.js”. For setting up and assigning a name to a cookie, follow the code – const express = require('express');const cookieParser = require('cookie-parser'); const app = express(); app.get('/', (req, res) => { res.cookie('name', 'GeeksForGeeks').send('Cookie-Parser');}); app.listen(3000, (err) => { if(err){ console.log(err) } else { console.log('Success!!') }}); Here, we sent the cookie to the new route and set the name of the cookie as ‘GeeksForGeeks’. In the last block of code, our server is listening to the port 3000 with a callback function. If there will be an error then the callback function will return the error else it will return “Success”.Now, run the following code with the command – node index.js To check if the cookie is set or not, just go to this link after successfully setting up the server. Open the console and write the command as – document.cookie You will get the output as – "name=GeeksForGeeks" Also, the cookie-parser middleware populates the req.cookies with name that is sent to the server. Here, in our case, we can add the following line of code in our route – console.log(req.cookies) The output of the above line will be – { name: 'GeeksForGeeks' } cookieParser(secret, options)– This middleware takes two parameters. First one will be the secret Id and other will the options. The secret Id can be a string or an array of strings. If the secret parameter is not provided then it will take the cookie as unsigned cookie. Therefore, it is optional to provide the secret ID. The second parameter will be an object specifying what actions to be taken with the cookies. For example, decode is a function to decode the value of the cookie. – This middleware takes two parameters. First one will be the secret Id and other will the options. The secret Id can be a string or an array of strings. If the secret parameter is not provided then it will take the cookie as unsigned cookie. Therefore, it is optional to provide the secret ID. The second parameter will be an object specifying what actions to be taken with the cookies. For example, decode is a function to decode the value of the cookie. cookieParser.JSONCookie(str)– This method will parse the value of the cookie as a JSON cookie. It will return the parsed JSON value if the cookie provided is a JSON cookie. If not a JSON cookie, it will return the passed value itself. – This method will parse the value of the cookie as a JSON cookie. It will return the parsed JSON value if the cookie provided is a JSON cookie. If not a JSON cookie, it will return the passed value itself. cookieParser.JSONCookies(cookies)– Provided an object with its Id attached. This method will iterate over the Object Id’s provided and will call the “JSONCookie” on each value. It will replace the original value with the parsed value. This will return the same object that was passed in. – Provided an object with its Id attached. This method will iterate over the Object Id’s provided and will call the “JSONCookie” on each value. It will replace the original value with the parsed value. This will return the same object that was passed in. cookieParser.signedCookie(string, secret)– This method parses the cookie as a signed cookie. If the cookie is a signed cookie and signature can be validated, then it will return the parsed unsigned value. If the cookie is unsigned, then the original value is returned. If the cookie is signed but the signature cannot be validated, then false is returned.Now, our second argument secretcan be a string or an array of strings. If it is a string, then it will be used as a secret. If it is an array, then iteration over each element of the array will be done and the cookie will be unsigned using each secret. – This method parses the cookie as a signed cookie. If the cookie is a signed cookie and signature can be validated, then it will return the parsed unsigned value. If the cookie is unsigned, then the original value is returned. If the cookie is signed but the signature cannot be validated, then false is returned.Now, our second argument secretcan be a string or an array of strings. If it is a string, then it will be used as a secret. If it is an array, then iteration over each element of the array will be done and the cookie will be unsigned using each secret. cookieParser.signedCookies(cookies, secret)– This method will perform the iteration over each ID and check if any ID is a signed cookie. If it is signed and the signature can be validated, then the ID will be deleted from the object will it will be added to the new returning object. – This method will perform the iteration over each ID and check if any ID is a signed cookie. If it is signed and the signature can be validated, then the ID will be deleted from the object will it will be added to the new returning object. Depending on the type of the cookie sent from the client, these methods will automatically be called. const express = require('express');const cookieParser = require('cookie-parser'); const app = express(); app.get('/', (req, res) => { res.cookie('name', 'GeeksForGeeks').send(); console.log(req.cookies); }); app.listen(3000, (err) => { if(err){ console.log(err) } else { console.log('Success!!') }}); The output for the above code will be – "name=GeeksForGeeks" var express = require('express')var cookieParser = require('cookie-parser') var app = express()app.use(cookieParser('GFG')) app.get('/', function (req, res) { res.cookie('name', 'GeeksForGeeks', { signed: true }).send(); console.log(req.signedCookies)}) app.listen(3000, (err) => { if(err) { console.log(err) } else { console.log('Success') }}) Here, In the 4th line – “GFG” is provided as a secret value to the cookie.In the 7th line – the name for the cookie is set to “GeeksForGeeks” and the object signed is set to true.The output for the above code will be – { name: 'GeeksForGeeks' } Node.js-Misc JavaScript Node.js Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Convert a string to an integer in JavaScript Differences between Functional Components and Class Components in React How to append HTML code to a div using JavaScript ? How to Open URL in New Tab using JavaScript ? Installation of Node.js on Linux How to update Node.js and NPM to next version ? Node.js fs.readFileSync() Method Node.js fs.readFile() Method How to update NPM ?
[ { "code": null, "e": 24465, "s": 24437, "text": "\n28 May, 2020" }, { "code": null, "e": 24655, "s": 24465, "text": "A cookie is a piece of data that is sent to the client-side with a request and is stored on the client-side itself by the Web Browser the user is currently using. With the help of cookies –" }, { "code": null, "e": 24714, "s": 24655, "text": "It is easy for websites to remember the user’s information" }, { "code": null, "e": 24764, "s": 24714, "text": "It is easy to capture the user’s browsing history" }, { "code": null, "e": 24813, "s": 24764, "text": "It is also useful in storing the user’s sessions" }, { "code": null, "e": 25073, "s": 24813, "text": "The session makes requests to all the servers using a secret Id. The information is stored on the server that is linked to this secret ID.To make use of cookies in our application, cookie-parser middleware is used. To install it, write the following command –" }, { "code": null, "e": 25113, "s": 25073, "text": "npm install cookie-parser@latest --save" }, { "code": null, "e": 25179, "s": 25113, "text": "Also, to install express middleware write the following command –" }, { "code": null, "e": 25213, "s": 25179, "text": "npm install express@latest --save" }, { "code": null, "e": 25511, "s": 25213, "text": "These commands will install the latest versions of cookie-parser and express.Cookie-parser middleware is used to parse the cookies that are attached to the request made by the client to the server. Therefore, to use cookie-parser, we will write the following lines of code in our JavaScript file –" }, { "code": "const cookieParser = require('cookie-parser');const express = require('express') const app = express();app.use(cookieParser());", "e": 25640, "s": 25511, "text": null }, { "code": null, "e": 25798, "s": 25640, "text": "Let’s look at an example of how to setup a new cookie. Create a new file named “index.js”. For setting up and assigning a name to a cookie, follow the code –" }, { "code": "const express = require('express');const cookieParser = require('cookie-parser'); const app = express(); app.get('/', (req, res) => { res.cookie('name', 'GeeksForGeeks').send('Cookie-Parser');}); app.listen(3000, (err) => { if(err){ console.log(err) } else { console.log('Success!!') }});", "e": 26099, "s": 25798, "text": null }, { "code": null, "e": 26438, "s": 26099, "text": "Here, we sent the cookie to the new route and set the name of the cookie as ‘GeeksForGeeks’. In the last block of code, our server is listening to the port 3000 with a callback function. If there will be an error then the callback function will return the error else it will return “Success”.Now, run the following code with the command –" }, { "code": null, "e": 26452, "s": 26438, "text": "node index.js" }, { "code": null, "e": 26597, "s": 26452, "text": "To check if the cookie is set or not, just go to this link after successfully setting up the server. Open the console and write the command as –" }, { "code": null, "e": 26613, "s": 26597, "text": "document.cookie" }, { "code": null, "e": 26642, "s": 26613, "text": "You will get the output as –" }, { "code": null, "e": 26663, "s": 26642, "text": "\"name=GeeksForGeeks\"" }, { "code": null, "e": 26834, "s": 26663, "text": "Also, the cookie-parser middleware populates the req.cookies with name that is sent to the server. Here, in our case, we can add the following line of code in our route –" }, { "code": null, "e": 26859, "s": 26834, "text": "console.log(req.cookies)" }, { "code": null, "e": 26898, "s": 26859, "text": "The output of the above line will be –" }, { "code": null, "e": 26924, "s": 26898, "text": "{ name: 'GeeksForGeeks' }" }, { "code": null, "e": 27410, "s": 26924, "text": "cookieParser(secret, options)– This middleware takes two parameters. First one will be the secret Id and other will the options. The secret Id can be a string or an array of strings. If the secret parameter is not provided then it will take the cookie as unsigned cookie. Therefore, it is optional to provide the secret ID. The second parameter will be an object specifying what actions to be taken with the cookies. For example, decode is a function to decode the value of the cookie." }, { "code": null, "e": 27867, "s": 27410, "text": "– This middleware takes two parameters. First one will be the secret Id and other will the options. The secret Id can be a string or an array of strings. If the secret parameter is not provided then it will take the cookie as unsigned cookie. Therefore, it is optional to provide the secret ID. The second parameter will be an object specifying what actions to be taken with the cookies. For example, decode is a function to decode the value of the cookie." }, { "code": null, "e": 28102, "s": 27867, "text": "cookieParser.JSONCookie(str)– This method will parse the value of the cookie as a JSON cookie. It will return the parsed JSON value if the cookie provided is a JSON cookie. If not a JSON cookie, it will return the passed value itself." }, { "code": null, "e": 28309, "s": 28102, "text": "– This method will parse the value of the cookie as a JSON cookie. It will return the parsed JSON value if the cookie provided is a JSON cookie. If not a JSON cookie, it will return the passed value itself." }, { "code": null, "e": 28597, "s": 28309, "text": "cookieParser.JSONCookies(cookies)– Provided an object with its Id attached. This method will iterate over the Object Id’s provided and will call the “JSONCookie” on each value. It will replace the original value with the parsed value. This will return the same object that was passed in." }, { "code": null, "e": 28852, "s": 28597, "text": "– Provided an object with its Id attached. This method will iterate over the Object Id’s provided and will call the “JSONCookie” on each value. It will replace the original value with the parsed value. This will return the same object that was passed in." }, { "code": null, "e": 29460, "s": 28852, "text": "cookieParser.signedCookie(string, secret)– This method parses the cookie as a signed cookie. If the cookie is a signed cookie and signature can be validated, then it will return the parsed unsigned value. If the cookie is unsigned, then the original value is returned. If the cookie is signed but the signature cannot be validated, then false is returned.Now, our second argument secretcan be a string or an array of strings. If it is a string, then it will be used as a secret. If it is an array, then iteration over each element of the array will be done and the cookie will be unsigned using each secret." }, { "code": null, "e": 30027, "s": 29460, "text": "– This method parses the cookie as a signed cookie. If the cookie is a signed cookie and signature can be validated, then it will return the parsed unsigned value. If the cookie is unsigned, then the original value is returned. If the cookie is signed but the signature cannot be validated, then false is returned.Now, our second argument secretcan be a string or an array of strings. If it is a string, then it will be used as a secret. If it is an array, then iteration over each element of the array will be done and the cookie will be unsigned using each secret." }, { "code": null, "e": 30311, "s": 30027, "text": "cookieParser.signedCookies(cookies, secret)– This method will perform the iteration over each ID and check if any ID is a signed cookie. If it is signed and the signature can be validated, then the ID will be deleted from the object will it will be added to the new returning object." }, { "code": null, "e": 30552, "s": 30311, "text": "– This method will perform the iteration over each ID and check if any ID is a signed cookie. If it is signed and the signature can be validated, then the ID will be deleted from the object will it will be added to the new returning object." }, { "code": null, "e": 30654, "s": 30552, "text": "Depending on the type of the cookie sent from the client, these methods will automatically be called." }, { "code": "const express = require('express');const cookieParser = require('cookie-parser'); const app = express(); app.get('/', (req, res) => { res.cookie('name', 'GeeksForGeeks').send(); console.log(req.cookies); }); app.listen(3000, (err) => { if(err){ console.log(err) } else { console.log('Success!!') }});", "e": 30972, "s": 30654, "text": null }, { "code": null, "e": 31012, "s": 30972, "text": "The output for the above code will be –" }, { "code": null, "e": 31033, "s": 31012, "text": "\"name=GeeksForGeeks\"" }, { "code": "var express = require('express')var cookieParser = require('cookie-parser') var app = express()app.use(cookieParser('GFG')) app.get('/', function (req, res) { res.cookie('name', 'GeeksForGeeks', { signed: true }).send(); console.log(req.signedCookies)}) app.listen(3000, (err) => { if(err) { console.log(err) } else { console.log('Success') }})", "e": 31388, "s": 31033, "text": null }, { "code": null, "e": 31607, "s": 31388, "text": "Here, In the 4th line – “GFG” is provided as a secret value to the cookie.In the 7th line – the name for the cookie is set to “GeeksForGeeks” and the object signed is set to true.The output for the above code will be –" }, { "code": null, "e": 31633, "s": 31607, "text": "{ name: 'GeeksForGeeks' }" }, { "code": null, "e": 31646, "s": 31633, "text": "Node.js-Misc" }, { "code": null, "e": 31657, "s": 31646, "text": "JavaScript" }, { "code": null, "e": 31665, "s": 31657, "text": "Node.js" }, { "code": null, "e": 31763, "s": 31665, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31772, "s": 31763, "text": "Comments" }, { "code": null, "e": 31785, "s": 31772, "text": "Old Comments" }, { "code": null, "e": 31846, "s": 31785, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 31891, "s": 31846, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31963, "s": 31891, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 32015, "s": 31963, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 32061, "s": 32015, "text": "How to Open URL in New Tab using JavaScript ?" }, { "code": null, "e": 32094, "s": 32061, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32142, "s": 32094, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32175, "s": 32142, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 32204, "s": 32175, "text": "Node.js fs.readFile() Method" } ]
ARIMA Model In Python | by Billy Bonaros | Towards Data Science
ARIMA is one of the most popular statistical models. It stands for AutoRegressive Integrated Moving Average and it’s fitted to time series data either for forecasting or to better understand the data. We will not cover the whole theory behind the ARIMA model but we will show you what’s the steps you need to follow to apply it correctly. The key aspects of the ARIMA model are the following: AR: Autoregression. This indicates that the time series is regressed on its own lagged values. I: Integrated. This indicates that the data values have been replaced with the difference between their values and the previous values in order to convert the series into stationary. MA: Moving Average. This indicates that the regression error is actually a linear combination of error terms whose values occurred contemporaneously and at various times in the past. The ARIMA model can be applied when we have seasonal or non-seasonal data. The difference is that when we have seasonal data we need to add some more parameters to the model. For non-seasonal data the parameters are: p: The number of lag observations the model will use d: The number of times that the raw observations are differenced till stationarity. q: The size of the moving average window. For seasonal data we need to add also the following: P: The number of seasonal lag observations the model will use D: The number of times that the seasonal observations are differenced till stationarity. Q: The size of the seasonal moving average window. m: The number of observations of 1 season This is very easy to understand. Seasonal data is when we have intervals, such as weekly, monthly, or quarterly. For example, in this tutorial, we will use data that are aggregated by month and our “season” is the year. So, we have seasonal data and for the m parameter in the ARIMA model, we will use 12 which is the number of months per year. ARIMA models can be applied only in stationary data. That means that we don’t want to have a trend in time. If the time series has a trend, then it’s non-stationary and we need to apply differencing to transform it into stationary. Below is an example of a stationary and a non-stationary series. We can use also the Augmented Dickey-Fuller test to help us conclude if the series is stationary or not. The null hypothesis of the test is that there is a unit root with the alternative that there is no unit root. In other words, If the p-value is below 0.05 (or any critical size you will use), our Series is Stationary. Let’s start coding. For this tutorial, we will use the Air Passengers data from Kaggle. import pandas as pdimport numpy as npfrom statsmodels.tsa.seasonal import seasonal_decompose #https://www.kaggle.com/rakannimer/air-passengersdf=pd.read_csv(‘AirPassengers.csv’) #We need to set the Month column as index and convert it into datetimedf.set_index(‘Month’,inplace=True)df.index=pd.to_datetime(df.index)df.head() First things first, let’s plot our data. df.plot() As you can clearly see, there is a trend in time and that suggests that the data are not stationary. However just to be sure we will use an Augmented Dickey-Fuller test. from statsmodels.tsa.stattools import adfullerresult=adfuller(df['#Passengers'])#to help you, we added the names of every valuedict(zip(['adf', 'pvalue', 'usedlag', 'nobs', 'critical' 'values', 'icbest'],result)){'adf': 0.8153688792060468, 'pvalue': 0.991880243437641, 'usedlag': 13, 'nobs': 130, 'criticalvalues': {'1%': -3.4816817173418295, '5%': -2.8840418343195267, '10%': -2.578770059171598}, 'icbest': 996.692930839019} As expected we failed to reject the Null Hypothesis and the series has a unit root thus is not stationary. The next step is to transform our data to Stationary so we will have an estimate for d and D parameters we will use in the model. This can be done using Differencing and it’s performed by subtracting the previous observation from the current observation. difference(T) = observation(T) — observation(T-1) Then, we will test it again for stationarity using the Augmented Dickey-Fuller test and if it’s stationary we will proceed to our next step. If not we will apply differencing again till we have a stationary series. Differencing can be done very easily with pandas using the shift function. df['1difference']=df['#Passengers']-df['#Passengers'].shift(1)df['1difference'].plot() It seems that we removed the trend and the series is Stationary. However, we will use the Augmented Dickey-Fuller test to prove it. #note we are dropping na values because the first value of the first difference is NAresult=adfuller(df['1difference'].dropna())dict(zip(['adf', 'pvalue', 'usedlag', 'nobs', 'critical' 'values', 'icbest'],result)){'adf': -2.8292668241699857, 'pvalue': 0.05421329028382734, 'usedlag': 12, 'nobs': 130, 'criticalvalues': {'1%': -3.4816817173418295, '5%': -2.8840418343195267, '10%': -2.578770059171598}, 'icbest': 988.5069317854084} As you can see we fail to reject the null hypothesis because we have a p-value>0.05. That suggests that the series is not stationary and we need to use differencing again taking the second difference. The second difference can be computed as the first but this time instead of using the observations, we will use the first difference. df['2difference']=df['1difference']-df['1difference'].shift(1)df['2difference'].plot() Let’s get the results from the Augmented Dickey-Fuller test for the second difference. result=adfuller((df['2difference']).dropna())dict(zip(['adf', 'pvalue', 'usedlag', 'nobs', 'critical' 'values', 'icbest'],result)){'adf': -16.384231542468452, 'pvalue': 2.732891850014516e-29, 'usedlag': 11, 'nobs': 130, 'criticalvalues': {'1%': -3.4816817173418295, '5%': -2.8840418343195267, '10%': -2.578770059171598}, 'icbest': 988.602041727561} The p-value is less than 0.05 so we can reject the null hypothesis. That means the second difference is stationary and that suggests that a good estimate for the value d is 2. Our data are seasonal so we need to estimate also the D value which is the same as the d value but for Seasonal Difference. The seasonal difference can be computed by shifting the data by the number of rows per season (in our example 12 months per year) and subtracting them from the previous season. This is not the first seasonal difference. If we get that the seasonal difference is stationary then the D value will be 0. If not then we will compute the seasonal first difference. seasonal difference(T) = observation(T) — observation(T-12) seasonal first difference(T) = seasonal difference(T) — seasonal difference(T-1) df['Seasonal_Difference']=df['#Passengers']-df['#Passengers'].shift(12)ax=df['Seasonal_Difference'].plot() result=adfuller((df['Seasonal_Difference']).dropna())dict(zip(['adf', 'pvalue', 'usedlag', 'nobs', 'critical' 'values', 'icbest'],result)){'adf': -3.383020726492481, 'pvalue': 0.011551493085514952, 'usedlag': 1, 'nobs': 130, 'criticalvalues': {'1%': -3.4816817173418295, '5%': -2.8840418343195267, '10%': -2.578770059171598}, 'icbest': 919.527129208137} The p-value is less than 0.05 thus it’s stationary and we don’t have to use differencing. That suggests using 0 for the D value. The last step before the ARIMA model is to create the Autocorrelation and Partial Autocorrelation Plots to help us estimate the p,q, P, and Q parameters. There are some very useful rules for ARIMA and Seasonal ARIMA models that we are using to help us estimate the parameters by looking at the Autocorrelation and Partial Autocorrelation Plots. We will create the plots for the second difference and the seasonal difference of our time series because these are the stationary series we end up using in ARIMA (d=2, D=0). First, let’s plot ACF and PACF for the second difference. from statsmodels.graphics.tsaplots import plot_acf, plot_pacffig1=plot_acf(df['2difference'].dropna())fig2=plot_pacf(df['2difference'].dropna()) We can see that we have a sharp cut-off at lag-1 in both of our plots. According to the rules we mentioned above, this suggests using an AR and MA term. In other words, p=1 and q=1. Now, we need the same plots of Seasonal Difference. fig1=plot_acf(df['2difference'].dropna())fig2=plot_pacf(df['2difference'].dropna()) We have a gradual decrease in the Autocorrelation plot and a sharp cut-off in the Partial Autocorrelation plot. This suggests using AR and not over the value of 1 for the seasonal part of the ARIMA. The values we chose may not be optimum. You can play around with these parameters to fine-tune the model having as a guide the rules we mentioned above. from statsmodels.tsa.statespace.sarimax import SARIMAXmodel=SARIMAX(df['#Passengers'],order=(1,2,1),seasonal_order=(1, 0, 0, 12))result=model.fit() We can plot the residuals of the model to have an idea on how well the model is fitted. Basically, the residuals are the difference between the original values and the predicted values from the model. result.resid.plot(kind='kde') It’s time for a forecast. We will create some future dates to add them to our data so we can predict the future values. from pandas.tseries.offsets import DateOffsetnew_dates=[df.index[-1]+DateOffset(months=x) for x in range(1,48)]df_pred=pd.DataFrame(index=new_dates,columns =df.columns)df_pred.head() The ARIMA model predicts taking as arguments the start and the end of the enumerated index and not the date range.We created an empty data frame having indexes future dates and we concatenated them in our original data. Our data had 144 rows and the new dada we added have 48 rows. Therefore, to get the predictions only for the future data, we will predict from row 143 to 191. df2=pd.concat([df,df_pred])df2['predictions']=result.predict(start=143,end=191)df2[['#Passengers','predictions']].plot() Arima is a great model for forecasting and It can be used both for seasonal and non-seasonal time series data.For non-seasonal ARIMA you have to estimate the p, d, q parameters, and for Seasonal ARIMA it has 3 more that applies to seasonal difference the P, D, Q parameters. The pipeline that we are using to run an ARIMA model is the following: Look at your time series to understand if they are Seasonal or Non-Seasonal. Apply differencing to time series and seasonal difference if needed to reach stationarity to get an estimate for d and D values. Plot the Autocorrelation and Partial Autocorrelation plots to help you estimate the p, P, and q, Q values. Fine-tune the model if needed changing the parameters according to the general rules of ARIMA Useful links:Rules for ARIMAArima In RHow To Backtest Your Crypto Trading Strategies In RARIMA in Wikipedia Originally published at https://predictivehacks.com.
[ { "code": null, "e": 511, "s": 172, "text": "ARIMA is one of the most popular statistical models. It stands for AutoRegressive Integrated Moving Average and it’s fitted to time series data either for forecasting or to better understand the data. We will not cover the whole theory behind the ARIMA model but we will show you what’s the steps you need to follow to apply it correctly." }, { "code": null, "e": 565, "s": 511, "text": "The key aspects of the ARIMA model are the following:" }, { "code": null, "e": 660, "s": 565, "text": "AR: Autoregression. This indicates that the time series is regressed on its own lagged values." }, { "code": null, "e": 843, "s": 660, "text": "I: Integrated. This indicates that the data values have been replaced with the difference between their values and the previous values in order to convert the series into stationary." }, { "code": null, "e": 1026, "s": 843, "text": "MA: Moving Average. This indicates that the regression error is actually a linear combination of error terms whose values occurred contemporaneously and at various times in the past." }, { "code": null, "e": 1201, "s": 1026, "text": "The ARIMA model can be applied when we have seasonal or non-seasonal data. The difference is that when we have seasonal data we need to add some more parameters to the model." }, { "code": null, "e": 1243, "s": 1201, "text": "For non-seasonal data the parameters are:" }, { "code": null, "e": 1296, "s": 1243, "text": "p: The number of lag observations the model will use" }, { "code": null, "e": 1380, "s": 1296, "text": "d: The number of times that the raw observations are differenced till stationarity." }, { "code": null, "e": 1422, "s": 1380, "text": "q: The size of the moving average window." }, { "code": null, "e": 1475, "s": 1422, "text": "For seasonal data we need to add also the following:" }, { "code": null, "e": 1537, "s": 1475, "text": "P: The number of seasonal lag observations the model will use" }, { "code": null, "e": 1626, "s": 1537, "text": "D: The number of times that the seasonal observations are differenced till stationarity." }, { "code": null, "e": 1677, "s": 1626, "text": "Q: The size of the seasonal moving average window." }, { "code": null, "e": 1719, "s": 1677, "text": "m: The number of observations of 1 season" }, { "code": null, "e": 2064, "s": 1719, "text": "This is very easy to understand. Seasonal data is when we have intervals, such as weekly, monthly, or quarterly. For example, in this tutorial, we will use data that are aggregated by month and our “season” is the year. So, we have seasonal data and for the m parameter in the ARIMA model, we will use 12 which is the number of months per year." }, { "code": null, "e": 2361, "s": 2064, "text": "ARIMA models can be applied only in stationary data. That means that we don’t want to have a trend in time. If the time series has a trend, then it’s non-stationary and we need to apply differencing to transform it into stationary. Below is an example of a stationary and a non-stationary series." }, { "code": null, "e": 2684, "s": 2361, "text": "We can use also the Augmented Dickey-Fuller test to help us conclude if the series is stationary or not. The null hypothesis of the test is that there is a unit root with the alternative that there is no unit root. In other words, If the p-value is below 0.05 (or any critical size you will use), our Series is Stationary." }, { "code": null, "e": 2704, "s": 2684, "text": "Let’s start coding." }, { "code": null, "e": 2772, "s": 2704, "text": "For this tutorial, we will use the Air Passengers data from Kaggle." }, { "code": null, "e": 3097, "s": 2772, "text": "import pandas as pdimport numpy as npfrom statsmodels.tsa.seasonal import seasonal_decompose #https://www.kaggle.com/rakannimer/air-passengersdf=pd.read_csv(‘AirPassengers.csv’) #We need to set the Month column as index and convert it into datetimedf.set_index(‘Month’,inplace=True)df.index=pd.to_datetime(df.index)df.head()" }, { "code": null, "e": 3138, "s": 3097, "text": "First things first, let’s plot our data." }, { "code": null, "e": 3148, "s": 3138, "text": "df.plot()" }, { "code": null, "e": 3318, "s": 3148, "text": "As you can clearly see, there is a trend in time and that suggests that the data are not stationary. However just to be sure we will use an Augmented Dickey-Fuller test." }, { "code": null, "e": 3746, "s": 3318, "text": "from statsmodels.tsa.stattools import adfullerresult=adfuller(df['#Passengers'])#to help you, we added the names of every valuedict(zip(['adf', 'pvalue', 'usedlag', 'nobs', 'critical' 'values', 'icbest'],result)){'adf': 0.8153688792060468, 'pvalue': 0.991880243437641, 'usedlag': 13, 'nobs': 130, 'criticalvalues': {'1%': -3.4816817173418295, '5%': -2.8840418343195267, '10%': -2.578770059171598}, 'icbest': 996.692930839019}" }, { "code": null, "e": 3853, "s": 3746, "text": "As expected we failed to reject the Null Hypothesis and the series has a unit root thus is not stationary." }, { "code": null, "e": 4108, "s": 3853, "text": "The next step is to transform our data to Stationary so we will have an estimate for d and D parameters we will use in the model. This can be done using Differencing and it’s performed by subtracting the previous observation from the current observation." }, { "code": null, "e": 4158, "s": 4108, "text": "difference(T) = observation(T) — observation(T-1)" }, { "code": null, "e": 4448, "s": 4158, "text": "Then, we will test it again for stationarity using the Augmented Dickey-Fuller test and if it’s stationary we will proceed to our next step. If not we will apply differencing again till we have a stationary series. Differencing can be done very easily with pandas using the shift function." }, { "code": null, "e": 4535, "s": 4448, "text": "df['1difference']=df['#Passengers']-df['#Passengers'].shift(1)df['1difference'].plot()" }, { "code": null, "e": 4667, "s": 4535, "text": "It seems that we removed the trend and the series is Stationary. However, we will use the Augmented Dickey-Fuller test to prove it." }, { "code": null, "e": 5100, "s": 4667, "text": "#note we are dropping na values because the first value of the first difference is NAresult=adfuller(df['1difference'].dropna())dict(zip(['adf', 'pvalue', 'usedlag', 'nobs', 'critical' 'values', 'icbest'],result)){'adf': -2.8292668241699857, 'pvalue': 0.05421329028382734, 'usedlag': 12, 'nobs': 130, 'criticalvalues': {'1%': -3.4816817173418295, '5%': -2.8840418343195267, '10%': -2.578770059171598}, 'icbest': 988.5069317854084}" }, { "code": null, "e": 5435, "s": 5100, "text": "As you can see we fail to reject the null hypothesis because we have a p-value>0.05. That suggests that the series is not stationary and we need to use differencing again taking the second difference. The second difference can be computed as the first but this time instead of using the observations, we will use the first difference." }, { "code": null, "e": 5522, "s": 5435, "text": "df['2difference']=df['1difference']-df['1difference'].shift(1)df['2difference'].plot()" }, { "code": null, "e": 5609, "s": 5522, "text": "Let’s get the results from the Augmented Dickey-Fuller test for the second difference." }, { "code": null, "e": 5960, "s": 5609, "text": "result=adfuller((df['2difference']).dropna())dict(zip(['adf', 'pvalue', 'usedlag', 'nobs', 'critical' 'values', 'icbest'],result)){'adf': -16.384231542468452, 'pvalue': 2.732891850014516e-29, 'usedlag': 11, 'nobs': 130, 'criticalvalues': {'1%': -3.4816817173418295, '5%': -2.8840418343195267, '10%': -2.578770059171598}, 'icbest': 988.602041727561}" }, { "code": null, "e": 6136, "s": 5960, "text": "The p-value is less than 0.05 so we can reject the null hypothesis. That means the second difference is stationary and that suggests that a good estimate for the value d is 2." }, { "code": null, "e": 6620, "s": 6136, "text": "Our data are seasonal so we need to estimate also the D value which is the same as the d value but for Seasonal Difference. The seasonal difference can be computed by shifting the data by the number of rows per season (in our example 12 months per year) and subtracting them from the previous season. This is not the first seasonal difference. If we get that the seasonal difference is stationary then the D value will be 0. If not then we will compute the seasonal first difference." }, { "code": null, "e": 6680, "s": 6620, "text": "seasonal difference(T) = observation(T) — observation(T-12)" }, { "code": null, "e": 6761, "s": 6680, "text": "seasonal first difference(T) = seasonal difference(T) — seasonal difference(T-1)" }, { "code": null, "e": 6868, "s": 6761, "text": "df['Seasonal_Difference']=df['#Passengers']-df['#Passengers'].shift(12)ax=df['Seasonal_Difference'].plot()" }, { "code": null, "e": 7224, "s": 6868, "text": "result=adfuller((df['Seasonal_Difference']).dropna())dict(zip(['adf', 'pvalue', 'usedlag', 'nobs', 'critical' 'values', 'icbest'],result)){'adf': -3.383020726492481, 'pvalue': 0.011551493085514952, 'usedlag': 1, 'nobs': 130, 'criticalvalues': {'1%': -3.4816817173418295, '5%': -2.8840418343195267, '10%': -2.578770059171598}, 'icbest': 919.527129208137}" }, { "code": null, "e": 7353, "s": 7224, "text": "The p-value is less than 0.05 thus it’s stationary and we don’t have to use differencing. That suggests using 0 for the D value." }, { "code": null, "e": 7507, "s": 7353, "text": "The last step before the ARIMA model is to create the Autocorrelation and Partial Autocorrelation Plots to help us estimate the p,q, P, and Q parameters." }, { "code": null, "e": 7873, "s": 7507, "text": "There are some very useful rules for ARIMA and Seasonal ARIMA models that we are using to help us estimate the parameters by looking at the Autocorrelation and Partial Autocorrelation Plots. We will create the plots for the second difference and the seasonal difference of our time series because these are the stationary series we end up using in ARIMA (d=2, D=0)." }, { "code": null, "e": 7931, "s": 7873, "text": "First, let’s plot ACF and PACF for the second difference." }, { "code": null, "e": 8076, "s": 7931, "text": "from statsmodels.graphics.tsaplots import plot_acf, plot_pacffig1=plot_acf(df['2difference'].dropna())fig2=plot_pacf(df['2difference'].dropna())" }, { "code": null, "e": 8258, "s": 8076, "text": "We can see that we have a sharp cut-off at lag-1 in both of our plots. According to the rules we mentioned above, this suggests using an AR and MA term. In other words, p=1 and q=1." }, { "code": null, "e": 8310, "s": 8258, "text": "Now, we need the same plots of Seasonal Difference." }, { "code": null, "e": 8394, "s": 8310, "text": "fig1=plot_acf(df['2difference'].dropna())fig2=plot_pacf(df['2difference'].dropna())" }, { "code": null, "e": 8593, "s": 8394, "text": "We have a gradual decrease in the Autocorrelation plot and a sharp cut-off in the Partial Autocorrelation plot. This suggests using AR and not over the value of 1 for the seasonal part of the ARIMA." }, { "code": null, "e": 8746, "s": 8593, "text": "The values we chose may not be optimum. You can play around with these parameters to fine-tune the model having as a guide the rules we mentioned above." }, { "code": null, "e": 8894, "s": 8746, "text": "from statsmodels.tsa.statespace.sarimax import SARIMAXmodel=SARIMAX(df['#Passengers'],order=(1,2,1),seasonal_order=(1, 0, 0, 12))result=model.fit()" }, { "code": null, "e": 9095, "s": 8894, "text": "We can plot the residuals of the model to have an idea on how well the model is fitted. Basically, the residuals are the difference between the original values and the predicted values from the model." }, { "code": null, "e": 9125, "s": 9095, "text": "result.resid.plot(kind='kde')" }, { "code": null, "e": 9245, "s": 9125, "text": "It’s time for a forecast. We will create some future dates to add them to our data so we can predict the future values." }, { "code": null, "e": 9428, "s": 9245, "text": "from pandas.tseries.offsets import DateOffsetnew_dates=[df.index[-1]+DateOffset(months=x) for x in range(1,48)]df_pred=pd.DataFrame(index=new_dates,columns =df.columns)df_pred.head()" }, { "code": null, "e": 9807, "s": 9428, "text": "The ARIMA model predicts taking as arguments the start and the end of the enumerated index and not the date range.We created an empty data frame having indexes future dates and we concatenated them in our original data. Our data had 144 rows and the new dada we added have 48 rows. Therefore, to get the predictions only for the future data, we will predict from row 143 to 191." }, { "code": null, "e": 9928, "s": 9807, "text": "df2=pd.concat([df,df_pred])df2['predictions']=result.predict(start=143,end=191)df2[['#Passengers','predictions']].plot()" }, { "code": null, "e": 10203, "s": 9928, "text": "Arima is a great model for forecasting and It can be used both for seasonal and non-seasonal time series data.For non-seasonal ARIMA you have to estimate the p, d, q parameters, and for Seasonal ARIMA it has 3 more that applies to seasonal difference the P, D, Q parameters." }, { "code": null, "e": 10274, "s": 10203, "text": "The pipeline that we are using to run an ARIMA model is the following:" }, { "code": null, "e": 10351, "s": 10274, "text": "Look at your time series to understand if they are Seasonal or Non-Seasonal." }, { "code": null, "e": 10480, "s": 10351, "text": "Apply differencing to time series and seasonal difference if needed to reach stationarity to get an estimate for d and D values." }, { "code": null, "e": 10587, "s": 10480, "text": "Plot the Autocorrelation and Partial Autocorrelation plots to help you estimate the p, P, and q, Q values." }, { "code": null, "e": 10681, "s": 10587, "text": "Fine-tune the model if needed changing the parameters according to the general rules of ARIMA" }, { "code": null, "e": 10789, "s": 10681, "text": "Useful links:Rules for ARIMAArima In RHow To Backtest Your Crypto Trading Strategies In RARIMA in Wikipedia" } ]
PySpark Analysis on Airport Data | by Ojaas Hampiholi | Towards Data Science
Big data is a collection of massive and complex data sets and data volume that include huge quantities of data, data management capabilities, social media analytics, and real-time data. Big Data means data that can not be processed by streamlined processing methods because of the sheer huge size of data to be processed. Big Data is also defined as the system of handling large amounts of data to produce results in real-time with very little latency. Apache Spark is a unified analytics engine that is used primarily for large-scale processing. Some of the major advantages of Apache Spark are Speed of Processing, Ease of Use, Generality for Platforms and Toolkits that can be integrated with it. PySpark is Python API that works on Apache Spark. The major advantages of using PySpark are that it integrates easily with Java, R, and Scala. Data Scientists can leverage RDD’s to work with higher speeds on distributed clusters storing data in parts. Disking Persistence and Powerful Caching help to improve processing speed more. In this article, we discuss how PySpark can be used on Google Collaboratory Notebooks to analyze a very huge data set containing about 3.6 Million rows and 15 Features. github.com Download JRE Headless version to Notebook. Download JRE Headless version to Notebook. !apt-get install openjdk-8-jdk-headless -qq > /dev/null 2. Download Spark with Hadoop installation zip file and unzip it for further use. !wget -q https://downloads.apache.org/spark/spark-3.0.2/spark-3.0.2-bin-hadoop2.7.tgz!tar xf spark-3.0.2-bin-hadoop2.7.tgz 3. Set the Javahome and Sparkhome variables. import os os.environ["JAVA_HOME"] = "/usr/lib/jvm/java-8-openjdk-amd64" os.environ["SPARK_HOME"] = "/content/spark-3.0.2-bin-hadoop2.7" 4. Install and Initialize findspark library. !pip install -q findsparkimport findsparkfindspark.find()findspark.init() 5. Create Spark and SQLContext Sessions. from pyspark.sql import SparkSessionspark = SparkSession.builder\ .master("local")\ .appName("Colab")\ .config('spark.ui.port', '4050')\ .getOrCreate()from pyspark.sql import SQLContextsqlContext = SQLContext(spark)spark The above steps can be found in the Notebook. Once we have made the necessary installations and set up the analysis environment, data is open source and can be found on Kaggle under the title USA Airport Dataset. This project uses a dataset that is available at the link as of 31 March 2021. After downloading, we can read the CSV data to pyspark and register its table form to be used with SQLContext. df = spark.read.csv("./Airports2.csv", header=True, inferSchema=True)df.registerTempTable('df') The first steps that any Data Analyst would take to do preliminary analysis on the dataset are to count the number of rows, the schema of data, and statistical descriptions of features. df.printSchema() df.describe().show() The steps above are done to get basics insights into the data and they help Data Analysts to determine pre-processing steps that need to be applied to the data to get it to the proper format. To understand the data better, we can have a look at the first few rows of data. Spark Transformations and Actions can be used to subset the data. df.select("Origin_airport","Destination_airport","Passengers","Seats").show(15) airportAgg_DF = df.groupBy("Origin_airport").agg(F.sum("Passengers"))airportAgg_DF.show(10) Once all Preliminary Analysis is complete, we proceed to answer some questions that can be formulated as SQL Queries using SQLContext. The Research Questions and their corresponding answers have been discussed in brief below. The code solutions to the questions posed below can be found here. We can see that popular airports in terms of flight departures are Chicago O’Hare, Hartsfield-Jackson Atlanta, Dallas/Fort Worth, and Los Angeles International Airports in the same order. We can see that popular airports in terms of passenger arrivals are Hartsfield-Jackson Atlanta, Chicago O’Hare, Dallas/Fort Worth, and Los Angeles International Airports in the same order. We can see that popular airports in terms of the Number of Flights are Chicago O’Hare, Hartsfield-Jackson Atlanta, Dallas/Fort Worth, and Los Angeles International Airports in the same order. We can see that popular airports in terms of the Number of Passengers are Dallas/Fort Worth, Hartsfield-Jackson Atlanta, Chicago O’Hare, and Los Angeles International Airports in the same order. The occupancy rates of popular flights are somewhere between 48% and 71% with an average of 60%. This implies that although there are lots of flights that operate between airports, most of them are not efficient in terms of passenger traffic. Also, reducing and rescheduling some flights to increase occupancy rates can help Airlines to reduce their fuel costs, while also helping to protect the environment by reducing carbon footprint. We can observe from the output that in most cases, the frequency of long-distance flights is low. However, it is interesting to note that there are lots of flights that operate between Hawaii — Honolulu (Honolulu International Airport) and New York (John F Kennedy International Airport and Newark Liberty International Airport) even with considerable long distance between the two places. We can see that medium distance routes (100–300 miles) have the greatest number of flights except for few exceptional cases. Flight Route between Chicago (ORD) and New York (EWR, LGA) is operated heavily even though the distance between airports is 725 miles. Another interesting case that we see here is that flight between Atlanta (ATL) and Dallas/Fort Worth (DFW) is a popular service even though the distance is around 720 miles. The Output tables can be saved as separate CSV files and can be used to visualize data using Python or Tableau to create interactive dashboards that can help people to choose flights and plan their vacations accordingly. An application can be made to include a workflow using Apache AirFlow which refreshes the data daily and updates charts that have been created on the dashboard.
[ { "code": null, "e": 872, "s": 172, "text": "Big data is a collection of massive and complex data sets and data volume that include huge quantities of data, data management capabilities, social media analytics, and real-time data. Big Data means data that can not be processed by streamlined processing methods because of the sheer huge size of data to be processed. Big Data is also defined as the system of handling large amounts of data to produce results in real-time with very little latency. Apache Spark is a unified analytics engine that is used primarily for large-scale processing. Some of the major advantages of Apache Spark are Speed of Processing, Ease of Use, Generality for Platforms and Toolkits that can be integrated with it." }, { "code": null, "e": 1373, "s": 872, "text": "PySpark is Python API that works on Apache Spark. The major advantages of using PySpark are that it integrates easily with Java, R, and Scala. Data Scientists can leverage RDD’s to work with higher speeds on distributed clusters storing data in parts. Disking Persistence and Powerful Caching help to improve processing speed more. In this article, we discuss how PySpark can be used on Google Collaboratory Notebooks to analyze a very huge data set containing about 3.6 Million rows and 15 Features." }, { "code": null, "e": 1384, "s": 1373, "text": "github.com" }, { "code": null, "e": 1427, "s": 1384, "text": "Download JRE Headless version to Notebook." }, { "code": null, "e": 1470, "s": 1427, "text": "Download JRE Headless version to Notebook." }, { "code": null, "e": 1526, "s": 1470, "text": "!apt-get install openjdk-8-jdk-headless -qq > /dev/null" }, { "code": null, "e": 1608, "s": 1526, "text": "2. Download Spark with Hadoop installation zip file and unzip it for further use." }, { "code": null, "e": 1731, "s": 1608, "text": "!wget -q https://downloads.apache.org/spark/spark-3.0.2/spark-3.0.2-bin-hadoop2.7.tgz!tar xf spark-3.0.2-bin-hadoop2.7.tgz" }, { "code": null, "e": 1776, "s": 1731, "text": "3. Set the Javahome and Sparkhome variables." }, { "code": null, "e": 1912, "s": 1776, "text": "import os os.environ[\"JAVA_HOME\"] = \"/usr/lib/jvm/java-8-openjdk-amd64\" os.environ[\"SPARK_HOME\"] = \"/content/spark-3.0.2-bin-hadoop2.7\"" }, { "code": null, "e": 1957, "s": 1912, "text": "4. Install and Initialize findspark library." }, { "code": null, "e": 2031, "s": 1957, "text": "!pip install -q findsparkimport findsparkfindspark.find()findspark.init()" }, { "code": null, "e": 2072, "s": 2031, "text": "5. Create Spark and SQLContext Sessions." }, { "code": null, "e": 2321, "s": 2072, "text": "from pyspark.sql import SparkSessionspark = SparkSession.builder\\ .master(\"local\")\\ .appName(\"Colab\")\\ .config('spark.ui.port', '4050')\\ .getOrCreate()from pyspark.sql import SQLContextsqlContext = SQLContext(spark)spark" }, { "code": null, "e": 2724, "s": 2321, "text": "The above steps can be found in the Notebook. Once we have made the necessary installations and set up the analysis environment, data is open source and can be found on Kaggle under the title USA Airport Dataset. This project uses a dataset that is available at the link as of 31 March 2021. After downloading, we can read the CSV data to pyspark and register its table form to be used with SQLContext." }, { "code": null, "e": 2820, "s": 2724, "text": "df = spark.read.csv(\"./Airports2.csv\", header=True, inferSchema=True)df.registerTempTable('df')" }, { "code": null, "e": 3006, "s": 2820, "text": "The first steps that any Data Analyst would take to do preliminary analysis on the dataset are to count the number of rows, the schema of data, and statistical descriptions of features." }, { "code": null, "e": 3023, "s": 3006, "text": "df.printSchema()" }, { "code": null, "e": 3044, "s": 3023, "text": "df.describe().show()" }, { "code": null, "e": 3383, "s": 3044, "text": "The steps above are done to get basics insights into the data and they help Data Analysts to determine pre-processing steps that need to be applied to the data to get it to the proper format. To understand the data better, we can have a look at the first few rows of data. Spark Transformations and Actions can be used to subset the data." }, { "code": null, "e": 3463, "s": 3383, "text": "df.select(\"Origin_airport\",\"Destination_airport\",\"Passengers\",\"Seats\").show(15)" }, { "code": null, "e": 3555, "s": 3463, "text": "airportAgg_DF = df.groupBy(\"Origin_airport\").agg(F.sum(\"Passengers\"))airportAgg_DF.show(10)" }, { "code": null, "e": 3848, "s": 3555, "text": "Once all Preliminary Analysis is complete, we proceed to answer some questions that can be formulated as SQL Queries using SQLContext. The Research Questions and their corresponding answers have been discussed in brief below. The code solutions to the questions posed below can be found here." }, { "code": null, "e": 4036, "s": 3848, "text": "We can see that popular airports in terms of flight departures are Chicago O’Hare, Hartsfield-Jackson Atlanta, Dallas/Fort Worth, and Los Angeles International Airports in the same order." }, { "code": null, "e": 4225, "s": 4036, "text": "We can see that popular airports in terms of passenger arrivals are Hartsfield-Jackson Atlanta, Chicago O’Hare, Dallas/Fort Worth, and Los Angeles International Airports in the same order." }, { "code": null, "e": 4417, "s": 4225, "text": "We can see that popular airports in terms of the Number of Flights are Chicago O’Hare, Hartsfield-Jackson Atlanta, Dallas/Fort Worth, and Los Angeles International Airports in the same order." }, { "code": null, "e": 4612, "s": 4417, "text": "We can see that popular airports in terms of the Number of Passengers are Dallas/Fort Worth, Hartsfield-Jackson Atlanta, Chicago O’Hare, and Los Angeles International Airports in the same order." }, { "code": null, "e": 5050, "s": 4612, "text": "The occupancy rates of popular flights are somewhere between 48% and 71% with an average of 60%. This implies that although there are lots of flights that operate between airports, most of them are not efficient in terms of passenger traffic. Also, reducing and rescheduling some flights to increase occupancy rates can help Airlines to reduce their fuel costs, while also helping to protect the environment by reducing carbon footprint." }, { "code": null, "e": 5440, "s": 5050, "text": "We can observe from the output that in most cases, the frequency of long-distance flights is low. However, it is interesting to note that there are lots of flights that operate between Hawaii — Honolulu (Honolulu International Airport) and New York (John F Kennedy International Airport and Newark Liberty International Airport) even with considerable long distance between the two places." }, { "code": null, "e": 5874, "s": 5440, "text": "We can see that medium distance routes (100–300 miles) have the greatest number of flights except for few exceptional cases. Flight Route between Chicago (ORD) and New York (EWR, LGA) is operated heavily even though the distance between airports is 725 miles. Another interesting case that we see here is that flight between Atlanta (ATL) and Dallas/Fort Worth (DFW) is a popular service even though the distance is around 720 miles." } ]
Stock Predictions — Intraday Trading | by Monik Raj | Towards Data Science
Now let's have a brief idea about the problem set we are going to deal with. Intraday-trading is that trading norm of the stock market whose vesting period is, in layman’s words, 1 day. Buyers buy shares at the opening time of market at a specific time window and then sell the same at the closing window of the same day. We are here dealing with a data set of one of the public companies of Tokyo, with daily data of two years from 2014–2016. We are going to use a simple machine learning model to : Understand our dataMake predictions based on an algorithm Understand our data Make predictions based on an algorithm For the reference, here is the link to my Github repository which contains : Python script for performing analysisTest data in csv formatTrain data in csv format Python script for performing analysis Test data in csv format Train data in csv format github.com Now since you can find all the python codes in my repository, I am not going to bore you by again taking you through the code base or explaining to you the same. The script is simple, stand-alone and pretty straightforward, so it’s quite simple to understand. I have also documented the script wherever required, and still if you are stuck, you can always drop a mail at bmonikraj@gmail.com and expect a reply within a day. Once my professor at NIT Rourkela, India said, “Understanding of the data and the problem set is as important as, the statistical knowledge required to analyze the same”. We need to understand about intra-day trading and the aspects defining the behaviour of our target value. So, our data set comprises of 7 columns, out of which 6 are features and 1 is target. Features Open — It is the opening price of a shares for that particular day High — It is the highest price the shares have touched in throughout day Low — It is the lowest price the shares have fallen to in throughout day Close — It is the closing price of the shares for that day Date — The date of the observation, mostly the index of our data Volume — The number of shares sold in throughout day Target Stock Trading- The price of the total shares in the market for that day Now, since our data has a ‘Time’ component, it is highly probable that our data is a Time-series data. But for a data to be qualified as time-series data, it must have a factor of either ‘Trend’ or ‘Seasonality’. To check if our data set is seasonal or trendy in nature, we can perform “Dickey-Fuller Analysis”. If our dataset is seasonal in nature, then we can analyze it as a ‘Time-series’ data. While implementing Dickey-fuller analysis in Python, it requires a variable, ‘Frequency’. Frequency is mathematically defined as Frequency = (Total time units expected till which data will show repetative patter, in minutes) / (time gap between each observations, in minutes) Now, in our data-set, we have basically Intra-day trading data. That means, our data is based on everyday’s behaviours of market, incidents in market or industries, management changes in the company, interests of buyers, policies and such other governing factors. Thus, we can strongly believe that our data will not show any pattern for more than a day. And also, from data-set it is evident that our observation frequency is one day. So, we chose the frequency to be 1. Here is the Dicker-Fuller Analysis report of my data-set From the above graph, it is clear that our data is not seasonal in behaviour, which means our data set is not a ‘time-series’ data-set, since seasonality is 0. Now, after removing the seasonality out of the equation, we have a data set which is completely numeric in nature and has five features, because ‘time’ is no longer a feature to be consider, since it is not time-series data. We can find the graphs of behaviour of various features and target over time here From the above, we can see the individual behaviour of the features with respect to time. We can also have the correlation graph between every feature with each other and understand the interdependent relation between every feature. From the above graph, the diagonal matrix gives the histogram of the values each column, which is of no use for us since we are not interested in distibution of the features or target (as the number of variables are high and also they are correlated). A general note on understanding correlation matrix plot If the total graph seems like a curve (either linear or non-linear), then they are correlated to good extentIf the plot seems scattered, then they are not correlated as expected If the total graph seems like a curve (either linear or non-linear), then they are correlated to good extent If the plot seems scattered, then they are not correlated as expected Now, we can infer from the above graph, that most of the features are inter-dependent of each other are correlated. ‘Open’ is highly correlated with ‘High’, ‘Low’ and ‘Close’. And ‘volume’ is correlated to a good extent with target, ‘Stock Trading’. Thus, all the features are important for analysis. The problem can now be laid out in the simple terms as below : Dataset has all numerical valuesNumber of Features = Dimension = 5One TargetTarget is ‘predicted’ (numerical)Train size < 1000 Dataset has all numerical values Number of Features = Dimension = 5 One Target Target is ‘predicted’ (numerical) Train size < 1000 From the above list, it is the best option to choose linear regression model for the same because It is a problem of prediction , so a regressor must be usedSince the dimension is quite small and so thus the train size, any complex and sophisticated model, like SVM regressor can overfit the model (You can try !) It is a problem of prediction , so a regressor must be used Since the dimension is quite small and so thus the train size, any complex and sophisticated model, like SVM regressor can overfit the model (You can try !) After implementing linear regression from scikit-learn module of Python, we get the RMSE = 4253929991.85, after testing our model on test data The value seems too high and seems a mis-fit, but we must not forget the fact that the order of features and target values are not similar or near to each other. The order of values in ‘stock trading’ ( 1011) >> order of values in features (105 ~ 106) So, from that manner, the RMSE’s order is justified, considering the order in which Mean Squared Error is calculated. Here is the plot of the Actual test target and calculated Test target. From this you can visualize how small the deviation is, hence the performance of our model. Applying the knowledge of machine learning and algorithms to daily life scenario and better decision making is the main purpose of such academic advances. And after all, ‘numbers play an important role in decision making, because numbers never lie’. If I may put a conclusion to my article at the end — “You don’t need a sword to cut your nails” Reach out to me in case you have any queries, at bmonikraj@gmail.com Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
[ { "code": null, "e": 248, "s": 171, "text": "Now let's have a brief idea about the problem set we are going to deal with." }, { "code": null, "e": 672, "s": 248, "text": "Intraday-trading is that trading norm of the stock market whose vesting period is, in layman’s words, 1 day. Buyers buy shares at the opening time of market at a specific time window and then sell the same at the closing window of the same day. We are here dealing with a data set of one of the public companies of Tokyo, with daily data of two years from 2014–2016. We are going to use a simple machine learning model to :" }, { "code": null, "e": 730, "s": 672, "text": "Understand our dataMake predictions based on an algorithm" }, { "code": null, "e": 750, "s": 730, "text": "Understand our data" }, { "code": null, "e": 789, "s": 750, "text": "Make predictions based on an algorithm" }, { "code": null, "e": 866, "s": 789, "text": "For the reference, here is the link to my Github repository which contains :" }, { "code": null, "e": 951, "s": 866, "text": "Python script for performing analysisTest data in csv formatTrain data in csv format" }, { "code": null, "e": 989, "s": 951, "text": "Python script for performing analysis" }, { "code": null, "e": 1013, "s": 989, "text": "Test data in csv format" }, { "code": null, "e": 1038, "s": 1013, "text": "Train data in csv format" }, { "code": null, "e": 1049, "s": 1038, "text": "github.com" }, { "code": null, "e": 1473, "s": 1049, "text": "Now since you can find all the python codes in my repository, I am not going to bore you by again taking you through the code base or explaining to you the same. The script is simple, stand-alone and pretty straightforward, so it’s quite simple to understand. I have also documented the script wherever required, and still if you are stuck, you can always drop a mail at bmonikraj@gmail.com and expect a reply within a day." }, { "code": null, "e": 1750, "s": 1473, "text": "Once my professor at NIT Rourkela, India said, “Understanding of the data and the problem set is as important as, the statistical knowledge required to analyze the same”. We need to understand about intra-day trading and the aspects defining the behaviour of our target value." }, { "code": null, "e": 1836, "s": 1750, "text": "So, our data set comprises of 7 columns, out of which 6 are features and 1 is target." }, { "code": null, "e": 1845, "s": 1836, "text": "Features" }, { "code": null, "e": 1912, "s": 1845, "text": "Open — It is the opening price of a shares for that particular day" }, { "code": null, "e": 1985, "s": 1912, "text": "High — It is the highest price the shares have touched in throughout day" }, { "code": null, "e": 2058, "s": 1985, "text": "Low — It is the lowest price the shares have fallen to in throughout day" }, { "code": null, "e": 2117, "s": 2058, "text": "Close — It is the closing price of the shares for that day" }, { "code": null, "e": 2182, "s": 2117, "text": "Date — The date of the observation, mostly the index of our data" }, { "code": null, "e": 2235, "s": 2182, "text": "Volume — The number of shares sold in throughout day" }, { "code": null, "e": 2242, "s": 2235, "text": "Target" }, { "code": null, "e": 2314, "s": 2242, "text": "Stock Trading- The price of the total shares in the market for that day" }, { "code": null, "e": 2712, "s": 2314, "text": "Now, since our data has a ‘Time’ component, it is highly probable that our data is a Time-series data. But for a data to be qualified as time-series data, it must have a factor of either ‘Trend’ or ‘Seasonality’. To check if our data set is seasonal or trendy in nature, we can perform “Dickey-Fuller Analysis”. If our dataset is seasonal in nature, then we can analyze it as a ‘Time-series’ data." }, { "code": null, "e": 2841, "s": 2712, "text": "While implementing Dickey-fuller analysis in Python, it requires a variable, ‘Frequency’. Frequency is mathematically defined as" }, { "code": null, "e": 2988, "s": 2841, "text": "Frequency = (Total time units expected till which data will show repetative patter, in minutes) / (time gap between each observations, in minutes)" }, { "code": null, "e": 3460, "s": 2988, "text": "Now, in our data-set, we have basically Intra-day trading data. That means, our data is based on everyday’s behaviours of market, incidents in market or industries, management changes in the company, interests of buyers, policies and such other governing factors. Thus, we can strongly believe that our data will not show any pattern for more than a day. And also, from data-set it is evident that our observation frequency is one day. So, we chose the frequency to be 1." }, { "code": null, "e": 3517, "s": 3460, "text": "Here is the Dicker-Fuller Analysis report of my data-set" }, { "code": null, "e": 3677, "s": 3517, "text": "From the above graph, it is clear that our data is not seasonal in behaviour, which means our data set is not a ‘time-series’ data-set, since seasonality is 0." }, { "code": null, "e": 3902, "s": 3677, "text": "Now, after removing the seasonality out of the equation, we have a data set which is completely numeric in nature and has five features, because ‘time’ is no longer a feature to be consider, since it is not time-series data." }, { "code": null, "e": 3984, "s": 3902, "text": "We can find the graphs of behaviour of various features and target over time here" }, { "code": null, "e": 4217, "s": 3984, "text": "From the above, we can see the individual behaviour of the features with respect to time. We can also have the correlation graph between every feature with each other and understand the interdependent relation between every feature." }, { "code": null, "e": 4469, "s": 4217, "text": "From the above graph, the diagonal matrix gives the histogram of the values each column, which is of no use for us since we are not interested in distibution of the features or target (as the number of variables are high and also they are correlated)." }, { "code": null, "e": 4525, "s": 4469, "text": "A general note on understanding correlation matrix plot" }, { "code": null, "e": 4703, "s": 4525, "text": "If the total graph seems like a curve (either linear or non-linear), then they are correlated to good extentIf the plot seems scattered, then they are not correlated as expected" }, { "code": null, "e": 4812, "s": 4703, "text": "If the total graph seems like a curve (either linear or non-linear), then they are correlated to good extent" }, { "code": null, "e": 4882, "s": 4812, "text": "If the plot seems scattered, then they are not correlated as expected" }, { "code": null, "e": 5183, "s": 4882, "text": "Now, we can infer from the above graph, that most of the features are inter-dependent of each other are correlated. ‘Open’ is highly correlated with ‘High’, ‘Low’ and ‘Close’. And ‘volume’ is correlated to a good extent with target, ‘Stock Trading’. Thus, all the features are important for analysis." }, { "code": null, "e": 5246, "s": 5183, "text": "The problem can now be laid out in the simple terms as below :" }, { "code": null, "e": 5373, "s": 5246, "text": "Dataset has all numerical valuesNumber of Features = Dimension = 5One TargetTarget is ‘predicted’ (numerical)Train size < 1000" }, { "code": null, "e": 5406, "s": 5373, "text": "Dataset has all numerical values" }, { "code": null, "e": 5441, "s": 5406, "text": "Number of Features = Dimension = 5" }, { "code": null, "e": 5452, "s": 5441, "text": "One Target" }, { "code": null, "e": 5486, "s": 5452, "text": "Target is ‘predicted’ (numerical)" }, { "code": null, "e": 5504, "s": 5486, "text": "Train size < 1000" }, { "code": null, "e": 5602, "s": 5504, "text": "From the above list, it is the best option to choose linear regression model for the same because" }, { "code": null, "e": 5818, "s": 5602, "text": "It is a problem of prediction , so a regressor must be usedSince the dimension is quite small and so thus the train size, any complex and sophisticated model, like SVM regressor can overfit the model (You can try !)" }, { "code": null, "e": 5878, "s": 5818, "text": "It is a problem of prediction , so a regressor must be used" }, { "code": null, "e": 6035, "s": 5878, "text": "Since the dimension is quite small and so thus the train size, any complex and sophisticated model, like SVM regressor can overfit the model (You can try !)" }, { "code": null, "e": 6178, "s": 6035, "text": "After implementing linear regression from scikit-learn module of Python, we get the RMSE = 4253929991.85, after testing our model on test data" }, { "code": null, "e": 6340, "s": 6178, "text": "The value seems too high and seems a mis-fit, but we must not forget the fact that the order of features and target values are not similar or near to each other." }, { "code": null, "e": 6430, "s": 6340, "text": "The order of values in ‘stock trading’ ( 1011) >> order of values in features (105 ~ 106)" }, { "code": null, "e": 6711, "s": 6430, "text": "So, from that manner, the RMSE’s order is justified, considering the order in which Mean Squared Error is calculated. Here is the plot of the Actual test target and calculated Test target. From this you can visualize how small the deviation is, hence the performance of our model." }, { "code": null, "e": 6961, "s": 6711, "text": "Applying the knowledge of machine learning and algorithms to daily life scenario and better decision making is the main purpose of such academic advances. And after all, ‘numbers play an important role in decision making, because numbers never lie’." }, { "code": null, "e": 7057, "s": 6961, "text": "If I may put a conclusion to my article at the end — “You don’t need a sword to cut your nails”" }, { "code": null, "e": 7126, "s": 7057, "text": "Reach out to me in case you have any queries, at bmonikraj@gmail.com" } ]
Using Deep Learning to train a Deep Search Chess Algorithm | by Victor Sim | Towards Data Science
In most chess engines, a searching algorithm along with a heuristic function gives the chess AI the main insight into the best moves to play. The bulk of the programming and most of the “brains” behind this is the heuristic function. What do I mean by heuristic function? Heuristic function refers to a function that takes certain measurements of the chessboard, gives each measurement a certain weightage, and finally calculate a numerical value of the advantage of each player. The heuristic function in chess usually considers basic things such as pawn structure, center control, and King safety, but it can also include more complex calculations such as tempo and opportunities to employ different tactics. A well-seasoned chess player with a decent proficiency in programming would be able to construct a good heuristic function. Unfortunately, I am not that well-seasoned chess player. I have decided to use a neural network to create a heuristic function for me. The concept of the program uses a neural network to evaluate the board, which is then fitted with the search algorithm, which checks all future position and finds the highest value, sort of like a min-max tree. from pandas import read_csvimport numpy as npimport chessimport osdf = read_csv('C:\\Users\\v_sim\\Desktop\\Files\\Data\\chess.csv')df = df[df['winner']!='draw']moves = df['moves'].values[:100]winner = df['winner'].valuesX = []y = [] This script extracts the csv file from my computer, and imports the necessary imports for the program to function. Pandas is for csv data extraction, numpy for the manipulation of arrays, chess for a ready-made chess board and empty lists to represent the X and y values for the network. def make_matrix(board): pgn = board.epd() foo = [] pieces = pgn.split(" ", 1)[0] rows = pieces.split("/") for row in rows: foo2 = [] for thing in row: if thing.isdigit(): for i in range(0, int(thing)): foo2.append('.') else: foo2.append(thing) foo.append(foo2) return foodef translate(matrix,chess_dict): rows = [] for row in matrix: terms = [] for term in row: terms.append(chess_dict[term]) rows.append(terms) return rowschess_dict = { 'p' : [1,0,0,0,0,0,0,0,0,0,0,0], 'P' : [0,0,0,0,0,0,1,0,0,0,0,0], 'n' : [0,1,0,0,0,0,0,0,0,0,0,0], 'N' : [0,0,0,0,0,0,0,1,0,0,0,0], 'b' : [0,0,1,0,0,0,0,0,0,0,0,0], 'B' : [0,0,0,0,0,0,0,0,1,0,0,0], 'r' : [0,0,0,1,0,0,0,0,0,0,0,0], 'R' : [0,0,0,0,0,0,0,0,0,1,0,0], 'q' : [0,0,0,0,1,0,0,0,0,0,0,0], 'Q' : [0,0,0,0,0,0,0,0,0,0,1,0], 'k' : [0,0,0,0,0,1,0,0,0,0,0,0], 'K' : [0,0,0,0,0,0,0,0,0,0,0,1], '.' : [0,0,0,0,0,0,0,0,0,0,0,0],} This script is able to transform the class board into a one-hot encoded chessboard. This is done by first accessing the epd form of the board, then splitting it into rows, and finally translating all the squares using a dictionary. for game in moves: index = list(moves).index(game) all_moves = game.split() total_moves = len(all_moves) if winner[index] == 'black': game_winner = -1 else: game_winner = 1 board = chess.Board() for i in range(len(all_moves)): board.push_san(all_moves[i]) value = game_winner * (i/total_moves) matrix = make_matrix(board.copy()) rows = translate(matrix,chess_dict) X.append([rows]) y.append(value)X = np.array(X).reshape(len(X),8,8,12)y = np.array(y)X.shape Believe it or not, this is where all of the magic happens. Instead of using pawn structure and development to calculate the advantage of a player, the neural network will skip directly ahead to checkmates. The dataset that I have loaded up includes over 14,000 games of chess, giving detailed information on the openings and the moves played. The data that I will synthesize for the network will try and calculate the heuristic value, by learning the value “How many more moves until checkmate for player X?”. It learns this pattern through the thousands of games until it has a strong grasp of the player’s advantage. from keras import callbacks, optimizersfrom keras.layers import (LSTM, BatchNormalization, Dense, Dropout, Flatten, TimeDistributed)from keras.layers.convolutional import Conv2D, MaxPooling2Dfrom keras.models import Sequential, load_model, model_from_jsonmodel = Sequential()model.add(Conv2D(filters=64, kernel_size=1, activation='relu', input_shape=(8,8,12)))model.add(MaxPooling2D())model.add(Conv2D(filters=24, kernel_size=1, activation='relu'))model.add(MaxPooling2D())model.add(Conv2D(filters=10, kernel_size=1, activation='relu'))model.add(Flatten())model.add(BatchNormalization())model.add(Dense(1,activation = 'tanh'))model.predict(X) This is a basic convolutional neural network, apart from the use of the hyperbolic tangent at the end of the forward propagation loop. The hyperbolic tangent is used in this case, as the values that are attributed to each board can be between -1 and 1, which perfectly fits the range of the hyperbolic tangent. from matplotlib import pyplot as pltmodel.compile(optimizer='Nadam', loss='mse')dirx = 'C:\\Users\\v_sim\\Desktop\\Files\\Programs\\ML\\Best Models'os.chdir(dirx)h5 = 'chess' + '_best_model' + '.h5'checkpoint = callbacks.ModelCheckpoint(h5, monitor='loss', verbose=0, save_best_only=True, save_weights_only=True, mode='auto', period=1)es = callbacks.EarlyStopping(monitor='loss', mode='min', verbose=1, patience=5000/10)callback = [checkpoint,es]json = 'chess' + '_best_model' + '.json'model_json = model.to_json()with open(json, "w") as json_file: json_file.write(model_json)print('Training Network...')history = model.fit(X,y,epochs = 1000,verbose = 2,callbacks = callback)plt.plot(history.history['loss']) This is the simple training setup for machine learning with sequential keras models. randint = np.random.randint(1,len(moves))randint2 = np.random.randint(1,len(moves[randint].split()))board = chess.Board()for i in range(randint2): board.push_san(moves[randint].split()[i])matrix = make_matrix(board.copy())rows = translate(matrix,chess_dict)print('Board Evaluation:',model.predict([rows])[0][0])board This step is optional, it is just to see if the evaluations of your network are logical. When the neural network is trained with the above training parameters, these are some of the results: This evaluation is correct. White is in a large disadvantage, moving his white queen into a square in which the knight on c6 can take it. This gives black a large material advantage. Keep in mind that the scale goes between -1 and 1, -1 being a checkmate for black and 1 being a checkmate for white The reason for this exact value is not clear, but the neural network is a black box: It does not have clear, defined rules that it follows to calculate this value This evaluation shows that the bot understands the concept of development and how development can lead to checkmates. White has absolute control of the center, with rook support along the e-file. The knight has a strong outpost on the center, eyeing the pawn on f7. With the correct support, the attack on the f7 pawn could result in a fork on the queen and the rock. Additionally, no pawns can attack the night, unless the knight on f6 moves away. import chessflatten = lambda l: [item for sublist in l for item in sublist]def search_positions(board,depth): #legal_moves = str(boards[depth][board].legal_moves)[38:-2].replace(',','').split() depth_list = [] for i in range(depth+1): depth_list.append([]) depth_list[0].append(board) for layer in depth_list: layer_set = [] try: stet = flatten(layer) except: stet = layer for i in range(len(stet)): legal_moves = str(stet[i].legal_moves)[38:-2].replace(',','').split() legal_moveset = [] for move in legal_moves: neo_board = stet[i].copy() neo_board.push_san(move) legal_moveset.append(neo_board) layer_set.append(legal_moveset) if depth_list.index(layer)+1 == len(depth_list): break depth_list[depth_list.index(layer)+1] = layer_set return depth_list boards = search_positions(chess.Board(),2) I won’t go into too much depth into how my deep search algorithm works, but it simply just uses the legal moves from the python-chess library and basic list functions to create a tree of possible moves. As I am only using a depth of 2, I only need to evaluate the last set of moves. When considering the worst case scenario for each move, check which one has the best worst case scenario, that is therefore the best move in this circumstance. In order to evaluate the board without using other complex iterator tools, I came up with an interesting application of the “try: , except:” structure that indexes itself into the next list, until a chess board is found: def evaluate(lst): for i in range(len(lst)): try: matrix = make_matrix(lst[i]) rows = translate(matrix,chess_dict) lst[i] = model.predict([rows]) except: evaluate(lst[i]) return lstevaluation = evaluate(boards[-1]) Cool right? maximum = 0for term in evaluation: if np.mean(term) > maximum: maximum = np.mean(term) index = evaluation.index(term) This final script shows you the best move for the circumstances given. I think that this program is an interesting case, where neural networks are not the ultimate solving factor, but a stepping stone to the final solution of the machine learning problem. I believe that people underestimate neural networks’ ability to bypass complex intermediary obstacles, that prevent one from reaching the goal. I hope that more people will use Neural networks as the intermediate step in more complicated projects. If you want to see more of my content, click this link.
[ { "code": null, "e": 406, "s": 172, "text": "In most chess engines, a searching algorithm along with a heuristic function gives the chess AI the main insight into the best moves to play. The bulk of the programming and most of the “brains” behind this is the heuristic function." }, { "code": null, "e": 883, "s": 406, "text": "What do I mean by heuristic function? Heuristic function refers to a function that takes certain measurements of the chessboard, gives each measurement a certain weightage, and finally calculate a numerical value of the advantage of each player. The heuristic function in chess usually considers basic things such as pawn structure, center control, and King safety, but it can also include more complex calculations such as tempo and opportunities to employ different tactics." }, { "code": null, "e": 1142, "s": 883, "text": "A well-seasoned chess player with a decent proficiency in programming would be able to construct a good heuristic function. Unfortunately, I am not that well-seasoned chess player. I have decided to use a neural network to create a heuristic function for me." }, { "code": null, "e": 1353, "s": 1142, "text": "The concept of the program uses a neural network to evaluate the board, which is then fitted with the search algorithm, which checks all future position and finds the highest value, sort of like a min-max tree." }, { "code": null, "e": 1587, "s": 1353, "text": "from pandas import read_csvimport numpy as npimport chessimport osdf = read_csv('C:\\\\Users\\\\v_sim\\\\Desktop\\\\Files\\\\Data\\\\chess.csv')df = df[df['winner']!='draw']moves = df['moves'].values[:100]winner = df['winner'].valuesX = []y = []" }, { "code": null, "e": 1875, "s": 1587, "text": "This script extracts the csv file from my computer, and imports the necessary imports for the program to function. Pandas is for csv data extraction, numpy for the manipulation of arrays, chess for a ready-made chess board and empty lists to represent the X and y values for the network." }, { "code": null, "e": 2938, "s": 1875, "text": "def make_matrix(board): pgn = board.epd() foo = [] pieces = pgn.split(\" \", 1)[0] rows = pieces.split(\"/\") for row in rows: foo2 = [] for thing in row: if thing.isdigit(): for i in range(0, int(thing)): foo2.append('.') else: foo2.append(thing) foo.append(foo2) return foodef translate(matrix,chess_dict): rows = [] for row in matrix: terms = [] for term in row: terms.append(chess_dict[term]) rows.append(terms) return rowschess_dict = { 'p' : [1,0,0,0,0,0,0,0,0,0,0,0], 'P' : [0,0,0,0,0,0,1,0,0,0,0,0], 'n' : [0,1,0,0,0,0,0,0,0,0,0,0], 'N' : [0,0,0,0,0,0,0,1,0,0,0,0], 'b' : [0,0,1,0,0,0,0,0,0,0,0,0], 'B' : [0,0,0,0,0,0,0,0,1,0,0,0], 'r' : [0,0,0,1,0,0,0,0,0,0,0,0], 'R' : [0,0,0,0,0,0,0,0,0,1,0,0], 'q' : [0,0,0,0,1,0,0,0,0,0,0,0], 'Q' : [0,0,0,0,0,0,0,0,0,0,1,0], 'k' : [0,0,0,0,0,1,0,0,0,0,0,0], 'K' : [0,0,0,0,0,0,0,0,0,0,0,1], '.' : [0,0,0,0,0,0,0,0,0,0,0,0],}" }, { "code": null, "e": 3170, "s": 2938, "text": "This script is able to transform the class board into a one-hot encoded chessboard. This is done by first accessing the epd form of the board, then splitting it into rows, and finally translating all the squares using a dictionary." }, { "code": null, "e": 3705, "s": 3170, "text": "for game in moves: index = list(moves).index(game) all_moves = game.split() total_moves = len(all_moves) if winner[index] == 'black': game_winner = -1 else: game_winner = 1 board = chess.Board() for i in range(len(all_moves)): board.push_san(all_moves[i]) value = game_winner * (i/total_moves) matrix = make_matrix(board.copy()) rows = translate(matrix,chess_dict) X.append([rows]) y.append(value)X = np.array(X).reshape(len(X),8,8,12)y = np.array(y)X.shape" }, { "code": null, "e": 4324, "s": 3705, "text": "Believe it or not, this is where all of the magic happens. Instead of using pawn structure and development to calculate the advantage of a player, the neural network will skip directly ahead to checkmates. The dataset that I have loaded up includes over 14,000 games of chess, giving detailed information on the openings and the moves played. The data that I will synthesize for the network will try and calculate the heuristic value, by learning the value “How many more moves until checkmate for player X?”. It learns this pattern through the thousands of games until it has a strong grasp of the player’s advantage." }, { "code": null, "e": 4992, "s": 4324, "text": "from keras import callbacks, optimizersfrom keras.layers import (LSTM, BatchNormalization, Dense, Dropout, Flatten, TimeDistributed)from keras.layers.convolutional import Conv2D, MaxPooling2Dfrom keras.models import Sequential, load_model, model_from_jsonmodel = Sequential()model.add(Conv2D(filters=64, kernel_size=1, activation='relu', input_shape=(8,8,12)))model.add(MaxPooling2D())model.add(Conv2D(filters=24, kernel_size=1, activation='relu'))model.add(MaxPooling2D())model.add(Conv2D(filters=10, kernel_size=1, activation='relu'))model.add(Flatten())model.add(BatchNormalization())model.add(Dense(1,activation = 'tanh'))model.predict(X)" }, { "code": null, "e": 5303, "s": 4992, "text": "This is a basic convolutional neural network, apart from the use of the hyperbolic tangent at the end of the forward propagation loop. The hyperbolic tangent is used in this case, as the values that are attributed to each board can be between -1 and 1, which perfectly fits the range of the hyperbolic tangent." }, { "code": null, "e": 6267, "s": 5303, "text": "from matplotlib import pyplot as pltmodel.compile(optimizer='Nadam', loss='mse')dirx = 'C:\\\\Users\\\\v_sim\\\\Desktop\\\\Files\\\\Programs\\\\ML\\\\Best Models'os.chdir(dirx)h5 = 'chess' + '_best_model' + '.h5'checkpoint = callbacks.ModelCheckpoint(h5, monitor='loss', verbose=0, save_best_only=True, save_weights_only=True, mode='auto', period=1)es = callbacks.EarlyStopping(monitor='loss', mode='min', verbose=1, patience=5000/10)callback = [checkpoint,es]json = 'chess' + '_best_model' + '.json'model_json = model.to_json()with open(json, \"w\") as json_file: json_file.write(model_json)print('Training Network...')history = model.fit(X,y,epochs = 1000,verbose = 2,callbacks = callback)plt.plot(history.history['loss'])" }, { "code": null, "e": 6352, "s": 6267, "text": "This is the simple training setup for machine learning with sequential keras models." }, { "code": null, "e": 6672, "s": 6352, "text": "randint = np.random.randint(1,len(moves))randint2 = np.random.randint(1,len(moves[randint].split()))board = chess.Board()for i in range(randint2): board.push_san(moves[randint].split()[i])matrix = make_matrix(board.copy())rows = translate(matrix,chess_dict)print('Board Evaluation:',model.predict([rows])[0][0])board" }, { "code": null, "e": 6863, "s": 6672, "text": "This step is optional, it is just to see if the evaluations of your network are logical. When the neural network is trained with the above training parameters, these are some of the results:" }, { "code": null, "e": 7046, "s": 6863, "text": "This evaluation is correct. White is in a large disadvantage, moving his white queen into a square in which the knight on c6 can take it. This gives black a large material advantage." }, { "code": null, "e": 7162, "s": 7046, "text": "Keep in mind that the scale goes between -1 and 1, -1 being a checkmate for black and 1 being a checkmate for white" }, { "code": null, "e": 7325, "s": 7162, "text": "The reason for this exact value is not clear, but the neural network is a black box: It does not have clear, defined rules that it follows to calculate this value" }, { "code": null, "e": 7521, "s": 7325, "text": "This evaluation shows that the bot understands the concept of development and how development can lead to checkmates. White has absolute control of the center, with rook support along the e-file." }, { "code": null, "e": 7774, "s": 7521, "text": "The knight has a strong outpost on the center, eyeing the pawn on f7. With the correct support, the attack on the f7 pawn could result in a fork on the queen and the rock. Additionally, no pawns can attack the night, unless the knight on f6 moves away." }, { "code": null, "e": 8762, "s": 7774, "text": "import chessflatten = lambda l: [item for sublist in l for item in sublist]def search_positions(board,depth): #legal_moves = str(boards[depth][board].legal_moves)[38:-2].replace(',','').split() depth_list = [] for i in range(depth+1): depth_list.append([]) depth_list[0].append(board) for layer in depth_list: layer_set = [] try: stet = flatten(layer) except: stet = layer for i in range(len(stet)): legal_moves = str(stet[i].legal_moves)[38:-2].replace(',','').split() legal_moveset = [] for move in legal_moves: neo_board = stet[i].copy() neo_board.push_san(move) legal_moveset.append(neo_board) layer_set.append(legal_moveset) if depth_list.index(layer)+1 == len(depth_list): break depth_list[depth_list.index(layer)+1] = layer_set return depth_list boards = search_positions(chess.Board(),2)" }, { "code": null, "e": 8965, "s": 8762, "text": "I won’t go into too much depth into how my deep search algorithm works, but it simply just uses the legal moves from the python-chess library and basic list functions to create a tree of possible moves." }, { "code": null, "e": 9205, "s": 8965, "text": "As I am only using a depth of 2, I only need to evaluate the last set of moves. When considering the worst case scenario for each move, check which one has the best worst case scenario, that is therefore the best move in this circumstance." }, { "code": null, "e": 9426, "s": 9205, "text": "In order to evaluate the board without using other complex iterator tools, I came up with an interesting application of the “try: , except:” structure that indexes itself into the next list, until a chess board is found:" }, { "code": null, "e": 9705, "s": 9426, "text": "def evaluate(lst): for i in range(len(lst)): try: matrix = make_matrix(lst[i]) rows = translate(matrix,chess_dict) lst[i] = model.predict([rows]) except: evaluate(lst[i]) return lstevaluation = evaluate(boards[-1])" }, { "code": null, "e": 9717, "s": 9705, "text": "Cool right?" }, { "code": null, "e": 9852, "s": 9717, "text": "maximum = 0for term in evaluation: if np.mean(term) > maximum: maximum = np.mean(term) index = evaluation.index(term)" }, { "code": null, "e": 9923, "s": 9852, "text": "This final script shows you the best move for the circumstances given." }, { "code": null, "e": 10252, "s": 9923, "text": "I think that this program is an interesting case, where neural networks are not the ultimate solving factor, but a stepping stone to the final solution of the machine learning problem. I believe that people underestimate neural networks’ ability to bypass complex intermediary obstacles, that prevent one from reaching the goal." }, { "code": null, "e": 10356, "s": 10252, "text": "I hope that more people will use Neural networks as the intermediate step in more complicated projects." } ]
Plotting a map of London Crime Data using R | by David Morison | Towards Data Science
I recently decided to play around and get familiar with the GIS (geographic information systems) packages available in R. I’ve always been interested in maps and I’m one of those who can spend as much time exploring Google maps as the average American spends on Facebook (maybe not quite as much). This write up is aimed more towards the experience I had in learning how to use R for GIS purposes and the steps I took to achieve an objective of plotting some points on a map. First of all I needed some data to work with. Having read a number of blogs based on the crime figures from the UK police data I decided to do a bit of exploration with this data. It was perfect for my objective of this project as it includes the month a crime took place, the latitude and longitude co-ordinates and the type of crime. My area of interest was London as this is where I live. The Greater London area is covered by the Metropolitan Police Service and the City of London Police data sets. I chose 2016 as the study period and downloaded the monthly data sets. (I only realized at a later stage when plotting the data that the Metropolitan Police Service data included crimes from other cities in the UK. This was easily corrected by including an extra step in my data preparation phase outlined in the next step.) The other data needed for this project was the GIS Shapefiles for which I was wanting to be able to plot the London borough boundaries. These are available from the government’s London Datastore website. After unzipping the downloaded data it contained a csv file for each month all in separate folders. I wrote a script to read all these separate csv files into R and then at the same time carry out the necessary sub-setting and binding to ultimately form one dataset. For the purpose of this project I retained only the variables “month”, “longitude”, “latitude”, and “crime.type”. I chose to exclude all missing data as I didn’t want to use any estimates as I was going to be plotting exact co-ordinates on a map for specific types of crime. The final data consisted of 988,848 crime incidences and 14 types of crime. There are a number of packages needed in R for reading in Shapefiles and transforming either the co-ordinates to match the map projections for your plots or vice versa. These packages included: rgdal, rgeos, sp and ggplot2. There are various other packages that can be used to achieve similar results. Firstly, the shapefile is imported into R using the “readOGR” method and then the projection needs to be transformed such that it matches the format of the latitude and longitude co-ordinates I have in the crime data set I curated. This proved to be the trickiest part of this project and took a large amount of Googling to work it out. ldn1 <- readOGR(file.path(data), layer = “london_sport”)proj4string(ldn1) <- CRS("+init=epsg:27700")ldn1.wgs84 <- spTransform(ldn1, CRS("+init=epsg:4326")) Once this is done it’s easy going from here especially if you are familiar with ggplot2. I took this in steps and first wanted to see how the plot of the map came out. This is done using the geom_polygonmethod available with ggplot2 and the transformed shapefile data from above: map1 <- ggplot(ldn1.wgs84) + geom_polygon(aes(x = long, y = lat, group = group), fill = “white”, colour = “black”)map1 + labs(x = “Longitude”, y = “Latitude”, title = “Map of Greater London with the borough boundaries”) The next step was to add a layer of all the crime locations and differentiate between the types of crime: map1 + geom_point(data = df, aes(x = Longitude, y = Latitude, colour = Crime.type)) + scale_colour_manual(values = rainbow(14)) + labs(x = “Longitude”, y = “Latitude”, title = “Map of Greater London with the borough boundaries”) In theory this was the objective of this project, however, as it is clear from the above plot that this isn’t ideal as it is far too busy and difficult to interpret. I decided to look only at one type of crime for a particular month. Seeing that I enjoy cycling I and wouldn’t ever want my mountain bike stolen, I would like to know whether I should be extra vigilant when parking my bike in certain areas therefore I trimmed the data set to look at bicycle theft for the month of December. dec <- df[df$Month == "2016-12", ]dec.bike <- dec[dec$Crime.type == “Bicycle theft”, ]map1 + geom_point(data = dec.bike, aes(x = Longitude, y = Latitude), colour = "red") + labs(title = "Bicycle theft in Greater London - December 2016") This produced a more visually appeasing plot that could be interpreted. As expected the crime incidences are concentrated more towards the city center. The down-side to this is that the amount of insight one can gain is limited to one type of crime for one month of the year, while there are another 13 types of crime and the other months of the year to look at. The objective of this project was to explore the GIS packages available in R and use these to plot some points on a map. This was achieved using data obtained from the UK police website for different types of crimes and their locations for the year of 2016. By trimming the data to look at one specific type of crime, in this case bicycle theft for one month it became easier to interpret the plot. This project was a great learning experience and demonstrated the usefulness of R as a tool for GIS. Considering the amount of data to display in this project and the limitations of interpreting larger data sets on the plots I thought it would be a great idea to turn this into an interactive ShinyApp, which I have left as a follow-up post, which can now be found here.
[ { "code": null, "e": 470, "s": 172, "text": "I recently decided to play around and get familiar with the GIS (geographic information systems) packages available in R. I’ve always been interested in maps and I’m one of those who can spend as much time exploring Google maps as the average American spends on Facebook (maybe not quite as much)." }, { "code": null, "e": 648, "s": 470, "text": "This write up is aimed more towards the experience I had in learning how to use R for GIS purposes and the steps I took to achieve an objective of plotting some points on a map." }, { "code": null, "e": 984, "s": 648, "text": "First of all I needed some data to work with. Having read a number of blogs based on the crime figures from the UK police data I decided to do a bit of exploration with this data. It was perfect for my objective of this project as it includes the month a crime took place, the latitude and longitude co-ordinates and the type of crime." }, { "code": null, "e": 1222, "s": 984, "text": "My area of interest was London as this is where I live. The Greater London area is covered by the Metropolitan Police Service and the City of London Police data sets. I chose 2016 as the study period and downloaded the monthly data sets." }, { "code": null, "e": 1476, "s": 1222, "text": "(I only realized at a later stage when plotting the data that the Metropolitan Police Service data included crimes from other cities in the UK. This was easily corrected by including an extra step in my data preparation phase outlined in the next step.)" }, { "code": null, "e": 1680, "s": 1476, "text": "The other data needed for this project was the GIS Shapefiles for which I was wanting to be able to plot the London borough boundaries. These are available from the government’s London Datastore website." }, { "code": null, "e": 1780, "s": 1680, "text": "After unzipping the downloaded data it contained a csv file for each month all in separate folders." }, { "code": null, "e": 1947, "s": 1780, "text": "I wrote a script to read all these separate csv files into R and then at the same time carry out the necessary sub-setting and binding to ultimately form one dataset." }, { "code": null, "e": 2222, "s": 1947, "text": "For the purpose of this project I retained only the variables “month”, “longitude”, “latitude”, and “crime.type”. I chose to exclude all missing data as I didn’t want to use any estimates as I was going to be plotting exact co-ordinates on a map for specific types of crime." }, { "code": null, "e": 2298, "s": 2222, "text": "The final data consisted of 988,848 crime incidences and 14 types of crime." }, { "code": null, "e": 2600, "s": 2298, "text": "There are a number of packages needed in R for reading in Shapefiles and transforming either the co-ordinates to match the map projections for your plots or vice versa. These packages included: rgdal, rgeos, sp and ggplot2. There are various other packages that can be used to achieve similar results." }, { "code": null, "e": 2937, "s": 2600, "text": "Firstly, the shapefile is imported into R using the “readOGR” method and then the projection needs to be transformed such that it matches the format of the latitude and longitude co-ordinates I have in the crime data set I curated. This proved to be the trickiest part of this project and took a large amount of Googling to work it out." }, { "code": null, "e": 3093, "s": 2937, "text": "ldn1 <- readOGR(file.path(data), layer = “london_sport”)proj4string(ldn1) <- CRS(\"+init=epsg:27700\")ldn1.wgs84 <- spTransform(ldn1, CRS(\"+init=epsg:4326\"))" }, { "code": null, "e": 3373, "s": 3093, "text": "Once this is done it’s easy going from here especially if you are familiar with ggplot2. I took this in steps and first wanted to see how the plot of the map came out. This is done using the geom_polygonmethod available with ggplot2 and the transformed shapefile data from above:" }, { "code": null, "e": 3594, "s": 3373, "text": "map1 <- ggplot(ldn1.wgs84) + geom_polygon(aes(x = long, y = lat, group = group), fill = “white”, colour = “black”)map1 + labs(x = “Longitude”, y = “Latitude”, title = “Map of Greater London with the borough boundaries”)" }, { "code": null, "e": 3700, "s": 3594, "text": "The next step was to add a layer of all the crime locations and differentiate between the types of crime:" }, { "code": null, "e": 3929, "s": 3700, "text": "map1 + geom_point(data = df, aes(x = Longitude, y = Latitude, colour = Crime.type)) + scale_colour_manual(values = rainbow(14)) + labs(x = “Longitude”, y = “Latitude”, title = “Map of Greater London with the borough boundaries”)" }, { "code": null, "e": 4095, "s": 3929, "text": "In theory this was the objective of this project, however, as it is clear from the above plot that this isn’t ideal as it is far too busy and difficult to interpret." }, { "code": null, "e": 4420, "s": 4095, "text": "I decided to look only at one type of crime for a particular month. Seeing that I enjoy cycling I and wouldn’t ever want my mountain bike stolen, I would like to know whether I should be extra vigilant when parking my bike in certain areas therefore I trimmed the data set to look at bicycle theft for the month of December." }, { "code": null, "e": 4657, "s": 4420, "text": "dec <- df[df$Month == \"2016-12\", ]dec.bike <- dec[dec$Crime.type == “Bicycle theft”, ]map1 + geom_point(data = dec.bike, aes(x = Longitude, y = Latitude), colour = \"red\") + labs(title = \"Bicycle theft in Greater London - December 2016\")" }, { "code": null, "e": 4809, "s": 4657, "text": "This produced a more visually appeasing plot that could be interpreted. As expected the crime incidences are concentrated more towards the city center." }, { "code": null, "e": 5020, "s": 4809, "text": "The down-side to this is that the amount of insight one can gain is limited to one type of crime for one month of the year, while there are another 13 types of crime and the other months of the year to look at." }, { "code": null, "e": 5419, "s": 5020, "text": "The objective of this project was to explore the GIS packages available in R and use these to plot some points on a map. This was achieved using data obtained from the UK police website for different types of crimes and their locations for the year of 2016. By trimming the data to look at one specific type of crime, in this case bicycle theft for one month it became easier to interpret the plot." }, { "code": null, "e": 5520, "s": 5419, "text": "This project was a great learning experience and demonstrated the usefulness of R as a tool for GIS." } ]
Linear Regression: Moneyball — Part 1 | by Sayar Banerjee | Towards Data Science
One of the most compelling stories of sports analytics made popular by the 2011 movie Moneyball, the Oakland Athletics team of 2002 created history by winning 20 consecutive games between August 13 and September 2002. Much of the Oakland Athletics (popularly referred to as the A’s) success in that season is attributed to their General Manager, Billy Beane and former Assistant General Manager, Paul DePodesta. DePodesta, a graduate in Economics from Harvard University joined the A’s in 1999 and quickly started incorporating analysis of baseball statistics to value and purchase players.(Sabermetrics) This approach came into the limelight following the historical 2002 season when Billy Beane purchased vastly undervalued players to supplant the departure of key players prior to the start of the season. Due to severe budgetary constraints of the Oakland Athletics, Billy resorted to the methods being researched by DePodesta in order to purchase underrated players to meet the California based team’s payroll. This article attempts to recreate portions of Paul DePodesta’s analysis in order to demonstrate the power of the simplest supervised learning technique a.k.a Linear Regression. This analysis is very similar to the case study in MIT’s Analytics Edge course on edX. However, my programming language of choice for the article is Python as opposed to R which was used in the aforementioned course. Linear regression is a supervised learning algorithm in machine learning that had it’s origins from statistical principles. It is primarily used to model the relationship between an explanatory variable usually y, with one or more independent variables denoted by X. When there is only one independent variable used to predict y, it is known as Simple Linear Regression or Linear Regression whereas when there are multiple independent variables, it is known as Multiple Linear Regression. The β terms called regression coefficients refer to the relationship between the x variable and the dependent variable y. Let us use an example to illustrate this. Equation: Price of house in $= 50000+1.35×(Size of house in sqft)+ ε The above equation is an example of a regression function used to determine price of houses given their size in square feet. 1.35 is the value of β which denotes that for every 1 sqft increase in the size of the house , there is a $1.35 increase in the price of the house. If the value of β were -1.35 then for every 1 sqft increase in house size, there would be a $1.35 unit decrease in the price of the house. The error term ε is used to denote the residuals or the difference between the actual values and predicted values of Y. It tells us how far off our predictions are from the actual value. Residuals formula: ε = y — ŷ where y denotes the actual values and ŷ denotes the value of y predicted by our model. I will not go into the explicit details of how the β values are calculated, how the model is optimised. Instead, lets jump right into the model building framework. The dataset I have used is the Moneyball dataset from Kaggle which was gathered from baseball-reference.com. The data is read into python using the pandas library. df = pd.read_csv("baseball.csv")df.head() We need to define a few of the terms here: RA stands for runs allowed. RS stand for runs scored. OBP stands for On Base Percentage. SLG stand for Slugging Percentage. BA is Batting Average. OOBP is opponent’s OBP. OSLG is opponent’s SLG. W stands for number of wins in that season. A new variable RD is added as the difference between RS and RA. Additionally, we shall only keep records with Year < 2002 in order to replicate the data prior to the 2002 season. We will use plots in order to find insights regarding the distributions of the numerical variables. Observe that all four features(variables) are approximately normally distributed. Both, the runs scored and runs allowed graph seems to be skewed slightly towards the left. The tails of the runs scored graph seems to be thicker than that of the runs allowed graph. According to DePodesta’s character in the clip, the A’s required at least 99 wins in order to make the playoffs in 2002. Lets try to visualise this insight. # Plotting scatterplotplt.figure(figsize=(10,8))plt.scatter(x=moneyball0.W,y = moneyball0.RS,c="red")plt.scatter(x=moneyball1.W,y = moneyball1.RS,c="blue")plt.xlabel("Wins")plt.ylabel("Runs Scored")plt.axvline(x = 99) From the above plot we see that DePodesta’s estimate of 99 wins makes sense since there appears to be only 3 observations (red) who haven’t made it to the playoffs with ≥ 99 wins. DePodesta also calculated that the A’s need to score atleast 814 runs and allow only 645 runs in order to make it to the postseason. That meant that the difference between runs scored and runs allowed needed to be approximately 169(RD). Let us look at the relationship between RD and Wins. x = np.array(moneyball.RD)y = np.array(moneyball.W)# Deriving slope,intercept valuesslope, intercept = np.polyfit(x, y, 1)abline_values = [slope * i + intercept for i in x]#Plotting the figureplt.figure(figsize=(10,8))plt.scatter(x, y)plt.plot(x, abline_values, 'b')plt.title("Slope = %s" % (slope))plt.xlabel("Run Difference")plt.ylabel("Wins")plt.show() We can clearly see that the relationship between the two variables is linear. print(np.corrcoef(x,y))output:[[ 1. 0.93851498] [ 0.93851498 1. ]] Additionally, there is a strong correlation of 0.9385 between RD and number of wins. Thus, our exploratory data analysis confirms that DePodesta’s estimates have been spot on so far. In the next part of the study we shall build regression models to further validate DePodesta’s analysis. Stay tuned for Part 2.
[ { "code": null, "e": 390, "s": 172, "text": "One of the most compelling stories of sports analytics made popular by the 2011 movie Moneyball, the Oakland Athletics team of 2002 created history by winning 20 consecutive games between August 13 and September 2002." }, { "code": null, "e": 584, "s": 390, "text": "Much of the Oakland Athletics (popularly referred to as the A’s) success in that season is attributed to their General Manager, Billy Beane and former Assistant General Manager, Paul DePodesta." }, { "code": null, "e": 777, "s": 584, "text": "DePodesta, a graduate in Economics from Harvard University joined the A’s in 1999 and quickly started incorporating analysis of baseball statistics to value and purchase players.(Sabermetrics)" }, { "code": null, "e": 1188, "s": 777, "text": "This approach came into the limelight following the historical 2002 season when Billy Beane purchased vastly undervalued players to supplant the departure of key players prior to the start of the season. Due to severe budgetary constraints of the Oakland Athletics, Billy resorted to the methods being researched by DePodesta in order to purchase underrated players to meet the California based team’s payroll." }, { "code": null, "e": 1365, "s": 1188, "text": "This article attempts to recreate portions of Paul DePodesta’s analysis in order to demonstrate the power of the simplest supervised learning technique a.k.a Linear Regression." }, { "code": null, "e": 1582, "s": 1365, "text": "This analysis is very similar to the case study in MIT’s Analytics Edge course on edX. However, my programming language of choice for the article is Python as opposed to R which was used in the aforementioned course." }, { "code": null, "e": 2071, "s": 1582, "text": "Linear regression is a supervised learning algorithm in machine learning that had it’s origins from statistical principles. It is primarily used to model the relationship between an explanatory variable usually y, with one or more independent variables denoted by X. When there is only one independent variable used to predict y, it is known as Simple Linear Regression or Linear Regression whereas when there are multiple independent variables, it is known as Multiple Linear Regression." }, { "code": null, "e": 2235, "s": 2071, "text": "The β terms called regression coefficients refer to the relationship between the x variable and the dependent variable y. Let us use an example to illustrate this." }, { "code": null, "e": 2245, "s": 2235, "text": "Equation:" }, { "code": null, "e": 2304, "s": 2245, "text": "Price of house in $= 50000+1.35×(Size of house in sqft)+ ε" }, { "code": null, "e": 2429, "s": 2304, "text": "The above equation is an example of a regression function used to determine price of houses given their size in square feet." }, { "code": null, "e": 2716, "s": 2429, "text": "1.35 is the value of β which denotes that for every 1 sqft increase in the size of the house , there is a $1.35 increase in the price of the house. If the value of β were -1.35 then for every 1 sqft increase in house size, there would be a $1.35 unit decrease in the price of the house." }, { "code": null, "e": 2903, "s": 2716, "text": "The error term ε is used to denote the residuals or the difference between the actual values and predicted values of Y. It tells us how far off our predictions are from the actual value." }, { "code": null, "e": 2922, "s": 2903, "text": "Residuals formula:" }, { "code": null, "e": 2933, "s": 2922, "text": "ε = y — ŷ" }, { "code": null, "e": 3021, "s": 2933, "text": "where y denotes the actual values and ŷ denotes the value of y predicted by our model." }, { "code": null, "e": 3185, "s": 3021, "text": "I will not go into the explicit details of how the β values are calculated, how the model is optimised. Instead, lets jump right into the model building framework." }, { "code": null, "e": 3294, "s": 3185, "text": "The dataset I have used is the Moneyball dataset from Kaggle which was gathered from baseball-reference.com." }, { "code": null, "e": 3349, "s": 3294, "text": "The data is read into python using the pandas library." }, { "code": null, "e": 3391, "s": 3349, "text": "df = pd.read_csv(\"baseball.csv\")df.head()" }, { "code": null, "e": 3434, "s": 3391, "text": "We need to define a few of the terms here:" }, { "code": null, "e": 3462, "s": 3434, "text": "RA stands for runs allowed." }, { "code": null, "e": 3488, "s": 3462, "text": "RS stand for runs scored." }, { "code": null, "e": 3523, "s": 3488, "text": "OBP stands for On Base Percentage." }, { "code": null, "e": 3558, "s": 3523, "text": "SLG stand for Slugging Percentage." }, { "code": null, "e": 3581, "s": 3558, "text": "BA is Batting Average." }, { "code": null, "e": 3605, "s": 3581, "text": "OOBP is opponent’s OBP." }, { "code": null, "e": 3629, "s": 3605, "text": "OSLG is opponent’s SLG." }, { "code": null, "e": 3673, "s": 3629, "text": "W stands for number of wins in that season." }, { "code": null, "e": 3737, "s": 3673, "text": "A new variable RD is added as the difference between RS and RA." }, { "code": null, "e": 3852, "s": 3737, "text": "Additionally, we shall only keep records with Year < 2002 in order to replicate the data prior to the 2002 season." }, { "code": null, "e": 3952, "s": 3852, "text": "We will use plots in order to find insights regarding the distributions of the numerical variables." }, { "code": null, "e": 4217, "s": 3952, "text": "Observe that all four features(variables) are approximately normally distributed. Both, the runs scored and runs allowed graph seems to be skewed slightly towards the left. The tails of the runs scored graph seems to be thicker than that of the runs allowed graph." }, { "code": null, "e": 4374, "s": 4217, "text": "According to DePodesta’s character in the clip, the A’s required at least 99 wins in order to make the playoffs in 2002. Lets try to visualise this insight." }, { "code": null, "e": 4592, "s": 4374, "text": "# Plotting scatterplotplt.figure(figsize=(10,8))plt.scatter(x=moneyball0.W,y = moneyball0.RS,c=\"red\")plt.scatter(x=moneyball1.W,y = moneyball1.RS,c=\"blue\")plt.xlabel(\"Wins\")plt.ylabel(\"Runs Scored\")plt.axvline(x = 99)" }, { "code": null, "e": 4772, "s": 4592, "text": "From the above plot we see that DePodesta’s estimate of 99 wins makes sense since there appears to be only 3 observations (red) who haven’t made it to the playoffs with ≥ 99 wins." }, { "code": null, "e": 5062, "s": 4772, "text": "DePodesta also calculated that the A’s need to score atleast 814 runs and allow only 645 runs in order to make it to the postseason. That meant that the difference between runs scored and runs allowed needed to be approximately 169(RD). Let us look at the relationship between RD and Wins." }, { "code": null, "e": 5418, "s": 5062, "text": "x = np.array(moneyball.RD)y = np.array(moneyball.W)# Deriving slope,intercept valuesslope, intercept = np.polyfit(x, y, 1)abline_values = [slope * i + intercept for i in x]#Plotting the figureplt.figure(figsize=(10,8))plt.scatter(x, y)plt.plot(x, abline_values, 'b')plt.title(\"Slope = %s\" % (slope))plt.xlabel(\"Run Difference\")plt.ylabel(\"Wins\")plt.show()" }, { "code": null, "e": 5496, "s": 5418, "text": "We can clearly see that the relationship between the two variables is linear." }, { "code": null, "e": 5580, "s": 5496, "text": "print(np.corrcoef(x,y))output:[[ 1. 0.93851498] [ 0.93851498 1. ]]" }, { "code": null, "e": 5665, "s": 5580, "text": "Additionally, there is a strong correlation of 0.9385 between RD and number of wins." }, { "code": null, "e": 5868, "s": 5665, "text": "Thus, our exploratory data analysis confirms that DePodesta’s estimates have been spot on so far. In the next part of the study we shall build regression models to further validate DePodesta’s analysis." } ]
JSF - ui:remove Tag
ui:remove tag is used to prevent the JSF specific code to be rendered on the client side. It is used especially to prevent commented out code to be rendered on the client side. <!-- JSF code commented out --> <!-- <h:commandButton value = "Ok" /> --> <!-- JSF code commented out --> <!-- &lt;h:commandButton value = "Ok" /&gt; --> Now using remove tag we'll see the following change in rendered output. <!-- JSF code commented out --> <ui:remove> <h:commandButton value = "Ok" /> </ui:remove> <!-- JSF code commented out --> Let us create a test JSF application to test the template tags in JSF. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> <h:head> <title>JSF tutorial</title> </h:head> <h:body> <ui:remove> <h:commandButton value = "Ok" /> </ui:remove> <!-- <h:commandButton value = "Cancel" /> --> </h:body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, you'll see an empty page. View source of the page and you will see the following html text. <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml"> <head> <title>JSF tutorial</title> </head> <body> <!-- &lt;h:commandButton value = "Cancel" /&gt; --> </body> </html> 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2129, "s": 1952, "text": "ui:remove tag is used to prevent the JSF specific code to be rendered on the client side. It is used especially to prevent commented out code to be rendered on the client side." }, { "code": null, "e": 2207, "s": 2129, "text": "<!-- JSF code commented out -->\n<!-- \n<h:commandButton value = \"Ok\" /> \n-->\n" }, { "code": null, "e": 2291, "s": 2207, "text": "<!-- JSF code commented out -->\n<!-- \n&lt;h:commandButton value = \"Ok\" /&gt; \n-->\n" }, { "code": null, "e": 2363, "s": 2291, "text": "Now using remove tag we'll see the following change in rendered output." }, { "code": null, "e": 2458, "s": 2363, "text": "<!-- JSF code commented out -->\n<ui:remove>\n <h:commandButton value = \"Ok\" /> \n</ui:remove>" }, { "code": null, "e": 2491, "s": 2458, "text": "<!-- JSF code commented out -->\n" }, { "code": null, "e": 2562, "s": 2491, "text": "Let us create a test JSF application to test the template tags in JSF." }, { "code": null, "e": 3133, "s": 2562, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:ui = \"http://java.sun.com/jsf/facelets\">\n \n <h:head>\n <title>JSF tutorial</title>\t\t\t\n </h:head>\n \n <h:body>\t\n <ui:remove>\n <h:commandButton value = \"Ok\" /> \n </ui:remove>\n \n <!--\n <h:commandButton value = \"Cancel\" /> \n -->\n </h:body> \n</html>" }, { "code": null, "e": 3335, "s": 3133, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, you'll see an empty page." }, { "code": null, "e": 3401, "s": 3335, "text": "View source of the page and you will see the following html text." }, { "code": null, "e": 3776, "s": 3401, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\">\n <head>\n <title>JSF tutorial</title>\n </head>\n \n <body>\n <!--\n &lt;h:commandButton value = \"Cancel\" /&gt; \n -->\n </body>\n</html>" }, { "code": null, "e": 3811, "s": 3776, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3826, "s": 3811, "text": " Chaand Sheikh" }, { "code": null, "e": 3833, "s": 3826, "text": " Print" }, { "code": null, "e": 3844, "s": 3833, "text": " Add Notes" } ]
SQLAlchemy ORM - Creating Session
In order to interact with the database, we need to obtain its handle. A session object is the handle to database. Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine object created earlier. from sqlalchemy.orm import sessionmaker Session = sessionmaker(bind = engine) The session object is then set up using its default constructor as follows − session = Session() Some of the frequently required methods of session class are listed below − begin() begins a transaction on this session add() places an object in the session. Its state is persisted in the database on next flush operation add_all() adds a collection of objects to the session commit() flushes all items and any transaction in progress delete() marks a transaction as deleted execute() executes a SQL expression expire() marks attributes of an instance as out of date flush() flushes all object changes to the database invalidate() closes the session using connection invalidation rollback() rolls back the current transaction in progress close() Closes current session by clearing all items and ending any transaction in progress 21 Lectures 1.5 hours Jack Chan Print Add Notes Bookmark this page
[ { "code": null, "e": 2593, "s": 2340, "text": "In order to interact with the database, we need to obtain its handle. A session object is the handle to database. Session class is defined using sessionmaker() – a configurable session factory method which is bound to the engine object created earlier." }, { "code": null, "e": 2671, "s": 2593, "text": "from sqlalchemy.orm import sessionmaker\nSession = sessionmaker(bind = engine)" }, { "code": null, "e": 2748, "s": 2671, "text": "The session object is then set up using its default constructor as follows −" }, { "code": null, "e": 2768, "s": 2748, "text": "session = Session()" }, { "code": null, "e": 2844, "s": 2768, "text": "Some of the frequently required methods of session class are listed below −" }, { "code": null, "e": 2852, "s": 2844, "text": "begin()" }, { "code": null, "e": 2889, "s": 2852, "text": "begins a transaction on this session" }, { "code": null, "e": 2895, "s": 2889, "text": "add()" }, { "code": null, "e": 2991, "s": 2895, "text": "places an object in the session. Its state is persisted in the database on next flush operation" }, { "code": null, "e": 3001, "s": 2991, "text": "add_all()" }, { "code": null, "e": 3045, "s": 3001, "text": "adds a collection of objects to the session" }, { "code": null, "e": 3054, "s": 3045, "text": "commit()" }, { "code": null, "e": 3104, "s": 3054, "text": "flushes all items and any transaction in progress" }, { "code": null, "e": 3113, "s": 3104, "text": "delete()" }, { "code": null, "e": 3144, "s": 3113, "text": "marks a transaction as deleted" }, { "code": null, "e": 3154, "s": 3144, "text": "execute()" }, { "code": null, "e": 3180, "s": 3154, "text": "executes a SQL expression" }, { "code": null, "e": 3189, "s": 3180, "text": "expire()" }, { "code": null, "e": 3236, "s": 3189, "text": "marks attributes of an instance as out of date" }, { "code": null, "e": 3244, "s": 3236, "text": "flush()" }, { "code": null, "e": 3287, "s": 3244, "text": "flushes all object changes to the database" }, { "code": null, "e": 3300, "s": 3287, "text": "invalidate()" }, { "code": null, "e": 3349, "s": 3300, "text": "closes the session using connection invalidation" }, { "code": null, "e": 3360, "s": 3349, "text": "rollback()" }, { "code": null, "e": 3407, "s": 3360, "text": "rolls back the current transaction in progress" }, { "code": null, "e": 3415, "s": 3407, "text": "close()" }, { "code": null, "e": 3499, "s": 3415, "text": "Closes current session by clearing all items and ending any transaction in progress" }, { "code": null, "e": 3534, "s": 3499, "text": "\n 21 Lectures \n 1.5 hours \n" }, { "code": null, "e": 3545, "s": 3534, "text": " Jack Chan" }, { "code": null, "e": 3552, "s": 3545, "text": " Print" }, { "code": null, "e": 3563, "s": 3552, "text": " Add Notes" } ]
GridSearch VS RandomizedSearch VS BayesSearch | by Jay Hui | Towards Data Science
You may know optimization algorithms (GridSearch, RandomizedSearch or even BayesianSearch) for tuning hyper-parameters in the machine learning model. So which one should you use it? And how to use it? In this post, I am going to give a tutorial with real code demo and comparison: www.kaggle.com We set up our tutorial as follow: Noted that the GridSearchCV, RandomizedSearch (in sci-kit learn) and BayesSearchCV (in Skopt, sci-kit learn optimization) are modelling optimization implementations. We would like to compare these three algorithms by time (based on Kaggle’s kernel) and accuracy. Here are the implementations of these three algorithms: best score of Grid Search over 120 iterations: 0.504CPU times: user 823 ms, sys: 62.1 ms, total: 885 ms best score of Randomized Search over 120 iterations: 0.708CPU times: user 876 ms, sys: 23.2 ms, total: 899 ms Noted that the input range the ”uniform” is (loc, loc + scale). best score of Bayes Search over 60 iterations: 0.728CPU times: user 2min 7s, sys: 2.11 s, total: 2min 9s Noted that the input range of the ”Real” is [lower bound, upper bound]. So based on the result, you can see BayesSearch provides the best result, even it only needs 60 iterations, while GridSearch and RandomizedSearch are searching for 120 iterations, but BayesSearch needs much more time. So, what can we learn from this simple experiment? RandomizedSearch defeats GridSearch RandomizedSearch defeats GridSearch For GridSearch and RandomizedSearch, you should always use RandomSearch as RandomSearch performs better (search time should be similar). The reason is that RandomSearch can easily and efficiently find the optimized values across important parameters. To illustrate it, consider the above picture with 1 important parameter and 1 unimportant parameter. With 3x3 = 9 combinations of GridSearch, actually, it only searches 3 different values for the important parameter in 9 iterations. However, for Randomized Search, it can search 9 different values for the 9 iterations. As a result, it is much easier for RandomizedSearch to search for the important parameters. 2. BayesSearch VS RandomizedSearch As RandomizedSearch searches for the parameters randomly, what if we search it intentionally and directionally with the idea similar to Gradient Descent? So what we can further improve it is to consider the conditional probability (bases’ rule) to search for the parameters more wisely. Since BasesSearch includes few computations for the conditional probability, for a small dataset, BayesSearch will take more time than the RandomizedSearch. Still, with a huge dataset, BayesSearch should have better performance than the RandomizedSearch given complex parameter search distributions and enough iterations. Let us do one more experiment with a larger dataset: best score of Randomized Search over 10 iterations: 0.91944CPU times: user 22.9 s, sys: 157 ms, total: 23.1 s best score of Bayes Search over 10 iterations: 0.95512CPU times: user 1min 28s, sys: 749 ms, total: 1min 28s In the first experiment with the small dataset, the time ratio between BayesSearch and RandomizedSearch is 129/0.9 = 143x. For the second experiment with the large dataset, the ratio now reduces to 88/23.1 = 3.81x. In conclusion, based on the theory and computation experiments, we suggest the following: You should choose RandomizedSearch over GridSearch. (Unless you just want to tune very few hyper-parameters.)For a huge dataset (≥ 100,000 records with more than 100 features), BayesSearch can search the optimal set of hype-parameters more efficiently. You should choose RandomizedSearch over GridSearch. (Unless you just want to tune very few hyper-parameters.) For a huge dataset (≥ 100,000 records with more than 100 features), BayesSearch can search the optimal set of hype-parameters more efficiently.
[ { "code": null, "e": 453, "s": 172, "text": "You may know optimization algorithms (GridSearch, RandomizedSearch or even BayesianSearch) for tuning hyper-parameters in the machine learning model. So which one should you use it? And how to use it? In this post, I am going to give a tutorial with real code demo and comparison:" }, { "code": null, "e": 468, "s": 453, "text": "www.kaggle.com" }, { "code": null, "e": 502, "s": 468, "text": "We set up our tutorial as follow:" }, { "code": null, "e": 765, "s": 502, "text": "Noted that the GridSearchCV, RandomizedSearch (in sci-kit learn) and BayesSearchCV (in Skopt, sci-kit learn optimization) are modelling optimization implementations. We would like to compare these three algorithms by time (based on Kaggle’s kernel) and accuracy." }, { "code": null, "e": 821, "s": 765, "text": "Here are the implementations of these three algorithms:" }, { "code": null, "e": 925, "s": 821, "text": "best score of Grid Search over 120 iterations: 0.504CPU times: user 823 ms, sys: 62.1 ms, total: 885 ms" }, { "code": null, "e": 1035, "s": 925, "text": "best score of Randomized Search over 120 iterations: 0.708CPU times: user 876 ms, sys: 23.2 ms, total: 899 ms" }, { "code": null, "e": 1099, "s": 1035, "text": "Noted that the input range the ”uniform” is (loc, loc + scale)." }, { "code": null, "e": 1204, "s": 1099, "text": "best score of Bayes Search over 60 iterations: 0.728CPU times: user 2min 7s, sys: 2.11 s, total: 2min 9s" }, { "code": null, "e": 1276, "s": 1204, "text": "Noted that the input range of the ”Real” is [lower bound, upper bound]." }, { "code": null, "e": 1494, "s": 1276, "text": "So based on the result, you can see BayesSearch provides the best result, even it only needs 60 iterations, while GridSearch and RandomizedSearch are searching for 120 iterations, but BayesSearch needs much more time." }, { "code": null, "e": 1545, "s": 1494, "text": "So, what can we learn from this simple experiment?" }, { "code": null, "e": 1581, "s": 1545, "text": "RandomizedSearch defeats GridSearch" }, { "code": null, "e": 1617, "s": 1581, "text": "RandomizedSearch defeats GridSearch" }, { "code": null, "e": 1868, "s": 1617, "text": "For GridSearch and RandomizedSearch, you should always use RandomSearch as RandomSearch performs better (search time should be similar). The reason is that RandomSearch can easily and efficiently find the optimized values across important parameters." }, { "code": null, "e": 2280, "s": 1868, "text": "To illustrate it, consider the above picture with 1 important parameter and 1 unimportant parameter. With 3x3 = 9 combinations of GridSearch, actually, it only searches 3 different values for the important parameter in 9 iterations. However, for Randomized Search, it can search 9 different values for the 9 iterations. As a result, it is much easier for RandomizedSearch to search for the important parameters." }, { "code": null, "e": 2315, "s": 2280, "text": "2. BayesSearch VS RandomizedSearch" }, { "code": null, "e": 2602, "s": 2315, "text": "As RandomizedSearch searches for the parameters randomly, what if we search it intentionally and directionally with the idea similar to Gradient Descent? So what we can further improve it is to consider the conditional probability (bases’ rule) to search for the parameters more wisely." }, { "code": null, "e": 2924, "s": 2602, "text": "Since BasesSearch includes few computations for the conditional probability, for a small dataset, BayesSearch will take more time than the RandomizedSearch. Still, with a huge dataset, BayesSearch should have better performance than the RandomizedSearch given complex parameter search distributions and enough iterations." }, { "code": null, "e": 2977, "s": 2924, "text": "Let us do one more experiment with a larger dataset:" }, { "code": null, "e": 3087, "s": 2977, "text": "best score of Randomized Search over 10 iterations: 0.91944CPU times: user 22.9 s, sys: 157 ms, total: 23.1 s" }, { "code": null, "e": 3196, "s": 3087, "text": "best score of Bayes Search over 10 iterations: 0.95512CPU times: user 1min 28s, sys: 749 ms, total: 1min 28s" }, { "code": null, "e": 3411, "s": 3196, "text": "In the first experiment with the small dataset, the time ratio between BayesSearch and RandomizedSearch is 129/0.9 = 143x. For the second experiment with the large dataset, the ratio now reduces to 88/23.1 = 3.81x." }, { "code": null, "e": 3501, "s": 3411, "text": "In conclusion, based on the theory and computation experiments, we suggest the following:" }, { "code": null, "e": 3754, "s": 3501, "text": "You should choose RandomizedSearch over GridSearch. (Unless you just want to tune very few hyper-parameters.)For a huge dataset (≥ 100,000 records with more than 100 features), BayesSearch can search the optimal set of hype-parameters more efficiently." }, { "code": null, "e": 3864, "s": 3754, "text": "You should choose RandomizedSearch over GridSearch. (Unless you just want to tune very few hyper-parameters.)" } ]
How to get file link from google cloud storage using Node.js ? - GeeksforGeeks
08 Jan, 2021 To get the signed public link of a file from the firebase storage, we need a reference to the file in Google cloud storage. As we just have a path to that file in storage we would first need to create a reference to that object and then get a signed link to that file. Steps to generate a public link to a file in storage using the file path: Get the reference to the storage using a bucket() and file() methods on the storage object from @google-cloud/storage.Generate a signed public link for that file using getSignedUrl method on the reference object created in the first step. Get the reference to the storage using a bucket() and file() methods on the storage object from @google-cloud/storage. Generate a signed public link for that file using getSignedUrl method on the reference object created in the first step. Module Installation: Install the module using the following command: npm install @google-cloud/storage The method getSignedUrl() tasks a config object as input and returns a Promise that resolves with the download URL or rejects if the fetch failed, including if the object did not exist. Example: Filename: index.js Javascript // Imports the Google Cloud client libraryconst {Storage} = require('@google-cloud/storage'); // Creates a clientconst storage = new Storage(); var bucketName = 'geeksforgeeks'; var fileName = 'gfg.png'; // Create a reference to the file to generate linkvar fileRef = storage.bucket(bucketName).file(fileName); fileRef.exists().then(function(data) { console.log("File in database exists ");}); const config = { action: 'read', // A timestamp when this link will expire expires: '01-01-2026',}; // Get the link to that filefileRef.getSignedUrl(config, function(err, url) { if (err) { console.error(err); return; } // The file is now available to // read from this URL console.log("Url is : " + url);}); Run the index.js file using the following command: node index.js Output: File in database existsUrl is : https://storage.googleapis.com/geeksforgeeks/gfg.png?X-Goog-Algorithm=[token] Node.js-Misc Picked Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Express.js express.Router() Function JWT Authentication with Node.js Express.js req.params Property Mongoose Populate() Method Difference between npm i and npm ci in Node.js Roadmap to Become a Web Developer in 2022 How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills Convert a string to an integer in JavaScript
[ { "code": null, "e": 25002, "s": 24974, "text": "\n08 Jan, 2021" }, { "code": null, "e": 25271, "s": 25002, "text": "To get the signed public link of a file from the firebase storage, we need a reference to the file in Google cloud storage. As we just have a path to that file in storage we would first need to create a reference to that object and then get a signed link to that file." }, { "code": null, "e": 25345, "s": 25271, "text": "Steps to generate a public link to a file in storage using the file path:" }, { "code": null, "e": 25584, "s": 25345, "text": "Get the reference to the storage using a bucket() and file() methods on the storage object from @google-cloud/storage.Generate a signed public link for that file using getSignedUrl method on the reference object created in the first step." }, { "code": null, "e": 25703, "s": 25584, "text": "Get the reference to the storage using a bucket() and file() methods on the storage object from @google-cloud/storage." }, { "code": null, "e": 25824, "s": 25703, "text": "Generate a signed public link for that file using getSignedUrl method on the reference object created in the first step." }, { "code": null, "e": 25893, "s": 25824, "text": "Module Installation: Install the module using the following command:" }, { "code": null, "e": 25927, "s": 25893, "text": "npm install @google-cloud/storage" }, { "code": null, "e": 26113, "s": 25927, "text": "The method getSignedUrl() tasks a config object as input and returns a Promise that resolves with the download URL or rejects if the fetch failed, including if the object did not exist." }, { "code": null, "e": 26142, "s": 26113, "text": "Example: Filename: index.js " }, { "code": null, "e": 26153, "s": 26142, "text": "Javascript" }, { "code": "// Imports the Google Cloud client libraryconst {Storage} = require('@google-cloud/storage'); // Creates a clientconst storage = new Storage(); var bucketName = 'geeksforgeeks'; var fileName = 'gfg.png'; // Create a reference to the file to generate linkvar fileRef = storage.bucket(bucketName).file(fileName); fileRef.exists().then(function(data) { console.log(\"File in database exists \");}); const config = { action: 'read', // A timestamp when this link will expire expires: '01-01-2026',}; // Get the link to that filefileRef.getSignedUrl(config, function(err, url) { if (err) { console.error(err); return; } // The file is now available to // read from this URL console.log(\"Url is : \" + url);});", "e": 26882, "s": 26153, "text": null }, { "code": null, "e": 26933, "s": 26882, "text": "Run the index.js file using the following command:" }, { "code": null, "e": 26947, "s": 26933, "text": "node index.js" }, { "code": null, "e": 26956, "s": 26947, "text": "Output: " }, { "code": null, "e": 27066, "s": 26956, "text": "File in database existsUrl is : https://storage.googleapis.com/geeksforgeeks/gfg.png?X-Goog-Algorithm=[token]" }, { "code": null, "e": 27079, "s": 27066, "text": "Node.js-Misc" }, { "code": null, "e": 27086, "s": 27079, "text": "Picked" }, { "code": null, "e": 27094, "s": 27086, "text": "Node.js" }, { "code": null, "e": 27111, "s": 27094, "text": "Web Technologies" }, { "code": null, "e": 27209, "s": 27111, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27246, "s": 27209, "text": "Express.js express.Router() Function" }, { "code": null, "e": 27278, "s": 27246, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 27309, "s": 27278, "text": "Express.js req.params Property" }, { "code": null, "e": 27336, "s": 27309, "text": "Mongoose Populate() Method" }, { "code": null, "e": 27383, "s": 27336, "text": "Difference between npm i and npm ci in Node.js" }, { "code": null, "e": 27425, "s": 27383, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27468, "s": 27425, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27518, "s": 27468, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 27580, "s": 27518, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
Python statistics for beginners. A beginners’ guide to Pearson... | by Maurice Henry Buettgenbach | Towards Data Science
All of us have heard the word “correlation” before. Although we might not be sure what it exactly means, we know that it is some kind of indicator of how strong two variables are related to each other. And you know what? That is pretty close to the truth. Correlation itself is a mathematical technique to examine a relationship between two quantitative variables as for example the price of a car and its engine size. So what types of correlation are there? Let us draw some graphs to get a better understanding: # Import working librariesimport pandas as pdimport numpy as np# Positive correlationx = np.arange(start=0, stop=25, step=1)plt.plot(x, 'o')# Negative correlationx = np.arange(start=25, stop=0, step=-1)plt.plot(x, 'o')# No correlationx = np.random.rand(25)plt.plot(x, 'o') Positive correlation indicates that two variables will move in the same direction. In other words, if one variable increases, the other will increase as well, and if one variable decreases the other decreases equivalently. A positive correlation can be illustrated as follows: A negative correlation is a relationship between two variables in which the increase in one variable leads to a decrease in the other. A good example of a negative correlation is the amount of oxygen to altitude. With an increase in altitude, the oxygen levels in the air will decrease (a common problem for extreme mountaineers). A negative correlation looks like this: And last but not least, the third form: No correlation. In this case, the data plots are completely random and do not show any sign of correlation. No correlation can be illustrated like this: Now, correlation comes in different forms. It can be linear, non-linear, or monotonic. Let us draw some more plots to illustrate the differences: # Import additional working librariesimport seaborn as sns# Linear correlation plotdata1 = 20 * np.random.random(100) + 100data2 = data1 + (10 * np.random.random(100) + 50)sns.regplot(x=data1, y=data2)# Non-linear correlation plotx = np.arange(0, 10, 0.1)ytrue = np.exp(-x / 10000) + 2 * np.sin(x / 3)y = ytrue + np.random.normal(size=len(x))sns.regplot(x, y, lowess=True)# Monotonic non-linear correlation plotdef f(x, a, b, c, d): return a / (1. + np.exp(-c * (x - d))) + ba, c = np.random.exponential(size=2)b, d = np.random.randn(2)n = 100x = np.linspace(-10., 10., n)y_model = f(x, a, b, c, d)y = y_model + a * .2 * np.random.randn(n)sns.scatterplot(x, y)sns.lineplot(x, y_model) A linear correlation is a trend in the data where both variables change at a constant rate. For example, suppose a car dealer wants to estimate the impact of fuel consumption on car prices. They find that for every additional liter of fuel consumption the price of cars decreases by $1000. This describes a linear relationship between fuel consumption and car prices where car prices are influenced by fuel consumption at the constant rate of $1000. A linear correlation can be identified by a straight line: A correlation is non-linear when the two variables do not change at a constant rate. In result, the relationship between the variables does not graph as a straight line but causes a somewhat curved pattern in the data. The following graph illustrates how that can look like: Similar to a linear relationship both variables in a monotonic relationship will move in the same direction. However, the variables do not necessarily have to move at a constant rate. The next plot shows this behavior where both variables are concurrently increasing but not at the same rate. Graphing the data and its relationship helps us to determine which type of correlation we are confronted with and which form it has. However, it doesn’t tell us how strong the correlation we are looking at actually is. To quantify the relationship between the two variables, we need to calculate the correlation coefficient. The correlation coefficient is a statistical measure that quantifies the relationship between two variables. The coefficient’s value ranges between -1.0 and 1.0 while a calculated number larger than 1.0 indicates an error in the function. A coefficient of -1.0 shows a perfect negative correlation and 1.0 a perfect positive correlation. A coefficient of 0.0 on the other hand means that there is no relationship between the two variables. There are many different ways to calculate the correlation coefficient of two variables. The most common one is the so-called Pearson’s correlation coefficient (r). It is a test to measure the strength of a linear relation between two normally distributed variables. If the data is not normally distributed, the Kendall and Spearman tests can be used. Since (r) is ranging between -1.0 and 1.0, its interpretation can become difficult when approaching zero. There are many rules of thumb on how to interpret the different values of (r) but the probably most common one was published in 2003 by Dennis E. Hinkle and his co-authors within their introductory text for applied statistics for behavioral sciences. It was designed to teach students and provided a rule of thumb for interpreting the size of a correlation coefficient: By measuring the (r) value we have quantified how strong the relationship between the two variables is. But that only tells us half the story right? The reason for that is that the correlation coefficient we have calculated only represents a sample and not the entire population. So while we know how the correlation looks like in our sample, we cannot be sure whether the correlation we have quantified is representative of the entire population. We are therefore now going to conduct a statistical significance test that can tell us whether our observation can be expected to be true in the entire population or not. Let us set up our test step by step: In hypothesis testing, we always have to formulate two hypotheses. One is called the null hypothesis while the other one is called the alternative hypothesis. They usually state opposite outcomes: The null hypothesis (Ho) is the hypothesis that we are trying to disprove. In our case, it is the hypothesis that there is not a significant linear correlation between the two variables in the given population. The alternative hypothesis (Ha) is the hypothesis that we try to provide evidence for. In this example, we will try to prove that there is a linear correlation in the population. Without going into the heavy math, the T-Test (also called Student’s T-Test) allows us to test an assumption on an entire population. In our case, it will help us to find out whether the correlation we have observed within our sample can be reproduced within the entire population. The T-Test will give us a number (t) that we in turn have to interpret. The higher (t), the higher the likelyhood that the correlation is repeatable within the population. But why is that? Simply put, the T-Test calculates how much two groups differ. In our case, we use the T-test to compare one group with no correlation and one with a proven relationship. If the correlation we have observed occurred due to coincidence, (t) will equal something around 0, indicating that the two populations are the same. However, if the two groups differ significantly, the t-value will be much higher and located at the extremes of the population. This indicates that the correlation we have observed is not due to coincidence and cannot be found in a population with no correlation: # Creating a bell curve for illustration purposesfrom scipy.stats import normx = np.arange(-4, 4, 0.001)y = norm.pdf(x,0,1)fig, ax = plt.subplots(figsize=(9,6))ax.plot(x,y)plt.show() Since (t) is a theoretical test statistic that is depending on the population, we do not know whether the t-value we observe is high or not. In other words, a population with a range from 0 to 1,000 will have other t-values than a population with a range from 0 to 1. To overcome this little problem, every T-Test also calculates the so-called p-value (p). The p-value shows us the probability that we can observe this t-value within the population of Ho. You can also think of it as a game of darts. The higher (p), the higher the chance that your dart lands somewhere near 0 in the graph above. The lower (p), the lower the chances that you will hit the middle. So the lower (p), the more likely it is that our t-value is located at one of the extremes and therefore is “high enough” to indicate a significant difference between our two populations. Or in other words: The lower (p), the higher the probability that our observed correlation has not occurred due to coincidence. Let us get to the final part and look at the last question — how low does (p) need to be? Again, it depends. It depends on the significance level (a) you set for your experiment. The significance level is your threshold for the p-value. Typically, (a) is set to 0.05 or 5%, meaning that a p-value larger than that will lead to accepting the null hypothesis. Or in other words: if you are not 95% sure that the two groups differ significantly, you cannot reject the null hypothesis. Assuming we have received a p-value of 0.002 while we set (a) to 0.05. In this case (p) is below our significance level and we can come to the following conclusion: We can reject Ho in favor of Ha because we have found that the correlation we have observed in our sample can be repeated in a larger population and does not occur by coincidence. But enough of the theory for now — let us look at a real-life example and how to do all that with Python! To work through this tutorial you will need to have the following specs: An editor like VS Code or Spyder Python 3.8.3 or higher The Automobile Data Set from the UCI Machine Learning Depository In this tutorial, we will have a look at the Automobile Data Set provided by the UCI Machine learning Depository. It is a data set that includes technical and price data as well as insurance information for cars from the year 1985. The data set is open source and typically used to train/test regression models. We will perform some formatting on this data set to make it work for us and then explore the correlation of a few variables with the variable price. First, we need to import the libraries we will need to perform our analysis. If you have not installed them yet, please check the respective documentation and do so before executing the below code. # Import working librariesimport pandas as pdimport numpy as npimport seaborn as snsfrom scipy import stats If you have not done it already, please download the “imports-85.data” from the UCI website and save it in your working directory. Please note, that you have to change “.data” to “.csv” to execute the following code. # Load data and show first 5 rowsdf = pd.read_csv("imports-85.csv")df.head(5) Have you noticed — our data set has no headers, and how some values show a question mark? That is something we should fix before we run our correlation analysis as our code otherwise probably won’t work and obtained results might be distorted. Let us in the first step add some column names so that it will be easier for us to understand the data set and work with it. # Add headers to df and display first 5 rowsheaders = ["symboling", "normalized-losses", "make", "fuel-type", "aspiration", "num-of-doors", "body-style", "drive-wheels", "engine-location", "wheel-base", "length", "width", "height", "curb-weight", "engine-type", "num-of-cylinders", "engine-size","fuel-system", "bore", "stroke", "compression-ratio", "horsepower", "peak-rpm", "city-mpg", "highway-mpg", "price"]df.columns = headersdf.head(5) As that seemed to work well, we should now have a look at these question marks in the normalized-losses column. We cannot use them for our further analysis, so we will replace them with NaN values. Note that we will call the pandas.replace function on the whole data frame and not just on the one column. We do that to ensure that we will later not encounter another question mark somewhere else in the data set. # Replace ? with NaN and show first 5 rows of dfdf = df.replace('?',np.NaN)df.head(5) Since we have no overview of where we have missing values now, we should run a quick analysis to find out the NaN values. We can do that by checking the data frame for NaN values first and then print out our analysis using a for loop. # Check df for missing valuesmissing_data = df.isnull()missing_data.head(5) # Run for loop to check for missing valuesfor column in missing_data.columns.values.tolist(): print(column) print (missing_data[column].value_counts()) print("") If you scroll through the analysis, you will find that we have missing values (=True) in the following columns: normalized-losses num-of-doors bore stroke horsepower peak-rpm price Since we need a functioning data set, we have to find a way to deal with the missing data. In general, there are two options. Either we drop columns or rows with missing data or we replace the missing data. Since our data set is not large enough that we can simply drop all rows/columns with missing values, we will replace the missing values with the means of the remaining data. The only exception will be the num-of-doors column as this data is not numerical. Here we will replace the missing data with the most common variant. In this case, that is “four”. # Replacing NaNs with mean / most common variantavg_norm_loss = df["normalized-losses"].astype("float").mean(axis=0)df["normalized-losses"].replace(np.nan, avg_norm_loss, inplace=True)avg_bore = df['bore'].astype('float').mean(axis=0)df["bore"].replace(np.nan, avg_bore, inplace=True)avg_stroke = df['stroke'].astype('float').mean(axis=0)df["stroke"].replace(np.nan, avg_stroke, inplace=True)avg_horsepower = df['horsepower'].astype('float').mean(axis=0)df['horsepower'].replace(np.nan, avg_horsepower, inplace=True)avg_peakrpm = df['peak-rpm'].astype('float').mean(axis=0)df['peak-rpm'].replace(np.nan, avg_peakrpm, inplace=True)avg_price = df['price'].astype('float').mean(axis=0)df['price'].replace(np.nan, avg_price, inplace=True)df["num-of-doors"].replace(np.nan, "four", inplace=True) What’s left? Right! Checking the data forms. We can do that easily by executing the following code: # Checking df typesdf.dtypes As you can see some columns still have the wrong data type (e.g. bore should have integers). So let us correct that quickly: # Format data typesdf[["bore", "stroke"]] = df[["bore", "stroke"]].astype("float")df[["normalized-losses"]] = df[["normalized-losses"]].astype("int")df[["price"]] = df[["price"]].astype("float")df[["peak-rpm"]] = df[["peak-rpm"]].astype("float") There is much more we could do in terms of data standardization and normalization but we do not need that for this tutorial, so let us move on. Let us quickly recap what we want to do: We want to look for variables that have some kind of correlation to the price of cars, right? So we need to first check the type and form of the relationship between the two variables — and the easiest way to do that is to draw some more graphs! To do that we will use the seaborn library and its regplot function. This function will plot the data points and a linear regression line for our selected variables on a 2D graph. While this does not help us to quantify the correlation, it helps us to identify the type and form of the relationship between the two variables. But without further ado, let’s get started and have a look at the price in relation to: Engine size Have a look at the graph below. We can observe that the linear regression line fits the plotted data quite well. We can also observe that the regression line has a steep upwards gradient. But what does that tell us considering type and form of correlation? While the increasing gradient of the regression line shows us that we can expect a positive correlation between the engine size and price, the good fit of the regression line indicates that the variables have a linear correlation. # Create a plot for engine-size and pricesns.regplot(x="engine-size", y="price", data=df) Highway-mpgThe graph below shows us the regression plot for highway miles per gallon (mpg) in relation to the cars’ prices. Here, we can observe that the regression line is decreasing, indicating a negative correlation. However, we can see that that the regression line does not cover the outliers between 0 and 25 on the x-axis. This indicates that linear regression is not a good fit and suggests that the data might be non-linear. # Create a plot for highway-mpg and pricesns.regplot(x="highway-mpg", y="price", data=df)plt.ylim(0,) Peak-rpmThe graph for peak-rpm and price looks different again. We see that the data points have a great variation and the regression line is almost horizontal. Based on that observation we cannot determine what form of correlation we can expect but assuming there is a linear relationship, the nearly-flat regression line indicates that we can expect a correlation coefficient around 0. We would therefore conclude that there is no correlation between peak rpm and price. # Create a plot for peak-rpm and pricesns.regplot(x="peak-rpm", y="price", data=df)plt.ylim(0,) Since it would take ages to look at each variable pair individually, we can shorten the process by using panda’s corr() function: # Using pandas corr() functiondf.corr() As you can see, the corr() function by pandas creates a correlation matrix with all variables contained in our data set. You might ask — why we didn’t do this from the beginning? The answer is relatively simple. While the corr() function calculates by default the Pearson correlation coefficients, it does not give you any information regarding the form of correlation. It can therefore serve you as a great starting point to identify potential high correlations but checking the variable pairs individually will still be necessary. Let us quickly summarize the outcome of our above analysis before we move on: We can expect a positive, linear correlation between engine size and price We have observed a negative correlation between highway-mpg and price that seems to be non-linear. We assume no correlation between peak-rpm and price and we have no reliable information of the form of correlation. We can thus conclude that the variables highway-mpg and peak-rpm seem to be not suitable for conducting a further analysis with the Pearson correlation coefficient. To have a closer look at the engine size, we can compute the Pearson correlation coefficient as well as the p-value with the help of the scipy.stats library. # Calculate pearson coefficient and p-valuepearson_coef, p_value = stats.pearsonr(df['wheel-base'], df['price'])print("The Pearson Correlation Coefficient is", pearson_coef, " with a P-value of P =", p_value) In result, we receive a Pearson correlation coefficient of ~ 0.87 and a p-value of pretty much 0. Since our coefficient is >0.7 but <0.9, we conclude that we are observing a high positive correlation between engine size and price. Finally, we can observe that our p-value is definitely below our significance level (a) of 0.05. We can therefore conclude that the correlation we have calculated above is not a coincidence and therefore significant. This would not be a good tutorial if I would not make the following, famous remark: Correlation does not imply causation. We have learned that correlation is a measure to describe the extent of a relationship between two variables. Causation on the other hand is the relationship between cause and effect between two variables. Even if we have observed a correlation, we cannot conclude that one variable causes a change in the other. Unless we have been able to consider all different variants, we have to assume that there is still a chance for coincidence or that a third factor might be causing both of our variables to change. It is therefore always important to conduct a more comprehensive experiment before drawing final conclusions regarding correlation figures.
[ { "code": null, "e": 428, "s": 172, "text": "All of us have heard the word “correlation” before. Although we might not be sure what it exactly means, we know that it is some kind of indicator of how strong two variables are related to each other. And you know what? That is pretty close to the truth." }, { "code": null, "e": 591, "s": 428, "text": "Correlation itself is a mathematical technique to examine a relationship between two quantitative variables as for example the price of a car and its engine size." }, { "code": null, "e": 686, "s": 591, "text": "So what types of correlation are there? Let us draw some graphs to get a better understanding:" }, { "code": null, "e": 959, "s": 686, "text": "# Import working librariesimport pandas as pdimport numpy as np# Positive correlationx = np.arange(start=0, stop=25, step=1)plt.plot(x, 'o')# Negative correlationx = np.arange(start=25, stop=0, step=-1)plt.plot(x, 'o')# No correlationx = np.random.rand(25)plt.plot(x, 'o')" }, { "code": null, "e": 1236, "s": 959, "text": "Positive correlation indicates that two variables will move in the same direction. In other words, if one variable increases, the other will increase as well, and if one variable decreases the other decreases equivalently. A positive correlation can be illustrated as follows:" }, { "code": null, "e": 1607, "s": 1236, "text": "A negative correlation is a relationship between two variables in which the increase in one variable leads to a decrease in the other. A good example of a negative correlation is the amount of oxygen to altitude. With an increase in altitude, the oxygen levels in the air will decrease (a common problem for extreme mountaineers). A negative correlation looks like this:" }, { "code": null, "e": 1800, "s": 1607, "text": "And last but not least, the third form: No correlation. In this case, the data plots are completely random and do not show any sign of correlation. No correlation can be illustrated like this:" }, { "code": null, "e": 1946, "s": 1800, "text": "Now, correlation comes in different forms. It can be linear, non-linear, or monotonic. Let us draw some more plots to illustrate the differences:" }, { "code": null, "e": 2634, "s": 1946, "text": "# Import additional working librariesimport seaborn as sns# Linear correlation plotdata1 = 20 * np.random.random(100) + 100data2 = data1 + (10 * np.random.random(100) + 50)sns.regplot(x=data1, y=data2)# Non-linear correlation plotx = np.arange(0, 10, 0.1)ytrue = np.exp(-x / 10000) + 2 * np.sin(x / 3)y = ytrue + np.random.normal(size=len(x))sns.regplot(x, y, lowess=True)# Monotonic non-linear correlation plotdef f(x, a, b, c, d): return a / (1. + np.exp(-c * (x - d))) + ba, c = np.random.exponential(size=2)b, d = np.random.randn(2)n = 100x = np.linspace(-10., 10., n)y_model = f(x, a, b, c, d)y = y_model + a * .2 * np.random.randn(n)sns.scatterplot(x, y)sns.lineplot(x, y_model)" }, { "code": null, "e": 3143, "s": 2634, "text": "A linear correlation is a trend in the data where both variables change at a constant rate. For example, suppose a car dealer wants to estimate the impact of fuel consumption on car prices. They find that for every additional liter of fuel consumption the price of cars decreases by $1000. This describes a linear relationship between fuel consumption and car prices where car prices are influenced by fuel consumption at the constant rate of $1000. A linear correlation can be identified by a straight line:" }, { "code": null, "e": 3418, "s": 3143, "text": "A correlation is non-linear when the two variables do not change at a constant rate. In result, the relationship between the variables does not graph as a straight line but causes a somewhat curved pattern in the data. The following graph illustrates how that can look like:" }, { "code": null, "e": 3711, "s": 3418, "text": "Similar to a linear relationship both variables in a monotonic relationship will move in the same direction. However, the variables do not necessarily have to move at a constant rate. The next plot shows this behavior where both variables are concurrently increasing but not at the same rate." }, { "code": null, "e": 4036, "s": 3711, "text": "Graphing the data and its relationship helps us to determine which type of correlation we are confronted with and which form it has. However, it doesn’t tell us how strong the correlation we are looking at actually is. To quantify the relationship between the two variables, we need to calculate the correlation coefficient." }, { "code": null, "e": 4476, "s": 4036, "text": "The correlation coefficient is a statistical measure that quantifies the relationship between two variables. The coefficient’s value ranges between -1.0 and 1.0 while a calculated number larger than 1.0 indicates an error in the function. A coefficient of -1.0 shows a perfect negative correlation and 1.0 a perfect positive correlation. A coefficient of 0.0 on the other hand means that there is no relationship between the two variables." }, { "code": null, "e": 4828, "s": 4476, "text": "There are many different ways to calculate the correlation coefficient of two variables. The most common one is the so-called Pearson’s correlation coefficient (r). It is a test to measure the strength of a linear relation between two normally distributed variables. If the data is not normally distributed, the Kendall and Spearman tests can be used." }, { "code": null, "e": 5304, "s": 4828, "text": "Since (r) is ranging between -1.0 and 1.0, its interpretation can become difficult when approaching zero. There are many rules of thumb on how to interpret the different values of (r) but the probably most common one was published in 2003 by Dennis E. Hinkle and his co-authors within their introductory text for applied statistics for behavioral sciences. It was designed to teach students and provided a rule of thumb for interpreting the size of a correlation coefficient:" }, { "code": null, "e": 5960, "s": 5304, "text": "By measuring the (r) value we have quantified how strong the relationship between the two variables is. But that only tells us half the story right? The reason for that is that the correlation coefficient we have calculated only represents a sample and not the entire population. So while we know how the correlation looks like in our sample, we cannot be sure whether the correlation we have quantified is representative of the entire population. We are therefore now going to conduct a statistical significance test that can tell us whether our observation can be expected to be true in the entire population or not. Let us set up our test step by step:" }, { "code": null, "e": 6157, "s": 5960, "text": "In hypothesis testing, we always have to formulate two hypotheses. One is called the null hypothesis while the other one is called the alternative hypothesis. They usually state opposite outcomes:" }, { "code": null, "e": 6368, "s": 6157, "text": "The null hypothesis (Ho) is the hypothesis that we are trying to disprove. In our case, it is the hypothesis that there is not a significant linear correlation between the two variables in the given population." }, { "code": null, "e": 6547, "s": 6368, "text": "The alternative hypothesis (Ha) is the hypothesis that we try to provide evidence for. In this example, we will try to prove that there is a linear correlation in the population." }, { "code": null, "e": 6829, "s": 6547, "text": "Without going into the heavy math, the T-Test (also called Student’s T-Test) allows us to test an assumption on an entire population. In our case, it will help us to find out whether the correlation we have observed within our sample can be reproduced within the entire population." }, { "code": null, "e": 7018, "s": 6829, "text": "The T-Test will give us a number (t) that we in turn have to interpret. The higher (t), the higher the likelyhood that the correlation is repeatable within the population. But why is that?" }, { "code": null, "e": 7338, "s": 7018, "text": "Simply put, the T-Test calculates how much two groups differ. In our case, we use the T-test to compare one group with no correlation and one with a proven relationship. If the correlation we have observed occurred due to coincidence, (t) will equal something around 0, indicating that the two populations are the same." }, { "code": null, "e": 7602, "s": 7338, "text": "However, if the two groups differ significantly, the t-value will be much higher and located at the extremes of the population. This indicates that the correlation we have observed is not due to coincidence and cannot be found in a population with no correlation:" }, { "code": null, "e": 7785, "s": 7602, "text": "# Creating a bell curve for illustration purposesfrom scipy.stats import normx = np.arange(-4, 4, 0.001)y = norm.pdf(x,0,1)fig, ax = plt.subplots(figsize=(9,6))ax.plot(x,y)plt.show()" }, { "code": null, "e": 8142, "s": 7785, "text": "Since (t) is a theoretical test statistic that is depending on the population, we do not know whether the t-value we observe is high or not. In other words, a population with a range from 0 to 1,000 will have other t-values than a population with a range from 0 to 1. To overcome this little problem, every T-Test also calculates the so-called p-value (p)." }, { "code": null, "e": 8449, "s": 8142, "text": "The p-value shows us the probability that we can observe this t-value within the population of Ho. You can also think of it as a game of darts. The higher (p), the higher the chance that your dart lands somewhere near 0 in the graph above. The lower (p), the lower the chances that you will hit the middle." }, { "code": null, "e": 8765, "s": 8449, "text": "So the lower (p), the more likely it is that our t-value is located at one of the extremes and therefore is “high enough” to indicate a significant difference between our two populations. Or in other words: The lower (p), the higher the probability that our observed correlation has not occurred due to coincidence." }, { "code": null, "e": 8855, "s": 8765, "text": "Let us get to the final part and look at the last question — how low does (p) need to be?" }, { "code": null, "e": 9247, "s": 8855, "text": "Again, it depends. It depends on the significance level (a) you set for your experiment. The significance level is your threshold for the p-value. Typically, (a) is set to 0.05 or 5%, meaning that a p-value larger than that will lead to accepting the null hypothesis. Or in other words: if you are not 95% sure that the two groups differ significantly, you cannot reject the null hypothesis." }, { "code": null, "e": 9412, "s": 9247, "text": "Assuming we have received a p-value of 0.002 while we set (a) to 0.05. In this case (p) is below our significance level and we can come to the following conclusion:" }, { "code": null, "e": 9592, "s": 9412, "text": "We can reject Ho in favor of Ha because we have found that the correlation we have observed in our sample can be repeated in a larger population and does not occur by coincidence." }, { "code": null, "e": 9698, "s": 9592, "text": "But enough of the theory for now — let us look at a real-life example and how to do all that with Python!" }, { "code": null, "e": 9771, "s": 9698, "text": "To work through this tutorial you will need to have the following specs:" }, { "code": null, "e": 9804, "s": 9771, "text": "An editor like VS Code or Spyder" }, { "code": null, "e": 9827, "s": 9804, "text": "Python 3.8.3 or higher" }, { "code": null, "e": 9892, "s": 9827, "text": "The Automobile Data Set from the UCI Machine Learning Depository" }, { "code": null, "e": 10204, "s": 9892, "text": "In this tutorial, we will have a look at the Automobile Data Set provided by the UCI Machine learning Depository. It is a data set that includes technical and price data as well as insurance information for cars from the year 1985. The data set is open source and typically used to train/test regression models." }, { "code": null, "e": 10353, "s": 10204, "text": "We will perform some formatting on this data set to make it work for us and then explore the correlation of a few variables with the variable price." }, { "code": null, "e": 10551, "s": 10353, "text": "First, we need to import the libraries we will need to perform our analysis. If you have not installed them yet, please check the respective documentation and do so before executing the below code." }, { "code": null, "e": 10659, "s": 10551, "text": "# Import working librariesimport pandas as pdimport numpy as npimport seaborn as snsfrom scipy import stats" }, { "code": null, "e": 10876, "s": 10659, "text": "If you have not done it already, please download the “imports-85.data” from the UCI website and save it in your working directory. Please note, that you have to change “.data” to “.csv” to execute the following code." }, { "code": null, "e": 10954, "s": 10876, "text": "# Load data and show first 5 rowsdf = pd.read_csv(\"imports-85.csv\")df.head(5)" }, { "code": null, "e": 11198, "s": 10954, "text": "Have you noticed — our data set has no headers, and how some values show a question mark? That is something we should fix before we run our correlation analysis as our code otherwise probably won’t work and obtained results might be distorted." }, { "code": null, "e": 11323, "s": 11198, "text": "Let us in the first step add some column names so that it will be easier for us to understand the data set and work with it." }, { "code": null, "e": 11765, "s": 11323, "text": "# Add headers to df and display first 5 rowsheaders = [\"symboling\", \"normalized-losses\", \"make\", \"fuel-type\", \"aspiration\", \"num-of-doors\", \"body-style\", \"drive-wheels\", \"engine-location\", \"wheel-base\", \"length\", \"width\", \"height\", \"curb-weight\", \"engine-type\", \"num-of-cylinders\", \"engine-size\",\"fuel-system\", \"bore\", \"stroke\", \"compression-ratio\", \"horsepower\", \"peak-rpm\", \"city-mpg\", \"highway-mpg\", \"price\"]df.columns = headersdf.head(5)" }, { "code": null, "e": 12178, "s": 11765, "text": "As that seemed to work well, we should now have a look at these question marks in the normalized-losses column. We cannot use them for our further analysis, so we will replace them with NaN values. Note that we will call the pandas.replace function on the whole data frame and not just on the one column. We do that to ensure that we will later not encounter another question mark somewhere else in the data set." }, { "code": null, "e": 12264, "s": 12178, "text": "# Replace ? with NaN and show first 5 rows of dfdf = df.replace('?',np.NaN)df.head(5)" }, { "code": null, "e": 12499, "s": 12264, "text": "Since we have no overview of where we have missing values now, we should run a quick analysis to find out the NaN values. We can do that by checking the data frame for NaN values first and then print out our analysis using a for loop." }, { "code": null, "e": 12575, "s": 12499, "text": "# Check df for missing valuesmissing_data = df.isnull()missing_data.head(5)" }, { "code": null, "e": 12746, "s": 12575, "text": "# Run for loop to check for missing valuesfor column in missing_data.columns.values.tolist(): print(column) print (missing_data[column].value_counts()) print(\"\")" }, { "code": null, "e": 12858, "s": 12746, "text": "If you scroll through the analysis, you will find that we have missing values (=True) in the following columns:" }, { "code": null, "e": 12876, "s": 12858, "text": "normalized-losses" }, { "code": null, "e": 12889, "s": 12876, "text": "num-of-doors" }, { "code": null, "e": 12894, "s": 12889, "text": "bore" }, { "code": null, "e": 12901, "s": 12894, "text": "stroke" }, { "code": null, "e": 12912, "s": 12901, "text": "horsepower" }, { "code": null, "e": 12921, "s": 12912, "text": "peak-rpm" }, { "code": null, "e": 12927, "s": 12921, "text": "price" }, { "code": null, "e": 13134, "s": 12927, "text": "Since we need a functioning data set, we have to find a way to deal with the missing data. In general, there are two options. Either we drop columns or rows with missing data or we replace the missing data." }, { "code": null, "e": 13308, "s": 13134, "text": "Since our data set is not large enough that we can simply drop all rows/columns with missing values, we will replace the missing values with the means of the remaining data." }, { "code": null, "e": 13488, "s": 13308, "text": "The only exception will be the num-of-doors column as this data is not numerical. Here we will replace the missing data with the most common variant. In this case, that is “four”." }, { "code": null, "e": 14279, "s": 13488, "text": "# Replacing NaNs with mean / most common variantavg_norm_loss = df[\"normalized-losses\"].astype(\"float\").mean(axis=0)df[\"normalized-losses\"].replace(np.nan, avg_norm_loss, inplace=True)avg_bore = df['bore'].astype('float').mean(axis=0)df[\"bore\"].replace(np.nan, avg_bore, inplace=True)avg_stroke = df['stroke'].astype('float').mean(axis=0)df[\"stroke\"].replace(np.nan, avg_stroke, inplace=True)avg_horsepower = df['horsepower'].astype('float').mean(axis=0)df['horsepower'].replace(np.nan, avg_horsepower, inplace=True)avg_peakrpm = df['peak-rpm'].astype('float').mean(axis=0)df['peak-rpm'].replace(np.nan, avg_peakrpm, inplace=True)avg_price = df['price'].astype('float').mean(axis=0)df['price'].replace(np.nan, avg_price, inplace=True)df[\"num-of-doors\"].replace(np.nan, \"four\", inplace=True)" }, { "code": null, "e": 14379, "s": 14279, "text": "What’s left? Right! Checking the data forms. We can do that easily by executing the following code:" }, { "code": null, "e": 14408, "s": 14379, "text": "# Checking df typesdf.dtypes" }, { "code": null, "e": 14533, "s": 14408, "text": "As you can see some columns still have the wrong data type (e.g. bore should have integers). So let us correct that quickly:" }, { "code": null, "e": 14779, "s": 14533, "text": "# Format data typesdf[[\"bore\", \"stroke\"]] = df[[\"bore\", \"stroke\"]].astype(\"float\")df[[\"normalized-losses\"]] = df[[\"normalized-losses\"]].astype(\"int\")df[[\"price\"]] = df[[\"price\"]].astype(\"float\")df[[\"peak-rpm\"]] = df[[\"peak-rpm\"]].astype(\"float\")" }, { "code": null, "e": 14923, "s": 14779, "text": "There is much more we could do in terms of data standardization and normalization but we do not need that for this tutorial, so let us move on." }, { "code": null, "e": 15210, "s": 14923, "text": "Let us quickly recap what we want to do: We want to look for variables that have some kind of correlation to the price of cars, right? So we need to first check the type and form of the relationship between the two variables — and the easiest way to do that is to draw some more graphs!" }, { "code": null, "e": 15536, "s": 15210, "text": "To do that we will use the seaborn library and its regplot function. This function will plot the data points and a linear regression line for our selected variables on a 2D graph. While this does not help us to quantify the correlation, it helps us to identify the type and form of the relationship between the two variables." }, { "code": null, "e": 15624, "s": 15536, "text": "But without further ado, let’s get started and have a look at the price in relation to:" }, { "code": null, "e": 15893, "s": 15624, "text": "Engine size Have a look at the graph below. We can observe that the linear regression line fits the plotted data quite well. We can also observe that the regression line has a steep upwards gradient. But what does that tell us considering type and form of correlation?" }, { "code": null, "e": 16124, "s": 15893, "text": "While the increasing gradient of the regression line shows us that we can expect a positive correlation between the engine size and price, the good fit of the regression line indicates that the variables have a linear correlation." }, { "code": null, "e": 16214, "s": 16124, "text": "# Create a plot for engine-size and pricesns.regplot(x=\"engine-size\", y=\"price\", data=df)" }, { "code": null, "e": 16648, "s": 16214, "text": "Highway-mpgThe graph below shows us the regression plot for highway miles per gallon (mpg) in relation to the cars’ prices. Here, we can observe that the regression line is decreasing, indicating a negative correlation. However, we can see that that the regression line does not cover the outliers between 0 and 25 on the x-axis. This indicates that linear regression is not a good fit and suggests that the data might be non-linear." }, { "code": null, "e": 16750, "s": 16648, "text": "# Create a plot for highway-mpg and pricesns.regplot(x=\"highway-mpg\", y=\"price\", data=df)plt.ylim(0,)" }, { "code": null, "e": 17223, "s": 16750, "text": "Peak-rpmThe graph for peak-rpm and price looks different again. We see that the data points have a great variation and the regression line is almost horizontal. Based on that observation we cannot determine what form of correlation we can expect but assuming there is a linear relationship, the nearly-flat regression line indicates that we can expect a correlation coefficient around 0. We would therefore conclude that there is no correlation between peak rpm and price." }, { "code": null, "e": 17319, "s": 17223, "text": "# Create a plot for peak-rpm and pricesns.regplot(x=\"peak-rpm\", y=\"price\", data=df)plt.ylim(0,)" }, { "code": null, "e": 17449, "s": 17319, "text": "Since it would take ages to look at each variable pair individually, we can shorten the process by using panda’s corr() function:" }, { "code": null, "e": 17489, "s": 17449, "text": "# Using pandas corr() functiondf.corr()" }, { "code": null, "e": 17668, "s": 17489, "text": "As you can see, the corr() function by pandas creates a correlation matrix with all variables contained in our data set. You might ask — why we didn’t do this from the beginning?" }, { "code": null, "e": 18022, "s": 17668, "text": "The answer is relatively simple. While the corr() function calculates by default the Pearson correlation coefficients, it does not give you any information regarding the form of correlation. It can therefore serve you as a great starting point to identify potential high correlations but checking the variable pairs individually will still be necessary." }, { "code": null, "e": 18100, "s": 18022, "text": "Let us quickly summarize the outcome of our above analysis before we move on:" }, { "code": null, "e": 18175, "s": 18100, "text": "We can expect a positive, linear correlation between engine size and price" }, { "code": null, "e": 18274, "s": 18175, "text": "We have observed a negative correlation between highway-mpg and price that seems to be non-linear." }, { "code": null, "e": 18390, "s": 18274, "text": "We assume no correlation between peak-rpm and price and we have no reliable information of the form of correlation." }, { "code": null, "e": 18555, "s": 18390, "text": "We can thus conclude that the variables highway-mpg and peak-rpm seem to be not suitable for conducting a further analysis with the Pearson correlation coefficient." }, { "code": null, "e": 18713, "s": 18555, "text": "To have a closer look at the engine size, we can compute the Pearson correlation coefficient as well as the p-value with the help of the scipy.stats library." }, { "code": null, "e": 18922, "s": 18713, "text": "# Calculate pearson coefficient and p-valuepearson_coef, p_value = stats.pearsonr(df['wheel-base'], df['price'])print(\"The Pearson Correlation Coefficient is\", pearson_coef, \" with a P-value of P =\", p_value)" }, { "code": null, "e": 19020, "s": 18922, "text": "In result, we receive a Pearson correlation coefficient of ~ 0.87 and a p-value of pretty much 0." }, { "code": null, "e": 19153, "s": 19020, "text": "Since our coefficient is >0.7 but <0.9, we conclude that we are observing a high positive correlation between engine size and price." }, { "code": null, "e": 19370, "s": 19153, "text": "Finally, we can observe that our p-value is definitely below our significance level (a) of 0.05. We can therefore conclude that the correlation we have calculated above is not a coincidence and therefore significant." }, { "code": null, "e": 19454, "s": 19370, "text": "This would not be a good tutorial if I would not make the following, famous remark:" }, { "code": null, "e": 19492, "s": 19454, "text": "Correlation does not imply causation." }, { "code": null, "e": 19698, "s": 19492, "text": "We have learned that correlation is a measure to describe the extent of a relationship between two variables. Causation on the other hand is the relationship between cause and effect between two variables." }, { "code": null, "e": 20002, "s": 19698, "text": "Even if we have observed a correlation, we cannot conclude that one variable causes a change in the other. Unless we have been able to consider all different variants, we have to assume that there is still a chance for coincidence or that a third factor might be causing both of our variables to change." } ]
Product of all leaf nodes of binary tree in C++
Given with a binary tree containing nodes and the task is to find the product of all the leaf nodes of a given binary tree. Leaf nodes are the end nodes which don’t have any children. In a tree, a node can act as a parent node or child node except the root node which can only be a parent node. So the nodes with right and left pointer as NULL are the leaf nodes. Input Output Leaf nodes are -: 23, 34, 25 Product-: 23*34*25 = 19550 Input the node data Input the node data Traverse all the nodes starting from the root node and going to either left sub directory or right subdirectory for traversal. Traverse all the nodes starting from the root node and going to either left sub directory or right subdirectory for traversal. Store those nodes with right and left pointer being NULL into a temporary variable to find the product. Store those nodes with right and left pointer being NULL into a temporary variable to find the product. Print the value of a temporary variable holding the multiplied values. Print the value of a temporary variable holding the multiplied values. Start Step 1 → create structure of a node and temp, next and head as pointer to a structure node struct node int data Create node *left, *right End Step 2 → declare function to insert a node in a tree node* new_node(int data) Set node* temp = new node() Set temp→data = data Set temp→left = temp→right = NULL return temp End Step 3 → Declare a function to find product of all the leaf nodes void leaf(node* root, int &product) IF (!root) Return End IF (!root→left && !root→right) Set product *= root→data Call leaf(root→left, product) Call leaf(root→right, product) Step 4 → In main() Create node* root = new_node(10) Set root→left = new_node(20) Set root→left→left = new_node(30) Set int product = 1 Call leaf(root, product) Display product Stop Live Demo #include <bits/stdc++.h> using namespace std; //structure of a node struct node{ int data; node *left, *right; }; //function to create a new leaf of a tree node* new_node(int data){ node* temp = new node(); temp→data = data; temp→left = temp→right = NULL; return temp; } //function to find the product of all leaf nodes of a tree void leaf(node* root, int &product){ if (!root) return; if (!root→left && !root->right) product *= root→data; leaf(root→left, product); leaf(root→right, product); } int main(){ node* root = new_node(10); root→left = new_node(20); root→left→left = new_node(30); root→left→right = new_node(40); root→right = new_node(50); root→right→right = new_node(60); root→right→left = new_node(70); int product = 1; leaf(root, product); cout<<"product of a leaf nodes are :"<<product; return 0; } If run the above code it will generate the following output − product of a leaf nodes are :5040000
[ { "code": null, "e": 1186, "s": 1062, "text": "Given with a binary tree containing nodes and the task is to find the product of all the leaf nodes of a given binary tree." }, { "code": null, "e": 1426, "s": 1186, "text": "Leaf nodes are the end nodes which don’t have any children. In a tree, a node can act as a parent node or child node except the root node which can only be a parent node. So the nodes with right and left pointer as NULL are the leaf nodes." }, { "code": null, "e": 1433, "s": 1426, "text": "Input " }, { "code": null, "e": 1441, "s": 1433, "text": "Output " }, { "code": null, "e": 1497, "s": 1441, "text": "Leaf nodes are -: 23, 34, 25\nProduct-: 23*34*25 = 19550" }, { "code": null, "e": 1517, "s": 1497, "text": "Input the node data" }, { "code": null, "e": 1537, "s": 1517, "text": "Input the node data" }, { "code": null, "e": 1664, "s": 1537, "text": "Traverse all the nodes starting from the root node and going to either left sub directory or right subdirectory for traversal." }, { "code": null, "e": 1791, "s": 1664, "text": "Traverse all the nodes starting from the root node and going to either left sub directory or right subdirectory for traversal." }, { "code": null, "e": 1895, "s": 1791, "text": "Store those nodes with right and left pointer being NULL into a temporary variable to find the product." }, { "code": null, "e": 1999, "s": 1895, "text": "Store those nodes with right and left pointer being NULL into a temporary variable to find the product." }, { "code": null, "e": 2070, "s": 1999, "text": "Print the value of a temporary variable holding the multiplied values." }, { "code": null, "e": 2141, "s": 2070, "text": "Print the value of a temporary variable holding the multiplied values." }, { "code": null, "e": 3026, "s": 2141, "text": "Start\nStep 1 → create structure of a node and temp, next and head as pointer to a\n structure node\n struct node\n int data\n Create node *left, *right\n End\nStep 2 → declare function to insert a node in a tree\n node* new_node(int data)\n Set node* temp = new node()\n Set temp→data = data\n Set temp→left = temp→right = NULL\n return temp\n End\nStep 3 → Declare a function to find product of all the leaf nodes\n void leaf(node* root, int &product)\n IF (!root)\n Return\n End\n IF (!root→left && !root→right)\n Set product *= root→data\n Call leaf(root→left, product)\n Call leaf(root→right, product)\nStep 4 → In main()\n Create node* root = new_node(10)\n Set root→left = new_node(20)\n Set root→left→left = new_node(30)\n Set int product = 1\n Call leaf(root, product)\n Display product\nStop" }, { "code": null, "e": 3037, "s": 3026, "text": " Live Demo" }, { "code": null, "e": 3925, "s": 3037, "text": "#include <bits/stdc++.h>\nusing namespace std;\n//structure of a node\nstruct node{\n int data;\n node *left, *right;\n};\n//function to create a new leaf of a tree\nnode* new_node(int data){\n node* temp = new node();\n temp→data = data;\n temp→left = temp→right = NULL;\n return temp;\n}\n//function to find the product of all leaf nodes of a tree\nvoid leaf(node* root, int &product){\n if (!root)\n return;\n if (!root→left && !root->right)\n product *= root→data;\n leaf(root→left, product);\n leaf(root→right, product);\n}\nint main(){\n node* root = new_node(10);\n root→left = new_node(20);\n root→left→left = new_node(30);\n root→left→right = new_node(40);\n root→right = new_node(50);\n root→right→right = new_node(60);\n root→right→left = new_node(70);\n int product = 1;\n leaf(root, product);\n cout<<\"product of a leaf nodes are :\"<<product;\n return 0;\n}" }, { "code": null, "e": 3987, "s": 3925, "text": "If run the above code it will generate the following output −" }, { "code": null, "e": 4024, "s": 3987, "text": "product of a leaf nodes are :5040000" } ]
Link Prediction in Bipartite Graph | by Edward Elson Kosasih | Towards Data Science
Answer: They can all be mathematically formulated as a graph link prediction problem! In short, given a graph G (V, E) with |V| vertices and |E| edges, our task is to predict the existence of a previously unknown edge e_12 ∉ E between vertices v_1, v_2 ∈ V. We can then use the link prediction model to, for instance, recommend the two vertices to each other. In Linkedin/Facebook this is equivalent to recommending “people/friends you may know”, in Tinder this would be a new person for you to swipe, in Amazon this is the “customer also bought” recommendation, in Netflix this is the “Top Picks for you”, in Spotify this is the personalised “Based on your recent listening / Shows you might like” playlist and in supply chain this is a new supplier that you could try to source from. In this article, we will focus on a particular type of network called bipartite graph. Mathematically speaking, this means we can split the vertices V into two disjoint sets, V_left and V_right, such that edges can only exist between vertex v_left ∈ V_left and v_right ∈ V_right. No two vertices from the same set are connected to each other. Bipartite graph can be used to model user-product network in a recommendation system e.g. V_left could be users and V_right products e.g. songs in Spotify, movies in Netflix, or items in Amazon. Users in these networks will only receive a recommendation about products and not other users, hence there are no edges formed between the same set. Such constraints in edges make link prediction in bipartite graphs tricky. As we will show later, some commonly used link prediction algorithms will no longer work. Therefore, we need to consider different methods. In this article, we will consider spectral transformation techniques proposed by Kunegis (2011) [1]. We will also discuss some issues related to measuring the performance of link prediction algorithms, as highlighted by Yang et. al. (2015) [2]. Disclaimer: The aim of this article to show a typical pipeline that one goes through when doing link prediction. We will work with a random bipartite graph, hence we don’t expect any pattern to emerge really. In practice, you could replace the graph G with your problem set. First, we import several python packages that we need to run our program. We use networkx as our underlying graph representation package. import networkx as nximport randomimport numpy as npimport scipy as scimport matplotlib.pyplot as pltfrom sklearn import metricsfrom scipy.optimize import curve_fitfrom tqdm import tqdm First, we create a random bipartite graph with 25 nodes and 50 edges (arbitrarily chosen). Looking at the adjacency matrix, we can tell that there are two independent block of vertices at the diagonal (upper-right to lower-left). # create random graphG = nx.bipartite.gnmk_random_graph(15, 10, 50, seed=123)# get layouttop = nx.bipartite.sets(G)[0]pos = nx.bipartite_layout(G, top)# get adjacency matrixA = nx.adjacency_matrix(G)A = A.toarray()# plot adjacency matrixplt.title(“Adjacency Matrix”)plt.imshow(A, cmap=’Greys’)plt.show()# plot graph visualisationnx.draw(G, pos, with_labels=True) Next, we split the graph into training and testing set by holding out 30% of the original edges [3]. Note that there are ongoing discussions about the importance of choosing test sets properly and the drastic impact it could have upon the performance result [2]. “””TRAINref: https://maelfabien.github.io/machinelearning/graph_4/#i-link-prediction“””# Remove 30% of the edgesproportion_edges = 0.3# this is our test setedge_subset = random.sample(G.edges(), int(proportion_edges * G.number_of_edges()))# Create a copy of the graph and remove the edgesG_train = G.copy()G_train.remove_edges_from(edge_subset)# adjacency matrixA_train = nx.adjacency_matrix(G_train)A_train = A_train.toarray()# visualise the train graphplt.title(“Train Graph”)nx.draw(G_train, pos, with_labels=True)plt.show()“””TEST“””G_test = nx.Graph()G_test.add_edges_from(edge_subset)# visualise the test graphplt.title(“Test Graph”)nx.draw(G_test, pos, with_labels=True)plt.show() There are two commonly used metrics to evaluate the performance of link prediction algorithms: Mean Average Precision (MAP) and Receiver Operating Characteristics (ROC) & Precision-Recall Curves. There are certain caveats to each (see [2]) for further discussion, as this is beyond the scope of this article. Mean Average Precision / MAP is defined as a weighted mean of the average precision across all nodes. A node’s average precision is obtained by ranking all predicted edges that are attached to it and calculating the accumulative mean of the precision score as we include more edges (see [4] for more derivation details). The formulas are provided below. """Mean Average Precision"""def MAP(G_test, G_pred, thres = 0): # calculate avePrecision for each node and its neighbors avePs = [] # loop through every node for node in tqdm(G_test.nodes()): # get predicted edges sorted in ranking order rankedPredWeights = sorted(G_pred[node].items(), key=lambda x: -x[1]['weight']) # only include edges that exist i.e. predicted rank / weight > threshold rankedPred = filter(lambda x: x[1]['weight'] > thres, rankedPredWeights) # get the rank pred = [x[0] for x in rankedPred] # calculate rel (existence of predicted edge in the groundtruth/actual set of edges) # get groundtruth neighbors gt = set(G_test[node]) rel = np.array([x in gt for x in pred]) # calculate P accumulative average of precision predLength = len(pred) P = np.array([ sum(rel[:i+1])/len(rel[:i+1]) for i in range(predLength) ]) # calculate aveP aveP = (rel @ P)/len(gt) # keep track of results avePs.append(aveP) MAPvalue = sum(avePs) / len(avePs) print("MAP: {}".format(MAPvalue)) return MAPvalue However, in order to use MAP, we’ll need to determine a fixed threshold of edge existence beforehand (e.g. in the above example, we set the threshold to be 0. In other words, if the link prediction model outputs a non-zero positive score to a pair of nodes, then we consider that there might be an edge there). Yang et al [2] have identified several issues with this approach. Therefore, we implement another approach, where we sweep across several thresholds in order to obtain the Receiver-Operating Characteristic Curve and Precision-Recall Curve. We can then measure the performance by looking at the Area Under Curve (AUC). This is a common evaluation metric used in classification tasks. """Visualise Receiver-Operating Characteristic Curve and Precision-Recall Curve"""def ROC_PRC(pred, G): # prediction score y_score = [p[2] for p in pred] # groundtruth label y_true = [G.has_edge(p[0], p[1]) for p in pred] fig, (ax1, ax2) = plt.subplots(1, 2) # precision-recall curve fpr, tpr, thresholds = metrics.precision_recall_curve(y_true, y_score) ax1.plot(fpr, tpr) ax1.set_title("Precision-Recall Curve") # receiver-operating characteristic curve fpr, tpr, thresholds = metrics.roc_curve(y_true, y_score) ax2.plot(fpr, tpr) ax2.set_title("ROC Curve, AUC = {:.2f}".format(metrics.roc_auc_score(y_true, y_score))) plt.show() Having defined the training-testing set and evaluation metrics, we can now move on and discuss some algorithms that we can use for link prediction. If we forget about our bipartite graph for a while and consider general undirected graphs, one of the most common link prediction methods are neighbours-based techniques. The idea here is that two disconnected vertices who share common neighbours will have a higher likelihood of being linked by an edge. The exact likelihood score varies in practice, depending on the exact implementation (see Resource Allocation index, Jaccard Coefficient and Adamic-Adar [5]). Unfortunately, these algorithms don’t work for bipartite graphs, because two vertices from different sets will never share common neighbours. If we insist on applying these algorithms, they will predict the existence of edges between the same sets, hence resulting in inferior performance, i.e. zero MAP. for algo in [ nx.resource_allocation_index, nx.jaccard_coefficient, nx.adamic_adar_index]: print(algo) pred = list(algo(G_train)) # create graph G_pred = nx.Graph() G_pred.add_weighted_edges_from(pred) # visualise adjacency matrix Apred = nx.adjacency_matrix(G_pred) Apred = Apred.toarray() plt.imshow(Apred, cmap='Greys') plt.show() # evaluation ROC_PRC(pred, G) MAP(G_test, G_pred) Researchers have identified this problem with neighbours-based approaches for a while. Several alternative algorithms such as odd paths counting have been proposed (odd because only odd length of paths matter in a bipartite graph eg even paths mean we’re connecting vertices from two different sets). Interestingly, Kunegis [1] proved that many of these algorithms can actually be generalised as the same spectral curve-fitting approach but with different kernel function. The main idea lies in the following equation. Consider performing an eigenvalue decomposition on the adjacency matrix A of graph G. We’ll then obtain the eigenvector matrix U and diagonal eigenvalue matrix Λ. Kunegis [1] proposed that one can transform a graph with kernel function F by either applying it directly to the adjacency matrix F(A) or to its’ eigenvalue matrix F(Λ). The assumption here is that the eigenvectors stay the same, because we assume that the original and transformed graph are not vastly different. This is reasonable for our case, where the original graph is our train set while the transformed graph is our test set. We assume that the two comes from the same underlying distribution profile. If they differ, then this is an out-of-distribution task which is another research topic beyond the scope of this article. Not all kernel functions F could work. For reference, Kunegis [1] has written down several of such working kernels as listed below. Now consider our link prediction task, where we have our training graph G (adjacency matrix A) and testing graph G’ (adjacency matrix A’). The idea here is to find a function F that can map our original A to A’. We can formulate this as the following objective function. We can swap U around from F(Λ) to A’ because the objective is calculated under a Frobenius norm that is invariant under multiplication by an orthogonal matrix (we assume full rank eigenvector matrix hence orthogonal). Kunegis [1] equated the above objective with a sum of one-dimensional least square regression problems as following. The function f (applied to eigenvalue) corresponds to its’ F version (applied to adjacency matrix) based on Table 1. In order to visualise what type of regression model would we need, we can do a scatter plot from each input-output pair of to see the pattern. """Kernel as Curve Fitting Problem"""# eigenvalue decompositionV_train, U_train = np.linalg.eig(A_train)# U.T * Atest * Utarget_V = U_train.T @ A @ U_train# take only the diagonalstarget_V = np.diag(target_V)# plot the patternplt.figure(figsize=(5, 3))plt.xlabel("V_train")plt.ylabel("V_test")plt.scatter(V_train, target_V, c='b')plt.show() We can then try to fit several kernel functions that are specifically designed for bipartite graphs (with odd path countings), as follows. We perform regression on the input-output data in order to learn the kernel parameters e.g. in this case α and β. # fit kernel functionfor kernel in [OddPathCountingKernel(), SinhPseudokernel(), OddNeumannPseudokernel()]: print(kernel) # fit the kernel to the data kernel.fit(V_train, target_V) # predict the output V_pred = kernel.pred(V_train) # assume our function is exponential V_train with alpha = 0.6 plt.figure(figsize=(5, 3)) plt.xlabel("V_train") plt.ylabel("V_test") plt.scatter(V_train, target_V, c='b', label="target_V") plt.scatter(V_train, V_pred, c='r', label="predicted_V") plt.legend() plt.show() # transformation Apred = U_train @ np.diag(V_pred) @ U_train.T Apred = Apred.real # make edges of prediction pred = [(i, j, Apred[i, j]) for i in range(Apred.shape[0]) for j in range(Apred.shape[1])] # create graph G_pred = nx.Graph() G_pred.add_weighted_edges_from(pred) # evaluate MAP and precision ROC_PRC(pred, G) MAP(G_test, G_pred) The first kernel that we use is odd path counting. Here we look at weighted sum of several odd powers of the original adjacency matrix (recall that k-th power of an adjacency matrix refers to numbers of k-hop neighbours from every node). The higher the value, the more likely it is for two vertices to be connected. # odd path counting kernel functionclass OddPathCountingKernel: def __init__(self): self.a1 = 0 self.a3 = 0 self.a5 = 0 self.a7 = 0 def func(self, V, a1, a3, a5, a7): return V * a1 + V**3 * a3 + V**5 * a5 + V**7 * a7 def fit(self, V_train, target_V): # do curve fitting popt, pcov = curve_fit(self.func, V_train, target_V) self.a1, self.a3, self.a5, self.a7 = popt def pred(self, V_train): return self.func(V_train, self.a1, self.a3, self.a5, self.a7) As shown by Kunegis [1], hyperbolic sine pseudokernel is a matrix exponential operation that’s basically equivalent to a weighted sum of all odd-power adjacency matrix. Smaller weights are assigned to terms with higher powers (using some clever tricks involving factorial terms), hence we can estimate this sum with a matrix exponential instead of having to enumerate all (infinitely many) powers of adjacency matrix. # sinh pseudokernel functionclass SinhPseudokernel: def __init__(self): self.alpha = 0 def func(self, V, alpha): return np.array([ alpha * (np.exp(lamb) - np.exp(-lamb)) for lamb in V ]) def fit(self, V_train, target_V): # do curve fitting popt, pcov = curve_fit(self.func, V_train, target_V) self.alpha, = popt def pred(self, V_train): return self.func(V_train, self.alpha) This has similar flavours to hyperbolic sinh pseudokernel, as it involves an infinite weighted sum of odd-powered adjacency matrix. However, the weights are designed in a different way hence resulting in a different form of kernel. # odd neumann pseudokernel functionclass OddNeumannPseudokernel: def __init__(self): self.alpha = 0 def func(self, V, alpha): return np.array([ alpha * (1/(1-lamb) - 1/(1+lamb)) for lamb in V ]) def fit(self, V_train, target_V): # do curve fitting popt, pcov = curve_fit(self.func, V_train, target_V) self.alpha, = popt def pred(self, V_train): return self.func(V_train, self.alpha) We can see that Odd Neumann pseudokernel doesn’t seem to fit the input-output data well (from the scatter plot), resulting in a worse AUC score compared to Odd Path Counting and Hyperbolic Sine Pseudokernel. In this article we’ve seen how to (1) define the link prediction task and split the train-test set, (2) write down two evaluation metrics: one with a fixed threshold (MAP) and another with sweeping thresholds (ROC and PR), (3) use spectral curve fitting methods to predict the existence of edges in a bipartite graph. For more rigorous mathematical derivation, please refer to the two papers from [1] and [2]. Find this article in a jupyter notebook version in my github repo here. [1] Kunegis, J. 2011. On the Spectral Evolution of Large Networks. Accessed from https://github.com/kunegis/phd. [2] Yang, Y., Lichtenwalter, R. N., Chawla, N. V. 2015. Evaluating Link Prediction Methods. Accessed from https://arxiv.org/abs/1505.04094. [3] Fabien, M. Graph Learning. Accessed from https://maelfabien.github.io/machinelearning/graph_4/#i-link-prediction. [4] Accessed from https://www.csie.ntu.edu.tw/~r01922164/SNA/Problems.pdf. [5] Accessed from https://networkx.github.io/documentation/stable/reference/algorithms/link_prediction.html.
[ { "code": null, "e": 258, "s": 172, "text": "Answer: They can all be mathematically formulated as a graph link prediction problem!" }, { "code": null, "e": 959, "s": 258, "text": "In short, given a graph G (V, E) with |V| vertices and |E| edges, our task is to predict the existence of a previously unknown edge e_12 ∉ E between vertices v_1, v_2 ∈ V. We can then use the link prediction model to, for instance, recommend the two vertices to each other. In Linkedin/Facebook this is equivalent to recommending “people/friends you may know”, in Tinder this would be a new person for you to swipe, in Amazon this is the “customer also bought” recommendation, in Netflix this is the “Top Picks for you”, in Spotify this is the personalised “Based on your recent listening / Shows you might like” playlist and in supply chain this is a new supplier that you could try to source from." }, { "code": null, "e": 1646, "s": 959, "text": "In this article, we will focus on a particular type of network called bipartite graph. Mathematically speaking, this means we can split the vertices V into two disjoint sets, V_left and V_right, such that edges can only exist between vertex v_left ∈ V_left and v_right ∈ V_right. No two vertices from the same set are connected to each other. Bipartite graph can be used to model user-product network in a recommendation system e.g. V_left could be users and V_right products e.g. songs in Spotify, movies in Netflix, or items in Amazon. Users in these networks will only receive a recommendation about products and not other users, hence there are no edges formed between the same set." }, { "code": null, "e": 1962, "s": 1646, "text": "Such constraints in edges make link prediction in bipartite graphs tricky. As we will show later, some commonly used link prediction algorithms will no longer work. Therefore, we need to consider different methods. In this article, we will consider spectral transformation techniques proposed by Kunegis (2011) [1]." }, { "code": null, "e": 2106, "s": 1962, "text": "We will also discuss some issues related to measuring the performance of link prediction algorithms, as highlighted by Yang et. al. (2015) [2]." }, { "code": null, "e": 2381, "s": 2106, "text": "Disclaimer: The aim of this article to show a typical pipeline that one goes through when doing link prediction. We will work with a random bipartite graph, hence we don’t expect any pattern to emerge really. In practice, you could replace the graph G with your problem set." }, { "code": null, "e": 2519, "s": 2381, "text": "First, we import several python packages that we need to run our program. We use networkx as our underlying graph representation package." }, { "code": null, "e": 2705, "s": 2519, "text": "import networkx as nximport randomimport numpy as npimport scipy as scimport matplotlib.pyplot as pltfrom sklearn import metricsfrom scipy.optimize import curve_fitfrom tqdm import tqdm" }, { "code": null, "e": 2935, "s": 2705, "text": "First, we create a random bipartite graph with 25 nodes and 50 edges (arbitrarily chosen). Looking at the adjacency matrix, we can tell that there are two independent block of vertices at the diagonal (upper-right to lower-left)." }, { "code": null, "e": 3298, "s": 2935, "text": "# create random graphG = nx.bipartite.gnmk_random_graph(15, 10, 50, seed=123)# get layouttop = nx.bipartite.sets(G)[0]pos = nx.bipartite_layout(G, top)# get adjacency matrixA = nx.adjacency_matrix(G)A = A.toarray()# plot adjacency matrixplt.title(“Adjacency Matrix”)plt.imshow(A, cmap=’Greys’)plt.show()# plot graph visualisationnx.draw(G, pos, with_labels=True)" }, { "code": null, "e": 3561, "s": 3298, "text": "Next, we split the graph into training and testing set by holding out 30% of the original edges [3]. Note that there are ongoing discussions about the importance of choosing test sets properly and the drastic impact it could have upon the performance result [2]." }, { "code": null, "e": 4249, "s": 3561, "text": "“””TRAINref: https://maelfabien.github.io/machinelearning/graph_4/#i-link-prediction“””# Remove 30% of the edgesproportion_edges = 0.3# this is our test setedge_subset = random.sample(G.edges(), int(proportion_edges * G.number_of_edges()))# Create a copy of the graph and remove the edgesG_train = G.copy()G_train.remove_edges_from(edge_subset)# adjacency matrixA_train = nx.adjacency_matrix(G_train)A_train = A_train.toarray()# visualise the train graphplt.title(“Train Graph”)nx.draw(G_train, pos, with_labels=True)plt.show()“””TEST“””G_test = nx.Graph()G_test.add_edges_from(edge_subset)# visualise the test graphplt.title(“Test Graph”)nx.draw(G_test, pos, with_labels=True)plt.show()" }, { "code": null, "e": 4558, "s": 4249, "text": "There are two commonly used metrics to evaluate the performance of link prediction algorithms: Mean Average Precision (MAP) and Receiver Operating Characteristics (ROC) & Precision-Recall Curves. There are certain caveats to each (see [2]) for further discussion, as this is beyond the scope of this article." }, { "code": null, "e": 4912, "s": 4558, "text": "Mean Average Precision / MAP is defined as a weighted mean of the average precision across all nodes. A node’s average precision is obtained by ranking all predicted edges that are attached to it and calculating the accumulative mean of the precision score as we include more edges (see [4] for more derivation details). The formulas are provided below." }, { "code": null, "e": 6079, "s": 4912, "text": "\"\"\"Mean Average Precision\"\"\"def MAP(G_test, G_pred, thres = 0): # calculate avePrecision for each node and its neighbors avePs = [] # loop through every node for node in tqdm(G_test.nodes()): # get predicted edges sorted in ranking order rankedPredWeights = sorted(G_pred[node].items(), key=lambda x: -x[1]['weight']) # only include edges that exist i.e. predicted rank / weight > threshold rankedPred = filter(lambda x: x[1]['weight'] > thres, rankedPredWeights) # get the rank pred = [x[0] for x in rankedPred] # calculate rel (existence of predicted edge in the groundtruth/actual set of edges) # get groundtruth neighbors gt = set(G_test[node]) rel = np.array([x in gt for x in pred]) # calculate P accumulative average of precision predLength = len(pred) P = np.array([ sum(rel[:i+1])/len(rel[:i+1]) for i in range(predLength) ]) # calculate aveP aveP = (rel @ P)/len(gt) # keep track of results avePs.append(aveP) MAPvalue = sum(avePs) / len(avePs) print(\"MAP: {}\".format(MAPvalue)) return MAPvalue" }, { "code": null, "e": 6773, "s": 6079, "text": "However, in order to use MAP, we’ll need to determine a fixed threshold of edge existence beforehand (e.g. in the above example, we set the threshold to be 0. In other words, if the link prediction model outputs a non-zero positive score to a pair of nodes, then we consider that there might be an edge there). Yang et al [2] have identified several issues with this approach. Therefore, we implement another approach, where we sweep across several thresholds in order to obtain the Receiver-Operating Characteristic Curve and Precision-Recall Curve. We can then measure the performance by looking at the Area Under Curve (AUC). This is a common evaluation metric used in classification tasks." }, { "code": null, "e": 7457, "s": 6773, "text": "\"\"\"Visualise Receiver-Operating Characteristic Curve and Precision-Recall Curve\"\"\"def ROC_PRC(pred, G): # prediction score y_score = [p[2] for p in pred] # groundtruth label y_true = [G.has_edge(p[0], p[1]) for p in pred] fig, (ax1, ax2) = plt.subplots(1, 2) # precision-recall curve fpr, tpr, thresholds = metrics.precision_recall_curve(y_true, y_score) ax1.plot(fpr, tpr) ax1.set_title(\"Precision-Recall Curve\") # receiver-operating characteristic curve fpr, tpr, thresholds = metrics.roc_curve(y_true, y_score) ax2.plot(fpr, tpr) ax2.set_title(\"ROC Curve, AUC = {:.2f}\".format(metrics.roc_auc_score(y_true, y_score))) plt.show()" }, { "code": null, "e": 8069, "s": 7457, "text": "Having defined the training-testing set and evaluation metrics, we can now move on and discuss some algorithms that we can use for link prediction. If we forget about our bipartite graph for a while and consider general undirected graphs, one of the most common link prediction methods are neighbours-based techniques. The idea here is that two disconnected vertices who share common neighbours will have a higher likelihood of being linked by an edge. The exact likelihood score varies in practice, depending on the exact implementation (see Resource Allocation index, Jaccard Coefficient and Adamic-Adar [5])." }, { "code": null, "e": 8374, "s": 8069, "text": "Unfortunately, these algorithms don’t work for bipartite graphs, because two vertices from different sets will never share common neighbours. If we insist on applying these algorithms, they will predict the existence of edges between the same sets, hence resulting in inferior performance, i.e. zero MAP." }, { "code": null, "e": 8806, "s": 8374, "text": "for algo in [ nx.resource_allocation_index, nx.jaccard_coefficient, nx.adamic_adar_index]: print(algo) pred = list(algo(G_train)) # create graph G_pred = nx.Graph() G_pred.add_weighted_edges_from(pred) # visualise adjacency matrix Apred = nx.adjacency_matrix(G_pred) Apred = Apred.toarray() plt.imshow(Apred, cmap='Greys') plt.show() # evaluation ROC_PRC(pred, G) MAP(G_test, G_pred)" }, { "code": null, "e": 9279, "s": 8806, "text": "Researchers have identified this problem with neighbours-based approaches for a while. Several alternative algorithms such as odd paths counting have been proposed (odd because only odd length of paths matter in a bipartite graph eg even paths mean we’re connecting vertices from two different sets). Interestingly, Kunegis [1] proved that many of these algorithms can actually be generalised as the same spectral curve-fitting approach but with different kernel function." }, { "code": null, "e": 10121, "s": 9279, "text": "The main idea lies in the following equation. Consider performing an eigenvalue decomposition on the adjacency matrix A of graph G. We’ll then obtain the eigenvector matrix U and diagonal eigenvalue matrix Λ. Kunegis [1] proposed that one can transform a graph with kernel function F by either applying it directly to the adjacency matrix F(A) or to its’ eigenvalue matrix F(Λ). The assumption here is that the eigenvectors stay the same, because we assume that the original and transformed graph are not vastly different. This is reasonable for our case, where the original graph is our train set while the transformed graph is our test set. We assume that the two comes from the same underlying distribution profile. If they differ, then this is an out-of-distribution task which is another research topic beyond the scope of this article." }, { "code": null, "e": 10253, "s": 10121, "text": "Not all kernel functions F could work. For reference, Kunegis [1] has written down several of such working kernels as listed below." }, { "code": null, "e": 10742, "s": 10253, "text": "Now consider our link prediction task, where we have our training graph G (adjacency matrix A) and testing graph G’ (adjacency matrix A’). The idea here is to find a function F that can map our original A to A’. We can formulate this as the following objective function. We can swap U around from F(Λ) to A’ because the objective is calculated under a Frobenius norm that is invariant under multiplication by an orthogonal matrix (we assume full rank eigenvector matrix hence orthogonal)." }, { "code": null, "e": 10976, "s": 10742, "text": "Kunegis [1] equated the above objective with a sum of one-dimensional least square regression problems as following. The function f (applied to eigenvalue) corresponds to its’ F version (applied to adjacency matrix) based on Table 1." }, { "code": null, "e": 11099, "s": 10976, "text": "In order to visualise what type of regression model would we need, we can do a scatter plot from each input-output pair of" }, { "code": null, "e": 11119, "s": 11099, "text": "to see the pattern." }, { "code": null, "e": 11460, "s": 11119, "text": "\"\"\"Kernel as Curve Fitting Problem\"\"\"# eigenvalue decompositionV_train, U_train = np.linalg.eig(A_train)# U.T * Atest * Utarget_V = U_train.T @ A @ U_train# take only the diagonalstarget_V = np.diag(target_V)# plot the patternplt.figure(figsize=(5, 3))plt.xlabel(\"V_train\")plt.ylabel(\"V_test\")plt.scatter(V_train, target_V, c='b')plt.show()" }, { "code": null, "e": 11599, "s": 11460, "text": "We can then try to fit several kernel functions that are specifically designed for bipartite graphs (with odd path countings), as follows." }, { "code": null, "e": 11713, "s": 11599, "text": "We perform regression on the input-output data in order to learn the kernel parameters e.g. in this case α and β." }, { "code": null, "e": 12628, "s": 11713, "text": "# fit kernel functionfor kernel in [OddPathCountingKernel(), SinhPseudokernel(), OddNeumannPseudokernel()]: print(kernel) # fit the kernel to the data kernel.fit(V_train, target_V) # predict the output V_pred = kernel.pred(V_train) # assume our function is exponential V_train with alpha = 0.6 plt.figure(figsize=(5, 3)) plt.xlabel(\"V_train\") plt.ylabel(\"V_test\") plt.scatter(V_train, target_V, c='b', label=\"target_V\") plt.scatter(V_train, V_pred, c='r', label=\"predicted_V\") plt.legend() plt.show() # transformation Apred = U_train @ np.diag(V_pred) @ U_train.T Apred = Apred.real # make edges of prediction pred = [(i, j, Apred[i, j]) for i in range(Apred.shape[0]) for j in range(Apred.shape[1])] # create graph G_pred = nx.Graph() G_pred.add_weighted_edges_from(pred) # evaluate MAP and precision ROC_PRC(pred, G) MAP(G_test, G_pred)" }, { "code": null, "e": 12944, "s": 12628, "text": "The first kernel that we use is odd path counting. Here we look at weighted sum of several odd powers of the original adjacency matrix (recall that k-th power of an adjacency matrix refers to numbers of k-hop neighbours from every node). The higher the value, the more likely it is for two vertices to be connected." }, { "code": null, "e": 13482, "s": 12944, "text": "# odd path counting kernel functionclass OddPathCountingKernel: def __init__(self): self.a1 = 0 self.a3 = 0 self.a5 = 0 self.a7 = 0 def func(self, V, a1, a3, a5, a7): return V * a1 + V**3 * a3 + V**5 * a5 + V**7 * a7 def fit(self, V_train, target_V): # do curve fitting popt, pcov = curve_fit(self.func, V_train, target_V) self.a1, self.a3, self.a5, self.a7 = popt def pred(self, V_train): return self.func(V_train, self.a1, self.a3, self.a5, self.a7)" }, { "code": null, "e": 13900, "s": 13482, "text": "As shown by Kunegis [1], hyperbolic sine pseudokernel is a matrix exponential operation that’s basically equivalent to a weighted sum of all odd-power adjacency matrix. Smaller weights are assigned to terms with higher powers (using some clever tricks involving factorial terms), hence we can estimate this sum with a matrix exponential instead of having to enumerate all (infinitely many) powers of adjacency matrix." }, { "code": null, "e": 14358, "s": 13900, "text": "# sinh pseudokernel functionclass SinhPseudokernel: def __init__(self): self.alpha = 0 def func(self, V, alpha): return np.array([ alpha * (np.exp(lamb) - np.exp(-lamb)) for lamb in V ]) def fit(self, V_train, target_V): # do curve fitting popt, pcov = curve_fit(self.func, V_train, target_V) self.alpha, = popt def pred(self, V_train): return self.func(V_train, self.alpha)" }, { "code": null, "e": 14590, "s": 14358, "text": "This has similar flavours to hyperbolic sinh pseudokernel, as it involves an infinite weighted sum of odd-powered adjacency matrix. However, the weights are designed in a different way hence resulting in a different form of kernel." }, { "code": null, "e": 15056, "s": 14590, "text": "# odd neumann pseudokernel functionclass OddNeumannPseudokernel: def __init__(self): self.alpha = 0 def func(self, V, alpha): return np.array([ alpha * (1/(1-lamb) - 1/(1+lamb)) for lamb in V ]) def fit(self, V_train, target_V): # do curve fitting popt, pcov = curve_fit(self.func, V_train, target_V) self.alpha, = popt def pred(self, V_train): return self.func(V_train, self.alpha)" }, { "code": null, "e": 15264, "s": 15056, "text": "We can see that Odd Neumann pseudokernel doesn’t seem to fit the input-output data well (from the scatter plot), resulting in a worse AUC score compared to Odd Path Counting and Hyperbolic Sine Pseudokernel." }, { "code": null, "e": 15674, "s": 15264, "text": "In this article we’ve seen how to (1) define the link prediction task and split the train-test set, (2) write down two evaluation metrics: one with a fixed threshold (MAP) and another with sweeping thresholds (ROC and PR), (3) use spectral curve fitting methods to predict the existence of edges in a bipartite graph. For more rigorous mathematical derivation, please refer to the two papers from [1] and [2]." }, { "code": null, "e": 15746, "s": 15674, "text": "Find this article in a jupyter notebook version in my github repo here." }, { "code": null, "e": 15859, "s": 15746, "text": "[1] Kunegis, J. 2011. On the Spectral Evolution of Large Networks. Accessed from https://github.com/kunegis/phd." }, { "code": null, "e": 15999, "s": 15859, "text": "[2] Yang, Y., Lichtenwalter, R. N., Chawla, N. V. 2015. Evaluating Link Prediction Methods. Accessed from https://arxiv.org/abs/1505.04094." }, { "code": null, "e": 16117, "s": 15999, "text": "[3] Fabien, M. Graph Learning. Accessed from https://maelfabien.github.io/machinelearning/graph_4/#i-link-prediction." }, { "code": null, "e": 16192, "s": 16117, "text": "[4] Accessed from https://www.csie.ntu.edu.tw/~r01922164/SNA/Problems.pdf." } ]
Can I get Age using BirthDate column in a MySQL query?
To get Age using BirthDate column in a MySQL query, you can use datediff(). Let us first create a table: mysql> create table DemoTable ( Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, DateOfBirth date ); Query OK, 0 rows affected (1.46 sec) Following is the query to insert some records in the table using insert command: mysql> insert into DemoTable(DateOfBirth) values('2010-01-21'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable(DateOfBirth) values('1993-04-02'); Query OK, 1 row affected (0.13 sec) mysql> insert into DemoTable(DateOfBirth) values('1999-12-01'); Query OK, 1 row affected (1.53 sec) mysql> insert into DemoTable(DateOfBirth) values('1998-11-16'); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable(DateOfBirth) values('2004-03-19'); Query OK, 1 row affected (0.11 sec) Following is the query to display records from the table using select command: mysql> select *from DemoTable; This will produce the following output: +----+-------------+ | Id | DateOfBirth | +----+-------------+ | 1 | 2010-01-21 | | 2 | 1993-04-02 | | 3 | 1999-12-01 | | 4 | 1998-11-16 | | 5 | 2004-03-19 | +----+-------------+ 5 rows in set (0.00 sec) Let us now get Age using birthdate column with DATEDIFF() method: mysql> select cast(DATEDIFF(curdate(),DateOfBirth) / 365.25 AS UNSIGNED) AS AGE from DemoTable; This will produce the following output: +------+ | AGE | +------+ | 9 | | 26 | | 19 | | 20 | | 15 | +------+ 5 rows in set (0.00 sec) Let us now write a query to get the DOB and ID where Age is between 20 and 26: mysql> SELECT *FROM DemoTable WHERE YEAR(CURDATE())-YEAR(DateOfBirth) BETWEEN 20 AND 26; This will produce the following output: +----+-------------+ | Id | DateOfBirth | +----+-------------+ | 2 | 1993-04-02 | | 3 | 1999-12-01 | | 4 | 1998-11-16 | +----+-------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1167, "s": 1062, "text": "To get Age using BirthDate column in a MySQL query, you can use datediff(). Let us first create a table:" }, { "code": null, "e": 1306, "s": 1167, "text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n DateOfBirth date\n);\nQuery OK, 0 rows affected (1.46 sec)" }, { "code": null, "e": 1387, "s": 1306, "text": "Following is the query to insert some records in the table using insert command:" }, { "code": null, "e": 1887, "s": 1387, "text": "mysql> insert into DemoTable(DateOfBirth) values('2010-01-21');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(DateOfBirth) values('1993-04-02');\nQuery OK, 1 row affected (0.13 sec)\nmysql> insert into DemoTable(DateOfBirth) values('1999-12-01');\nQuery OK, 1 row affected (1.53 sec)\nmysql> insert into DemoTable(DateOfBirth) values('1998-11-16');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable(DateOfBirth) values('2004-03-19');\nQuery OK, 1 row affected (0.11 sec)" }, { "code": null, "e": 1966, "s": 1887, "text": "Following is the query to display records from the table using select command:" }, { "code": null, "e": 1997, "s": 1966, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2037, "s": 1997, "text": "This will produce the following output:" }, { "code": null, "e": 2251, "s": 2037, "text": "+----+-------------+\n| Id | DateOfBirth |\n+----+-------------+\n| 1 | 2010-01-21 |\n| 2 | 1993-04-02 |\n| 3 | 1999-12-01 |\n| 4 | 1998-11-16 |\n| 5 | 2004-03-19 |\n+----+-------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2317, "s": 2251, "text": "Let us now get Age using birthdate column with DATEDIFF() method:" }, { "code": null, "e": 2413, "s": 2317, "text": "mysql> select cast(DATEDIFF(curdate(),DateOfBirth) / 365.25 AS UNSIGNED) AS AGE from DemoTable;" }, { "code": null, "e": 2453, "s": 2413, "text": "This will produce the following output:" }, { "code": null, "e": 2559, "s": 2453, "text": "+------+\n| AGE |\n+------+\n| 9 |\n| 26 |\n| 19 |\n| 20 |\n| 15 |\n+------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2638, "s": 2559, "text": "Let us now write a query to get the DOB and ID where Age is between 20 and 26:" }, { "code": null, "e": 2727, "s": 2638, "text": "mysql> SELECT *FROM DemoTable WHERE YEAR(CURDATE())-YEAR(DateOfBirth)\nBETWEEN 20 AND 26;" }, { "code": null, "e": 2767, "s": 2727, "text": "This will produce the following output:" }, { "code": null, "e": 2939, "s": 2767, "text": "+----+-------------+\n| Id | DateOfBirth |\n+----+-------------+\n| 2 | 1993-04-02 |\n| 3 | 1999-12-01 |\n| 4 | 1998-11-16 |\n+----+-------------+\n3 rows in set (0.00 sec)" } ]
Handling Outliers in Clusters using Silhouette Analysis | by Satyam Kumar | Towards Data Science
The real-world data often has a lot of outlier values. The cause of outliers can be data corruption or failure to record data. The handling of outliers is very important during the data preprocessing pipeline as the presence of outliers can prevent the model to perform best. There are various strategies to handle outliers in the dataset. This article will cover how to handle outliers after clustering data into several clusters using Silhouette Analysis. The silhouette method is a method to find the optimal number of clusters and interpretation and validation of consistency within clusters of data. The silhouette method computes silhouette coefficients of each point that measure how much a point is similar to its own cluster compared to other clusters. by providing a succinct graphical representation of how well each object has been classified. The analysis of these graphical representations is called Silhouette Analysis. The silhouette value is a measure of how similar an object is to its own cluster (cohesion) compared to other clusters (separation). The value of the silhouette ranges between [1, -1]. Important Points:The Silhouette coefficient of +1 indicates that the sample is far away from the neighboring clusters.The Silhouette coefficient of 0 indicates that the sample is on or very close to the decision boundary between two neighboring clusters.Silhouette coefficient <0 indicates that those samples might have been assigned to the wrong cluster or are outliers. Steps to find the silhouette coefficient of an i’th point: Compute an (i): The average distance of that point with all other points in the same clusters.Compute b(i): The average distance of that point with all the points in the closest cluster to its cluster.Compute s(i) — silhouette coefficient or i’th point using below mentioned formula. Compute an (i): The average distance of that point with all other points in the same clusters. Compute b(i): The average distance of that point with all the points in the closest cluster to its cluster. Compute s(i) — silhouette coefficient or i’th point using below mentioned formula. Use the Silhouette Method to find the optimal number of clusters. It can also be found using the Elbow method, but the Silhouette Method is considered a better approach than the Elbow method. Read the below article to know more: towardsdatascience.com The silhouette plot displays a measure of how close each point in one cluster is to points in the neighboring clusters and thus provides a way to assess parameters like the number of clusters visually. From the silhouette line plot and silhouette analysis for different values of n_clusters, it is observed that n_cluster=3 is the best value of the number of clusters (k).In the above image for “silhouette analysis for KMeans clustering on sample data with n_clusters=3”, it is observed that all the clusters [0,1,2] have most of their points have silhouette coefficients more than average silhouette score.In the above image for “silhouette analysis for KMeans clustering on sample data with n_clusters=3”, it is observed that for cluster_label 2, there are few points that have negative silhouette coefficients, that can be considered as outliers. Also for cluster_label 1, some points have silhouette coefficients less than the average silhouette score, which are points on cluster boundaries away from its cluster center. From the silhouette line plot and silhouette analysis for different values of n_clusters, it is observed that n_cluster=3 is the best value of the number of clusters (k). In the above image for “silhouette analysis for KMeans clustering on sample data with n_clusters=3”, it is observed that all the clusters [0,1,2] have most of their points have silhouette coefficients more than average silhouette score. In the above image for “silhouette analysis for KMeans clustering on sample data with n_clusters=3”, it is observed that for cluster_label 2, there are few points that have negative silhouette coefficients, that can be considered as outliers. Also for cluster_label 1, some points have silhouette coefficients less than the average silhouette score, which are points on cluster boundaries away from its cluster center. To find the outliers, find the points that have a negative silhouette coefficient, and remove it. Points lying on the cluster boundaries away from its cluster center can also be removed to create a robust model, but it depends on the case study. Read this article to get deep dive explanation of Silhouette Analysis, and refer gist to get python code implementation. [1] Wikipedia: Silhouette (clustering), (14 Sep 2020) [2] Scikit Learn documentation: Selecting the number of clusters with silhouette analysis on KMeans clustering Thank You for Reading
[ { "code": null, "e": 448, "s": 172, "text": "The real-world data often has a lot of outlier values. The cause of outliers can be data corruption or failure to record data. The handling of outliers is very important during the data preprocessing pipeline as the presence of outliers can prevent the model to perform best." }, { "code": null, "e": 630, "s": 448, "text": "There are various strategies to handle outliers in the dataset. This article will cover how to handle outliers after clustering data into several clusters using Silhouette Analysis." }, { "code": null, "e": 1107, "s": 630, "text": "The silhouette method is a method to find the optimal number of clusters and interpretation and validation of consistency within clusters of data. The silhouette method computes silhouette coefficients of each point that measure how much a point is similar to its own cluster compared to other clusters. by providing a succinct graphical representation of how well each object has been classified. The analysis of these graphical representations is called Silhouette Analysis." }, { "code": null, "e": 1292, "s": 1107, "text": "The silhouette value is a measure of how similar an object is to its own cluster (cohesion) compared to other clusters (separation). The value of the silhouette ranges between [1, -1]." }, { "code": null, "e": 1664, "s": 1292, "text": "Important Points:The Silhouette coefficient of +1 indicates that the sample is far away from the neighboring clusters.The Silhouette coefficient of 0 indicates that the sample is on or very close to the decision boundary between two neighboring clusters.Silhouette coefficient <0 indicates that those samples might have been assigned to the wrong cluster or are outliers." }, { "code": null, "e": 1723, "s": 1664, "text": "Steps to find the silhouette coefficient of an i’th point:" }, { "code": null, "e": 2007, "s": 1723, "text": "Compute an (i): The average distance of that point with all other points in the same clusters.Compute b(i): The average distance of that point with all the points in the closest cluster to its cluster.Compute s(i) — silhouette coefficient or i’th point using below mentioned formula." }, { "code": null, "e": 2102, "s": 2007, "text": "Compute an (i): The average distance of that point with all other points in the same clusters." }, { "code": null, "e": 2210, "s": 2102, "text": "Compute b(i): The average distance of that point with all the points in the closest cluster to its cluster." }, { "code": null, "e": 2293, "s": 2210, "text": "Compute s(i) — silhouette coefficient or i’th point using below mentioned formula." }, { "code": null, "e": 2522, "s": 2293, "text": "Use the Silhouette Method to find the optimal number of clusters. It can also be found using the Elbow method, but the Silhouette Method is considered a better approach than the Elbow method. Read the below article to know more:" }, { "code": null, "e": 2545, "s": 2522, "text": "towardsdatascience.com" }, { "code": null, "e": 2747, "s": 2545, "text": "The silhouette plot displays a measure of how close each point in one cluster is to points in the neighboring clusters and thus provides a way to assess parameters like the number of clusters visually." }, { "code": null, "e": 3572, "s": 2747, "text": "From the silhouette line plot and silhouette analysis for different values of n_clusters, it is observed that n_cluster=3 is the best value of the number of clusters (k).In the above image for “silhouette analysis for KMeans clustering on sample data with n_clusters=3”, it is observed that all the clusters [0,1,2] have most of their points have silhouette coefficients more than average silhouette score.In the above image for “silhouette analysis for KMeans clustering on sample data with n_clusters=3”, it is observed that for cluster_label 2, there are few points that have negative silhouette coefficients, that can be considered as outliers. Also for cluster_label 1, some points have silhouette coefficients less than the average silhouette score, which are points on cluster boundaries away from its cluster center." }, { "code": null, "e": 3743, "s": 3572, "text": "From the silhouette line plot and silhouette analysis for different values of n_clusters, it is observed that n_cluster=3 is the best value of the number of clusters (k)." }, { "code": null, "e": 3980, "s": 3743, "text": "In the above image for “silhouette analysis for KMeans clustering on sample data with n_clusters=3”, it is observed that all the clusters [0,1,2] have most of their points have silhouette coefficients more than average silhouette score." }, { "code": null, "e": 4399, "s": 3980, "text": "In the above image for “silhouette analysis for KMeans clustering on sample data with n_clusters=3”, it is observed that for cluster_label 2, there are few points that have negative silhouette coefficients, that can be considered as outliers. Also for cluster_label 1, some points have silhouette coefficients less than the average silhouette score, which are points on cluster boundaries away from its cluster center." }, { "code": null, "e": 4645, "s": 4399, "text": "To find the outliers, find the points that have a negative silhouette coefficient, and remove it. Points lying on the cluster boundaries away from its cluster center can also be removed to create a robust model, but it depends on the case study." }, { "code": null, "e": 4766, "s": 4645, "text": "Read this article to get deep dive explanation of Silhouette Analysis, and refer gist to get python code implementation." }, { "code": null, "e": 4820, "s": 4766, "text": "[1] Wikipedia: Silhouette (clustering), (14 Sep 2020)" }, { "code": null, "e": 4931, "s": 4820, "text": "[2] Scikit Learn documentation: Selecting the number of clusters with silhouette analysis on KMeans clustering" } ]
Explain the concept of an array within a structure in C programming
An array of structure in C programming is a collection of different datatype variables, grouped together under a single name. General form of structure declaration The structural declaration is as follows − struct tagname{ datatype member1; datatype member2; datatype member n; }; Here, struct is the keyword. tagname specifies the name of structure. member1, member2 specifies the data items that make up structure. The following example shows the usage of array within a structure in C programming − struct book{ int pages; char author [30]; float price; }; Following is the C program to demonstrate the use of an array within a structure − Live Demo #include <stdio.h> // Declaration of the structure candidate struct candidate { int roll_no; char grade; // Array within the structure float marks[4]; }; // Function to displays the content of // the structure variables void display(struct candidate a1){ printf("Roll number : %d\n", a1.roll_no); printf("Grade : %c\n", a1.grade); printf("Marks secured:\n"); int i; int len = sizeof(a1.marks) / sizeof(float); // Accessing the contents of the // array within the structure for (i = 0; i < len; i++) { printf("Subject %d : %.2f\n", i + 1, a1.marks[i]); } } // Driver Code int main(){ // Initialize a structure struct candidate A= { 1, 'A', { 98.5, 77, 89, 78.5 } }; // Function to display structure display(A); return 0; } When the above program is executed, it produces the following result − Roll number : 1 Grade : A Marks secured: Subject 1 : 98.50 Subject 2 : 77.00 Subject 3 : 89.00 Subject 4 : 78.50
[ { "code": null, "e": 1188, "s": 1062, "text": "An array of structure in C programming is a collection of different datatype variables, grouped together under a single name." }, { "code": null, "e": 1226, "s": 1188, "text": "General form of structure declaration" }, { "code": null, "e": 1269, "s": 1226, "text": "The structural declaration is as follows −" }, { "code": null, "e": 1352, "s": 1269, "text": "struct tagname{\n datatype member1;\n datatype member2;\n datatype member n;\n};" }, { "code": null, "e": 1381, "s": 1352, "text": "Here, struct is the keyword." }, { "code": null, "e": 1422, "s": 1381, "text": "tagname specifies the name of structure." }, { "code": null, "e": 1488, "s": 1422, "text": "member1, member2 specifies the data items that make up structure." }, { "code": null, "e": 1573, "s": 1488, "text": "The following example shows the usage of array within a structure in C programming −" }, { "code": null, "e": 1640, "s": 1573, "text": "struct book{\n int pages;\n char author [30];\n float price;\n};" }, { "code": null, "e": 1723, "s": 1640, "text": "Following is the C program to demonstrate the use of an array within a structure −" }, { "code": null, "e": 1734, "s": 1723, "text": " Live Demo" }, { "code": null, "e": 2522, "s": 1734, "text": "#include <stdio.h>\n// Declaration of the structure candidate\nstruct candidate {\n int roll_no;\n char grade;\n // Array within the structure\n float marks[4];\n};\n// Function to displays the content of\n// the structure variables\nvoid display(struct candidate a1){\n printf(\"Roll number : %d\\n\", a1.roll_no);\n printf(\"Grade : %c\\n\", a1.grade);\n printf(\"Marks secured:\\n\");\n int i;\n int len = sizeof(a1.marks) / sizeof(float);\n // Accessing the contents of the\n // array within the structure\n for (i = 0; i < len; i++) {\n printf(\"Subject %d : %.2f\\n\",\n i + 1, a1.marks[i]);\n }\n}\n// Driver Code\nint main(){\n // Initialize a structure\n struct candidate A= { 1, 'A', { 98.5, 77, 89, 78.5 } };\n // Function to display structure\n display(A);\n return 0;\n}" }, { "code": null, "e": 2593, "s": 2522, "text": "When the above program is executed, it produces the following result −" }, { "code": null, "e": 2706, "s": 2593, "text": "Roll number : 1\nGrade : A\nMarks secured:\nSubject 1 : 98.50\nSubject 2 : 77.00\nSubject 3 : 89.00\nSubject 4 : 78.50" } ]
JSF - f:validateDoubleRange
f:validateDoubleRange tag is used to validate a value to a range of float values. <f:validateDoubleRange minimum = "1000.50" maximum = "10000.50" /> minimum Minimum long value within an optional range maximum Maximum long value within an optional range Let us create a test JSF application to test the above tag. package com.tutorialspoint.test; import java.io.Serializable; import javax.faces.bean.ManagedBean; import javax.faces.bean.SessionScoped; @ManagedBean(name = "userData", eager = true) @SessionScoped public class UserData implements Serializable { private static final long serialVersionUID = 1L; private double salary; public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } } <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:f = "http://java.sun.com/jsf/core"> <h:head> <title>JSF tutorial</title> </h:head> <h:body> <h2>h:validateDoubleRange Example</h2> <h:form> <h:inputText id = "salaryInput" value = "#{userData.salary}" label = "salary" > <f:validateDoubleRange minimum = "1000.50" maximum = "10000.50" /> </h:inputText> <h:commandButton value = "submit" action = "result"/> <h:message for = "salaryInput" style = "color:red" /> </h:form> </h:body> </html> <?xml version = "1.0" encoding = "UTF-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core" xmlns:h = "http://java.sun.com/jsf/html"> <h:head> <title>JSF Tutorial!</title> </h:head> <h:body> <h2>Result</h2> Salary: #{userData.salary} </h:body> </html> Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result. Enter an invalid value. Following will be the output. Enter a valid value. Following will be the output. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2034, "s": 1952, "text": "f:validateDoubleRange tag is used to validate a value to a range of float values." }, { "code": null, "e": 2102, "s": 2034, "text": "<f:validateDoubleRange minimum = \"1000.50\" maximum = \"10000.50\" />\n" }, { "code": null, "e": 2110, "s": 2102, "text": "minimum" }, { "code": null, "e": 2154, "s": 2110, "text": "Minimum long value within an optional range" }, { "code": null, "e": 2162, "s": 2154, "text": "maximum" }, { "code": null, "e": 2206, "s": 2162, "text": "Maximum long value within an optional range" }, { "code": null, "e": 2266, "s": 2206, "text": "Let us create a test JSF application to test the above tag." }, { "code": null, "e": 2734, "s": 2266, "text": "package com.tutorialspoint.test;\n\nimport java.io.Serializable;\n\nimport javax.faces.bean.ManagedBean;\nimport javax.faces.bean.SessionScoped;\n\n@ManagedBean(name = \"userData\", eager = true)\n@SessionScoped\npublic class UserData implements Serializable {\n private static final long serialVersionUID = 1L;\n private double salary;\n \n public double getSalary() {\n return salary;\n }\n \n public void setSalary(double salary) {\n this.salary = salary;\n }\n}" }, { "code": null, "e": 3563, "s": 2734, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:h = \"http://java.sun.com/jsf/html\"\n xmlns:f = \"http://java.sun.com/jsf/core\">\n \n <h:head>\n <title>JSF tutorial</title>\t\t\t\n </h:head>\n \n <h:body> \n <h2>h:validateDoubleRange Example</h2>\n \n <h:form>\n <h:inputText id = \"salaryInput\" value = \"#{userData.salary}\" \n label = \"salary\" >\n <f:validateDoubleRange minimum = \"1000.50\" maximum = \"10000.50\" />\n </h:inputText>\t\t\t\n <h:commandButton value = \"submit\" action = \"result\"/>\n <h:message for = \"salaryInput\" style = \"color:red\" />\n </h:form> \n \n </h:body>\n</html>" }, { "code": null, "e": 4029, "s": 3563, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \n\"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n\n<html xmlns = \"http://www.w3.org/1999/xhtml\"\n xmlns:f = \"http://java.sun.com/jsf/core\" \n xmlns:h = \"http://java.sun.com/jsf/html\">\n \n <h:head>\n <title>JSF Tutorial!</title> \n </h:head>\n \n <h:body>\n <h2>Result</h2>\n Salary: #{userData.salary}\n </h:body>\n</html> " }, { "code": null, "e": 4245, "s": 4029, "text": "Once you are ready with all the changes done, let us compile and run the application as we did in JSF - First Application chapter. If everything is fine with your application, this will produce the following result." }, { "code": null, "e": 4299, "s": 4245, "text": "Enter an invalid value. Following will be the output." }, { "code": null, "e": 4350, "s": 4299, "text": "Enter a valid value. Following will be the output." }, { "code": null, "e": 4385, "s": 4350, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4400, "s": 4385, "text": " Chaand Sheikh" }, { "code": null, "e": 4407, "s": 4400, "text": " Print" }, { "code": null, "e": 4418, "s": 4407, "text": " Add Notes" } ]
Find a pair with given sum in a Balanced BST - GeeksforGeeks
17 Apr, 2022 Given a Balanced Binary Search Tree and a target sum, write a function that returns true if there is a pair with sum equals to target sum, otherwise return false. Expected time complexity is O(n) and only O(Logn) extra space can be used. Any modification to Binary Search Tree is not allowed. Note that height of a Balanced BST is always O(Logn). This problem is mainly extension of the previous post. Here we are not allowed to modify the BST. The Brute Force Solution is to consider each pair in BST and check whether the sum equals to X. The time complexity of this solution will be O(n^2). A Better Solution is to create an auxiliary array and store the Inorder traversal of BST in the array. The array will be sorted as Inorder traversal of BST always produces sorted data. Once we have the Inorder traversal, we can pair in O(n) time (See this for details). This solution works in O(n) time but requires O(n) auxiliary space. C++ Java Python3 C# Javascript #include<bits/stdc++.h>using namespace std; class Node{ public: int data; Node* left; Node* right; Node(int d) { data=d; left=NULL; right=NULL; }}; class BinarySearchTree { // Root of BST public: Node *root; // Constructor BinarySearchTree() { root = NULL; } // Utility function for inorder traversal of the tree void inorderUtil(Node* node) { if (node == NULL) return; inorderUtil(node->left); cout << node->data << " "; inorderUtil(node->right); } // Inorder traversal of the tree void inorder() { inorderUtil(this->root); } /* A recursive function to insert a new key in BST */ Node* insertRec(Node* root, int data) { /* If the tree is empty, return a new node */ if (root == NULL) { root = new Node(data); return root; } /* Otherwise, recur down the tree */ if (data < root->data) root->left = insertRec(root->left, data); else if (data > root->data) root->right = insertRec(root->right, data); return root; } // This method mainly calls insertRec() void insert(int key) { root = insertRec(root, key); } // Method that adds values of given BST into vector // and hence returns the vector vector<int> treeToList(Node* node, vector<int>& list) { // Base Case if (node == NULL) return list; treeToList(node->left, list); list.push_back(node->data); treeToList(node->right, list); return list; } // method that checks if there is a pair present bool isPairPresent(Node* node, int target) { // This list a1 is passed as an argument // in treeToList method // which is later on filled by the values of BST vector<int> a1; // a2 list contains all the values of BST // returned by treeToList method vector<int> a2 = treeToList(node, a1); int start = 0; // Starting index of a2 int end = (int)a2.size() - 1; // Ending index of a2 while (start < end) { if (a2[start] + a2[end] == target) // Target Found! { cout << "Pair Found: " << a2[start] << " + " << a2[end] << " = " << target << '\n'; return true; } if (a2[start] + a2[end] > target) // decrements end { end--; } if (a2[start] + a2[end] < target) // increments start { start++; } } cout << "No such values are found!\n"; return false; }}; // Driver functionint main(){ BinarySearchTree *tree = new BinarySearchTree(); /* 15 / \ 10 20 / \ / \ 8 12 16 25 */ tree->insert(15); tree->insert(10); tree->insert(20); tree->insert(8); tree->insert(12); tree->insert(16); tree->insert(25); tree->isPairPresent(tree->root, 33);} // Java code to find a pair with given sum// in a Balanced BSTimport java.util.ArrayList; // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinarySearchTree { // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // Inorder traversal of the tree void inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of the tree void inorderUtil(Node node) { if (node == null) return; inorderUtil(node.left); System.out.print(node.data + " "); inorderUtil(node.right); } // This method mainly calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int data) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(data); return root; } /* Otherwise, recur down the tree */ if (data < root.data) root.left = insertRec(root.left, data); else if (data > root.data) root.right = insertRec(root.right, data); return root; } // Method that adds values of given BST into ArrayList // and hence returns the ArrayList ArrayList<Integer> treeToList(Node node, ArrayList<Integer> list) { // Base Case if (node == null) return list; treeToList(node.left, list); list.add(node.data); treeToList(node.right, list); return list; } // method that checks if there is a pair present boolean isPairPresent(Node node, int target) { // This list a1 is passed as an argument // in treeToList method // which is later on filled by the values of BST ArrayList<Integer> a1 = new ArrayList<>(); // a2 list contains all the values of BST // returned by treeToList method ArrayList<Integer> a2 = treeToList(node, a1); int start = 0; // Starting index of a2 int end = a2.size() - 1; // Ending index of a2 while (start < end) { if (a2.get(start) + a2.get(end) == target) // Target Found! { System.out.println("Pair Found: " + a2.get(start) + " + " + a2.get(end) + " " + "= " + target); return true; } if (a2.get(start) + a2.get(end) > target) // decrements end { end--; } if (a2.get(start) + a2.get(end) < target) // increments start { start++; } } System.out.println("No such values are found!"); return false; } // Driver function public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* 15 / \ 10 20 / \ / \ 8 12 16 25 */ tree.insert(15); tree.insert(10); tree.insert(20); tree.insert(8); tree.insert(12); tree.insert(16); tree.insert(25); tree.isPairPresent(tree.root, 33); }} // This code is contributed by Kamal Rawal # Python3 code to find a pair with given sum# in a Balanced BSTclass Node: # Construct to create a new Node def __init__(self, key): self.data = key self.left = self.right = None # A utility function to insert a new# Node with given key in BSTdef insert(root: Node, key: int): # If the tree is empty, return a new Node if root is None: return Node(key) # Otherwise, recur down the tree if root.data > key: root.left = insert(root.left, key) elif root.data < key: root.right = insert(root.right, key) # return the (unchanged) Node pointer return root # Function that adds values of given BST into# ArrayList and hence returns the ArrayListdef tree_to_list(root: Node, arr: list): if not root: return arr tree_to_list(root.left, arr) arr.append(root.data) tree_to_list(root.right, arr) return arr # Function that checks if there is a pair presentdef isPairPresent(root: Node, target: int) -> bool: # This list a1 is passed as an argument # in treeToList method which is later # on filled by the values of BST arr1 = [] # a2 list contains all the values of BST # returned by treeToList method arr2 = tree_to_list(root, arr1) # Starting index of a2 start = 0 # Ending index of a2 end = len(arr2) - 1 while start < end: # If target found if arr2[start] + arr2[end] == target: print(f"Pair Found: {arr2[start]} + {arr2[end]} = {target}") return True # Decrements end if arr2[start] + arr2[end] > target: end -= 1 # Increments start if arr2[start] + arr2[end] < target: start += 1 print("No such values are found!") return False # Driver codeif __name__ == "__main__": root = None root = insert(root, 15) root = insert(root, 10) root = insert(root, 20) root = insert(root, 8) root = insert(root, 12) root = insert(root, 16) root = insert(root, 25) isPairPresent(root, 33) # This code is contributed by shindesharad71 // C# code to find a pair with given sum// in a Balanced BSTusing System;using System.Collections.Generic; // A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinarySearchTree { // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // Inorder traversal of the tree void inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of the tree void inorderUtil(Node node) { if (node == null) return; inorderUtil(node.left); Console.Write(node.data + " "); inorderUtil(node.right); } // This method mainly calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int data) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(data); return root; } /* Otherwise, recur down the tree */ if (data < root.data) root.left = insertRec(root.left, data); else if (data > root.data) root.right = insertRec(root.right, data); return root; } // Method that adds values of given BST into ArrayList // and hence returns the ArrayList List<int> treeToList(Node node, List<int> list) { // Base Case if (node == null) return list; treeToList(node.left, list); list.Add(node.data); treeToList(node.right, list); return list; } // method that checks if there is a pair present bool isPairPresent(Node node, int target) { // This list a1 is passed as an argument // in treeToList method // which is later on filled by the values of BST List<int> a1 = new List<int>(); // a2 list contains all the values of BST // returned by treeToList method List<int> a2 = treeToList(node, a1); int start = 0; // Starting index of a2 int end = a2.Count - 1; // Ending index of a2 while (start < end) { if (a2[start] + a2[end] == target) // Target Found! { Console.WriteLine("Pair Found: " + a2[start] + " + " + a2[end] + " " + "= " + target); return true; } if (a2[start] + a2[end] > target) // decrements end { end--; } if (a2[start] + a2[end] < target) // increments start { start++; } } Console.WriteLine("No such values are found!"); return false; } // Driver code public static void Main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* 15 / \ 10 20 / \ / \ 8 12 16 25 */ tree.insert(15); tree.insert(10); tree.insert(20); tree.insert(8); tree.insert(12); tree.insert(16); tree.insert(25); tree.isPairPresent(tree.root, 33); }} // This code contributed by Rajput-Ji <script> // JavaScript code to find a pair with given sum // in a Balanced BST // A binary tree node class Node { constructor(d) { this.data = d; this.left = null; this.right = null; } } class BinarySearchTree { // Constructor constructor() { this.root = null; } // Inorder traversal of the tree inorder() { this.inorderUtil(this.root); } // Utility function for inorder traversal of the tree inorderUtil(node) { if (node == null) return; this.inorderUtil(node.left); document.write(node.data + " "); this.inorderUtil(node.right); } // This method mainly calls insertRec() insert(key) { this.root = this.insertRec(this.root, key); } /* A recursive function to insert a new key in BST */ insertRec(root, data) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(data); return root; } /* Otherwise, recur down the tree */ if (data < root.data) root.left = this.insertRec(root.left, data); else if (data > root.data) root.right = this.insertRec(root.right, data); return root; } // Method that adds values of given BST into ArrayList // and hence returns the ArrayList treeToList(node, list) { // Base Case if (node == null) return list; this.treeToList(node.left, list); list.push(node.data); this.treeToList(node.right, list); return list; } // method that checks if there is a pair present isPairPresent(node, target) { // This list a1 is passed as an argument // in treeToList method // which is later on filled by the values of BST var a1 = []; // a2 list contains all the values of BST // returned by treeToList method var a2 = this.treeToList(node, a1); var start = 0; // Starting index of a2 var end = a2.length - 1; // Ending index of a2 while (start < end) { if (a2[start] + a2[end] == target) { // Target Found! document.write( "Pair Found: " + a2[start] + " + " + a2[end] + " " + "= " + target + "<br>" ); return true; } if (a2[start] + a2[end] > target) { // decrements end end--; } if (a2[start] + a2[end] < target) { // increments start start++; } } document.write("No such values are found!"); return false; } } // Driver code var tree = new BinarySearchTree(); /* 15 / \ 10 20 / \ / \ 8 12 16 25 */ tree.insert(15); tree.insert(10); tree.insert(20); tree.insert(8); tree.insert(12); tree.insert(16); tree.insert(25); tree.isPairPresent(tree.root, 33); </script> Output : Pair Found: 8 + 25 = 33 Complexity Analysis: Time Complexity: O(n). Inorder Traversal of BST takes linear time.Auxiliary Space: O(n). Use of array for storing the Inorder Traversal. Time Complexity: O(n). Inorder Traversal of BST takes linear time. Auxiliary Space: O(n). Use of array for storing the Inorder Traversal. A space optimized solution is discussed in previous post. The idea was to first in-place convert BST to Doubly Linked List (DLL), then find pair in sorted DLL in O(n) time. This solution takes O(n) time and O(Logn) extra space, but it modifies the given BST. The solution discussed below takes O(n) time, O(Logn) space and doesn’t modify BST. The idea is same as finding the pair in sorted array (See method 1 of this for details). We traverse BST in Normal Inorder and Reverse Inorder simultaneously. In reverse inorder, we start from the rightmost node which is the maximum value node. In normal inorder, we start from the left most node which is minimum value node. We add sum of current nodes in both traversals and compare this sum with given target sum. If the sum is same as target sum, we return true. If the sum is more than target sum, we move to next node in reverse inorder traversal, otherwise we move to next node in normal inorder traversal. If any of the traversals is finished without finding a pair, we return false. Following is the implementation of this approach. C++ C Java Python3 C# Javascript /* In a balanced binary search treeisPairPresent two element which sums toa given value time O(n) space O(logn) */#include <bits/stdc++.h>using namespace std;#define MAX_SIZE 100 // A BST nodeclass node {public: int val; node *left, *right;}; // Stack typeclass Stack {public: int size; int top; node** array;}; // A utility function to create a stack of given sizeStack* createStack(int size){ Stack* stack = new Stack(); stack->size = size; stack->top = -1; stack->array = new node*[(stack->size * sizeof(node*))]; return stack;} // BASIC OPERATIONS OF STACKint isFull(Stack* stack){ return stack->top - 1 == stack->size;} int isEmpty(Stack* stack){ return stack->top == -1;} void push(Stack* stack, node* node){ if (isFull(stack)) return; stack->array[++stack->top] = node;} node* pop(Stack* stack){ if (isEmpty(stack)) return NULL; return stack->array[stack->top--];} // Returns true if a pair with target// sum exists in BST, otherwise falsebool isPairPresent(node* root, int target){ // Create two stacks. s1 is used for // normal inorder traversal and s2 is // used for reverse inorder traversal Stack* s1 = createStack(MAX_SIZE); Stack* s2 = createStack(MAX_SIZE); // Note the sizes of stacks is MAX_SIZE, // we can find the tree size and fix stack size // as O(Logn) for balanced trees like AVL and Red Black // tree. We have used MAX_SIZE to keep the code simple // done1, val1 and curr1 are used for // normal inorder traversal using s1 // done2, val2 and curr2 are used for // reverse inorder traversal using s2 bool done1 = false, done2 = false; int val1 = 0, val2 = 0; node *curr1 = root, *curr2 = root; // The loop will break when we either find a pair or one of the two // traversals is complete while (1) { // Find next node in normal Inorder // traversal. See following post // https:// www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ while (done1 == false) { if (curr1 != NULL) { push(s1, curr1); curr1 = curr1->left; } else { if (isEmpty(s1)) done1 = 1; else { curr1 = pop(s1); val1 = curr1->val; curr1 = curr1->right; done1 = 1; } } } // Find next node in REVERSE Inorder traversal. The only // difference between above and below loop is, in below loop // right subtree is traversed before left subtree while (done2 == false) { if (curr2 != NULL) { push(s2, curr2); curr2 = curr2->right; } else { if (isEmpty(s2)) done2 = 1; else { curr2 = pop(s2); val2 = curr2->val; curr2 = curr2->left; done2 = 1; } } } // If we find a pair, then print the pair and return. The first // condition makes sure that two same values are not added if ((val1 != val2) && (val1 + val2) == target) { cout << "Pair Found: " << val1 << "+ " << val2 << " = " << target << endl; return true; } // If sum of current values is smaller, // then move to next node in // normal inorder traversal else if ((val1 + val2) < target) done1 = false; // If sum of current values is greater, // then move to next node in // reverse inorder traversal else if ((val1 + val2) > target) done2 = false; // If any of the inorder traversals is // over, then there is no pair // so return false if (val1 >= val2) return false; }} // A utility function to create BST nodenode* NewNode(int val){ node* tmp = new node(); tmp->val = val; tmp->right = tmp->left = NULL; return tmp;} // Driver program to test above functionsint main(){ /* 15 / \ 10 20 / \ / \ 8 12 16 25 */ node* root = NewNode(15); root->left = NewNode(10); root->right = NewNode(20); root->left->left = NewNode(8); root->left->right = NewNode(12); root->right->left = NewNode(16); root->right->right = NewNode(25); int target = 33; if (isPairPresent(root, target) == false) cout << "\nNo such values are found\n"; return 0;} // This code is contributed by rathbhupendra /* In a balanced binary search tree isPairPresent two element which sums to a given value time O(n) space O(logn) */#include <stdio.h>#include <stdlib.h>#define MAX_SIZE 100 // A BST nodestruct node { int val; struct node *left, *right;}; // Stack typestruct Stack { int size; int top; struct node** array;}; // A utility function to create a stack of given sizestruct Stack* createStack(int size){ struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack)); stack->size = size; stack->top = -1; stack->array = (struct node**)malloc(stack->size * sizeof(struct node*)); return stack;} // BASIC OPERATIONS OF STACKint isFull(struct Stack* stack){ return stack->top - 1 == stack->size;} int isEmpty(struct Stack* stack){ return stack->top == -1;} void push(struct Stack* stack, struct node* node){ if (isFull(stack)) return; stack->array[++stack->top] = node;} struct node* pop(struct Stack* stack){ if (isEmpty(stack)) return NULL; return stack->array[stack->top--];} // Returns true if a pair with target sum exists in BST, otherwise falsebool isPairPresent(struct node* root, int target){ // Create two stacks. s1 is used for normal inorder traversal // and s2 is used for reverse inorder traversal struct Stack* s1 = createStack(MAX_SIZE); struct Stack* s2 = createStack(MAX_SIZE); // Note the sizes of stacks is MAX_SIZE, we can find the tree size and // fix stack size as O(Logn) for balanced trees like AVL and Red Black // tree. We have used MAX_SIZE to keep the code simple // done1, val1 and curr1 are used for normal inorder traversal using s1 // done2, val2 and curr2 are used for reverse inorder traversal using s2 bool done1 = false, done2 = false; int val1 = 0, val2 = 0; struct node *curr1 = root, *curr2 = root; // The loop will break when we either find a pair or one of the two // traversals is complete while (1) { // Find next node in normal Inorder traversal. See following post // https:// www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ while (done1 == false) { if (curr1 != NULL) { push(s1, curr1); curr1 = curr1->left; } else { if (isEmpty(s1)) done1 = 1; else { curr1 = pop(s1); val1 = curr1->val; curr1 = curr1->right; done1 = 1; } } } // Find next node in REVERSE Inorder traversal. The only // difference between above and below loop is, in below loop // right subtree is traversed before left subtree while (done2 == false) { if (curr2 != NULL) { push(s2, curr2); curr2 = curr2->right; } else { if (isEmpty(s2)) done2 = 1; else { curr2 = pop(s2); val2 = curr2->val; curr2 = curr2->left; done2 = 1; } } } // If we find a pair, then print the pair and return. The first // condition makes sure that two same values are not added if ((val1 != val2) && (val1 + val2) == target) { printf("\n Pair Found: %d + %d = %d\n", val1, val2, target); return true; } // If sum of current values is smaller, then move to next node in // normal inorder traversal else if ((val1 + val2) < target) done1 = false; // If sum of current values is greater, then move to next node in // reverse inorder traversal else if ((val1 + val2) > target) done2 = false; // If any of the inorder traversals is over, then there is no pair // so return false if (val1 >= val2) return false; }} // A utility function to create BST nodestruct node* NewNode(int val){ struct node* tmp = (struct node*)malloc(sizeof(struct node)); tmp->val = val; tmp->right = tmp->left = NULL; return tmp;} // Driver program to test above functionsint main(){ /* 15 / \ 10 20 / \ / \ 8 12 16 25 */ struct node* root = NewNode(15); root->left = NewNode(10); root->right = NewNode(20); root->left->left = NewNode(8); root->left->right = NewNode(12); root->right->left = NewNode(16); root->right->right = NewNode(25); int target = 33; if (isPairPresent(root, target) == false) printf("\n No such values are found\n"); getchar(); return 0;} /* In a balanced binary search treeisPairPresent two element which sums toa given value time O(n) space O(logn) */import java.util.*;class GFG{static final int MAX_SIZE= 100; // A BST nodestatic class node{ int val; node left, right;}; // Stack typestatic class Stack{ int size; int top; node []array;}; // A utility function to create a stack of given sizestatic Stack createStack(int size){ Stack stack = new Stack(); stack.size = size; stack.top = -1; stack.array = new node[stack.size]; return stack;} // BASIC OPERATIONS OF STACKstatic int isFull(Stack stack){ return (stack.top - 1 == stack.size)?1:0 ;} static int isEmpty(Stack stack){ return stack.top == -1?1:0;} static void push(Stack stack, node node){ if (isFull(stack)==1) return; stack.array[++stack.top] = node;} static node pop(Stack stack){ if (isEmpty(stack) == 1) return null; return stack.array[stack.top--];} // Returns true if a pair with target// sum exists in BST, otherwise falsestatic boolean isPairPresent(node root, int target){ // Create two stacks. s1 is used for // normal inorder traversal and s2 is // used for reverse inorder traversal Stack s1 = createStack(MAX_SIZE); Stack s2 = createStack(MAX_SIZE); // Note the sizes of stacks is MAX_SIZE, // we can find the tree size and fix stack size // as O(Logn) for balanced trees like AVL and Red Black // tree. We have used MAX_SIZE to keep the code simple // done1, val1 and curr1 are used for // normal inorder traversal using s1 // done2, val2 and curr2 are used for // reverse inorder traversal using s2 boolean done1 = false, done2 = false; int val1 = 0, val2 = 0; node curr1 = root, curr2 = root; // The loop will break when we either // find a pair or one of the two // traversals is complete while (true) { // Find next node in normal Inorder // traversal. See following post // https:// www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ while (done1 == false) { if (curr1 != null) { push(s1, curr1); curr1 = curr1.left; } else { if (isEmpty(s1) == 1) done1 = true; else { curr1 = pop(s1); val1 = curr1.val; curr1 = curr1.right; done1 = true; } } } // Find next node in REVERSE Inorder traversal. The only // difference between above and below loop is, in below loop // right subtree is traversed before left subtree while (done2 == false) { if (curr2 != null) { push(s2, curr2); curr2 = curr2.right; } else { if (isEmpty(s2) == 1) done2 = true; else { curr2 = pop(s2); val2 = curr2.val; curr2 = curr2.left; done2 = true; } } } // If we find a pair, then print the pair and return. The first // condition makes sure that two same values are not added if ((val1 != val2) && (val1 + val2) == target) { System.out.print("Pair Found: " + val1+ "+ " + val2+ " = " + target +"\n"); return true; } // If sum of current values is smaller, // then move to next node in // normal inorder traversal else if ((val1 + val2) < target) done1 = false; // If sum of current values is greater, // then move to next node in // reverse inorder traversal else if ((val1 + val2) > target) done2 = false; // If any of the inorder traversals is // over, then there is no pair // so return false if (val1 >= val2) return false; }} // A utility function to create BST nodestatic node NewNode(int val){ node tmp = new node(); tmp.val = val; tmp.right = tmp.left = null; return tmp;} // Driver program to test above functionspublic static void main(String[] args){ /* 15 / \ 10 20 / \ / \ 8 12 16 25 */ node root = NewNode(15); root.left = NewNode(10); root.right = NewNode(20); root.left.left = NewNode(8); root.left.right = NewNode(12); root.right.left = NewNode(16); root.right.right = NewNode(25); int target = 33; if (isPairPresent(root, target) == false) System.out.print("\nNo such values are found\n");}} // This code is contributed by aashish1995 # In a balanced binary search tree# isPairPresent two element which sums to# a given value time O(n) space O(logn)MAX_SIZE= 100 # A BST nodeclass Node: def __init__(self,val): self.val = val self.left = self.right = None # Stack typeclass Stack: def __init__(self): self.size = 0 self.top = 0 self.array = [] # A utility function to create a stack of given sizedef createStack(size): stack = Stack() stack.size = size stack.top = -1 stack.array = [0 for i in range(stack.size)] return stack # BASIC OPERATIONS OF STACKdef isFull(stack): return 1 if(stack.top - 1 == stack.size) else 0 def isEmpty(stack): return 1 if stack.top == -1 else 0 def push(stack,node): if (isFull(stack)==1): return stack.array[stack.top+1] = node stack.top += 1 def pop(stack): if (isEmpty(stack) == 1): return None x = stack.array[stack.top] stack.top -= 1 return x # Returns true if a pair with target# sum exists in BST, otherwise Falsedef isPairPresent(root,target): # Create two stacks. s1 is used for # normal inorder traversal and s2 is # used for reverse inorder traversal s1 = createStack(MAX_SIZE) s2 = createStack(MAX_SIZE) # Note the sizes of stacks is MAX_SIZE, # we can find the tree size and fix stack size # as O(Logn) for balanced trees like AVL and Red Black # tree. We have used MAX_SIZE to keep the code simple # done1, val1 and curr1 are used for # normal inorder traversal using s1 # done2, val2 and curr2 are used for # reverse inorder traversal using s2 done1,done2 = False,False val1,val2 = 0,0 curr1,curr2 = root,root # The loop will break when we either# find a pair or one of the two # traversals is complete while (True): # Find next node in normal Inorder # traversal. See following post # https:# www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ while (done1 == False): if (curr1 != None): push(s1, curr1) curr1 = curr1.left else: if (isEmpty(s1) == 1): done1 = True else: curr1 = pop(s1) val1 = curr1.val curr1 = curr1.right done1 = True # Find next node in REVERSE Inorder traversal. The only # difference between above and below loop is, in below loop # right subtree is traversed before left subtree while (done2 == False): if (curr2 != None): push(s2, curr2) curr2 = curr2.right else: if (isEmpty(s2) == 1): done2 = True else: curr2 = pop(s2) val2 = curr2.val curr2 = curr2.left done2 = True # If we find a pair, then print the pair and return. The first # condition makes sure that two same values are not added if ((val1 != val2) and (val1 + val2) == target): print("Pair Found: " +str(val1)+ " + " +str(val2)+ " = " +str(target)) return True # If sum of current values is smaller, # then move to next node in # normal inorder traversal elif ((val1 + val2) < target): done1 = False # If sum of current values is greater, # then move to next node in # reverse inorder traversal elif ((val1 + val2) > target): done2 = False # If any of the inorder traversals is # over, then there is no pair # so return False if (val1 >= val2): return False # Driver program to test above functions # 15 # / \ # 10 20 # / \ / \ # 8 12 16 25root = Node(15)root.left = Node(10)root.right = Node(20)root.left.left = Node(8)root.left.right = Node(12)root.right.left = Node(16)root.right.right = Node(25) target = 33if (isPairPresent(root, target) == False): print("<br>No such values are found") # This code is contributed by shinjanpatra /* In a balanced binary search treeisPairPresent two element which sums toa given value time O(n) space O(logn) */using System;using System.Collections.Generic; public class GFG{static readonly int MAX_SIZE= 100; // A BST nodepublic class node{ public int val; public node left, right;}; // Stack typepublic class Stack{ public int size; public int top; public node []array;}; // A utility function to create a stack of given sizestatic Stack createStack(int size){ Stack stack = new Stack(); stack.size = size; stack.top = -1; stack.array = new node[stack.size]; return stack;} // BASIC OPERATIONS OF STACKstatic int isFull(Stack stack){ return (stack.top - 1 == stack.size) ? 1 : 0 ;} static int isEmpty(Stack stack){ return stack.top == -1?1:0;} static void push(Stack stack, node node){ if (isFull(stack)==1) return; stack.array[++stack.top] = node;} static node pop(Stack stack){ if (isEmpty(stack) == 1) return null; return stack.array[stack.top--];} // Returns true if a pair with target// sum exists in BST, otherwise falsestatic bool isPairPresent(node root, int target){ // Create two stacks. s1 is used for // normal inorder traversal and s2 is // used for reverse inorder traversal Stack s1 = createStack(MAX_SIZE); Stack s2 = createStack(MAX_SIZE); // Note the sizes of stacks is MAX_SIZE, // we can find the tree size and fix stack size // as O(Logn) for balanced trees like AVL and Red Black // tree. We have used MAX_SIZE to keep the code simple // done1, val1 and curr1 are used for // normal inorder traversal using s1 // done2, val2 and curr2 are used for // reverse inorder traversal using s2 bool done1 = false, done2 = false; int val1 = 0, val2 = 0; node curr1 = root, curr2 = root; // The loop will break when we either // find a pair or one of the two // traversals is complete while (true) { // Find next node in normal Inorder // traversal. See following post // https:// www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ while (done1 == false) { if (curr1 != null) { push(s1, curr1); curr1 = curr1.left; } else { if (isEmpty(s1) == 1) done1 = true; else { curr1 = pop(s1); val1 = curr1.val; curr1 = curr1.right; done1 = true; } } } // Find next node in REVERSE Inorder traversal. The only // difference between above and below loop is, in below loop // right subtree is traversed before left subtree while (done2 == false) { if (curr2 != null) { push(s2, curr2); curr2 = curr2.right; } else { if (isEmpty(s2) == 1) done2 = true; else { curr2 = pop(s2); val2 = curr2.val; curr2 = curr2.left; done2 = true; } } } // If we find a pair, then print the pair and return. The first // condition makes sure that two same values are not added if ((val1 != val2) && (val1 + val2) == target) { Console.Write("Pair Found: " + val1+ "+ " + val2+ " = " + target +"\n"); return true; } // If sum of current values is smaller, // then move to next node in // normal inorder traversal else if ((val1 + val2) < target) done1 = false; // If sum of current values is greater, // then move to next node in // reverse inorder traversal else if ((val1 + val2) > target) done2 = false; // If any of the inorder traversals is // over, then there is no pair // so return false if (val1 >= val2) return false; }} // A utility function to create BST nodestatic node NewNode(int val){ node tmp = new node(); tmp.val = val; tmp.right = tmp.left = null; return tmp;} // Driver program to test above functionspublic static void Main(String[] args){ /* 15 / \ 10 20 / \ / \ 8 12 16 25 */ node root = NewNode(15); root.left = NewNode(10); root.right = NewNode(20); root.left.left = NewNode(8); root.left.right = NewNode(12); root.right.left = NewNode(16); root.right.right = NewNode(25); int target = 33; if (isPairPresent(root, target) == false) Console.Write("\nNo such values are found\n");}} // This code is contributed by aashish1995 <script>/* In a balanced binary search treeisPairPresent two element which sums toa given value time O(n) space O(logn) */ let MAX_SIZE= 100; // A BST nodeclass Node{ constructor(val) { this.val = val; this.left = this.right = null; }} // Stack typeclass Stack{ constructor() { this.size = 0; this.top = 0; this.array; }} // A utility function to create a stack of given sizefunction createStack(size){ let stack = new Stack(); stack.size = size; stack.top = -1; stack.array = new Array(stack.size); return stack;} // BASIC OPERATIONS OF STACKfunction isFull(stack){ return (stack.top - 1 == stack.size)?1:0 ;} function isEmpty(stack){ return stack.top == -1?1:0;} function push(stack,node){ if (isFull(stack)==1) return; stack.array[++stack.top] = node;} function pop(stack){ if (isEmpty(stack) == 1) return null; return stack.array[stack.top--];} // Returns true if a pair with target// sum exists in BST, otherwise falsefunction isPairPresent(root,target){ // Create two stacks. s1 is used for // normal inorder traversal and s2 is // used for reverse inorder traversal let s1 = createStack(MAX_SIZE); let s2 = createStack(MAX_SIZE); // Note the sizes of stacks is MAX_SIZE, // we can find the tree size and fix stack size // as O(Logn) for balanced trees like AVL and Red Black // tree. We have used MAX_SIZE to keep the code simple // done1, val1 and curr1 are used for // normal inorder traversal using s1 // done2, val2 and curr2 are used for // reverse inorder traversal using s2 let done1 = false, done2 = false; let val1 = 0, val2 = 0; let curr1 = root, curr2 = root; // The loop will break when we either // find a pair or one of the two // traversals is complete while (true) { // Find next node in normal Inorder // traversal. See following post // https:// www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ while (done1 == false) { if (curr1 != null) { push(s1, curr1); curr1 = curr1.left; } else { if (isEmpty(s1) == 1) done1 = true; else { curr1 = pop(s1); val1 = curr1.val; curr1 = curr1.right; done1 = true; } } } // Find next node in REVERSE Inorder traversal. The only // difference between above and below loop is, in below loop // right subtree is traversed before left subtree while (done2 == false) { if (curr2 != null) { push(s2, curr2); curr2 = curr2.right; } else { if (isEmpty(s2) == 1) done2 = true; else { curr2 = pop(s2); val2 = curr2.val; curr2 = curr2.left; done2 = true; } } } // If we find a pair, then print the pair and return. The first // condition makes sure that two same values are not added if ((val1 != val2) && (val1 + val2) == target) { document.write("Pair Found: " + val1+ "+ " + val2+ " = " + target +"<br>"); return true; } // If sum of current values is smaller, // then move to next node in // normal inorder traversal else if ((val1 + val2) < target) done1 = false; // If sum of current values is greater, // then move to next node in // reverse inorder traversal else if ((val1 + val2) > target) done2 = false; // If any of the inorder traversals is // over, then there is no pair // so return false if (val1 >= val2) return false; }} // Driver program to test above functions/* 15 / \ 10 20 / \ / \ 8 12 16 25 */let root = new Node(15);root.left = new Node(10);root.right = new Node(20);root.left.left = new Node(8);root.left.right = new Node(12);root.right.left = new Node(16);root.right.right = new Node(25); let target = 33;if (isPairPresent(root, target) == false) document.write("<br>No such values are found<br>"); // This code is contributed by avanitrachhadiya2155</script> Output: Pair Found: 8 + 25 = 33 Complexity Analysis: Time Complexity: O(n). Inorder Traversal of BST takes linear time.Auxiliary Space: O(logn). The stack holds log N values as at a single time Time Complexity: O(n). Inorder Traversal of BST takes linear time. Auxiliary Space: O(logn). The stack holds log N values as at a single time https://www.youtube.com/embed/TvAFvAoS6s8?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk This article is compiled by Kumar and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. rathbhupendra Rajput-Ji bidibaaz123 aashish1995 itwasme shindesharad71 avanitrachhadiya2155 ashutoshsinghgeeksforgeeks shinjanpatra Amazon OYO Rooms Snapdeal Visa VMWare Binary Search Tree VMWare Amazon OYO Rooms Snapdeal Visa Binary Search Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Sorted Array to Balanced BST Inorder Successor in Binary Search Tree Optimal Binary Search Tree | DP-24 Two nodes of a BST are swapped, correct the BST Find the node with minimum value in a Binary Search Tree Find k-th smallest element in BST (Order Statistics in BST) Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Difference between Binary Tree and Binary Search Tree Lowest Common Ancestor in a Binary Search Tree. Convert a normal BST to Balanced BST
[ { "code": null, "e": 24409, "s": 24381, "text": "\n17 Apr, 2022" }, { "code": null, "e": 24756, "s": 24409, "text": "Given a Balanced Binary Search Tree and a target sum, write a function that returns true if there is a pair with sum equals to target sum, otherwise return false. Expected time complexity is O(n) and only O(Logn) extra space can be used. Any modification to Binary Search Tree is not allowed. Note that height of a Balanced BST is always O(Logn)." }, { "code": null, "e": 24854, "s": 24756, "text": "This problem is mainly extension of the previous post. Here we are not allowed to modify the BST." }, { "code": null, "e": 25003, "s": 24854, "text": "The Brute Force Solution is to consider each pair in BST and check whether the sum equals to X. The time complexity of this solution will be O(n^2)." }, { "code": null, "e": 25343, "s": 25003, "text": "A Better Solution is to create an auxiliary array and store the Inorder traversal of BST in the array. The array will be sorted as Inorder traversal of BST always produces sorted data. Once we have the Inorder traversal, we can pair in O(n) time (See this for details). This solution works in O(n) time but requires O(n) auxiliary space. " }, { "code": null, "e": 25347, "s": 25343, "text": "C++" }, { "code": null, "e": 25352, "s": 25347, "text": "Java" }, { "code": null, "e": 25360, "s": 25352, "text": "Python3" }, { "code": null, "e": 25363, "s": 25360, "text": "C#" }, { "code": null, "e": 25374, "s": 25363, "text": "Javascript" }, { "code": "#include<bits/stdc++.h>using namespace std; class Node{ public: int data; Node* left; Node* right; Node(int d) { data=d; left=NULL; right=NULL; }}; class BinarySearchTree { // Root of BST public: Node *root; // Constructor BinarySearchTree() { root = NULL; } // Utility function for inorder traversal of the tree void inorderUtil(Node* node) { if (node == NULL) return; inorderUtil(node->left); cout << node->data << \" \"; inorderUtil(node->right); } // Inorder traversal of the tree void inorder() { inorderUtil(this->root); } /* A recursive function to insert a new key in BST */ Node* insertRec(Node* root, int data) { /* If the tree is empty, return a new node */ if (root == NULL) { root = new Node(data); return root; } /* Otherwise, recur down the tree */ if (data < root->data) root->left = insertRec(root->left, data); else if (data > root->data) root->right = insertRec(root->right, data); return root; } // This method mainly calls insertRec() void insert(int key) { root = insertRec(root, key); } // Method that adds values of given BST into vector // and hence returns the vector vector<int> treeToList(Node* node, vector<int>& list) { // Base Case if (node == NULL) return list; treeToList(node->left, list); list.push_back(node->data); treeToList(node->right, list); return list; } // method that checks if there is a pair present bool isPairPresent(Node* node, int target) { // This list a1 is passed as an argument // in treeToList method // which is later on filled by the values of BST vector<int> a1; // a2 list contains all the values of BST // returned by treeToList method vector<int> a2 = treeToList(node, a1); int start = 0; // Starting index of a2 int end = (int)a2.size() - 1; // Ending index of a2 while (start < end) { if (a2[start] + a2[end] == target) // Target Found! { cout << \"Pair Found: \" << a2[start] << \" + \" << a2[end] << \" = \" << target << '\\n'; return true; } if (a2[start] + a2[end] > target) // decrements end { end--; } if (a2[start] + a2[end] < target) // increments start { start++; } } cout << \"No such values are found!\\n\"; return false; }}; // Driver functionint main(){ BinarySearchTree *tree = new BinarySearchTree(); /* 15 / \\ 10 20 / \\ / \\ 8 12 16 25 */ tree->insert(15); tree->insert(10); tree->insert(20); tree->insert(8); tree->insert(12); tree->insert(16); tree->insert(25); tree->isPairPresent(tree->root, 33);}", "e": 28466, "s": 25374, "text": null }, { "code": "// Java code to find a pair with given sum// in a Balanced BSTimport java.util.ArrayList; // A binary tree nodeclass Node { int data; Node left, right; Node(int d) { data = d; left = right = null; }} class BinarySearchTree { // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // Inorder traversal of the tree void inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of the tree void inorderUtil(Node node) { if (node == null) return; inorderUtil(node.left); System.out.print(node.data + \" \"); inorderUtil(node.right); } // This method mainly calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int data) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(data); return root; } /* Otherwise, recur down the tree */ if (data < root.data) root.left = insertRec(root.left, data); else if (data > root.data) root.right = insertRec(root.right, data); return root; } // Method that adds values of given BST into ArrayList // and hence returns the ArrayList ArrayList<Integer> treeToList(Node node, ArrayList<Integer> list) { // Base Case if (node == null) return list; treeToList(node.left, list); list.add(node.data); treeToList(node.right, list); return list; } // method that checks if there is a pair present boolean isPairPresent(Node node, int target) { // This list a1 is passed as an argument // in treeToList method // which is later on filled by the values of BST ArrayList<Integer> a1 = new ArrayList<>(); // a2 list contains all the values of BST // returned by treeToList method ArrayList<Integer> a2 = treeToList(node, a1); int start = 0; // Starting index of a2 int end = a2.size() - 1; // Ending index of a2 while (start < end) { if (a2.get(start) + a2.get(end) == target) // Target Found! { System.out.println(\"Pair Found: \" + a2.get(start) + \" + \" + a2.get(end) + \" \" + \"= \" + target); return true; } if (a2.get(start) + a2.get(end) > target) // decrements end { end--; } if (a2.get(start) + a2.get(end) < target) // increments start { start++; } } System.out.println(\"No such values are found!\"); return false; } // Driver function public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* 15 / \\ 10 20 / \\ / \\ 8 12 16 25 */ tree.insert(15); tree.insert(10); tree.insert(20); tree.insert(8); tree.insert(12); tree.insert(16); tree.insert(25); tree.isPairPresent(tree.root, 33); }} // This code is contributed by Kamal Rawal", "e": 31881, "s": 28466, "text": null }, { "code": "# Python3 code to find a pair with given sum# in a Balanced BSTclass Node: # Construct to create a new Node def __init__(self, key): self.data = key self.left = self.right = None # A utility function to insert a new# Node with given key in BSTdef insert(root: Node, key: int): # If the tree is empty, return a new Node if root is None: return Node(key) # Otherwise, recur down the tree if root.data > key: root.left = insert(root.left, key) elif root.data < key: root.right = insert(root.right, key) # return the (unchanged) Node pointer return root # Function that adds values of given BST into# ArrayList and hence returns the ArrayListdef tree_to_list(root: Node, arr: list): if not root: return arr tree_to_list(root.left, arr) arr.append(root.data) tree_to_list(root.right, arr) return arr # Function that checks if there is a pair presentdef isPairPresent(root: Node, target: int) -> bool: # This list a1 is passed as an argument # in treeToList method which is later # on filled by the values of BST arr1 = [] # a2 list contains all the values of BST # returned by treeToList method arr2 = tree_to_list(root, arr1) # Starting index of a2 start = 0 # Ending index of a2 end = len(arr2) - 1 while start < end: # If target found if arr2[start] + arr2[end] == target: print(f\"Pair Found: {arr2[start]} + {arr2[end]} = {target}\") return True # Decrements end if arr2[start] + arr2[end] > target: end -= 1 # Increments start if arr2[start] + arr2[end] < target: start += 1 print(\"No such values are found!\") return False # Driver codeif __name__ == \"__main__\": root = None root = insert(root, 15) root = insert(root, 10) root = insert(root, 20) root = insert(root, 8) root = insert(root, 12) root = insert(root, 16) root = insert(root, 25) isPairPresent(root, 33) # This code is contributed by shindesharad71", "e": 34022, "s": 31881, "text": null }, { "code": "// C# code to find a pair with given sum// in a Balanced BSTusing System;using System.Collections.Generic; // A binary tree nodepublic class Node { public int data; public Node left, right; public Node(int d) { data = d; left = right = null; }} public class BinarySearchTree { // Root of BST Node root; // Constructor BinarySearchTree() { root = null; } // Inorder traversal of the tree void inorder() { inorderUtil(this.root); } // Utility function for inorder traversal of the tree void inorderUtil(Node node) { if (node == null) return; inorderUtil(node.left); Console.Write(node.data + \" \"); inorderUtil(node.right); } // This method mainly calls insertRec() void insert(int key) { root = insertRec(root, key); } /* A recursive function to insert a new key in BST */ Node insertRec(Node root, int data) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(data); return root; } /* Otherwise, recur down the tree */ if (data < root.data) root.left = insertRec(root.left, data); else if (data > root.data) root.right = insertRec(root.right, data); return root; } // Method that adds values of given BST into ArrayList // and hence returns the ArrayList List<int> treeToList(Node node, List<int> list) { // Base Case if (node == null) return list; treeToList(node.left, list); list.Add(node.data); treeToList(node.right, list); return list; } // method that checks if there is a pair present bool isPairPresent(Node node, int target) { // This list a1 is passed as an argument // in treeToList method // which is later on filled by the values of BST List<int> a1 = new List<int>(); // a2 list contains all the values of BST // returned by treeToList method List<int> a2 = treeToList(node, a1); int start = 0; // Starting index of a2 int end = a2.Count - 1; // Ending index of a2 while (start < end) { if (a2[start] + a2[end] == target) // Target Found! { Console.WriteLine(\"Pair Found: \" + a2[start] + \" + \" + a2[end] + \" \" + \"= \" + target); return true; } if (a2[start] + a2[end] > target) // decrements end { end--; } if (a2[start] + a2[end] < target) // increments start { start++; } } Console.WriteLine(\"No such values are found!\"); return false; } // Driver code public static void Main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* 15 / \\ 10 20 / \\ / \\ 8 12 16 25 */ tree.insert(15); tree.insert(10); tree.insert(20); tree.insert(8); tree.insert(12); tree.insert(16); tree.insert(25); tree.isPairPresent(tree.root, 33); }} // This code contributed by Rajput-Ji", "e": 37337, "s": 34022, "text": null }, { "code": "<script> // JavaScript code to find a pair with given sum // in a Balanced BST // A binary tree node class Node { constructor(d) { this.data = d; this.left = null; this.right = null; } } class BinarySearchTree { // Constructor constructor() { this.root = null; } // Inorder traversal of the tree inorder() { this.inorderUtil(this.root); } // Utility function for inorder traversal of the tree inorderUtil(node) { if (node == null) return; this.inorderUtil(node.left); document.write(node.data + \" \"); this.inorderUtil(node.right); } // This method mainly calls insertRec() insert(key) { this.root = this.insertRec(this.root, key); } /* A recursive function to insert a new key in BST */ insertRec(root, data) { /* If the tree is empty, return a new node */ if (root == null) { root = new Node(data); return root; } /* Otherwise, recur down the tree */ if (data < root.data) root.left = this.insertRec(root.left, data); else if (data > root.data) root.right = this.insertRec(root.right, data); return root; } // Method that adds values of given BST into ArrayList // and hence returns the ArrayList treeToList(node, list) { // Base Case if (node == null) return list; this.treeToList(node.left, list); list.push(node.data); this.treeToList(node.right, list); return list; } // method that checks if there is a pair present isPairPresent(node, target) { // This list a1 is passed as an argument // in treeToList method // which is later on filled by the values of BST var a1 = []; // a2 list contains all the values of BST // returned by treeToList method var a2 = this.treeToList(node, a1); var start = 0; // Starting index of a2 var end = a2.length - 1; // Ending index of a2 while (start < end) { if (a2[start] + a2[end] == target) { // Target Found! document.write( \"Pair Found: \" + a2[start] + \" + \" + a2[end] + \" \" + \"= \" + target + \"<br>\" ); return true; } if (a2[start] + a2[end] > target) { // decrements end end--; } if (a2[start] + a2[end] < target) { // increments start start++; } } document.write(\"No such values are found!\"); return false; } } // Driver code var tree = new BinarySearchTree(); /* 15 / \\ 10 20 / \\ / \\ 8 12 16 25 */ tree.insert(15); tree.insert(10); tree.insert(20); tree.insert(8); tree.insert(12); tree.insert(16); tree.insert(25); tree.isPairPresent(tree.root, 33); </script>", "e": 40675, "s": 37337, "text": null }, { "code": null, "e": 40686, "s": 40675, "text": "Output : " }, { "code": null, "e": 40710, "s": 40686, "text": "Pair Found: 8 + 25 = 33" }, { "code": null, "e": 40868, "s": 40710, "text": "Complexity Analysis: Time Complexity: O(n). Inorder Traversal of BST takes linear time.Auxiliary Space: O(n). Use of array for storing the Inorder Traversal." }, { "code": null, "e": 40935, "s": 40868, "text": "Time Complexity: O(n). Inorder Traversal of BST takes linear time." }, { "code": null, "e": 41006, "s": 40935, "text": "Auxiliary Space: O(n). Use of array for storing the Inorder Traversal." }, { "code": null, "e": 41265, "s": 41006, "text": "A space optimized solution is discussed in previous post. The idea was to first in-place convert BST to Doubly Linked List (DLL), then find pair in sorted DLL in O(n) time. This solution takes O(n) time and O(Logn) extra space, but it modifies the given BST." }, { "code": null, "e": 42041, "s": 41265, "text": "The solution discussed below takes O(n) time, O(Logn) space and doesn’t modify BST. The idea is same as finding the pair in sorted array (See method 1 of this for details). We traverse BST in Normal Inorder and Reverse Inorder simultaneously. In reverse inorder, we start from the rightmost node which is the maximum value node. In normal inorder, we start from the left most node which is minimum value node. We add sum of current nodes in both traversals and compare this sum with given target sum. If the sum is same as target sum, we return true. If the sum is more than target sum, we move to next node in reverse inorder traversal, otherwise we move to next node in normal inorder traversal. If any of the traversals is finished without finding a pair, we return false." }, { "code": null, "e": 42092, "s": 42041, "text": "Following is the implementation of this approach. " }, { "code": null, "e": 42096, "s": 42092, "text": "C++" }, { "code": null, "e": 42098, "s": 42096, "text": "C" }, { "code": null, "e": 42103, "s": 42098, "text": "Java" }, { "code": null, "e": 42111, "s": 42103, "text": "Python3" }, { "code": null, "e": 42114, "s": 42111, "text": "C#" }, { "code": null, "e": 42125, "s": 42114, "text": "Javascript" }, { "code": "/* In a balanced binary search treeisPairPresent two element which sums toa given value time O(n) space O(logn) */#include <bits/stdc++.h>using namespace std;#define MAX_SIZE 100 // A BST nodeclass node {public: int val; node *left, *right;}; // Stack typeclass Stack {public: int size; int top; node** array;}; // A utility function to create a stack of given sizeStack* createStack(int size){ Stack* stack = new Stack(); stack->size = size; stack->top = -1; stack->array = new node*[(stack->size * sizeof(node*))]; return stack;} // BASIC OPERATIONS OF STACKint isFull(Stack* stack){ return stack->top - 1 == stack->size;} int isEmpty(Stack* stack){ return stack->top == -1;} void push(Stack* stack, node* node){ if (isFull(stack)) return; stack->array[++stack->top] = node;} node* pop(Stack* stack){ if (isEmpty(stack)) return NULL; return stack->array[stack->top--];} // Returns true if a pair with target// sum exists in BST, otherwise falsebool isPairPresent(node* root, int target){ // Create two stacks. s1 is used for // normal inorder traversal and s2 is // used for reverse inorder traversal Stack* s1 = createStack(MAX_SIZE); Stack* s2 = createStack(MAX_SIZE); // Note the sizes of stacks is MAX_SIZE, // we can find the tree size and fix stack size // as O(Logn) for balanced trees like AVL and Red Black // tree. We have used MAX_SIZE to keep the code simple // done1, val1 and curr1 are used for // normal inorder traversal using s1 // done2, val2 and curr2 are used for // reverse inorder traversal using s2 bool done1 = false, done2 = false; int val1 = 0, val2 = 0; node *curr1 = root, *curr2 = root; // The loop will break when we either find a pair or one of the two // traversals is complete while (1) { // Find next node in normal Inorder // traversal. See following post // https:// www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ while (done1 == false) { if (curr1 != NULL) { push(s1, curr1); curr1 = curr1->left; } else { if (isEmpty(s1)) done1 = 1; else { curr1 = pop(s1); val1 = curr1->val; curr1 = curr1->right; done1 = 1; } } } // Find next node in REVERSE Inorder traversal. The only // difference between above and below loop is, in below loop // right subtree is traversed before left subtree while (done2 == false) { if (curr2 != NULL) { push(s2, curr2); curr2 = curr2->right; } else { if (isEmpty(s2)) done2 = 1; else { curr2 = pop(s2); val2 = curr2->val; curr2 = curr2->left; done2 = 1; } } } // If we find a pair, then print the pair and return. The first // condition makes sure that two same values are not added if ((val1 != val2) && (val1 + val2) == target) { cout << \"Pair Found: \" << val1 << \"+ \" << val2 << \" = \" << target << endl; return true; } // If sum of current values is smaller, // then move to next node in // normal inorder traversal else if ((val1 + val2) < target) done1 = false; // If sum of current values is greater, // then move to next node in // reverse inorder traversal else if ((val1 + val2) > target) done2 = false; // If any of the inorder traversals is // over, then there is no pair // so return false if (val1 >= val2) return false; }} // A utility function to create BST nodenode* NewNode(int val){ node* tmp = new node(); tmp->val = val; tmp->right = tmp->left = NULL; return tmp;} // Driver program to test above functionsint main(){ /* 15 / \\ 10 20 / \\ / \\ 8 12 16 25 */ node* root = NewNode(15); root->left = NewNode(10); root->right = NewNode(20); root->left->left = NewNode(8); root->left->right = NewNode(12); root->right->left = NewNode(16); root->right->right = NewNode(25); int target = 33; if (isPairPresent(root, target) == false) cout << \"\\nNo such values are found\\n\"; return 0;} // This code is contributed by rathbhupendra", "e": 46760, "s": 42125, "text": null }, { "code": "/* In a balanced binary search tree isPairPresent two element which sums to a given value time O(n) space O(logn) */#include <stdio.h>#include <stdlib.h>#define MAX_SIZE 100 // A BST nodestruct node { int val; struct node *left, *right;}; // Stack typestruct Stack { int size; int top; struct node** array;}; // A utility function to create a stack of given sizestruct Stack* createStack(int size){ struct Stack* stack = (struct Stack*)malloc(sizeof(struct Stack)); stack->size = size; stack->top = -1; stack->array = (struct node**)malloc(stack->size * sizeof(struct node*)); return stack;} // BASIC OPERATIONS OF STACKint isFull(struct Stack* stack){ return stack->top - 1 == stack->size;} int isEmpty(struct Stack* stack){ return stack->top == -1;} void push(struct Stack* stack, struct node* node){ if (isFull(stack)) return; stack->array[++stack->top] = node;} struct node* pop(struct Stack* stack){ if (isEmpty(stack)) return NULL; return stack->array[stack->top--];} // Returns true if a pair with target sum exists in BST, otherwise falsebool isPairPresent(struct node* root, int target){ // Create two stacks. s1 is used for normal inorder traversal // and s2 is used for reverse inorder traversal struct Stack* s1 = createStack(MAX_SIZE); struct Stack* s2 = createStack(MAX_SIZE); // Note the sizes of stacks is MAX_SIZE, we can find the tree size and // fix stack size as O(Logn) for balanced trees like AVL and Red Black // tree. We have used MAX_SIZE to keep the code simple // done1, val1 and curr1 are used for normal inorder traversal using s1 // done2, val2 and curr2 are used for reverse inorder traversal using s2 bool done1 = false, done2 = false; int val1 = 0, val2 = 0; struct node *curr1 = root, *curr2 = root; // The loop will break when we either find a pair or one of the two // traversals is complete while (1) { // Find next node in normal Inorder traversal. See following post // https:// www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ while (done1 == false) { if (curr1 != NULL) { push(s1, curr1); curr1 = curr1->left; } else { if (isEmpty(s1)) done1 = 1; else { curr1 = pop(s1); val1 = curr1->val; curr1 = curr1->right; done1 = 1; } } } // Find next node in REVERSE Inorder traversal. The only // difference between above and below loop is, in below loop // right subtree is traversed before left subtree while (done2 == false) { if (curr2 != NULL) { push(s2, curr2); curr2 = curr2->right; } else { if (isEmpty(s2)) done2 = 1; else { curr2 = pop(s2); val2 = curr2->val; curr2 = curr2->left; done2 = 1; } } } // If we find a pair, then print the pair and return. The first // condition makes sure that two same values are not added if ((val1 != val2) && (val1 + val2) == target) { printf(\"\\n Pair Found: %d + %d = %d\\n\", val1, val2, target); return true; } // If sum of current values is smaller, then move to next node in // normal inorder traversal else if ((val1 + val2) < target) done1 = false; // If sum of current values is greater, then move to next node in // reverse inorder traversal else if ((val1 + val2) > target) done2 = false; // If any of the inorder traversals is over, then there is no pair // so return false if (val1 >= val2) return false; }} // A utility function to create BST nodestruct node* NewNode(int val){ struct node* tmp = (struct node*)malloc(sizeof(struct node)); tmp->val = val; tmp->right = tmp->left = NULL; return tmp;} // Driver program to test above functionsint main(){ /* 15 / \\ 10 20 / \\ / \\ 8 12 16 25 */ struct node* root = NewNode(15); root->left = NewNode(10); root->right = NewNode(20); root->left->left = NewNode(8); root->left->right = NewNode(12); root->right->left = NewNode(16); root->right->right = NewNode(25); int target = 33; if (isPairPresent(root, target) == false) printf(\"\\n No such values are found\\n\"); getchar(); return 0;}", "e": 51497, "s": 46760, "text": null }, { "code": "/* In a balanced binary search treeisPairPresent two element which sums toa given value time O(n) space O(logn) */import java.util.*;class GFG{static final int MAX_SIZE= 100; // A BST nodestatic class node{ int val; node left, right;}; // Stack typestatic class Stack{ int size; int top; node []array;}; // A utility function to create a stack of given sizestatic Stack createStack(int size){ Stack stack = new Stack(); stack.size = size; stack.top = -1; stack.array = new node[stack.size]; return stack;} // BASIC OPERATIONS OF STACKstatic int isFull(Stack stack){ return (stack.top - 1 == stack.size)?1:0 ;} static int isEmpty(Stack stack){ return stack.top == -1?1:0;} static void push(Stack stack, node node){ if (isFull(stack)==1) return; stack.array[++stack.top] = node;} static node pop(Stack stack){ if (isEmpty(stack) == 1) return null; return stack.array[stack.top--];} // Returns true if a pair with target// sum exists in BST, otherwise falsestatic boolean isPairPresent(node root, int target){ // Create two stacks. s1 is used for // normal inorder traversal and s2 is // used for reverse inorder traversal Stack s1 = createStack(MAX_SIZE); Stack s2 = createStack(MAX_SIZE); // Note the sizes of stacks is MAX_SIZE, // we can find the tree size and fix stack size // as O(Logn) for balanced trees like AVL and Red Black // tree. We have used MAX_SIZE to keep the code simple // done1, val1 and curr1 are used for // normal inorder traversal using s1 // done2, val2 and curr2 are used for // reverse inorder traversal using s2 boolean done1 = false, done2 = false; int val1 = 0, val2 = 0; node curr1 = root, curr2 = root; // The loop will break when we either // find a pair or one of the two // traversals is complete while (true) { // Find next node in normal Inorder // traversal. See following post // https:// www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ while (done1 == false) { if (curr1 != null) { push(s1, curr1); curr1 = curr1.left; } else { if (isEmpty(s1) == 1) done1 = true; else { curr1 = pop(s1); val1 = curr1.val; curr1 = curr1.right; done1 = true; } } } // Find next node in REVERSE Inorder traversal. The only // difference between above and below loop is, in below loop // right subtree is traversed before left subtree while (done2 == false) { if (curr2 != null) { push(s2, curr2); curr2 = curr2.right; } else { if (isEmpty(s2) == 1) done2 = true; else { curr2 = pop(s2); val2 = curr2.val; curr2 = curr2.left; done2 = true; } } } // If we find a pair, then print the pair and return. The first // condition makes sure that two same values are not added if ((val1 != val2) && (val1 + val2) == target) { System.out.print(\"Pair Found: \" + val1+ \"+ \" + val2+ \" = \" + target +\"\\n\"); return true; } // If sum of current values is smaller, // then move to next node in // normal inorder traversal else if ((val1 + val2) < target) done1 = false; // If sum of current values is greater, // then move to next node in // reverse inorder traversal else if ((val1 + val2) > target) done2 = false; // If any of the inorder traversals is // over, then there is no pair // so return false if (val1 >= val2) return false; }} // A utility function to create BST nodestatic node NewNode(int val){ node tmp = new node(); tmp.val = val; tmp.right = tmp.left = null; return tmp;} // Driver program to test above functionspublic static void main(String[] args){ /* 15 / \\ 10 20 / \\ / \\ 8 12 16 25 */ node root = NewNode(15); root.left = NewNode(10); root.right = NewNode(20); root.left.left = NewNode(8); root.left.right = NewNode(12); root.right.left = NewNode(16); root.right.right = NewNode(25); int target = 33; if (isPairPresent(root, target) == false) System.out.print(\"\\nNo such values are found\\n\");}} // This code is contributed by aashish1995", "e": 56351, "s": 51497, "text": null }, { "code": "# In a balanced binary search tree# isPairPresent two element which sums to# a given value time O(n) space O(logn)MAX_SIZE= 100 # A BST nodeclass Node: def __init__(self,val): self.val = val self.left = self.right = None # Stack typeclass Stack: def __init__(self): self.size = 0 self.top = 0 self.array = [] # A utility function to create a stack of given sizedef createStack(size): stack = Stack() stack.size = size stack.top = -1 stack.array = [0 for i in range(stack.size)] return stack # BASIC OPERATIONS OF STACKdef isFull(stack): return 1 if(stack.top - 1 == stack.size) else 0 def isEmpty(stack): return 1 if stack.top == -1 else 0 def push(stack,node): if (isFull(stack)==1): return stack.array[stack.top+1] = node stack.top += 1 def pop(stack): if (isEmpty(stack) == 1): return None x = stack.array[stack.top] stack.top -= 1 return x # Returns true if a pair with target# sum exists in BST, otherwise Falsedef isPairPresent(root,target): # Create two stacks. s1 is used for # normal inorder traversal and s2 is # used for reverse inorder traversal s1 = createStack(MAX_SIZE) s2 = createStack(MAX_SIZE) # Note the sizes of stacks is MAX_SIZE, # we can find the tree size and fix stack size # as O(Logn) for balanced trees like AVL and Red Black # tree. We have used MAX_SIZE to keep the code simple # done1, val1 and curr1 are used for # normal inorder traversal using s1 # done2, val2 and curr2 are used for # reverse inorder traversal using s2 done1,done2 = False,False val1,val2 = 0,0 curr1,curr2 = root,root # The loop will break when we either# find a pair or one of the two # traversals is complete while (True): # Find next node in normal Inorder # traversal. See following post # https:# www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ while (done1 == False): if (curr1 != None): push(s1, curr1) curr1 = curr1.left else: if (isEmpty(s1) == 1): done1 = True else: curr1 = pop(s1) val1 = curr1.val curr1 = curr1.right done1 = True # Find next node in REVERSE Inorder traversal. The only # difference between above and below loop is, in below loop # right subtree is traversed before left subtree while (done2 == False): if (curr2 != None): push(s2, curr2) curr2 = curr2.right else: if (isEmpty(s2) == 1): done2 = True else: curr2 = pop(s2) val2 = curr2.val curr2 = curr2.left done2 = True # If we find a pair, then print the pair and return. The first # condition makes sure that two same values are not added if ((val1 != val2) and (val1 + val2) == target): print(\"Pair Found: \" +str(val1)+ \" + \" +str(val2)+ \" = \" +str(target)) return True # If sum of current values is smaller, # then move to next node in # normal inorder traversal elif ((val1 + val2) < target): done1 = False # If sum of current values is greater, # then move to next node in # reverse inorder traversal elif ((val1 + val2) > target): done2 = False # If any of the inorder traversals is # over, then there is no pair # so return False if (val1 >= val2): return False # Driver program to test above functions # 15 # / \\ # 10 20 # / \\ / \\ # 8 12 16 25root = Node(15)root.left = Node(10)root.right = Node(20)root.left.left = Node(8)root.left.right = Node(12)root.right.left = Node(16)root.right.right = Node(25) target = 33if (isPairPresent(root, target) == False): print(\"<br>No such values are found\") # This code is contributed by shinjanpatra", "e": 60507, "s": 56351, "text": null }, { "code": "/* In a balanced binary search treeisPairPresent two element which sums toa given value time O(n) space O(logn) */using System;using System.Collections.Generic; public class GFG{static readonly int MAX_SIZE= 100; // A BST nodepublic class node{ public int val; public node left, right;}; // Stack typepublic class Stack{ public int size; public int top; public node []array;}; // A utility function to create a stack of given sizestatic Stack createStack(int size){ Stack stack = new Stack(); stack.size = size; stack.top = -1; stack.array = new node[stack.size]; return stack;} // BASIC OPERATIONS OF STACKstatic int isFull(Stack stack){ return (stack.top - 1 == stack.size) ? 1 : 0 ;} static int isEmpty(Stack stack){ return stack.top == -1?1:0;} static void push(Stack stack, node node){ if (isFull(stack)==1) return; stack.array[++stack.top] = node;} static node pop(Stack stack){ if (isEmpty(stack) == 1) return null; return stack.array[stack.top--];} // Returns true if a pair with target// sum exists in BST, otherwise falsestatic bool isPairPresent(node root, int target){ // Create two stacks. s1 is used for // normal inorder traversal and s2 is // used for reverse inorder traversal Stack s1 = createStack(MAX_SIZE); Stack s2 = createStack(MAX_SIZE); // Note the sizes of stacks is MAX_SIZE, // we can find the tree size and fix stack size // as O(Logn) for balanced trees like AVL and Red Black // tree. We have used MAX_SIZE to keep the code simple // done1, val1 and curr1 are used for // normal inorder traversal using s1 // done2, val2 and curr2 are used for // reverse inorder traversal using s2 bool done1 = false, done2 = false; int val1 = 0, val2 = 0; node curr1 = root, curr2 = root; // The loop will break when we either // find a pair or one of the two // traversals is complete while (true) { // Find next node in normal Inorder // traversal. See following post // https:// www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ while (done1 == false) { if (curr1 != null) { push(s1, curr1); curr1 = curr1.left; } else { if (isEmpty(s1) == 1) done1 = true; else { curr1 = pop(s1); val1 = curr1.val; curr1 = curr1.right; done1 = true; } } } // Find next node in REVERSE Inorder traversal. The only // difference between above and below loop is, in below loop // right subtree is traversed before left subtree while (done2 == false) { if (curr2 != null) { push(s2, curr2); curr2 = curr2.right; } else { if (isEmpty(s2) == 1) done2 = true; else { curr2 = pop(s2); val2 = curr2.val; curr2 = curr2.left; done2 = true; } } } // If we find a pair, then print the pair and return. The first // condition makes sure that two same values are not added if ((val1 != val2) && (val1 + val2) == target) { Console.Write(\"Pair Found: \" + val1+ \"+ \" + val2+ \" = \" + target +\"\\n\"); return true; } // If sum of current values is smaller, // then move to next node in // normal inorder traversal else if ((val1 + val2) < target) done1 = false; // If sum of current values is greater, // then move to next node in // reverse inorder traversal else if ((val1 + val2) > target) done2 = false; // If any of the inorder traversals is // over, then there is no pair // so return false if (val1 >= val2) return false; }} // A utility function to create BST nodestatic node NewNode(int val){ node tmp = new node(); tmp.val = val; tmp.right = tmp.left = null; return tmp;} // Driver program to test above functionspublic static void Main(String[] args){ /* 15 / \\ 10 20 / \\ / \\ 8 12 16 25 */ node root = NewNode(15); root.left = NewNode(10); root.right = NewNode(20); root.left.left = NewNode(8); root.left.right = NewNode(12); root.right.left = NewNode(16); root.right.right = NewNode(25); int target = 33; if (isPairPresent(root, target) == false) Console.Write(\"\\nNo such values are found\\n\");}} // This code is contributed by aashish1995", "e": 65426, "s": 60507, "text": null }, { "code": "<script>/* In a balanced binary search treeisPairPresent two element which sums toa given value time O(n) space O(logn) */ let MAX_SIZE= 100; // A BST nodeclass Node{ constructor(val) { this.val = val; this.left = this.right = null; }} // Stack typeclass Stack{ constructor() { this.size = 0; this.top = 0; this.array; }} // A utility function to create a stack of given sizefunction createStack(size){ let stack = new Stack(); stack.size = size; stack.top = -1; stack.array = new Array(stack.size); return stack;} // BASIC OPERATIONS OF STACKfunction isFull(stack){ return (stack.top - 1 == stack.size)?1:0 ;} function isEmpty(stack){ return stack.top == -1?1:0;} function push(stack,node){ if (isFull(stack)==1) return; stack.array[++stack.top] = node;} function pop(stack){ if (isEmpty(stack) == 1) return null; return stack.array[stack.top--];} // Returns true if a pair with target// sum exists in BST, otherwise falsefunction isPairPresent(root,target){ // Create two stacks. s1 is used for // normal inorder traversal and s2 is // used for reverse inorder traversal let s1 = createStack(MAX_SIZE); let s2 = createStack(MAX_SIZE); // Note the sizes of stacks is MAX_SIZE, // we can find the tree size and fix stack size // as O(Logn) for balanced trees like AVL and Red Black // tree. We have used MAX_SIZE to keep the code simple // done1, val1 and curr1 are used for // normal inorder traversal using s1 // done2, val2 and curr2 are used for // reverse inorder traversal using s2 let done1 = false, done2 = false; let val1 = 0, val2 = 0; let curr1 = root, curr2 = root; // The loop will break when we either // find a pair or one of the two // traversals is complete while (true) { // Find next node in normal Inorder // traversal. See following post // https:// www.geeksforgeeks.org/inorder-tree-traversal-without-recursion/ while (done1 == false) { if (curr1 != null) { push(s1, curr1); curr1 = curr1.left; } else { if (isEmpty(s1) == 1) done1 = true; else { curr1 = pop(s1); val1 = curr1.val; curr1 = curr1.right; done1 = true; } } } // Find next node in REVERSE Inorder traversal. The only // difference between above and below loop is, in below loop // right subtree is traversed before left subtree while (done2 == false) { if (curr2 != null) { push(s2, curr2); curr2 = curr2.right; } else { if (isEmpty(s2) == 1) done2 = true; else { curr2 = pop(s2); val2 = curr2.val; curr2 = curr2.left; done2 = true; } } } // If we find a pair, then print the pair and return. The first // condition makes sure that two same values are not added if ((val1 != val2) && (val1 + val2) == target) { document.write(\"Pair Found: \" + val1+ \"+ \" + val2+ \" = \" + target +\"<br>\"); return true; } // If sum of current values is smaller, // then move to next node in // normal inorder traversal else if ((val1 + val2) < target) done1 = false; // If sum of current values is greater, // then move to next node in // reverse inorder traversal else if ((val1 + val2) > target) done2 = false; // If any of the inorder traversals is // over, then there is no pair // so return false if (val1 >= val2) return false; }} // Driver program to test above functions/* 15 / \\ 10 20 / \\ / \\ 8 12 16 25 */let root = new Node(15);root.left = new Node(10);root.right = new Node(20);root.left.left = new Node(8);root.left.right = new Node(12);root.right.left = new Node(16);root.right.right = new Node(25); let target = 33;if (isPairPresent(root, target) == false) document.write(\"<br>No such values are found<br>\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 70053, "s": 65426, "text": null }, { "code": null, "e": 70062, "s": 70053, "text": "Output: " }, { "code": null, "e": 70087, "s": 70062, "text": " Pair Found: 8 + 25 = 33" }, { "code": null, "e": 70249, "s": 70087, "text": "Complexity Analysis: Time Complexity: O(n). Inorder Traversal of BST takes linear time.Auxiliary Space: O(logn). The stack holds log N values as at a single time" }, { "code": null, "e": 70316, "s": 70249, "text": "Time Complexity: O(n). Inorder Traversal of BST takes linear time." }, { "code": null, "e": 70391, "s": 70316, "text": "Auxiliary Space: O(logn). The stack holds log N values as at a single time" }, { "code": null, "e": 70476, "s": 70393, "text": "https://www.youtube.com/embed/TvAFvAoS6s8?list=PLqM7alHXFySHCXD7r1J0ky9Zg_GBB1dbk " }, { "code": null, "e": 70672, "s": 70476, "text": "This article is compiled by Kumar and reviewed by GeeksforGeeks team. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 70688, "s": 70674, "text": "rathbhupendra" }, { "code": null, "e": 70698, "s": 70688, "text": "Rajput-Ji" }, { "code": null, "e": 70710, "s": 70698, "text": "bidibaaz123" }, { "code": null, "e": 70722, "s": 70710, "text": "aashish1995" }, { "code": null, "e": 70730, "s": 70722, "text": "itwasme" }, { "code": null, "e": 70745, "s": 70730, "text": "shindesharad71" }, { "code": null, "e": 70766, "s": 70745, "text": "avanitrachhadiya2155" }, { "code": null, "e": 70793, "s": 70766, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 70806, "s": 70793, "text": "shinjanpatra" }, { "code": null, "e": 70813, "s": 70806, "text": "Amazon" }, { "code": null, "e": 70823, "s": 70813, "text": "OYO Rooms" }, { "code": null, "e": 70832, "s": 70823, "text": "Snapdeal" }, { "code": null, "e": 70837, "s": 70832, "text": "Visa" }, { "code": null, "e": 70844, "s": 70837, "text": "VMWare" }, { "code": null, "e": 70863, "s": 70844, "text": "Binary Search Tree" }, { "code": null, "e": 70870, "s": 70863, "text": "VMWare" }, { "code": null, "e": 70877, "s": 70870, "text": "Amazon" }, { "code": null, "e": 70887, "s": 70877, "text": "OYO Rooms" }, { "code": null, "e": 70896, "s": 70887, "text": "Snapdeal" }, { "code": null, "e": 70901, "s": 70896, "text": "Visa" }, { "code": null, "e": 70920, "s": 70901, "text": "Binary Search Tree" }, { "code": null, "e": 71018, "s": 70920, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 71027, "s": 71018, "text": "Comments" }, { "code": null, "e": 71040, "s": 71027, "text": "Old Comments" }, { "code": null, "e": 71069, "s": 71040, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 71109, "s": 71069, "text": "Inorder Successor in Binary Search Tree" }, { "code": null, "e": 71144, "s": 71109, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 71192, "s": 71144, "text": "Two nodes of a BST are swapped, correct the BST" }, { "code": null, "e": 71249, "s": 71192, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 71309, "s": 71249, "text": "Find k-th smallest element in BST (Order Statistics in BST)" }, { "code": null, "e": 71379, "s": 71309, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 71433, "s": 71379, "text": "Difference between Binary Tree and Binary Search Tree" }, { "code": null, "e": 71481, "s": 71433, "text": "Lowest Common Ancestor in a Binary Search Tree." } ]
Link your Virtual Environment to Jupyter Using Kernels | by mlearnere | Towards Data Science
When I first started using Python, the concept of a virtual environment was extremely elusive to me. It often took me hours of searching and experimenting with creating one only to end up more confused than when I had started. This article aims to be a one-stop-shop for understanding what virtual environments exactly do, how to create them, and linking them to your Jupyter Notebook. What is a Virtual Environment? Create an Environment Using Anaconda Installing Packages into the Environment Using Virtual Environments in Jupyter as Kernels Deleting Environments and Kernels Let’s first start with the story of Bob. Bob works at a large financial firm as a Data Scientist. Bob and his team all use Python and regularly collaborate with each other on certain projects. However, since this financial firm is quite large, they all have numerous individual projects they are working on as well. Because of this, there needs to be a universal way to separate these projects from each other to ensure they run on any computer with Python installed. This is where virtual environments come into play. You can think of a virtual environment as a specific copy of Python in your computer that you can specify yourself. This copy can be any version of Python with any packages installed. Using virtual environments ensures that there are certain barriers between projects. These barriers in place make sure that anyone can run your version of Python regardless of what is on their computer. I will be using Anaconda in this tutorial as it makes creating and maintaining virtual environments extremely easy. If you do not have it downloaded, you can set up the individual edition on Anaconda’s website. It may take some time to download fully. If you allow Anaconda to set up a PATH variable, then you can follow what I do on your command prompt. If you do not, you can still follow these steps on your Anaconda Prompt that comes with the download. Let’s first start by creating a new environment. I will be naming it tutorial, but you can call it whatever you like: $ conda create -n tutorial python=3.7 Notes: -n indicates the name of the virtual environment python=3.7 is optional and can be changed to any version. I prefer setting a specific version when creating the environment as it will give you a “bare bones” Python environment to work within. You will be asked to proceed with a set of packages to be installed. Type in y and hit Enter. Now that our environment is created, we are given a prompt by Anaconda. ## To activate this environment, use## $ conda activate tutorial## To deactivate an active environment, use## $ conda deactivate So we will do just that. To activate our environment: $ conda activate tutorial This what we should expect to see: Notice how the name of the virtual environment is in parentheses appeared when we activated it. This is how we know we are inside the environment. To install packages, we can just use pip as we would for any other packages. Since the aim of this article is to also allow us to use the virtual environment in Jupyter, we will install ipykernel to do the job for us. However, you may install any needed packages for your project at this stage. $ pip install ipykernel Let the prompt run and install ipykernel. We can now create Python kernels for Jupyter. When using Jupyter notebooks, you can either use plain text or code. The code blocks we use are kernels. We can create new kernels with ipykernel. When we create kernels, we can link it to our virtual environment. This becomes very useful when you are creating a new project and you are unsure of the necessary packages you need. Whether you remove two-thirds of the installed packages or install one more, the kernel will always mirror the virtual environment we created. To do this: $ python -m ipykernel install --user --name=tutorial Now to verify if the kernel is in our Jupyter notebooks: As you can see, tutorial is now available as one of our kernels. We can now create new notebooks with this environment or utilize existing notebooks with this new kernel. For management purposes, I will also show you how to reverse what we have accomplished in this article. First, deactivate your virtual environment. $ conda deactivate You should see (tutorial) go away. First, see the list of kernels on your computer. If you have never done this before reading this article, you should expect a list of two kernels: Python 3 and the kernel we just created. $ jupyter kernelspec list Now that we know what we have, we know what to remove. To remove the kernel use the command below. You will be asked to verify with y once more. $ jupyter kernelspec remove tutorial Once it has completed, verify once more that it has been removed with jupyter kernelspec list. Removing virtual environments largely follows the same procedure as removing kernels. First, to view the list of environments we have: $ conda env list Do not worry if you do not have blind-source-separation in your list. This is one of my projects that I am working on personally. You should expect to see base and tutorial. To remove tutorial: $ conda env remove -n tutorial Once it has been removed, view the environment list for verification. I hope this tutorial helped you understand how to create virtual environments and link them to your Jupyter notebooks. Feel free to save this article to save you time from searching for these procedures again and again. Thank you for reading.
[ { "code": null, "e": 399, "s": 172, "text": "When I first started using Python, the concept of a virtual environment was extremely elusive to me. It often took me hours of searching and experimenting with creating one only to end up more confused than when I had started." }, { "code": null, "e": 558, "s": 399, "text": "This article aims to be a one-stop-shop for understanding what virtual environments exactly do, how to create them, and linking them to your Jupyter Notebook." }, { "code": null, "e": 589, "s": 558, "text": "What is a Virtual Environment?" }, { "code": null, "e": 626, "s": 589, "text": "Create an Environment Using Anaconda" }, { "code": null, "e": 667, "s": 626, "text": "Installing Packages into the Environment" }, { "code": null, "e": 716, "s": 667, "text": "Using Virtual Environments in Jupyter as Kernels" }, { "code": null, "e": 750, "s": 716, "text": "Deleting Environments and Kernels" }, { "code": null, "e": 791, "s": 750, "text": "Let’s first start with the story of Bob." }, { "code": null, "e": 1269, "s": 791, "text": "Bob works at a large financial firm as a Data Scientist. Bob and his team all use Python and regularly collaborate with each other on certain projects. However, since this financial firm is quite large, they all have numerous individual projects they are working on as well. Because of this, there needs to be a universal way to separate these projects from each other to ensure they run on any computer with Python installed. This is where virtual environments come into play." }, { "code": null, "e": 1656, "s": 1269, "text": "You can think of a virtual environment as a specific copy of Python in your computer that you can specify yourself. This copy can be any version of Python with any packages installed. Using virtual environments ensures that there are certain barriers between projects. These barriers in place make sure that anyone can run your version of Python regardless of what is on their computer." }, { "code": null, "e": 1908, "s": 1656, "text": "I will be using Anaconda in this tutorial as it makes creating and maintaining virtual environments extremely easy. If you do not have it downloaded, you can set up the individual edition on Anaconda’s website. It may take some time to download fully." }, { "code": null, "e": 2113, "s": 1908, "text": "If you allow Anaconda to set up a PATH variable, then you can follow what I do on your command prompt. If you do not, you can still follow these steps on your Anaconda Prompt that comes with the download." }, { "code": null, "e": 2231, "s": 2113, "text": "Let’s first start by creating a new environment. I will be naming it tutorial, but you can call it whatever you like:" }, { "code": null, "e": 2269, "s": 2231, "text": "$ conda create -n tutorial python=3.7" }, { "code": null, "e": 2276, "s": 2269, "text": "Notes:" }, { "code": null, "e": 2325, "s": 2276, "text": "-n indicates the name of the virtual environment" }, { "code": null, "e": 2519, "s": 2325, "text": "python=3.7 is optional and can be changed to any version. I prefer setting a specific version when creating the environment as it will give you a “bare bones” Python environment to work within." }, { "code": null, "e": 2613, "s": 2519, "text": "You will be asked to proceed with a set of packages to be installed. Type in y and hit Enter." }, { "code": null, "e": 2685, "s": 2613, "text": "Now that our environment is created, we are given a prompt by Anaconda." }, { "code": null, "e": 2822, "s": 2685, "text": "## To activate this environment, use## $ conda activate tutorial## To deactivate an active environment, use## $ conda deactivate" }, { "code": null, "e": 2876, "s": 2822, "text": "So we will do just that. To activate our environment:" }, { "code": null, "e": 2902, "s": 2876, "text": "$ conda activate tutorial" }, { "code": null, "e": 2937, "s": 2902, "text": "This what we should expect to see:" }, { "code": null, "e": 3084, "s": 2937, "text": "Notice how the name of the virtual environment is in parentheses appeared when we activated it. This is how we know we are inside the environment." }, { "code": null, "e": 3379, "s": 3084, "text": "To install packages, we can just use pip as we would for any other packages. Since the aim of this article is to also allow us to use the virtual environment in Jupyter, we will install ipykernel to do the job for us. However, you may install any needed packages for your project at this stage." }, { "code": null, "e": 3403, "s": 3379, "text": "$ pip install ipykernel" }, { "code": null, "e": 3491, "s": 3403, "text": "Let the prompt run and install ipykernel. We can now create Python kernels for Jupyter." }, { "code": null, "e": 3638, "s": 3491, "text": "When using Jupyter notebooks, you can either use plain text or code. The code blocks we use are kernels. We can create new kernels with ipykernel." }, { "code": null, "e": 3964, "s": 3638, "text": "When we create kernels, we can link it to our virtual environment. This becomes very useful when you are creating a new project and you are unsure of the necessary packages you need. Whether you remove two-thirds of the installed packages or install one more, the kernel will always mirror the virtual environment we created." }, { "code": null, "e": 3976, "s": 3964, "text": "To do this:" }, { "code": null, "e": 4029, "s": 3976, "text": "$ python -m ipykernel install --user --name=tutorial" }, { "code": null, "e": 4086, "s": 4029, "text": "Now to verify if the kernel is in our Jupyter notebooks:" }, { "code": null, "e": 4257, "s": 4086, "text": "As you can see, tutorial is now available as one of our kernels. We can now create new notebooks with this environment or utilize existing notebooks with this new kernel." }, { "code": null, "e": 4405, "s": 4257, "text": "For management purposes, I will also show you how to reverse what we have accomplished in this article. First, deactivate your virtual environment." }, { "code": null, "e": 4424, "s": 4405, "text": "$ conda deactivate" }, { "code": null, "e": 4459, "s": 4424, "text": "You should see (tutorial) go away." }, { "code": null, "e": 4647, "s": 4459, "text": "First, see the list of kernels on your computer. If you have never done this before reading this article, you should expect a list of two kernels: Python 3 and the kernel we just created." }, { "code": null, "e": 4673, "s": 4647, "text": "$ jupyter kernelspec list" }, { "code": null, "e": 4818, "s": 4673, "text": "Now that we know what we have, we know what to remove. To remove the kernel use the command below. You will be asked to verify with y once more." }, { "code": null, "e": 4855, "s": 4818, "text": "$ jupyter kernelspec remove tutorial" }, { "code": null, "e": 4950, "s": 4855, "text": "Once it has completed, verify once more that it has been removed with jupyter kernelspec list." }, { "code": null, "e": 5085, "s": 4950, "text": "Removing virtual environments largely follows the same procedure as removing kernels. First, to view the list of environments we have:" }, { "code": null, "e": 5102, "s": 5085, "text": "$ conda env list" }, { "code": null, "e": 5296, "s": 5102, "text": "Do not worry if you do not have blind-source-separation in your list. This is one of my projects that I am working on personally. You should expect to see base and tutorial. To remove tutorial:" }, { "code": null, "e": 5327, "s": 5296, "text": "$ conda env remove -n tutorial" }, { "code": null, "e": 5397, "s": 5327, "text": "Once it has been removed, view the environment list for verification." }, { "code": null, "e": 5617, "s": 5397, "text": "I hope this tutorial helped you understand how to create virtual environments and link them to your Jupyter notebooks. Feel free to save this article to save you time from searching for these procedures again and again." } ]
Biopython - Entrez Database
Entrez is an online search system provided by NCBI. It provides access to nearly all known molecular biology databases with an integrated global query supporting Boolean operators and field search. It returns results from all the databases with information like the number of hits from each databases, records with links to the originating database, etc. Some of the popular databases which can be accessed through Entrez are listed below − Pubmed Pubmed Central Nucleotide (GenBank Sequence Database) Protein (Sequence Database) Genome (Whole Genome Database) Structure (Three Dimensional Macromolecular Structure) Taxonomy (Organisms in GenBank) SNP (Single Nucleotide Polymorphism) UniGene (Gene Oriented Clusters of Transcript Sequences) CDD (Conserved Protein Domain Database) 3D Domains (Domains from Entrez Structure) In addition to the above databases, Entrez provides many more databases to perform the field search. Biopython provides an Entrez specific module, Bio.Entrez to access Entrez database. Let us learn how to access Entrez using Biopython in this chapter − To add the features of Entrez, import the following module − >>> from Bio import Entrez Next set your email to identify who is connected with the code given below − >>> Entrez.email = '<youremail>' Then, set the Entrez tool parameter and by default, it is Biopython. >>> Entrez.tool = 'Demoscript' Now, call einfo function to find index term counts, last update, and available links for each database as defined below − >>> info = Entrez.einfo() The einfo method returns an object, which provides access to the information through its read method as shown below − >>> data = info.read() >>> print(data) <?xml version = "1.0" encoding = "UTF-8" ?> <!DOCTYPE eInfoResult PUBLIC "-//NLM//DTD einfo 20130322//EN" "https://eutils.ncbi.nlm.nih.gov/eutils/dtd/20130322/einfo.dtd"> <eInfoResult> <DbList> <DbName>pubmed</DbName> <DbName>protein</DbName> <DbName>nuccore</DbName> <DbName>ipg</DbName> <DbName>nucleotide</DbName> <DbName>nucgss</DbName> <DbName>nucest</DbName> <DbName>structure</DbName> <DbName>sparcle</DbName> <DbName>genome</DbName> <DbName>annotinfo</DbName> <DbName>assembly</DbName> <DbName>bioproject</DbName> <DbName>biosample</DbName> <DbName>blastdbinfo</DbName> <DbName>books</DbName> <DbName>cdd</DbName> <DbName>clinvar</DbName> <DbName>clone</DbName> <DbName>gap</DbName> <DbName>gapplus</DbName> <DbName>grasp</DbName> <DbName>dbvar</DbName> <DbName>gene</DbName> <DbName>gds</DbName> <DbName>geoprofiles</DbName> <DbName>homologene</DbName> <DbName>medgen</DbName> <DbName>mesh</DbName> <DbName>ncbisearch</DbName> <DbName>nlmcatalog</DbName> <DbName>omim</DbName> <DbName>orgtrack</DbName> <DbName>pmc</DbName> <DbName>popset</DbName> <DbName>probe</DbName> <DbName>proteinclusters</DbName> <DbName>pcassay</DbName> <DbName>biosystems</DbName> <DbName>pccompound</DbName> <DbName>pcsubstance</DbName> <DbName>pubmedhealth</DbName> <DbName>seqannot</DbName> <DbName>snp</DbName> <DbName>sra</DbName> <DbName>taxonomy</DbName> <DbName>biocollections</DbName> <DbName>unigene</DbName> <DbName>gencoll</DbName> <DbName>gtr</DbName> </DbList> </eInfoResult> The data is in XML format, and to get the data as python object, use Entrez.read method as soon as Entrez.einfo() method is invoked − >>> info = Entrez.einfo() >>> record = Entrez.read(info) Here, record is a dictionary which has one key, DbList as shown below − >>> record.keys() [u'DbList'] Accessing the DbList key returns the list of database names shown below − >>> record[u'DbList'] ['pubmed', 'protein', 'nuccore', 'ipg', 'nucleotide', 'nucgss', 'nucest', 'structure', 'sparcle', 'genome', 'annotinfo', 'assembly', 'bioproject', 'biosample', 'blastdbinfo', 'books', 'cdd', 'clinvar', 'clone', 'gap', 'gapplus', 'grasp', 'dbvar', 'gene', 'gds', 'geoprofiles', 'homologene', 'medgen', 'mesh', 'ncbisearch', 'nlmcatalog', 'omim', 'orgtrack', 'pmc', 'popset', 'probe', 'proteinclusters', 'pcassay', 'biosystems', 'pccompound', 'pcsubstance', 'pubmedhealth', 'seqannot', 'snp', 'sra', 'taxonomy', 'biocollections', 'unigene', 'gencoll', 'gtr'] >>> Basically, Entrez module parses the XML returned by Entrez search system and provide it as python dictionary and lists. To search any of one the Entrez databases, we can use Bio.Entrez.esearch() module. It is defined below − >>> info = Entrez.einfo() >>> info = Entrez.esearch(db = "pubmed",term = "genome") >>> record = Entrez.read(info) >>>print(record) DictElement({u'Count': '1146113', u'RetMax': '20', u'IdList': ['30347444', '30347404', '30347317', '30347292', '30347286', '30347249', '30347194', '30347187', '30347172', '30347088', '30347075', '30346992', '30346990', '30346982', '30346980', '30346969', '30346962', '30346954', '30346941', '30346939'], u'TranslationStack': [DictElement({u'Count': '927819', u'Field': 'MeSH Terms', u'Term': '"genome"[MeSH Terms]', u'Explode': 'Y'}, attributes = {}) , DictElement({u'Count': '422712', u'Field': 'All Fields', u'Term': '"genome"[All Fields]', u'Explode': 'N'}, attributes = {}), 'OR', 'GROUP'], u'TranslationSet': [DictElement({u'To': '"genome"[MeSH Terms] OR "genome"[All Fields]', u'From': 'genome'}, attributes = {})], u'RetStart': '0', u'QueryTranslation': '"genome"[MeSH Terms] OR "genome"[All Fields]'}, attributes = {}) >>> If you assign incorrect db then it returns >>> info = Entrez.esearch(db = "blastdbinfo",term = "books") >>> record = Entrez.read(info) >>> print(record) DictElement({u'Count': '0', u'RetMax': '0', u'IdList': [], u'WarningList': DictElement({u'OutputMessage': ['No items found.'], u'PhraseIgnored': [], u'QuotedPhraseNotFound': []}, attributes = {}), u'ErrorList': DictElement({u'FieldNotFound': [], u'PhraseNotFound': ['books']}, attributes = {}), u'TranslationSet': [], u'RetStart': '0', u'QueryTranslation': '(books[All Fields])'}, attributes = {}) If you want to search across database, then you can use Entrez.egquery. This is similar to Entrez.esearch except it is enough to specify the keyword and skip the database parameter. >>>info = Entrez.egquery(term = "entrez") >>> record = Entrez.read(info) >>> for row in record["eGQueryResult"]: ... print(row["DbName"], row["Count"]) ... pubmed 458 pmc 12779 mesh 1 ... ... ... biosample 7 biocollections 0 Enterz provides a special method, efetch to search and download the full details of a record from Entrez. Consider the following simple example − >>> handle = Entrez.efetch( db = "nucleotide", id = "EU490707", rettype = "fasta") Now, we can simply read the records using SeqIO object >>> record = SeqIO.read( handle, "fasta" ) >>> record SeqRecord(seq = Seq('ATTTTTTACGAACCTGTGGAAATTTTTGGTTATGACAATAAATCTAGTTTAGTA...GAA', SingleLetterAlphabet()), id = 'EU490707.1', name = 'EU490707.1', description = 'EU490707.1 Selenipedium aequinoctiale maturase K (matK) gene, partial cds; chloroplast', dbxrefs = []) Print Add Notes Bookmark this page
[ { "code": null, "e": 2461, "s": 2106, "text": "Entrez is an online search system provided by NCBI. It provides access to nearly all known molecular biology databases with an integrated global query supporting Boolean operators and field search. It returns results from all the databases with information like the number of hits from each databases, records with links to the originating database, etc." }, { "code": null, "e": 2547, "s": 2461, "text": "Some of the popular databases which can be accessed through Entrez are listed below −" }, { "code": null, "e": 2554, "s": 2547, "text": "Pubmed" }, { "code": null, "e": 2569, "s": 2554, "text": "Pubmed Central" }, { "code": null, "e": 2608, "s": 2569, "text": "Nucleotide (GenBank Sequence Database)" }, { "code": null, "e": 2636, "s": 2608, "text": "Protein (Sequence Database)" }, { "code": null, "e": 2667, "s": 2636, "text": "Genome (Whole Genome Database)" }, { "code": null, "e": 2722, "s": 2667, "text": "Structure (Three Dimensional Macromolecular Structure)" }, { "code": null, "e": 2754, "s": 2722, "text": "Taxonomy (Organisms in GenBank)" }, { "code": null, "e": 2791, "s": 2754, "text": "SNP (Single Nucleotide Polymorphism)" }, { "code": null, "e": 2848, "s": 2791, "text": "UniGene (Gene Oriented Clusters of Transcript Sequences)" }, { "code": null, "e": 2888, "s": 2848, "text": "CDD (Conserved Protein Domain Database)" }, { "code": null, "e": 2931, "s": 2888, "text": "3D Domains (Domains from Entrez Structure)" }, { "code": null, "e": 3032, "s": 2931, "text": "In addition to the above databases, Entrez provides many more databases to perform the field search." }, { "code": null, "e": 3184, "s": 3032, "text": "Biopython provides an Entrez specific module, Bio.Entrez to access Entrez database. Let us learn how to access Entrez using Biopython in this chapter −" }, { "code": null, "e": 3245, "s": 3184, "text": "To add the features of Entrez, import the following module −" }, { "code": null, "e": 3273, "s": 3245, "text": ">>> from Bio import Entrez\n" }, { "code": null, "e": 3350, "s": 3273, "text": "Next set your email to identify who is connected with the code given below −" }, { "code": null, "e": 3384, "s": 3350, "text": ">>> Entrez.email = '<youremail>'\n" }, { "code": null, "e": 3453, "s": 3384, "text": "Then, set the Entrez tool parameter and by default, it is Biopython." }, { "code": null, "e": 3485, "s": 3453, "text": ">>> Entrez.tool = 'Demoscript'\n" }, { "code": null, "e": 3607, "s": 3485, "text": "Now, call einfo function to find index term counts, last update, and available links for each database as defined below −" }, { "code": null, "e": 3634, "s": 3607, "text": ">>> info = Entrez.einfo()\n" }, { "code": null, "e": 3752, "s": 3634, "text": "The einfo method returns an object, which provides access to the information through its read method as shown below −" }, { "code": null, "e": 5606, "s": 3752, "text": ">>> data = info.read() \n>>> print(data) \n<?xml version = \"1.0\" encoding = \"UTF-8\" ?>\n<!DOCTYPE eInfoResult PUBLIC \"-//NLM//DTD einfo 20130322//EN\" \n \"https://eutils.ncbi.nlm.nih.gov/eutils/dtd/20130322/einfo.dtd\"> \n<eInfoResult>\n <DbList>\n <DbName>pubmed</DbName> \n <DbName>protein</DbName>\n <DbName>nuccore</DbName> \n <DbName>ipg</DbName> \n <DbName>nucleotide</DbName>\n <DbName>nucgss</DbName> \n <DbName>nucest</DbName>\n <DbName>structure</DbName>\n <DbName>sparcle</DbName>\n <DbName>genome</DbName>\n <DbName>annotinfo</DbName>\n <DbName>assembly</DbName> \n <DbName>bioproject</DbName>\n <DbName>biosample</DbName>\n <DbName>blastdbinfo</DbName>\n <DbName>books</DbName> \n <DbName>cdd</DbName>\n <DbName>clinvar</DbName> \n <DbName>clone</DbName> \n <DbName>gap</DbName> \n <DbName>gapplus</DbName> \n <DbName>grasp</DbName> \n <DbName>dbvar</DbName>\n <DbName>gene</DbName> \n <DbName>gds</DbName> \n <DbName>geoprofiles</DbName>\n <DbName>homologene</DbName> \n <DbName>medgen</DbName> \n <DbName>mesh</DbName>\n <DbName>ncbisearch</DbName> \n <DbName>nlmcatalog</DbName>\n <DbName>omim</DbName>\n <DbName>orgtrack</DbName>\n <DbName>pmc</DbName>\n <DbName>popset</DbName>\n <DbName>probe</DbName>\n <DbName>proteinclusters</DbName>\n <DbName>pcassay</DbName>\n <DbName>biosystems</DbName> \n <DbName>pccompound</DbName> \n <DbName>pcsubstance</DbName> \n <DbName>pubmedhealth</DbName> \n <DbName>seqannot</DbName> \n <DbName>snp</DbName> \n <DbName>sra</DbName> \n <DbName>taxonomy</DbName> \n <DbName>biocollections</DbName> \n <DbName>unigene</DbName>\n <DbName>gencoll</DbName> \n <DbName>gtr</DbName>\n </DbList> \n</eInfoResult>" }, { "code": null, "e": 5740, "s": 5606, "text": "The data is in XML format, and to get the data as python object, use Entrez.read method as soon as Entrez.einfo() method is invoked −" }, { "code": null, "e": 5799, "s": 5740, "text": ">>> info = Entrez.einfo() \n>>> record = Entrez.read(info)\n" }, { "code": null, "e": 5871, "s": 5799, "text": "Here, record is a dictionary which has one key, DbList as shown below −" }, { "code": null, "e": 5903, "s": 5871, "text": ">>> record.keys() \n[u'DbList']\n" }, { "code": null, "e": 5977, "s": 5903, "text": "Accessing the DbList key returns the list of database names shown below −" }, { "code": null, "e": 6590, "s": 5977, "text": ">>> record[u'DbList'] \n['pubmed', 'protein', 'nuccore', 'ipg', 'nucleotide', 'nucgss', \n 'nucest', 'structure', 'sparcle', 'genome', 'annotinfo', 'assembly', \n 'bioproject', 'biosample', 'blastdbinfo', 'books', 'cdd', 'clinvar', \n 'clone', 'gap', 'gapplus', 'grasp', 'dbvar', 'gene', 'gds', 'geoprofiles', \n 'homologene', 'medgen', 'mesh', 'ncbisearch', 'nlmcatalog', 'omim', \n 'orgtrack', 'pmc', 'popset', 'probe', 'proteinclusters', 'pcassay', \n 'biosystems', 'pccompound', 'pcsubstance', 'pubmedhealth', 'seqannot', \n 'snp', 'sra', 'taxonomy', 'biocollections', 'unigene', 'gencoll', 'gtr'] \n>>>" }, { "code": null, "e": 6710, "s": 6590, "text": "Basically, Entrez module parses the XML returned by Entrez search system and provide it as python dictionary and lists." }, { "code": null, "e": 6815, "s": 6710, "text": "To search any of one the Entrez databases, we can use Bio.Entrez.esearch() module. It is defined below −" }, { "code": null, "e": 7793, "s": 6815, "text": ">>> info = Entrez.einfo() \n>>> info = Entrez.esearch(db = \"pubmed\",term = \"genome\") \n>>> record = Entrez.read(info) \n>>>print(record) \nDictElement({u'Count': '1146113', u'RetMax': '20', u'IdList':\n['30347444', '30347404', '30347317', '30347292', \n'30347286', '30347249', '30347194', '30347187', \n'30347172', '30347088', '30347075', '30346992', \n'30346990', '30346982', '30346980', '30346969', \n'30346962', '30346954', '30346941', '30346939'], \nu'TranslationStack': [DictElement({u'Count': \n'927819', u'Field': 'MeSH Terms', u'Term': '\"genome\"[MeSH Terms]', \nu'Explode': 'Y'}, attributes = {})\n, DictElement({u'Count': '422712', u'Field': \n'All Fields', u'Term': '\"genome\"[All Fields]', u'Explode': 'N'}, attributes = {}), \n'OR', 'GROUP'], u'TranslationSet': [DictElement({u'To': '\"genome\"[MeSH Terms] \nOR \"genome\"[All Fields]', u'From': 'genome'}, attributes = {})], u'RetStart': '0', \nu'QueryTranslation': '\"genome\"[MeSH Terms] OR \"genome\"[All Fields]'}, \nattributes = {})\n>>>" }, { "code": null, "e": 7836, "s": 7793, "text": "If you assign incorrect db then it returns" }, { "code": null, "e": 8369, "s": 7836, "text": ">>> info = Entrez.esearch(db = \"blastdbinfo\",term = \"books\")\n>>> record = Entrez.read(info) \n>>> print(record) \nDictElement({u'Count': '0', u'RetMax': '0', u'IdList': [], \nu'WarningList': DictElement({u'OutputMessage': ['No items found.'], \n u'PhraseIgnored': [], u'QuotedPhraseNotFound': []}, attributes = {}), \n u'ErrorList': DictElement({u'FieldNotFound': [], u'PhraseNotFound': \n ['books']}, attributes = {}), u'TranslationSet': [], u'RetStart': '0', \n u'QueryTranslation': '(books[All Fields])'}, attributes = {})" }, { "code": null, "e": 8551, "s": 8369, "text": "If you want to search across database, then you can use Entrez.egquery. This is similar to Entrez.esearch except it is enough to specify the keyword and skip the database parameter." }, { "code": null, "e": 8787, "s": 8551, "text": ">>>info = Entrez.egquery(term = \"entrez\") \n>>> record = Entrez.read(info) \n>>> for row in record[\"eGQueryResult\"]: \n... print(row[\"DbName\"], row[\"Count\"]) \n... \npubmed 458 \npmc 12779 mesh 1 \n... \n... \n... \nbiosample 7 \nbiocollections 0" }, { "code": null, "e": 8933, "s": 8787, "text": "Enterz provides a special method, efetch to search and download the full details of a record from Entrez. Consider the following simple example −" }, { "code": null, "e": 9019, "s": 8933, "text": ">>> handle = Entrez.efetch(\n db = \"nucleotide\", id = \"EU490707\", rettype = \"fasta\")" }, { "code": null, "e": 9074, "s": 9019, "text": "Now, we can simply read the records using SeqIO object" }, { "code": null, "e": 9401, "s": 9074, "text": ">>> record = SeqIO.read( handle, \"fasta\" ) \n>>> record \nSeqRecord(seq = Seq('ATTTTTTACGAACCTGTGGAAATTTTTGGTTATGACAATAAATCTAGTTTAGTA...GAA', \nSingleLetterAlphabet()), id = 'EU490707.1', name = 'EU490707.1', \ndescription = 'EU490707.1 \nSelenipedium aequinoctiale maturase K (matK) gene, partial cds; chloroplast', \ndbxrefs = [])" }, { "code": null, "e": 9408, "s": 9401, "text": " Print" }, { "code": null, "e": 9419, "s": 9408, "text": " Add Notes" } ]
Java Delete Files
To delete a file in Java, use the delete() method: import java.io.File; // Import the File class public class DeleteFile { public static void main(String[] args) { File myObj = new File("filename.txt"); if (myObj.delete()) { System.out.println("Deleted the file: " + myObj.getName()); } else { System.out.println("Failed to delete the file."); } } } The output will be: You can also delete a folder. However, it must be empty: import java.io.File; public class DeleteFolder { public static void main(String[] args) { File myObj = new File("C:\\Users\\MyName\\Test"); if (myObj.delete()) { System.out.println("Deleted the folder: " + myObj.getName()); } else { System.out.println("Failed to delete the folder."); } } } The output will be: We just launchedW3Schools videos Get certifiedby completinga course today! If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: help@w3schools.com Your message has been sent to W3Schools.
[ { "code": null, "e": 51, "s": 0, "text": "To delete a file in Java, use the delete() method:" }, { "code": null, "e": 389, "s": 51, "text": "import java.io.File; // Import the File class\n\npublic class DeleteFile {\n public static void main(String[] args) { \n File myObj = new File(\"filename.txt\"); \n if (myObj.delete()) { \n System.out.println(\"Deleted the file: \" + myObj.getName());\n } else {\n System.out.println(\"Failed to delete the file.\");\n } \n } \n}" }, { "code": null, "e": 409, "s": 389, "text": "The output will be:" }, { "code": null, "e": 466, "s": 409, "text": "You can also delete a folder. However, it must be empty:" }, { "code": null, "e": 796, "s": 466, "text": "import java.io.File; \n\npublic class DeleteFolder {\n public static void main(String[] args) { \n File myObj = new File(\"C:\\\\Users\\\\MyName\\\\Test\"); \n if (myObj.delete()) { \n System.out.println(\"Deleted the folder: \" + myObj.getName());\n } else {\n System.out.println(\"Failed to delete the folder.\");\n } \n } \n}" }, { "code": null, "e": 816, "s": 796, "text": "The output will be:" }, { "code": null, "e": 849, "s": 816, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 891, "s": 849, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 998, "s": 891, "text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:" }, { "code": null, "e": 1017, "s": 998, "text": "help@w3schools.com" } ]
Scala String endsWith() method with example - GeeksforGeeks
03 Oct, 2019 The endsWith() method is utilized to check if the stated string ends with the suffix stated in the argument. Method Definition: Boolean endsWith(String suffix)Return Type: It returns true if the string ends with the suffix stated else it returns false. Example #1: // Scala program of endsWith()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1= "Nidhi" // Applying endsWith() method val result = m1.endsWith("i") // Displays output println(result) }} true Example #2: // Scala program of endsWith()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1= "Nidhi" // Applying endsWith() method val result = m1.endsWith("y") // Displays output println(result) }} false Scala Scala-Method Scala-Strings Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Scala Tutorial – Learn Scala with Step By Step Guide Scala List filter() method with example Scala Map Type Casting in Scala Scala Lists Class and Object in Scala Scala List contains() method with example Break statement in Scala Operators in Scala
[ { "code": null, "e": 23623, "s": 23595, "text": "\n03 Oct, 2019" }, { "code": null, "e": 23732, "s": 23623, "text": "The endsWith() method is utilized to check if the stated string ends with the suffix stated in the argument." }, { "code": null, "e": 23876, "s": 23732, "text": "Method Definition: Boolean endsWith(String suffix)Return Type: It returns true if the string ends with the suffix stated else it returns false." }, { "code": null, "e": 23888, "s": 23876, "text": "Example #1:" }, { "code": "// Scala program of endsWith()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1= \"Nidhi\" // Applying endsWith() method val result = m1.endsWith(\"i\") // Displays output println(result) }} ", "e": 24224, "s": 23888, "text": null }, { "code": null, "e": 24230, "s": 24224, "text": "true\n" }, { "code": null, "e": 24242, "s": 24230, "text": "Example #2:" }, { "code": "// Scala program of endsWith()// method // Creating objectobject GfG{ // Main method def main(args:Array[String]) { // Creating a String val m1= \"Nidhi\" // Applying endsWith() method val result = m1.endsWith(\"y\") // Displays output println(result) }} ", "e": 24578, "s": 24242, "text": null }, { "code": null, "e": 24585, "s": 24578, "text": "false\n" }, { "code": null, "e": 24591, "s": 24585, "text": "Scala" }, { "code": null, "e": 24604, "s": 24591, "text": "Scala-Method" }, { "code": null, "e": 24618, "s": 24604, "text": "Scala-Strings" }, { "code": null, "e": 24624, "s": 24618, "text": "Scala" }, { "code": null, "e": 24722, "s": 24624, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24731, "s": 24722, "text": "Comments" }, { "code": null, "e": 24744, "s": 24731, "text": "Old Comments" }, { "code": null, "e": 24797, "s": 24744, "text": "Scala Tutorial – Learn Scala with Step By Step Guide" }, { "code": null, "e": 24837, "s": 24797, "text": "Scala List filter() method with example" }, { "code": null, "e": 24847, "s": 24837, "text": "Scala Map" }, { "code": null, "e": 24869, "s": 24847, "text": "Type Casting in Scala" }, { "code": null, "e": 24881, "s": 24869, "text": "Scala Lists" }, { "code": null, "e": 24907, "s": 24881, "text": "Class and Object in Scala" }, { "code": null, "e": 24949, "s": 24907, "text": "Scala List contains() method with example" }, { "code": null, "e": 24974, "s": 24949, "text": "Break statement in Scala" } ]
Select Top N Highest Values by Group in R - GeeksforGeeks
26 Oct, 2021 In this article, we are going to see how to select the Top Nth highest value by the group in R language. The dataframe can be ordered by group in descending order of their values by the order method. The corresponding dataframe is then accessed using the indexing method by taking the order function’s output in the form of row indexes. Syntax: order(vec, decreasing = TRUE) Arguments : vec – The dataframe column name to arrange in descending order decreasing – The flag to set data in descending order The Reduce method in base R can also be used to select top n highest rows from each group in a dataframe. This method takes as input a function f of two arguments and also a list or vector vec, which is to be reduced using the function f. The function f is rbind method, which is used to bind the rows together to form a dataframe. The by() method in R is used to apply a function to specified subsets of a dataframe. The first argument of this method takes up the data and second parameter is by which the function is applied and third parameter is the function. Here, the head is used as the function specified using the third argument of the method call. It is used to specify the the n rows group wise from the dataframe. Syntax: by(df, df$col-name, FUN) Arguments : df – The dataframe to apply the functions on FUN – The function to be applied The combined function application can be summarized as follows : Reduce(rbind,by()) Code: R # creating dataframedata_frame <- data.frame(col1 = rep(letters[1:4], each = 5), col2 = 1:20, col3 = 20:39)print("Original DataFrame")print(data_frame) # sorting the data by the column# required in descending orderdata_sorted <- data_frame[order(data_frame$col2, decreasing = TRUE), ] # select top 3 values from each groupdata_mod <- Reduce(rbind, by(data_sorted, data_sorted["col1"], head, n = 3)) print ("Modified DataFrame")print (data_mod) Output: The dplyr package in R is used to perform mutations and data manipulations in R. It is particularly useful for working with dataframes and data tables. The package can be downloaded and installed into the working directory using the following command : install.packages(“dplyr”) A sequence of methods are available in this package which are used to select top n rows from each group in a dataframe. Initially, the arrange() method is invoked to arrange the data of the dataframe in the ascending order or descending order. The descending order is invoked using the desc() method. The column name specified as the argument in this method is used for arranging the data. arrange(desc(col-name)) This is followed by the application of the group_by method which takes as arguments the set of column names that are used for grouping the data. It may comprise of one or more columns. group_by(col-name1, col-name2..) Then slice() method is used to retrieve the top n rows from the dataframe. slice(1:n) The output is returned in the form of a tibble containing entire information about the rows returned. The row numbers of the original dataframe are not retained. Code: R library("dplyr") # creating dataframedata_frame <- data.frame(col1 = rep(letters[1:4], each = 5), col2 = 1:20, col3 = 20:39)print("Original DataFrame")print(data_frame) # sorting the data by the column# required in descending orderdata_mod<- data_frame %>% arrange(desc(col2)) %>% group_by(col1) %>% slice(1:3)print("Modified DataFrame")print(data_mod) Output: The data.table method in R is used to perform data storage and manipulations in a well organized manner. The package can be downloaded and installed into the working directory using the following command : install.packages(data.table) The data table can be re-ordered by group in descending order of their values by the order method. The corresponding dataframe is then accessed using the indexing method by taking the order function’s output in the form of row indexes. Syntax: order(vec, decreasing = TRUE) Arguments : Vec – The dataframe column name to arrange in descending order Decreasing – The flag to set data in descending order The dataframe can then be converted into a data table using the data.table() method along with the column name to be used in setKey() method. The key attribute contains the column name to group the data by in the data.table. data.table(df, key = ) Now, the head along with .SD attribute can be used to access the top n rows of each of the taken groups. The by argument contains the grouping column. The head method takes as arguments .SD and integer value n. df[ , head(.SD, 3), by =] Code: R library("data.table") # creating dataframedata_frame <- data.frame(col1 = rep(letters[1:4], each = 5), col2 = 1:20, col3 = 20:39)print("Original DataFrame")print(data_frame) # sorting the data in descending order # Top N highest values by groupdata_mod <- data_frame[order(data_frame$col2, decreasing = TRUE), ] # organising the data by groupdata_mod <- data.table(data_mod, key = "col1") # getting top2 valuesdata_mod <- data_mod[ , head(.SD, 2), by = col1] # printing modified dataframe print("Modified DataFrame")print(data_mod) Output: Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R Data Visualization in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr Logistic Regression in R Programming 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? Merge DataFrames by Column Names in R
[ { "code": null, "e": 25162, "s": 25134, "text": "\n26 Oct, 2021" }, { "code": null, "e": 25267, "s": 25162, "text": "In this article, we are going to see how to select the Top Nth highest value by the group in R language." }, { "code": null, "e": 25499, "s": 25267, "text": "The dataframe can be ordered by group in descending order of their values by the order method. The corresponding dataframe is then accessed using the indexing method by taking the order function’s output in the form of row indexes." }, { "code": null, "e": 25537, "s": 25499, "text": "Syntax: order(vec, decreasing = TRUE)" }, { "code": null, "e": 25549, "s": 25537, "text": "Arguments :" }, { "code": null, "e": 25612, "s": 25549, "text": "vec – The dataframe column name to arrange in descending order" }, { "code": null, "e": 25666, "s": 25612, "text": "decreasing – The flag to set data in descending order" }, { "code": null, "e": 26392, "s": 25666, "text": "The Reduce method in base R can also be used to select top n highest rows from each group in a dataframe. This method takes as input a function f of two arguments and also a list or vector vec, which is to be reduced using the function f. The function f is rbind method, which is used to bind the rows together to form a dataframe. The by() method in R is used to apply a function to specified subsets of a dataframe. The first argument of this method takes up the data and second parameter is by which the function is applied and third parameter is the function. Here, the head is used as the function specified using the third argument of the method call. It is used to specify the the n rows group wise from the dataframe." }, { "code": null, "e": 26425, "s": 26392, "text": "Syntax: by(df, df$col-name, FUN)" }, { "code": null, "e": 26437, "s": 26425, "text": "Arguments :" }, { "code": null, "e": 26483, "s": 26437, "text": "df – The dataframe to apply the functions on " }, { "code": null, "e": 26517, "s": 26483, "text": "FUN – The function to be applied " }, { "code": null, "e": 26582, "s": 26517, "text": "The combined function application can be summarized as follows :" }, { "code": null, "e": 26601, "s": 26582, "text": "Reduce(rbind,by())" }, { "code": null, "e": 26607, "s": 26601, "text": "Code:" }, { "code": null, "e": 26609, "s": 26607, "text": "R" }, { "code": "# creating dataframedata_frame <- data.frame(col1 = rep(letters[1:4], each = 5), col2 = 1:20, col3 = 20:39)print(\"Original DataFrame\")print(data_frame) # sorting the data by the column# required in descending orderdata_sorted <- data_frame[order(data_frame$col2, decreasing = TRUE), ] # select top 3 values from each groupdata_mod <- Reduce(rbind, by(data_sorted, data_sorted[\"col1\"], head, n = 3)) print (\"Modified DataFrame\")print (data_mod)", "e": 27252, "s": 26609, "text": null }, { "code": null, "e": 27260, "s": 27252, "text": "Output:" }, { "code": null, "e": 27513, "s": 27260, "text": "The dplyr package in R is used to perform mutations and data manipulations in R. It is particularly useful for working with dataframes and data tables. The package can be downloaded and installed into the working directory using the following command :" }, { "code": null, "e": 27539, "s": 27513, "text": "install.packages(“dplyr”)" }, { "code": null, "e": 27929, "s": 27539, "text": "A sequence of methods are available in this package which are used to select top n rows from each group in a dataframe. Initially, the arrange() method is invoked to arrange the data of the dataframe in the ascending order or descending order. The descending order is invoked using the desc() method. The column name specified as the argument in this method is used for arranging the data." }, { "code": null, "e": 27953, "s": 27929, "text": "arrange(desc(col-name))" }, { "code": null, "e": 28138, "s": 27953, "text": "This is followed by the application of the group_by method which takes as arguments the set of column names that are used for grouping the data. It may comprise of one or more columns." }, { "code": null, "e": 28171, "s": 28138, "text": "group_by(col-name1, col-name2..)" }, { "code": null, "e": 28246, "s": 28171, "text": "Then slice() method is used to retrieve the top n rows from the dataframe." }, { "code": null, "e": 28257, "s": 28246, "text": "slice(1:n)" }, { "code": null, "e": 28419, "s": 28257, "text": "The output is returned in the form of a tibble containing entire information about the rows returned. The row numbers of the original dataframe are not retained." }, { "code": null, "e": 28425, "s": 28419, "text": "Code:" }, { "code": null, "e": 28427, "s": 28425, "text": "R" }, { "code": "library(\"dplyr\") # creating dataframedata_frame <- data.frame(col1 = rep(letters[1:4], each = 5), col2 = 1:20, col3 = 20:39)print(\"Original DataFrame\")print(data_frame) # sorting the data by the column# required in descending orderdata_mod<- data_frame %>% arrange(desc(col2)) %>% group_by(col1) %>% slice(1:3)print(\"Modified DataFrame\")print(data_mod)", "e": 28872, "s": 28427, "text": null }, { "code": null, "e": 28880, "s": 28872, "text": "Output:" }, { "code": null, "e": 29086, "s": 28880, "text": "The data.table method in R is used to perform data storage and manipulations in a well organized manner. The package can be downloaded and installed into the working directory using the following command :" }, { "code": null, "e": 29115, "s": 29086, "text": "install.packages(data.table)" }, { "code": null, "e": 29351, "s": 29115, "text": "The data table can be re-ordered by group in descending order of their values by the order method. The corresponding dataframe is then accessed using the indexing method by taking the order function’s output in the form of row indexes." }, { "code": null, "e": 29389, "s": 29351, "text": "Syntax: order(vec, decreasing = TRUE)" }, { "code": null, "e": 29401, "s": 29389, "text": "Arguments :" }, { "code": null, "e": 29464, "s": 29401, "text": "Vec – The dataframe column name to arrange in descending order" }, { "code": null, "e": 29518, "s": 29464, "text": "Decreasing – The flag to set data in descending order" }, { "code": null, "e": 29743, "s": 29518, "text": "The dataframe can then be converted into a data table using the data.table() method along with the column name to be used in setKey() method. The key attribute contains the column name to group the data by in the data.table." }, { "code": null, "e": 29766, "s": 29743, "text": "data.table(df, key = )" }, { "code": null, "e": 29977, "s": 29766, "text": "Now, the head along with .SD attribute can be used to access the top n rows of each of the taken groups. The by argument contains the grouping column. The head method takes as arguments .SD and integer value n." }, { "code": null, "e": 30003, "s": 29977, "text": "df[ , head(.SD, 3), by =]" }, { "code": null, "e": 30009, "s": 30003, "text": "Code:" }, { "code": null, "e": 30011, "s": 30009, "text": "R" }, { "code": "library(\"data.table\") # creating dataframedata_frame <- data.frame(col1 = rep(letters[1:4], each = 5), col2 = 1:20, col3 = 20:39)print(\"Original DataFrame\")print(data_frame) # sorting the data in descending order # Top N highest values by groupdata_mod <- data_frame[order(data_frame$col2, decreasing = TRUE), ] # organising the data by groupdata_mod <- data.table(data_mod, key = \"col1\") # getting top2 valuesdata_mod <- data_mod[ , head(.SD, 2), by = col1] # printing modified dataframe print(\"Modified DataFrame\")print(data_mod)", "e": 30637, "s": 30011, "text": null }, { "code": null, "e": 30645, "s": 30637, "text": "Output:" }, { "code": null, "e": 30652, "s": 30645, "text": "Picked" }, { "code": null, "e": 30673, "s": 30652, "text": "R DataFrame-Programs" }, { "code": null, "e": 30685, "s": 30673, "text": "R-DataFrame" }, { "code": null, "e": 30696, "s": 30685, "text": "R Language" }, { "code": null, "e": 30707, "s": 30696, "text": "R Programs" }, { "code": null, "e": 30805, "s": 30707, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30814, "s": 30805, "text": "Comments" }, { "code": null, "e": 30827, "s": 30814, "text": "Old Comments" }, { "code": null, "e": 30879, "s": 30827, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30903, "s": 30879, "text": "Data Visualization in R" }, { "code": null, "e": 30941, "s": 30903, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30976, "s": 30941, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 31013, "s": 30976, "text": "Logistic Regression in R Programming" }, { "code": null, "e": 31071, "s": 31013, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 31114, "s": 31071, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 31163, "s": 31114, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 31213, "s": 31163, "text": "How to filter R dataframe by multiple conditions?" } ]
numpy.random.gamma() in Python - GeeksforGeeks
15 Jul, 2020 With the help of numpy.random.gamma() method, we can get the random samples of gamma distribution and return the random samples of numpy array by using this method. gamma distribution Syntax : numpy.random.gamma(shape, scale=1.0, size=None) Return : Return the random samples of numpy array. Example #1 : In this example we can see that by using numpy.random.gamma() method, we are able to get the random samples from gamma distribution and return the random samples by using this method. Python3 # import numpy and gammaimport numpy as npimport matplotlib.pyplot as plt # Using gamma() methodgfg = np.random.gamma(3, 20, 1000) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show() Output : Example #2 : Python3 # import numpy and gammaimport numpy as npimport matplotlib.pyplot as plt # Using gamma() methodgfg = np.random.gamma(4.98, 12, 40000)gfg1 = np.random.gamma(gfg, 13.46, 40000) count, bins, ignored = plt.hist(gfg1, 50, density = True)plt.show() Output : Python numpy-Random Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Enumerate() in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() sum() function in Python Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python Graph Plotting in Python | Set 1 Print lists in Python (4 Different Ways)
[ { "code": null, "e": 23885, "s": 23857, "text": "\n15 Jul, 2020" }, { "code": null, "e": 24050, "s": 23885, "text": "With the help of numpy.random.gamma() method, we can get the random samples of gamma distribution and return the random samples of numpy array by using this method." }, { "code": null, "e": 24069, "s": 24050, "text": "gamma distribution" }, { "code": null, "e": 24126, "s": 24069, "text": "Syntax : numpy.random.gamma(shape, scale=1.0, size=None)" }, { "code": null, "e": 24177, "s": 24126, "text": "Return : Return the random samples of numpy array." }, { "code": null, "e": 24190, "s": 24177, "text": "Example #1 :" }, { "code": null, "e": 24374, "s": 24190, "text": "In this example we can see that by using numpy.random.gamma() method, we are able to get the random samples from gamma distribution and return the random samples by using this method." }, { "code": null, "e": 24382, "s": 24374, "text": "Python3" }, { "code": "# import numpy and gammaimport numpy as npimport matplotlib.pyplot as plt # Using gamma() methodgfg = np.random.gamma(3, 20, 1000) count, bins, ignored = plt.hist(gfg, 14, density = True)plt.show()", "e": 24582, "s": 24382, "text": null }, { "code": null, "e": 24591, "s": 24582, "text": "Output :" }, { "code": null, "e": 24604, "s": 24591, "text": "Example #2 :" }, { "code": null, "e": 24612, "s": 24604, "text": "Python3" }, { "code": "# import numpy and gammaimport numpy as npimport matplotlib.pyplot as plt # Using gamma() methodgfg = np.random.gamma(4.98, 12, 40000)gfg1 = np.random.gamma(gfg, 13.46, 40000) count, bins, ignored = plt.hist(gfg1, 50, density = True)plt.show()", "e": 24858, "s": 24612, "text": null }, { "code": null, "e": 24867, "s": 24858, "text": "Output :" }, { "code": null, "e": 24887, "s": 24867, "text": "Python numpy-Random" }, { "code": null, "e": 24900, "s": 24887, "text": "Python-numpy" }, { "code": null, "e": 24907, "s": 24900, "text": "Python" }, { "code": null, "e": 25005, "s": 24907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25014, "s": 25005, "text": "Comments" }, { "code": null, "e": 25027, "s": 25014, "text": "Old Comments" }, { "code": null, "e": 25049, "s": 25027, "text": "Enumerate() in Python" }, { "code": null, "e": 25081, "s": 25049, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25123, "s": 25081, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25149, "s": 25123, "text": "Python String | replace()" }, { "code": null, "e": 25174, "s": 25149, "text": "sum() function in Python" }, { "code": null, "e": 25211, "s": 25174, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25267, "s": 25211, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 25296, "s": 25267, "text": "*args and **kwargs in Python" }, { "code": null, "e": 25329, "s": 25296, "text": "Graph Plotting in Python | Set 1" } ]
Using Time datatype in MySQL without seconds?
You need to use DATE_FORMAT() for this. The syntax is as follows − SELECT DATE_FORMAT(yourColumnName,'%k:%i') as anyAliasName FROM yourTableName; You can use ‘%H:%i’ for the same result. To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table TimeDemo -> ( -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> LastLoginTime time -> ); Query OK, 0 rows affected (0.56 sec) Now you can insert some records in the table using insert command. The query is as follows − mysql> insert into TimeDemo(LastLoginTime) values('09:30:35'); Query OK, 1 row affected (0.20 sec) mysql> insert into TimeDemo(LastLoginTime) values('10:45:30'); Query OK, 1 row affected (0.19 sec) mysql> insert into TimeDemo(LastLoginTime) values('13:33:58'); Query OK, 1 row affected (0.24 sec) mysql> insert into TimeDemo(LastLoginTime) values('15:45:31'); Query OK, 1 row affected (0.21 sec) mysql> insert into TimeDemo(LastLoginTime) values('16:40:36'); Query OK, 1 row affected (0.17 sec) Display all records from the table using a select statement. The query is as follows − mysql> select *from TimeDemo; The following is the output − +----+---------------+ | Id | LastLoginTime | +----+---------------+ | 1 | 09:30:35 | | 2 | 10:45:30 | | 3 | 13:33:58 | | 4 | 15:45:31 | | 5 | 16:40:36 | +----+---------------+ 5 rows in set (0.00 sec) Here is the query to get time without seconds. The query is as follows − mysql> select DATE_FORMAT(LastLoginTime,'%k:%i') as `Time` from TimeDemo; The following is the output − +-------+ | Time | +-------+ | 9:30 | | 10:45 | | 13:33 | | 15:45 | | 16:40 | +-------+ 5 rows in set (0.00 sec) You can change the format specifier like %H:%i to get the same result without seconds. The query is as follows − mysql> select DATE_FORMAT(LastLoginTime,' %H:%i') as `Time` from TimeDemo; The following is the output − +--------+ | Time | +--------+ | 09:30 | | 10:45 | | 13:33 | | 15:45 | | 16:40 | +--------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1129, "s": 1062, "text": "You need to use DATE_FORMAT() for this. The syntax is as follows −" }, { "code": null, "e": 1208, "s": 1129, "text": "SELECT DATE_FORMAT(yourColumnName,'%k:%i') as anyAliasName FROM yourTableName;" }, { "code": null, "e": 1304, "s": 1208, "text": "You can use ‘%H:%i’ for the same result. To understand the above syntax, let us create a table." }, { "code": null, "e": 1348, "s": 1304, "text": "The query to create a table is as follows −" }, { "code": null, "e": 1506, "s": 1348, "text": "mysql> create table TimeDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> LastLoginTime time\n -> );\nQuery OK, 0 rows affected (0.56 sec)" }, { "code": null, "e": 1599, "s": 1506, "text": "Now you can insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2094, "s": 1599, "text": "mysql> insert into TimeDemo(LastLoginTime) values('09:30:35');\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into TimeDemo(LastLoginTime) values('10:45:30');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into TimeDemo(LastLoginTime) values('13:33:58');\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into TimeDemo(LastLoginTime) values('15:45:31');\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into TimeDemo(LastLoginTime) values('16:40:36');\nQuery OK, 1 row affected (0.17 sec)" }, { "code": null, "e": 2181, "s": 2094, "text": "Display all records from the table using a select statement. The query is as follows −" }, { "code": null, "e": 2211, "s": 2181, "text": "mysql> select *from TimeDemo;" }, { "code": null, "e": 2241, "s": 2211, "text": "The following is the output −" }, { "code": null, "e": 2473, "s": 2241, "text": "+----+---------------+\n| Id | LastLoginTime |\n+----+---------------+\n| 1 | 09:30:35 |\n| 2 | 10:45:30 |\n| 3 | 13:33:58 |\n| 4 | 15:45:31 |\n| 5 | 16:40:36 |\n+----+---------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2546, "s": 2473, "text": "Here is the query to get time without seconds. The query is as follows −" }, { "code": null, "e": 2620, "s": 2546, "text": "mysql> select DATE_FORMAT(LastLoginTime,'%k:%i') as `Time` from TimeDemo;" }, { "code": null, "e": 2650, "s": 2620, "text": "The following is the output −" }, { "code": null, "e": 2765, "s": 2650, "text": "+-------+\n| Time |\n+-------+\n| 9:30 |\n| 10:45 |\n| 13:33 |\n| 15:45 |\n| 16:40 |\n+-------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2878, "s": 2765, "text": "You can change the format specifier like %H:%i to get the same result without seconds. The query is as follows −" }, { "code": null, "e": 2953, "s": 2878, "text": "mysql> select DATE_FORMAT(LastLoginTime,' %H:%i') as `Time` from TimeDemo;" }, { "code": null, "e": 2983, "s": 2953, "text": "The following is the output −" }, { "code": null, "e": 3107, "s": 2983, "text": "+--------+\n| Time |\n+--------+\n| 09:30 |\n| 10:45 |\n| 13:33 |\n| 15:45 |\n| 16:40 |\n+--------+\n5 rows in set (0.00 sec)" } ]
How to set the local user account settings using PowerShell?
To set the local user account settings related to the account or the password expiration, we can use the Set-LocalUser command. The below command will change the local user Testuser account and password set to never expire. Set-LocalUser -Name Testuser -AccountNeverExpires -PasswordNeverExpires $true -Verbose The below command will set the account expiry, Set-LocalUser -Name Testuser -AccountExpires 05/11/2022 -Verbose To run the above commands on the remote computers, use the Invoke-Command. Invoke-Command -ComputerName Computer1, computer2 -ScriptBlock{ Set-LocalUser -Name Testuser -AccountNeverExpires -PasswordNeverExpires $true -Verbose } Invoke-Command -ComputerName Computer1, computer2 -ScriptBlock{ Set-LocalUser -Name Testuser -AccountExpires 05/11/2022 -Verbose }
[ { "code": null, "e": 1190, "s": 1062, "text": "To set the local user account settings related to the account or the password expiration, we can use the Set-LocalUser command." }, { "code": null, "e": 1286, "s": 1190, "text": "The below command will change the local user Testuser account and password set to never expire." }, { "code": null, "e": 1373, "s": 1286, "text": "Set-LocalUser -Name Testuser -AccountNeverExpires -PasswordNeverExpires $true -Verbose" }, { "code": null, "e": 1420, "s": 1373, "text": "The below command will set the account expiry," }, { "code": null, "e": 1485, "s": 1420, "text": "Set-LocalUser -Name Testuser -AccountExpires 05/11/2022 -Verbose" }, { "code": null, "e": 1560, "s": 1485, "text": "To run the above commands on the remote computers, use the Invoke-Command." }, { "code": null, "e": 1850, "s": 1560, "text": "Invoke-Command -ComputerName Computer1, computer2 -ScriptBlock{\n Set-LocalUser -Name Testuser -AccountNeverExpires -PasswordNeverExpires $true -Verbose\n}\nInvoke-Command -ComputerName Computer1, computer2 -ScriptBlock{\n Set-LocalUser -Name Testuser -AccountExpires 05/11/2022 -Verbose\n}" } ]
fill() function in C++ STL with examples - GeeksforGeeks
11 Oct, 2019 The fill() function in C++ STL is used to fill some default value in a container. The fill() function can also be used to fill values in a range in the container. It accepts two iterators begin and end and fills a value in the container starting from position pointed by begin and just before the position pointed by end. Syntax: void fill(iterator begin, iterator end, type value); Parameters: begin: The function will start filling values from the position pointed by the iterator begin. end: The function will fill values upto the position just before the position pointed by the iterator end. value: This parameter denotes the value to be filled by the function in the container. NOTE : Notice carefully that ‘begin’ is included in the range but ‘end’ is NOT included. Return Value: This function does not returns any value. Below program illustrate the fill() function in C++ STL: // C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vect(8); // calling fill to initialize values in the // range to 4 fill(vect.begin() + 2, vect.end() - 1, 4); for (int i = 0; i < vect.size(); i++) cout << vect[i] << " "; // Filling the complete vector with value 10 fill(vect.begin(), vect.end(), 10); cout << endl; for (int i = 0; i < vect.size(); i++) cout << vect[i] << " "; return 0;} 0 0 4 4 4 4 4 0 10 10 10 10 10 10 10 10 Reference: http://www.cplusplus.com/reference/algorithm/fill/ CPP-Functions C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Iterators in C++ STL Operator Overloading in C++ Friend class and function in C++ Polymorphism in C++ Sorting a vector in C++ Convert string to char array in C++ Inline Functions in C++ List in C++ Standard Template Library (STL) std::string class in C++ new and delete operators in C++ for dynamic memory
[ { "code": null, "e": 24018, "s": 23990, "text": "\n11 Oct, 2019" }, { "code": null, "e": 24340, "s": 24018, "text": "The fill() function in C++ STL is used to fill some default value in a container. The fill() function can also be used to fill values in a range in the container. It accepts two iterators begin and end and fills a value in the container starting from position pointed by begin and just before the position pointed by end." }, { "code": null, "e": 24348, "s": 24340, "text": "Syntax:" }, { "code": null, "e": 24402, "s": 24348, "text": "void fill(iterator begin, iterator end, type value);\n" }, { "code": null, "e": 24414, "s": 24402, "text": "Parameters:" }, { "code": null, "e": 24509, "s": 24414, "text": "begin: The function will start filling values from the position pointed by the iterator begin." }, { "code": null, "e": 24616, "s": 24509, "text": "end: The function will fill values upto the position just before the position pointed by the iterator end." }, { "code": null, "e": 24703, "s": 24616, "text": "value: This parameter denotes the value to be filled by the function in the container." }, { "code": null, "e": 24792, "s": 24703, "text": "NOTE : Notice carefully that ‘begin’ is included in the range but ‘end’ is NOT included." }, { "code": null, "e": 24848, "s": 24792, "text": "Return Value: This function does not returns any value." }, { "code": null, "e": 24905, "s": 24848, "text": "Below program illustrate the fill() function in C++ STL:" }, { "code": "// C++ program to demonstrate working of fill()#include <bits/stdc++.h>using namespace std; int main(){ vector<int> vect(8); // calling fill to initialize values in the // range to 4 fill(vect.begin() + 2, vect.end() - 1, 4); for (int i = 0; i < vect.size(); i++) cout << vect[i] << \" \"; // Filling the complete vector with value 10 fill(vect.begin(), vect.end(), 10); cout << endl; for (int i = 0; i < vect.size(); i++) cout << vect[i] << \" \"; return 0;}", "e": 25418, "s": 24905, "text": null }, { "code": null, "e": 25460, "s": 25418, "text": "0 0 4 4 4 4 4 0 \n10 10 10 10 10 10 10 10\n" }, { "code": null, "e": 25522, "s": 25460, "text": "Reference: http://www.cplusplus.com/reference/algorithm/fill/" }, { "code": null, "e": 25536, "s": 25522, "text": "CPP-Functions" }, { "code": null, "e": 25540, "s": 25536, "text": "C++" }, { "code": null, "e": 25544, "s": 25540, "text": "CPP" }, { "code": null, "e": 25642, "s": 25544, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25651, "s": 25642, "text": "Comments" }, { "code": null, "e": 25664, "s": 25651, "text": "Old Comments" }, { "code": null, "e": 25685, "s": 25664, "text": "Iterators in C++ STL" }, { "code": null, "e": 25713, "s": 25685, "text": "Operator Overloading in C++" }, { "code": null, "e": 25746, "s": 25713, "text": "Friend class and function in C++" }, { "code": null, "e": 25766, "s": 25746, "text": "Polymorphism in C++" }, { "code": null, "e": 25790, "s": 25766, "text": "Sorting a vector in C++" }, { "code": null, "e": 25826, "s": 25790, "text": "Convert string to char array in C++" }, { "code": null, "e": 25850, "s": 25826, "text": "Inline Functions in C++" }, { "code": null, "e": 25894, "s": 25850, "text": "List in C++ Standard Template Library (STL)" }, { "code": null, "e": 25919, "s": 25894, "text": "std::string class in C++" } ]
Count occurrences of a character in string in Python
We are given a string and a character. We want to find out how many times the given character is repeated in a given string. We design a for loop to match the character with every character present in the string which are accessed using index. The range and len function helps us determine how many times the matching has to be done when moving from left to right of the string. Live Demo Astr = "How do you do" char = 'o' # Given String and Character print("Given String:\n", Astr) print("Given Character:\n",char) res = 0 for i in range(len(Astr)): # Checking character in string if (Astr[i] == char): res = res + 1 print("Number of time character is present in string:\n",res) Running the above code gives us the following result − Given String: How do you do Given Character: o Number of time character is present in string: 4 We apply the Counter function from the collections module to get the count of each character in the string. And then choose only those counts where the index matches with the value of the character we are searching for. Live Demo from collections import Counter Astr = "How do you do" char = 'o' # Given String and Character print("Given String:\n", Astr) print("Given Character:\n",char) count = Counter(Astr) print("Number of time character is present in string:\n",count['o']) Running the above code gives us the following result − Given String: How do you do Given Character: o Number of time character is present in string: 4
[ { "code": null, "e": 1187, "s": 1062, "text": "We are given a string and a character. We want to find out how many times the given character is repeated in a given string." }, { "code": null, "e": 1441, "s": 1187, "text": "We design a for loop to match the character with every character present in the string which are accessed using index. The range and len function helps us determine how many times the matching has to be done when moving from left to right of the string." }, { "code": null, "e": 1452, "s": 1441, "text": " Live Demo" }, { "code": null, "e": 1755, "s": 1452, "text": "Astr = \"How do you do\"\nchar = 'o'\n# Given String and Character\nprint(\"Given String:\\n\", Astr)\nprint(\"Given Character:\\n\",char)\nres = 0\nfor i in range(len(Astr)):\n # Checking character in string\n if (Astr[i] == char):\n res = res + 1\nprint(\"Number of time character is present in string:\\n\",res)" }, { "code": null, "e": 1810, "s": 1755, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1906, "s": 1810, "text": "Given String:\nHow do you do\nGiven Character:\no\nNumber of time character is present in string:\n4" }, { "code": null, "e": 2126, "s": 1906, "text": "We apply the Counter function from the collections module to get the count of each character in the string. And then choose only those counts where the index matches with the value of the character we are searching for." }, { "code": null, "e": 2137, "s": 2126, "text": " Live Demo" }, { "code": null, "e": 2387, "s": 2137, "text": "from collections import Counter\nAstr = \"How do you do\"\nchar = 'o'\n# Given String and Character\nprint(\"Given String:\\n\", Astr)\nprint(\"Given Character:\\n\",char)\ncount = Counter(Astr)\nprint(\"Number of time character is present in string:\\n\",count['o'])" }, { "code": null, "e": 2442, "s": 2387, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2538, "s": 2442, "text": "Given String:\nHow do you do\nGiven Character:\no\nNumber of time character is present in string:\n4" } ]
Introduction of Lexical Analysis
28 Jun, 2021 Lexical Analysis is the first phase of the compiler also known as a scanner. It converts the High level input program into a sequence of Tokens. Lexical Analysis can be implemented with the Deterministic finite Automata. The output is a sequence of tokens that is sent to the parser for syntax analysis What is a token?A lexical token is a sequence of characters that can be treated as a unit in the grammar of the programming languages. Example of tokens: Type token (id, number, real, . . . ) Punctuation tokens (IF, void, return, . . . ) Alphabetic tokens (keywords) Keywords; Examples-for, while, if etc. Identifier; Examples-Variable name, function name, etc. Operators; Examples '+', '++', '-' etc. Separators; Examples ',' ';' etc Example of Non-Tokens: Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Comments, preprocessor directive, macros, blanks, tabs, newline, etc. Lexeme: The sequence of characters matched by a pattern to formthe corresponding token or a sequence of input characters that comprises a single token is called a lexeme. eg- “float”, “abs_zero_Kelvin”, “=”, “-”, “273”, “;” . How Lexical Analyzer functions1. Tokenization i.e. Dividing the program into valid tokens.2. Remove white space characters.3. Remove comments.4. It also provides help in generating error messages by providing row numbers and column numbers. The lexical analyzer identifies the error with the help of the automation machine and the grammar of the given language on which it is based like C, C++, and gives row number and column number of the error. Suppose we pass a statement through lexical analyzer – a = b + c ; It will generate token sequence like this: id=id+id; Where each id refers to it’s variable in the symbol table referencing all details For example, consider the program int main() { // 2 variables int a, b; a = 10; return 0; } All the valid tokens are: 'int' 'main' '(' ')' '{' 'int' 'a' ',' 'b' ';' 'a' '=' '10' ';' 'return' '0' ';' '}' Above are the valid tokens.You can observe that we have omitted comments. As another example, consider below printf statement.There are 5 valid token in this printf statement.Exercise 1:Count number of tokens : int main() { int a = 10, b = 20; printf("sum is :%d",a+b); return 0; } Answer: Total number of token: 27. Exercise 2: Count number of tokens : int max(int i); Lexical analyzer first read int and finds it to be valid and accepts as token max is read by it and found to be a valid function name after reading ( int is also a token , then again i as another token and finally ; Answer: Total number of tokens 7: int, max, ( ,int, i, ), ; Below are previous year GATE question on Lexical analysis. https://www.geeksforgeeks.org/lexical-analysis-gq/Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above VaibhavRai3 jishnu3 jahanzaibmlk321 Compiler Design GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 197, "s": 52, "text": "Lexical Analysis is the first phase of the compiler also known as a scanner. It converts the High level input program into a sequence of Tokens." }, { "code": null, "e": 273, "s": 197, "text": "Lexical Analysis can be implemented with the Deterministic finite Automata." }, { "code": null, "e": 355, "s": 273, "text": "The output is a sequence of tokens that is sent to the parser for syntax analysis" }, { "code": null, "e": 490, "s": 355, "text": "What is a token?A lexical token is a sequence of characters that can be treated as a unit in the grammar of the programming languages." }, { "code": null, "e": 509, "s": 490, "text": "Example of tokens:" }, { "code": null, "e": 547, "s": 509, "text": "Type token (id, number, real, . . . )" }, { "code": null, "e": 593, "s": 547, "text": "Punctuation tokens (IF, void, return, . . . )" }, { "code": null, "e": 622, "s": 593, "text": "Alphabetic tokens (keywords)" }, { "code": null, "e": 790, "s": 622, "text": "Keywords; Examples-for, while, if etc.\nIdentifier; Examples-Variable name, function name, etc.\nOperators; Examples '+', '++', '-' etc.\nSeparators; Examples ',' ';' etc" }, { "code": null, "e": 813, "s": 790, "text": "Example of Non-Tokens:" }, { "code": null, "e": 822, "s": 813, "text": "Chapters" }, { "code": null, "e": 849, "s": 822, "text": "descriptions off, selected" }, { "code": null, "e": 899, "s": 849, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 922, "s": 899, "text": "captions off, selected" }, { "code": null, "e": 930, "s": 922, "text": "English" }, { "code": null, "e": 954, "s": 930, "text": "This is a modal window." }, { "code": null, "e": 1023, "s": 954, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1045, "s": 1023, "text": "End of dialog window." }, { "code": null, "e": 1115, "s": 1045, "text": "Comments, preprocessor directive, macros, blanks, tabs, newline, etc." }, { "code": null, "e": 1341, "s": 1115, "text": "Lexeme: The sequence of characters matched by a pattern to formthe corresponding token or a sequence of input characters that comprises a single token is called a lexeme. eg- “float”, “abs_zero_Kelvin”, “=”, “-”, “273”, “;” ." }, { "code": null, "e": 1582, "s": 1341, "text": "How Lexical Analyzer functions1. Tokenization i.e. Dividing the program into valid tokens.2. Remove white space characters.3. Remove comments.4. It also provides help in generating error messages by providing row numbers and column numbers." }, { "code": null, "e": 1789, "s": 1582, "text": "The lexical analyzer identifies the error with the help of the automation machine and the grammar of the given language on which it is based like C, C++, and gives row number and column number of the error." }, { "code": null, "e": 1844, "s": 1789, "text": "Suppose we pass a statement through lexical analyzer –" }, { "code": null, "e": 1914, "s": 1844, "text": "a = b + c ; It will generate token sequence like this:" }, { "code": null, "e": 2022, "s": 1914, "text": "id=id+id; Where each id refers to it’s variable in the symbol table referencing all details" }, { "code": null, "e": 2056, "s": 2022, "text": "For example, consider the program" }, { "code": null, "e": 2121, "s": 2056, "text": "int main()\n{\n // 2 variables\n int a, b;\n a = 10;\n return 0;\n}" }, { "code": null, "e": 2147, "s": 2121, "text": "All the valid tokens are:" }, { "code": null, "e": 2247, "s": 2147, "text": "'int' 'main' '(' ')' '{' 'int' 'a' ',' 'b' ';'\n 'a' '=' '10' ';' 'return' '0' ';' '}'" }, { "code": null, "e": 2321, "s": 2247, "text": "Above are the valid tokens.You can observe that we have omitted comments." }, { "code": null, "e": 2458, "s": 2321, "text": "As another example, consider below printf statement.There are 5 valid token in this printf statement.Exercise 1:Count number of tokens :" }, { "code": null, "e": 2570, "s": 2458, "text": "int main()\n{\n int a = 10, b = 20;\n printf(\"sum is :%d\",a+b);\n return 0;\n}\nAnswer: Total number of token: 27." }, { "code": null, "e": 2582, "s": 2570, "text": "Exercise 2:" }, { "code": null, "e": 2607, "s": 2582, "text": "Count number of tokens :" }, { "code": null, "e": 2623, "s": 2607, "text": "int max(int i);" }, { "code": null, "e": 2701, "s": 2623, "text": "Lexical analyzer first read int and finds it to be valid and accepts as token" }, { "code": null, "e": 2773, "s": 2701, "text": "max is read by it and found to be a valid function name after reading (" }, { "code": null, "e": 2840, "s": 2773, "text": "int is also a token , then again i as another token and finally ;" }, { "code": null, "e": 2907, "s": 2840, "text": " Answer: Total number of tokens 7: \nint, max, ( ,int, i, ), ;" }, { "code": null, "e": 2966, "s": 2907, "text": "Below are previous year GATE question on Lexical analysis." }, { "code": null, "e": 3140, "s": 2966, "text": "https://www.geeksforgeeks.org/lexical-analysis-gq/Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 3152, "s": 3140, "text": "VaibhavRai3" }, { "code": null, "e": 3160, "s": 3152, "text": "jishnu3" }, { "code": null, "e": 3176, "s": 3160, "text": "jahanzaibmlk321" }, { "code": null, "e": 3192, "s": 3176, "text": "Compiler Design" }, { "code": null, "e": 3200, "s": 3192, "text": "GATE CS" } ]
Java Program to Convert Long to String
08 Dec, 2021 Conversion of long type to string type generally comes in need in the case when we have to display a long number in GUI application because everything is displayed as string form. Given a Long number, the task is to convert it into String in Java. Examples: Input:Long = 20L Output:"20" Input:Long = 999999999999L Output:"999999999999" For converting any data-type to string type, we can simply add/+ empty string indicated by double quotes(“”). Syntax: String str = l+" "; Java // Java program to convert Long to String // using + operator public class GFG { // main method public static void main(String args[]) { // create a Long Long varLong = 999999999999L; // convert into String String str = varLong+" "; // printing the type of str to // show that long has been converted to string System.out.println("Converted type : "+str.getClass().getName()); // print Long as String System.out.println(str); } } Converted type : java.lang.String 999999999999 The valueOf() method converts data from its internal form into human-readable form. It is a static method that is overloaded within a string for all of Java’s built-in types so that each type can be converted properly into a string.It is called when a string representation of some other type of data is needed-for example during concatenation operation. You can call this method with any data type and get a reasonable String representation. Syntax: String str = String.valueOf(varLong); Java // Java program to convert Long to String// using valueOf() Method public class GFG { // main method public static void main(String args[]) { // create a Long Long varLong = 999999999999L; // convert into String String str = String.valueOf(varLong); // printing the type of str to // show that long has been converted to string System.out.println("Converted type : " + str.getClass().getName()); // print Long as String System.out.println(str); }} Converted type : java.lang.String 999999999999 Object class contains toString() method. We can use toString() method to get string representation of an object. Whenever we try to print the Object reference then internally toString() method is invoked. If we did not define toString() method in your class then Object class toString() method is invoked otherwise our implemented/Overridden toString() method will be called. Syntax: String str = Long.toString(varLong); Java // Java program to convert Long to String // using toString() method public class GFG { // main method public static void main(String args[]) { // create a Long Long varLong = 999999999999L; // convert into String String str = Long.toString(varLong); // printing the type of str to // show that long has been converted to string System.out.println("Converted type : " + str.getClass().getName()); // print Long as String System.out.println(str); } } Converted type : java.lang.String 999999999999 This constructor is not valid in java 9. Syntax: String str = new Long(varLong).toString(); Java // Java program to convert Long to String // using long constructor import java.util.*;public class GFG { // main method public static void main(String args[]) { // create a Long Long varLong = 999999999999L; // convert into String String str = new Long(varLong).toString(); // printing the type of str to // show that long has been converted to string System.out.println("Converted type : " + str.getClass().getName()); // print Long as String System.out.println(str); } } Since this version of java does not support this constructor. Hence, on running the program, we will get the error displaying Note: prog.java uses or overrides a deprecated API. The java string format() method returns a formatted string using the given locale, specified format string and arguments. Syntax: long varLong = 9999999L; String str = String.format("%d", varLong); Java // Java program to demonstrate// working of format() method class Gfg { public static void main(String args[]) { long varLong = 9999999L; String str = String.format("%d", varLong); // printing the type of str to // show that long has been converted to string System.out.println("Converted type : " + str.getClass().getName()); // print Long as String System.out.println(str); }} Converted type : java.lang.String 9999999 StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences. Syntax: long varLong = 9999999L; String str = new StringBuilder().append(varLong).toString(); Java // Java program to convert long to// string using StringBuilder class Gfg { public static void main(String args[]) { long varLong = 9999999L; String str = new StringBuilder().append(varLong).toString(); // printing the type of str to // show that long has been converted to string System.out.println("Converted type : " + str.getClass().getName()); // print Long as String System.out.println(str); }} Converted type : java.lang.String 9999999 kapoorsagar226 kalrap615 varshagumber28 Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Dec, 2021" }, { "code": null, "e": 234, "s": 54, "text": "Conversion of long type to string type generally comes in need in the case when we have to display a long number in GUI application because everything is displayed as string form." }, { "code": null, "e": 302, "s": 234, "text": "Given a Long number, the task is to convert it into String in Java." }, { "code": null, "e": 312, "s": 302, "text": "Examples:" }, { "code": null, "e": 391, "s": 312, "text": "Input:Long = 20L\nOutput:\"20\"\n\nInput:Long = 999999999999L\nOutput:\"999999999999\"" }, { "code": null, "e": 501, "s": 391, "text": "For converting any data-type to string type, we can simply add/+ empty string indicated by double quotes(“”)." }, { "code": null, "e": 509, "s": 501, "text": "Syntax:" }, { "code": null, "e": 529, "s": 509, "text": "String str = l+\" \";" }, { "code": null, "e": 534, "s": 529, "text": "Java" }, { "code": "// Java program to convert Long to String // using + operator public class GFG { // main method public static void main(String args[]) { // create a Long Long varLong = 999999999999L; // convert into String String str = varLong+\" \"; // printing the type of str to // show that long has been converted to string System.out.println(\"Converted type : \"+str.getClass().getName()); // print Long as String System.out.println(str); } }", "e": 1078, "s": 534, "text": null }, { "code": null, "e": 1125, "s": 1078, "text": "Converted type : java.lang.String\n999999999999" }, { "code": null, "e": 1568, "s": 1125, "text": "The valueOf() method converts data from its internal form into human-readable form. It is a static method that is overloaded within a string for all of Java’s built-in types so that each type can be converted properly into a string.It is called when a string representation of some other type of data is needed-for example during concatenation operation. You can call this method with any data type and get a reasonable String representation." }, { "code": null, "e": 1576, "s": 1568, "text": "Syntax:" }, { "code": null, "e": 1614, "s": 1576, "text": "String str = String.valueOf(varLong);" }, { "code": null, "e": 1619, "s": 1614, "text": "Java" }, { "code": "// Java program to convert Long to String// using valueOf() Method public class GFG { // main method public static void main(String args[]) { // create a Long Long varLong = 999999999999L; // convert into String String str = String.valueOf(varLong); // printing the type of str to // show that long has been converted to string System.out.println(\"Converted type : \" + str.getClass().getName()); // print Long as String System.out.println(str); }}", "e": 2173, "s": 1619, "text": null }, { "code": null, "e": 2220, "s": 2173, "text": "Converted type : java.lang.String\n999999999999" }, { "code": null, "e": 2596, "s": 2220, "text": "Object class contains toString() method. We can use toString() method to get string representation of an object. Whenever we try to print the Object reference then internally toString() method is invoked. If we did not define toString() method in your class then Object class toString() method is invoked otherwise our implemented/Overridden toString() method will be called." }, { "code": null, "e": 2604, "s": 2596, "text": "Syntax:" }, { "code": null, "e": 2641, "s": 2604, "text": "String str = Long.toString(varLong);" }, { "code": null, "e": 2646, "s": 2641, "text": "Java" }, { "code": "// Java program to convert Long to String // using toString() method public class GFG { // main method public static void main(String args[]) { // create a Long Long varLong = 999999999999L; // convert into String String str = Long.toString(varLong); // printing the type of str to // show that long has been converted to string System.out.println(\"Converted type : \" + str.getClass().getName()); // print Long as String System.out.println(str); } }", "e": 3237, "s": 2646, "text": null }, { "code": null, "e": 3284, "s": 3237, "text": "Converted type : java.lang.String\n999999999999" }, { "code": null, "e": 3325, "s": 3284, "text": "This constructor is not valid in java 9." }, { "code": null, "e": 3333, "s": 3325, "text": "Syntax:" }, { "code": null, "e": 3376, "s": 3333, "text": "String str = new Long(varLong).toString();" }, { "code": null, "e": 3381, "s": 3376, "text": "Java" }, { "code": "// Java program to convert Long to String // using long constructor import java.util.*;public class GFG { // main method public static void main(String args[]) { // create a Long Long varLong = 999999999999L; // convert into String String str = new Long(varLong).toString(); // printing the type of str to // show that long has been converted to string System.out.println(\"Converted type : \" + str.getClass().getName()); // print Long as String System.out.println(str); } }", "e": 3994, "s": 3381, "text": null }, { "code": null, "e": 4121, "s": 3994, "text": " Since this version of java does not support this constructor. Hence, on running the program, we will get the error displaying" }, { "code": null, "e": 4173, "s": 4121, "text": "Note: prog.java uses or overrides a deprecated API." }, { "code": null, "e": 4295, "s": 4173, "text": "The java string format() method returns a formatted string using the given locale, specified format string and arguments." }, { "code": null, "e": 4303, "s": 4295, "text": "Syntax:" }, { "code": null, "e": 4372, "s": 4303, "text": "long varLong = 9999999L;\nString str = String.format(\"%d\", varLong); " }, { "code": null, "e": 4377, "s": 4372, "text": "Java" }, { "code": "// Java program to demonstrate// working of format() method class Gfg { public static void main(String args[]) { long varLong = 9999999L; String str = String.format(\"%d\", varLong); // printing the type of str to // show that long has been converted to string System.out.println(\"Converted type : \" + str.getClass().getName()); // print Long as String System.out.println(str); }}", "e": 4846, "s": 4377, "text": null }, { "code": null, "e": 4888, "s": 4846, "text": "Converted type : java.lang.String\n9999999" }, { "code": null, "e": 5118, "s": 4888, "text": "StringBuffer is a peer class of String that provides much of the functionality of strings. The string represents fixed-length, immutable character sequences while StringBuffer represents growable and writable character sequences." }, { "code": null, "e": 5126, "s": 5118, "text": "Syntax:" }, { "code": null, "e": 5212, "s": 5126, "text": "long varLong = 9999999L;\nString str = new StringBuilder().append(varLong).toString();" }, { "code": null, "e": 5217, "s": 5212, "text": "Java" }, { "code": "// Java program to convert long to// string using StringBuilder class Gfg { public static void main(String args[]) { long varLong = 9999999L; String str = new StringBuilder().append(varLong).toString(); // printing the type of str to // show that long has been converted to string System.out.println(\"Converted type : \" + str.getClass().getName()); // print Long as String System.out.println(str); }}", "e": 5705, "s": 5217, "text": null }, { "code": null, "e": 5747, "s": 5705, "text": "Converted type : java.lang.String\n9999999" }, { "code": null, "e": 5762, "s": 5747, "text": "kapoorsagar226" }, { "code": null, "e": 5772, "s": 5762, "text": "kalrap615" }, { "code": null, "e": 5787, "s": 5772, "text": "varshagumber28" }, { "code": null, "e": 5794, "s": 5787, "text": "Picked" }, { "code": null, "e": 5818, "s": 5794, "text": "Technical Scripter 2020" }, { "code": null, "e": 5823, "s": 5818, "text": "Java" }, { "code": null, "e": 5837, "s": 5823, "text": "Java Programs" }, { "code": null, "e": 5856, "s": 5837, "text": "Technical Scripter" }, { "code": null, "e": 5861, "s": 5856, "text": "Java" } ]
Spring Boot – How Thymeleaf Works?
13 Jan, 2022 Thymeleaf is a Java library, template engine used to parse and render the data produced by the application to template files – thus providing transformation. It is just like HTML but is provided with more attributes for working with rendered data. It allows caching of the parsed data/file to increase efficiency while at production. Types of templates it can process are – HTML, JAVASCRIPT, CSS, XML, TEXT, RAW. Template engines used with Spring-Boot: ThymeleafFreeMarkerMustacheGroovyJava Server Pages Thymeleaf FreeMarker Mustache Groovy Java Server Pages Thymeleaf follows a De-Coupled Architecture – It is unaware of any web framework.In the same way, it is unaware of the Spring’s abstraction of model and thus cannot handle the data that the controller places in Model.When Spring-Boot’s autoconfiguration detects Thymeleaf in the classpath, it creates beans supporting Thymeleaf view for Spring MVC.It can work with request attributes of Servlet.Therefore, Spring copies the model data into request attributes that the Thymeleaf template can work with. Thymeleaf follows a De-Coupled Architecture – It is unaware of any web framework. In the same way, it is unaware of the Spring’s abstraction of model and thus cannot handle the data that the controller places in Model. When Spring-Boot’s autoconfiguration detects Thymeleaf in the classpath, it creates beans supporting Thymeleaf view for Spring MVC. It can work with request attributes of Servlet. Therefore, Spring copies the model data into request attributes that the Thymeleaf template can work with. Simple life-cycle of Thymeleaf template To use Thymeleaf, add its dependency in the project build. Maven – pom.xml <dependency> <groupID>org.springframework.boot</groupID> <artifactID>spring-boot-starter-thymeleaf</artifactID> </dependency> Gradle – build.gradle compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf' Place the template files in the following directory : /src/main/resources/templates/ Project Structure (Maven) To render an attribute, use ‘th:text’ attribute in Thymeleaf Template <p th:text="${attributeKey}"> attributeValue will be placed here </p> Controller (TemplateController.java) file: Java package gfg; import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping; @Controller@RequestMapping("/")public class TemplateController { @GetMapping("/template1") public String template(Model model) { String msg = "Welcome to Thymeleaf Template"; // adding the attribute(key-value pair) model.addAttribute("message", msg); // returning the view name return "index"; }} Template (index.html) file: HTML <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>GFG</title> </head> <body> <h1>Welcome to GeeksForGeeks...</h1> <div id="one"> <h1 th:text="${message}"> <span>message will print here</span> </h1> </div> </body> </html> Output: To render a collection, use ‘th:each’ attributes in the Thymeleaf template <p th:each="variable:${collectionName}"> <span th:text=${variable}> items iterated will be placed here </span> </p> Note: span tag will be iterated as much as the number of collection items. Controller (TemplateController2.java) file: Java package gfg; import java.util.ArrayList;import java.util.List; import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping; @Controller@RequestMapping("/")public class TemplateController2 { @GetMapping("/template2") public String template(Model model) { String message = "Top 5 Cloud Service Providers"; // creating a collection List<String> list = new ArrayList<>(); list.add("Amazon Web Services"); list.add("Microsoft Azure"); list.add("Google Cloud"); list.add("Alibaba Cloud"); list.add("IBM Cloud"); model.addAttribute("message", message); // adding the collection attribute model.addAttribute("cloudProvider", list); return "index2"; }} Template (index2.html) file: HTML <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>GFG2</title> </head> <body> <div id="one"> <h2 th:text="${message}"> <span>message will print here</span> </h2> </div > <div id="two" th:each="List:${cloudProvider}"> <ul> <li> <span th:text=${List}>items will print here</span> </li> </ul> </div> </body> </html> Output: Pre-requisites: Object to which values will be bound must have ‘getter/setter’ methods for each field. You can use the ‘Lombok’ library to generate these methods by ‘@Data’ annotation. Add dependency of Lombok : Maven (pom.xml) <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> Using Thymeleaf, the input data is bound to the object using ‘th:object’ attribute <form method="POST" th:object="${objectName}"> </form> To map the input to a specific field of object use ‘th:field’ attribute <input type="text" th:field="*{fieldName}" /> Controller (TemplateController3.java) file: Java package gfg; import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping; import gfg.os.OperatingSystem; @Controller@RequestMapping("/template3")public class TemplateController3 { @GetMapping public String template(Model model) { model.addAttribute("ops", new OperatingSystem()); return "index3"; } @PostMapping public String template( @ModelAttribute("ops") OperatingSystem os , Model model) { model.addAttribute("message", os.getOS1()+" "+os.getOS2()+" "+os.getOS3()); return "index"; }} Class of the object to be bound (OperatingSystem.java) file: Java package gfg.os; import lombok.Data; @Datapublic class OperatingSystem { public String OS1 ,OS2, OS3; } Template (index3.html) file: HTML <!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"> <head> <title>GFG3</title> </head> <body> <h1>Welcome to GeeksForGeeks...</h1> <form method="POST" th:object="${ops}"> <div><label for="first">First OS</label></div> <input id="first" type="text" th:field="*{OS1}" /> <div><label for="second">Second OS</label></div> <input id="second" type="text" th:field="*{OS2}" /> <div><label for="third">Third OS</label></div> <input id="third" type="text" th:field="*{OS3}" /> <input type="submit" value="Send" /> </form> </body> </html> Output: Note: You can use other attributes of Thymeleaf as well. The caching of the template is enabled by default.You can turn off caching by specifying the following in the ‘application.properties’ file. You can turn off caching by specifying the following in the ‘application.properties’ file. spring.thymeleaf.cache=false Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Functional Interfaces in Java Java Programming Examples Strings in Java Differences between JDK, JRE and JVM Abstraction in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Jan, 2022" }, { "code": null, "e": 441, "s": 28, "text": "Thymeleaf is a Java library, template engine used to parse and render the data produced by the application to template files – thus providing transformation. It is just like HTML but is provided with more attributes for working with rendered data. It allows caching of the parsed data/file to increase efficiency while at production. Types of templates it can process are – HTML, JAVASCRIPT, CSS, XML, TEXT, RAW." }, { "code": null, "e": 481, "s": 441, "text": "Template engines used with Spring-Boot:" }, { "code": null, "e": 532, "s": 481, "text": "ThymeleafFreeMarkerMustacheGroovyJava Server Pages" }, { "code": null, "e": 542, "s": 532, "text": "Thymeleaf" }, { "code": null, "e": 553, "s": 542, "text": "FreeMarker" }, { "code": null, "e": 562, "s": 553, "text": "Mustache" }, { "code": null, "e": 569, "s": 562, "text": "Groovy" }, { "code": null, "e": 587, "s": 569, "text": "Java Server Pages" }, { "code": null, "e": 1089, "s": 587, "text": "Thymeleaf follows a De-Coupled Architecture – It is unaware of any web framework.In the same way, it is unaware of the Spring’s abstraction of model and thus cannot handle the data that the controller places in Model.When Spring-Boot’s autoconfiguration detects Thymeleaf in the classpath, it creates beans supporting Thymeleaf view for Spring MVC.It can work with request attributes of Servlet.Therefore, Spring copies the model data into request attributes that the Thymeleaf template can work with." }, { "code": null, "e": 1171, "s": 1089, "text": "Thymeleaf follows a De-Coupled Architecture – It is unaware of any web framework." }, { "code": null, "e": 1308, "s": 1171, "text": "In the same way, it is unaware of the Spring’s abstraction of model and thus cannot handle the data that the controller places in Model." }, { "code": null, "e": 1440, "s": 1308, "text": "When Spring-Boot’s autoconfiguration detects Thymeleaf in the classpath, it creates beans supporting Thymeleaf view for Spring MVC." }, { "code": null, "e": 1488, "s": 1440, "text": "It can work with request attributes of Servlet." }, { "code": null, "e": 1595, "s": 1488, "text": "Therefore, Spring copies the model data into request attributes that the Thymeleaf template can work with." }, { "code": null, "e": 1635, "s": 1595, "text": "Simple life-cycle of Thymeleaf template" }, { "code": null, "e": 1694, "s": 1635, "text": "To use Thymeleaf, add its dependency in the project build." }, { "code": null, "e": 1710, "s": 1694, "text": "Maven – pom.xml" }, { "code": null, "e": 1838, "s": 1710, "text": "<dependency>\n <groupID>org.springframework.boot</groupID>\n <artifactID>spring-boot-starter-thymeleaf</artifactID>\n</dependency>" }, { "code": null, "e": 1860, "s": 1838, "text": "Gradle – build.gradle" }, { "code": null, "e": 1941, "s": 1860, "text": "compile group: 'org.springframework.boot', name: 'spring-boot-starter-thymeleaf'" }, { "code": null, "e": 1995, "s": 1941, "text": "Place the template files in the following directory :" }, { "code": null, "e": 2026, "s": 1995, "text": "/src/main/resources/templates/" }, { "code": null, "e": 2052, "s": 2026, "text": "Project Structure (Maven)" }, { "code": null, "e": 2122, "s": 2052, "text": "To render an attribute, use ‘th:text’ attribute in Thymeleaf Template" }, { "code": null, "e": 2192, "s": 2122, "text": "<p th:text=\"${attributeKey}\"> attributeValue will be placed here </p>" }, { "code": null, "e": 2235, "s": 2192, "text": "Controller (TemplateController.java) file:" }, { "code": null, "e": 2240, "s": 2235, "text": "Java" }, { "code": "package gfg; import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping; @Controller@RequestMapping(\"/\")public class TemplateController { @GetMapping(\"/template1\") public String template(Model model) { String msg = \"Welcome to Thymeleaf Template\"; // adding the attribute(key-value pair) model.addAttribute(\"message\", msg); // returning the view name return \"index\"; }}", "e": 2808, "s": 2240, "text": null }, { "code": null, "e": 2836, "s": 2808, "text": "Template (index.html) file:" }, { "code": null, "e": 2841, "s": 2836, "text": "HTML" }, { "code": "<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:th=\"http://www.thymeleaf.org\"> <head> <title>GFG</title> </head> <body> <h1>Welcome to GeeksForGeeks...</h1> <div id=\"one\"> <h1 th:text=\"${message}\"> <span>message will print here</span> </h1> </div> </body> </html>", "e": 3141, "s": 2841, "text": null }, { "code": null, "e": 3149, "s": 3141, "text": "Output:" }, { "code": null, "e": 3224, "s": 3149, "text": "To render a collection, use ‘th:each’ attributes in the Thymeleaf template" }, { "code": null, "e": 3345, "s": 3224, "text": "<p th:each=\"variable:${collectionName}\"> \n <span th:text=${variable}> items iterated will be placed here </span>\n</p> " }, { "code": null, "e": 3420, "s": 3345, "text": "Note: span tag will be iterated as much as the number of collection items." }, { "code": null, "e": 3464, "s": 3420, "text": "Controller (TemplateController2.java) file:" }, { "code": null, "e": 3469, "s": 3464, "text": "Java" }, { "code": "package gfg; import java.util.ArrayList;import java.util.List; import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping; @Controller@RequestMapping(\"/\")public class TemplateController2 { @GetMapping(\"/template2\") public String template(Model model) { String message = \"Top 5 Cloud Service Providers\"; // creating a collection List<String> list = new ArrayList<>(); list.add(\"Amazon Web Services\"); list.add(\"Microsoft Azure\"); list.add(\"Google Cloud\"); list.add(\"Alibaba Cloud\"); list.add(\"IBM Cloud\"); model.addAttribute(\"message\", message); // adding the collection attribute model.addAttribute(\"cloudProvider\", list); return \"index2\"; }}", "e": 4361, "s": 3469, "text": null }, { "code": null, "e": 4390, "s": 4361, "text": "Template (index2.html) file:" }, { "code": null, "e": 4395, "s": 4390, "text": "HTML" }, { "code": "<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:th=\"http://www.thymeleaf.org\"> <head> <title>GFG2</title> </head> <body> <div id=\"one\"> <h2 th:text=\"${message}\"> <span>message will print here</span> </h2> </div > <div id=\"two\" th:each=\"List:${cloudProvider}\"> <ul> <li> <span th:text=${List}>items will print here</span> </li> </ul> </div> </body> </html>", "e": 4809, "s": 4395, "text": null }, { "code": null, "e": 4817, "s": 4809, "text": "Output:" }, { "code": null, "e": 4834, "s": 4817, "text": "Pre-requisites: " }, { "code": null, "e": 4921, "s": 4834, "text": "Object to which values will be bound must have ‘getter/setter’ methods for each field." }, { "code": null, "e": 5003, "s": 4921, "text": "You can use the ‘Lombok’ library to generate these methods by ‘@Data’ annotation." }, { "code": null, "e": 5046, "s": 5003, "text": "Add dependency of Lombok : Maven (pom.xml)" }, { "code": null, "e": 5171, "s": 5046, "text": "<dependency>\n <groupId>org.projectlombok</groupId>\n <artifactId>lombok</artifactId>\n <optional>true</optional>\n</dependency>" }, { "code": null, "e": 5254, "s": 5171, "text": "Using Thymeleaf, the input data is bound to the object using ‘th:object’ attribute" }, { "code": null, "e": 5314, "s": 5254, "text": "<form \n method=\"POST\" th:object=\"${objectName}\">\n</form>" }, { "code": null, "e": 5386, "s": 5314, "text": "To map the input to a specific field of object use ‘th:field’ attribute" }, { "code": null, "e": 5432, "s": 5386, "text": "<input type=\"text\" th:field=\"*{fieldName}\" />" }, { "code": null, "e": 5476, "s": 5432, "text": "Controller (TemplateController3.java) file:" }, { "code": null, "e": 5481, "s": 5476, "text": "Java" }, { "code": "package gfg; import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.ModelAttribute;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.RequestMapping; import gfg.os.OperatingSystem; @Controller@RequestMapping(\"/template3\")public class TemplateController3 { @GetMapping public String template(Model model) { model.addAttribute(\"ops\", new OperatingSystem()); return \"index3\"; } @PostMapping public String template( @ModelAttribute(\"ops\") OperatingSystem os , Model model) { model.addAttribute(\"message\", os.getOS1()+\" \"+os.getOS2()+\" \"+os.getOS3()); return \"index\"; }}", "e": 6298, "s": 5481, "text": null }, { "code": null, "e": 6359, "s": 6298, "text": "Class of the object to be bound (OperatingSystem.java) file:" }, { "code": null, "e": 6364, "s": 6359, "text": "Java" }, { "code": "package gfg.os; import lombok.Data; @Datapublic class OperatingSystem { public String OS1 ,OS2, OS3; }", "e": 6483, "s": 6364, "text": null }, { "code": null, "e": 6512, "s": 6483, "text": "Template (index3.html) file:" }, { "code": null, "e": 6517, "s": 6512, "text": "HTML" }, { "code": "<!DOCTYPE html><html xmlns=\"http://www.w3.org/1999/xhtml\" xmlns:th=\"http://www.thymeleaf.org\"> <head> <title>GFG3</title> </head> <body> <h1>Welcome to GeeksForGeeks...</h1> <form method=\"POST\" th:object=\"${ops}\"> <div><label for=\"first\">First OS</label></div> <input id=\"first\" type=\"text\" th:field=\"*{OS1}\" /> <div><label for=\"second\">Second OS</label></div> <input id=\"second\" type=\"text\" th:field=\"*{OS2}\" /> <div><label for=\"third\">Third OS</label></div> <input id=\"third\" type=\"text\" th:field=\"*{OS3}\" /> <input type=\"submit\" value=\"Send\" /> </form> </body> </html>", "e": 7174, "s": 6517, "text": null }, { "code": null, "e": 7182, "s": 7174, "text": "Output:" }, { "code": null, "e": 7189, "s": 7182, "text": "Note: " }, { "code": null, "e": 7240, "s": 7189, "text": "You can use other attributes of Thymeleaf as well." }, { "code": null, "e": 7381, "s": 7240, "text": "The caching of the template is enabled by default.You can turn off caching by specifying the following in the ‘application.properties’ file." }, { "code": null, "e": 7472, "s": 7381, "text": "You can turn off caching by specifying the following in the ‘application.properties’ file." }, { "code": null, "e": 7501, "s": 7472, "text": "spring.thymeleaf.cache=false" }, { "code": null, "e": 7508, "s": 7501, "text": "Picked" }, { "code": null, "e": 7513, "s": 7508, "text": "Java" }, { "code": null, "e": 7518, "s": 7513, "text": "Java" }, { "code": null, "e": 7616, "s": 7518, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7631, "s": 7616, "text": "Stream In Java" }, { "code": null, "e": 7652, "s": 7631, "text": "Introduction to Java" }, { "code": null, "e": 7673, "s": 7652, "text": "Constructors in Java" }, { "code": null, "e": 7692, "s": 7673, "text": "Exceptions in Java" }, { "code": null, "e": 7709, "s": 7692, "text": "Generics in Java" }, { "code": null, "e": 7739, "s": 7709, "text": "Functional Interfaces in Java" }, { "code": null, "e": 7765, "s": 7739, "text": "Java Programming Examples" }, { "code": null, "e": 7781, "s": 7765, "text": "Strings in Java" }, { "code": null, "e": 7818, "s": 7781, "text": "Differences between JDK, JRE and JVM" } ]
Program to calculate GST from original and net prices
23 Jun, 2022 Given Original cost and Net price then calculate the percentage of GSTExamples: Input : Netprice = 120, original_cost = 100 Output : GST = 20% Input : Netprice = 105, original_cost = 100 Output : GST = 5% How to calculate GST GST ( Goods and Services Tax ) which is included in netprice of product for get GST % first need to calculate GST Amount by subtract original cost from Netprice and then apply GST % formula = (GST_Amount*100) / original_costNetprice = original_cost + GST_Amount GST_Amount = Netprice – original_cost GST_Percentage = (GST_Amount * 100)/ original_cost C++ Java Python3 C# PHP Javascript // CPP Program to compute GST from original// and net prices.#include <iostream>using namespace std; float Calculate_GST(float org_cost, float N_price){ // return value after calculate GST% return (((N_price - org_cost) * 100) / org_cost);}// Driver program to test above functionsint main(){ float org_cost = 100; float N_price = 120; cout << "GST = " << Calculate_GST(org_cost, N_price) << " % "; return 0;} // Java Program to compute GST// from original and net prices.import java.io.*; class GFG{ static float Calculate_GST(float org_cost, float N_price) { // return value after calculate GST% return (((N_price - org_cost) * 100) / org_cost); } // Driver code public static void main (String[] args) { float org_cost = 100; float N_price = 120; System.out.print(" GST = " + Calculate_GST (org_cost, N_price) + "%"); }} // This code is contributed// by vt_m. # Python3 Program to# compute GST from original# and net prices. def Calculate_GST(org_cost, N_price): # return value after calculate GST% return (((N_price - org_cost) * 100) / org_cost); # Driver program to test above functionsorg_cost = 100N_price = 120print("GST = ",end='') print(round(Calculate_GST(org_cost, N_price)),end='') print("%") # This code is contributed# by Smitha Dinesh Semwal // C# Program to compute GST// from original and net prices.using System; class GFG{ static float Calculate_GST(float org_cost, float N_price) { // return value after calculate GST% return (((N_price - org_cost) * 100) / org_cost); } // Driver code public static void Main () { float org_cost = 100; float N_price = 120; Console.Write(" GST = " + Calculate_GST (org_cost, N_price) + "%"); }} // This code is contributed// by vt_m. <?php// PHP Program to compute GST from// original and net prices. function Calculate_GST($org_cost, $N_price){ // return value after calculate GST% return ((($N_price - $org_cost) * 100) / $org_cost);} // Driver Code $org_cost = 100; $N_price = 120; echo("GST = "); echo(Calculate_GST($org_cost, $N_price)); echo(" % "); // This code is contributed// by vt_m.?> <script>// javascript Program to compute GST// from original and net prices. function Calculate_GST(org_cost , N_price) { // return value after calculate GST% return (((N_price - org_cost) * 100) / org_cost); } // Driver code var org_cost = 100; var N_price = 120; document.write(" GST = " + Calculate_GST(org_cost, N_price) + "%"); // This code contributed by aashish1995 </script> Output: GST = 20% Time Complexity: O(1) Auxiliary Space: O(1) vt_m aashish1995 shivamanandrj9 Mathematical School Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Minimum number of jumps to reach end Find minimum number of coins that make a given value Python Dictionary Reverse a string in Java Arrays in C/C++ Introduction To PYTHON Interfaces in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Jun, 2022" }, { "code": null, "e": 135, "s": 53, "text": "Given Original cost and Net price then calculate the percentage of GSTExamples: " }, { "code": null, "e": 261, "s": 135, "text": "Input : Netprice = 120, original_cost = 100\nOutput : GST = 20%\n\nInput : Netprice = 105, original_cost = 100\nOutput : GST = 5%" }, { "code": null, "e": 637, "s": 263, "text": "How to calculate GST GST ( Goods and Services Tax ) which is included in netprice of product for get GST % first need to calculate GST Amount by subtract original cost from Netprice and then apply GST % formula = (GST_Amount*100) / original_costNetprice = original_cost + GST_Amount GST_Amount = Netprice – original_cost GST_Percentage = (GST_Amount * 100)/ original_cost " }, { "code": null, "e": 641, "s": 637, "text": "C++" }, { "code": null, "e": 646, "s": 641, "text": "Java" }, { "code": null, "e": 654, "s": 646, "text": "Python3" }, { "code": null, "e": 657, "s": 654, "text": "C#" }, { "code": null, "e": 661, "s": 657, "text": "PHP" }, { "code": null, "e": 672, "s": 661, "text": "Javascript" }, { "code": "// CPP Program to compute GST from original// and net prices.#include <iostream>using namespace std; float Calculate_GST(float org_cost, float N_price){ // return value after calculate GST% return (((N_price - org_cost) * 100) / org_cost);}// Driver program to test above functionsint main(){ float org_cost = 100; float N_price = 120; cout << \"GST = \" << Calculate_GST(org_cost, N_price) << \" % \"; return 0;}", "e": 1116, "s": 672, "text": null }, { "code": "// Java Program to compute GST// from original and net prices.import java.io.*; class GFG{ static float Calculate_GST(float org_cost, float N_price) { // return value after calculate GST% return (((N_price - org_cost) * 100) / org_cost); } // Driver code public static void main (String[] args) { float org_cost = 100; float N_price = 120; System.out.print(\" GST = \" + Calculate_GST (org_cost, N_price) + \"%\"); }} // This code is contributed// by vt_m.", "e": 1705, "s": 1116, "text": null }, { "code": "# Python3 Program to# compute GST from original# and net prices. def Calculate_GST(org_cost, N_price): # return value after calculate GST% return (((N_price - org_cost) * 100) / org_cost); # Driver program to test above functionsorg_cost = 100N_price = 120print(\"GST = \",end='') print(round(Calculate_GST(org_cost, N_price)),end='') print(\"%\") # This code is contributed# by Smitha Dinesh Semwal", "e": 2108, "s": 1705, "text": null }, { "code": "// C# Program to compute GST// from original and net prices.using System; class GFG{ static float Calculate_GST(float org_cost, float N_price) { // return value after calculate GST% return (((N_price - org_cost) * 100) / org_cost); } // Driver code public static void Main () { float org_cost = 100; float N_price = 120; Console.Write(\" GST = \" + Calculate_GST (org_cost, N_price) + \"%\"); }} // This code is contributed// by vt_m.", "e": 2669, "s": 2108, "text": null }, { "code": "<?php// PHP Program to compute GST from// original and net prices. function Calculate_GST($org_cost, $N_price){ // return value after calculate GST% return ((($N_price - $org_cost) * 100) / $org_cost);} // Driver Code $org_cost = 100; $N_price = 120; echo(\"GST = \"); echo(Calculate_GST($org_cost, $N_price)); echo(\" % \"); // This code is contributed// by vt_m.?>", "e": 3076, "s": 2669, "text": null }, { "code": "<script>// javascript Program to compute GST// from original and net prices. function Calculate_GST(org_cost , N_price) { // return value after calculate GST% return (((N_price - org_cost) * 100) / org_cost); } // Driver code var org_cost = 100; var N_price = 120; document.write(\" GST = \" + Calculate_GST(org_cost, N_price) + \"%\"); // This code contributed by aashish1995 </script>", "e": 3510, "s": 3076, "text": null }, { "code": null, "e": 3520, "s": 3510, "text": "Output: " }, { "code": null, "e": 3530, "s": 3520, "text": "GST = 20%" }, { "code": null, "e": 3552, "s": 3530, "text": "Time Complexity: O(1)" }, { "code": null, "e": 3574, "s": 3552, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3579, "s": 3574, "text": "vt_m" }, { "code": null, "e": 3591, "s": 3579, "text": "aashish1995" }, { "code": null, "e": 3606, "s": 3591, "text": "shivamanandrj9" }, { "code": null, "e": 3619, "s": 3606, "text": "Mathematical" }, { "code": null, "e": 3638, "s": 3619, "text": "School Programming" }, { "code": null, "e": 3651, "s": 3638, "text": "Mathematical" }, { "code": null, "e": 3749, "s": 3651, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3773, "s": 3749, "text": "Merge two sorted arrays" }, { "code": null, "e": 3794, "s": 3773, "text": "Operators in C / C++" }, { "code": null, "e": 3808, "s": 3794, "text": "Prime Numbers" }, { "code": null, "e": 3845, "s": 3808, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 3898, "s": 3845, "text": "Find minimum number of coins that make a given value" }, { "code": null, "e": 3916, "s": 3898, "text": "Python Dictionary" }, { "code": null, "e": 3941, "s": 3916, "text": "Reverse a string in Java" }, { "code": null, "e": 3957, "s": 3941, "text": "Arrays in C/C++" }, { "code": null, "e": 3980, "s": 3957, "text": "Introduction To PYTHON" } ]
replace() Function Of Datetime.date Class In Python
23 Aug, 2021 replace() function is used to manipulate the object of DateTime class of module of DateTime. Generally, it replaces the date( Year, Month, Day) and returns a new DateTime object. Syntax: replace(year=self.year, month=self.month, day=self.day) Parameters: Year: New year value (range: 1 <= year <= 9999) month: New month value(range: 1 <= month <= 12) day: New day value(range: 1<= day <= 31) Returns: New datetime object. Example 1: Replace the year with datetime object. Python3 # import modulefrom datetime import date # Creating an instance# of datetimeDate = date(2010, 2, 12)print("Original date : ", Date) # Using replace() methodNew_date = Date.replace(year=2021)print("After Modify the year:", New_date) Original date : 2010-02-12 After Modify the year: 2021-02-12 Example 2: Replace the month with datetime object. Python3 # import modulefrom datetime import date # Creating an instance# of datetimeDate = date(2010, 2, 12)print("Original date : ", Date) # Using replace() methodNew_date = Date.replace(month=5)print("After Modify the month:", New_date) Original date : 2010-02-12 After Modify the month: 2010-05-12 Example 3: Replace the day with datetime object. Python3 # import modulefrom datetime import date # Creating an instance# of datetimeDate = date(2010, 2, 12)print("Original date : ", Date) # Using replace() methodNew_date = Date.replace(day=21)print("After Modify the day:", New_date) Original date : 2010-02-12 After Modify the day: 2010-02-21 Example 4: Replace the time with datetime object. Python3 from datetime import datetime Date = datetime(2010, 2, 12, 8, 50, 23)print("Original date and time : ", Date) New_date = Date.replace(hour=1, minute=3, second=12)print("After modify date and time : ", New_date) Original date and time : 2010-02-12 08:50:23 After modify date and time : 2010-02-12 01:03:12 Picked Python-datetime 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": 207, "s": 28, "text": "replace() function is used to manipulate the object of DateTime class of module of DateTime. Generally, it replaces the date( Year, Month, Day) and returns a new DateTime object." }, { "code": null, "e": 271, "s": 207, "text": "Syntax: replace(year=self.year, month=self.month, day=self.day)" }, { "code": null, "e": 283, "s": 271, "text": "Parameters:" }, { "code": null, "e": 331, "s": 283, "text": "Year: New year value (range: 1 <= year <= 9999)" }, { "code": null, "e": 379, "s": 331, "text": "month: New month value(range: 1 <= month <= 12)" }, { "code": null, "e": 420, "s": 379, "text": "day: New day value(range: 1<= day <= 31)" }, { "code": null, "e": 450, "s": 420, "text": "Returns: New datetime object." }, { "code": null, "e": 500, "s": 450, "text": "Example 1: Replace the year with datetime object." }, { "code": null, "e": 508, "s": 500, "text": "Python3" }, { "code": "# import modulefrom datetime import date # Creating an instance# of datetimeDate = date(2010, 2, 12)print(\"Original date : \", Date) # Using replace() methodNew_date = Date.replace(year=2021)print(\"After Modify the year:\", New_date)", "e": 742, "s": 508, "text": null }, { "code": null, "e": 805, "s": 742, "text": "Original date : 2010-02-12\nAfter Modify the year: 2021-02-12\n" }, { "code": null, "e": 856, "s": 805, "text": "Example 2: Replace the month with datetime object." }, { "code": null, "e": 864, "s": 856, "text": "Python3" }, { "code": "# import modulefrom datetime import date # Creating an instance# of datetimeDate = date(2010, 2, 12)print(\"Original date : \", Date) # Using replace() methodNew_date = Date.replace(month=5)print(\"After Modify the month:\", New_date)", "e": 1097, "s": 864, "text": null }, { "code": null, "e": 1161, "s": 1097, "text": "Original date : 2010-02-12\nAfter Modify the month: 2010-05-12\n" }, { "code": null, "e": 1210, "s": 1161, "text": "Example 3: Replace the day with datetime object." }, { "code": null, "e": 1218, "s": 1210, "text": "Python3" }, { "code": "# import modulefrom datetime import date # Creating an instance# of datetimeDate = date(2010, 2, 12)print(\"Original date : \", Date) # Using replace() methodNew_date = Date.replace(day=21)print(\"After Modify the day:\", New_date)", "e": 1448, "s": 1218, "text": null }, { "code": null, "e": 1510, "s": 1448, "text": "Original date : 2010-02-12\nAfter Modify the day: 2010-02-21\n" }, { "code": null, "e": 1560, "s": 1510, "text": "Example 4: Replace the time with datetime object." }, { "code": null, "e": 1568, "s": 1560, "text": "Python3" }, { "code": "from datetime import datetime Date = datetime(2010, 2, 12, 8, 50, 23)print(\"Original date and time : \", Date) New_date = Date.replace(hour=1, minute=3, second=12)print(\"After modify date and time : \", New_date)", "e": 1827, "s": 1568, "text": null }, { "code": null, "e": 1924, "s": 1827, "text": "Original date and time : 2010-02-12 08:50:23\nAfter modify date and time : 2010-02-12 01:03:12\n" }, { "code": null, "e": 1931, "s": 1924, "text": "Picked" }, { "code": null, "e": 1947, "s": 1931, "text": "Python-datetime" }, { "code": null, "e": 1954, "s": 1947, "text": "Python" } ]
How to delete default values in text field using Selenium?
We can delete default values in the text field with Selenium webdriver. There are multiple ways to do this. We can use the clear() method which resets value present already in edit box or text area field. We can use the Keys.chord() method along with sendKeys(). The Keys.chord() method helps to press multiple keys simultaneously. It accepts the sequence of keys or strings as a parameter to the method. To delete default values, it takes, Keys.CONTROL, "a" as parameters. This string is then sent as a parameter to the sendKeys() method. Finally, we have to pass Keys.DELETE to the sendKeys() method. Let us consider the below edit field where we will delete the input values. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class DelDefaultVal{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); // identify element WebElement l = driver.findElement(By.id("gsc-i-id1")); // input text l.sendKeys("Selenium"); // delete default value with clear() l.clear(); driver.quit() } } import org.openqa.selenium.By; import org.openqa.selenium.Keys; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class DelDefaultValue{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver","C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://www.tutorialspoint.com/index.htm"; driver.get(url); driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS); // identify element WebElement l = driver.findElement(By.id("gsc-i-id1")); // input text l.sendKeys("Selenium"); // sending Ctrl+a by Keys.Chord() String s = Keys.chord(Keys.CONTROL, "a"); l.sendKeys(s); // sending DELETE key l.sendKeys(Keys.DELETE); driver.quit() } }
[ { "code": null, "e": 1392, "s": 1187, "text": "We can delete default values in the text field with Selenium webdriver. There are multiple ways to do this. We can use the clear() method which resets value present already in edit box or text area field." }, { "code": null, "e": 1592, "s": 1392, "text": "We can use the Keys.chord() method along with sendKeys(). The Keys.chord() method helps to press multiple keys simultaneously. It accepts the sequence of keys or strings as a parameter to the method." }, { "code": null, "e": 1790, "s": 1592, "text": "To delete default values, it takes, Keys.CONTROL, \"a\" as parameters. This string is then sent as a parameter to the sendKeys() method. Finally, we have to pass Keys.DELETE to the sendKeys() method." }, { "code": null, "e": 1866, "s": 1790, "text": "Let us consider the below edit field where we will delete the input values." }, { "code": null, "e": 2659, "s": 1866, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\n\npublic class DelDefaultVal{\n public static void main(String[] args) {\nSystem.setProperty(\"webdriver.chrome.driver\",\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);\n // identify element\n WebElement l = driver.findElement(By.id(\"gsc-i-id1\"));\n // input text\n l.sendKeys(\"Selenium\");\n // delete default value with clear()\n l.clear();\n driver.quit()\n }\n}" }, { "code": null, "e": 3595, "s": 2659, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.Keys;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\n\npublic class DelDefaultValue{\n public static void main(String[] args) {\nSystem.setProperty(\"webdriver.chrome.driver\",\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://www.tutorialspoint.com/index.htm\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(4, TimeUnit.SECONDS);\n // identify element\n WebElement l = driver.findElement(By.id(\"gsc-i-id1\"));\n // input text\n l.sendKeys(\"Selenium\");\n // sending Ctrl+a by Keys.Chord()\n String s = Keys.chord(Keys.CONTROL, \"a\");\n l.sendKeys(s);\n // sending DELETE key\n l.sendKeys(Keys.DELETE);\n driver.quit()\n }\n}" } ]
C++ program to Implement Threaded Binary Tree
Threaded binary tree is a binary tree that provides the facility to traverse the tree in a particular order. It makes inorder traversal faster and do it without stack and without recursion. There are two types of threaded binary trees. Single Threaded Each node is threaded towards either left or right means in-order predecessor or successor. Here, all right null pointers will point to inorder successor or all left null pointers will point to inorder predecessor. Double threaded Each node is threaded towards either left and right means in-order predecessor and successor. Here, all right null pointers will point to inorder successor and all left null pointers will point to inorder predecessor. This is a C++ program to implement Threaded Binary Tree. Insert node as root if tree is completely empty. Otherwise, if newnode < current node then Go to left thread and set the newnode as left child. else Go to right thread and set the newnode as right child. If search key < root then Go to left thread else Go to right thread Find Node and its parent. For deleting node there are three cases − Node which has two children. Has only left child. Has only right child. #include <iostream> #include <cstdlib> #define MAX_VALUE 65536 using namespace std; class N { //node declaration public: int k; N *l, *r; bool leftTh, rightTh; }; class ThreadedBinaryTree { private: N *root; public: ThreadedBinaryTree() { //constructor to initialize the variables root= new N(); root->r= root->l= root; root->leftTh = true; root->k = MAX_VALUE; } void makeEmpty() { //clear tree root= new N(); root->r = root->l = root; root->leftTh = true; root->k = MAX_VALUE; } void insert(int key) { N *p = root; for (;;) { if (p->k< key) { / /move to right thread if (p->rightTh) break; p = p->r; } else if (p->k > key) { // move to left thread if (p->leftTh) break; p = p->l; } else { return; } } N *temp = new N(); temp->k = key; temp->rightTh= temp->leftTh= true; if (p->k < key) { temp->r = p->r; temp->l= p; p->r = temp; p->rightTh= false; } else { temp->r = p; temp->l = p->l; p->l = temp; p->leftTh = false; } } bool search(int key) { N *temp = root->l; for (;;) { if (temp->k < key) { //search in left thread if (temp->rightTh) return false; temp = temp->r; } else if (temp->k > key) { //search in right thread if (temp->leftTh) return false; temp = temp->l; } else { return true; } } } void Delete(int key) { N *dest = root->l, *p = root; for (;;) { //find Node and its parent. if (dest->k < key) { if (dest->rightTh) return; p = dest; dest = dest->r; } else if (dest->k > key) { if (dest->leftTh) return; p = dest; dest = dest->l; } else { break; } } N *target = dest; if (!dest->rightTh && !dest->leftTh) { p = dest; //has two children target = dest->l; //largest node at left child while (!target->rightTh) { p = target; target = target->r; } dest->k= target->k; //replace mode } if (p->k >= target->k) { //only left child if (target->rightTh && target->leftTh) { p->l = target->l; p->leftTh = true; } else if (target->rightTh) { N*largest = target->l; while (!largest->rightTh) { largest = largest->r; } largest->r = p; p->l= target->l; } else { N *smallest = target->r; while (!smallest->leftTh) { smallest = smallest->l; } smallest->l = target->l; p->l = target->r; } } else {//only right child if (target->rightTh && target->leftTh) { p->r= target->r; p->rightTh = true; } else if (target->rightTh) { N *largest = target->l; while (!largest->rightTh) { largest = largest->r; } largest->r= target->r; p->r = target->l; } else { N *smallest = target->r; while (!smallest->leftTh) { smallest = smallest->l; } smallest->l= p; p->r= target->r; } } } void displayTree() { //print the tree N *temp = root, *p; for (;;) { p = temp; temp = temp->r; if (!p->rightTh) { while (!temp->leftTh) { temp = temp->l; } } if (temp == root) break; cout<<temp->k<<" "; } cout<<endl; } }; int main() { ThreadedBinaryTree tbt; cout<<"ThreadedBinaryTree\n"; char ch; int c, v; while(1) { cout<<"1. Insert "<<endl; cout<<"2. Delete"<<endl; cout<<"3. Search"<<endl; cout<<"4. Clear"<<endl; cout<<"5. Display"<<endl; cout<<"6. Exit"<<endl; cout<<"Enter Your Choice: "; cin>>c; //perform switch operation switch (c) { case 1 : cout<<"Enter integer element to insert: "; cin>>v; tbt.insert(v); break; case 2 : cout<<"Enter integer element to delete: "; cin>>v; tbt.Delete(v); break; case 3 : cout<<"Enter integer element to search: "; cin>>v; if (tbt.search(v) == true) cout<<"Element "<<v<<" found in the tree"<<endl; else cout<<"Element "<<v<<" not found in the tree"<<endl; break; case 4 : cout<<"\nTree Cleared\n"; tbt.makeEmpty(); break; case 5: cout<<"Display tree: \n "; tbt.displayTree(); break; case 6: exit(1); default: cout<<"\nInvalid type! \n"; } } cout<<"\n"; return 0; } ThreadedBinaryTree 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 1 Enter integer element to insert: 10 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 1 Enter integer element to insert: 7 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 1 Enter integer element to insert: 6 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 1 Enter integer element to insert: 4 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 1 Enter integer element to insert: 5 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 1 Enter integer element to insert: 3 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 5 Display tree 3 4 5 6 7 10 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 3 Enter integer element to search: 7 Element 7 found in the tree 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 3 Enter integer element to search: 1 Element 1 not found in the tree 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 2 Enter integer element to delete: 3 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 5 Display tree 4 5 6 7 10 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 4 Tree Cleared 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 5 Display tree 1. Insert 2. Delete 3. Search 4. Clear 5. Display 6. Exit Enter Your Choice: 6
[ { "code": null, "e": 1296, "s": 1187, "text": "Threaded binary tree is a binary tree that provides the facility to traverse the tree in a particular order." }, { "code": null, "e": 1423, "s": 1296, "text": "It makes inorder traversal faster and do it without stack and without recursion. There are two types of threaded binary trees." }, { "code": null, "e": 1654, "s": 1423, "text": "Single Threaded Each node is threaded towards either left or right means in-order predecessor or successor. Here, all right null pointers will point to inorder successor or all left null pointers will point to inorder predecessor." }, { "code": null, "e": 1888, "s": 1654, "text": "Double threaded Each node is threaded towards either left and right means in-order predecessor and successor. Here, all right null pointers will point to inorder successor and all left null pointers will point to inorder predecessor." }, { "code": null, "e": 1945, "s": 1888, "text": "This is a C++ program to implement Threaded Binary Tree." }, { "code": null, "e": 2155, "s": 1945, "text": "Insert node as root if tree is completely empty.\nOtherwise, if newnode < current node then\n Go to left thread and set the newnode as left child.\nelse\n Go to right thread and set the newnode as right child." }, { "code": null, "e": 2229, "s": 2155, "text": "If search key < root then\n Go to left thread\nelse\n Go to right thread" }, { "code": null, "e": 2297, "s": 2229, "text": "Find Node and its parent. For deleting node there are three cases −" }, { "code": null, "e": 2326, "s": 2297, "text": "Node which has two children." }, { "code": null, "e": 2347, "s": 2326, "text": "Has only left child." }, { "code": null, "e": 2369, "s": 2347, "text": "Has only right child." }, { "code": null, "e": 7422, "s": 2369, "text": "#include <iostream>\n#include <cstdlib>\n#define MAX_VALUE 65536\nusing namespace std;\nclass N { //node declaration\n public:\n int k;\n N *l, *r;\n bool leftTh, rightTh;\n};\nclass ThreadedBinaryTree {\n private:\n N *root;\n public:\n ThreadedBinaryTree() { //constructor to initialize the variables\n root= new N();\n root->r= root->l= root;\n root->leftTh = true;\n root->k = MAX_VALUE;\n }\n void makeEmpty() { //clear tree\n root= new N();\n root->r = root->l = root;\n root->leftTh = true;\n root->k = MAX_VALUE;\n }\n void insert(int key) {\n N *p = root;\n for (;;) {\n if (p->k< key) { / /move to right thread\n if (p->rightTh)\n break;\n p = p->r;\n } else if (p->k > key) { // move to left thread\n if (p->leftTh)\n break;\n p = p->l;\n } else {\n return;\n }\n }\n N *temp = new N();\n temp->k = key;\n temp->rightTh= temp->leftTh= true;\n if (p->k < key) {\n temp->r = p->r;\n temp->l= p;\n p->r = temp;\n p->rightTh= false;\n } else {\n temp->r = p;\n temp->l = p->l;\n p->l = temp;\n p->leftTh = false;\n }\n }\n bool search(int key) {\n N *temp = root->l;\n for (;;) {\n if (temp->k < key) { //search in left thread\n if (temp->rightTh)\n return false;\n temp = temp->r;\n } else if (temp->k > key) { //search in right thread\n if (temp->leftTh)\n return false;\n temp = temp->l;\n } else {\n return true;\n }\n }\n}\nvoid Delete(int key) {\n N *dest = root->l, *p = root;\n for (;;) { //find Node and its parent.\n if (dest->k < key) {\n if (dest->rightTh)\n return;\n p = dest;\n dest = dest->r;\n } else if (dest->k > key) {\n if (dest->leftTh)\n return;\n p = dest;\n dest = dest->l;\n } else {\n break;\n }\n }\n N *target = dest;\n if (!dest->rightTh && !dest->leftTh) {\n p = dest; //has two children\n target = dest->l; //largest node at left child\n while (!target->rightTh) {\n p = target;\n target = target->r;\n }\n dest->k= target->k; //replace mode\n }\n if (p->k >= target->k) { //only left child\n if (target->rightTh && target->leftTh) {\n p->l = target->l;\n p->leftTh = true;\n } else if (target->rightTh) {\n N*largest = target->l;\n while (!largest->rightTh) {\n largest = largest->r;\n }\n largest->r = p;\n p->l= target->l;\n } else {\n N *smallest = target->r;\n while (!smallest->leftTh) {\n smallest = smallest->l;\n }\n smallest->l = target->l;\n p->l = target->r;\n }\n } else {//only right child\n if (target->rightTh && target->leftTh) {\n p->r= target->r;\n p->rightTh = true;\n } else if (target->rightTh) {\n N *largest = target->l;\n while (!largest->rightTh) {\n largest = largest->r;\n }\n largest->r= target->r;\n p->r = target->l;\n } else {\n N *smallest = target->r;\n while (!smallest->leftTh) {\n smallest = smallest->l;\n }\n smallest->l= p;\n p->r= target->r;\n }\n }\n}\nvoid displayTree() { //print the tree\n N *temp = root, *p;\n for (;;) {\n p = temp;\n temp = temp->r;\n if (!p->rightTh) {\n while (!temp->leftTh) {\n temp = temp->l;\n }\n }\n if (temp == root)\n break;\n cout<<temp->k<<\" \";\n }\n cout<<endl;\n}\n};\nint main() {\n ThreadedBinaryTree tbt;\n cout<<\"ThreadedBinaryTree\\n\";\n char ch;\n int c, v; \n while(1) {\n cout<<\"1. Insert \"<<endl;\n cout<<\"2. Delete\"<<endl;\n cout<<\"3. Search\"<<endl;\n cout<<\"4. Clear\"<<endl;\n cout<<\"5. Display\"<<endl;\n cout<<\"6. Exit\"<<endl;\n cout<<\"Enter Your Choice: \";\n cin>>c;\n //perform switch operation\n switch (c) {\n case 1 :\n cout<<\"Enter integer element to insert: \";\n cin>>v;\n tbt.insert(v);\n break;\n case 2 :\n cout<<\"Enter integer element to delete: \";\n cin>>v;\n tbt.Delete(v);\n break;\n case 3 :\n cout<<\"Enter integer element to search: \";\n cin>>v;\n if (tbt.search(v) == true)\n cout<<\"Element \"<<v<<\" found in the tree\"<<endl;\n else\n cout<<\"Element \"<<v<<\" not found in the tree\"<<endl;\n break;\n case 4 :\n cout<<\"\\nTree Cleared\\n\";\n tbt.makeEmpty();\n break;\n case 5:\n cout<<\"Display tree: \\n \";\n tbt.displayTree();\n break;\n case 6:\n exit(1);\n default:\n cout<<\"\\nInvalid type! \\n\";\n }\n }\n cout<<\"\\n\";\n return 0;\n}" }, { "code": null, "e": 9001, "s": 7422, "text": "ThreadedBinaryTree\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 1\nEnter integer element to insert: 10\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 1\nEnter integer element to insert: 7\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 1\nEnter integer element to insert: 6\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 1\nEnter integer element to insert: 4\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 1\nEnter integer element to insert: 5\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 1\nEnter integer element to insert: 3\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 5\nDisplay tree\n3 4 5 6 7 10\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 3\nEnter integer element to search: 7\nElement 7 found in the tree\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 3\nEnter integer element to search: 1\nElement 1 not found in the tree\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 2\nEnter integer element to delete: 3\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 5\nDisplay tree\n4 5 6 7 10\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 4\n\nTree Cleared\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 5\nDisplay tree\n\n1. Insert\n2. Delete\n3. Search\n4. Clear\n5. Display\n6. Exit\nEnter Your Choice: 6" } ]
Program for Mobius Function
23 Jun, 2022 Mobius Function is a multiplicative function that is used in combinatorics. It has one of three possible values -1, 0 and 1.Examples: Input : 6 Output : 1 Solution: Prime Factors: 2 3. Therefore p = 2, (-1)^p = 1 Input: 49 Output: 0 Solution: Prime Factors: 7 ( occurs twice). Since the prime factor occurs twice answer is 0. Input: 3 Output: -1 Solution: Prime Factors: 3. Therefore p = 1, (-1) ^ p =-1 Input : 78 Output : 1 Solution: Prime Factors: 3, 13. Therefore p = 2, (-1)^p = 1 Method 1 (Simple) We iterate through all numbers i smaller than or equal to N. For every number we check if it divides N. If yes, we check if it’s also prime. If both conditions are satisfied, we check if its square also divides N. If yes, we return 0. If the square doesn’t divide, we increment count of prime factors. Finally, we return 1 if there are an even number of prime factors and return -1 if there are odd number of prime factors. C++ Java Python3 C# PHP Javascript // CPP Program to evaluate Mobius Function// M(N) = 1 if N = 1// M(N) = 0 if any prime factor of N is contained twice// M(N) = (-1)^(no of distinct prime factors)#include<iostream>using namespace std; // Function to check if n is prime or notbool isPrime(int n){ if (n < 2) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true;} int mobius(int N){ // Base Case if (N == 1) return 1; // For a prime factor i check if i^2 is also // a factor. int p = 0; for (int i = 1; i <= N; i++) { if (N % i == 0 && isPrime(i)) { // Check if N is divisible by i^2 if (N % (i * i) == 0) return 0; else // i occurs only once, increase f p++; } } // All prime factors are contained only once // Return 1 if p is even else -1 return (p % 2 != 0)? -1 : 1;} // Driver codeint main(){ int N = 17; cout << "Mobius Functions M(N) at N = " << N << " is: " << mobius(N) << endl; cout << "Mobius Functions M(N) at N = " << 25 << " is: " << mobius(25) << endl; cout << "Mobius Functions M(N) at N = " << 6 << " is: " << mobius(6) << endl;} // Java program for mobious functionimport java.io.*;public class GFG { // C# Program to evaluate Mobius // Function: M(N) = 1 if N = 1 // M(N) = 0 if any prime factor // of N is contained twice // M(N) = (-1)^(no of distinct // prime factors) // Function to check if n is // prime or not static boolean isPrime(int n) { if (n < 2) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } static int mobius(int N) { // Base Case if (N == 1) return 1; // For a prime factor i check if // i^2 is also a factor. int p = 0; for (int i = 1; i <= N; i++) { if (N % i == 0 && isPrime(i)) { // Check if N is divisible by i^2 if (N % (i * i) == 0) return 0; else // i occurs only once, increase f p++; } } // All prime factors are contained only // once Return 1 if p is even else -1 return (p % 2 != 0) ? -1 : 1; } // Driver code static public void main(String[] args) { int N = 17; System.out.println("Mobius Functions M(N) at " + " N = " + N + " is: " + mobius(N)); System.out.println("Mobius Functions M(N) at " + " N = " + 25 + " is: " + mobius(25)); System.out.println("Mobius Functions M(N) at " + " N = " + 6 + " is: " + mobius(6)); }} // This code is contributed by vt_m # Python Program to# evaluate Mobius def# M(N) = 1 if N = 1# M(N) = 0 if any# prime factor of# N is contained twice# M(N) = (-1)^(no of# distinct prime factors) # def to check if# n is prime or notdef isPrime(n) : if (n < 2) : return False for i in range(2, n + 1) : if (i * i <= n and n % i == 0) : return False return True def mobius(N) : # Base Case if (N == 1) : return 1 # For a prime factor i # check if i^2 is also # a factor. p = 0 for i in range(1, N + 1) : if (N % i == 0 and isPrime(i)) : # Check if N is # divisible by i^2 if (N % (i * i) == 0) : return 0 else : # i occurs only once, # increase f p = p + 1 # All prime factors are # contained only once # Return 1 if p is even # else -1 if(p % 2 != 0) : return -1 else : return 1 # Driver CodeN = 17print ("Mobius defs M(N) at N = {} is: {}" . format(N, mobius(N)),end = "\n")print ("Mobius defs M(N) at N = {} is: {}" . format(25, mobius(25)),end = "\n")print ("Mobius defs M(N) at N = {} is: {}" . format(6, mobius(6)),end = "\n") # This code is contributed by# Manish Shaw(manishshaw1) // C# Program to evaluate Mobius Functionusing System; public class GFG{ // M(N) = 1 if N = 1 // M(N) = 0 if any prime factor // of N is contained twice // M(N) = (-1)^(no of distinct // prime factors) // Function to check if n is // prime or not static bool isPrime(int n) { if (n == 2) return true; if (n % 2 == 0) return false; for (int i = 3; i * i <= n / 2; i += 2) if (n % i == 0) return false; return true; } static int mobius(int N) { // Base Case if (N == 1) return 1; // For a prime factor i check // if i^2 is also a factor. int p = 0; for (int i = 2; i <= N; i++) { if (N % i == 0 && isPrime(i)) { // Check if N is divisible by i^2 if (N % (i * i) == 0) return 0; else // i occurs only once, increase f p++; } } // All prime factors are contained only // once Return 1 if p is even else -1 return (p % 2 != 0) ? -1 : 1; } // Driver code static public void Main() { Console.WriteLine("Mobius Functions M(N) at " + "N = " + 17 + " is: " + mobius(17)); Console.WriteLine("Mobius Functions M(N) at " + "N = " + 25 + " is: " + mobius(25)); Console.WriteLine("Mobius Functions M(N) at " + "N = " + 6 + " is: " + mobius(6)); }} // This code is contributed by vt_m <?php// PHP Program to evaluate Mobius Function// M(N) = 1 if N = 1// M(N) = 0 if any prime factor of// N is contained twice// M(N) = (-1)^(no of distinct prime factors) // Function to check if n is prime or notfunction isPrime($n){ if ($n < 2) return false; for ($i = 2; $i * $i <= $n; $i++) if ($n % $i == 0) return false; return true;} function mobius($N){ // Base Case if ($N == 1) return 1; // For a prime factor i // check if i^2 is also // a factor. $p = 0; for ($i = 1; $i <= $N; $i++) { if ($N % $i == 0 && isPrime($i)) { // Check if N is divisible by i^2 if ($N % ($i * $i) == 0) return 0; else // i occurs only once, increase f $p++; } } // All prime factors are // contained only once // Return 1 if p is even // else -1 return ($p % 2 != 0) ? -1 : 1;} // Driver Code $N = 17; echo "Mobius Functions M(N) at N = " ,$N , " is: " , mobius($N) ,"\n"; echo "Mobius Functions M(N) at N = " ,25, " is: " , mobius(25),"\n" ; echo "Mobius Functions M(N) at N = " ,6, " is: " , mobius(6) ; // This code is contributed by nitin mittal.?> <script> // JavaScript program for mobius function // JavaScript Program to evaluate Mobius // Function: M(N) = 1 if N = 1 // M(N) = 0 if any prime factor // of N is contained twice // M(N) = (-1)^(no of distinct // prime factors) // Function to check if n is // prime or not function isPrime(n) { if (n < 2) return false; for (let i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } function mobius(N) { // Base Case if (N == 1) return 1; // For a prime factor i check if // i^2 is also a factor. let p = 0; for (let i = 1; i <= N; i++) { if (N % i == 0 && isPrime(i)) { // Check if N is divisible by i^2 if (N % (i * i) == 0) return 0; else // i occurs only once, increase f p++; } } // All prime factors are contained only // once Return 1 if p is even else -1 return (p % 2 != 0) ? -1 : 1; } // Driver code let N = 17; document.write("Mobius Functions M(N) at " + " N = " + N + " is: " + mobius(N) + "<br/>"); document.write("Mobius Functions M(N) at " + " N = " + 25 + " is: " + mobius(25) + "<br/>"); document.write("Mobius Functions M(N) at " + " N = " + 6 + " is: " + mobius(6) + "<br/>"); </script> Output: Mobius Functions M(N) at N = 17 is: -1 Mobius Functions M(N) at N = 25 is: 0 Mobius Functions M(N) at N = 6 is: 1 Time Complexity: O(n√n ) Auxiliary Space: O(1) Method 2 (Efficient) The idea is based on efficient program to print all prime factors of a given number. The interesting thing is, we do not need inner while loop here because if a number divides more than once, we can immediately return 0. C++ Java Python3 C# PHP Javascript // Program to print all prime factors# include <bits/stdc++.h>using namespace std; // Returns value of mobius()int mobius(int n){ int p = 0; // Handling 2 separately if (n%2 == 0) { n = n/2; p++; // If 2^2 also divides N if (n % 2 == 0) return 0; } // Check for all other prime factors for (int i = 3; i <= sqrt(n); i = i+2) { // If i divides n if (n%i == 0) { n = n/i; p++; // If i^2 also divides N if (n % i == 0) return 0; } } return (p % 2 == 0)? -1 : 1;} // Driver codeint main() { int N = 17; cout << "Mobius Functions M(N) at N = " << N << " is: " << mobius(N) << endl; cout << "Mobius Functions M(N) at N = " << 25 << " is: " << mobius(25) << endl; cout << "Mobius Functions M(N) at N = " << 6 << " is: " << mobius(6) << endl;} // Java program to print all prime factorsimport java.io.*; class GFG { // Returns value of mobius() static int mobius(int n) { int p = 0; // Handling 2 separately if (n % 2 == 0) { n = n / 2; p++; // If 2^2 also divides N if (n % 2 == 0) return 0; } // Check for all other prime factors for (int i = 3; i <= Math.sqrt(n); i = i+2) { // If i divides n if (n % i == 0) { n = n / i; p++; // If i^2 also divides N if (n % i == 0) return 0; } } return (p % 2 == 0)? -1 : 1; } // Driver code public static void main (String[] args) { int N = 17; System.out.println( "Mobius Functions" + " M(N) at N = " + N + " is: " + mobius(N)); System.out.println ("Mobius Functions" + "M(N) at N = " + 25 + " is: " + mobius(25)); System.out.println( "Mobius Functions" + "M(N) at N = " + 6 + " is: " + mobius(6)); }} // This code is contributed by anuj_67. # Python Program to evaluate# Mobius def M(N) = 1 if N = 1# M(N) = 0 if any prime factor# of N is contained twice# M(N) = (-1)^(no of distinct# prime factors)import math # def to check if n# is prime or notdef isPrime(n) : if (n < 2) : return False for i in range(2, n + 1) : if (n % i == 0) : return False i = i * i return True def mobius(n) : p = 0 # Handling 2 separately if (n % 2 == 0) : n = int(n / 2) p = p + 1 # If 2^2 also # divides N if (n % 2 == 0) : return 0 # Check for all # other prime factors for i in range(3, int(math.sqrt(n)) + 1) : # If i divides n if (n % i == 0) : n = int(n / i) p = p + 1 # If i^2 also # divides N if (n % i == 0) : return 0 i = i + 2 if(p % 2 == 0) : return -1 else : return 1 # Driver CodeN = 17print ("Mobius defs M(N) at N = {} is: {}\n" . format(N, mobius(N)));print ("Mobius defs M(N) at N = 25 is: {}\n" . format(mobius(25)));print ("Mobius defs M(N) at N = 6 is: {}\n" . format(mobius(6))); # This code is contributed by# Manish Shaw(manishshaw1) // C# program to print all prime factorsusing System;class GFG { // Returns value of mobius() static int mobius(int n) { int p = 0; // Handling 2 separately if (n % 2 == 0) { n = n / 2; p++; // If 2^2 also divides N if (n % 2 == 0) return 0; } // Check for all other prime factors for (int i = 3; i <= Math.Sqrt(n); i = i+2) { // If i divides n if (n % i == 0) { n = n / i; p++; // If i^2 also divides N if (n % i == 0) return 0; } } return (p % 2 == 0)? -1 : 1; } // Driver Code public static void Main () { int N = 17; Console.WriteLine( "Mobius Functions" + " M(N) at N = " + N + " is: " + mobius(N)); Console.WriteLine("Mobius Functions" + "M(N) at N = " + 25 + " is: " + mobius(25)); Console.WriteLine( "Mobius Functions" + "M(N) at N = " + 6 + " is: " + mobius(6)); }} // This code is contributed by anuj_67. <?php// PHP Program to print// all prime factors // Returns value of mobius()function mobius( $n){ $p = 0; // Handling 2 separately if ($n % 2 == 0) { $n = $n / 2; $p++; // If 2^2 also divides N if ($n % 2 == 0) return 0; } // Check for all // other prime factors for ( $i = 3; $i <= sqrt($n); $i = $i + 2) { // If i divides n if ($n % $i == 0) { $n = $n / $i; $p++; // If i^2 also divides N if ($n % $i == 0) return 0; } } return ($p % 2 == 0)? -1 : 1;} // Driver code $N = 17; echo "Mobius Functions M(N) at N = ", $N, " is: " , mobius($N),"\n" ; echo "Mobius Functions M(N) at N = " , 25 , " is: " , mobius(25),"\n"; echo "Mobius Functions M(N) at N = " , 6 , " is: " , mobius(6) ; // This code is contributed by anuj_67.?> <script> // JavaScript program to print all prime factors // Returns value of mobius() function mobius(n) { let p = 0; // Handling 2 separately if (n % 2 == 0) { n = parseInt(n / 2, 10); p++; // If 2^2 also divides N if (n % 2 == 0) return 0; } // Check for all other prime factors for (let i = 3; i <= Math.sqrt(n); i = i+2) { // If i divides n if (n % i == 0) { n = parseInt(n / i, 10); p++; // If i^2 also divides N if (n % i == 0) return 0; } } return (p % 2 == 0)? -1 : 1; } let N = 17; document.write( "Mobius Functions" + " M(N) at N = " + N + " is: " + mobius(N) + "</br>"); document.write("Mobius Functions" + "M(N) at N = " + 25 + " is: " + mobius(25) + "</br>"); document.write( "Mobius Functions" + "M(N) at N = " + 6 + " is: " + mobius(6)); </script> Output: Mobius Functions M(N) at N = 17 is: -1 Mobius Functions M(N) at N = 25 is: 0 Mobius Functions M(N) at N = 6 is: 1 Time Complexity: O(√n) Auxiliary Space: O(1) Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above References 1) http://mathworld.wolfram.com/MobiusFunction.html 2) https://en.wikipedia.org/wiki/M%C3%B6bius_function 3) https://en.wikipedia.org/wiki/Completely_multiplicative_function nitin mittal vt_m manishshaw1 souravghosh0416 mukesh07 anikakapoor simmytarika5 codewithmini number-theory prime-factor Mathematical number-theory Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Operators in C / C++ Prime Numbers Program to find GCD or HCF of two numbers Minimum number of jumps to reach end Algorithm to solve Rubik's Cube Modulo 10^9+7 (1000000007) The Knight's tour problem | Backtracking-1 Program for Decimal to Binary Conversion Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 190, "s": 54, "text": "Mobius Function is a multiplicative function that is used in combinatorics. It has one of three possible values -1, 0 and 1.Examples: " }, { "code": null, "e": 549, "s": 190, "text": "Input : 6\nOutput : 1\nSolution: Prime Factors: 2 3.\nTherefore p = 2, (-1)^p = 1\n\nInput: 49\nOutput: 0\nSolution: Prime Factors: 7 ( occurs twice). \nSince the prime factor occurs twice answer\nis 0. \n\nInput: 3\nOutput: -1\nSolution: Prime Factors: 3. Therefore p = 1, \n(-1) ^ p =-1\n\nInput : 78\nOutput : 1\nSolution: Prime Factors: 3, 13. Therefore p = 2, \n(-1)^p = 1" }, { "code": null, "e": 995, "s": 551, "text": "Method 1 (Simple) We iterate through all numbers i smaller than or equal to N. For every number we check if it divides N. If yes, we check if it’s also prime. If both conditions are satisfied, we check if its square also divides N. If yes, we return 0. If the square doesn’t divide, we increment count of prime factors. Finally, we return 1 if there are an even number of prime factors and return -1 if there are odd number of prime factors. " }, { "code": null, "e": 999, "s": 995, "text": "C++" }, { "code": null, "e": 1004, "s": 999, "text": "Java" }, { "code": null, "e": 1012, "s": 1004, "text": "Python3" }, { "code": null, "e": 1015, "s": 1012, "text": "C#" }, { "code": null, "e": 1019, "s": 1015, "text": "PHP" }, { "code": null, "e": 1030, "s": 1019, "text": "Javascript" }, { "code": "// CPP Program to evaluate Mobius Function// M(N) = 1 if N = 1// M(N) = 0 if any prime factor of N is contained twice// M(N) = (-1)^(no of distinct prime factors)#include<iostream>using namespace std; // Function to check if n is prime or notbool isPrime(int n){ if (n < 2) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true;} int mobius(int N){ // Base Case if (N == 1) return 1; // For a prime factor i check if i^2 is also // a factor. int p = 0; for (int i = 1; i <= N; i++) { if (N % i == 0 && isPrime(i)) { // Check if N is divisible by i^2 if (N % (i * i) == 0) return 0; else // i occurs only once, increase f p++; } } // All prime factors are contained only once // Return 1 if p is even else -1 return (p % 2 != 0)? -1 : 1;} // Driver codeint main(){ int N = 17; cout << \"Mobius Functions M(N) at N = \" << N << \" is: \" << mobius(N) << endl; cout << \"Mobius Functions M(N) at N = \" << 25 << \" is: \" << mobius(25) << endl; cout << \"Mobius Functions M(N) at N = \" << 6 << \" is: \" << mobius(6) << endl;}", "e": 2284, "s": 1030, "text": null }, { "code": "// Java program for mobious functionimport java.io.*;public class GFG { // C# Program to evaluate Mobius // Function: M(N) = 1 if N = 1 // M(N) = 0 if any prime factor // of N is contained twice // M(N) = (-1)^(no of distinct // prime factors) // Function to check if n is // prime or not static boolean isPrime(int n) { if (n < 2) return false; for (int i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } static int mobius(int N) { // Base Case if (N == 1) return 1; // For a prime factor i check if // i^2 is also a factor. int p = 0; for (int i = 1; i <= N; i++) { if (N % i == 0 && isPrime(i)) { // Check if N is divisible by i^2 if (N % (i * i) == 0) return 0; else // i occurs only once, increase f p++; } } // All prime factors are contained only // once Return 1 if p is even else -1 return (p % 2 != 0) ? -1 : 1; } // Driver code static public void main(String[] args) { int N = 17; System.out.println(\"Mobius Functions M(N) at \" + \" N = \" + N + \" is: \" + mobius(N)); System.out.println(\"Mobius Functions M(N) at \" + \" N = \" + 25 + \" is: \" + mobius(25)); System.out.println(\"Mobius Functions M(N) at \" + \" N = \" + 6 + \" is: \" + mobius(6)); }} // This code is contributed by vt_m", "e": 3919, "s": 2284, "text": null }, { "code": "# Python Program to# evaluate Mobius def# M(N) = 1 if N = 1# M(N) = 0 if any# prime factor of# N is contained twice# M(N) = (-1)^(no of# distinct prime factors) # def to check if# n is prime or notdef isPrime(n) : if (n < 2) : return False for i in range(2, n + 1) : if (i * i <= n and n % i == 0) : return False return True def mobius(N) : # Base Case if (N == 1) : return 1 # For a prime factor i # check if i^2 is also # a factor. p = 0 for i in range(1, N + 1) : if (N % i == 0 and isPrime(i)) : # Check if N is # divisible by i^2 if (N % (i * i) == 0) : return 0 else : # i occurs only once, # increase f p = p + 1 # All prime factors are # contained only once # Return 1 if p is even # else -1 if(p % 2 != 0) : return -1 else : return 1 # Driver CodeN = 17print (\"Mobius defs M(N) at N = {} is: {}\" . format(N, mobius(N)),end = \"\\n\")print (\"Mobius defs M(N) at N = {} is: {}\" . format(25, mobius(25)),end = \"\\n\")print (\"Mobius defs M(N) at N = {} is: {}\" . format(6, mobius(6)),end = \"\\n\") # This code is contributed by# Manish Shaw(manishshaw1)", "e": 5261, "s": 3919, "text": null }, { "code": "// C# Program to evaluate Mobius Functionusing System; public class GFG{ // M(N) = 1 if N = 1 // M(N) = 0 if any prime factor // of N is contained twice // M(N) = (-1)^(no of distinct // prime factors) // Function to check if n is // prime or not static bool isPrime(int n) { if (n == 2) return true; if (n % 2 == 0) return false; for (int i = 3; i * i <= n / 2; i += 2) if (n % i == 0) return false; return true; } static int mobius(int N) { // Base Case if (N == 1) return 1; // For a prime factor i check // if i^2 is also a factor. int p = 0; for (int i = 2; i <= N; i++) { if (N % i == 0 && isPrime(i)) { // Check if N is divisible by i^2 if (N % (i * i) == 0) return 0; else // i occurs only once, increase f p++; } } // All prime factors are contained only // once Return 1 if p is even else -1 return (p % 2 != 0) ? -1 : 1; } // Driver code static public void Main() { Console.WriteLine(\"Mobius Functions M(N) at \" + \"N = \" + 17 + \" is: \" + mobius(17)); Console.WriteLine(\"Mobius Functions M(N) at \" + \"N = \" + 25 + \" is: \" + mobius(25)); Console.WriteLine(\"Mobius Functions M(N) at \" + \"N = \" + 6 + \" is: \" + mobius(6)); }} // This code is contributed by vt_m", "e": 6884, "s": 5261, "text": null }, { "code": "<?php// PHP Program to evaluate Mobius Function// M(N) = 1 if N = 1// M(N) = 0 if any prime factor of// N is contained twice// M(N) = (-1)^(no of distinct prime factors) // Function to check if n is prime or notfunction isPrime($n){ if ($n < 2) return false; for ($i = 2; $i * $i <= $n; $i++) if ($n % $i == 0) return false; return true;} function mobius($N){ // Base Case if ($N == 1) return 1; // For a prime factor i // check if i^2 is also // a factor. $p = 0; for ($i = 1; $i <= $N; $i++) { if ($N % $i == 0 && isPrime($i)) { // Check if N is divisible by i^2 if ($N % ($i * $i) == 0) return 0; else // i occurs only once, increase f $p++; } } // All prime factors are // contained only once // Return 1 if p is even // else -1 return ($p % 2 != 0) ? -1 : 1;} // Driver Code $N = 17; echo \"Mobius Functions M(N) at N = \" ,$N , \" is: \" , mobius($N) ,\"\\n\"; echo \"Mobius Functions M(N) at N = \" ,25, \" is: \" , mobius(25),\"\\n\" ; echo \"Mobius Functions M(N) at N = \" ,6, \" is: \" , mobius(6) ; // This code is contributed by nitin mittal.?>", "e": 8264, "s": 6884, "text": null }, { "code": "<script> // JavaScript program for mobius function // JavaScript Program to evaluate Mobius // Function: M(N) = 1 if N = 1 // M(N) = 0 if any prime factor // of N is contained twice // M(N) = (-1)^(no of distinct // prime factors) // Function to check if n is // prime or not function isPrime(n) { if (n < 2) return false; for (let i = 2; i * i <= n; i++) if (n % i == 0) return false; return true; } function mobius(N) { // Base Case if (N == 1) return 1; // For a prime factor i check if // i^2 is also a factor. let p = 0; for (let i = 1; i <= N; i++) { if (N % i == 0 && isPrime(i)) { // Check if N is divisible by i^2 if (N % (i * i) == 0) return 0; else // i occurs only once, increase f p++; } } // All prime factors are contained only // once Return 1 if p is even else -1 return (p % 2 != 0) ? -1 : 1; } // Driver code let N = 17; document.write(\"Mobius Functions M(N) at \" + \" N = \" + N + \" is: \" + mobius(N) + \"<br/>\"); document.write(\"Mobius Functions M(N) at \" + \" N = \" + 25 + \" is: \" + mobius(25) + \"<br/>\"); document.write(\"Mobius Functions M(N) at \" + \" N = \" + 6 + \" is: \" + mobius(6) + \"<br/>\"); </script>", "e": 9837, "s": 8264, "text": null }, { "code": null, "e": 9847, "s": 9837, "text": "Output: " }, { "code": null, "e": 9961, "s": 9847, "text": "Mobius Functions M(N) at N = 17 is: -1\nMobius Functions M(N) at N = 25 is: 0\nMobius Functions M(N) at N = 6 is: 1" }, { "code": null, "e": 10008, "s": 9961, "text": "Time Complexity: O(n√n ) Auxiliary Space: O(1)" }, { "code": null, "e": 10252, "s": 10008, "text": "Method 2 (Efficient) The idea is based on efficient program to print all prime factors of a given number. The interesting thing is, we do not need inner while loop here because if a number divides more than once, we can immediately return 0. " }, { "code": null, "e": 10256, "s": 10252, "text": "C++" }, { "code": null, "e": 10261, "s": 10256, "text": "Java" }, { "code": null, "e": 10269, "s": 10261, "text": "Python3" }, { "code": null, "e": 10272, "s": 10269, "text": "C#" }, { "code": null, "e": 10276, "s": 10272, "text": "PHP" }, { "code": null, "e": 10287, "s": 10276, "text": "Javascript" }, { "code": "// Program to print all prime factors# include <bits/stdc++.h>using namespace std; // Returns value of mobius()int mobius(int n){ int p = 0; // Handling 2 separately if (n%2 == 0) { n = n/2; p++; // If 2^2 also divides N if (n % 2 == 0) return 0; } // Check for all other prime factors for (int i = 3; i <= sqrt(n); i = i+2) { // If i divides n if (n%i == 0) { n = n/i; p++; // If i^2 also divides N if (n % i == 0) return 0; } } return (p % 2 == 0)? -1 : 1;} // Driver codeint main() { int N = 17; cout << \"Mobius Functions M(N) at N = \" << N << \" is: \" << mobius(N) << endl; cout << \"Mobius Functions M(N) at N = \" << 25 << \" is: \" << mobius(25) << endl; cout << \"Mobius Functions M(N) at N = \" << 6 << \" is: \" << mobius(6) << endl;}", "e": 11218, "s": 10287, "text": null }, { "code": "// Java program to print all prime factorsimport java.io.*; class GFG { // Returns value of mobius() static int mobius(int n) { int p = 0; // Handling 2 separately if (n % 2 == 0) { n = n / 2; p++; // If 2^2 also divides N if (n % 2 == 0) return 0; } // Check for all other prime factors for (int i = 3; i <= Math.sqrt(n); i = i+2) { // If i divides n if (n % i == 0) { n = n / i; p++; // If i^2 also divides N if (n % i == 0) return 0; } } return (p % 2 == 0)? -1 : 1; } // Driver code public static void main (String[] args) { int N = 17; System.out.println( \"Mobius Functions\" + \" M(N) at N = \" + N + \" is: \" + mobius(N)); System.out.println (\"Mobius Functions\" + \"M(N) at N = \" + 25 + \" is: \" + mobius(25)); System.out.println( \"Mobius Functions\" + \"M(N) at N = \" + 6 + \" is: \" + mobius(6)); }} // This code is contributed by anuj_67.", "e": 12569, "s": 11218, "text": null }, { "code": "# Python Program to evaluate# Mobius def M(N) = 1 if N = 1# M(N) = 0 if any prime factor# of N is contained twice# M(N) = (-1)^(no of distinct# prime factors)import math # def to check if n# is prime or notdef isPrime(n) : if (n < 2) : return False for i in range(2, n + 1) : if (n % i == 0) : return False i = i * i return True def mobius(n) : p = 0 # Handling 2 separately if (n % 2 == 0) : n = int(n / 2) p = p + 1 # If 2^2 also # divides N if (n % 2 == 0) : return 0 # Check for all # other prime factors for i in range(3, int(math.sqrt(n)) + 1) : # If i divides n if (n % i == 0) : n = int(n / i) p = p + 1 # If i^2 also # divides N if (n % i == 0) : return 0 i = i + 2 if(p % 2 == 0) : return -1 else : return 1 # Driver CodeN = 17print (\"Mobius defs M(N) at N = {} is: {}\\n\" . format(N, mobius(N)));print (\"Mobius defs M(N) at N = 25 is: {}\\n\" . format(mobius(25)));print (\"Mobius defs M(N) at N = 6 is: {}\\n\" . format(mobius(6))); # This code is contributed by# Manish Shaw(manishshaw1)", "e": 13931, "s": 12569, "text": null }, { "code": "// C# program to print all prime factorsusing System;class GFG { // Returns value of mobius() static int mobius(int n) { int p = 0; // Handling 2 separately if (n % 2 == 0) { n = n / 2; p++; // If 2^2 also divides N if (n % 2 == 0) return 0; } // Check for all other prime factors for (int i = 3; i <= Math.Sqrt(n); i = i+2) { // If i divides n if (n % i == 0) { n = n / i; p++; // If i^2 also divides N if (n % i == 0) return 0; } } return (p % 2 == 0)? -1 : 1; } // Driver Code public static void Main () { int N = 17; Console.WriteLine( \"Mobius Functions\" + \" M(N) at N = \" + N + \" is: \" + mobius(N)); Console.WriteLine(\"Mobius Functions\" + \"M(N) at N = \" + 25 + \" is: \" + mobius(25)); Console.WriteLine( \"Mobius Functions\" + \"M(N) at N = \" + 6 + \" is: \" + mobius(6)); }} // This code is contributed by anuj_67.", "e": 15252, "s": 13931, "text": null }, { "code": "<?php// PHP Program to print// all prime factors // Returns value of mobius()function mobius( $n){ $p = 0; // Handling 2 separately if ($n % 2 == 0) { $n = $n / 2; $p++; // If 2^2 also divides N if ($n % 2 == 0) return 0; } // Check for all // other prime factors for ( $i = 3; $i <= sqrt($n); $i = $i + 2) { // If i divides n if ($n % $i == 0) { $n = $n / $i; $p++; // If i^2 also divides N if ($n % $i == 0) return 0; } } return ($p % 2 == 0)? -1 : 1;} // Driver code $N = 17; echo \"Mobius Functions M(N) at N = \", $N, \" is: \" , mobius($N),\"\\n\" ; echo \"Mobius Functions M(N) at N = \" , 25 , \" is: \" , mobius(25),\"\\n\"; echo \"Mobius Functions M(N) at N = \" , 6 , \" is: \" , mobius(6) ; // This code is contributed by anuj_67.?>", "e": 16181, "s": 15252, "text": null }, { "code": "<script> // JavaScript program to print all prime factors // Returns value of mobius() function mobius(n) { let p = 0; // Handling 2 separately if (n % 2 == 0) { n = parseInt(n / 2, 10); p++; // If 2^2 also divides N if (n % 2 == 0) return 0; } // Check for all other prime factors for (let i = 3; i <= Math.sqrt(n); i = i+2) { // If i divides n if (n % i == 0) { n = parseInt(n / i, 10); p++; // If i^2 also divides N if (n % i == 0) return 0; } } return (p % 2 == 0)? -1 : 1; } let N = 17; document.write( \"Mobius Functions\" + \" M(N) at N = \" + N + \" is: \" + mobius(N) + \"</br>\"); document.write(\"Mobius Functions\" + \"M(N) at N = \" + 25 + \" is: \" + mobius(25) + \"</br>\"); document.write( \"Mobius Functions\" + \"M(N) at N = \" + 6 + \" is: \" + mobius(6)); </script>", "e": 17395, "s": 16181, "text": null }, { "code": null, "e": 17404, "s": 17395, "text": "Output: " }, { "code": null, "e": 17518, "s": 17404, "text": "Mobius Functions M(N) at N = 17 is: -1\nMobius Functions M(N) at N = 25 is: 0\nMobius Functions M(N) at N = 6 is: 1" }, { "code": null, "e": 17563, "s": 17518, "text": "Time Complexity: O(√n) Auxiliary Space: O(1)" }, { "code": null, "e": 17830, "s": 17563, "text": "Please suggest if someone has a better solution which is more efficient in terms of space and time.This article is contributed by Aarti_Rathi. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 18016, "s": 17830, "text": "References 1) http://mathworld.wolfram.com/MobiusFunction.html 2) https://en.wikipedia.org/wiki/M%C3%B6bius_function 3) https://en.wikipedia.org/wiki/Completely_multiplicative_function " }, { "code": null, "e": 18029, "s": 18016, "text": "nitin mittal" }, { "code": null, "e": 18034, "s": 18029, "text": "vt_m" }, { "code": null, "e": 18046, "s": 18034, "text": "manishshaw1" }, { "code": null, "e": 18062, "s": 18046, "text": "souravghosh0416" }, { "code": null, "e": 18071, "s": 18062, "text": "mukesh07" }, { "code": null, "e": 18083, "s": 18071, "text": "anikakapoor" }, { "code": null, "e": 18096, "s": 18083, "text": "simmytarika5" }, { "code": null, "e": 18109, "s": 18096, "text": "codewithmini" }, { "code": null, "e": 18123, "s": 18109, "text": "number-theory" }, { "code": null, "e": 18136, "s": 18123, "text": "prime-factor" }, { "code": null, "e": 18149, "s": 18136, "text": "Mathematical" }, { "code": null, "e": 18163, "s": 18149, "text": "number-theory" }, { "code": null, "e": 18176, "s": 18163, "text": "Mathematical" }, { "code": null, "e": 18274, "s": 18176, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 18298, "s": 18274, "text": "Merge two sorted arrays" }, { "code": null, "e": 18319, "s": 18298, "text": "Operators in C / C++" }, { "code": null, "e": 18333, "s": 18319, "text": "Prime Numbers" }, { "code": null, "e": 18375, "s": 18333, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 18412, "s": 18375, "text": "Minimum number of jumps to reach end" }, { "code": null, "e": 18444, "s": 18412, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 18471, "s": 18444, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 18514, "s": 18471, "text": "The Knight's tour problem | Backtracking-1" }, { "code": null, "e": 18555, "s": 18514, "text": "Program for Decimal to Binary Conversion" } ]
Minimum cost of reducing Array by merging any adjacent elements repetitively
14 Jun, 2021 Given an array arr[] of N numbers. We can merge two adjacent numbers into one and the cost of merging the two numbers is equal to the sum of the two values. The task is to find the total minimum cost of merging all the numbers.Examples: Input: arr[] = { 6, 4, 4, 6 } Output: 40 Explanation: Following is the optimal way of merging numbers to get the total minimum cost of merging of numbers: 1. Merge (6, 4), then array becomes, arr[] = {10, 4, 6} and cost = 10 2. Merge (4, 6), then array becomes, arr[] = {10, 10} and cost = 10 3. Merge (10, 10), then array becomes, arr[] = {20} and cost = 20 Hence the total cost is 10 + 10 + 20 = 40.Input: arr[] = { 3, 2, 4, 1 } Output: 20 Explanation: Following is the optimal way of merging numbers to get the total minimum cost of merging of numbers: 1. Merge (3, 2), then array becomes, arr[] = {5, 4, 1} and cost = 5 2. Merge (4, 1), then array becomes, arr[] = {5, 5} and cost = 5 3. Merge (5, 5), then array becomes, arr[] = {10} and cost = 10 Hence the total cost is 5 + 5 + 10 = 20. Approach: The problem can be solved using Dynamic Programming. Below are the steps: The idea is to merge 2 consecutive numbers into every possible index i and then solve recursively for left and right parts of index i.Add the result of merging two numbers in above steps and store the minimum of them.Since there are many subproblems that are repeating, hence we use memoization to store the values in a NxN matrix.The recurrence relation for the above problem statement is given as: The idea is to merge 2 consecutive numbers into every possible index i and then solve recursively for left and right parts of index i. Add the result of merging two numbers in above steps and store the minimum of them. Since there are many subproblems that are repeating, hence we use memoization to store the values in a NxN matrix. The recurrence relation for the above problem statement is given as: dp[i][j] = min(dp[i][j], (sum[i][j] + dp[i][k] + dp[k + 1][j])), for every (i ≤ k lt; j) 5. Now dp[1][N] will give the minimum total cost of merging all the numbers. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the total minimum// cost of merging two consecutive numbersint mergeTwoNumbers(vector<int>& numbers){ int len, i, j, k; // Find the size of numbers[] int n = numbers.size(); // If array is empty, return 0 if (numbers.size() == 0) { return 0; } // To store the prefix Sum of // numbers array numbers[] vector<int> prefixSum(n + 1, 0); // Traverse numbers[] to find the // prefix sum for (int i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + numbers[i - 1]; } // dp table to memoised the value vector<vector<int> > dp( n + 1, vector<int>(n + 1)); // For single numbers cost is zero for (int i = 1; i <= n; i++) { dp[i][i] = 0; } // Iterate for length >= 1 for (len = 2; len <= n; len++) { for (i = 1; i <= n - len + 1; i++) { j = i + len - 1; // Find sum in range [i..j] int sum = prefixSum[j] - prefixSum[i - 1]; // Initialise dp[i][j] to INT_MAX dp[i][j] = INT_MAX; // Iterate for all possible // K to find the minimum cost for (k = i; k < j; k++) { // Update the minimum sum dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum); } } } // Return the final minimum cost return dp[1][n];} // Driver Codeint main(){ // Given set of numbers vector<int> arr1 = { 6, 4, 4, 6 }; // Function Call cout << mergeTwoNumbers(arr1) << endl; return 0;} // Java program for the above approachimport java.util.*;class GFG{ // Function to find the total minimum// cost of merging two consecutive numbersstatic int mergeTwoNumbers(int []numbers){ int len, i, j, k; // Find the size of numbers[] int n = numbers.length; // If array is empty, return 0 if (numbers.length == 0) { return 0; } // To store the prefix Sum of // numbers array numbers[] int []prefixSum = new int[n + 1]; // Traverse numbers[] to find the // prefix sum for (i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + numbers[i - 1]; } // dp table to memoised the value int [][]dp = new int[n + 1][n + 1]; // Iterate for length >= 1 for (len = 2; len <= n; len++) { for (i = 1; i <= n - len + 1; i++) { j = i + len - 1; // Find sum in range [i..j] int sum = prefixSum[j] - prefixSum[i - 1]; // Initialise dp[i][j] to Integer.MAX_VALUE dp[i][j] = Integer.MAX_VALUE; // Iterate for all possible // K to find the minimum cost for (k = i; k < j; k++) { // Update the minimum sum dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum); } } } // Return the final minimum cost return dp[1][n];} // Driver Codepublic static void main(String[] args){ // Given set of numbers int []arr1 = { 6, 4, 4, 6 }; // Function Call System.out.print(mergeTwoNumbers(arr1) + "\n");}} // This code is contributed by sapnasingh4991 # Python3 program for the above approachimport sys # Function to find the total minimum# cost of merging two consecutive numbersdef mergeTwoNumbers(numbers): # Find the size of numbers[] n = len(numbers) # If array is empty, return 0 if (len(numbers) == 0): return 0 # To store the prefix Sum of # numbers array numbers[] prefixSum = [0] * (n + 1) # Traverse numbers[] to find the # prefix sum for i in range(1, n + 1): prefixSum[i] = (prefixSum[i - 1] + numbers[i - 1]) # dp table to memoised the value dp = [[0 for i in range(n + 1)] for j in range(n + 1)] # For single numbers cost is zero for i in range(1, n + 1): dp[i][i] = 0 # Iterate for length >= 1 for p in range(2, n + 1): for i in range(1, n - p + 2): j = i + p - 1 # Find sum in range [i..j] sum = prefixSum[j] - prefixSum[i - 1] # Initialise dp[i][j] to _MAX dp[i][j] = sys.maxsize # Iterate for all possible # K to find the minimum cost for k in range(i, j): # Update the minimum sum dp[i][j] = min(dp[i][j], (dp[i][k] + dp[k + 1][j] + sum)) # Return the final minimum cost return dp[1][n] # Driver Code # Given set of numbersarr1 = [ 6, 4, 4, 6 ] # Function callprint(mergeTwoNumbers(arr1)) # This code is contributed by sanjoy_62 // C# program for the above approachusing System;class GFG{ // Function to find the total minimum// cost of merging two consecutive numbersstatic int mergeTwoNumbers(int []numbers){ int len, i, j, k; // Find the size of numbers[] int n = numbers.Length; // If array is empty, return 0 if (numbers.Length == 0) { return 0; } // To store the prefix Sum of // numbers array numbers[] int []prefixSum = new int[n + 1]; // Traverse numbers[] to find the // prefix sum for (i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + numbers[i - 1]; } // dp table to memoised the value int [,]dp = new int[n + 1, n + 1]; // Iterate for length >= 1 for (len = 2; len <= n; len++) { for (i = 1; i <= n - len + 1; i++) { j = i + len - 1; // Find sum in range [i..j] int sum = prefixSum[j] - prefixSum[i - 1]; // Initialise dp[i,j] to int.MaxValue dp[i,j] = int.MaxValue; // Iterate for all possible // K to find the minimum cost for (k = i; k < j; k++) { // Update the minimum sum dp[i, j] = Math.Min(dp[i, j], dp[i, k] + dp[k + 1, j] + sum); } } } // Return the readonly minimum cost return dp[1, n];} // Driver Codepublic static void Main(String[] args){ // Given set of numbers int []arr1 = { 6, 4, 4, 6 }; // Function Call Console.Write(mergeTwoNumbers(arr1) + "\n");}} // This code is contributed by sapnasingh4991 <script> // JavaScript program for the above approach // Function to find the total minimum// cost of merging two consecutive numbersfunction mergeTwoNumbers(numbers){ var len, i, j, k; // Find the size of numbers[] var n = numbers.length; // If array is empty, return 0 if (numbers.length == 0) { return 0; } // To store the prefix Sum of // numbers array numbers[] var prefixSum = Array(n+1).fill(0); // Traverse numbers[] to find the // prefix sum for (var i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + numbers[i - 1]; } // dp table to memoised the value var dp = Array.from(Array(n+1), ()=>Array(n+1)); // For single numbers cost is zero for (var i = 1; i <= n; i++) { dp[i][i] = 0; } // Iterate for length >= 1 for (len = 2; len <= n; len++) { for (i = 1; i <= n - len + 1; i++) { j = i + len - 1; // Find sum in range [i..j] var sum = prefixSum[j] - prefixSum[i - 1]; // Initialise dp[i][j] to INT_MAX dp[i][j] = 1000000000; // Iterate for all possible // K to find the minimum cost for (k = i; k < j; k++) { // Update the minimum sum dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum); } } } // Return the final minimum cost return dp[1][n];} // Driver Code // Given set of numbersvar arr1 = [6, 4, 4, 6]; // Function Calldocument.write( mergeTwoNumbers(arr1)) </script> 40 Time Complexity: O(N3) Auxiliary Space Complexity: O(N2) sapnasingh4991 sanjoy_62 itsok Amazon Advanced Data Structure Arrays Competitive Programming Divide and Conquer Dynamic Programming Recursion Amazon Arrays Dynamic Programming Recursion Divide and Conquer Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n14 Jun, 2021" }, { "code": null, "e": 291, "s": 52, "text": "Given an array arr[] of N numbers. We can merge two adjacent numbers into one and the cost of merging the two numbers is equal to the sum of the two values. The task is to find the total minimum cost of merging all the numbers.Examples: " }, { "code": null, "e": 1085, "s": 291, "text": "Input: arr[] = { 6, 4, 4, 6 } Output: 40 Explanation: Following is the optimal way of merging numbers to get the total minimum cost of merging of numbers: 1. Merge (6, 4), then array becomes, arr[] = {10, 4, 6} and cost = 10 2. Merge (4, 6), then array becomes, arr[] = {10, 10} and cost = 10 3. Merge (10, 10), then array becomes, arr[] = {20} and cost = 20 Hence the total cost is 10 + 10 + 20 = 40.Input: arr[] = { 3, 2, 4, 1 } Output: 20 Explanation: Following is the optimal way of merging numbers to get the total minimum cost of merging of numbers: 1. Merge (3, 2), then array becomes, arr[] = {5, 4, 1} and cost = 5 2. Merge (4, 1), then array becomes, arr[] = {5, 5} and cost = 5 3. Merge (5, 5), then array becomes, arr[] = {10} and cost = 10 Hence the total cost is 5 + 5 + 10 = 20." }, { "code": null, "e": 1171, "s": 1085, "text": "Approach: The problem can be solved using Dynamic Programming. Below are the steps: " }, { "code": null, "e": 1573, "s": 1171, "text": "The idea is to merge 2 consecutive numbers into every possible index i and then solve recursively for left and right parts of index i.Add the result of merging two numbers in above steps and store the minimum of them.Since there are many subproblems that are repeating, hence we use memoization to store the values in a NxN matrix.The recurrence relation for the above problem statement is given as: " }, { "code": null, "e": 1708, "s": 1573, "text": "The idea is to merge 2 consecutive numbers into every possible index i and then solve recursively for left and right parts of index i." }, { "code": null, "e": 1792, "s": 1708, "text": "Add the result of merging two numbers in above steps and store the minimum of them." }, { "code": null, "e": 1907, "s": 1792, "text": "Since there are many subproblems that are repeating, hence we use memoization to store the values in a NxN matrix." }, { "code": null, "e": 1978, "s": 1907, "text": "The recurrence relation for the above problem statement is given as: " }, { "code": null, "e": 2068, "s": 1978, "text": "dp[i][j] = min(dp[i][j], (sum[i][j] + dp[i][k] + dp[k + 1][j])), for every (i ≤ k lt; j) " }, { "code": null, "e": 2151, "s": 2068, "text": " 5. Now dp[1][N] will give the minimum total cost of merging all the numbers." }, { "code": null, "e": 2203, "s": 2151, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 2207, "s": 2203, "text": "C++" }, { "code": null, "e": 2212, "s": 2207, "text": "Java" }, { "code": null, "e": 2220, "s": 2212, "text": "Python3" }, { "code": null, "e": 2223, "s": 2220, "text": "C#" }, { "code": null, "e": 2234, "s": 2223, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the total minimum// cost of merging two consecutive numbersint mergeTwoNumbers(vector<int>& numbers){ int len, i, j, k; // Find the size of numbers[] int n = numbers.size(); // If array is empty, return 0 if (numbers.size() == 0) { return 0; } // To store the prefix Sum of // numbers array numbers[] vector<int> prefixSum(n + 1, 0); // Traverse numbers[] to find the // prefix sum for (int i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + numbers[i - 1]; } // dp table to memoised the value vector<vector<int> > dp( n + 1, vector<int>(n + 1)); // For single numbers cost is zero for (int i = 1; i <= n; i++) { dp[i][i] = 0; } // Iterate for length >= 1 for (len = 2; len <= n; len++) { for (i = 1; i <= n - len + 1; i++) { j = i + len - 1; // Find sum in range [i..j] int sum = prefixSum[j] - prefixSum[i - 1]; // Initialise dp[i][j] to INT_MAX dp[i][j] = INT_MAX; // Iterate for all possible // K to find the minimum cost for (k = i; k < j; k++) { // Update the minimum sum dp[i][j] = min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum); } } } // Return the final minimum cost return dp[1][n];} // Driver Codeint main(){ // Given set of numbers vector<int> arr1 = { 6, 4, 4, 6 }; // Function Call cout << mergeTwoNumbers(arr1) << endl; return 0;}", "e": 4014, "s": 2234, "text": null }, { "code": "// Java program for the above approachimport java.util.*;class GFG{ // Function to find the total minimum// cost of merging two consecutive numbersstatic int mergeTwoNumbers(int []numbers){ int len, i, j, k; // Find the size of numbers[] int n = numbers.length; // If array is empty, return 0 if (numbers.length == 0) { return 0; } // To store the prefix Sum of // numbers array numbers[] int []prefixSum = new int[n + 1]; // Traverse numbers[] to find the // prefix sum for (i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + numbers[i - 1]; } // dp table to memoised the value int [][]dp = new int[n + 1][n + 1]; // Iterate for length >= 1 for (len = 2; len <= n; len++) { for (i = 1; i <= n - len + 1; i++) { j = i + len - 1; // Find sum in range [i..j] int sum = prefixSum[j] - prefixSum[i - 1]; // Initialise dp[i][j] to Integer.MAX_VALUE dp[i][j] = Integer.MAX_VALUE; // Iterate for all possible // K to find the minimum cost for (k = i; k < j; k++) { // Update the minimum sum dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum); } } } // Return the final minimum cost return dp[1][n];} // Driver Codepublic static void main(String[] args){ // Given set of numbers int []arr1 = { 6, 4, 4, 6 }; // Function Call System.out.print(mergeTwoNumbers(arr1) + \"\\n\");}} // This code is contributed by sapnasingh4991", "e": 5761, "s": 4014, "text": null }, { "code": "# Python3 program for the above approachimport sys # Function to find the total minimum# cost of merging two consecutive numbersdef mergeTwoNumbers(numbers): # Find the size of numbers[] n = len(numbers) # If array is empty, return 0 if (len(numbers) == 0): return 0 # To store the prefix Sum of # numbers array numbers[] prefixSum = [0] * (n + 1) # Traverse numbers[] to find the # prefix sum for i in range(1, n + 1): prefixSum[i] = (prefixSum[i - 1] + numbers[i - 1]) # dp table to memoised the value dp = [[0 for i in range(n + 1)] for j in range(n + 1)] # For single numbers cost is zero for i in range(1, n + 1): dp[i][i] = 0 # Iterate for length >= 1 for p in range(2, n + 1): for i in range(1, n - p + 2): j = i + p - 1 # Find sum in range [i..j] sum = prefixSum[j] - prefixSum[i - 1] # Initialise dp[i][j] to _MAX dp[i][j] = sys.maxsize # Iterate for all possible # K to find the minimum cost for k in range(i, j): # Update the minimum sum dp[i][j] = min(dp[i][j], (dp[i][k] + dp[k + 1][j] + sum)) # Return the final minimum cost return dp[1][n] # Driver Code # Given set of numbersarr1 = [ 6, 4, 4, 6 ] # Function callprint(mergeTwoNumbers(arr1)) # This code is contributed by sanjoy_62", "e": 7290, "s": 5761, "text": null }, { "code": "// C# program for the above approachusing System;class GFG{ // Function to find the total minimum// cost of merging two consecutive numbersstatic int mergeTwoNumbers(int []numbers){ int len, i, j, k; // Find the size of numbers[] int n = numbers.Length; // If array is empty, return 0 if (numbers.Length == 0) { return 0; } // To store the prefix Sum of // numbers array numbers[] int []prefixSum = new int[n + 1]; // Traverse numbers[] to find the // prefix sum for (i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + numbers[i - 1]; } // dp table to memoised the value int [,]dp = new int[n + 1, n + 1]; // Iterate for length >= 1 for (len = 2; len <= n; len++) { for (i = 1; i <= n - len + 1; i++) { j = i + len - 1; // Find sum in range [i..j] int sum = prefixSum[j] - prefixSum[i - 1]; // Initialise dp[i,j] to int.MaxValue dp[i,j] = int.MaxValue; // Iterate for all possible // K to find the minimum cost for (k = i; k < j; k++) { // Update the minimum sum dp[i, j] = Math.Min(dp[i, j], dp[i, k] + dp[k + 1, j] + sum); } } } // Return the readonly minimum cost return dp[1, n];} // Driver Codepublic static void Main(String[] args){ // Given set of numbers int []arr1 = { 6, 4, 4, 6 }; // Function Call Console.Write(mergeTwoNumbers(arr1) + \"\\n\");}} // This code is contributed by sapnasingh4991", "e": 9016, "s": 7290, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the total minimum// cost of merging two consecutive numbersfunction mergeTwoNumbers(numbers){ var len, i, j, k; // Find the size of numbers[] var n = numbers.length; // If array is empty, return 0 if (numbers.length == 0) { return 0; } // To store the prefix Sum of // numbers array numbers[] var prefixSum = Array(n+1).fill(0); // Traverse numbers[] to find the // prefix sum for (var i = 1; i <= n; i++) { prefixSum[i] = prefixSum[i - 1] + numbers[i - 1]; } // dp table to memoised the value var dp = Array.from(Array(n+1), ()=>Array(n+1)); // For single numbers cost is zero for (var i = 1; i <= n; i++) { dp[i][i] = 0; } // Iterate for length >= 1 for (len = 2; len <= n; len++) { for (i = 1; i <= n - len + 1; i++) { j = i + len - 1; // Find sum in range [i..j] var sum = prefixSum[j] - prefixSum[i - 1]; // Initialise dp[i][j] to INT_MAX dp[i][j] = 1000000000; // Iterate for all possible // K to find the minimum cost for (k = i; k < j; k++) { // Update the minimum sum dp[i][j] = Math.min(dp[i][j], dp[i][k] + dp[k + 1][j] + sum); } } } // Return the final minimum cost return dp[1][n];} // Driver Code // Given set of numbersvar arr1 = [6, 4, 4, 6]; // Function Calldocument.write( mergeTwoNumbers(arr1)) </script>", "e": 10706, "s": 9016, "text": null }, { "code": null, "e": 10712, "s": 10709, "text": "40" }, { "code": null, "e": 10774, "s": 10716, "text": "Time Complexity: O(N3) Auxiliary Space Complexity: O(N2) " }, { "code": null, "e": 10791, "s": 10776, "text": "sapnasingh4991" }, { "code": null, "e": 10801, "s": 10791, "text": "sanjoy_62" }, { "code": null, "e": 10807, "s": 10801, "text": "itsok" }, { "code": null, "e": 10814, "s": 10807, "text": "Amazon" }, { "code": null, "e": 10838, "s": 10814, "text": "Advanced Data Structure" }, { "code": null, "e": 10845, "s": 10838, "text": "Arrays" }, { "code": null, "e": 10869, "s": 10845, "text": "Competitive Programming" }, { "code": null, "e": 10888, "s": 10869, "text": "Divide and Conquer" }, { "code": null, "e": 10908, "s": 10888, "text": "Dynamic Programming" }, { "code": null, "e": 10918, "s": 10908, "text": "Recursion" }, { "code": null, "e": 10925, "s": 10918, "text": "Amazon" }, { "code": null, "e": 10932, "s": 10925, "text": "Arrays" }, { "code": null, "e": 10952, "s": 10932, "text": "Dynamic Programming" }, { "code": null, "e": 10962, "s": 10952, "text": "Recursion" }, { "code": null, "e": 10981, "s": 10962, "text": "Divide and Conquer" } ]
How to add custom filter in search Box in ReactJS?
09 Sep, 2021 The custom filter means adding our own business login to filter the options shown in searchbox or any dropdown menu. Material UI for React has this component available for us and it is very easy to integrate. We can create our own custom filter for options in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command: npm install @material-ui/core npm install @material-ui/lab Project Structure: It will look like the following. Project Structure App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from 'react'import TextField from '@material-ui/core/TextField';import Autocomplete, { createFilterOptions } from '@material-ui/lab/Autocomplete'; const App = () => { const filterOptions = createFilterOptions({ matchFrom: 'start', stringify: option => option, }); // Sample options for search box const myOptions = ['One Number', 'Two Number', 'Five Number', 'This is a sample text', 'Dummy text', 'Dropdown option teet', 'Hello text', 'Welcome to text field']; return ( <div style={{ marginLeft: '40%', marginTop: '60px' }}> <h3>Greetings from GeeksforGeeks!</h3> <Autocomplete style={{ width: 500 }} freeSolo filterOptions={filterOptions} options={myOptions} renderInput={(params) => ( <TextField {...params} variant="outlined" label="Search Box" /> )} /> </div> );} export default App Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: The following would have been the output without adding our custom filter function: sweetyty JavaScript ReactJS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n09 Sep, 2021" }, { "code": null, "e": 350, "s": 52, "text": "The custom filter means adding our own business login to filter the options shown in searchbox or any dropdown menu. Material UI for React has this component available for us and it is very easy to integrate. We can create our own custom filter for options in ReactJS using the following approach." }, { "code": null, "e": 400, "s": 350, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 464, "s": 400, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 496, "s": 464, "text": "npx create-react-app foldername" }, { "code": null, "e": 596, "s": 496, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 610, "s": 596, "text": "cd foldername" }, { "code": null, "e": 719, "s": 610, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 778, "s": 719, "text": "npm install @material-ui/core\nnpm install @material-ui/lab" }, { "code": null, "e": 830, "s": 778, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 848, "s": 830, "text": "Project Structure" }, { "code": null, "e": 977, "s": 848, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 988, "s": 977, "text": "Javascript" }, { "code": "import React from 'react'import TextField from '@material-ui/core/TextField';import Autocomplete, { createFilterOptions } from '@material-ui/lab/Autocomplete'; const App = () => { const filterOptions = createFilterOptions({ matchFrom: 'start', stringify: option => option, }); // Sample options for search box const myOptions = ['One Number', 'Two Number', 'Five Number', 'This is a sample text', 'Dummy text', 'Dropdown option teet', 'Hello text', 'Welcome to text field']; return ( <div style={{ marginLeft: '40%', marginTop: '60px' }}> <h3>Greetings from GeeksforGeeks!</h3> <Autocomplete style={{ width: 500 }} freeSolo filterOptions={filterOptions} options={myOptions} renderInput={(params) => ( <TextField {...params} variant=\"outlined\" label=\"Search Box\" /> )} /> </div> );} export default App", "e": 1913, "s": 988, "text": null }, { "code": null, "e": 2028, "s": 1913, "text": " Step to Run Application: Run the application using the following command from the root directory of the project: " }, { "code": null, "e": 2038, "s": 2028, "text": "npm start" }, { "code": null, "e": 2137, "s": 2038, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 2221, "s": 2137, "text": "The following would have been the output without adding our custom filter function:" }, { "code": null, "e": 2232, "s": 2223, "text": "sweetyty" }, { "code": null, "e": 2243, "s": 2232, "text": "JavaScript" }, { "code": null, "e": 2251, "s": 2243, "text": "ReactJS" }, { "code": null, "e": 2270, "s": 2251, "text": "Technical Scripter" }, { "code": null, "e": 2287, "s": 2270, "text": "Web Technologies" } ]
Smallest subarray with sum greater than a given value
23 Jun, 2022 Given an array of integers and a number x, find the smallest subarray with sum greater than the given value. Examples: arr[] = {1, 4, 45, 6, 0, 19} x = 51 Output: 3 Minimum length subarray is {4, 45, 6} arr[] = {1, 10, 5, 2, 7} x = 9 Output: 1 Minimum length subarray is {10} arr[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250} x = 280 Output: 4 Minimum length subarray is {100, 1, 0, 200} arr[] = {1, 2, 4} x = 8 Output : Not Possible Whole array sum is smaller than 8. A simple solution is to use two nested loops. The outer loop picks a starting element, the inner loop considers all elements (on right side of current start) as ending element. Whenever sum of elements between current start and end becomes more than the given number, update the result if current length is smaller than the smallest length so far. Following is the implementation of simple approach. C++ Java Python3 C# PHP Javascript # include <iostream>using namespace std; // Returns length of smallest subarray with sum greater than x.// If there is no subarray with given sum, then returns n+1int smallestSubWithSum(int arr[], int n, int x){ // Initialize length of smallest subarray as n+1 int min_len = n + 1; // Pick every element as starting point for (int start=0; start<n; start++) { // Initialize sum starting with current start int curr_sum = arr[start]; // If first element itself is greater if (curr_sum > x) return 1; // Try different ending points for current start for (int end=start+1; end<n; end++) { // add last element to current sum curr_sum += arr[end]; // If sum becomes more than x and length of // this subarray is smaller than current smallest // length, update the smallest length (or result) if (curr_sum > x && (end - start + 1) < min_len) min_len = (end - start + 1); } } return min_len;} /* Driver program to test above function */int main(){ int arr1[] = {1, 4, 45, 6, 10, 19}; int x = 51; int n1 = sizeof(arr1)/sizeof(arr1[0]); int res1 = smallestSubWithSum(arr1, n1, x); (res1 == n1+1)? cout << "Not possible\n" : cout << res1 << endl; int arr2[] = {1, 10, 5, 2, 7}; int n2 = sizeof(arr2)/sizeof(arr2[0]); x = 9; int res2 = smallestSubWithSum(arr2, n2, x); (res2 == n2+1)? cout << "Not possible\n" : cout << res2 << endl; int arr3[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250}; int n3 = sizeof(arr3)/sizeof(arr3[0]); x = 280; int res3 = smallestSubWithSum(arr3, n3, x); (res3 == n3+1)? cout << "Not possible\n" : cout << res3 << endl; return 0;} class SmallestSubArraySum{ // Returns length of smallest subarray with sum greater than x. // If there is no subarray with given sum, then returns n+1 static int smallestSubWithSum(int arr[], int n, int x) { // Initialize length of smallest subarray as n+1 int min_len = n + 1; // Pick every element as starting point for (int start = 0; start < n; start++) { // Initialize sum starting with current start int curr_sum = arr[start]; // If first element itself is greater if (curr_sum > x) return 1; // Try different ending points for curremt start for (int end = start + 1; end < n; end++) { // add last element to current sum curr_sum += arr[end]; // If sum becomes more than x and length of // this subarray is smaller than current smallest // length, update the smallest length (or result) if (curr_sum > x && (end - start + 1) < min_len) min_len = (end - start + 1); } } return min_len; } // Driver program to test above functions public static void main(String[] args) { int arr1[] = {1, 4, 45, 6, 10, 19}; int x = 51; int n1 = arr1.length; int res1 = smallestSubWithSum(arr1, n1, x); if (res1 == n1+1) System.out.println("Not Possible"); else System.out.println(res1); int arr2[] = {1, 10, 5, 2, 7}; int n2 = arr2.length; x = 9; int res2 = smallestSubWithSum(arr2, n2, x); if (res2 == n2+1) System.out.println("Not Possible"); else System.out.println(res2); int arr3[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250}; int n3 = arr3.length; x = 280; int res3 = smallestSubWithSum(arr3, n3, x); if (res3 == n3+1) System.out.println("Not Possible"); else System.out.println(res3); }} // This code has been contributed by Mayank Jaiswal # Python3 program to find Smallest# subarray with sum greater# than a given value # Returns length of smallest subarray# with sum greater than x. If there# is no subarray with given sum,# then returns n+1def smallestSubWithSum(arr, n, x): # Initialize length of smallest # subarray as n+1 min_len = n + 1 # Pick every element as starting point for start in range(0,n): # Initialize sum starting # with current start curr_sum = arr[start] # If first element itself is greater if (curr_sum > x): return 1 # Try different ending points # for curremt start for end in range(start+1,n): # add last element to current sum curr_sum += arr[end] # If sum becomes more than x # and length of this subarray # is smaller than current smallest # length, update the smallest # length (or result) if curr_sum > x and (end - start + 1) < min_len: min_len = (end - start + 1) return min_len; # Driver program to test above function */arr1 = [1, 4, 45, 6, 10, 19]x = 51n1 = len(arr1)res1 = smallestSubWithSum(arr1, n1, x);if res1 == n1+1: print("Not possible")else: print(res1) arr2 = [1, 10, 5, 2, 7]n2 = len(arr2)x = 9res2 = smallestSubWithSum(arr2, n2, x);if res2 == n2+1: print("Not possible")else: print(res2) arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]n3 = len(arr3)x = 280res3 = smallestSubWithSum(arr3, n3, x)if res3 == n3+1: print("Not possible")else: print(res3) # This code is contributed by Smitha Dinesh Semwal // C# program to find Smallest// subarray with sum greater// than a given valueusing System; class GFG{ // Returns length of smallest // subarray with sum greater // than x. If there is no // subarray with given sum, // then returns n+1 static int smallestSubWithSum(int []arr, int n, int x) { // Initialize length of // smallest subarray as n+1 int min_len = n + 1; // Pick every element // as starting point for (int start = 0; start < n; start++) { // Initialize sum starting // with current start int curr_sum = arr[start]; // If first element // itself is greater if (curr_sum > x) return 1; // Try different ending // points for curremt start for (int end = start + 1; end < n; end++) { // add last element // to current sum curr_sum += arr[end]; // If sum becomes more than // x and length of this // subarray is smaller than // current smallest length, // update the smallest // length (or result) if (curr_sum > x && (end - start + 1) < min_len) min_len = (end - start + 1); } } return min_len; } // Driver Code static public void Main () { int []arr1 = {1, 4, 45, 6, 10, 19}; int x = 51; int n1 = arr1.Length; int res1 = smallestSubWithSum(arr1, n1, x); if (res1 == n1 + 1) Console.WriteLine("Not Possible"); else Console.WriteLine(res1); int []arr2 = {1, 10, 5, 2, 7}; int n2 = arr2.Length; x = 9; int res2 = smallestSubWithSum(arr2, n2, x); if (res2 == n2 + 1) Console.WriteLine("Not Possible"); else Console.WriteLine(res2); int []arr3 = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250}; int n3 = arr3.Length; x = 280; int res3 = smallestSubWithSum(arr3, n3, x); if (res3 == n3 + 1) Console.WriteLine("Not Possible"); else Console.WriteLine(res3); }} // This code is contributed by ajit <?php// Returns length of smallest// subarray with sum greater// than x. If there is no// subarray with given sum,// then returns n+1function smallestSubWithSum($arr, $n, $x){ // Initialize length of // smallest subarray as n+1 $min_len = $n + 1; // Pick every element // as starting point for ($start = 0; $start < $n; $start++) { // Initialize sum starting // with current start $curr_sum = $arr[$start]; // If first element // itself is greater if ($curr_sum > $x) return 1; // Try different ending // points for curremt start for ($end= $start + 1; $end < $n; $end++) { // add last element // to current sum $curr_sum += $arr[$end]; // If sum becomes more than // x and length of this subarray // is smaller than current // smallest length, update the // smallest length (or result) if ($curr_sum > $x && ($end - $start + 1) < $min_len) $min_len = ($end - $start + 1); } } return $min_len;} // Driver Code$arr1 = array (1, 4, 45, 6, 10, 19);$x = 51;$n1 = sizeof($arr1);$res1 = smallestSubWithSum($arr1, $n1, $x); if (($res1 == $n1 + 1) == true) echo "Not possible\n" ;else echo $res1 , "\n"; $arr2 = array(1, 10, 5, 2, 7);$n2 = sizeof($arr2);$x = 9;$res2 = smallestSubWithSum($arr2, $n2, $x); if (($res2 == $n2 + 1) == true) echo "Not possible\n" ;else echo $res2 , "\n"; $arr3 = array (1, 11, 100, 1, 0, 200, 3, 2, 1, 250);$n3 = sizeof($arr3);$x = 280;$res3 = smallestSubWithSum($arr3, $n3, $x);if (($res3 == $n3 + 1) == true) echo "Not possible\n" ;else echo $res3 , "\n"; // This code is contributed by ajit?> <script> // Returns length of smallest subarray with sum greater than x.// If there is no subarray with given sum, then returns n+1function smallestSubWithSum(arr, n, x){ // Initialize length of smallest subarray as n+1 let min_len = n + 1; // Pick every element as starting point for (let start=0; start<n; start++) { // Initialize sum starting with current start let curr_sum = arr[start]; // If first element itself is greater if (curr_sum > x) return 1; // Try different ending points for curremt start for (let end=start+1; end<n; end++) { // add last element to current sum curr_sum += arr[end]; // If sum becomes more than x and length of // this subarray is smaller than current smallest // length, update the smallest length (or result) if (curr_sum > x && (end - start + 1) < min_len) min_len = (end - start + 1); } } return min_len;} /* Driver program to test above function */ let arr1 = [1, 4, 45, 6, 10, 19]; let x = 51; let n1 = arr1.length; let res1 = smallestSubWithSum(arr1, n1, x); (res1 == n1 + 1)? document.write("Not possible<br>") : document.write(res1 + "<br>"); let arr2 = [1, 10, 5, 2, 7]; let n2 = arr2.length; x = 9; let res2 = smallestSubWithSum(arr2, n2, x); (res2 == n2 + 1)? document.write("Not possible<br>") : document.write(res2 + "<br>"); let arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]; let n3 = arr3.length; x = 280; let res3 = smallestSubWithSum(arr3, n3, x); (res3 == n3 + 1)? document.write("Not possible<br>") : document.write(res3 + "<br>"); // This code is contributed by Surbhi Tyagi.</script> 3 1 4 Time Complexity: O(n2).Auxiliary Space: O(1) Efficient Solution: This problem can be solved in O(n) time using the idea used in this post. Thanks to Ankit and Nitin for suggesting this optimized solution. C++14 Java Python3 C# PHP Javascript // O(n) solution for finding smallest subarray with sum// greater than x#include <iostream>using namespace std; // Returns length of smallest subarray with sum greater than// x. If there is no subarray with given sum, then returns// n+1int smallestSubWithSum(int arr[], int n, int x){ // Initialize current sum and minimum length int curr_sum = 0, min_len = n + 1; // Initialize starting and ending indexes int start = 0, end = 0; while (end < n) { // Keep adding array elements while current sum // is smaller than or equal to x while (curr_sum <= x && end < n) curr_sum += arr[end++]; // If current sum becomes greater than x. while (curr_sum > x && start < n) { // Update minimum length if needed if (end - start < min_len) min_len = end - start; // remove starting elements curr_sum -= arr[start++]; } } return min_len;} /* Driver program to test above function */int main(){ int arr1[] = { 1, 4, 45, 6, 10, 19 }; int x = 51; int n1 = sizeof(arr1) / sizeof(arr1[0]); int res1 = smallestSubWithSum(arr1, n1, x); (res1 == n1 + 1) ? cout << "Not possible\n" : cout << res1 << endl; int arr2[] = { 1, 10, 5, 2, 7 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); x = 9; int res2 = smallestSubWithSum(arr2, n2, x); (res2 == n2 + 1) ? cout << "Not possible\n" : cout << res2 << endl; int arr3[] = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 }; int n3 = sizeof(arr3) / sizeof(arr3[0]); x = 280; int res3 = smallestSubWithSum(arr3, n3, x); (res3 == n3 + 1) ? cout << "Not possible\n" : cout << res3 << endl; return 0;} // O(n) solution for finding smallest subarray with sum// greater than x class SmallestSubArraySum { // Returns length of smallest subarray with sum greater // than x. If there is no subarray with given sum, then // returns n+1 static int smallestSubWithSum(int arr[], int n, int x) { // Initialize current sum and minimum length int curr_sum = 0, min_len = n + 1; // Initialize starting and ending indexes int start = 0, end = 0; while (end < n) { // Keep adding array elements while current sum // is smaller than or equal to x while (curr_sum <= x && end < n) curr_sum += arr[end++]; // If current sum becomes greater than x. while (curr_sum > x && start < n) { // Update minimum length if needed if (end - start < min_len) min_len = end - start; // remove starting elements curr_sum -= arr[start++]; } } return min_len; } // Driver program to test above functions public static void main(String[] args) { int arr1[] = { 1, 4, 45, 6, 10, 19 }; int x = 51; int n1 = arr1.length; int res1 = smallestSubWithSum(arr1, n1, x); if (res1 == n1 + 1) System.out.println("Not Possible"); else System.out.println(res1); int arr2[] = { 1, 10, 5, 2, 7 }; int n2 = arr2.length; x = 9; int res2 = smallestSubWithSum(arr2, n2, x); if (res2 == n2 + 1) System.out.println("Not Possible"); else System.out.println(res2); int arr3[] = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 }; int n3 = arr3.length; x = 280; int res3 = smallestSubWithSum(arr3, n3, x); if (res3 == n3 + 1) System.out.println("Not Possible"); else System.out.println(res3); }} // This code has been contributed by Mayank Jaiswal # O(n) solution for finding smallest# subarray with sum greater than x # Returns length of smallest subarray# with sum greater than x. If there# is no subarray with given sum, then# returns n + 1 def smallestSubWithSum(arr, n, x): # Initialize current sum and minimum length curr_sum = 0 min_len = n + 1 # Initialize starting and ending indexes start = 0 end = 0 while (end < n): # Keep adding array elements while current # sum is smaller than or equal to x while (curr_sum <= x and end < n): curr_sum += arr[end] end += 1 # If current sum becomes greater than x. while (curr_sum > x and start < n): # Update minimum length if needed if (end - start < min_len): min_len = end - start # remove starting elements curr_sum -= arr[start] start += 1 return min_len # Driver programarr1 = [1, 4, 45, 6, 10, 19]x = 51n1 = len(arr1)res1 = smallestSubWithSum(arr1, n1, x)print("Not possible") if (res1 == n1 + 1) else print(res1) arr2 = [1, 10, 5, 2, 7]n2 = len(arr2)x = 9res2 = smallestSubWithSum(arr2, n2, x)print("Not possible") if (res2 == n2 + 1) else print(res2) arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]n3 = len(arr3)x = 280res3 = smallestSubWithSum(arr3, n3, x)print("Not possible") if (res3 == n3 + 1) else print(res3) # This code is contributed by# Smitha Dinesh Semwal // O(n) solution for finding// smallest subarray with sum// greater than xusing System; class GFG { // Returns length of smallest // subarray with sum greater // than x. If there is no // subarray with given sum, // then returns n+1 static int smallestSubWithSum(int[] arr, int n, int x) { // Initialize current // sum and minimum length int curr_sum = 0, min_len = n + 1; // Initialize starting // and ending indexes int start = 0, end = 0; while (end < n) { // Keep adding array elements // while current sum is smaller // than or equal to x while (curr_sum <= x && end < n) curr_sum += arr[end++]; // If current sum becomes // greater than x. while (curr_sum > x && start < n) { // Update minimum // length if needed if (end - start < min_len) min_len = end - start; // remove starting elements curr_sum -= arr[start++]; } } return min_len; } // Driver Code static public void Main() { int[] arr1 = { 1, 4, 45, 6, 10, 19 }; int x = 51; int n1 = arr1.Length; int res1 = smallestSubWithSum(arr1, n1, x); if (res1 == n1 + 1) Console.WriteLine("Not Possible"); else Console.WriteLine(res1); int[] arr2 = { 1, 10, 5, 2, 7 }; int n2 = arr2.Length; x = 9; int res2 = smallestSubWithSum(arr2, n2, x); if (res2 == n2 + 1) Console.WriteLine("Not Possible"); else Console.WriteLine(res2); int[] arr3 = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 }; int n3 = arr3.Length; x = 280; int res3 = smallestSubWithSum(arr3, n3, x); if (res3 == n3 + 1) Console.WriteLine("Not Possible"); else Console.WriteLine(res3); }} // This code is contributed by akt_mit <?php// O(n) solution for finding// smallest subarray with sum// greater than x // Returns length of smallest// subarray with sum greater// than x. If there is no// subarray with given sum,// then returns n+1function smallestSubWithSum($arr, $n, $x){ // Initialize current // sum and minimum length $curr_sum = 0; $min_len = $n + 1; // Initialize starting // and ending indexes $start = 0; $end = 0; while ($end < $n) { // Keep adding array elements // while current sum is smaller // than or equal to x while ($curr_sum <= $x && $end < $n) $curr_sum += $arr[$end++]; // If current sum becomes // greater than x. while ($curr_sum > $x && $start < $n) { // Update minimum // length if needed if ($end - $start < $min_len) $min_len = $end - $start; // remove starting elements $curr_sum -= $arr[$start++]; } } return $min_len;} // Driver Code$arr1 = array(1, 4, 45, 6, 10, 19);$x = 51;$n1 = sizeof($arr1);$res1 = smallestSubWithSum($arr1, $n1, $x);if($res1 == $n1 + 1)echo "Not possible\n" ;elseecho $res1 ,"\n"; $arr2 = array(1, 10, 5, 2, 7);$n2 = sizeof($arr2);$x = 9;$res2 = smallestSubWithSum($arr2, $n2, $x);if($res2 == $n2 + 1)echo "Not possible\n" ;elseecho $res2,"\n"; $arr3 = array(1, 11, 100, 1, 0, 200, 3, 2, 1, 250);$n3 = sizeof($arr3);$x = 280;$res3 = smallestSubWithSum($arr3, $n3, $x); if($res3 == $n3 + 1)echo "Not possible\n" ;elseecho $res3, "\n"; // This code is contributed by ajit?> <script>// O(n) solution for finding smallest subarray with sum// greater than x // Returns length of smallest subarray with sum greater than// x. If there is no subarray with given sum, then returns// n+1function smallestSubWithSum(arr, n, x){ // Initialize current sum and minimum length let curr_sum = 0, min_len = n + 1; // Initialize starting and ending indexes let start = 0, end = 0; while (end < n) { // Keep adding array elements while current sum // is smaller than or equal to x while (curr_sum <= x && end < n) curr_sum += arr[end++]; // If current sum becomes greater than x. while (curr_sum > x && start < n) { // Update minimum length if needed if (end - start < min_len) min_len = end - start; // remove starting elements curr_sum -= arr[start++]; } } return min_len;} /* Driver program to test above function */let arr1 = [ 1, 4, 45, 6, 10, 19 ];let x = 51;let n1 = arr1.length;let res1 = smallestSubWithSum(arr1, n1, x);(res1 == n1 + 1) ? document.write("Not possible<br>") : document.write(res1 + "<br>"); let arr2 = [ 1, 10, 5, 2, 7 ];let n2 = arr2.length;x = 9;let res2 = smallestSubWithSum(arr2, n2, x);(res2 == n2 + 1) ? document.write("Not possible<br>") : document.write(res2 + "<br>"); let arr3 = [ 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 ];let n3 = arr3.length;x = 280;let res3 = smallestSubWithSum(arr3, n3, x);(res3 == n3 + 1) ? document.write("Not possible<br>") : document.write(res3 + "<br>"); // This code is contributed by subham348.</script> 3 1 4 Time Complexity: O(n).Auxiliary Space: O(1) How to handle negative numbers? The above solution may not work if input array contains negative numbers. For example arr[] = {- 8, 1, 4, 2, -6}. To handle negative numbers, add a condition to ignore subarrays with negative sums. We can use the solution discussed in Find subarray with given sum with negatives allowed in constant space jit_t Mithun Kumar RajeshKumar27 kapilkumar2001 surbhityagi15 subham348 sweetyty prachisoda1234 _shinchancode hardikkoriintern Accolite Amazon Facebook Goldman Sachs sliding-window subarray subarray-sum Arrays Accolite Amazon Goldman Sachs Facebook sliding-window Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Arrays in Java Write a program to reverse an array or string Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Largest Sum Contiguous Subarray Arrays in C/C++ Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Subset Sum Problem | DP-25
[ { "code": null, "e": 54, "s": 26, "text": "\n23 Jun, 2022" }, { "code": null, "e": 164, "s": 54, "text": "Given an array of integers and a number x, find the smallest subarray with sum greater than the given value. " }, { "code": null, "e": 540, "s": 164, "text": "Examples:\narr[] = {1, 4, 45, 6, 0, 19}\n x = 51\nOutput: 3\nMinimum length subarray is {4, 45, 6}\n\narr[] = {1, 10, 5, 2, 7}\n x = 9\nOutput: 1\nMinimum length subarray is {10}\n\narr[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250}\n x = 280\nOutput: 4\nMinimum length subarray is {100, 1, 0, 200}\n\narr[] = {1, 2, 4}\n x = 8\nOutput : Not Possible\nWhole array sum is smaller than 8." }, { "code": null, "e": 889, "s": 540, "text": "A simple solution is to use two nested loops. The outer loop picks a starting element, the inner loop considers all elements (on right side of current start) as ending element. Whenever sum of elements between current start and end becomes more than the given number, update the result if current length is smaller than the smallest length so far. " }, { "code": null, "e": 942, "s": 889, "text": "Following is the implementation of simple approach. " }, { "code": null, "e": 946, "s": 942, "text": "C++" }, { "code": null, "e": 951, "s": 946, "text": "Java" }, { "code": null, "e": 959, "s": 951, "text": "Python3" }, { "code": null, "e": 962, "s": 959, "text": "C#" }, { "code": null, "e": 966, "s": 962, "text": "PHP" }, { "code": null, "e": 977, "s": 966, "text": "Javascript" }, { "code": "# include <iostream>using namespace std; // Returns length of smallest subarray with sum greater than x.// If there is no subarray with given sum, then returns n+1int smallestSubWithSum(int arr[], int n, int x){ // Initialize length of smallest subarray as n+1 int min_len = n + 1; // Pick every element as starting point for (int start=0; start<n; start++) { // Initialize sum starting with current start int curr_sum = arr[start]; // If first element itself is greater if (curr_sum > x) return 1; // Try different ending points for current start for (int end=start+1; end<n; end++) { // add last element to current sum curr_sum += arr[end]; // If sum becomes more than x and length of // this subarray is smaller than current smallest // length, update the smallest length (or result) if (curr_sum > x && (end - start + 1) < min_len) min_len = (end - start + 1); } } return min_len;} /* Driver program to test above function */int main(){ int arr1[] = {1, 4, 45, 6, 10, 19}; int x = 51; int n1 = sizeof(arr1)/sizeof(arr1[0]); int res1 = smallestSubWithSum(arr1, n1, x); (res1 == n1+1)? cout << \"Not possible\\n\" : cout << res1 << endl; int arr2[] = {1, 10, 5, 2, 7}; int n2 = sizeof(arr2)/sizeof(arr2[0]); x = 9; int res2 = smallestSubWithSum(arr2, n2, x); (res2 == n2+1)? cout << \"Not possible\\n\" : cout << res2 << endl; int arr3[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250}; int n3 = sizeof(arr3)/sizeof(arr3[0]); x = 280; int res3 = smallestSubWithSum(arr3, n3, x); (res3 == n3+1)? cout << \"Not possible\\n\" : cout << res3 << endl; return 0;}", "e": 2828, "s": 977, "text": null }, { "code": "class SmallestSubArraySum{ // Returns length of smallest subarray with sum greater than x. // If there is no subarray with given sum, then returns n+1 static int smallestSubWithSum(int arr[], int n, int x) { // Initialize length of smallest subarray as n+1 int min_len = n + 1; // Pick every element as starting point for (int start = 0; start < n; start++) { // Initialize sum starting with current start int curr_sum = arr[start]; // If first element itself is greater if (curr_sum > x) return 1; // Try different ending points for curremt start for (int end = start + 1; end < n; end++) { // add last element to current sum curr_sum += arr[end]; // If sum becomes more than x and length of // this subarray is smaller than current smallest // length, update the smallest length (or result) if (curr_sum > x && (end - start + 1) < min_len) min_len = (end - start + 1); } } return min_len; } // Driver program to test above functions public static void main(String[] args) { int arr1[] = {1, 4, 45, 6, 10, 19}; int x = 51; int n1 = arr1.length; int res1 = smallestSubWithSum(arr1, n1, x); if (res1 == n1+1) System.out.println(\"Not Possible\"); else System.out.println(res1); int arr2[] = {1, 10, 5, 2, 7}; int n2 = arr2.length; x = 9; int res2 = smallestSubWithSum(arr2, n2, x); if (res2 == n2+1) System.out.println(\"Not Possible\"); else System.out.println(res2); int arr3[] = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250}; int n3 = arr3.length; x = 280; int res3 = smallestSubWithSum(arr3, n3, x); if (res3 == n3+1) System.out.println(\"Not Possible\"); else System.out.println(res3); }} // This code has been contributed by Mayank Jaiswal", "e": 4942, "s": 2828, "text": null }, { "code": "# Python3 program to find Smallest# subarray with sum greater# than a given value # Returns length of smallest subarray# with sum greater than x. If there# is no subarray with given sum,# then returns n+1def smallestSubWithSum(arr, n, x): # Initialize length of smallest # subarray as n+1 min_len = n + 1 # Pick every element as starting point for start in range(0,n): # Initialize sum starting # with current start curr_sum = arr[start] # If first element itself is greater if (curr_sum > x): return 1 # Try different ending points # for curremt start for end in range(start+1,n): # add last element to current sum curr_sum += arr[end] # If sum becomes more than x # and length of this subarray # is smaller than current smallest # length, update the smallest # length (or result) if curr_sum > x and (end - start + 1) < min_len: min_len = (end - start + 1) return min_len; # Driver program to test above function */arr1 = [1, 4, 45, 6, 10, 19]x = 51n1 = len(arr1)res1 = smallestSubWithSum(arr1, n1, x);if res1 == n1+1: print(\"Not possible\")else: print(res1) arr2 = [1, 10, 5, 2, 7]n2 = len(arr2)x = 9res2 = smallestSubWithSum(arr2, n2, x);if res2 == n2+1: print(\"Not possible\")else: print(res2) arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]n3 = len(arr3)x = 280res3 = smallestSubWithSum(arr3, n3, x)if res3 == n3+1: print(\"Not possible\")else: print(res3) # This code is contributed by Smitha Dinesh Semwal", "e": 6588, "s": 4942, "text": null }, { "code": "// C# program to find Smallest// subarray with sum greater// than a given valueusing System; class GFG{ // Returns length of smallest // subarray with sum greater // than x. If there is no // subarray with given sum, // then returns n+1 static int smallestSubWithSum(int []arr, int n, int x) { // Initialize length of // smallest subarray as n+1 int min_len = n + 1; // Pick every element // as starting point for (int start = 0; start < n; start++) { // Initialize sum starting // with current start int curr_sum = arr[start]; // If first element // itself is greater if (curr_sum > x) return 1; // Try different ending // points for curremt start for (int end = start + 1; end < n; end++) { // add last element // to current sum curr_sum += arr[end]; // If sum becomes more than // x and length of this // subarray is smaller than // current smallest length, // update the smallest // length (or result) if (curr_sum > x && (end - start + 1) < min_len) min_len = (end - start + 1); } } return min_len; } // Driver Code static public void Main () { int []arr1 = {1, 4, 45, 6, 10, 19}; int x = 51; int n1 = arr1.Length; int res1 = smallestSubWithSum(arr1, n1, x); if (res1 == n1 + 1) Console.WriteLine(\"Not Possible\"); else Console.WriteLine(res1); int []arr2 = {1, 10, 5, 2, 7}; int n2 = arr2.Length; x = 9; int res2 = smallestSubWithSum(arr2, n2, x); if (res2 == n2 + 1) Console.WriteLine(\"Not Possible\"); else Console.WriteLine(res2); int []arr3 = {1, 11, 100, 1, 0, 200, 3, 2, 1, 250}; int n3 = arr3.Length; x = 280; int res3 = smallestSubWithSum(arr3, n3, x); if (res3 == n3 + 1) Console.WriteLine(\"Not Possible\"); else Console.WriteLine(res3); }} // This code is contributed by ajit", "e": 9091, "s": 6588, "text": null }, { "code": "<?php// Returns length of smallest// subarray with sum greater// than x. If there is no// subarray with given sum,// then returns n+1function smallestSubWithSum($arr, $n, $x){ // Initialize length of // smallest subarray as n+1 $min_len = $n + 1; // Pick every element // as starting point for ($start = 0; $start < $n; $start++) { // Initialize sum starting // with current start $curr_sum = $arr[$start]; // If first element // itself is greater if ($curr_sum > $x) return 1; // Try different ending // points for curremt start for ($end= $start + 1; $end < $n; $end++) { // add last element // to current sum $curr_sum += $arr[$end]; // If sum becomes more than // x and length of this subarray // is smaller than current // smallest length, update the // smallest length (or result) if ($curr_sum > $x && ($end - $start + 1) < $min_len) $min_len = ($end - $start + 1); } } return $min_len;} // Driver Code$arr1 = array (1, 4, 45, 6, 10, 19);$x = 51;$n1 = sizeof($arr1);$res1 = smallestSubWithSum($arr1, $n1, $x); if (($res1 == $n1 + 1) == true) echo \"Not possible\\n\" ;else echo $res1 , \"\\n\"; $arr2 = array(1, 10, 5, 2, 7);$n2 = sizeof($arr2);$x = 9;$res2 = smallestSubWithSum($arr2, $n2, $x); if (($res2 == $n2 + 1) == true) echo \"Not possible\\n\" ;else echo $res2 , \"\\n\"; $arr3 = array (1, 11, 100, 1, 0, 200, 3, 2, 1, 250);$n3 = sizeof($arr3);$x = 280;$res3 = smallestSubWithSum($arr3, $n3, $x);if (($res3 == $n3 + 1) == true) echo \"Not possible\\n\" ;else echo $res3 , \"\\n\"; // This code is contributed by ajit?>", "e": 10894, "s": 9091, "text": null }, { "code": "<script> // Returns length of smallest subarray with sum greater than x.// If there is no subarray with given sum, then returns n+1function smallestSubWithSum(arr, n, x){ // Initialize length of smallest subarray as n+1 let min_len = n + 1; // Pick every element as starting point for (let start=0; start<n; start++) { // Initialize sum starting with current start let curr_sum = arr[start]; // If first element itself is greater if (curr_sum > x) return 1; // Try different ending points for curremt start for (let end=start+1; end<n; end++) { // add last element to current sum curr_sum += arr[end]; // If sum becomes more than x and length of // this subarray is smaller than current smallest // length, update the smallest length (or result) if (curr_sum > x && (end - start + 1) < min_len) min_len = (end - start + 1); } } return min_len;} /* Driver program to test above function */ let arr1 = [1, 4, 45, 6, 10, 19]; let x = 51; let n1 = arr1.length; let res1 = smallestSubWithSum(arr1, n1, x); (res1 == n1 + 1)? document.write(\"Not possible<br>\") : document.write(res1 + \"<br>\"); let arr2 = [1, 10, 5, 2, 7]; let n2 = arr2.length; x = 9; let res2 = smallestSubWithSum(arr2, n2, x); (res2 == n2 + 1)? document.write(\"Not possible<br>\") : document.write(res2 + \"<br>\"); let arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]; let n3 = arr3.length; x = 280; let res3 = smallestSubWithSum(arr3, n3, x); (res3 == n3 + 1)? document.write(\"Not possible<br>\") : document.write(res3 + \"<br>\"); // This code is contributed by Surbhi Tyagi.</script>", "e": 12715, "s": 10894, "text": null }, { "code": null, "e": 12722, "s": 12715, "text": "3\n1\n4\n" }, { "code": null, "e": 12767, "s": 12722, "text": "Time Complexity: O(n2).Auxiliary Space: O(1)" }, { "code": null, "e": 12928, "s": 12767, "text": "Efficient Solution: This problem can be solved in O(n) time using the idea used in this post. Thanks to Ankit and Nitin for suggesting this optimized solution. " }, { "code": null, "e": 12934, "s": 12928, "text": "C++14" }, { "code": null, "e": 12939, "s": 12934, "text": "Java" }, { "code": null, "e": 12947, "s": 12939, "text": "Python3" }, { "code": null, "e": 12950, "s": 12947, "text": "C#" }, { "code": null, "e": 12954, "s": 12950, "text": "PHP" }, { "code": null, "e": 12965, "s": 12954, "text": "Javascript" }, { "code": "// O(n) solution for finding smallest subarray with sum// greater than x#include <iostream>using namespace std; // Returns length of smallest subarray with sum greater than// x. If there is no subarray with given sum, then returns// n+1int smallestSubWithSum(int arr[], int n, int x){ // Initialize current sum and minimum length int curr_sum = 0, min_len = n + 1; // Initialize starting and ending indexes int start = 0, end = 0; while (end < n) { // Keep adding array elements while current sum // is smaller than or equal to x while (curr_sum <= x && end < n) curr_sum += arr[end++]; // If current sum becomes greater than x. while (curr_sum > x && start < n) { // Update minimum length if needed if (end - start < min_len) min_len = end - start; // remove starting elements curr_sum -= arr[start++]; } } return min_len;} /* Driver program to test above function */int main(){ int arr1[] = { 1, 4, 45, 6, 10, 19 }; int x = 51; int n1 = sizeof(arr1) / sizeof(arr1[0]); int res1 = smallestSubWithSum(arr1, n1, x); (res1 == n1 + 1) ? cout << \"Not possible\\n\" : cout << res1 << endl; int arr2[] = { 1, 10, 5, 2, 7 }; int n2 = sizeof(arr2) / sizeof(arr2[0]); x = 9; int res2 = smallestSubWithSum(arr2, n2, x); (res2 == n2 + 1) ? cout << \"Not possible\\n\" : cout << res2 << endl; int arr3[] = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 }; int n3 = sizeof(arr3) / sizeof(arr3[0]); x = 280; int res3 = smallestSubWithSum(arr3, n3, x); (res3 == n3 + 1) ? cout << \"Not possible\\n\" : cout << res3 << endl; return 0;}", "e": 14715, "s": 12965, "text": null }, { "code": "// O(n) solution for finding smallest subarray with sum// greater than x class SmallestSubArraySum { // Returns length of smallest subarray with sum greater // than x. If there is no subarray with given sum, then // returns n+1 static int smallestSubWithSum(int arr[], int n, int x) { // Initialize current sum and minimum length int curr_sum = 0, min_len = n + 1; // Initialize starting and ending indexes int start = 0, end = 0; while (end < n) { // Keep adding array elements while current sum // is smaller than or equal to x while (curr_sum <= x && end < n) curr_sum += arr[end++]; // If current sum becomes greater than x. while (curr_sum > x && start < n) { // Update minimum length if needed if (end - start < min_len) min_len = end - start; // remove starting elements curr_sum -= arr[start++]; } } return min_len; } // Driver program to test above functions public static void main(String[] args) { int arr1[] = { 1, 4, 45, 6, 10, 19 }; int x = 51; int n1 = arr1.length; int res1 = smallestSubWithSum(arr1, n1, x); if (res1 == n1 + 1) System.out.println(\"Not Possible\"); else System.out.println(res1); int arr2[] = { 1, 10, 5, 2, 7 }; int n2 = arr2.length; x = 9; int res2 = smallestSubWithSum(arr2, n2, x); if (res2 == n2 + 1) System.out.println(\"Not Possible\"); else System.out.println(res2); int arr3[] = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 }; int n3 = arr3.length; x = 280; int res3 = smallestSubWithSum(arr3, n3, x); if (res3 == n3 + 1) System.out.println(\"Not Possible\"); else System.out.println(res3); }} // This code has been contributed by Mayank Jaiswal", "e": 16738, "s": 14715, "text": null }, { "code": "# O(n) solution for finding smallest# subarray with sum greater than x # Returns length of smallest subarray# with sum greater than x. If there# is no subarray with given sum, then# returns n + 1 def smallestSubWithSum(arr, n, x): # Initialize current sum and minimum length curr_sum = 0 min_len = n + 1 # Initialize starting and ending indexes start = 0 end = 0 while (end < n): # Keep adding array elements while current # sum is smaller than or equal to x while (curr_sum <= x and end < n): curr_sum += arr[end] end += 1 # If current sum becomes greater than x. while (curr_sum > x and start < n): # Update minimum length if needed if (end - start < min_len): min_len = end - start # remove starting elements curr_sum -= arr[start] start += 1 return min_len # Driver programarr1 = [1, 4, 45, 6, 10, 19]x = 51n1 = len(arr1)res1 = smallestSubWithSum(arr1, n1, x)print(\"Not possible\") if (res1 == n1 + 1) else print(res1) arr2 = [1, 10, 5, 2, 7]n2 = len(arr2)x = 9res2 = smallestSubWithSum(arr2, n2, x)print(\"Not possible\") if (res2 == n2 + 1) else print(res2) arr3 = [1, 11, 100, 1, 0, 200, 3, 2, 1, 250]n3 = len(arr3)x = 280res3 = smallestSubWithSum(arr3, n3, x)print(\"Not possible\") if (res3 == n3 + 1) else print(res3) # This code is contributed by# Smitha Dinesh Semwal", "e": 18173, "s": 16738, "text": null }, { "code": "// O(n) solution for finding// smallest subarray with sum// greater than xusing System; class GFG { // Returns length of smallest // subarray with sum greater // than x. If there is no // subarray with given sum, // then returns n+1 static int smallestSubWithSum(int[] arr, int n, int x) { // Initialize current // sum and minimum length int curr_sum = 0, min_len = n + 1; // Initialize starting // and ending indexes int start = 0, end = 0; while (end < n) { // Keep adding array elements // while current sum is smaller // than or equal to x while (curr_sum <= x && end < n) curr_sum += arr[end++]; // If current sum becomes // greater than x. while (curr_sum > x && start < n) { // Update minimum // length if needed if (end - start < min_len) min_len = end - start; // remove starting elements curr_sum -= arr[start++]; } } return min_len; } // Driver Code static public void Main() { int[] arr1 = { 1, 4, 45, 6, 10, 19 }; int x = 51; int n1 = arr1.Length; int res1 = smallestSubWithSum(arr1, n1, x); if (res1 == n1 + 1) Console.WriteLine(\"Not Possible\"); else Console.WriteLine(res1); int[] arr2 = { 1, 10, 5, 2, 7 }; int n2 = arr2.Length; x = 9; int res2 = smallestSubWithSum(arr2, n2, x); if (res2 == n2 + 1) Console.WriteLine(\"Not Possible\"); else Console.WriteLine(res2); int[] arr3 = { 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 }; int n3 = arr3.Length; x = 280; int res3 = smallestSubWithSum(arr3, n3, x); if (res3 == n3 + 1) Console.WriteLine(\"Not Possible\"); else Console.WriteLine(res3); }} // This code is contributed by akt_mit", "e": 20216, "s": 18173, "text": null }, { "code": "<?php// O(n) solution for finding// smallest subarray with sum// greater than x // Returns length of smallest// subarray with sum greater// than x. If there is no// subarray with given sum,// then returns n+1function smallestSubWithSum($arr, $n, $x){ // Initialize current // sum and minimum length $curr_sum = 0; $min_len = $n + 1; // Initialize starting // and ending indexes $start = 0; $end = 0; while ($end < $n) { // Keep adding array elements // while current sum is smaller // than or equal to x while ($curr_sum <= $x && $end < $n) $curr_sum += $arr[$end++]; // If current sum becomes // greater than x. while ($curr_sum > $x && $start < $n) { // Update minimum // length if needed if ($end - $start < $min_len) $min_len = $end - $start; // remove starting elements $curr_sum -= $arr[$start++]; } } return $min_len;} // Driver Code$arr1 = array(1, 4, 45, 6, 10, 19);$x = 51;$n1 = sizeof($arr1);$res1 = smallestSubWithSum($arr1, $n1, $x);if($res1 == $n1 + 1)echo \"Not possible\\n\" ;elseecho $res1 ,\"\\n\"; $arr2 = array(1, 10, 5, 2, 7);$n2 = sizeof($arr2);$x = 9;$res2 = smallestSubWithSum($arr2, $n2, $x);if($res2 == $n2 + 1)echo \"Not possible\\n\" ;elseecho $res2,\"\\n\"; $arr3 = array(1, 11, 100, 1, 0, 200, 3, 2, 1, 250);$n3 = sizeof($arr3);$x = 280;$res3 = smallestSubWithSum($arr3, $n3, $x); if($res3 == $n3 + 1)echo \"Not possible\\n\" ;elseecho $res3, \"\\n\"; // This code is contributed by ajit?>", "e": 21989, "s": 20216, "text": null }, { "code": "<script>// O(n) solution for finding smallest subarray with sum// greater than x // Returns length of smallest subarray with sum greater than// x. If there is no subarray with given sum, then returns// n+1function smallestSubWithSum(arr, n, x){ // Initialize current sum and minimum length let curr_sum = 0, min_len = n + 1; // Initialize starting and ending indexes let start = 0, end = 0; while (end < n) { // Keep adding array elements while current sum // is smaller than or equal to x while (curr_sum <= x && end < n) curr_sum += arr[end++]; // If current sum becomes greater than x. while (curr_sum > x && start < n) { // Update minimum length if needed if (end - start < min_len) min_len = end - start; // remove starting elements curr_sum -= arr[start++]; } } return min_len;} /* Driver program to test above function */let arr1 = [ 1, 4, 45, 6, 10, 19 ];let x = 51;let n1 = arr1.length;let res1 = smallestSubWithSum(arr1, n1, x);(res1 == n1 + 1) ? document.write(\"Not possible<br>\") : document.write(res1 + \"<br>\"); let arr2 = [ 1, 10, 5, 2, 7 ];let n2 = arr2.length;x = 9;let res2 = smallestSubWithSum(arr2, n2, x);(res2 == n2 + 1) ? document.write(\"Not possible<br>\") : document.write(res2 + \"<br>\"); let arr3 = [ 1, 11, 100, 1, 0, 200, 3, 2, 1, 250 ];let n3 = arr3.length;x = 280;let res3 = smallestSubWithSum(arr3, n3, x);(res3 == n3 + 1) ? document.write(\"Not possible<br>\") : document.write(res3 + \"<br>\"); // This code is contributed by subham348.</script>", "e": 23615, "s": 21989, "text": null }, { "code": null, "e": 23622, "s": 23615, "text": "3\n1\n4\n" }, { "code": null, "e": 23666, "s": 23622, "text": "Time Complexity: O(n).Auxiliary Space: O(1)" }, { "code": null, "e": 23699, "s": 23666, "text": "How to handle negative numbers? " }, { "code": null, "e": 24005, "s": 23699, "text": "The above solution may not work if input array contains negative numbers. For example arr[] = {- 8, 1, 4, 2, -6}. To handle negative numbers, add a condition to ignore subarrays with negative sums. We can use the solution discussed in Find subarray with given sum with negatives allowed in constant space " }, { "code": null, "e": 24011, "s": 24005, "text": "jit_t" }, { "code": null, "e": 24024, "s": 24011, "text": "Mithun Kumar" }, { "code": null, "e": 24038, "s": 24024, "text": "RajeshKumar27" }, { "code": null, "e": 24053, "s": 24038, "text": "kapilkumar2001" }, { "code": null, "e": 24067, "s": 24053, "text": "surbhityagi15" }, { "code": null, "e": 24077, "s": 24067, "text": "subham348" }, { "code": null, "e": 24086, "s": 24077, "text": "sweetyty" }, { "code": null, "e": 24101, "s": 24086, "text": "prachisoda1234" }, { "code": null, "e": 24115, "s": 24101, "text": "_shinchancode" }, { "code": null, "e": 24132, "s": 24115, "text": "hardikkoriintern" }, { "code": null, "e": 24141, "s": 24132, "text": "Accolite" }, { "code": null, "e": 24148, "s": 24141, "text": "Amazon" }, { "code": null, "e": 24157, "s": 24148, "text": "Facebook" }, { "code": null, "e": 24171, "s": 24157, "text": "Goldman Sachs" }, { "code": null, "e": 24186, "s": 24171, "text": "sliding-window" }, { "code": null, "e": 24195, "s": 24186, "text": "subarray" }, { "code": null, "e": 24208, "s": 24195, "text": "subarray-sum" }, { "code": null, "e": 24215, "s": 24208, "text": "Arrays" }, { "code": null, "e": 24224, "s": 24215, "text": "Accolite" }, { "code": null, "e": 24231, "s": 24224, "text": "Amazon" }, { "code": null, "e": 24245, "s": 24231, "text": "Goldman Sachs" }, { "code": null, "e": 24254, "s": 24245, "text": "Facebook" }, { "code": null, "e": 24269, "s": 24254, "text": "sliding-window" }, { "code": null, "e": 24276, "s": 24269, "text": "Arrays" }, { "code": null, "e": 24374, "s": 24276, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 24389, "s": 24374, "text": "Arrays in Java" }, { "code": null, "e": 24435, "s": 24389, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 24503, "s": 24435, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 24547, "s": 24503, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 24579, "s": 24547, "text": "Largest Sum Contiguous Subarray" }, { "code": null, "e": 24595, "s": 24579, "text": "Arrays in C/C++" }, { "code": null, "e": 24627, "s": 24595, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 24675, "s": 24627, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 24689, "s": 24675, "text": "Linear Search" } ]
Python – Dynamic GUI Calculator using Tkinter module
14 Aug, 2021 Python provides many options for developing GUI like Kivy, PyQT, WxPython, and several others. Tkinter is the one that is shipped inbuilt with python which makes it the most commonly used out of all. Tkinter is easy, fast, and powerful. Beginners can easily learn to create a simple calculator using this article: Python | Simple GUI calculator using Tkinter The simple calculator created by manually adding each button and creating different functions for each unique button is a tedious task. It is not the best practice. Here we will see a dynamic calculator program that can be easily scaled. Let us create a simple and easy GUI calculator that can do basic math operations like multiplication, division, square root, addition, and subtraction, even more operations can be added, and according to it changes can be made in the function. Creating the main window Creating a container containing all keys used in the calculator (Here List) Creating a container for all our buttons created Creating buttons and adding them to the button container Defining the function to be called when a button is pressed Running the main loop Python3 # Import required modulesfrom tkinter import *import tkinter.font as font # Creating the main windowroot = Tk() # Assigning it the desired geometryroot.geometry("380x400") # Assigning the name of our windowroot.title("Calculator") # Assigning it the capability to# be resizable (It is default)root.resizable(0, 0) # Creating a StringVar to take# the text entered in the Entry widgetinp = StringVar()myFont = font.Font(size=15) # Creating an Entry widget to get the# mathematical expression# And also to display the resultsscreen = Entry(root, text=inp, width=30, justify='right', font=(10), bd=4) # We will use a grid like structurescreen.grid(row=0, columnspan=4, padx=15, pady=15, ipady=5) # Key matrix contains all the required the keyskey_matrix = [["c", u"\u221A", "/", "<-"], ["7", "8", "9", "*"], ["4", "5", "6", "-"], ["1", "2", "3", "+"], ["!", 0, ".", "="]] # Creating a dictionary for the buttonsbtn_dict = {} # Variable to store our resultsans_to_print = 0 # Defining the function for calculationdef Calculate(event): # getting the name of the button clicked button = event.widget.cget("text") # Referring the global values global key_matrix, inp, ans_to_print try: # Event containing a sqrt operation if button == u"\u221A": ans = float(inp.get())**(0.5) ans_to_print = str(ans) inp.set(str(ans)) elif button == "c": # Clear Button inp.set("") elif button == "!": # Factorial def fact(n): return 1 if n == 0 else n*fact(n-1) inp.set(str(fact(int(inp.get())))) elif button == "<-": # Backspace inp.set(inp.get()[:len(inp.get())-1]) elif button == "=": # Showing The Results # Calculating the mathematical exp. using eval ans_to_print = str(eval(inp.get())) inp.set(ans_to_print) # You may add many more operations else: # Displaying the digit pressed on screen inp.set(inp.get()+str(button)) except: # In case invalid syntax given in expression inp.set("Wrong Operation") # Creating the buttons using for loop # Number of rows containing buttonsfor i in range(len(key_matrix)): # Number of columns for j in range(len(key_matrix[i])): # Creating and Adding the buttons to dictionary btn_dict["btn_"+str(key_matrix[i][j])] = Button( root, bd=1, text=str(key_matrix[i][j]), font=myFont) # Positioning buttons btn_dict["btn_"+str(key_matrix[i][j])].grid( row=i+1, column=j, padx=5, pady=5, ipadx=5, ipady=5) # Assigning an action to the buttons btn_dict["btn_"+str(key_matrix[i][j])].bind('<Button-1>', Calculate) # Running the main looproot.mainloop() Output: Output Example 2 saurabh1990aror rajeev0719singh gulshankumarar231 Python Tkinter-exercises Python Tkinter-projects Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Aug, 2021" }, { "code": null, "e": 292, "s": 54, "text": "Python provides many options for developing GUI like Kivy, PyQT, WxPython, and several others. Tkinter is the one that is shipped inbuilt with python which makes it the most commonly used out of all. Tkinter is easy, fast, and powerful. " }, { "code": null, "e": 414, "s": 292, "text": "Beginners can easily learn to create a simple calculator using this article: Python | Simple GUI calculator using Tkinter" }, { "code": null, "e": 896, "s": 414, "text": "The simple calculator created by manually adding each button and creating different functions for each unique button is a tedious task. It is not the best practice. Here we will see a dynamic calculator program that can be easily scaled. Let us create a simple and easy GUI calculator that can do basic math operations like multiplication, division, square root, addition, and subtraction, even more operations can be added, and according to it changes can be made in the function." }, { "code": null, "e": 921, "s": 896, "text": "Creating the main window" }, { "code": null, "e": 997, "s": 921, "text": "Creating a container containing all keys used in the calculator (Here List)" }, { "code": null, "e": 1046, "s": 997, "text": "Creating a container for all our buttons created" }, { "code": null, "e": 1103, "s": 1046, "text": "Creating buttons and adding them to the button container" }, { "code": null, "e": 1163, "s": 1103, "text": "Defining the function to be called when a button is pressed" }, { "code": null, "e": 1185, "s": 1163, "text": "Running the main loop" }, { "code": null, "e": 1193, "s": 1185, "text": "Python3" }, { "code": "# Import required modulesfrom tkinter import *import tkinter.font as font # Creating the main windowroot = Tk() # Assigning it the desired geometryroot.geometry(\"380x400\") # Assigning the name of our windowroot.title(\"Calculator\") # Assigning it the capability to# be resizable (It is default)root.resizable(0, 0) # Creating a StringVar to take# the text entered in the Entry widgetinp = StringVar()myFont = font.Font(size=15) # Creating an Entry widget to get the# mathematical expression# And also to display the resultsscreen = Entry(root, text=inp, width=30, justify='right', font=(10), bd=4) # We will use a grid like structurescreen.grid(row=0, columnspan=4, padx=15, pady=15, ipady=5) # Key matrix contains all the required the keyskey_matrix = [[\"c\", u\"\\u221A\", \"/\", \"<-\"], [\"7\", \"8\", \"9\", \"*\"], [\"4\", \"5\", \"6\", \"-\"], [\"1\", \"2\", \"3\", \"+\"], [\"!\", 0, \".\", \"=\"]] # Creating a dictionary for the buttonsbtn_dict = {} # Variable to store our resultsans_to_print = 0 # Defining the function for calculationdef Calculate(event): # getting the name of the button clicked button = event.widget.cget(\"text\") # Referring the global values global key_matrix, inp, ans_to_print try: # Event containing a sqrt operation if button == u\"\\u221A\": ans = float(inp.get())**(0.5) ans_to_print = str(ans) inp.set(str(ans)) elif button == \"c\": # Clear Button inp.set(\"\") elif button == \"!\": # Factorial def fact(n): return 1 if n == 0 else n*fact(n-1) inp.set(str(fact(int(inp.get())))) elif button == \"<-\": # Backspace inp.set(inp.get()[:len(inp.get())-1]) elif button == \"=\": # Showing The Results # Calculating the mathematical exp. using eval ans_to_print = str(eval(inp.get())) inp.set(ans_to_print) # You may add many more operations else: # Displaying the digit pressed on screen inp.set(inp.get()+str(button)) except: # In case invalid syntax given in expression inp.set(\"Wrong Operation\") # Creating the buttons using for loop # Number of rows containing buttonsfor i in range(len(key_matrix)): # Number of columns for j in range(len(key_matrix[i])): # Creating and Adding the buttons to dictionary btn_dict[\"btn_\"+str(key_matrix[i][j])] = Button( root, bd=1, text=str(key_matrix[i][j]), font=myFont) # Positioning buttons btn_dict[\"btn_\"+str(key_matrix[i][j])].grid( row=i+1, column=j, padx=5, pady=5, ipadx=5, ipady=5) # Assigning an action to the buttons btn_dict[\"btn_\"+str(key_matrix[i][j])].bind('<Button-1>', Calculate) # Running the main looproot.mainloop()", "e": 4067, "s": 1193, "text": null }, { "code": null, "e": 4075, "s": 4067, "text": "Output:" }, { "code": null, "e": 4092, "s": 4075, "text": "Output Example 2" }, { "code": null, "e": 4108, "s": 4092, "text": "saurabh1990aror" }, { "code": null, "e": 4124, "s": 4108, "text": "rajeev0719singh" }, { "code": null, "e": 4142, "s": 4124, "text": "gulshankumarar231" }, { "code": null, "e": 4167, "s": 4142, "text": "Python Tkinter-exercises" }, { "code": null, "e": 4191, "s": 4167, "text": "Python Tkinter-projects" }, { "code": null, "e": 4206, "s": 4191, "text": "Python-tkinter" }, { "code": null, "e": 4213, "s": 4206, "text": "Python" } ]
Java Program to Find Maximum Odd Number in Array Using Stream and Filter
29 Oct, 2020 Java 8 introduced some great features like Stream and Filter which tremendously simplify tasks like reading data and performing operations like minimum, maximum, sum, and conditional check on them. In this program, we will get the maximum of all odd numbers from a list of integers with the help of the Java Stream and Filter method. In the absence of Streams, we could achieve the given task by iterating through the list and checking if the number is odd. If true, we would check if it is larger than the maximum odd number until now. Below is the implementation of the approach: Java // Java implementation to find// the maximum odd number in array import java.util.List;import java.util.ArrayList;import java.util.Iterator; class GFG { // Function to find the maximum // odd number in array public static int maxOdd(List<Integer> list) { // Iterator for accessing the elements Iterator<Integer> it = list.iterator(); int max = 0; while (it.hasNext()) { int num = it.next(); // Adding the elements // greater than 5 if (num % 2 == 1) { if (num > max) { max = num; } } } return max; } // Driver Code public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(11); list.add(43); list.add(56); list.add(82); list.add(51); list.add(29); list.add(10); System.out.println("Largest odd number: " + maxOdd(list)); }} Largest odd number: 51 Stream filter returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation. These operations are always lazy i.e, executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. Below is the implementation of the above approach: Java // Java implementation to find // the maximum odd number// in the array import java.util.List;import java.util.ArrayList;import java.util.Iterator; class GFG { // Function to find the maximum odd // number in the list public static int maxOdd(List<Integer> list) { // Converted to Stream // Filtering the odd number // Taking maximum out of those integers return list.stream() .filter(n -> n % 2 == 1) .max(Integer::compare) .orElse(0); } // Driver Code public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(11); list.add(43); list.add(56); list.add(82); list.add(51); list.add(29); list.add(10); System.out.println("Largest odd number: " + maxOdd(list)); }} Largest odd number: 51 Performance Analysis: Time Complexity: O(N) Auxiliary Space: O(1) Java-Array-Programs Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Initializing a List in Java Java Programming Examples Convert a String to Character Array in Java Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Oct, 2020" }, { "code": null, "e": 362, "s": 28, "text": "Java 8 introduced some great features like Stream and Filter which tremendously simplify tasks like reading data and performing operations like minimum, maximum, sum, and conditional check on them. In this program, we will get the maximum of all odd numbers from a list of integers with the help of the Java Stream and Filter method." }, { "code": null, "e": 566, "s": 362, "text": "In the absence of Streams, we could achieve the given task by iterating through the list and checking if the number is odd. If true, we would check if it is larger than the maximum odd number until now. " }, { "code": null, "e": 611, "s": 566, "text": "Below is the implementation of the approach:" }, { "code": null, "e": 616, "s": 611, "text": "Java" }, { "code": "// Java implementation to find// the maximum odd number in array import java.util.List;import java.util.ArrayList;import java.util.Iterator; class GFG { // Function to find the maximum // odd number in array public static int maxOdd(List<Integer> list) { // Iterator for accessing the elements Iterator<Integer> it = list.iterator(); int max = 0; while (it.hasNext()) { int num = it.next(); // Adding the elements // greater than 5 if (num % 2 == 1) { if (num > max) { max = num; } } } return max; } // Driver Code public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(11); list.add(43); list.add(56); list.add(82); list.add(51); list.add(29); list.add(10); System.out.println(\"Largest odd number: \" + maxOdd(list)); }}", "e": 1675, "s": 616, "text": null }, { "code": null, "e": 1698, "s": 1675, "text": "Largest odd number: 51" }, { "code": null, "e": 2101, "s": 1698, "text": "Stream filter returns a stream consisting of the elements of this stream that match the given predicate. This is an intermediate operation. These operations are always lazy i.e, executing an intermediate operation such as filter() does not actually perform any filtering, but instead creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate." }, { "code": null, "e": 2152, "s": 2101, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 2157, "s": 2152, "text": "Java" }, { "code": "// Java implementation to find // the maximum odd number// in the array import java.util.List;import java.util.ArrayList;import java.util.Iterator; class GFG { // Function to find the maximum odd // number in the list public static int maxOdd(List<Integer> list) { // Converted to Stream // Filtering the odd number // Taking maximum out of those integers return list.stream() .filter(n -> n % 2 == 1) .max(Integer::compare) .orElse(0); } // Driver Code public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); list.add(11); list.add(43); list.add(56); list.add(82); list.add(51); list.add(29); list.add(10); System.out.println(\"Largest odd number: \" + maxOdd(list)); }}", "e": 3065, "s": 2157, "text": null }, { "code": null, "e": 3088, "s": 3065, "text": "Largest odd number: 51" }, { "code": null, "e": 3110, "s": 3088, "text": "Performance Analysis:" }, { "code": null, "e": 3132, "s": 3110, "text": "Time Complexity: O(N)" }, { "code": null, "e": 3154, "s": 3132, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 3174, "s": 3154, "text": "Java-Array-Programs" }, { "code": null, "e": 3179, "s": 3174, "text": "Java" }, { "code": null, "e": 3193, "s": 3179, "text": "Java Programs" }, { "code": null, "e": 3198, "s": 3193, "text": "Java" }, { "code": null, "e": 3296, "s": 3198, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3347, "s": 3296, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3378, "s": 3347, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3397, "s": 3378, "text": "Interfaces in Java" }, { "code": null, "e": 3427, "s": 3397, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3445, "s": 3427, "text": "ArrayList in Java" }, { "code": null, "e": 3473, "s": 3445, "text": "Initializing a List in Java" }, { "code": null, "e": 3499, "s": 3473, "text": "Java Programming Examples" }, { "code": null, "e": 3543, "s": 3499, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 3577, "s": 3543, "text": "Convert Double to Integer in Java" } ]
Python | Creating tensors using different functions in Tensorflow
21 Nov, 2018 Tensorflow is an open-source machine learning framework that is used for complex numerical computation. It was developed by the Google Brain team in Google. Tensorflow can train and run deep neural networks that can be used to develop several AI applications. What is a Tensor?A tensor can be described as a n-dimensional numerical array. A tensor can be called a generalized matrix. It could be a 0-D matrix (a single number), 1-D matrix (a vector), 2-D matrix or any higher dimensional structure. A tensor is identified by three parameters viz., rank, shape and size. The number of dimensions of the tensor is said to be its rank. The number of columns and rows that the tensor has, is said to be its shape. And, the data type assigned to the tensor’s elements is said to be its type. Importance of Tensor in Tensorflow:A tensor can be called as the central data type of Tensorflow. It is because tensors are the fundamental components of computation inside the Tensorflow framework. As the name suggests, Tensorflow is a framework that involves defining and running computations involving tensors. Let’s discuss all the different ways to create tensors in Tensorflow. Method #1: Creating tensor using the constant() function. The most popular function for creating tensors in Tensorflow is the constant() function. We need to give values or list of values as argument for creating tensor. If the values given are of type integer, then int32 is the default data type. And if the values given are of floating type, then float32 is the default data type. # Program to create tensor# using the constant() function import tensorflow as tf t1 = tf.constant([1, 2, 3])t2 = tf.constant([[1.1, 2.2, 3.3], [4, 5, 6]])t3 = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])t4 = tf.constant(["String_one", "String_two", "String_three"])t5 = tf.constant([1.2, 2.3, 3.4], tf.float16, [3], 'N3', False) sess = tf.Session()print(t1)print(sess.run(t1))print("\n") print(t2)print(sess.run(t2))print("\n") print(t3)print(sess.run(t3))print("\n") print(t4)print(sess.run(t4))print("\n") print(t5)print(sess.run(t5)) Output: Here, t1 is a one-dimensional tensor and has three integer values of datatype int32. t2 is a two-dimensional tensor and it contains floating-point values of datatype float32. t3 is a three-dimensional tensor and it contains integer values of datatype int32. t4 is a one-dimensional having three strings of datatype string. In t5, we have given it a name ‘N3’, specified the datatype as ‘float16’ and given the value of shape as 3. Since the shape value of t5 is 3, we cannot pass more than 3 elements in it. Otherwise, it will throw an error. Method #2: Creating tensor using the zeros() function. The zeros() function is used to create tensor with all of its elements as zero. The shape of the tensor is the only required argument. # Program to create tensor using the zeros() function import tensorflow as tf zero_int = tf.zeros([3])zero_float = tf.zeros([3], tf.int32, 'zero_float')zero_3d = tf.zeros([3, 3, 3], tf.int8, '3d') sess = tf.Session() print(zero_int)print(sess.run(zero_int))print("\n") print(zero_float)print(sess.run(zero_float))print("\n") print(zero_3d)print(sess.run(zero_3d)) Output: Method #3: Creating tensor using the “ones()” function. The ones() function basically does the same thing as the zeros() function, but the elements are one in this case instead of zero. # Program to create tensor using the ones() function import tensorflow as tf one_float = tf.ones([3])one_complex = tf.ones([2, 2], tf.complex64, 'complex_ones_tensor')one_3d = tf.ones([3, 3, 3], tf.int8, '3d') sess = tf.Session() print(one_float)print(sess.run(one_float))print("\n") print(one_complex)print(sess.run(one_complex))print("\n") print(one_3d)print(sess.run(one_3d)) Output: Method #4: Creating tensor using the fill() function. The fill() function is used to create tensors with all the elements in the tensor having the same value. The value of the element is to be passed as an argument and the datatype depends upon that value passed. # Program to create tensor using the fill() function import tensorflow as tf fill_1d = tf.fill([3], 10)fill_2d = tf.fill([2, 2], 6, '2d')fill_string = tf.fill([2, 2], "str", 'fill_tensor_string')fill_3d = tf.fill([3, 3, 3], 1.2, '3d') sess = tf.Session() print(fill_1d)print(sess.run(fill_1d))print("\n") print(fill_2d)print(sess.run(fill_2d))print("\n") print(fill_string)print(sess.run(fill_string))print("\n") print(fill_3d)print(sess.run(fill_3d)) Output: Method #5: Creating tensors using the linspace() function. The linspace() function is used in creating tensors in which we specify the starting value, ending value and the number of elements as arguments and the elements of the tensor changes its values based on the arguments. # Program to create tensor using the linspace() function import tensorflow as tf linspace_inc = tf.linspace(1.0, 10.0, 5, "linspace_inc")linspace_dec = tf.linspace(100.0, 10.0, 20, "linspace_dec") sess = tf.Session() print(linspace_inc)print(sess.run(linspace_inc))print("\n") print(linspace_dec)print(sess.run(linspace_dec)) Output: Method #6: Creating tensors using the range() function. The range() function is almost the same as the linspace() function. The only difference is that in the range() function, we specify a value called delta, that is used to calculate the successive elements of the tensor, instead of the number of elements in the linspace() function. # Program to create tensor using the range() function import tensorflow as tf range_inc = tf.range(10.0, 100.0, delta = 25.5)range_dec = tf.range(100.0, delta = 25.5, name ="range_dec") sess = tf.Session() print(range_inc)print(sess.run(range_inc))print("\n") print(range_dec)print(sess.run(range_dec)) Output: Tensorflow Machine Learning Python Technical Scripter Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Monte Carlo Tree Search (MCTS) Introduction to Recurrent Neural Network Markov Decision Process Support Vector Machine Algorithm DBSCAN Clustering in ML | Density based clustering Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Nov, 2018" }, { "code": null, "e": 288, "s": 28, "text": "Tensorflow is an open-source machine learning framework that is used for complex numerical computation. It was developed by the Google Brain team in Google. Tensorflow can train and run deep neural networks that can be used to develop several AI applications." }, { "code": null, "e": 815, "s": 288, "text": "What is a Tensor?A tensor can be described as a n-dimensional numerical array. A tensor can be called a generalized matrix. It could be a 0-D matrix (a single number), 1-D matrix (a vector), 2-D matrix or any higher dimensional structure. A tensor is identified by three parameters viz., rank, shape and size. The number of dimensions of the tensor is said to be its rank. The number of columns and rows that the tensor has, is said to be its shape. And, the data type assigned to the tensor’s elements is said to be its type." }, { "code": null, "e": 1129, "s": 815, "text": "Importance of Tensor in Tensorflow:A tensor can be called as the central data type of Tensorflow. It is because tensors are the fundamental components of computation inside the Tensorflow framework. As the name suggests, Tensorflow is a framework that involves defining and running computations involving tensors." }, { "code": null, "e": 1199, "s": 1129, "text": "Let’s discuss all the different ways to create tensors in Tensorflow." }, { "code": null, "e": 1257, "s": 1199, "text": "Method #1: Creating tensor using the constant() function." }, { "code": null, "e": 1583, "s": 1257, "text": "The most popular function for creating tensors in Tensorflow is the constant() function. We need to give values or list of values as argument for creating tensor. If the values given are of type integer, then int32 is the default data type. And if the values given are of floating type, then float32 is the default data type." }, { "code": "# Program to create tensor# using the constant() function import tensorflow as tf t1 = tf.constant([1, 2, 3])t2 = tf.constant([[1.1, 2.2, 3.3], [4, 5, 6]])t3 = tf.constant([[1, 2, 3], [4, 5, 6], [7, 8, 9]])t4 = tf.constant([\"String_one\", \"String_two\", \"String_three\"])t5 = tf.constant([1.2, 2.3, 3.4], tf.float16, [3], 'N3', False) sess = tf.Session()print(t1)print(sess.run(t1))print(\"\\n\") print(t2)print(sess.run(t2))print(\"\\n\") print(t3)print(sess.run(t3))print(\"\\n\") print(t4)print(sess.run(t4))print(\"\\n\") print(t5)print(sess.run(t5))", "e": 2130, "s": 1583, "text": null }, { "code": null, "e": 2138, "s": 2130, "text": "Output:" }, { "code": null, "e": 2736, "s": 2138, "text": "Here, t1 is a one-dimensional tensor and has three integer values of datatype int32. t2 is a two-dimensional tensor and it contains floating-point values of datatype float32. t3 is a three-dimensional tensor and it contains integer values of datatype int32. t4 is a one-dimensional having three strings of datatype string. In t5, we have given it a name ‘N3’, specified the datatype as ‘float16’ and given the value of shape as 3. Since the shape value of t5 is 3, we cannot pass more than 3 elements in it. Otherwise, it will throw an error. Method #2: Creating tensor using the zeros() function." }, { "code": null, "e": 2871, "s": 2736, "text": "The zeros() function is used to create tensor with all of its elements as zero. The shape of the tensor is the only required argument." }, { "code": "# Program to create tensor using the zeros() function import tensorflow as tf zero_int = tf.zeros([3])zero_float = tf.zeros([3], tf.int32, 'zero_float')zero_3d = tf.zeros([3, 3, 3], tf.int8, '3d') sess = tf.Session() print(zero_int)print(sess.run(zero_int))print(\"\\n\") print(zero_float)print(sess.run(zero_float))print(\"\\n\") print(zero_3d)print(sess.run(zero_3d))", "e": 3241, "s": 2871, "text": null }, { "code": null, "e": 3305, "s": 3241, "text": "Output: Method #3: Creating tensor using the “ones()” function." }, { "code": null, "e": 3435, "s": 3305, "text": "The ones() function basically does the same thing as the zeros() function, but the elements are one in this case instead of zero." }, { "code": "# Program to create tensor using the ones() function import tensorflow as tf one_float = tf.ones([3])one_complex = tf.ones([2, 2], tf.complex64, 'complex_ones_tensor')one_3d = tf.ones([3, 3, 3], tf.int8, '3d') sess = tf.Session() print(one_float)print(sess.run(one_float))print(\"\\n\") print(one_complex)print(sess.run(one_complex))print(\"\\n\") print(one_3d)print(sess.run(one_3d))", "e": 3820, "s": 3435, "text": null }, { "code": null, "e": 3882, "s": 3820, "text": "Output: Method #4: Creating tensor using the fill() function." }, { "code": null, "e": 4092, "s": 3882, "text": "The fill() function is used to create tensors with all the elements in the tensor having the same value. The value of the element is to be passed as an argument and the datatype depends upon that value passed." }, { "code": "# Program to create tensor using the fill() function import tensorflow as tf fill_1d = tf.fill([3], 10)fill_2d = tf.fill([2, 2], 6, '2d')fill_string = tf.fill([2, 2], \"str\", 'fill_tensor_string')fill_3d = tf.fill([3, 3, 3], 1.2, '3d') sess = tf.Session() print(fill_1d)print(sess.run(fill_1d))print(\"\\n\") print(fill_2d)print(sess.run(fill_2d))print(\"\\n\") print(fill_string)print(sess.run(fill_string))print(\"\\n\") print(fill_3d)print(sess.run(fill_3d))", "e": 4553, "s": 4092, "text": null }, { "code": null, "e": 4562, "s": 4553, "text": "Output: " }, { "code": null, "e": 4621, "s": 4562, "text": "Method #5: Creating tensors using the linspace() function." }, { "code": null, "e": 4840, "s": 4621, "text": "The linspace() function is used in creating tensors in which we specify the starting value, ending value and the number of elements as arguments and the elements of the tensor changes its values based on the arguments." }, { "code": "# Program to create tensor using the linspace() function import tensorflow as tf linspace_inc = tf.linspace(1.0, 10.0, 5, \"linspace_inc\")linspace_dec = tf.linspace(100.0, 10.0, 20, \"linspace_dec\") sess = tf.Session() print(linspace_inc)print(sess.run(linspace_inc))print(\"\\n\") print(linspace_dec)print(sess.run(linspace_dec))", "e": 5173, "s": 4840, "text": null }, { "code": null, "e": 5237, "s": 5173, "text": "Output: Method #6: Creating tensors using the range() function." }, { "code": null, "e": 5518, "s": 5237, "text": "The range() function is almost the same as the linspace() function. The only difference is that in the range() function, we specify a value called delta, that is used to calculate the successive elements of the tensor, instead of the number of elements in the linspace() function." }, { "code": "# Program to create tensor using the range() function import tensorflow as tf range_inc = tf.range(10.0, 100.0, delta = 25.5)range_dec = tf.range(100.0, delta = 25.5, name =\"range_dec\") sess = tf.Session() print(range_inc)print(sess.run(range_inc))print(\"\\n\") print(range_dec)print(sess.run(range_dec))", "e": 5827, "s": 5518, "text": null }, { "code": null, "e": 5835, "s": 5827, "text": "Output:" }, { "code": null, "e": 5846, "s": 5835, "text": "Tensorflow" }, { "code": null, "e": 5863, "s": 5846, "text": "Machine Learning" }, { "code": null, "e": 5870, "s": 5863, "text": "Python" }, { "code": null, "e": 5889, "s": 5870, "text": "Technical Scripter" }, { "code": null, "e": 5906, "s": 5889, "text": "Machine Learning" }, { "code": null, "e": 6004, "s": 5906, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6040, "s": 6004, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 6081, "s": 6040, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 6105, "s": 6081, "text": "Markov Decision Process" }, { "code": null, "e": 6138, "s": 6105, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 6189, "s": 6138, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 6217, "s": 6189, "text": "Read JSON file using Python" }, { "code": null, "e": 6267, "s": 6217, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 6289, "s": 6267, "text": "Python map() function" } ]
Exponential Distribution in R Programming – dexp(), pexp(), qexp(), and rexp() Functions
08 Jul, 2020 The exponential distribution in R Language is the probability distribution of the time between events in a Poisson point process, i.e., a process in which events occur continuously and independently at a constant average rate. It is a particular case of the gamma distribution. In R, there are 4 built-in functions to generate exponential distribution: dexp()dexp(x_dexp, rate) dexp(x_dexp, rate) pexp()pexp(x_pexp, rate ) pexp(x_pexp, rate ) qexp()qexp(x_qexp, rate) qexp(x_qexp, rate) rexp()rexp(N, rate ) rexp(N, rate ) where, x: represents x-values for exp function .rate: represents the shapex.N: Specify sample size dexp() function returns the corresponding values of the exponential density for an input vector of quantiles. Syntax: dexp(x_dexp, rate) Example: # R program to illustrate# exponential distribution# Specify x-valuesx_dexp <- seq(1, 10, by = 0.1) # Apply dexp() function y_dexp <- dexp(x_dexp, rate = 5) # Plot dexp values plot(y_dexp) Output: pexp() function returns the corresponding values of the exponential cumulative distribution function for an input vector of quantiles. Syntax: pexp(x_pexp, rate ) Example: # R program to illustrate# exponential distribution # Specify x-valuesx_pexp <- seq(1, 10, by = 0.2) # Apply pexp() functiony_pexp <- pexp(x_pexp, rate = 1) # Plot values plot(y_pexp) Output : qexp() function gives the possibility, we can use the qexp function to return the corresponding values of the quantile function. Syntax: qexp(x_qexp, rate) Example: # R program to illustrate# exponential distribution # Specify x-values x_qexp <- seq(0, 1, by = 0.2) # Apply qexp() functiony_qexp <- qexp(x_qexp, rate = 1) # Plot values plot(y_qexp) Output: rexp() function is used to simulate a set of random numbers drawn from the exponential distribution. Syntax: rexp(N, rate ) Example: # R program to illustrate# exponential distribution # Set seed for reproducibilityset.seed(500) # Specify size N <- 100 # Draw exp distributed valuesy_rexp <- rexp(N, rate = 1) # Plot exp density hist(y_rexp, breaks = 50, main = "") Output : R Statistics-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? Printing Output of an R Program How to Change Axis Scales in R Plots? R - if statement
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jul, 2020" }, { "code": null, "e": 306, "s": 28, "text": "The exponential distribution in R Language is the probability distribution of the time between events in a Poisson point process, i.e., a process in which events occur continuously and independently at a constant average rate. It is a particular case of the gamma distribution." }, { "code": null, "e": 381, "s": 306, "text": "In R, there are 4 built-in functions to generate exponential distribution:" }, { "code": null, "e": 407, "s": 381, "text": "dexp()dexp(x_dexp, rate) " }, { "code": null, "e": 427, "s": 407, "text": "dexp(x_dexp, rate) " }, { "code": null, "e": 453, "s": 427, "text": "pexp()pexp(x_pexp, rate )" }, { "code": null, "e": 473, "s": 453, "text": "pexp(x_pexp, rate )" }, { "code": null, "e": 498, "s": 473, "text": "qexp()qexp(x_qexp, rate)" }, { "code": null, "e": 517, "s": 498, "text": "qexp(x_qexp, rate)" }, { "code": null, "e": 538, "s": 517, "text": "rexp()rexp(N, rate )" }, { "code": null, "e": 553, "s": 538, "text": "rexp(N, rate )" }, { "code": null, "e": 560, "s": 553, "text": "where," }, { "code": null, "e": 652, "s": 560, "text": "x: represents x-values for exp function .rate: represents the shapex.N: Specify sample size" }, { "code": null, "e": 762, "s": 652, "text": "dexp() function returns the corresponding values of the exponential density for an input vector of quantiles." }, { "code": null, "e": 770, "s": 762, "text": "Syntax:" }, { "code": null, "e": 789, "s": 770, "text": "dexp(x_dexp, rate)" }, { "code": null, "e": 798, "s": 789, "text": "Example:" }, { "code": "# R program to illustrate# exponential distribution# Specify x-valuesx_dexp <- seq(1, 10, by = 0.1) # Apply dexp() function y_dexp <- dexp(x_dexp, rate = 5) # Plot dexp values plot(y_dexp)", "e": 1028, "s": 798, "text": null }, { "code": null, "e": 1036, "s": 1028, "text": "Output:" }, { "code": null, "e": 1171, "s": 1036, "text": "pexp() function returns the corresponding values of the exponential cumulative distribution function for an input vector of quantiles." }, { "code": null, "e": 1179, "s": 1171, "text": "Syntax:" }, { "code": null, "e": 1199, "s": 1179, "text": "pexp(x_pexp, rate )" }, { "code": null, "e": 1208, "s": 1199, "text": "Example:" }, { "code": "# R program to illustrate# exponential distribution # Specify x-valuesx_pexp <- seq(1, 10, by = 0.2) # Apply pexp() functiony_pexp <- pexp(x_pexp, rate = 1) # Plot values plot(y_pexp) ", "e": 1502, "s": 1208, "text": null }, { "code": null, "e": 1511, "s": 1502, "text": "Output :" }, { "code": null, "e": 1640, "s": 1511, "text": "qexp() function gives the possibility, we can use the qexp function to return the corresponding values of the quantile function." }, { "code": null, "e": 1648, "s": 1640, "text": "Syntax:" }, { "code": null, "e": 1667, "s": 1648, "text": "qexp(x_qexp, rate)" }, { "code": null, "e": 1676, "s": 1667, "text": "Example:" }, { "code": "# R program to illustrate# exponential distribution # Specify x-values x_qexp <- seq(0, 1, by = 0.2) # Apply qexp() functiony_qexp <- qexp(x_qexp, rate = 1) # Plot values plot(y_qexp) ", "e": 1943, "s": 1676, "text": null }, { "code": null, "e": 1951, "s": 1943, "text": "Output:" }, { "code": null, "e": 2052, "s": 1951, "text": "rexp() function is used to simulate a set of random numbers drawn from the exponential distribution." }, { "code": null, "e": 2060, "s": 2052, "text": "Syntax:" }, { "code": null, "e": 2075, "s": 2060, "text": "rexp(N, rate )" }, { "code": null, "e": 2084, "s": 2075, "text": "Example:" }, { "code": "# R program to illustrate# exponential distribution # Set seed for reproducibilityset.seed(500) # Specify size N <- 100 # Draw exp distributed valuesy_rexp <- rexp(N, rate = 1) # Plot exp density hist(y_rexp, breaks = 50, main = \"\")", "e": 2332, "s": 2084, "text": null }, { "code": null, "e": 2341, "s": 2332, "text": "Output :" }, { "code": null, "e": 2363, "s": 2341, "text": "R Statistics-Function" }, { "code": null, "e": 2374, "s": 2363, "text": "R Language" }, { "code": null, "e": 2472, "s": 2374, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2524, "s": 2472, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 2582, "s": 2524, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 2634, "s": 2582, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2692, "s": 2634, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2724, "s": 2692, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 2759, "s": 2724, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2803, "s": 2759, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 2835, "s": 2803, "text": "Printing Output of an R Program" }, { "code": null, "e": 2873, "s": 2835, "text": "How to Change Axis Scales in R Plots?" } ]
How to use Collapse Component in ReactJS ?
22 Feb, 2021 Collapse Component adds a Collapse animation to a child element or component in which it vertically expands from the top of the child element. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Collapse Component in ReactJS using the following approach. Creating React Application And Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command. npm install @material-ui/core Project Structure: Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react';import FormControlLabel from '@material-ui/core/FormControlLabel';import Paper from '@material-ui/core/Paper';import Switch from '@material-ui/core/Switch';import Collapse from '@material-ui/core/Collapse'; export default function App() { const [isChecked, setIsChecked] = React.useState(false); return ( <div style={{ display: 'block', padding: 30 }}> <h4>How to use Collapse Component in ReactJS?</h4> <FormControlLabel control={<Switch checked={isChecked} onChange={() => { setIsChecked((prev) => !prev); }} />} label="Toggle me to see Collapse Effect" /> <div style={{ display: 'flex' }}> <Collapse in={isChecked}> <Paper elevation={5} style={{ margin: 5 }} > <svg style={{ width: 100, height: 100 }}> <polygon points="0,80 45,00, 80,70" style={{ fill: 'orange', stroke: 'dimgrey', strokeWidth: 1, }} /> </svg> </Paper> </Collapse> </div> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. Reference: https://material-ui.com/components/transitions/#collapse Material-UI React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to do crud operations in ReactJS ? How to install bootstrap in React.js ? How to Use Bootstrap with React? 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? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Feb, 2021" }, { "code": null, "e": 339, "s": 28, "text": "Collapse Component adds a Collapse animation to a child element or component in which it vertically expands from the top of the child element. Material UI for React has this component available for us, and it is very easy to integrate. We can use the Collapse Component in ReactJS using the following approach." }, { "code": null, "e": 389, "s": 339, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 453, "s": 389, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 485, "s": 453, "text": "npx create-react-app foldername" }, { "code": null, "e": 585, "s": 485, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 599, "s": 585, "text": "cd foldername" }, { "code": null, "e": 708, "s": 599, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command." }, { "code": null, "e": 738, "s": 708, "text": "npm install @material-ui/core" }, { "code": null, "e": 758, "s": 738, "text": "Project Structure: " }, { "code": null, "e": 776, "s": 758, "text": "Project Structure" }, { "code": null, "e": 907, "s": 776, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. " }, { "code": null, "e": 914, "s": 907, "text": "App.js" }, { "code": "import React from 'react';import FormControlLabel from '@material-ui/core/FormControlLabel';import Paper from '@material-ui/core/Paper';import Switch from '@material-ui/core/Switch';import Collapse from '@material-ui/core/Collapse'; export default function App() { const [isChecked, setIsChecked] = React.useState(false); return ( <div style={{ display: 'block', padding: 30 }}> <h4>How to use Collapse Component in ReactJS?</h4> <FormControlLabel control={<Switch checked={isChecked} onChange={() => { setIsChecked((prev) => !prev); }} />} label=\"Toggle me to see Collapse Effect\" /> <div style={{ display: 'flex' }}> <Collapse in={isChecked}> <Paper elevation={5} style={{ margin: 5 }} > <svg style={{ width: 100, height: 100 }}> <polygon points=\"0,80 45,00, 80,70\" style={{ fill: 'orange', stroke: 'dimgrey', strokeWidth: 1, }} /> </svg> </Paper> </Collapse> </div> </div> );}", "e": 2033, "s": 914, "text": null }, { "code": null, "e": 2146, "s": 2033, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 2156, "s": 2146, "text": "npm start" }, { "code": null, "e": 2255, "s": 2156, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 2323, "s": 2255, "text": "Reference: https://material-ui.com/components/transitions/#collapse" }, { "code": null, "e": 2335, "s": 2323, "text": "Material-UI" }, { "code": null, "e": 2351, "s": 2335, "text": "React-Questions" }, { "code": null, "e": 2359, "s": 2351, "text": "ReactJS" }, { "code": null, "e": 2376, "s": 2359, "text": "Web Technologies" }, { "code": null, "e": 2474, "s": 2376, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2512, "s": 2474, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 2539, "s": 2512, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 2578, "s": 2539, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 2617, "s": 2578, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 2650, "s": 2617, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 2683, "s": 2650, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2745, "s": 2683, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2806, "s": 2745, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2856, "s": 2806, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Print concentric rectangular pattern in a 2d matrix
22 Nov, 2021 Given a positive integer n, print the matrix filled with rectangle pattern as shown below: a a a a a a b b b a a b c b a a b b b a a a a a a where a = n, b = n – 1,c = n – 2 and so on. Examples: Input : n = 4 Output : 4 4 4 4 4 4 4 4 3 3 3 3 3 4 4 3 2 2 2 3 4 4 3 2 1 2 3 4 4 3 2 2 2 3 4 4 3 3 3 3 3 4 4 4 4 4 4 4 4 Input : n = 3 Output : 3 3 3 3 3 3 2 2 2 3 3 2 1 2 3 3 2 2 2 3 3 3 3 3 3 For the given n, the number of rows or columns to be printed will be 2*n – 1. We will print the matrix in two parts. We will first print upper half from rows from 0 to floor((2*n – 1)/2) and then second half from floor((2*n – 1)/2) + 1 to 2*n – 2. Now for each row, we will print it in three parts. First part is decreasing sequence which will start from n and decrease by 1 in each iteration. The number of iteration will be equal to row number, the second part is a constant sequence where constant is n – i and it will be print 2*n – 1 – 2 * row number, and the third part is increasing sequence which is nothing but opposite of the first sequence. For lower half, observe, it is a mirror image of upper half (excluding middle row). So, simply run a loop of the upper half from (2*n – 1)/2 to 0. Below is the basic implementation of this approach: C++ Java Python3 C# PHP Javascript // C++ program for printing// the rectangular pattern#include <bits/stdc++.h>using namespace std; // Function to print the patternvoid printPattern(int n){ // number of rows and columns to be printed int s = 2 * n - 1; // Upper Half for (int i = 0; i < (s / 2) + 1; i++) { int m = n; // Decreasing part for (int j = 0; j < i; j++) { cout << m << " "; m--; } // Constant Part for (int k = 0; k < s - 2 * i; k++) { cout << n - i << " "; } // Increasing part. m = n - i + 1; for (int l = 0; l < i; l++) { cout << m << " "; m++; } cout << endl; } // Lower Half for (int i = s / 2 - 1; i >= 0; i--) { // Decreasing Part int m = n; for (int j = 0; j < i; j++) { cout << m << " "; m--; } // Constant Part. for (int k = 0; k < s - 2 * i; k++) { cout << n - i << " "; } // Decreasing Part m = n - i + 1; for (int l = 0; l < i; l++) { cout << m << " "; m++; } cout << endl; }}// Driven Programint main(){ int n = 3; printPattern(n); return 0;} // Java program for printing// the rectangular patternimport java.io.*; class GFG{ // Function to// print the patternstatic void printPattern(int n){ // number of rows and // columns to be printed int s = 2 * n - 1; // Upper Half for (int i = 0; i < (s / 2) + 1; i++) { int m = n; // Decreasing part for (int j = 0; j < i; j++) { System.out.print(m + " "); m--; } // Constant Part for (int k = 0; k < s - 2 * i; k++) { System.out.print(n - i + " "); } // Increasing part. m = n - i + 1; for (int l = 0; l < i; l++) { System.out.print(m + " "); m++; } System.out.println(); } // Lower Half for (int i = s / 2 - 1; i >= 0; i--) { // Decreasing Part int m = n; for (int j = 0; j < i; j++) { System.out.print(m + " "); m--; } // Constant Part. for (int k = 0; k < s - 2 * i; k++) { System.out.print(n - i + " "); } // Decreasing Part m = n - i + 1; for (int l = 0; l < i; l++) { System.out.print(m + " "); m++; } System.out.println(); }}// Driver Codepublic static void main (String[] args){ int n = 3; printPattern(n);}} // This code is contributed// by anuj_67. # Python3 program for printing# the rectangular pattern # Function to print the patterndef printPattern(n) : # number of rows and columns to be printed s = 2 * n - 1 # Upper Half for i in range(0, int(s / 2) + 1): m = n # Decreasing part for j in range(0, i): print(m ,end= " " ) m-=1 # Constant Part for k in range(0, s - 2 * i): print(n-i ,end= " " ) # Increasing part. m = n - i + 1 for l in range(0, i): print(m ,end= " " ) m+=1 print("") # Lower Half for i in range(int(s / 2),-1,-1): # Decreasing Part m = n for j in range(0, i): print(m ,end= " " ) m-=1 # Constant Part. for k in range(0, s - 2 * i): print(n-i ,end= " " ) # Decreasing Part m = n - i + 1 for l in range(0, i): print(m ,end= " " ) m+=1 print("") # Driven Programif __name__=='__main__': n = 3 printPattern(n) # this code is contributed by Smitha Dinesh# Semwal // C# program for printing// the rectangular patternusing System; class GFG{ // Function to// print the patternstatic void printPattern(int n){ // number of rows and // columns to be printed int s = 2 * n - 1; // Upper Half for (int i = 0; i < (s / 2) + 1; i++) { int m = n; // Decreasing part for (int j = 0; j < i; j++) { Console.Write(m + " "); m--; } // Constant Part for (int k = 0; k < s - 2 * i; k++) { Console.Write(n - i + " "); } // Increasing part. m = n - i + 1; for (int l = 0; l < i; l++) { Console.Write(m + " "); m++; } Console.WriteLine(); } // Lower Half for (int i = s / 2 - 1; i >= 0; i--) { // Decreasing Part int m = n; for (int j = 0; j < i; j++) { Console.Write(m + " "); m--; } // Constant Part. for (int k = 0; k < s - 2 * i; k++) { Console.Write(n - i + " "); } // Decreasing Part m = n - i + 1; for (int l = 0; l < i; l++) { Console.Write(m + " "); m++; } Console.WriteLine(); }}// Driver Codepublic static void Main (){ int n = 3; printPattern(n);}} // This code is contributed// by anuj_67. <?php// PHP program for printing// the rectangular pattern // Function to print the patternfunction printPattern($n){ // number of rows and columns // to be printed $s = 2 * $n - 1; // Upper Half for ($i = 0; $i < (int)($s / 2) + 1; $i++) { $m = $n; // Decreasing part for ($j = 0; $j < $i; $j++) { echo $m , " "; $m--; } // Constant Part for ($k = 0; $k < $s - 2 * $i; $k++) { echo ($n - $i) , " "; } // Increasing part. $m = $n - $i + 1; for ($l = 0; $l < $i; $l++) { echo $m , " "; $m++; } echo "\n"; } // Lower Half for ($i = (int)($s / 2 - 1); $i >= 0; $i--) { // Decreasing Part $m = $n; for ($j = 0; $j < $i; $j++) { echo $m, " "; $m--; } // Constant Part. for ($k = 0; $k < $s - 2 * $i; $k++) { echo $n - $i , " "; } // Decreasing Part $m = $n - $i + 1; for ($l = 0; $l < $i; $l++) { echo $m , " "; $m++; } echo "\n"; }} // Driver Code$n = 3;printPattern($n); // This code is contributed// by Sach_Code ?> <script> // Javascript program for printing// the rectangular pattern // Function to// print the patternfunction printPattern(n){ // number of rows and // columns to be printed let s = 2 * n - 1; // Upper Half for (let i = 0; i < Math.floor(s / 2) + 1; i++) { let m = n; // Decreasing part for (let j = 0; j < i; j++) { document.write(m + " "); m--; } // Constant Part for (let k = 0; k < s - 2 * i; k++) { document.write(n - i + " "); } // Increasing part. m = n - i + 1; for (let l = 0; l < i; l++) { document.write(m + " "); m++; } document.write("<br/>"); } // Lower Half for (let i = Math.floor(s / 2) - 1; i >= 0; i--) { // Decreasing Part let m = n; for (let j = 0; j < i; j++) { document.write(m + " "); m--; } // Constant Part. for (let k = 0; k < s - 2 * i; k++) { document.write(n - i + " "); } // Decreasing Part m = n - i + 1; for (let l = 0; l < i; l++) { document.write(m + " "); m++; } document.write("<br/>"); }} // Driver Code let n = 3; printPattern(n); </script> Output 3 3 3 3 3 3 2 2 2 3 3 2 1 2 3 3 2 2 2 3 3 3 3 3 3 Another Approach: C++ Java Python3 C# PHP Javascript // C++ program for printing// the rectangular pattern#include<bits/stdc++.h>using namespace std; // Function to print the patternvoid printPattern(int n){ int arraySize = n * 2 - 1; int result[arraySize][arraySize]; // Fill the values for(int i = 0; i < arraySize; i++) { for(int j = 0; j < arraySize; j++) { if(abs(i - arraySize / 2) > abs(j - arraySize / 2)) result[i][j] = abs(i - arraySize / 2) + 1; else result[i][j] = (abs(j-arraySize / 2) + 1); } } // Print the array for(int i = 0; i < arraySize; i++) { for(int j = 0; j < arraySize; j++) { cout << result[i][j] << " "; } cout << endl; }} // Driver Codeint main(){ int n = 3; printPattern(n); return 0;} // This code is contributed// by Rajput-Ji. // Java program for printing// the rectangular patternimport java.io.*; class GFG{ // Function to print the patternstatic void printPattern(int n){ int arraySize = n * 2 - 1; int[][] result = new int[arraySize][arraySize]; //Fill the values for(int i = 0; i < arraySize; i++) { for(int j = 0; j < arraySize; j++) { result[i][j] = Math.max(Math.abs(i-arraySize/2), Math.abs(j-arraySize/2))+1; } } //Print the array for(int i = 0; i < arraySize; i++) { for(int j = 0; j < arraySize; j++) { System.out.print(result[i][j]); } System.out.println(); }}// Driver Codepublic static void main (String[] args){ int n = 3; printPattern(n);}} // This code is contributed// by MohitSharma23. # Python3 program for printing# the rectangular pattern # Function to print the patterndef printPattern(n): arraySize = n * 2 - 1; result = [[0 for x in range(arraySize)] for y in range(arraySize)]; # Fill the values for i in range(arraySize): for j in range(arraySize): if(abs(i - (arraySize // 2)) > abs(j - (arraySize // 2))): result[i][j] = abs(i - (arraySize // 2)) + 1; else: result[i][j] = abs(j - (arraySize // 2)) + 1; # Print the array for i in range(arraySize): for j in range(arraySize): print(result[i][j], end = " "); print(""); # Driver Coden = 3; printPattern(n); # This code is contributed by mits // C# program for printing// the rectangular patternusing System; class GFG{ // Function to print the patternstatic void printPattern(int n){ int arraySize = n * 2 - 1; int[,] result = new int[arraySize,arraySize]; // Fill the values for(int i = 0; i < arraySize; i++) { for(int j = 0; j < arraySize; j++) { result[i,j] = Math.Max(Math.Abs(i-arraySize/2), Math.Abs(j-arraySize/2))+1; } } // Print the array for(int i = 0; i < arraySize; i++) { for(int j = 0; j < arraySize; j++) { Console.Write(result[i,j]+" "); } Console.WriteLine(); }} // Driver Codepublic static void Main (String[] args){ int n = 3; printPattern(n);}} // This code has been contributed by 29AjayKumar <?php// PHP program for printing// the rectangular pattern // Function to print the patternfunction printPattern($n){ $arraySize = $n * 2 - 1; $result=array_fill(0,$arraySize,array_fill(0,$arraySize,0)); // Fill the values for($i = 0; $i < $arraySize; $i++) { for($j = 0; $j < $arraySize; $j++) { if(abs($i - (int)($arraySize / 2)) > abs($j - (int)($arraySize / 2))) $result[$i][$j] = abs($i - (int)($arraySize / 2)) + 1; else $result[$i][$j] = (abs($j-(int) ($arraySize / 2)) + 1); } } // Print the array for($i = 0; $i < $arraySize; $i++) { for($j = 0; $j < $arraySize; $j++) { echo $result[$i][$j]." "; } echo "\n"; }} // Driver Code $n = 3; printPattern($n); // This code is contributed by mits?> <script> // Javascript program for printing the rectangular pattern // Function to print the pattern function printPattern(n) { let arraySize = n * 2 - 1; let result = new Array(arraySize); // Fill the values for(let i = 0; i < arraySize; i++) { result[i] = new Array(arraySize); for(let j = 0; j < arraySize; j++) { result[i][j] = Math.max(Math.abs(i-parseInt(arraySize/2, 10)), Math.abs(j-parseInt(arraySize/2, 10)))+1; } } // Print the array for(let i = 0; i < arraySize; i++) { for(let j = 0; j < arraySize; j++) { document.write(result[i][j] + " "); } document.write("</br>"); } } let n = 3; printPattern(n); // This code is contributed by divyeshrabadiya07.</script> Output 3 3 3 3 3 3 2 2 2 3 3 2 1 2 3 3 2 2 2 3 3 3 3 3 3 vt_m Smitha Dinesh Semwal Sach_Code MohitSharma23 Rajput-Ji 29AjayKumar Mithun Kumar avijitmondal1998 divyeshrabadiya07 arorakashish0911 pattern-printing Matrix pattern-printing Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unique paths in a Grid with Obstacles Find median in row wise sorted matrix Traverse a given Matrix using Recursion Zigzag (or diagonal) traversal of Matrix A Boolean Matrix Question Common elements in all rows of a given matrix Find a specific pair in Matrix Python program to add two Matrices Flood fill Algorithm - how to implement fill() in paint? Find shortest safe route in a path with landmines
[ { "code": null, "e": 54, "s": 26, "text": "\n22 Nov, 2021" }, { "code": null, "e": 239, "s": 54, "text": "Given a positive integer n, print the matrix filled with rectangle pattern as shown below: a a a a a a b b b a a b c b a a b b b a a a a a a where a = n, b = n – 1,c = n – 2 and so on." }, { "code": null, "e": 250, "s": 239, "text": "Examples: " }, { "code": null, "e": 457, "s": 250, "text": "Input : n = 4\nOutput :\n4 4 4 4 4 4 4 \n4 3 3 3 3 3 4 \n4 3 2 2 2 3 4 \n4 3 2 1 2 3 4 \n4 3 2 2 2 3 4 \n4 3 3 3 3 3 4 \n4 4 4 4 4 4 4 \n\nInput : n = 3\nOutput :\n3 3 3 3 3 \n3 2 2 2 3 \n3 2 1 2 3 \n3 2 2 2 3 \n3 3 3 3 3 " }, { "code": null, "e": 1256, "s": 457, "text": "For the given n, the number of rows or columns to be printed will be 2*n – 1. We will print the matrix in two parts. We will first print upper half from rows from 0 to floor((2*n – 1)/2) and then second half from floor((2*n – 1)/2) + 1 to 2*n – 2. Now for each row, we will print it in three parts. First part is decreasing sequence which will start from n and decrease by 1 in each iteration. The number of iteration will be equal to row number, the second part is a constant sequence where constant is n – i and it will be print 2*n – 1 – 2 * row number, and the third part is increasing sequence which is nothing but opposite of the first sequence. For lower half, observe, it is a mirror image of upper half (excluding middle row). So, simply run a loop of the upper half from (2*n – 1)/2 to 0." }, { "code": null, "e": 1309, "s": 1256, "text": "Below is the basic implementation of this approach: " }, { "code": null, "e": 1313, "s": 1309, "text": "C++" }, { "code": null, "e": 1318, "s": 1313, "text": "Java" }, { "code": null, "e": 1326, "s": 1318, "text": "Python3" }, { "code": null, "e": 1329, "s": 1326, "text": "C#" }, { "code": null, "e": 1333, "s": 1329, "text": "PHP" }, { "code": null, "e": 1344, "s": 1333, "text": "Javascript" }, { "code": "// C++ program for printing// the rectangular pattern#include <bits/stdc++.h>using namespace std; // Function to print the patternvoid printPattern(int n){ // number of rows and columns to be printed int s = 2 * n - 1; // Upper Half for (int i = 0; i < (s / 2) + 1; i++) { int m = n; // Decreasing part for (int j = 0; j < i; j++) { cout << m << \" \"; m--; } // Constant Part for (int k = 0; k < s - 2 * i; k++) { cout << n - i << \" \"; } // Increasing part. m = n - i + 1; for (int l = 0; l < i; l++) { cout << m << \" \"; m++; } cout << endl; } // Lower Half for (int i = s / 2 - 1; i >= 0; i--) { // Decreasing Part int m = n; for (int j = 0; j < i; j++) { cout << m << \" \"; m--; } // Constant Part. for (int k = 0; k < s - 2 * i; k++) { cout << n - i << \" \"; } // Decreasing Part m = n - i + 1; for (int l = 0; l < i; l++) { cout << m << \" \"; m++; } cout << endl; }}// Driven Programint main(){ int n = 3; printPattern(n); return 0;}", "e": 2607, "s": 1344, "text": null }, { "code": "// Java program for printing// the rectangular patternimport java.io.*; class GFG{ // Function to// print the patternstatic void printPattern(int n){ // number of rows and // columns to be printed int s = 2 * n - 1; // Upper Half for (int i = 0; i < (s / 2) + 1; i++) { int m = n; // Decreasing part for (int j = 0; j < i; j++) { System.out.print(m + \" \"); m--; } // Constant Part for (int k = 0; k < s - 2 * i; k++) { System.out.print(n - i + \" \"); } // Increasing part. m = n - i + 1; for (int l = 0; l < i; l++) { System.out.print(m + \" \"); m++; } System.out.println(); } // Lower Half for (int i = s / 2 - 1; i >= 0; i--) { // Decreasing Part int m = n; for (int j = 0; j < i; j++) { System.out.print(m + \" \"); m--; } // Constant Part. for (int k = 0; k < s - 2 * i; k++) { System.out.print(n - i + \" \"); } // Decreasing Part m = n - i + 1; for (int l = 0; l < i; l++) { System.out.print(m + \" \"); m++; } System.out.println(); }}// Driver Codepublic static void main (String[] args){ int n = 3; printPattern(n);}} // This code is contributed// by anuj_67.", "e": 4092, "s": 2607, "text": null }, { "code": "# Python3 program for printing# the rectangular pattern # Function to print the patterndef printPattern(n) : # number of rows and columns to be printed s = 2 * n - 1 # Upper Half for i in range(0, int(s / 2) + 1): m = n # Decreasing part for j in range(0, i): print(m ,end= \" \" ) m-=1 # Constant Part for k in range(0, s - 2 * i): print(n-i ,end= \" \" ) # Increasing part. m = n - i + 1 for l in range(0, i): print(m ,end= \" \" ) m+=1 print(\"\") # Lower Half for i in range(int(s / 2),-1,-1): # Decreasing Part m = n for j in range(0, i): print(m ,end= \" \" ) m-=1 # Constant Part. for k in range(0, s - 2 * i): print(n-i ,end= \" \" ) # Decreasing Part m = n - i + 1 for l in range(0, i): print(m ,end= \" \" ) m+=1 print(\"\") # Driven Programif __name__=='__main__': n = 3 printPattern(n) # this code is contributed by Smitha Dinesh# Semwal", "e": 5264, "s": 4092, "text": null }, { "code": "// C# program for printing// the rectangular patternusing System; class GFG{ // Function to// print the patternstatic void printPattern(int n){ // number of rows and // columns to be printed int s = 2 * n - 1; // Upper Half for (int i = 0; i < (s / 2) + 1; i++) { int m = n; // Decreasing part for (int j = 0; j < i; j++) { Console.Write(m + \" \"); m--; } // Constant Part for (int k = 0; k < s - 2 * i; k++) { Console.Write(n - i + \" \"); } // Increasing part. m = n - i + 1; for (int l = 0; l < i; l++) { Console.Write(m + \" \"); m++; } Console.WriteLine(); } // Lower Half for (int i = s / 2 - 1; i >= 0; i--) { // Decreasing Part int m = n; for (int j = 0; j < i; j++) { Console.Write(m + \" \"); m--; } // Constant Part. for (int k = 0; k < s - 2 * i; k++) { Console.Write(n - i + \" \"); } // Decreasing Part m = n - i + 1; for (int l = 0; l < i; l++) { Console.Write(m + \" \"); m++; } Console.WriteLine(); }}// Driver Codepublic static void Main (){ int n = 3; printPattern(n);}} // This code is contributed// by anuj_67.", "e": 6710, "s": 5264, "text": null }, { "code": "<?php// PHP program for printing// the rectangular pattern // Function to print the patternfunction printPattern($n){ // number of rows and columns // to be printed $s = 2 * $n - 1; // Upper Half for ($i = 0; $i < (int)($s / 2) + 1; $i++) { $m = $n; // Decreasing part for ($j = 0; $j < $i; $j++) { echo $m , \" \"; $m--; } // Constant Part for ($k = 0; $k < $s - 2 * $i; $k++) { echo ($n - $i) , \" \"; } // Increasing part. $m = $n - $i + 1; for ($l = 0; $l < $i; $l++) { echo $m , \" \"; $m++; } echo \"\\n\"; } // Lower Half for ($i = (int)($s / 2 - 1); $i >= 0; $i--) { // Decreasing Part $m = $n; for ($j = 0; $j < $i; $j++) { echo $m, \" \"; $m--; } // Constant Part. for ($k = 0; $k < $s - 2 * $i; $k++) { echo $n - $i , \" \"; } // Decreasing Part $m = $n - $i + 1; for ($l = 0; $l < $i; $l++) { echo $m , \" \"; $m++; } echo \"\\n\"; }} // Driver Code$n = 3;printPattern($n); // This code is contributed// by Sach_Code ?>", "e": 8013, "s": 6710, "text": null }, { "code": "<script> // Javascript program for printing// the rectangular pattern // Function to// print the patternfunction printPattern(n){ // number of rows and // columns to be printed let s = 2 * n - 1; // Upper Half for (let i = 0; i < Math.floor(s / 2) + 1; i++) { let m = n; // Decreasing part for (let j = 0; j < i; j++) { document.write(m + \" \"); m--; } // Constant Part for (let k = 0; k < s - 2 * i; k++) { document.write(n - i + \" \"); } // Increasing part. m = n - i + 1; for (let l = 0; l < i; l++) { document.write(m + \" \"); m++; } document.write(\"<br/>\"); } // Lower Half for (let i = Math.floor(s / 2) - 1; i >= 0; i--) { // Decreasing Part let m = n; for (let j = 0; j < i; j++) { document.write(m + \" \"); m--; } // Constant Part. for (let k = 0; k < s - 2 * i; k++) { document.write(n - i + \" \"); } // Decreasing Part m = n - i + 1; for (let l = 0; l < i; l++) { document.write(m + \" \"); m++; } document.write(\"<br/>\"); }} // Driver Code let n = 3; printPattern(n); </script>", "e": 9448, "s": 8013, "text": null }, { "code": null, "e": 9457, "s": 9448, "text": "Output " }, { "code": null, "e": 9513, "s": 9457, "text": "3 3 3 3 3 \n3 2 2 2 3 \n3 2 1 2 3 \n3 2 2 2 3 \n3 3 3 3 3 " }, { "code": null, "e": 9533, "s": 9513, "text": "Another Approach: " }, { "code": null, "e": 9537, "s": 9533, "text": "C++" }, { "code": null, "e": 9542, "s": 9537, "text": "Java" }, { "code": null, "e": 9550, "s": 9542, "text": "Python3" }, { "code": null, "e": 9553, "s": 9550, "text": "C#" }, { "code": null, "e": 9557, "s": 9553, "text": "PHP" }, { "code": null, "e": 9568, "s": 9557, "text": "Javascript" }, { "code": "// C++ program for printing// the rectangular pattern#include<bits/stdc++.h>using namespace std; // Function to print the patternvoid printPattern(int n){ int arraySize = n * 2 - 1; int result[arraySize][arraySize]; // Fill the values for(int i = 0; i < arraySize; i++) { for(int j = 0; j < arraySize; j++) { if(abs(i - arraySize / 2) > abs(j - arraySize / 2)) result[i][j] = abs(i - arraySize / 2) + 1; else result[i][j] = (abs(j-arraySize / 2) + 1); } } // Print the array for(int i = 0; i < arraySize; i++) { for(int j = 0; j < arraySize; j++) { cout << result[i][j] << \" \"; } cout << endl; }} // Driver Codeint main(){ int n = 3; printPattern(n); return 0;} // This code is contributed// by Rajput-Ji.", "e": 10457, "s": 9568, "text": null }, { "code": "// Java program for printing// the rectangular patternimport java.io.*; class GFG{ // Function to print the patternstatic void printPattern(int n){ int arraySize = n * 2 - 1; int[][] result = new int[arraySize][arraySize]; //Fill the values for(int i = 0; i < arraySize; i++) { for(int j = 0; j < arraySize; j++) { result[i][j] = Math.max(Math.abs(i-arraySize/2), Math.abs(j-arraySize/2))+1; } } //Print the array for(int i = 0; i < arraySize; i++) { for(int j = 0; j < arraySize; j++) { System.out.print(result[i][j]); } System.out.println(); }}// Driver Codepublic static void main (String[] args){ int n = 3; printPattern(n);}} // This code is contributed// by MohitSharma23.", "e": 11369, "s": 10457, "text": null }, { "code": "# Python3 program for printing# the rectangular pattern # Function to print the patterndef printPattern(n): arraySize = n * 2 - 1; result = [[0 for x in range(arraySize)] for y in range(arraySize)]; # Fill the values for i in range(arraySize): for j in range(arraySize): if(abs(i - (arraySize // 2)) > abs(j - (arraySize // 2))): result[i][j] = abs(i - (arraySize // 2)) + 1; else: result[i][j] = abs(j - (arraySize // 2)) + 1; # Print the array for i in range(arraySize): for j in range(arraySize): print(result[i][j], end = \" \"); print(\"\"); # Driver Coden = 3; printPattern(n); # This code is contributed by mits", "e": 12139, "s": 11369, "text": null }, { "code": "// C# program for printing// the rectangular patternusing System; class GFG{ // Function to print the patternstatic void printPattern(int n){ int arraySize = n * 2 - 1; int[,] result = new int[arraySize,arraySize]; // Fill the values for(int i = 0; i < arraySize; i++) { for(int j = 0; j < arraySize; j++) { result[i,j] = Math.Max(Math.Abs(i-arraySize/2), Math.Abs(j-arraySize/2))+1; } } // Print the array for(int i = 0; i < arraySize; i++) { for(int j = 0; j < arraySize; j++) { Console.Write(result[i,j]+\" \"); } Console.WriteLine(); }} // Driver Codepublic static void Main (String[] args){ int n = 3; printPattern(n);}} // This code has been contributed by 29AjayKumar", "e": 13049, "s": 12139, "text": null }, { "code": "<?php// PHP program for printing// the rectangular pattern // Function to print the patternfunction printPattern($n){ $arraySize = $n * 2 - 1; $result=array_fill(0,$arraySize,array_fill(0,$arraySize,0)); // Fill the values for($i = 0; $i < $arraySize; $i++) { for($j = 0; $j < $arraySize; $j++) { if(abs($i - (int)($arraySize / 2)) > abs($j - (int)($arraySize / 2))) $result[$i][$j] = abs($i - (int)($arraySize / 2)) + 1; else $result[$i][$j] = (abs($j-(int) ($arraySize / 2)) + 1); } } // Print the array for($i = 0; $i < $arraySize; $i++) { for($j = 0; $j < $arraySize; $j++) { echo $result[$i][$j].\" \"; } echo \"\\n\"; }} // Driver Code $n = 3; printPattern($n); // This code is contributed by mits?>", "e": 14004, "s": 13049, "text": null }, { "code": "<script> // Javascript program for printing the rectangular pattern // Function to print the pattern function printPattern(n) { let arraySize = n * 2 - 1; let result = new Array(arraySize); // Fill the values for(let i = 0; i < arraySize; i++) { result[i] = new Array(arraySize); for(let j = 0; j < arraySize; j++) { result[i][j] = Math.max(Math.abs(i-parseInt(arraySize/2, 10)), Math.abs(j-parseInt(arraySize/2, 10)))+1; } } // Print the array for(let i = 0; i < arraySize; i++) { for(let j = 0; j < arraySize; j++) { document.write(result[i][j] + \" \"); } document.write(\"</br>\"); } } let n = 3; printPattern(n); // This code is contributed by divyeshrabadiya07.</script>", "e": 15021, "s": 14004, "text": null }, { "code": null, "e": 15030, "s": 15021, "text": "Output " }, { "code": null, "e": 15086, "s": 15030, "text": "3 3 3 3 3 \n3 2 2 2 3 \n3 2 1 2 3 \n3 2 2 2 3 \n3 3 3 3 3 " }, { "code": null, "e": 15093, "s": 15088, "text": "vt_m" }, { "code": null, "e": 15114, "s": 15093, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 15124, "s": 15114, "text": "Sach_Code" }, { "code": null, "e": 15138, "s": 15124, "text": "MohitSharma23" }, { "code": null, "e": 15148, "s": 15138, "text": "Rajput-Ji" }, { "code": null, "e": 15160, "s": 15148, "text": "29AjayKumar" }, { "code": null, "e": 15173, "s": 15160, "text": "Mithun Kumar" }, { "code": null, "e": 15190, "s": 15173, "text": "avijitmondal1998" }, { "code": null, "e": 15208, "s": 15190, "text": "divyeshrabadiya07" }, { "code": null, "e": 15225, "s": 15208, "text": "arorakashish0911" }, { "code": null, "e": 15242, "s": 15225, "text": "pattern-printing" }, { "code": null, "e": 15249, "s": 15242, "text": "Matrix" }, { "code": null, "e": 15266, "s": 15249, "text": "pattern-printing" }, { "code": null, "e": 15273, "s": 15266, "text": "Matrix" }, { "code": null, "e": 15371, "s": 15273, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15409, "s": 15371, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 15447, "s": 15409, "text": "Find median in row wise sorted matrix" }, { "code": null, "e": 15487, "s": 15447, "text": "Traverse a given Matrix using Recursion" }, { "code": null, "e": 15528, "s": 15487, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 15554, "s": 15528, "text": "A Boolean Matrix Question" }, { "code": null, "e": 15600, "s": 15554, "text": "Common elements in all rows of a given matrix" }, { "code": null, "e": 15631, "s": 15600, "text": "Find a specific pair in Matrix" }, { "code": null, "e": 15666, "s": 15631, "text": "Python program to add two Matrices" }, { "code": null, "e": 15723, "s": 15666, "text": "Flood fill Algorithm - how to implement fill() in paint?" } ]
How to check multiple variables against a value in Python?
19 May, 2021 Given some variables, the task is to write a Python program to check multiple variables against a value. There are three possible known ways to achieve this in Python: Method #1: Using or operator This is pretty simple and straightforward. The following code snippets illustrate this method. Example 1: Python3 # assigning variablesa = 100b = 0c = -1 # checking multiple variables against a valueif a == -1 or b == 100 or c == -1: print('Value Found!')else: print('Not Found!') Output: Value Found! Method #2: Using in keyword It is usually used to search through a sequence but can very well replace the code above. Python3 # assigning variablesa = 100b = 0c = -1 # checking multiple variables against a valueif a in [100, 0, -1]: print('Value Found!')else: print('Not Found!') Output: Value Found! You can use it for inverse statements also: Example 2: Python3 # assigning variablesa = 90 # checking multiple variables against a valueif a not in [0, -1, 100]: print('Value Found!')else: print('Not Found!') Output: Value Found! Method #2: Using == operator This approach is only applicable to multiple variables when checked with a single value. Example 1: Python3 # assigning variablesa = 9b = 9c = 9 # checking multiple variables against a valueif a == b == c == 9: print('Value Found!')else: print('Not Found!') Output: Value Found! gabaa406 Picked python-basics 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 May, 2021" }, { "code": null, "e": 197, "s": 28, "text": "Given some variables, the task is to write a Python program to check multiple variables against a value. There are three possible known ways to achieve this in Python:" }, { "code": null, "e": 226, "s": 197, "text": "Method #1: Using or operator" }, { "code": null, "e": 321, "s": 226, "text": "This is pretty simple and straightforward. The following code snippets illustrate this method." }, { "code": null, "e": 332, "s": 321, "text": "Example 1:" }, { "code": null, "e": 340, "s": 332, "text": "Python3" }, { "code": "# assigning variablesa = 100b = 0c = -1 # checking multiple variables against a valueif a == -1 or b == 100 or c == -1: print('Value Found!')else: print('Not Found!')", "e": 513, "s": 340, "text": null }, { "code": null, "e": 521, "s": 513, "text": "Output:" }, { "code": null, "e": 534, "s": 521, "text": "Value Found!" }, { "code": null, "e": 562, "s": 534, "text": "Method #2: Using in keyword" }, { "code": null, "e": 652, "s": 562, "text": "It is usually used to search through a sequence but can very well replace the code above." }, { "code": null, "e": 660, "s": 652, "text": "Python3" }, { "code": "# assigning variablesa = 100b = 0c = -1 # checking multiple variables against a valueif a in [100, 0, -1]: print('Value Found!')else: print('Not Found!')", "e": 820, "s": 660, "text": null }, { "code": null, "e": 828, "s": 820, "text": "Output:" }, { "code": null, "e": 841, "s": 828, "text": "Value Found!" }, { "code": null, "e": 885, "s": 841, "text": "You can use it for inverse statements also:" }, { "code": null, "e": 897, "s": 885, "text": "Example 2: " }, { "code": null, "e": 905, "s": 897, "text": "Python3" }, { "code": "# assigning variablesa = 90 # checking multiple variables against a valueif a not in [0, -1, 100]: print('Value Found!')else: print('Not Found!')", "e": 1057, "s": 905, "text": null }, { "code": null, "e": 1065, "s": 1057, "text": "Output:" }, { "code": null, "e": 1078, "s": 1065, "text": "Value Found!" }, { "code": null, "e": 1107, "s": 1078, "text": "Method #2: Using == operator" }, { "code": null, "e": 1196, "s": 1107, "text": "This approach is only applicable to multiple variables when checked with a single value." }, { "code": null, "e": 1208, "s": 1196, "text": "Example 1: " }, { "code": null, "e": 1216, "s": 1208, "text": "Python3" }, { "code": "# assigning variablesa = 9b = 9c = 9 # checking multiple variables against a valueif a == b == c == 9: print('Value Found!')else: print('Not Found!')", "e": 1372, "s": 1216, "text": null }, { "code": null, "e": 1380, "s": 1372, "text": "Output:" }, { "code": null, "e": 1393, "s": 1380, "text": "Value Found!" }, { "code": null, "e": 1402, "s": 1393, "text": "gabaa406" }, { "code": null, "e": 1409, "s": 1402, "text": "Picked" }, { "code": null, "e": 1423, "s": 1409, "text": "python-basics" }, { "code": null, "e": 1430, "s": 1423, "text": "Python" } ]
Python | Find the list elements starting with specific letter
25 Apr, 2019 Sometimes, we require to get the words that start with the specific letter. This kind of use case is quiet common in the places of common programming projects or competitive programming. Let’s discuss certain shorthands to deal with this problem in Python. Method #1 : Using list comprehension + lower() This problem can be solved using the combination of above two functions, list comprehension performs the task of extending the logic to whole list and lower function checks for case insensitivity with the target word of argument letter. # Python3 code to demonstrate# Words starting with specific letter# using list comprehension + lower() # initializing listtest_list = ['Akash', 'Nikhil', 'Manjeet', 'akshat'] # initializing check lettercheck = 'A' # printing original listprint("The original list : " + str(test_list)) # using list comprehension + lower()# Words starting with specific letterres = [idx for idx in test_list if idx[0].lower() == check.lower()] # print resultprint("The list of matching first letter : " + str(res)) The original list : ['Akash', 'Nikhil', 'Manjeet', 'akshat'] The list of matching first letter : ['Akash', 'akshat'] Method #2 : Using list comprehension + startswith() + lower() This method is similar to the above method but rather than checking for equality with operator, it checks using the startswith function which is inbuilt provided by python inbuilt library. # Python3 code to demonstrate# Words starting with specific letter# using list comprehension + startswith() + lower() # initializing listtest_list = ['Akash', 'Nikhil', 'Manjeet', 'akshat'] # initializing check lettercheck = 'A' # printing original listprint("The original list : " + str(test_list)) # using list comprehension + startswith() + lower()# Words starting with specific letterres = [idx for idx in test_list if idx.lower().startswith(check.lower())] # print resultprint("The list of matching first letter : " + str(res)) The original list : ['Akash', 'Nikhil', 'Manjeet', 'akshat'] The list of matching first letter : ['Akash', 'akshat'] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n25 Apr, 2019" }, { "code": null, "e": 311, "s": 54, "text": "Sometimes, we require to get the words that start with the specific letter. This kind of use case is quiet common in the places of common programming projects or competitive programming. Let’s discuss certain shorthands to deal with this problem in Python." }, { "code": null, "e": 358, "s": 311, "text": "Method #1 : Using list comprehension + lower()" }, { "code": null, "e": 595, "s": 358, "text": "This problem can be solved using the combination of above two functions, list comprehension performs the task of extending the logic to whole list and lower function checks for case insensitivity with the target word of argument letter." }, { "code": "# Python3 code to demonstrate# Words starting with specific letter# using list comprehension + lower() # initializing listtest_list = ['Akash', 'Nikhil', 'Manjeet', 'akshat'] # initializing check lettercheck = 'A' # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + lower()# Words starting with specific letterres = [idx for idx in test_list if idx[0].lower() == check.lower()] # print resultprint(\"The list of matching first letter : \" + str(res))", "e": 1097, "s": 595, "text": null }, { "code": null, "e": 1215, "s": 1097, "text": "The original list : ['Akash', 'Nikhil', 'Manjeet', 'akshat']\nThe list of matching first letter : ['Akash', 'akshat']\n" }, { "code": null, "e": 1279, "s": 1217, "text": "Method #2 : Using list comprehension + startswith() + lower()" }, { "code": null, "e": 1468, "s": 1279, "text": "This method is similar to the above method but rather than checking for equality with operator, it checks using the startswith function which is inbuilt provided by python inbuilt library." }, { "code": "# Python3 code to demonstrate# Words starting with specific letter# using list comprehension + startswith() + lower() # initializing listtest_list = ['Akash', 'Nikhil', 'Manjeet', 'akshat'] # initializing check lettercheck = 'A' # printing original listprint(\"The original list : \" + str(test_list)) # using list comprehension + startswith() + lower()# Words starting with specific letterres = [idx for idx in test_list if idx.lower().startswith(check.lower())] # print resultprint(\"The list of matching first letter : \" + str(res))", "e": 2006, "s": 1468, "text": null }, { "code": null, "e": 2124, "s": 2006, "text": "The original list : ['Akash', 'Nikhil', 'Manjeet', 'akshat']\nThe list of matching first letter : ['Akash', 'akshat']\n" }, { "code": null, "e": 2145, "s": 2124, "text": "Python list-programs" }, { "code": null, "e": 2152, "s": 2145, "text": "Python" }, { "code": null, "e": 2168, "s": 2152, "text": "Python Programs" } ]
C++ program for hashing with chaining
12 Jul, 2022 In hashing there is a hash function that maps keys to some values. But these hashing function may lead to collision that is two or more keys are mapped to same value. Chain hashing avoids collision. The idea is to make each cell of hash table point to a linked list of records that have same hash function value.Let’s create a hash function, such that our hash table has ‘N’ number of buckets. To insert a node into the hash table, we need to find the hash index for the given key. And it could be calculated using the hash function. Example: hashIndex = key % noOfBucketsInsert: Move to the bucket corresponds to the above calculated hash index and insert the new node at the end of the list.Delete: To delete a node from hash table, calculate the hash index for the key, move to the bucket corresponds to the calculated hash index, search the list in the current bucket to find and remove the node with the given key (if found). Please refer Hashing | Set 2 (Separate Chaining) for details.We use a list in C++ which is internally implemented as linked list (Faster insertion and deletion). CPP // CPP program to implement hashing with chaining#include<bits/stdc++.h>using namespace std; class Hash{ int BUCKET; // No. of buckets // Pointer to an array containing buckets list<int> *table;public: Hash(int V); // Constructor // inserts a key into hash table void insertItem(int x); // deletes a key from hash table void deleteItem(int key); // hash function to map values to key int hashFunction(int x) { return (x % BUCKET); } void displayHash();}; Hash::Hash(int b){ this->BUCKET = b; table = new list<int>[BUCKET];} void Hash::insertItem(int key){ int index = hashFunction(key); table[index].push_back(key);} void Hash::deleteItem(int key){ // get the hash index of key int index = hashFunction(key); // find the key in (index)th list list <int> :: iterator i; for (i = table[index].begin(); i != table[index].end(); i++) { if (*i == key) break; } // if key is found in hash table, remove it if (i != table[index].end()) table[index].erase(i);} // function to display hash tablevoid Hash::displayHash() { for (int i = 0; i < BUCKET; i++) { cout << i; for (auto x : table[i]) cout << " --> " << x; cout << endl; }} // Driver programint main(){ // array that contains keys to be mapped int a[] = {15, 11, 27, 8, 12}; int n = sizeof(a)/sizeof(a[0]); // insert the keys into the hash table Hash h(7); // 7 is count of buckets in // hash table for (int i = 0; i < n; i++) h.insertItem(a[i]); // delete 12 from hash table h.deleteItem(12); // display the Hash table h.displayHash(); return 0;} 0 1 --> 15 --> 8 2 3 4 --> 11 5 6 --> 27 Time Complexity: Search : O(1+(n/m)) Delete : O(1+(n/m)) where n = Number of slots in Hash table m = Number of keys to be inserted Here n/m is the Load Factor. Load Factor (∝) must be as small as possible. Auxiliary Space : O(1) rajeev0719singh shwetagaur4698 rishavpgl4 cpp-list C++ Programs Hash Hash Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n12 Jul, 2022" }, { "code": null, "e": 987, "s": 54, "text": "In hashing there is a hash function that maps keys to some values. But these hashing function may lead to collision that is two or more keys are mapped to same value. Chain hashing avoids collision. The idea is to make each cell of hash table point to a linked list of records that have same hash function value.Let’s create a hash function, such that our hash table has ‘N’ number of buckets. To insert a node into the hash table, we need to find the hash index for the given key. And it could be calculated using the hash function. Example: hashIndex = key % noOfBucketsInsert: Move to the bucket corresponds to the above calculated hash index and insert the new node at the end of the list.Delete: To delete a node from hash table, calculate the hash index for the key, move to the bucket corresponds to the calculated hash index, search the list in the current bucket to find and remove the node with the given key (if found). " }, { "code": null, "e": 1150, "s": 987, "text": "Please refer Hashing | Set 2 (Separate Chaining) for details.We use a list in C++ which is internally implemented as linked list (Faster insertion and deletion). " }, { "code": null, "e": 1154, "s": 1150, "text": "CPP" }, { "code": "// CPP program to implement hashing with chaining#include<bits/stdc++.h>using namespace std; class Hash{ int BUCKET; // No. of buckets // Pointer to an array containing buckets list<int> *table;public: Hash(int V); // Constructor // inserts a key into hash table void insertItem(int x); // deletes a key from hash table void deleteItem(int key); // hash function to map values to key int hashFunction(int x) { return (x % BUCKET); } void displayHash();}; Hash::Hash(int b){ this->BUCKET = b; table = new list<int>[BUCKET];} void Hash::insertItem(int key){ int index = hashFunction(key); table[index].push_back(key);} void Hash::deleteItem(int key){ // get the hash index of key int index = hashFunction(key); // find the key in (index)th list list <int> :: iterator i; for (i = table[index].begin(); i != table[index].end(); i++) { if (*i == key) break; } // if key is found in hash table, remove it if (i != table[index].end()) table[index].erase(i);} // function to display hash tablevoid Hash::displayHash() { for (int i = 0; i < BUCKET; i++) { cout << i; for (auto x : table[i]) cout << \" --> \" << x; cout << endl; }} // Driver programint main(){ // array that contains keys to be mapped int a[] = {15, 11, 27, 8, 12}; int n = sizeof(a)/sizeof(a[0]); // insert the keys into the hash table Hash h(7); // 7 is count of buckets in // hash table for (int i = 0; i < n; i++) h.insertItem(a[i]); // delete 12 from hash table h.deleteItem(12); // display the Hash table h.displayHash(); return 0;}", "e": 2796, "s": 1154, "text": null }, { "code": null, "e": 2837, "s": 2796, "text": "0\n1 --> 15 --> 8\n2\n3\n4 --> 11\n5\n6 --> 27" }, { "code": null, "e": 2856, "s": 2839, "text": "Time Complexity:" }, { "code": null, "e": 2876, "s": 2856, "text": "Search : O(1+(n/m))" }, { "code": null, "e": 2896, "s": 2876, "text": "Delete : O(1+(n/m))" }, { "code": null, "e": 2937, "s": 2896, "text": "where n = Number of slots in Hash table " }, { "code": null, "e": 2982, "s": 2937, "text": " m = Number of keys to be inserted" }, { "code": null, "e": 3011, "s": 2982, "text": "Here n/m is the Load Factor." }, { "code": null, "e": 3057, "s": 3011, "text": "Load Factor (∝) must be as small as possible." }, { "code": null, "e": 3080, "s": 3057, "text": "Auxiliary Space : O(1)" }, { "code": null, "e": 3096, "s": 3080, "text": "rajeev0719singh" }, { "code": null, "e": 3111, "s": 3096, "text": "shwetagaur4698" }, { "code": null, "e": 3122, "s": 3111, "text": "rishavpgl4" }, { "code": null, "e": 3131, "s": 3122, "text": "cpp-list" }, { "code": null, "e": 3144, "s": 3131, "text": "C++ Programs" }, { "code": null, "e": 3149, "s": 3144, "text": "Hash" }, { "code": null, "e": 3154, "s": 3149, "text": "Hash" } ]
How to break an outer loop with PHP ?
01 Oct, 2019 Using break keyword: The break keyword is used to immediately terminate the loop and the program control resumes at the next statement following the loop. To terminate the control from any loop we need to use break keyword. The break keyword is used to end the execution of current for, foreach, while, do-while or switch structure. But in nested loops, to exit out from all or some of the outer loops, we need to pass a numeric argument which tells it how many nested enclosing structures are to be terminated. Syntax: break number_of_nested_loop_to_terminate; Parameters: The break keyword followed by a numeric argument which is by default 1. Passing of variables and 0 as a numeric argument is not allowed. Examples: break 2; // It terminates second outer loop break 3; // It terminates third outer loop break $num; // Variable cannot be used as numeric argument since version 5.4.0 break 0; // 0 is not a valid argument to pass Below programs illustrate how to break outer loops in PHP: Program 1: PHP program to display the number while inner loop is not terminated. <?php // Initialize a number$num = 10; // Outer loop to iterate $num timesfor( $i = 0; $i < 10; $i++ ) { // Initialize a variable $j $j = 1; // Inner loop while( $j <= 3 ) { if( $i >= 1 ) // Breaking the outer loop break 2; echo $j . " "; $j++; } } ?> 1 2 3 Program 2: PHP program to search a number in an array and break the outer loop when it is found. <?php // Create a 2D array$arr = array( array (105, 96, 112), array(96, 45, 63) ); // Initialize a number which// need to fine in the array$num = 45; // Declare a boolean variable and// initialize it with false$found = FALSE; // Outer loopfor($i = 0; $i < 2; $i++) { // Inner loop for($j = 0; $j < 3; $j++) { if($num == $arr[$i][$j]) { $found = TRUE; // Terminate the outer loop break 2; } } } // Check number is found or notif( $found ) echo $num . " is found in the array";else echo $num . " is not found in the given array"; ?> 45 is found in the array Using goto keyword: The goto keyword is used to jump the section of the program. It jumps to the target label. Program 3: PHP program to break the outer loop using goto keyword. <?php // Create a 2D array$arr = array( array (105, 96, 112), array(96, 45, 63) ); // Initialize a number which// need to fine in the array$num = 45; // Declare a boolean variable and// initialize it with false$found = FALSE; // Outer loopfor($i = 0; $i < 2; $i++) { // Inner loop for($j = 0; $j < 3; $j++) { if($num == $arr[$i][$j]) { $found = TRUE; // Terminate the outer loop // using goto keyword goto terminateLoop; } } } // target labelterminateLoop: // Check number is found or notif( $found ) echo $num . " is found in the array";else echo $num . " is not found in the given array"; ?> 45 is found in the array Mitrajit PHP-Control-Statement Picked PHP PHP Programs Web Technologies Web technologies Questions PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Oct, 2019" }, { "code": null, "e": 540, "s": 28, "text": "Using break keyword: The break keyword is used to immediately terminate the loop and the program control resumes at the next statement following the loop. To terminate the control from any loop we need to use break keyword. The break keyword is used to end the execution of current for, foreach, while, do-while or switch structure. But in nested loops, to exit out from all or some of the outer loops, we need to pass a numeric argument which tells it how many nested enclosing structures are to be terminated." }, { "code": null, "e": 548, "s": 540, "text": "Syntax:" }, { "code": null, "e": 590, "s": 548, "text": "break number_of_nested_loop_to_terminate;" }, { "code": null, "e": 739, "s": 590, "text": "Parameters: The break keyword followed by a numeric argument which is by default 1. Passing of variables and 0 as a numeric argument is not allowed." }, { "code": null, "e": 749, "s": 739, "text": "Examples:" }, { "code": null, "e": 962, "s": 749, "text": "break 2; // It terminates second outer loop\nbreak 3; // It terminates third outer loop\nbreak $num; // Variable cannot be used as numeric argument since version 5.4.0\nbreak 0; // 0 is not a valid argument to pass\n" }, { "code": null, "e": 1021, "s": 962, "text": "Below programs illustrate how to break outer loops in PHP:" }, { "code": null, "e": 1102, "s": 1021, "text": "Program 1: PHP program to display the number while inner loop is not terminated." }, { "code": "<?php // Initialize a number$num = 10; // Outer loop to iterate $num timesfor( $i = 0; $i < 10; $i++ ) { // Initialize a variable $j $j = 1; // Inner loop while( $j <= 3 ) { if( $i >= 1 ) // Breaking the outer loop break 2; echo $j . \" \"; $j++; } } ?>", "e": 1461, "s": 1102, "text": null }, { "code": null, "e": 1468, "s": 1461, "text": "1 2 3\n" }, { "code": null, "e": 1565, "s": 1468, "text": "Program 2: PHP program to search a number in an array and break the outer loop when it is found." }, { "code": "<?php // Create a 2D array$arr = array( array (105, 96, 112), array(96, 45, 63) ); // Initialize a number which// need to fine in the array$num = 45; // Declare a boolean variable and// initialize it with false$found = FALSE; // Outer loopfor($i = 0; $i < 2; $i++) { // Inner loop for($j = 0; $j < 3; $j++) { if($num == $arr[$i][$j]) { $found = TRUE; // Terminate the outer loop break 2; } } } // Check number is found or notif( $found ) echo $num . \" is found in the array\";else echo $num . \" is not found in the given array\"; ?>", "e": 2201, "s": 1565, "text": null }, { "code": null, "e": 2227, "s": 2201, "text": "45 is found in the array\n" }, { "code": null, "e": 2338, "s": 2227, "text": "Using goto keyword: The goto keyword is used to jump the section of the program. It jumps to the target label." }, { "code": null, "e": 2405, "s": 2338, "text": "Program 3: PHP program to break the outer loop using goto keyword." }, { "code": "<?php // Create a 2D array$arr = array( array (105, 96, 112), array(96, 45, 63) ); // Initialize a number which// need to fine in the array$num = 45; // Declare a boolean variable and// initialize it with false$found = FALSE; // Outer loopfor($i = 0; $i < 2; $i++) { // Inner loop for($j = 0; $j < 3; $j++) { if($num == $arr[$i][$j]) { $found = TRUE; // Terminate the outer loop // using goto keyword goto terminateLoop; } } } // target labelterminateLoop: // Check number is found or notif( $found ) echo $num . \" is found in the array\";else echo $num . \" is not found in the given array\"; ?>", "e": 3116, "s": 2405, "text": null }, { "code": null, "e": 3142, "s": 3116, "text": "45 is found in the array\n" }, { "code": null, "e": 3151, "s": 3142, "text": "Mitrajit" }, { "code": null, "e": 3173, "s": 3151, "text": "PHP-Control-Statement" }, { "code": null, "e": 3180, "s": 3173, "text": "Picked" }, { "code": null, "e": 3184, "s": 3180, "text": "PHP" }, { "code": null, "e": 3197, "s": 3184, "text": "PHP Programs" }, { "code": null, "e": 3214, "s": 3197, "text": "Web Technologies" }, { "code": null, "e": 3241, "s": 3214, "text": "Web technologies Questions" }, { "code": null, "e": 3245, "s": 3241, "text": "PHP" } ]
JavaScript promise reject() Method
31 May, 2022 A promise is a JavaScript object which is responsible for handling callbacks and other asynchronous events or data with 2 different possible states, it either resolves or rejects. The Promise.reject() method is used to return a rejected Promise object with a given reason for rejection. It is used for debugging purposes and selective error catching. The catch() method can be used for logging the output of the reject() method to the console that is catch() method acts as a career which carries the rejected message from Promise.reject() method and displays that in user’s console. Syntax: Promise.reject(reason) Parameter: This method accepts a single parameter as mentioned above and described below: reason: It is the reason for which the promise is rejected. Return value: It returns the rejected promise with the given reason, either specified by user or via the backend. The examples below illustrate the reject() method in very much simplified and accurate manner: Example 1: JavaScript <script> // Initialize a promise variable and // use the reject() method with a // reason as a parameter var promise = Promise.reject("I am a reason of error"); // Catch the promise and pass the // function for logging the error in console promise.catch(function (error) { console.log(error); });</script> // This code is contributed by Aman Singla Output: I am a reason of error Example 2: JavaScript <script> function main() { return new Promise(function (resolve, reject) { setTimeout(() => { // This is the error which is handled // according to network requests const error = true; reject(); }, 2000); }); } main().catch(function () { // Only executed if rejects the promise console.log("rejected the promise, something wrong happened"); });</script> Output: rejected the promise, something wrong happened Example 3: JavaScript <script> function main() { return new Promise(function (resolve, reject) { num = 100; if (num > 50) { reject(); } }); } main().catch(function () { // Only executed if rejects the promise console.log("Not greater than 100"); });</script> Output: Not greater than 100 Supported Browsers: Google Chrome 32 and above Edge 12 and above Firefox 29 and above Opera 19 and above Safari 8 and above Internet Explorer not supported amansingla kumargaurav97520 JavaScript-Methods Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Remove elements from a JavaScript Array Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners JavaScript | Promises Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2022" }, { "code": null, "e": 208, "s": 28, "text": "A promise is a JavaScript object which is responsible for handling callbacks and other asynchronous events or data with 2 different possible states, it either resolves or rejects." }, { "code": null, "e": 612, "s": 208, "text": "The Promise.reject() method is used to return a rejected Promise object with a given reason for rejection. It is used for debugging purposes and selective error catching. The catch() method can be used for logging the output of the reject() method to the console that is catch() method acts as a career which carries the rejected message from Promise.reject() method and displays that in user’s console." }, { "code": null, "e": 620, "s": 612, "text": "Syntax:" }, { "code": null, "e": 643, "s": 620, "text": "Promise.reject(reason)" }, { "code": null, "e": 733, "s": 643, "text": "Parameter: This method accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 793, "s": 733, "text": "reason: It is the reason for which the promise is rejected." }, { "code": null, "e": 907, "s": 793, "text": "Return value: It returns the rejected promise with the given reason, either specified by user or via the backend." }, { "code": null, "e": 1002, "s": 907, "text": "The examples below illustrate the reject() method in very much simplified and accurate manner:" }, { "code": null, "e": 1013, "s": 1002, "text": "Example 1:" }, { "code": null, "e": 1024, "s": 1013, "text": "JavaScript" }, { "code": "<script> // Initialize a promise variable and // use the reject() method with a // reason as a parameter var promise = Promise.reject(\"I am a reason of error\"); // Catch the promise and pass the // function for logging the error in console promise.catch(function (error) { console.log(error); });</script> // This code is contributed by Aman Singla", "e": 1385, "s": 1024, "text": null }, { "code": null, "e": 1393, "s": 1385, "text": "Output:" }, { "code": null, "e": 1416, "s": 1393, "text": "I am a reason of error" }, { "code": null, "e": 1427, "s": 1416, "text": "Example 2:" }, { "code": null, "e": 1438, "s": 1427, "text": "JavaScript" }, { "code": "<script> function main() { return new Promise(function (resolve, reject) { setTimeout(() => { // This is the error which is handled // according to network requests const error = true; reject(); }, 2000); }); } main().catch(function () { // Only executed if rejects the promise console.log(\"rejected the promise, something wrong happened\"); });</script>", "e": 1846, "s": 1438, "text": null }, { "code": null, "e": 1854, "s": 1846, "text": "Output:" }, { "code": null, "e": 1901, "s": 1854, "text": "rejected the promise, something wrong happened" }, { "code": null, "e": 1913, "s": 1901, "text": "Example 3: " }, { "code": null, "e": 1924, "s": 1913, "text": "JavaScript" }, { "code": "<script> function main() { return new Promise(function (resolve, reject) { num = 100; if (num > 50) { reject(); } }); } main().catch(function () { // Only executed if rejects the promise console.log(\"Not greater than 100\"); });</script>", "e": 2199, "s": 1924, "text": null }, { "code": null, "e": 2207, "s": 2199, "text": "Output:" }, { "code": null, "e": 2228, "s": 2207, "text": "Not greater than 100" }, { "code": null, "e": 2248, "s": 2228, "text": "Supported Browsers:" }, { "code": null, "e": 2275, "s": 2248, "text": "Google Chrome 32 and above" }, { "code": null, "e": 2293, "s": 2275, "text": "Edge 12 and above" }, { "code": null, "e": 2314, "s": 2293, "text": "Firefox 29 and above" }, { "code": null, "e": 2333, "s": 2314, "text": "Opera 19 and above" }, { "code": null, "e": 2352, "s": 2333, "text": "Safari 8 and above" }, { "code": null, "e": 2384, "s": 2352, "text": "Internet Explorer not supported" }, { "code": null, "e": 2395, "s": 2384, "text": "amansingla" }, { "code": null, "e": 2412, "s": 2395, "text": "kumargaurav97520" }, { "code": null, "e": 2431, "s": 2412, "text": "JavaScript-Methods" }, { "code": null, "e": 2438, "s": 2431, "text": "Picked" }, { "code": null, "e": 2449, "s": 2438, "text": "JavaScript" }, { "code": null, "e": 2466, "s": 2449, "text": "Web Technologies" }, { "code": null, "e": 2564, "s": 2466, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2625, "s": 2564, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2665, "s": 2625, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2706, "s": 2665, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 2748, "s": 2706, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 2770, "s": 2748, "text": "JavaScript | Promises" }, { "code": null, "e": 2803, "s": 2770, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2865, "s": 2803, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2926, "s": 2865, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2976, "s": 2926, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Saddle point in a matrix
05 Jul, 2022 Given a matrix of n x n size, the task is to find the saddle point of the matrix. A saddle point is an element of the matrix such that it is the minimum element in its row and maximum in its column. Examples : Input: Mat[3][3] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9}} Output: 7 7 is minimum in its row and maximum in its column. Input: Mat[3][3] = {{1, 2, 3}, {4, 5, 6}, {10, 18, 4}} Output: No saddle point A simple solution is to traverse all matrix elements one by one and check if the element is Saddle Point or not. An efficient solution is based on the below steps. Traverse all rows one by one and do the following for every row i. Find the minimum element of the current row and store the column index of the minimum element.Check if the row minimum element is also maximum in its column. We use the stored column index here.If yes, then saddle point else continues till the end of the matrix. Find the minimum element of the current row and store the column index of the minimum element. Check if the row minimum element is also maximum in its column. We use the stored column index here. If yes, then saddle point else continues till the end of the matrix. Below is the implementation of the above steps. C++ C Java Python3 C# PHP Javascript // C++ program to illustrate Saddle point#include <bits/stdc++.h>using namespace std; const int MAX = 100; // Function to find saddle pointbool findSaddlePoint(int mat[MAX][MAX], int n){ // Process all rows one by one for (int i = 0; i < n; i++) { // Find the minimum element of row i. // Also find column index of the minimum element int min_row = mat[i][0], col_ind = 0; for (int j = 1; j < n; j++) { if (min_row > mat[i][j]) { min_row = mat[i][j]; col_ind = j; } } // Check if the minimum element of row is also // the maximum element of column or not int k; for (k = 0; k < n; k++) // Note that col_ind is fixed if (min_row < mat[k][col_ind]) break; // If saddle point is present in this row then // print it if (k == n) { cout << "Value of Saddle Point " << min_row; return true; } } // If Saddle Point not found return false;} // Driver codeint main(){ int mat[MAX][MAX] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = 3; if (findSaddlePoint(mat, n) == false) cout << "No Saddle Point "; return 0;} // C program to illustrate Saddle point#include <stdio.h>#include <stdbool.h> #define MAX 100 // Function to find saddle pointbool findSaddlePoint(int mat[MAX][MAX], int n){ // Process all rows one by one for (int i = 0; i < n; i++) { // Find the minimum element of row i. // Also find column index of the minimum element int min_row = mat[i][0], col_ind = 0; for (int j = 1; j < n; j++) { if (min_row > mat[i][j]) { min_row = mat[i][j]; col_ind = j; } } // Check if the minimum element of row is also // the maximum element of column or not int k; for (k = 0; k < n; k++) // Note that col_ind is fixed if (min_row < mat[k][col_ind]) break; // If saddle point is present in this row then // print it if (k == n) { printf("Value of Saddle Point %d",min_row); return true; } } // If Saddle Point not found return false;} // Driver codeint main(){ int mat[MAX][MAX] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = 3; if (findSaddlePoint(mat, n) == false) printf("No Saddle Point "); return 0;} // This code is contributed by kothavvsaakash. // Java program to illustrate Saddle point class Test{ // Method to find saddle point static boolean findSaddlePoint(int mat[][ ], int n) { // Process all rows one by one for (int i = 0; i < n; i++) { // Find the minimum element of row i. // Also find column index of the minimum element int min_row = mat[i][0], col_ind = 0; for (int j = 1; j < n; j++) { if (min_row > mat[i][j]) { min_row = mat[i][j]; col_ind = j; } } // Check if the minimum element of row is also // the maximum element of column or not int k; for (k = 0; k < n; k++) // Note that col_ind is fixed if (min_row < mat[k][col_ind]) break; // If saddle point is present in this row then // print it if (k == n) { System.out.println("Value of Saddle Point " + min_row); return true; } } // If Saddle Point not found return false; } // Driver method public static void main(String[] args) { int mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = 3; if (findSaddlePoint(mat, n) == false) System.out.println("No Saddle Point "); }} # Python3 program to illustrate# Saddle point # Method to find saddle pointdef findSaddlePoint(mat, n): # Process all rows one # by one for i in range(n): # Find the minimum element # of row i. # Also find column index of # the minimum element min_row = mat[i][0]; col_ind = 0; for j in range(1, n): if (min_row > mat[i][j]): min_row = mat[i][j]; col_ind = j; # Check if the minimum element # of row is also the maximum # element of column or not k = 0; for k in range(n): # Note that col_ind is fixed if (min_row < mat[k][col_ind]): break; k += 1; # If saddle point present in this # row then print if (k == n): print("Value of Saddle Point ", min_row); return True; # If Saddle Point found return False; # Driver methodif __name__ == '__main__': mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; n = 3; if (findSaddlePoint(mat, n) == False): print("No Saddle Po"); # This code is contributed by 29AjayKumar // C# program to illustrate Saddle pointusing System; class GFG { // Method to find saddle point static bool findSaddlePoint(int [,] mat, int n) { // Process all rows one by one for (int i = 0; i < n; i++) { // Find the minimum element of // row i. Also find column index // of the minimum element int min_row = mat[i, 0], col_ind = 0; for (int j = 1; j < n; j++) { if (min_row > mat[i, j]) { min_row = mat[i, j]; col_ind = j; } } // Check if the minimum element // of row is also the maximum // element of column or not int k; for (k = 0; k < n; k++) // Note that col_ind is fixed if (min_row < mat[k, col_ind]) break; // If saddle point is present in this row then // print it if (k == n) { Console.WriteLine("Value of Saddle Point " + min_row); return true; } } // If Saddle Point not found return false; } // Driver code public static void Main() { int [,] mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = 3; if (findSaddlePoint(mat, n) == false) Console.WriteLine("No Saddle Point "); }} // This code is contributed by KRV. <?php// PHP program to illustrate// Saddle point $MAX = 100; // Function to find saddle pointfunction findSaddlePoint( $mat, $n){ // Process all rows one by one for ( $i = 0; $i < $n; $i++) { // Find the minimum element // of row i. Also find column // index of the minimum element $min_row = $mat[$i][0]; $col_ind = 0; for ( $j = 1; $j < $n; $j++) { if ($min_row > $mat[$i][$j]) { $min_row = $mat[$i][$j]; $col_ind = $j; } } // Check if the minimum element of // row is also the maximum element // of column or not $k; for ($k = 0; $k < $n; $k++) // Note that col_ind is fixed if ($min_row < $mat[$k][$col_ind]) break; // If saddle point is present in // this row then print it if ($k == $n) { echo "Value of Saddle Point " , $min_row; return true; } } // If Saddle Point not found return false;} // Driver code$mat = array(array(1, 2, 3), array(4, 5, 6), array (7, 8, 9));$n = 3;if (findSaddlePoint($mat, $n) == false)echo "No Saddle Point "; // This code is contributed by anuj_67.?> <script>// Javascript program to illustrate Saddle point // Method to find saddle pointfunction findSaddlePoint(mat, n){ // Process all rows one by one for (let i = 0; i < n; i++) { // Find the minimum element of row i. // Also find column index of the minimum element let min_row = mat[i][0], col_ind = 0; for (let j = 1; j < n; j++) { if (min_row > mat[i][j]) { min_row = mat[i][j]; col_ind = j; } } // Check if the minimum element of row is also // the maximum element of column or not let k; for (k = 0; k < n; k++) // Note that col_ind is fixed if (min_row < mat[k][col_ind]) break; // If saddle point is present in this row then // print it if (k == n) { document.write("Value of Saddle Point " + min_row+"<br>"); return true; } } // If Saddle Point not found return false;} // Driver methodlet mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; let n = 3; if (findSaddlePoint(mat, n) == false) document.write("No Saddle Point "); // This code is contributed by rag2127</script> Value of Saddle Point 7 Exercise : Can there be more than one Saddle Points in a Matrix? This article is contributed by Sahil Chhabra(KILLER). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. KRV vt_m 29AjayKumar rag2127 kothavvsaakash hardikkoriintern Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Unique paths in a Grid with Obstacles Find the longest path in a matrix with given constraints Find median in row wise sorted matrix Zigzag (or diagonal) traversal of Matrix A Boolean Matrix Question Traverse a given Matrix using Recursion Find a specific pair in Matrix Common elements in all rows of a given matrix Shortest distance between two cells in a matrix or grid Python program to add two Matrices
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Jul, 2022" }, { "code": null, "e": 254, "s": 54, "text": "Given a matrix of n x n size, the task is to find the saddle point of the matrix. A saddle point is an element of the matrix such that it is the minimum element in its row and maximum in its column. " }, { "code": null, "e": 266, "s": 254, "text": "Examples : " }, { "code": null, "e": 537, "s": 266, "text": "Input: Mat[3][3] = { {1, 2, 3},\n {4, 5, 6},\n {7, 8, 9}}\nOutput: 7\n7 is minimum in its row and maximum in its column.\n\nInput: Mat[3][3] = {{1, 2, 3},\n {4, 5, 6},\n {10, 18, 4}}\nOutput: No saddle point" }, { "code": null, "e": 650, "s": 537, "text": "A simple solution is to traverse all matrix elements one by one and check if the element is Saddle Point or not." }, { "code": null, "e": 702, "s": 650, "text": "An efficient solution is based on the below steps. " }, { "code": null, "e": 771, "s": 702, "text": "Traverse all rows one by one and do the following for every row i. " }, { "code": null, "e": 1034, "s": 771, "text": "Find the minimum element of the current row and store the column index of the minimum element.Check if the row minimum element is also maximum in its column. We use the stored column index here.If yes, then saddle point else continues till the end of the matrix." }, { "code": null, "e": 1129, "s": 1034, "text": "Find the minimum element of the current row and store the column index of the minimum element." }, { "code": null, "e": 1230, "s": 1129, "text": "Check if the row minimum element is also maximum in its column. We use the stored column index here." }, { "code": null, "e": 1299, "s": 1230, "text": "If yes, then saddle point else continues till the end of the matrix." }, { "code": null, "e": 1349, "s": 1299, "text": "Below is the implementation of the above steps. " }, { "code": null, "e": 1353, "s": 1349, "text": "C++" }, { "code": null, "e": 1355, "s": 1353, "text": "C" }, { "code": null, "e": 1360, "s": 1355, "text": "Java" }, { "code": null, "e": 1368, "s": 1360, "text": "Python3" }, { "code": null, "e": 1371, "s": 1368, "text": "C#" }, { "code": null, "e": 1375, "s": 1371, "text": "PHP" }, { "code": null, "e": 1386, "s": 1375, "text": "Javascript" }, { "code": "// C++ program to illustrate Saddle point#include <bits/stdc++.h>using namespace std; const int MAX = 100; // Function to find saddle pointbool findSaddlePoint(int mat[MAX][MAX], int n){ // Process all rows one by one for (int i = 0; i < n; i++) { // Find the minimum element of row i. // Also find column index of the minimum element int min_row = mat[i][0], col_ind = 0; for (int j = 1; j < n; j++) { if (min_row > mat[i][j]) { min_row = mat[i][j]; col_ind = j; } } // Check if the minimum element of row is also // the maximum element of column or not int k; for (k = 0; k < n; k++) // Note that col_ind is fixed if (min_row < mat[k][col_ind]) break; // If saddle point is present in this row then // print it if (k == n) { cout << \"Value of Saddle Point \" << min_row; return true; } } // If Saddle Point not found return false;} // Driver codeint main(){ int mat[MAX][MAX] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = 3; if (findSaddlePoint(mat, n) == false) cout << \"No Saddle Point \"; return 0;}", "e": 2699, "s": 1386, "text": null }, { "code": "// C program to illustrate Saddle point#include <stdio.h>#include <stdbool.h> #define MAX 100 // Function to find saddle pointbool findSaddlePoint(int mat[MAX][MAX], int n){ // Process all rows one by one for (int i = 0; i < n; i++) { // Find the minimum element of row i. // Also find column index of the minimum element int min_row = mat[i][0], col_ind = 0; for (int j = 1; j < n; j++) { if (min_row > mat[i][j]) { min_row = mat[i][j]; col_ind = j; } } // Check if the minimum element of row is also // the maximum element of column or not int k; for (k = 0; k < n; k++) // Note that col_ind is fixed if (min_row < mat[k][col_ind]) break; // If saddle point is present in this row then // print it if (k == n) { printf(\"Value of Saddle Point %d\",min_row); return true; } } // If Saddle Point not found return false;} // Driver codeint main(){ int mat[MAX][MAX] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = 3; if (findSaddlePoint(mat, n) == false) printf(\"No Saddle Point \"); return 0;} // This code is contributed by kothavvsaakash.", "e": 4045, "s": 2699, "text": null }, { "code": "// Java program to illustrate Saddle point class Test{ // Method to find saddle point static boolean findSaddlePoint(int mat[][ ], int n) { // Process all rows one by one for (int i = 0; i < n; i++) { // Find the minimum element of row i. // Also find column index of the minimum element int min_row = mat[i][0], col_ind = 0; for (int j = 1; j < n; j++) { if (min_row > mat[i][j]) { min_row = mat[i][j]; col_ind = j; } } // Check if the minimum element of row is also // the maximum element of column or not int k; for (k = 0; k < n; k++) // Note that col_ind is fixed if (min_row < mat[k][col_ind]) break; // If saddle point is present in this row then // print it if (k == n) { System.out.println(\"Value of Saddle Point \" + min_row); return true; } } // If Saddle Point not found return false; } // Driver method public static void main(String[] args) { int mat[][] = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = 3; if (findSaddlePoint(mat, n) == false) System.out.println(\"No Saddle Point \"); }}", "e": 5547, "s": 4045, "text": null }, { "code": "# Python3 program to illustrate# Saddle point # Method to find saddle pointdef findSaddlePoint(mat, n): # Process all rows one # by one for i in range(n): # Find the minimum element # of row i. # Also find column index of # the minimum element min_row = mat[i][0]; col_ind = 0; for j in range(1, n): if (min_row > mat[i][j]): min_row = mat[i][j]; col_ind = j; # Check if the minimum element # of row is also the maximum # element of column or not k = 0; for k in range(n): # Note that col_ind is fixed if (min_row < mat[k][col_ind]): break; k += 1; # If saddle point present in this # row then print if (k == n): print(\"Value of Saddle Point \", min_row); return True; # If Saddle Point found return False; # Driver methodif __name__ == '__main__': mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; n = 3; if (findSaddlePoint(mat, n) == False): print(\"No Saddle Po\"); # This code is contributed by 29AjayKumar", "e": 6756, "s": 5547, "text": null }, { "code": "// C# program to illustrate Saddle pointusing System; class GFG { // Method to find saddle point static bool findSaddlePoint(int [,] mat, int n) { // Process all rows one by one for (int i = 0; i < n; i++) { // Find the minimum element of // row i. Also find column index // of the minimum element int min_row = mat[i, 0], col_ind = 0; for (int j = 1; j < n; j++) { if (min_row > mat[i, j]) { min_row = mat[i, j]; col_ind = j; } } // Check if the minimum element // of row is also the maximum // element of column or not int k; for (k = 0; k < n; k++) // Note that col_ind is fixed if (min_row < mat[k, col_ind]) break; // If saddle point is present in this row then // print it if (k == n) { Console.WriteLine(\"Value of Saddle Point \" + min_row); return true; } } // If Saddle Point not found return false; } // Driver code public static void Main() { int [,] mat = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}; int n = 3; if (findSaddlePoint(mat, n) == false) Console.WriteLine(\"No Saddle Point \"); }} // This code is contributed by KRV.", "e": 8415, "s": 6756, "text": null }, { "code": "<?php// PHP program to illustrate// Saddle point $MAX = 100; // Function to find saddle pointfunction findSaddlePoint( $mat, $n){ // Process all rows one by one for ( $i = 0; $i < $n; $i++) { // Find the minimum element // of row i. Also find column // index of the minimum element $min_row = $mat[$i][0]; $col_ind = 0; for ( $j = 1; $j < $n; $j++) { if ($min_row > $mat[$i][$j]) { $min_row = $mat[$i][$j]; $col_ind = $j; } } // Check if the minimum element of // row is also the maximum element // of column or not $k; for ($k = 0; $k < $n; $k++) // Note that col_ind is fixed if ($min_row < $mat[$k][$col_ind]) break; // If saddle point is present in // this row then print it if ($k == $n) { echo \"Value of Saddle Point \" , $min_row; return true; } } // If Saddle Point not found return false;} // Driver code$mat = array(array(1, 2, 3), array(4, 5, 6), array (7, 8, 9));$n = 3;if (findSaddlePoint($mat, $n) == false)echo \"No Saddle Point \"; // This code is contributed by anuj_67.?>", "e": 9717, "s": 8415, "text": null }, { "code": "<script>// Javascript program to illustrate Saddle point // Method to find saddle pointfunction findSaddlePoint(mat, n){ // Process all rows one by one for (let i = 0; i < n; i++) { // Find the minimum element of row i. // Also find column index of the minimum element let min_row = mat[i][0], col_ind = 0; for (let j = 1; j < n; j++) { if (min_row > mat[i][j]) { min_row = mat[i][j]; col_ind = j; } } // Check if the minimum element of row is also // the maximum element of column or not let k; for (k = 0; k < n; k++) // Note that col_ind is fixed if (min_row < mat[k][col_ind]) break; // If saddle point is present in this row then // print it if (k == n) { document.write(\"Value of Saddle Point \" + min_row+\"<br>\"); return true; } } // If Saddle Point not found return false;} // Driver methodlet mat = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]; let n = 3; if (findSaddlePoint(mat, n) == false) document.write(\"No Saddle Point \"); // This code is contributed by rag2127</script>", "e": 11169, "s": 9717, "text": null }, { "code": null, "e": 11193, "s": 11169, "text": "Value of Saddle Point 7" }, { "code": null, "e": 11258, "s": 11193, "text": "Exercise : Can there be more than one Saddle Points in a Matrix?" }, { "code": null, "e": 11563, "s": 11258, "text": "This article is contributed by Sahil Chhabra(KILLER). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 11567, "s": 11563, "text": "KRV" }, { "code": null, "e": 11572, "s": 11567, "text": "vt_m" }, { "code": null, "e": 11584, "s": 11572, "text": "29AjayKumar" }, { "code": null, "e": 11592, "s": 11584, "text": "rag2127" }, { "code": null, "e": 11607, "s": 11592, "text": "kothavvsaakash" }, { "code": null, "e": 11624, "s": 11607, "text": "hardikkoriintern" }, { "code": null, "e": 11631, "s": 11624, "text": "Matrix" }, { "code": null, "e": 11638, "s": 11631, "text": "Matrix" }, { "code": null, "e": 11736, "s": 11638, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 11774, "s": 11736, "text": "Unique paths in a Grid with Obstacles" }, { "code": null, "e": 11831, "s": 11774, "text": "Find the longest path in a matrix with given constraints" }, { "code": null, "e": 11869, "s": 11831, "text": "Find median in row wise sorted matrix" }, { "code": null, "e": 11910, "s": 11869, "text": "Zigzag (or diagonal) traversal of Matrix" }, { "code": null, "e": 11936, "s": 11910, "text": "A Boolean Matrix Question" }, { "code": null, "e": 11976, "s": 11936, "text": "Traverse a given Matrix using Recursion" }, { "code": null, "e": 12007, "s": 11976, "text": "Find a specific pair in Matrix" }, { "code": null, "e": 12053, "s": 12007, "text": "Common elements in all rows of a given matrix" }, { "code": null, "e": 12109, "s": 12053, "text": "Shortest distance between two cells in a matrix or grid" } ]
HTML - URL Encoding
URL encoding is the practice of translating unprintable characters or characters with special meaning within URLs to a representation that is unambiguous and universally accepted by web browsers and servers. These characters include − ASCII control characters − Unprintable characters typically used for output control. Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). A complete encoding table is given below. ASCII control characters − Unprintable characters typically used for output control. Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). A complete encoding table is given below. Non-ASCII control characters − These are characters beyond the ASCII character set of 128 characters. This range is part of the ISO-Latin character set and includes the entire "top half" of the ISO-Latin set 80-FF hex (128-255 decimal). A complete encoding table is given below. Non-ASCII control characters − These are characters beyond the ASCII character set of 128 characters. This range is part of the ISO-Latin character set and includes the entire "top half" of the ISO-Latin set 80-FF hex (128-255 decimal). A complete encoding table is given below. Reserved characters − These are special characters such as the dollar sign, ampersand, plus, common, forward slash, colon, semi-colon, equals sign, question mark, and "at" symbol. All of these can have different meanings inside a URL so need to be encoded. A complete encoding table is given below. Reserved characters − These are special characters such as the dollar sign, ampersand, plus, common, forward slash, colon, semi-colon, equals sign, question mark, and "at" symbol. All of these can have different meanings inside a URL so need to be encoded. A complete encoding table is given below. Unsafe characters − These are space, quotation marks, less than symbol, greater than symbol, pound character, percent character, Left Curly Brace, Right Curly Brace, Pipe, Backslash, Caret, Tilde, Left Square Bracket, Right Square Bracket, Grave Accent. These character present the possibility of being misunderstood within URLs for various reasons. These characters should also always be encoded. A complete encoding table is given below. Unsafe characters − These are space, quotation marks, less than symbol, greater than symbol, pound character, percent character, Left Curly Brace, Right Curly Brace, Pipe, Backslash, Caret, Tilde, Left Square Bracket, Right Square Bracket, Grave Accent. These character present the possibility of being misunderstood within URLs for various reasons. These characters should also always be encoded. A complete encoding table is given below. The encoding notation replaces the desired character with three characters: a percent sign and two hexadecimal digits that correspond to the position of the character in the ASCII character set. One of the most common special characters is a white space. You can't type a space in a URL directly. A space position in the character set is 20 hexadecimals. So you can use %20 in place of a space when passing your request to the server. http://www.example.com/new%20pricing.htm This URL actually retrieves a document named "new pricing.htm" from the www.example.com This includes the encoding for character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal) This includes the encoding for the entire "top half" of the ISO-Latin set 80-FF hex (128255 decimal.) Following is the table to be used to encode reserved characters. Following is the table to be used to encode unsafe characters.
[ { "code": null, "e": 2743, "s": 2508, "text": "URL encoding is the practice of translating unprintable characters or characters with special meaning within URLs to a representation that is unambiguous and universally accepted by web browsers and servers. These characters include −" }, { "code": null, "e": 2934, "s": 2743, "text": "ASCII control characters − Unprintable characters typically used for output control. Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). A complete encoding table is given below." }, { "code": null, "e": 3125, "s": 2934, "text": "ASCII control characters − Unprintable characters typically used for output control. Character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal). A complete encoding table is given below." }, { "code": null, "e": 3404, "s": 3125, "text": "Non-ASCII control characters − These are characters beyond the ASCII character set of 128 characters. This range is part of the ISO-Latin character set and includes the entire \"top half\" of the ISO-Latin set 80-FF hex (128-255 decimal). A complete encoding table is given below." }, { "code": null, "e": 3683, "s": 3404, "text": "Non-ASCII control characters − These are characters beyond the ASCII character set of 128 characters. This range is part of the ISO-Latin character set and includes the entire \"top half\" of the ISO-Latin set 80-FF hex (128-255 decimal). A complete encoding table is given below." }, { "code": null, "e": 3982, "s": 3683, "text": "Reserved characters − These are special characters such as the dollar sign, ampersand, plus, common, forward slash, colon, semi-colon, equals sign, question mark, and \"at\" symbol. All of these can have different meanings inside a URL so need to be encoded. A complete encoding table is given below." }, { "code": null, "e": 4281, "s": 3982, "text": "Reserved characters − These are special characters such as the dollar sign, ampersand, plus, common, forward slash, colon, semi-colon, equals sign, question mark, and \"at\" symbol. All of these can have different meanings inside a URL so need to be encoded. A complete encoding table is given below." }, { "code": null, "e": 4721, "s": 4281, "text": "Unsafe characters − These are space, quotation marks, less than symbol, greater than symbol, pound character, percent character, Left Curly Brace, Right Curly Brace, Pipe, Backslash, Caret, Tilde, Left Square Bracket, Right Square Bracket, Grave Accent. These character present the possibility of being misunderstood within URLs for various reasons. These characters should also always be encoded. A complete encoding table is given below." }, { "code": null, "e": 5161, "s": 4721, "text": "Unsafe characters − These are space, quotation marks, less than symbol, greater than symbol, pound character, percent character, Left Curly Brace, Right Curly Brace, Pipe, Backslash, Caret, Tilde, Left Square Bracket, Right Square Bracket, Grave Accent. These character present the possibility of being misunderstood within URLs for various reasons. These characters should also always be encoded. A complete encoding table is given below." }, { "code": null, "e": 5356, "s": 5161, "text": "The encoding notation replaces the desired character with three characters: a percent sign and two hexadecimal digits that correspond to the position of the character in the ASCII character set." }, { "code": null, "e": 5596, "s": 5356, "text": "One of the most common special characters is a white space. You can't type a space in a URL directly. A space position in the character set is 20 hexadecimals. So you can use %20 in place of a space when passing your request to the server." }, { "code": null, "e": 5638, "s": 5596, "text": "http://www.example.com/new%20pricing.htm\n" }, { "code": null, "e": 5726, "s": 5638, "text": "This URL actually retrieves a document named \"new pricing.htm\" from the www.example.com" }, { "code": null, "e": 5820, "s": 5726, "text": "This includes the encoding for character ranges 00-1F hex (0-31 decimal) and 7F (127 decimal)" }, { "code": null, "e": 5922, "s": 5820, "text": "This includes the encoding for the entire \"top half\" of the ISO-Latin set 80-FF hex (128255 decimal.)" }, { "code": null, "e": 5987, "s": 5922, "text": "Following is the table to be used to encode reserved characters." } ]
Text Decoration in CSS
For text decoration in CSS, use the text-decoration property as a shorthand property for the following properties − text-decoration-line text-decoration-color text-decoration-style Let us see an example for text decoration in CSS − Live Demo <!DOCTYPE html> <html> <head> <style> .demo { text-decoration: overline underline; } </style> </head> <body> <h1>Details</h1> <p class="demo">Examination Center near ABC College.</p> <p class="demo2">Exam begins at 9AM.</p> </body> </html> Let us now see another example wherein we are using separate values − Live Demo <!DOCTYPE html> <html> <head> <style> p { writing-mode: vertical-rl; text-decoration-line: overline; text-decoration-color: red; text-decoration-style: wavy; } </style> </head> <body> <h1>Demo Heading</h1> <p>This is demo text.</p> </body> </html>
[ { "code": null, "e": 1303, "s": 1187, "text": "For text decoration in CSS, use the text-decoration property as a shorthand property for the following properties −" }, { "code": null, "e": 1368, "s": 1303, "text": "text-decoration-line\ntext-decoration-color\ntext-decoration-style" }, { "code": null, "e": 1419, "s": 1368, "text": "Let us see an example for text decoration in CSS −" }, { "code": null, "e": 1430, "s": 1419, "text": " Live Demo" }, { "code": null, "e": 1673, "s": 1430, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n.demo {\n text-decoration: overline underline;\n}\n</style>\n</head>\n<body>\n<h1>Details</h1>\n<p class=\"demo\">Examination Center near ABC College.</p>\n<p class=\"demo2\">Exam begins at 9AM.</p>\n</body>\n</html>" }, { "code": null, "e": 1743, "s": 1673, "text": "Let us now see another example wherein we are using separate values −" }, { "code": null, "e": 1754, "s": 1743, "text": " Live Demo" }, { "code": null, "e": 2014, "s": 1754, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\np {\n writing-mode: vertical-rl;\n text-decoration-line: overline;\n text-decoration-color: red;\n text-decoration-style: wavy;\n}\n</style>\n</head>\n<body>\n<h1>Demo Heading</h1>\n<p>This is demo text.</p>\n</body>\n</html>" } ]
Print even and odd numbers in a given range using recursion
23 Apr, 2021 Given two integers L and R, the task is to print all the even and odd numbers from L to R using recursion. Examples: Input: L = 1, R = 10Output: Even numbers: 2 4 6 8 10Odd numbers: 1 3 5 7 9 Input: L = 10, R = 25 Output: Even numbers:10 12 14 16 18 20 22 24 Odd numbers:11 13 15 17 19 21 23 25 Approach: Follow the steps below to solve the problem using Recursion: Traverse the range [R, L]. Print the odd elements from the range using recursion using the following recurrence relation: Odd(L, R) = R % 2 == 1? Odd(L, R – 2) : Odd(L, R – 1) Print the even elements from the range using recursion using the following recurrence relation: Even(L, R) = R % 2 == 0 ? Even(L, R – 2) : Even(L, R – 1) Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print all the// even numbers from L to Rvoid Even(int L, int R){ // Base case if (R < L) { return; } // Recurrence relation R % 2 == 0 ? Even(L, R - 2) : Even(L, R - 1); // Check if R is even if (R % 2 == 0) { cout << R << " "; }} // Function to print all the// odd numbers from L to Rvoid Odd(int L, int R){ // Base case if (R < L) { return; } // Recurrence relation R % 2 == 1 ? Odd(L, R - 2) : Odd(L, R - 1); // Check if R is even if (R % 2 == 1) { cout << R << " "; }} // Driver Codeint main(){ int L = 10, R = 25; cout << "Even numbers:"; // Print all the // even numbers Even(L, R); cout << endl; // Print all the // odd numbers cout << "Odd numbers:"; Odd(L, R);} // Java program to implement// the above approachimport java.util.*;class GFG{ // Function to print// all the even numbers// from L to Rstatic void Even(int L, int R){ // Base case if (R < L) { return; } // Recurrence relation if(R % 2 == 0 ) Even(L, R - 2); else Even(L, R - 1); // Check if R is even if (R % 2 == 0) { System.out.print(R + " "); }} // Function to print// all the odd numbers// from L to Rstatic void Odd(int L, int R){ // Base case if (R < L) { return; } // Recurrence relation if(R % 2 == 1 ) Odd(L, R - 2); else Odd(L, R - 1); // Check if R is even if (R % 2 == 1) { System.out.print(R + " "); }} // Driver Codepublic static void main(String[] args){ int L = 10, R = 25; System.out.print("Even numbers:"); // Print all the // even numbers Even(L, R); System.out.println(); // Print all the // odd numbers System.out.print("Odd numbers:"); Odd(L, R);}} // This code is contributed by Rajput-Ji # Python3 program to implement# the above approach # Function to print all the# even numbers from L to Rdef Even(L, R): # Base case if (R < L): return # Recurrence relation if (R % 2 == 0): Even(L, R - 2) else: Even(L, R - 1) # Check if R is even if (R % 2 == 0): print(R, end = " ") # Function to print all the# odd numbers from L to Rdef Odd(L, R): # Base case if (R < L): return # Recurrence relation if (R % 2 == 1): Odd(L, R - 2) else: Odd(L, R - 1) # Check if R is even if (R % 2 == 1): print(R, end = " ") # Driver Codeif __name__ == '__main__': L = 10 R = 25 print("Even numbers:") # Print all the # even numbers Even(L, R) print() # Print all the # odd numbers print("Odd numbers:") Odd(L, R) # This code is contributed by Amit Katiyar // C# program to implement// the above approachusing System;class GFG{ // Function to print// all the even numbers// from L to Rstatic void Even(int L, int R){ // Base case if (R < L) { return; } // Recurrence relation if(R % 2 == 0 ) Even(L, R - 2); else Even(L, R - 1); // Check if R is even if (R % 2 == 0) { Console.Write(R + " "); }} // Function to print// all the odd numbers// from L to Rstatic void Odd(int L, int R){ // Base case if (R < L) { return; } // Recurrence relation if(R % 2 == 1 ) Odd(L, R - 2); else Odd(L, R - 1); // Check if R is even if (R % 2 == 1) { Console.Write(R + " "); }} // Driver Codepublic static void Main(String[] args){ int L = 10, R = 25; Console.Write("Even numbers:"); // Print all the // even numbers Even(L, R); Console.WriteLine(); // Print all the // odd numbers Console.Write("Odd numbers:"); Odd(L, R);}} // This code is contributed by 29AjayKumar <script> // Java script program to implement// the above approach // Function to print// all the even numbers// from L to Rfunction Even(L, R){ // Base case if (R < L) { return; } // Recurrence relation if (R % 2 == 0 ) { Even(L, R - 2); } else { Even(L, R - 1); } // Check if R is even if (R % 2 == 0) { document.write(R + " "); }} // Function to print// all the odd numbers// from L to Rfunction Odd(L, R){ // Base case if (R < L) { return; } // Recurrence relation if (R % 2 == 1 ) { Odd(L, R - 2); } else { Odd(L, R - 1); } // Check if R is even if (R % 2 == 1) { document.write(R + " "); }} // Driver Codelet L = 10;let R = 25;document.write("Even numbers:"); // Print all the// even numbersEven(L, R);document.write("<br>"); // Print all the// odd numbersdocument.write("Odd numbers:");Odd(L, R); // This code is contributed by sravan kumar G </script> Even numbers:10 12 14 16 18 20 22 24 Odd numbers:11 13 15 17 19 21 23 25 Time Complexity: O(N)Auxiliary Space: O(1) Rajput-Ji 29AjayKumar amit143katiyar sravankumar8128 Number Divisibility Mathematical Recursion Mathematical Recursion Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n23 Apr, 2021" }, { "code": null, "e": 160, "s": 53, "text": "Given two integers L and R, the task is to print all the even and odd numbers from L to R using recursion." }, { "code": null, "e": 170, "s": 160, "text": "Examples:" }, { "code": null, "e": 245, "s": 170, "text": "Input: L = 1, R = 10Output: Even numbers: 2 4 6 8 10Odd numbers: 1 3 5 7 9" }, { "code": null, "e": 348, "s": 245, "text": "Input: L = 10, R = 25 Output: Even numbers:10 12 14 16 18 20 22 24 Odd numbers:11 13 15 17 19 21 23 25" }, { "code": null, "e": 419, "s": 348, "text": "Approach: Follow the steps below to solve the problem using Recursion:" }, { "code": null, "e": 446, "s": 419, "text": "Traverse the range [R, L]." }, { "code": null, "e": 541, "s": 446, "text": "Print the odd elements from the range using recursion using the following recurrence relation:" }, { "code": null, "e": 596, "s": 541, "text": "Odd(L, R) = R % 2 == 1? Odd(L, R – 2) : Odd(L, R – 1) " }, { "code": null, "e": 692, "s": 596, "text": "Print the even elements from the range using recursion using the following recurrence relation:" }, { "code": null, "e": 751, "s": 692, "text": "Even(L, R) = R % 2 == 0 ? Even(L, R – 2) : Even(L, R – 1) " }, { "code": null, "e": 802, "s": 751, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 806, "s": 802, "text": "C++" }, { "code": null, "e": 811, "s": 806, "text": "Java" }, { "code": null, "e": 819, "s": 811, "text": "Python3" }, { "code": null, "e": 822, "s": 819, "text": "C#" }, { "code": null, "e": 833, "s": 822, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std; // Function to print all the// even numbers from L to Rvoid Even(int L, int R){ // Base case if (R < L) { return; } // Recurrence relation R % 2 == 0 ? Even(L, R - 2) : Even(L, R - 1); // Check if R is even if (R % 2 == 0) { cout << R << \" \"; }} // Function to print all the// odd numbers from L to Rvoid Odd(int L, int R){ // Base case if (R < L) { return; } // Recurrence relation R % 2 == 1 ? Odd(L, R - 2) : Odd(L, R - 1); // Check if R is even if (R % 2 == 1) { cout << R << \" \"; }} // Driver Codeint main(){ int L = 10, R = 25; cout << \"Even numbers:\"; // Print all the // even numbers Even(L, R); cout << endl; // Print all the // odd numbers cout << \"Odd numbers:\"; Odd(L, R);}", "e": 1754, "s": 833, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*;class GFG{ // Function to print// all the even numbers// from L to Rstatic void Even(int L, int R){ // Base case if (R < L) { return; } // Recurrence relation if(R % 2 == 0 ) Even(L, R - 2); else Even(L, R - 1); // Check if R is even if (R % 2 == 0) { System.out.print(R + \" \"); }} // Function to print// all the odd numbers// from L to Rstatic void Odd(int L, int R){ // Base case if (R < L) { return; } // Recurrence relation if(R % 2 == 1 ) Odd(L, R - 2); else Odd(L, R - 1); // Check if R is even if (R % 2 == 1) { System.out.print(R + \" \"); }} // Driver Codepublic static void main(String[] args){ int L = 10, R = 25; System.out.print(\"Even numbers:\"); // Print all the // even numbers Even(L, R); System.out.println(); // Print all the // odd numbers System.out.print(\"Odd numbers:\"); Odd(L, R);}} // This code is contributed by Rajput-Ji", "e": 2760, "s": 1754, "text": null }, { "code": "# Python3 program to implement# the above approach # Function to print all the# even numbers from L to Rdef Even(L, R): # Base case if (R < L): return # Recurrence relation if (R % 2 == 0): Even(L, R - 2) else: Even(L, R - 1) # Check if R is even if (R % 2 == 0): print(R, end = \" \") # Function to print all the# odd numbers from L to Rdef Odd(L, R): # Base case if (R < L): return # Recurrence relation if (R % 2 == 1): Odd(L, R - 2) else: Odd(L, R - 1) # Check if R is even if (R % 2 == 1): print(R, end = \" \") # Driver Codeif __name__ == '__main__': L = 10 R = 25 print(\"Even numbers:\") # Print all the # even numbers Even(L, R) print() # Print all the # odd numbers print(\"Odd numbers:\") Odd(L, R) # This code is contributed by Amit Katiyar", "e": 3662, "s": 2760, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ // Function to print// all the even numbers// from L to Rstatic void Even(int L, int R){ // Base case if (R < L) { return; } // Recurrence relation if(R % 2 == 0 ) Even(L, R - 2); else Even(L, R - 1); // Check if R is even if (R % 2 == 0) { Console.Write(R + \" \"); }} // Function to print// all the odd numbers// from L to Rstatic void Odd(int L, int R){ // Base case if (R < L) { return; } // Recurrence relation if(R % 2 == 1 ) Odd(L, R - 2); else Odd(L, R - 1); // Check if R is even if (R % 2 == 1) { Console.Write(R + \" \"); }} // Driver Codepublic static void Main(String[] args){ int L = 10, R = 25; Console.Write(\"Even numbers:\"); // Print all the // even numbers Even(L, R); Console.WriteLine(); // Print all the // odd numbers Console.Write(\"Odd numbers:\"); Odd(L, R);}} // This code is contributed by 29AjayKumar", "e": 4649, "s": 3662, "text": null }, { "code": "<script> // Java script program to implement// the above approach // Function to print// all the even numbers// from L to Rfunction Even(L, R){ // Base case if (R < L) { return; } // Recurrence relation if (R % 2 == 0 ) { Even(L, R - 2); } else { Even(L, R - 1); } // Check if R is even if (R % 2 == 0) { document.write(R + \" \"); }} // Function to print// all the odd numbers// from L to Rfunction Odd(L, R){ // Base case if (R < L) { return; } // Recurrence relation if (R % 2 == 1 ) { Odd(L, R - 2); } else { Odd(L, R - 1); } // Check if R is even if (R % 2 == 1) { document.write(R + \" \"); }} // Driver Codelet L = 10;let R = 25;document.write(\"Even numbers:\"); // Print all the// even numbersEven(L, R);document.write(\"<br>\"); // Print all the// odd numbersdocument.write(\"Odd numbers:\");Odd(L, R); // This code is contributed by sravan kumar G </script>", "e": 5684, "s": 4649, "text": null }, { "code": null, "e": 5758, "s": 5684, "text": "Even numbers:10 12 14 16 18 20 22 24 \nOdd numbers:11 13 15 17 19 21 23 25" }, { "code": null, "e": 5803, "s": 5760, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 5813, "s": 5803, "text": "Rajput-Ji" }, { "code": null, "e": 5825, "s": 5813, "text": "29AjayKumar" }, { "code": null, "e": 5840, "s": 5825, "text": "amit143katiyar" }, { "code": null, "e": 5856, "s": 5840, "text": "sravankumar8128" }, { "code": null, "e": 5876, "s": 5856, "text": "Number Divisibility" }, { "code": null, "e": 5889, "s": 5876, "text": "Mathematical" }, { "code": null, "e": 5899, "s": 5889, "text": "Recursion" }, { "code": null, "e": 5912, "s": 5899, "text": "Mathematical" }, { "code": null, "e": 5922, "s": 5912, "text": "Recursion" } ]
Python – Check if string contains any number
06 Jul, 2022 In this article, we will check How to check if a string contains a number in Python. Input : test_str = ‘geeks4g2eeks’ Output : True Explanation : Contains 4 and 2. Input : test_str = ‘geeksforgeeks’ Output : False Explanation : Contains no number. The combination of the above functions can be used to solve this problem. In this, we check for numbers using isdigit() and check for any occurrence using any(). Python3 # Python3 code to demonstrate working of# Check if string contains any number# Using isdigit() + any() # initializing stringtest_str = 'geeks4geeks' # printing original stringprint("The original string is : " + str(test_str)) # using any() to check for any occurrenceres = any(chr.isdigit() for chr in test_str) # printing resultprint("Does string contain any digit ? : " + str(res)) Output The original string is : geeks4geeks Does string contain any digit ? : Tru This is yet another way in which this task can be performed. This is recommended in cases of larger strings, the iteration in the generator is cheap, but construction is usually inefficient. Python3 # Python3 code to demonstrate working of# Check if string contains any number# Using isdigit() + next() + generator expression # initializing stringtest_str = 'geeks4geeks' # printing original stringprint("The original string is : " + str(test_str)) # next() checking for each element, reaches end, if no element found as digitres = True if next((chr for chr in test_str if chr.isdigit()), None) else False # printing resultprint("Does string contain any digit ? : " + str(res)) Output The original string is : geeks4geeks Does string contain any digit ? : True In this example, we will see if the string contains any number or not using the map function. The map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable. Python3 str1 = "Geeks"str2 = "for345"str3 = "Geeks" print(any(map(str.isdigit, str1)))print(any(map(str.isdigit, str2)))print(any(map(str.isdigit, str3))) Output: False True False In this example, we will use the regular expression to check if the string contains the digit or not. A regular expression is a powerful tool for matching text, based on a pre-defined pattern. To check the digit, regular expression use \d which matches the digit character. Python3 import re str1 = "Geek3s"str2 = "for345"str3 = "Geeks" print(bool(re.search(r'\d', str1)))print(bool(re.search(r'\d', str2)))print(bool(re.search(r'\d', str3))) Output: True True False surajkumarguptaintern Python string-programs Python Python Programs 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 program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python | Convert string dictionary to dictionary
[ { "code": null, "e": 53, "s": 25, "text": "\n06 Jul, 2022" }, { "code": null, "e": 139, "s": 53, "text": "In this article, we will check How to check if a string contains a number in Python. " }, { "code": null, "e": 174, "s": 139, "text": "Input : test_str = ‘geeks4g2eeks’ " }, { "code": null, "e": 189, "s": 174, "text": "Output : True " }, { "code": null, "e": 222, "s": 189, "text": "Explanation : Contains 4 and 2. " }, { "code": null, "e": 258, "s": 222, "text": "Input : test_str = ‘geeksforgeeks’ " }, { "code": null, "e": 274, "s": 258, "text": "Output : False " }, { "code": null, "e": 308, "s": 274, "text": "Explanation : Contains no number." }, { "code": null, "e": 470, "s": 308, "text": "The combination of the above functions can be used to solve this problem. In this, we check for numbers using isdigit() and check for any occurrence using any()." }, { "code": null, "e": 478, "s": 470, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Check if string contains any number# Using isdigit() + any() # initializing stringtest_str = 'geeks4geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # using any() to check for any occurrenceres = any(chr.isdigit() for chr in test_str) # printing resultprint(\"Does string contain any digit ? : \" + str(res))", "e": 866, "s": 478, "text": null }, { "code": null, "e": 873, "s": 866, "text": "Output" }, { "code": null, "e": 948, "s": 873, "text": "The original string is : geeks4geeks\nDoes string contain any digit ? : Tru" }, { "code": null, "e": 1139, "s": 948, "text": "This is yet another way in which this task can be performed. This is recommended in cases of larger strings, the iteration in the generator is cheap, but construction is usually inefficient." }, { "code": null, "e": 1147, "s": 1139, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of# Check if string contains any number# Using isdigit() + next() + generator expression # initializing stringtest_str = 'geeks4geeks' # printing original stringprint(\"The original string is : \" + str(test_str)) # next() checking for each element, reaches end, if no element found as digitres = True if next((chr for chr in test_str if chr.isdigit()), None) else False # printing resultprint(\"Does string contain any digit ? : \" + str(res))", "e": 1630, "s": 1147, "text": null }, { "code": null, "e": 1637, "s": 1630, "text": "Output" }, { "code": null, "e": 1713, "s": 1637, "text": "The original string is : geeks4geeks\nDoes string contain any digit ? : True" }, { "code": null, "e": 1952, "s": 1713, "text": "In this example, we will see if the string contains any number or not using the map function. The map() function returns a map object(which is an iterator) of the results after applying the given function to each item of a given iterable." }, { "code": null, "e": 1960, "s": 1952, "text": "Python3" }, { "code": "str1 = \"Geeks\"str2 = \"for345\"str3 = \"Geeks\" print(any(map(str.isdigit, str1)))print(any(map(str.isdigit, str2)))print(any(map(str.isdigit, str3)))", "e": 2107, "s": 1960, "text": null }, { "code": null, "e": 2115, "s": 2107, "text": "Output:" }, { "code": null, "e": 2132, "s": 2115, "text": "False\nTrue\nFalse" }, { "code": null, "e": 2406, "s": 2132, "text": "In this example, we will use the regular expression to check if the string contains the digit or not. A regular expression is a powerful tool for matching text, based on a pre-defined pattern. To check the digit, regular expression use \\d which matches the digit character." }, { "code": null, "e": 2414, "s": 2406, "text": "Python3" }, { "code": "import re str1 = \"Geek3s\"str2 = \"for345\"str3 = \"Geeks\" print(bool(re.search(r'\\d', str1)))print(bool(re.search(r'\\d', str2)))print(bool(re.search(r'\\d', str3)))", "e": 2575, "s": 2414, "text": null }, { "code": null, "e": 2583, "s": 2575, "text": "Output:" }, { "code": null, "e": 2599, "s": 2583, "text": "True\nTrue\nFalse" }, { "code": null, "e": 2621, "s": 2599, "text": "surajkumarguptaintern" }, { "code": null, "e": 2644, "s": 2621, "text": "Python string-programs" }, { "code": null, "e": 2651, "s": 2644, "text": "Python" }, { "code": null, "e": 2667, "s": 2651, "text": "Python Programs" }, { "code": null, "e": 2765, "s": 2667, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2807, "s": 2765, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2829, "s": 2807, "text": "Enumerate() in Python" }, { "code": null, "e": 2855, "s": 2829, "text": "Python String | replace()" }, { "code": null, "e": 2887, "s": 2855, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2916, "s": 2887, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2959, "s": 2916, "text": "Python program to convert a list to string" }, { "code": null, "e": 2981, "s": 2959, "text": "Defaultdict in Python" }, { "code": null, "e": 3020, "s": 2981, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3058, "s": 3020, "text": "Python | Convert a list to dictionary" } ]
Get only the date in timestamp in MySQL?
In order to get the date from the timestamp, you can use DATE() function from MySQL. The syntax is as follows − SELECT DATE(yourTimestampColumnName) as anyVariableName from yourTableName; To understand the above syntax, let us first create a table. The query to create a table is as follows − mysql> create table DateFromTimestamp -> ( -> ShippingDateTime timestamp -> ); Query OK, 0 rows affected (0.60 sec) Insert date and time for the column ShippingDateTime we created above. The query to insert record is as follows − mysql> insert into DateFromTimestamp values('2012-12-26 13:24:35'); Query OK, 1 row affected (0.14 sec) mysql> insert into DateFromTimestamp values('2013-11-26 14:36:40'); Query OK, 1 row affected (0.13 sec) mysql> insert into DateFromTimestamp values('2016-07-22 15:20:10'); Query OK, 1 row affected (0.19 sec) mysql> insert into DateFromTimestamp values('2017-11-04 04:25:30'); Query OK, 1 row affected (0.15 sec) Display all records from the table using select command. The query is as follows − mysql> select *from DateFromTimestamp; +---------------------+ | ShippingDateTime | +---------------------+ | 2012-12-26 13:24:35 | | 2013-11-26 14:36:40 | | 2016-07-22 15:20:10 | | 2017-11-04 04:25:30 | +---------------------+ 4 rows in set (0.00 sec) The following is the query to display only date from a timestamp using date() function − mysql> select date(ShippingDateTime) as OnlyDatePartFromTimestamp from DateFromTimestamp; +---------------------------+ | OnlyDatePartFromTimestamp | +---------------------------+ | 2012-12-26 | | 2013-11-26 | | 2016-07-22 | | 2017-11-04 | +---------------------------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1272, "s": 1187, "text": "In order to get the date from the timestamp, you can use DATE() function from MySQL." }, { "code": null, "e": 1299, "s": 1272, "text": "The syntax is as follows −" }, { "code": null, "e": 1375, "s": 1299, "text": "SELECT DATE(yourTimestampColumnName) as anyVariableName from yourTableName;" }, { "code": null, "e": 1480, "s": 1375, "text": "To understand the above syntax, let us first create a table. The query to create a table is as follows −" }, { "code": null, "e": 1596, "s": 1480, "text": "mysql> create table DateFromTimestamp\n-> (\n-> ShippingDateTime timestamp\n-> );\nQuery OK, 0 rows affected (0.60 sec)" }, { "code": null, "e": 1667, "s": 1596, "text": "Insert date and time for the column ShippingDateTime we created above." }, { "code": null, "e": 1710, "s": 1667, "text": "The query to insert record is as follows −" }, { "code": null, "e": 2129, "s": 1710, "text": "mysql> insert into DateFromTimestamp values('2012-12-26 13:24:35');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DateFromTimestamp values('2013-11-26 14:36:40');\nQuery OK, 1 row affected (0.13 sec)\n\nmysql> insert into DateFromTimestamp values('2016-07-22 15:20:10');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into DateFromTimestamp values('2017-11-04 04:25:30');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 2212, "s": 2129, "text": "Display all records from the table using select command. The query is as follows −" }, { "code": null, "e": 2251, "s": 2212, "text": "mysql> select *from DateFromTimestamp;" }, { "code": null, "e": 2468, "s": 2251, "text": "+---------------------+\n| ShippingDateTime |\n+---------------------+\n| 2012-12-26 13:24:35 |\n| 2013-11-26 14:36:40 |\n| 2016-07-22 15:20:10 |\n| 2017-11-04 04:25:30 |\n+---------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2557, "s": 2468, "text": "The following is the query to display only date from a timestamp using date() function −" }, { "code": null, "e": 2647, "s": 2557, "text": "mysql> select date(ShippingDateTime) as OnlyDatePartFromTimestamp from\nDateFromTimestamp;" }, { "code": null, "e": 2912, "s": 2647, "text": "+---------------------------+\n| OnlyDatePartFromTimestamp |\n+---------------------------+\n| 2012-12-26 |\n| 2013-11-26 |\n| 2016-07-22 |\n| 2017-11-04 |\n+---------------------------+\n4 rows in set (0.00 sec)" } ]