title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Find n-th term of series 1, 4, 27, 16, 125, 36, 343 ....... - GeeksforGeeks
10 Mar, 2021 Given a number n, find the n-th term in the series 1, 4, 27, 16, 125, 36, 343........Examples: Input : 5 Output : 125 Input : 6 Output : 36 Naive approach : In this Sequence, if the Nth term is even then the Nth term is square of N else Nth term is a cube of N. N = 5 In this case, N is odd N = N * N * N N = 5 * 5 * 5 N = 125Similarly, N = 6 N = N * N N = 6 * 6 N = 36 and so on.. Implementation of the above approach is given below: C++ Java Python 3 C# PHP Javascript // CPP code to generate first 'n' terms// of Logic sequence#include <bits/stdc++.h>using namespace std; // Function to generate a fixed \numberint logicOfSequence(int N){ if (N % 2 == 0) N = N * N; else N = N * N * N; return N;} // Driver Methodint main(){ int N = 6; cout << logicOfSequence(N) << endl; return 0;} // JAVA code to generate first// 'n' terms of Logic sequence class GFG { // Function to generate// a fixed \numberpublic static int logicOfSequence(int N){ if (N % 2 == 0) N = N * N; else N = N * N * N; return N;} // Driver Methodpublic static void main(String args[]){ int N = 6; System.out.println(logicOfSequence(N));}} // This code is contributed by Jaideep Pyne # Python code to generate first# 'n' terms of Logic sequence # Function to generate a fixed# numberdef logicOfSequence(N): if(N % 2 == 0): N = N * N else: N = N * N * N return N N = 6print (logicOfSequence(N)) # This code is contributed by# Vishal Gupta // C# code to generate first// 'n' terms of Logic sequenceusing System; class GFG { // Function to generate// a fixed numberpublic static int logicOfSequence(int N){ if (N % 2 == 0) N = N * N; else N = N * N * N; return N;} // Driver Methodpublic static void Main(){ int N = 6; Console.Write(logicOfSequence(N));}} // This code is contributed by nitin mittal <?php// PHP code to generate first 'n' terms// of Logic sequence // Function to generate a fixed numberfunction logicOfSequence($N){ if ($N % 2 == 0) $N = $N * $N; else $N = $N * $N * $N; return $N;} // Driver Code $N = 6; echo logicOfSequence($N); // This code is contributed by nitin mittal.?> <script>// JavaScript code to generate first 'n' terms// of Logic sequence // Function to generate a fixed \numberfunction logicOfSequence( N){ if (N % 2 == 0) N = N * N; else N = N * N * N; return N;} // Driver Function let N = 6; document.write(logicOfSequence(N)); // This code contributed by Rajput-Ji </script> Output: 36 Time Complexity : O(1) jaideeppyne1997 vishal9619 nitin mittal Rajput-Ji School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Operator Overloading in C++ Overriding in Java Polymorphism in C++ Constructors in Java Inheritance in Java Different ways of Reading a text file in Java Python program to check if a string is palindrome or not Friend class and function in C++ Types of Operating Systems
[ { "code": null, "e": 25152, "s": 25124, "text": "\n10 Mar, 2021" }, { "code": null, "e": 25249, "s": 25152, "text": "Given a number n, find the n-th term in the series 1, 4, 27, 16, 125, 36, 343........Examples: " }, { "code": null, "e": 25295, "s": 25249, "text": "Input : 5\nOutput : 125\n\nInput : 6\nOutput : 36" }, { "code": null, "e": 25420, "s": 25297, "text": "Naive approach : In this Sequence, if the Nth term is even then the Nth term is square of N else Nth term is a cube of N. " }, { "code": null, "e": 25542, "s": 25420, "text": "N = 5 In this case, N is odd N = N * N * N N = 5 * 5 * 5 N = 125Similarly, N = 6 N = N * N N = 6 * 6 N = 36 and so on.. " }, { "code": null, "e": 25597, "s": 25542, "text": "Implementation of the above approach is given below: " }, { "code": null, "e": 25601, "s": 25597, "text": "C++" }, { "code": null, "e": 25606, "s": 25601, "text": "Java" }, { "code": null, "e": 25615, "s": 25606, "text": "Python 3" }, { "code": null, "e": 25618, "s": 25615, "text": "C#" }, { "code": null, "e": 25622, "s": 25618, "text": "PHP" }, { "code": null, "e": 25633, "s": 25622, "text": "Javascript" }, { "code": "// CPP code to generate first 'n' terms// of Logic sequence#include <bits/stdc++.h>using namespace std; // Function to generate a fixed \\numberint logicOfSequence(int N){ if (N % 2 == 0) N = N * N; else N = N * N * N; return N;} // Driver Methodint main(){ int N = 6; cout << logicOfSequence(N) << endl; return 0;}", "e": 25985, "s": 25633, "text": null }, { "code": "// JAVA code to generate first// 'n' terms of Logic sequence class GFG { // Function to generate// a fixed \\numberpublic static int logicOfSequence(int N){ if (N % 2 == 0) N = N * N; else N = N * N * N; return N;} // Driver Methodpublic static void main(String args[]){ int N = 6; System.out.println(logicOfSequence(N));}} // This code is contributed by Jaideep Pyne", "e": 26381, "s": 25985, "text": null }, { "code": "# Python code to generate first# 'n' terms of Logic sequence # Function to generate a fixed# numberdef logicOfSequence(N): if(N % 2 == 0): N = N * N else: N = N * N * N return N N = 6print (logicOfSequence(N)) # This code is contributed by# Vishal Gupta", "e": 26658, "s": 26381, "text": null }, { "code": "// C# code to generate first// 'n' terms of Logic sequenceusing System; class GFG { // Function to generate// a fixed numberpublic static int logicOfSequence(int N){ if (N % 2 == 0) N = N * N; else N = N * N * N; return N;} // Driver Methodpublic static void Main(){ int N = 6; Console.Write(logicOfSequence(N));}} // This code is contributed by nitin mittal", "e": 27046, "s": 26658, "text": null }, { "code": "<?php// PHP code to generate first 'n' terms// of Logic sequence // Function to generate a fixed numberfunction logicOfSequence($N){ if ($N % 2 == 0) $N = $N * $N; else $N = $N * $N * $N; return $N;} // Driver Code $N = 6; echo logicOfSequence($N); // This code is contributed by nitin mittal.?>", "e": 27375, "s": 27046, "text": null }, { "code": "<script>// JavaScript code to generate first 'n' terms// of Logic sequence // Function to generate a fixed \\numberfunction logicOfSequence( N){ if (N % 2 == 0) N = N * N; else N = N * N * N; return N;} // Driver Function let N = 6; document.write(logicOfSequence(N)); // This code contributed by Rajput-Ji </script>", "e": 27730, "s": 27375, "text": null }, { "code": null, "e": 27739, "s": 27730, "text": "Output: " }, { "code": null, "e": 27742, "s": 27739, "text": "36" }, { "code": null, "e": 27766, "s": 27742, "text": "Time Complexity : O(1) " }, { "code": null, "e": 27782, "s": 27766, "text": "jaideeppyne1997" }, { "code": null, "e": 27793, "s": 27782, "text": "vishal9619" }, { "code": null, "e": 27806, "s": 27793, "text": "nitin mittal" }, { "code": null, "e": 27816, "s": 27806, "text": "Rajput-Ji" }, { "code": null, "e": 27835, "s": 27816, "text": "School Programming" }, { "code": null, "e": 27933, "s": 27835, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27952, "s": 27933, "text": "Interfaces in Java" }, { "code": null, "e": 27980, "s": 27952, "text": "Operator Overloading in C++" }, { "code": null, "e": 27999, "s": 27980, "text": "Overriding in Java" }, { "code": null, "e": 28019, "s": 27999, "text": "Polymorphism in C++" }, { "code": null, "e": 28040, "s": 28019, "text": "Constructors in Java" }, { "code": null, "e": 28060, "s": 28040, "text": "Inheritance in Java" }, { "code": null, "e": 28106, "s": 28060, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 28163, "s": 28106, "text": "Python program to check if a string is palindrome or not" }, { "code": null, "e": 28196, "s": 28163, "text": "Friend class and function in C++" } ]
How to create a responsive bottom navigation menu with CSS and JavaScript?
Following is the code to create a responsive bottom navigation menu with CSS and JavaScript − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { margin: 0px; margin-top: 10px; padding: 0px; } nav { position: fixed; bottom: 0; width: 100%; background-color: rgb(39, 39, 39); overflow: auto; height: auto; } .links { display: inline-block; text-align: center; padding: 14px; color: rgb(178, 137, 253); text-decoration: none; font-size: 17px; } .links:hover { background-color: rgb(100, 100, 100); } .selected { background-color: rgb(0, 18, 43); } .hamburger { color: white; font-weight: bolder; display: none; } @media screen and (max-width: 600px) { nav a:not(:first-child) { display: none; } nav a.hamburger { float: right; display: block; padding: 12px; } nav.openNav a.hamburger { position: absolute; right: 0; bottom: 0; } nav.openNav a { float: none; display: block; text-align: center; } } </style> </head> <body> <nav class="bottomNav"> <a class="links selected" href="#"> Home</a> <a class="links" href="#"> Login</a> <a class="links" href="#">Register</a> <a class="links" href="#"> Contact Us</a> <a class="links" href="#">More Info</a> <a class="hamburger">☰</a> </nav> <div> <h1>Bottom navigation menu</h1> </div> <script> function toggleNav() { var x = document.getElementsByTagName("nav")[0]; if (x.className === "bottomNav") { x.className += " openNav"; } else { x.className = "bottomNav"; } } document.querySelector(".hamburger").addEventListener("click", toggleNav); </script> </body> </html> The above code will produce the following output − On resizing the browser the hamburger icon to open navigation will be shown − On clicking the hamburger icon −
[ { "code": null, "e": 1156, "s": 1062, "text": "Following is the code to create a responsive bottom navigation menu with CSS and JavaScript −" }, { "code": null, "e": 1167, "s": 1156, "text": " Live Demo" }, { "code": null, "e": 2822, "s": 1167, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\nbody {\n margin: 0px;\n margin-top: 10px;\n padding: 0px;\n}\nnav {\n position: fixed;\n bottom: 0;\n width: 100%;\n background-color: rgb(39, 39, 39);\n overflow: auto;\n height: auto;\n}\n.links {\n display: inline-block;\n text-align: center;\n padding: 14px;\n color: rgb(178, 137, 253);\n text-decoration: none;\n font-size: 17px;\n}\n.links:hover {\n background-color: rgb(100, 100, 100);\n}\n.selected {\n background-color: rgb(0, 18, 43);\n}\n.hamburger {\n color: white;\n font-weight: bolder;\n display: none;\n}\n@media screen and (max-width: 600px) {\nnav a:not(:first-child) {\n display: none;\n}\nnav a.hamburger {\n float: right;\n display: block;\n padding: 12px;\n}\nnav.openNav a.hamburger {\n position: absolute;\n right: 0;\n bottom: 0;\n}\nnav.openNav a {\n float: none;\n display: block;\n text-align: center;\n}\n}\n</style>\n</head>\n<body>\n<nav class=\"bottomNav\">\n<a class=\"links selected\" href=\"#\"> Home</a>\n<a class=\"links\" href=\"#\"> Login</a>\n<a class=\"links\" href=\"#\">Register</a>\n<a class=\"links\" href=\"#\"> Contact Us</a>\n<a class=\"links\" href=\"#\">More Info</a>\n<a class=\"hamburger\">☰</a>\n</nav>\n<div>\n<h1>Bottom navigation menu</h1>\n</div>\n<script>\nfunction toggleNav() {\n var x = document.getElementsByTagName(\"nav\")[0];\n if (x.className === \"bottomNav\") {\n x.className += \" openNav\";\n } else {\n x.className = \"bottomNav\";\n }\n}\ndocument.querySelector(\".hamburger\").addEventListener(\"click\", toggleNav);\n</script>\n</body>\n</html>" }, { "code": null, "e": 2873, "s": 2822, "text": "The above code will produce the following output −" }, { "code": null, "e": 2951, "s": 2873, "text": "On resizing the browser the hamburger icon to open navigation will be shown −" }, { "code": null, "e": 2984, "s": 2951, "text": "On clicking the hamburger icon −" } ]
Adding new options in Dropdown dynamically using ReactJS - GeeksforGeeks
18 Jan, 2021 Creating our own options in the dropdown means that whenever the user types any new value other than the values shown in the options, that new value should be added to the drop down menu as an option. Material UI for React has this component available for us and it is very easy to integrate. 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 filter = createFilterOptions(); const App = () => { // Our sample dropdown options const options = ['One', 'Two', 'Three', 'Four'] return ( <div style={{ marginLeft: '40%', marginTop: '60px' }}> <h3>Greetings from GeeksforGeeks!</h3> <Autocomplete filterOptions={(options, params) => { const filtered = filter(options, params); // Suggest the creation of a new value if (params.inputValue !== '') { filtered.push(`Add "${params.inputValue}"`); } return filtered; }} selectOnFocus clearOnBlur handleHomeEndKeys options={options} renderOption={(option) => option} style={{ width: 300 }} freeSolo renderInput={(params) => ( <TextField {...params} label="Enter Something" variant="outlined" /> )} /> </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: All Options Available Now if we start typing any other text apart from these options, it will show the Add feature to add our user typed option as shown below: Adding New Option Note: Now you can handle this new input with handleChange() function and push it to our options array as per user need. JavaScript ReactJS Technical Scripter Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Set the value of an input field in JavaScript Difference Between PUT and PATCH Request How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? Create a Responsive Navbar using ReactJS
[ { "code": null, "e": 24870, "s": 24842, "text": "\n18 Jan, 2021" }, { "code": null, "e": 25163, "s": 24870, "text": "Creating our own options in the dropdown means that whenever the user types any new value other than the values shown in the options, that new value should be added to the drop down menu as an option. Material UI for React has this component available for us and it is very easy to integrate." }, { "code": null, "e": 25213, "s": 25163, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 25277, "s": 25213, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 25309, "s": 25277, "text": "npx create-react-app foldername" }, { "code": null, "e": 25409, "s": 25309, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 25423, "s": 25409, "text": "cd foldername" }, { "code": null, "e": 25532, "s": 25423, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:" }, { "code": null, "e": 25591, "s": 25532, "text": "npm install @material-ui/core\nnpm install @material-ui/lab" }, { "code": null, "e": 25643, "s": 25591, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 25661, "s": 25643, "text": "Project Structure" }, { "code": null, "e": 25790, "s": 25661, "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": 25801, "s": 25790, "text": "Javascript" }, { "code": "import React from 'react'import TextField from '@material-ui/core/TextField';import Autocomplete,{ createFilterOptions } from '@material-ui/lab/Autocomplete';const filter = createFilterOptions(); const App = () => { // Our sample dropdown options const options = ['One', 'Two', 'Three', 'Four'] return ( <div style={{ marginLeft: '40%', marginTop: '60px' }}> <h3>Greetings from GeeksforGeeks!</h3> <Autocomplete filterOptions={(options, params) => { const filtered = filter(options, params); // Suggest the creation of a new value if (params.inputValue !== '') { filtered.push(`Add \"${params.inputValue}\"`); } return filtered; }} selectOnFocus clearOnBlur handleHomeEndKeys options={options} renderOption={(option) => option} style={{ width: 300 }} freeSolo renderInput={(params) => ( <TextField {...params} label=\"Enter Something\" variant=\"outlined\" /> )} /> </div> );} export default App", "e": 26875, "s": 25801, "text": null }, { "code": null, "e": 26988, "s": 26875, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 26998, "s": 26988, "text": "npm start" }, { "code": null, "e": 27097, "s": 26998, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 27119, "s": 27097, "text": "All Options Available" }, { "code": null, "e": 27257, "s": 27119, "text": "Now if we start typing any other text apart from these options, it will show the Add feature to add our user typed option as shown below:" }, { "code": null, "e": 27275, "s": 27257, "text": "Adding New Option" }, { "code": null, "e": 27395, "s": 27275, "text": "Note: Now you can handle this new input with handleChange() function and push it to our options array as per user need." }, { "code": null, "e": 27406, "s": 27395, "text": "JavaScript" }, { "code": null, "e": 27414, "s": 27406, "text": "ReactJS" }, { "code": null, "e": 27433, "s": 27414, "text": "Technical Scripter" }, { "code": null, "e": 27450, "s": 27433, "text": "Web Technologies" }, { "code": null, "e": 27548, "s": 27450, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27557, "s": 27548, "text": "Comments" }, { "code": null, "e": 27570, "s": 27557, "text": "Old Comments" }, { "code": null, "e": 27615, "s": 27570, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27676, "s": 27615, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27748, "s": 27676, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 27794, "s": 27748, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 27835, "s": 27794, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27878, "s": 27835, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27923, "s": 27878, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27988, "s": 27923, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 28056, "s": 27988, "text": "How to pass data from one component to other component in ReactJS ?" } ]
Genetic Algorithm Implementation in Python | by Ahmed Gad | Towards Data Science
This tutorial will implement the genetic algorithm optimization technique in Python based on a simple example in which we are trying to maximize the output of an equation. The tutorial uses the decimal representation for genes, one point crossover, and uniform mutation. 5 May 2020 Note The GitHub project of this tutorial is updated where major changes to the project are made to support multiple features: https://github.com/ahmedfgad/GeneticAlgorithmPython. For example, multiple types of mutation and crossover are implemented in addition to the ability to customize the fitness function to work on any type of problem. Based on the project, a library named PyGAD is deployed to PyPI where you can install using pip:https://pypi.org/project/pygad The original code of this tutorial is available under the Tutorial Project directory which is available at this link: https://github.com/ahmedfgad/GeneticAlgorithmPython/tree/master/Tutorial%20Project Flowchart of the genetic algorithm (GA) is shown in figure 1. Each step involved in the GA has some variations. For example, there are different types of representations for genes such as binary, decimal, integer, and others. Each type is treated differently. There are different types of mutation such as bit flip, swap, inverse, uniform, non-uniform, Gaussian, shrink, and others. Also, crossover has different types such as blend, one point, two points, uniform, and others. This tutorial will not implement all of them but just implements one type of each step involved in GA. The tutorial uses the decimal representation for genes, one point crossover, and uniform mutation. The Reader should have an understanding of how GA works. If not, please read this article titled “Introduction to Optimization with Genetic Algorithm” found in these links: LinkedIn: https://www.linkedin.com/pulse/introduction-optimization-genetic-algorithm-ahmed-gad/ KDnuggets: https://www.kdnuggets.com/2018/03/introduction-optimization-with-genetic-algorithm.html TowardsDataScience: https://towardsdatascience.com/introduction-to-optimization-with-genetic-algorithm-2f5001d9964b SlideShare: https://www.slideshare.net/AhmedGadFCIT/introduction-to-optimization-with-genetic-algorithm-ga The tutorial starts by presenting the equation that we are going to implement. The equation is shown below: Y = w1x1 + w2x2 + w3x3 + w4x4 + w5x5 + w6x6 The equation has 6 inputs (x1 to x6) and 6 weights (w1 to w6) as shown and inputs values are (x1,x2,x3,x4,x5,x6)=(4,-2,7,5,11,1). We are looking to find the parameters (weights) that maximize such equation. The idea of maximizing such equation seems simple. The positive input is to be multiplied by the largest possible positive number and the negative number is to be multiplied by the smallest possible negative number. But the idea we are looking to implement is how to make GA do that its own in order to know that it is better to use positive weight with positive inputs and negative weights with negative inputs. Let us start implementing GA. At first, let us create a list of the 6 inputs and a variable to hold the number of weights as follows: # Inputs of the equation. equation_inputs = [4,-2,3.5,5,-11,-4.7] # Number of the weights we are looking to optimize. num_weights = 6 The next step is to define the initial population. Based on the number of weights, each chromosome (solution or individual) in the population will definitely have 6 genes, one gene for each weight. But the question is how many solutions per the population? There is no fixed value for that and we can select the value that fits well with our problem. But we could leave it generic so that it can be changed in the code. Next, we create a variable that holds the number of solutions per population, another to hold the size of the population, and finally, a variable that holds the actual initial population: import numpysol_per_pop = 8# Defining the population size.pop_size = (sol_per_pop,num_weights) # The population will have sol_per_pop chromosome where each chromosome has num_weights genes.#Creating the initial population.new_population = numpy.random.uniform(low=-4.0, high=4.0, size=pop_size) After importing the numpy library, we are able to create the initial population randomly using the numpy.random.uniform function. According to the selected parameters, it will be of shape (8, 6). That is 8 chromosomes and each one has 6 genes, one for each weight. After running this code, the population is as follows: [[-2.19134006 -2.88907857 2.02365737 -3.97346034 3.45160502 2.05773249][ 2.12480298 2.97122243 3.60375452 3.78571392 0.28776565 3.5170347 ][ 1.81098962 0.35130155 1.03049548 -0.33163294 3.52586421 2.53845644][-0.63698911 -2.8638447 2.93392615 -1.40103767 -1.20313655 0.30567304][-1.48998583 -1.53845766 1.11905299 -3.67541087 1.33225142 2.86073836][ 1.14159503 2.88160332 1.74877772 -3.45854293 0.96125878 2.99178241][ 1.96561297 0.51030292 0.52852716 -1.56909315 -2.35855588 2.29682254][ 3.00912373 -2.745417 3.27131287 -0.72163167 0.7516408 0.00677938]] Note that it is generated randomly and thus it will definitely change when get run again. After preparing the population, next is to follow the flowchart in figure 1. Based on the fitness function, we are going to select the best individuals within the current population as parents for mating. Next is to apply the GA variants (crossover and mutation) to produce the offspring of the next generation, creating the new population by appending both parents and offspring, and repeating such steps for a number of iterations/generations. The next code applies these steps: import ganum_generations = 5num_parents_mating = 4for generation in range(num_generations): # Measuring the fitness of each chromosome in the population. fitness = ga.cal_pop_fitness(equation_inputs, new_population) # Selecting the best parents in the population for mating. parents = ga.select_mating_pool(new_population, fitness, num_parents_mating) # Generating next generation using crossover. offspring_crossover = ga.crossover(parents, offspring_size=(pop_size[0]-parents.shape[0], num_weights)) # Adding some variations to the offsrping using mutation. offspring_mutation = ga.mutation(offspring_crossover)# Creating the new population based on the parents and offspring. new_population[0:parents.shape[0], :] = parents new_population[parents.shape[0]:, :] = offspring_mutation The current number of generations is 5. It is selected to be small for presenting results of all generations within the tutorial. There is a module named GA that holds the implementation of the algorithm. The first step is to find the fitness value of each solution within the population using the ga.cal_pop_fitness function. The implementation of such function inside the GA module is as follows: def cal_pop_fitness(equation_inputs, pop): # Calculating the fitness value of each solution in the current population. # The fitness function calculates the sum of products between each input and its corresponding weight. fitness = numpy.sum(pop*equation_inputs, axis=1) return fitness The fitness function accepts both the equation inputs values (x1 to x6) in addition to the population. The fitness value is calculated as the sum of product (SOP) between each input and its corresponding gene (weight) according to our function. According to the number of solutions per population, there will be a number of SOPs. As we previously set the number of solutions to 8 in the variable named sol_per_pop, there will be 8 SOPs as shown below: [-63.41070188 14.40299221 -42.22532674 18.24112489 -45.44363278 -37.00404311 15.99527402 17.0688537 ] Note that the higher the fitness value the better the solution. After calculating the fitness values for all solutions, next is to select the best of them as parents in the mating pool according to the next function ga.select_mating_pool. Such function accepts the population, the fitness values, and the number of parents needed. It returns the parents selected. Its implementation inside the GA module is as follows: def select_mating_pool(pop, fitness, num_parents): # Selecting the best individuals in the current generation as parents for producing the offspring of the next generation. parents = numpy.empty((num_parents, pop.shape[1])) for parent_num in range(num_parents): max_fitness_idx = numpy.where(fitness == numpy.max(fitness)) max_fitness_idx = max_fitness_idx[0][0] parents[parent_num, :] = pop[max_fitness_idx, :] fitness[max_fitness_idx] = -99999999999 return parents Based on the number of parents required as defined in the variable num_parents_mating, the function creates an empty array to hold them as in this line: parents = numpy.empty((num_parents, pop.shape[1])) Looping through the current population, the function gets the index of the highest fitness value because it is the best solution to be selected according to this line: max_fitness_idx = numpy.where(fitness == numpy.max(fitness)) This index is used to retrieve the solution that corresponds to such fitness value using this line: parents[parent_num, :] = pop[max_fitness_idx, :] To avoid selecting such solution again, its fitness value is set to a very small value that is likely to not be selected again which is -99999999999. The parents array is returned finally which will be as follows according to our example: [[-0.63698911 -2.8638447 2.93392615 -1.40103767 -1.20313655 0.30567304][ 3.00912373 -2.745417 3.27131287 -0.72163167 0.7516408 0.00677938][ 1.96561297 0.51030292 0.52852716 -1.56909315 -2.35855588 2.29682254][ 2.12480298 2.97122243 3.60375452 3.78571392 0.28776565 3.5170347 ]] Note that these three parents are the best individuals within the current population based on their fitness values which are 18.24112489, 17.0688537, 15.99527402, and 14.40299221, respectively. Next step is to use such selected parents for mating in order to generate the offspring. The mating starts with the crossover operation according to the ga.crossover function. This function accepts the parents and the offspring size. It uses the offspring size to know the number of offspring to produce from such parents. Such a function is implemented as follows inside the GA module: def crossover(parents, offspring_size): offspring = numpy.empty(offspring_size) # The point at which crossover takes place between two parents. Usually, it is at the center. crossover_point = numpy.uint8(offspring_size[1]/2) for k in range(offspring_size[0]): # Index of the first parent to mate. parent1_idx = k%parents.shape[0] # Index of the second parent to mate. parent2_idx = (k+1)%parents.shape[0] # The new offspring will have its first half of its genes taken from the first parent. offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point] # The new offspring will have its second half of its genes taken from the second parent. offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:] return offspring The function starts by creating an empty array based on the offspring size as in this line: offspring = numpy.empty(offspring_size) Because we are using single point crossover, we need to specify the point at which crossover takes place. The point is selected to divide the solution into two equal halves according to this line: crossover_point = numpy.uint8(offspring_size[1]/2) Then we need to select the two parents to crossover. The indices of these parents are selected according to these two lines: parent1_idx = k%parents.shape[0]parent2_idx = (k+1)%parents.shape[0] The parents are selected in a way similar to a ring. The first with indices 0 and 1 are selected at first to produce two offspring. If there still remaining offspring to produce, then we select the parent 1 with parent 2 to produce another two offspring. If we are in need of more offspring, then we select the next two parents with indices 2 and 3. By index 3, we reached the last parent. If we need to produce more offspring, then we select parent with index 3 and go back to the parent with index 0, and so on. The solutions after applying the crossover operation to the parents are stored into the offspring variable and they are as follows: [[-0.63698911 -2.8638447 2.93392615 -0.72163167 0.7516408 0.00677938][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.35855588 2.29682254][ 1.96561297 0.51030292 0.52852716 3.78571392 0.28776565 3.5170347 ][ 2.12480298 2.97122243 3.60375452 -1.40103767 -1.20313655 0.30567304]] Next is to apply the second GA variant, mutation, to the results of the crossover stored in the offspring variable using the ga.mutation function inside the GA module. Such function accepts the crossover offspring and returns them after applying uniform mutation. That function is implemented as follows: def mutation(offspring_crossover): # Mutation changes a single gene in each offspring randomly. for idx in range(offspring_crossover.shape[0]): # The random value to be added to the gene. random_value = numpy.random.uniform(-1.0, 1.0, 1) offspring_crossover[idx, 4] = offspring_crossover[idx, 4] + random_value return offspring_crossover It loops through each offspring and adds a uniformly generated random number in the range from -1 to 1 according to this line: random_value = numpy.random.uniform(-1.0, 1.0, 1) Such random number is then added to the gene with index 4 of the offspring according to this line: offspring_crossover[idx, 4] = offspring_crossover[idx, 4] + random_value Note that the index could be changed to any other index. The offspring after applying mutation are as follows: [[-0.63698911 -2.8638447 2.93392615 -0.72163167 1.66083721 0.00677938][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254][ 1.96561297 0.51030292 0.52852716 3.78571392 0.45337472 3.5170347 ][ 2.12480298 2.97122243 3.60375452 -1.40103767 -1.5781162 0.30567304]] Such results are added to the variable offspring_crossover and got returned by the function. At this point, we successfully produced 4 offspring from the 4 selected parents and we are ready to create the new population of the next generation. Note that GA is a random-based optimization technique. It tries to enhance the current solutions by applying some random changes to them. Because such changes are random, we are not sure that they will produce better solutions. For such reason, it is preferred to keep the previous best solutions (parents) in the new population. In the worst case when all the new offspring are worse than such parents, we will continue using such parents. As a result, we guarantee that the new generation will at least preserve the previous good results and will not go worse. The new population will have its first 4 solutions from the previous parents. The last 4 solutions come from the offspring created after applying crossover and mutation: new_population[0:parents.shape[0], :] = parentsnew_population[parents.shape[0]:, :] = offspring_mutation By calculating the fitness of all solutions (parents and offspring) of the first generation, their fitness is as follows: [ 18.24112489 17.0688537 15.99527402 14.40299221 -8.46075629 31.73289712 6.10307563 24.08733441] The highest fitness previously was 18.24112489 but now it is 31.7328971158. That means that the random changes moved towards a better solution. This is GREAT. But such results could be enhanced by going through more generations. Below are the results of each step for another 4 generations: Generation : 1Fitness values:[ 18.24112489 17.0688537 15.99527402 14.40299221 -8.46075629 31.73289712 6.10307563 24.08733441]Selected parents:[[ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254][ 2.12480298 2.97122243 3.60375452 -1.40103767 -1.5781162 0.30567304][-0.63698911 -2.8638447 2.93392615 -1.40103767 -1.20313655 0.30567304][ 3.00912373 -2.745417 3.27131287 -0.72163167 0.7516408 0.00677938]]Crossover result:[[ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.5781162 0.30567304][ 2.12480298 2.97122243 3.60375452 -1.40103767 -1.20313655 0.30567304][-0.63698911 -2.8638447 2.93392615 -0.72163167 0.7516408 0.00677938][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254]]Mutation result:[[ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.2392086 0.30567304][ 2.12480298 2.97122243 3.60375452 -1.40103767 -0.38610586 0.30567304][-0.63698911 -2.8638447 2.93392615 -0.72163167 1.33639943 0.00677938][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.13941727 2.29682254]]Best result after generation 1 : 34.1663669207Generation : 2Fitness values:[ 31.73289712 24.08733441 18.24112489 17.0688537 34.16636692 10.97522073 -4.89194068 22.86998223]Selected Parents:[[ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.2392086 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254][ 2.12480298 2.97122243 3.60375452 -1.40103767 -1.5781162 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.13941727 2.29682254]]Crossover result:[[ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.5781162 0.30567304][ 2.12480298 2.97122243 3.60375452 -1.56909315 -1.13941727 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.2392086 0.30567304]]Mutation result:[[ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.20515009 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -0.73543721 0.30567304][ 2.12480298 2.97122243 3.60375452 -1.56909315 -0.50581509 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.20089639 0.30567304]]Best result after generation 2: 34.5930432629Generation : 3Fitness values:[ 34.16636692 31.73289712 24.08733441 22.86998223 34.59304326 28.6248816 2.09334217 33.7449326 ]Selected parents:[[ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.20515009 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.2392086 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.20089639 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254]]Crossover result:[[ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.2392086 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.20089639 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.20515009 2.29682254]]Mutation result:[[ 3.00912373 -2.745417 3.27131287 -1.40103767 -2.20744102 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.16589294 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.37553107 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.44124005 2.29682254]]Best result after generation 3: 44.8169235189Generation : 4Fitness values[ 34.59304326 34.16636692 33.7449326 31.73289712 44.8169235233.35989464 36.46723397 37.19003273]Selected parents:[[ 3.00912373 -2.745417 3.27131287 -1.40103767 -2.20744102 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.44124005 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.37553107 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.20515009 2.29682254]]Crossover result:[[ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.37553107 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.20515009 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -2.20744102 0.30567304]]Mutation result:[[ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.13382082 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.98105233 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.27638584 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.70558545 0.30567304]]Best result after generation 4: 44.8169235189 After the above 5 generations, the best result now has a fitness value equal to 44.8169235189 compared to the best result after the first generation which is 18.24112489. The best solution has the following weights: [3.00912373 -2.745417 3.27131287 -1.40103767 -2.20744102 0.30567304] The complete code is available in my GitHub account here: https://github.com/ahmedfgad/GeneticAlgorithmPython/tree/master/Tutorial%20Project. It will be listed in the tutorial too. Here is the implementation of the example: The GA module is as follows: The original article is available at LinkedIn on this page: https://www.linkedin.com/pulse/genetic-algorithm-implementation-python-ahmed-gad/
[ { "code": null, "e": 318, "s": 47, "text": "This tutorial will implement the genetic algorithm optimization technique in Python based on a simple example in which we are trying to maximize the output of an equation. The tutorial uses the decimal representation for genes, one point crossover, and uniform mutation." }, { "code": null, "e": 334, "s": 318, "text": "5 May 2020 Note" }, { "code": null, "e": 798, "s": 334, "text": "The GitHub project of this tutorial is updated where major changes to the project are made to support multiple features: https://github.com/ahmedfgad/GeneticAlgorithmPython. For example, multiple types of mutation and crossover are implemented in addition to the ability to customize the fitness function to work on any type of problem. Based on the project, a library named PyGAD is deployed to PyPI where you can install using pip:https://pypi.org/project/pygad" }, { "code": null, "e": 999, "s": 798, "text": "The original code of this tutorial is available under the Tutorial Project directory which is available at this link: https://github.com/ahmedfgad/GeneticAlgorithmPython/tree/master/Tutorial%20Project" }, { "code": null, "e": 1111, "s": 999, "text": "Flowchart of the genetic algorithm (GA) is shown in figure 1. Each step involved in the GA has some variations." }, { "code": null, "e": 1852, "s": 1111, "text": "For example, there are different types of representations for genes such as binary, decimal, integer, and others. Each type is treated differently. There are different types of mutation such as bit flip, swap, inverse, uniform, non-uniform, Gaussian, shrink, and others. Also, crossover has different types such as blend, one point, two points, uniform, and others. This tutorial will not implement all of them but just implements one type of each step involved in GA. The tutorial uses the decimal representation for genes, one point crossover, and uniform mutation. The Reader should have an understanding of how GA works. If not, please read this article titled “Introduction to Optimization with Genetic Algorithm” found in these links:" }, { "code": null, "e": 1948, "s": 1852, "text": "LinkedIn: https://www.linkedin.com/pulse/introduction-optimization-genetic-algorithm-ahmed-gad/" }, { "code": null, "e": 2047, "s": 1948, "text": "KDnuggets: https://www.kdnuggets.com/2018/03/introduction-optimization-with-genetic-algorithm.html" }, { "code": null, "e": 2163, "s": 2047, "text": "TowardsDataScience: https://towardsdatascience.com/introduction-to-optimization-with-genetic-algorithm-2f5001d9964b" }, { "code": null, "e": 2270, "s": 2163, "text": "SlideShare: https://www.slideshare.net/AhmedGadFCIT/introduction-to-optimization-with-genetic-algorithm-ga" }, { "code": null, "e": 2378, "s": 2270, "text": "The tutorial starts by presenting the equation that we are going to implement. The equation is shown below:" }, { "code": null, "e": 2422, "s": 2378, "text": "Y = w1x1 + w2x2 + w3x3 + w4x4 + w5x5 + w6x6" }, { "code": null, "e": 3072, "s": 2422, "text": "The equation has 6 inputs (x1 to x6) and 6 weights (w1 to w6) as shown and inputs values are (x1,x2,x3,x4,x5,x6)=(4,-2,7,5,11,1). We are looking to find the parameters (weights) that maximize such equation. The idea of maximizing such equation seems simple. The positive input is to be multiplied by the largest possible positive number and the negative number is to be multiplied by the smallest possible negative number. But the idea we are looking to implement is how to make GA do that its own in order to know that it is better to use positive weight with positive inputs and negative weights with negative inputs. Let us start implementing GA." }, { "code": null, "e": 3176, "s": 3072, "text": "At first, let us create a list of the 6 inputs and a variable to hold the number of weights as follows:" }, { "code": null, "e": 3310, "s": 3176, "text": "# Inputs of the equation. equation_inputs = [4,-2,3.5,5,-11,-4.7] # Number of the weights we are looking to optimize. num_weights = 6" }, { "code": null, "e": 3918, "s": 3310, "text": "The next step is to define the initial population. Based on the number of weights, each chromosome (solution or individual) in the population will definitely have 6 genes, one gene for each weight. But the question is how many solutions per the population? There is no fixed value for that and we can select the value that fits well with our problem. But we could leave it generic so that it can be changed in the code. Next, we create a variable that holds the number of solutions per population, another to hold the size of the population, and finally, a variable that holds the actual initial population:" }, { "code": null, "e": 4213, "s": 3918, "text": "import numpysol_per_pop = 8# Defining the population size.pop_size = (sol_per_pop,num_weights) # The population will have sol_per_pop chromosome where each chromosome has num_weights genes.#Creating the initial population.new_population = numpy.random.uniform(low=-4.0, high=4.0, size=pop_size)" }, { "code": null, "e": 4533, "s": 4213, "text": "After importing the numpy library, we are able to create the initial population randomly using the numpy.random.uniform function. According to the selected parameters, it will be of shape (8, 6). That is 8 chromosomes and each one has 6 genes, one for each weight. After running this code, the population is as follows:" }, { "code": null, "e": 5120, "s": 4533, "text": "[[-2.19134006 -2.88907857 2.02365737 -3.97346034 3.45160502 2.05773249][ 2.12480298 2.97122243 3.60375452 3.78571392 0.28776565 3.5170347 ][ 1.81098962 0.35130155 1.03049548 -0.33163294 3.52586421 2.53845644][-0.63698911 -2.8638447 2.93392615 -1.40103767 -1.20313655 0.30567304][-1.48998583 -1.53845766 1.11905299 -3.67541087 1.33225142 2.86073836][ 1.14159503 2.88160332 1.74877772 -3.45854293 0.96125878 2.99178241][ 1.96561297 0.51030292 0.52852716 -1.56909315 -2.35855588 2.29682254][ 3.00912373 -2.745417 3.27131287 -0.72163167 0.7516408 0.00677938]]" }, { "code": null, "e": 5210, "s": 5120, "text": "Note that it is generated randomly and thus it will definitely change when get run again." }, { "code": null, "e": 5691, "s": 5210, "text": "After preparing the population, next is to follow the flowchart in figure 1. Based on the fitness function, we are going to select the best individuals within the current population as parents for mating. Next is to apply the GA variants (crossover and mutation) to produce the offspring of the next generation, creating the new population by appending both parents and offspring, and repeating such steps for a number of iterations/generations. The next code applies these steps:" }, { "code": null, "e": 6595, "s": 5691, "text": "import ganum_generations = 5num_parents_mating = 4for generation in range(num_generations): # Measuring the fitness of each chromosome in the population. fitness = ga.cal_pop_fitness(equation_inputs, new_population) # Selecting the best parents in the population for mating. parents = ga.select_mating_pool(new_population, fitness, num_parents_mating) # Generating next generation using crossover. offspring_crossover = ga.crossover(parents, offspring_size=(pop_size[0]-parents.shape[0], num_weights)) # Adding some variations to the offsrping using mutation. offspring_mutation = ga.mutation(offspring_crossover)# Creating the new population based on the parents and offspring. new_population[0:parents.shape[0], :] = parents new_population[parents.shape[0]:, :] = offspring_mutation" }, { "code": null, "e": 6800, "s": 6595, "text": "The current number of generations is 5. It is selected to be small for presenting results of all generations within the tutorial. There is a module named GA that holds the implementation of the algorithm." }, { "code": null, "e": 6994, "s": 6800, "text": "The first step is to find the fitness value of each solution within the population using the ga.cal_pop_fitness function. The implementation of such function inside the GA module is as follows:" }, { "code": null, "e": 7296, "s": 6994, "text": "def cal_pop_fitness(equation_inputs, pop): # Calculating the fitness value of each solution in the current population. # The fitness function calculates the sum of products between each input and its corresponding weight. fitness = numpy.sum(pop*equation_inputs, axis=1) return fitness" }, { "code": null, "e": 7748, "s": 7296, "text": "The fitness function accepts both the equation inputs values (x1 to x6) in addition to the population. The fitness value is calculated as the sum of product (SOP) between each input and its corresponding gene (weight) according to our function. According to the number of solutions per population, there will be a number of SOPs. As we previously set the number of solutions to 8 in the variable named sol_per_pop, there will be 8 SOPs as shown below:" }, { "code": null, "e": 7854, "s": 7748, "text": "[-63.41070188 14.40299221 -42.22532674 18.24112489 -45.44363278 -37.00404311 15.99527402 17.0688537 ]" }, { "code": null, "e": 7918, "s": 7854, "text": "Note that the higher the fitness value the better the solution." }, { "code": null, "e": 8273, "s": 7918, "text": "After calculating the fitness values for all solutions, next is to select the best of them as parents in the mating pool according to the next function ga.select_mating_pool. Such function accepts the population, the fitness values, and the number of parents needed. It returns the parents selected. Its implementation inside the GA module is as follows:" }, { "code": null, "e": 8780, "s": 8273, "text": "def select_mating_pool(pop, fitness, num_parents): # Selecting the best individuals in the current generation as parents for producing the offspring of the next generation. parents = numpy.empty((num_parents, pop.shape[1])) for parent_num in range(num_parents): max_fitness_idx = numpy.where(fitness == numpy.max(fitness)) max_fitness_idx = max_fitness_idx[0][0] parents[parent_num, :] = pop[max_fitness_idx, :] fitness[max_fitness_idx] = -99999999999 return parents" }, { "code": null, "e": 8933, "s": 8780, "text": "Based on the number of parents required as defined in the variable num_parents_mating, the function creates an empty array to hold them as in this line:" }, { "code": null, "e": 8984, "s": 8933, "text": "parents = numpy.empty((num_parents, pop.shape[1]))" }, { "code": null, "e": 9152, "s": 8984, "text": "Looping through the current population, the function gets the index of the highest fitness value because it is the best solution to be selected according to this line:" }, { "code": null, "e": 9213, "s": 9152, "text": "max_fitness_idx = numpy.where(fitness == numpy.max(fitness))" }, { "code": null, "e": 9313, "s": 9213, "text": "This index is used to retrieve the solution that corresponds to such fitness value using this line:" }, { "code": null, "e": 9362, "s": 9313, "text": "parents[parent_num, :] = pop[max_fitness_idx, :]" }, { "code": null, "e": 9601, "s": 9362, "text": "To avoid selecting such solution again, its fitness value is set to a very small value that is likely to not be selected again which is -99999999999. The parents array is returned finally which will be as follows according to our example:" }, { "code": null, "e": 9896, "s": 9601, "text": "[[-0.63698911 -2.8638447 2.93392615 -1.40103767 -1.20313655 0.30567304][ 3.00912373 -2.745417 3.27131287 -0.72163167 0.7516408 0.00677938][ 1.96561297 0.51030292 0.52852716 -1.56909315 -2.35855588 2.29682254][ 2.12480298 2.97122243 3.60375452 3.78571392 0.28776565 3.5170347 ]]" }, { "code": null, "e": 10090, "s": 9896, "text": "Note that these three parents are the best individuals within the current population based on their fitness values which are 18.24112489, 17.0688537, 15.99527402, and 14.40299221, respectively." }, { "code": null, "e": 10477, "s": 10090, "text": "Next step is to use such selected parents for mating in order to generate the offspring. The mating starts with the crossover operation according to the ga.crossover function. This function accepts the parents and the offspring size. It uses the offspring size to know the number of offspring to produce from such parents. Such a function is implemented as follows inside the GA module:" }, { "code": null, "e": 11306, "s": 10477, "text": "def crossover(parents, offspring_size): offspring = numpy.empty(offspring_size) # The point at which crossover takes place between two parents. Usually, it is at the center. crossover_point = numpy.uint8(offspring_size[1]/2) for k in range(offspring_size[0]): # Index of the first parent to mate. parent1_idx = k%parents.shape[0] # Index of the second parent to mate. parent2_idx = (k+1)%parents.shape[0] # The new offspring will have its first half of its genes taken from the first parent. offspring[k, 0:crossover_point] = parents[parent1_idx, 0:crossover_point] # The new offspring will have its second half of its genes taken from the second parent. offspring[k, crossover_point:] = parents[parent2_idx, crossover_point:] return offspring" }, { "code": null, "e": 11398, "s": 11306, "text": "The function starts by creating an empty array based on the offspring size as in this line:" }, { "code": null, "e": 11438, "s": 11398, "text": "offspring = numpy.empty(offspring_size)" }, { "code": null, "e": 11635, "s": 11438, "text": "Because we are using single point crossover, we need to specify the point at which crossover takes place. The point is selected to divide the solution into two equal halves according to this line:" }, { "code": null, "e": 11686, "s": 11635, "text": "crossover_point = numpy.uint8(offspring_size[1]/2)" }, { "code": null, "e": 11811, "s": 11686, "text": "Then we need to select the two parents to crossover. The indices of these parents are selected according to these two lines:" }, { "code": null, "e": 11880, "s": 11811, "text": "parent1_idx = k%parents.shape[0]parent2_idx = (k+1)%parents.shape[0]" }, { "code": null, "e": 12394, "s": 11880, "text": "The parents are selected in a way similar to a ring. The first with indices 0 and 1 are selected at first to produce two offspring. If there still remaining offspring to produce, then we select the parent 1 with parent 2 to produce another two offspring. If we are in need of more offspring, then we select the next two parents with indices 2 and 3. By index 3, we reached the last parent. If we need to produce more offspring, then we select parent with index 3 and go back to the parent with index 0, and so on." }, { "code": null, "e": 12526, "s": 12394, "text": "The solutions after applying the crossover operation to the parents are stored into the offspring variable and they are as follows:" }, { "code": null, "e": 12821, "s": 12526, "text": "[[-0.63698911 -2.8638447 2.93392615 -0.72163167 0.7516408 0.00677938][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.35855588 2.29682254][ 1.96561297 0.51030292 0.52852716 3.78571392 0.28776565 3.5170347 ][ 2.12480298 2.97122243 3.60375452 -1.40103767 -1.20313655 0.30567304]]" }, { "code": null, "e": 13126, "s": 12821, "text": "Next is to apply the second GA variant, mutation, to the results of the crossover stored in the offspring variable using the ga.mutation function inside the GA module. Such function accepts the crossover offspring and returns them after applying uniform mutation. That function is implemented as follows:" }, { "code": null, "e": 13494, "s": 13126, "text": "def mutation(offspring_crossover): # Mutation changes a single gene in each offspring randomly. for idx in range(offspring_crossover.shape[0]): # The random value to be added to the gene. random_value = numpy.random.uniform(-1.0, 1.0, 1) offspring_crossover[idx, 4] = offspring_crossover[idx, 4] + random_value return offspring_crossover" }, { "code": null, "e": 13621, "s": 13494, "text": "It loops through each offspring and adds a uniformly generated random number in the range from -1 to 1 according to this line:" }, { "code": null, "e": 13671, "s": 13621, "text": "random_value = numpy.random.uniform(-1.0, 1.0, 1)" }, { "code": null, "e": 13770, "s": 13671, "text": "Such random number is then added to the gene with index 4 of the offspring according to this line:" }, { "code": null, "e": 13843, "s": 13770, "text": "offspring_crossover[idx, 4] = offspring_crossover[idx, 4] + random_value" }, { "code": null, "e": 13954, "s": 13843, "text": "Note that the index could be changed to any other index. The offspring after applying mutation are as follows:" }, { "code": null, "e": 14249, "s": 13954, "text": "[[-0.63698911 -2.8638447 2.93392615 -0.72163167 1.66083721 0.00677938][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254][ 1.96561297 0.51030292 0.52852716 3.78571392 0.45337472 3.5170347 ][ 2.12480298 2.97122243 3.60375452 -1.40103767 -1.5781162 0.30567304]]" }, { "code": null, "e": 14342, "s": 14249, "text": "Such results are added to the variable offspring_crossover and got returned by the function." }, { "code": null, "e": 14492, "s": 14342, "text": "At this point, we successfully produced 4 offspring from the 4 selected parents and we are ready to create the new population of the next generation." }, { "code": null, "e": 15225, "s": 14492, "text": "Note that GA is a random-based optimization technique. It tries to enhance the current solutions by applying some random changes to them. Because such changes are random, we are not sure that they will produce better solutions. For such reason, it is preferred to keep the previous best solutions (parents) in the new population. In the worst case when all the new offspring are worse than such parents, we will continue using such parents. As a result, we guarantee that the new generation will at least preserve the previous good results and will not go worse. The new population will have its first 4 solutions from the previous parents. The last 4 solutions come from the offspring created after applying crossover and mutation:" }, { "code": null, "e": 15330, "s": 15225, "text": "new_population[0:parents.shape[0], :] = parentsnew_population[parents.shape[0]:, :] = offspring_mutation" }, { "code": null, "e": 15452, "s": 15330, "text": "By calculating the fitness of all solutions (parents and offspring) of the first generation, their fitness is as follows:" }, { "code": null, "e": 15558, "s": 15452, "text": "[ 18.24112489 17.0688537 15.99527402 14.40299221 -8.46075629 31.73289712 6.10307563 24.08733441]" }, { "code": null, "e": 15849, "s": 15558, "text": "The highest fitness previously was 18.24112489 but now it is 31.7328971158. That means that the random changes moved towards a better solution. This is GREAT. But such results could be enhanced by going through more generations. Below are the results of each step for another 4 generations:" }, { "code": null, "e": 20227, "s": 15849, "text": "Generation : 1Fitness values:[ 18.24112489 17.0688537 15.99527402 14.40299221 -8.46075629 31.73289712 6.10307563 24.08733441]Selected parents:[[ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254][ 2.12480298 2.97122243 3.60375452 -1.40103767 -1.5781162 0.30567304][-0.63698911 -2.8638447 2.93392615 -1.40103767 -1.20313655 0.30567304][ 3.00912373 -2.745417 3.27131287 -0.72163167 0.7516408 0.00677938]]Crossover result:[[ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.5781162 0.30567304][ 2.12480298 2.97122243 3.60375452 -1.40103767 -1.20313655 0.30567304][-0.63698911 -2.8638447 2.93392615 -0.72163167 0.7516408 0.00677938][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254]]Mutation result:[[ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.2392086 0.30567304][ 2.12480298 2.97122243 3.60375452 -1.40103767 -0.38610586 0.30567304][-0.63698911 -2.8638447 2.93392615 -0.72163167 1.33639943 0.00677938][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.13941727 2.29682254]]Best result after generation 1 : 34.1663669207Generation : 2Fitness values:[ 31.73289712 24.08733441 18.24112489 17.0688537 34.16636692 10.97522073 -4.89194068 22.86998223]Selected Parents:[[ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.2392086 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254][ 2.12480298 2.97122243 3.60375452 -1.40103767 -1.5781162 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.13941727 2.29682254]]Crossover result:[[ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.5781162 0.30567304][ 2.12480298 2.97122243 3.60375452 -1.56909315 -1.13941727 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.2392086 0.30567304]]Mutation result:[[ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.20515009 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -0.73543721 0.30567304][ 2.12480298 2.97122243 3.60375452 -1.56909315 -0.50581509 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.20089639 0.30567304]]Best result after generation 2: 34.5930432629Generation : 3Fitness values:[ 34.16636692 31.73289712 24.08733441 22.86998223 34.59304326 28.6248816 2.09334217 33.7449326 ]Selected parents:[[ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.20515009 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.2392086 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.20089639 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254]]Crossover result:[[ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.2392086 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.20089639 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.56909315 -1.94513681 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.20515009 2.29682254]]Mutation result:[[ 3.00912373 -2.745417 3.27131287 -1.40103767 -2.20744102 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.16589294 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.37553107 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.44124005 2.29682254]]Best result after generation 3: 44.8169235189Generation : 4Fitness values[ 34.59304326 34.16636692 33.7449326 31.73289712 44.8169235233.35989464 36.46723397 37.19003273]Selected parents:[[ 3.00912373 -2.745417 3.27131287 -1.40103767 -2.20744102 0.30567304][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.44124005 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.37553107 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.20515009 2.29682254]]Crossover result:[[ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.37553107 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.20515009 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -2.20744102 0.30567304]]Mutation result:[[ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.13382082 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.98105233 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.56909315 -2.27638584 2.29682254][ 3.00912373 -2.745417 3.27131287 -1.40103767 -1.70558545 0.30567304]]Best result after generation 4: 44.8169235189" }, { "code": null, "e": 20398, "s": 20227, "text": "After the above 5 generations, the best result now has a fitness value equal to 44.8169235189 compared to the best result after the first generation which is 18.24112489." }, { "code": null, "e": 20443, "s": 20398, "text": "The best solution has the following weights:" }, { "code": null, "e": 20516, "s": 20443, "text": "[3.00912373 -2.745417 3.27131287 -1.40103767 -2.20744102 0.30567304]" }, { "code": null, "e": 20697, "s": 20516, "text": "The complete code is available in my GitHub account here: https://github.com/ahmedfgad/GeneticAlgorithmPython/tree/master/Tutorial%20Project. It will be listed in the tutorial too." }, { "code": null, "e": 20740, "s": 20697, "text": "Here is the implementation of the example:" }, { "code": null, "e": 20769, "s": 20740, "text": "The GA module is as follows:" } ]
Level Up Your Data Visualizations with Trend Lines in Python | by Byron Dolon | Towards Data Science
Data visualization is a key part of data analysis. Visualizing data makes it easier for people to understand the trends in a dataset compared to just looking at numbers on a table. Part of this includes picking the right chart types to go with the right type of data you are trying to showcase, like using a line chart for time-series data. You can go further than this by adding some cosmetic changes like color and font to make important data points pop. In addition, trend lines are helpful to clearly outline the general direction of a dataset over all its data points. You could also implement static trend lines to have a value you choose to be a horizontal or vertical line on the graph that you use to easily see if the values in your dataset are higher or lower than the static line. In this piece, we will take a look at implementing both forms of trend lines using the Plotly library in Python for the data visualization. We’ll also use Pandas for some initial data pre-processing, so make sure you have these two packages installed already. Then, import the following and get ready to follow along! import pandas as pdimport plotly.express as pximport random Let’s get to it! Let’s first generate some sample data. To do so, run the following code. expense_data = { "Person": random.choices(["A", "B"], k=20), "Amount": random.sample(range(100, 200), 10) + random.sample(range(0, 99), 10), "Category": ["Groceries"] * 10 + ["Restaurant"] * 10, "Date": pd.to_datetime(pd.date_range('2020-01-01','2020-10-01', freq='MS').tolist() * 2)}df = pd.DataFrame(data=expense_data) The data we’re going to visualize will be based on some randomly generated personal expense data. Above you can see we’re just randomly creating expense data for 10 months and loading it into a Pandas DataFrame. The above code should output 20 lines worth of data. In this piece, the first goal of our data analysis is to compare the average monthly spending per category to each month’s spending in that category. As such, let’s use some Pandas to group the total spending per month together per category. df_grouped = df.groupby(by=[pd.Grouper(key="Date", freq="1M"), "Category"])["Amount"]df_grouped = df_grouped.sum().reset_index() Now, we can get to creating charts. Since we want to create a chart for each category of spending with each of its monthly data points and a static average trend line, we can start by creating a list of the categories in our DataFrame. categories = df["Category"].unique().tolist() Then, we’ll loop through all the categories and create a graph for each using the following code. for category in categories: df_category = df_grouped.loc[df_grouped["Category"] == category].copy() df_category["Average Spending"] = round(df_category["Amount"].mean(), 2) category_graph = px.line( df_category, x="Date", y=["Amount", "Average Spending"], title=f"{category} Spending with Average Trend Line" ) category_graph.show() This code first creates a new DataFrame with only the rows that have the desired category in each loop. Then, we create a new column “Average Spending” which simply uses the mean method on the “Amount” column in the DataFrame to return a column with only the average spending values. Finally, we use the Plotly Express library to create a line chart with the new DataFrame. You’ll notice that we passed a list into the y parameter, which will give us two lines in the line chart. The result of this code is the following graphs. Using these graphs, you can easily see which months fall over the average spending for the category and which are under. This would be helpful for someone looking to manage their finances over time so that they could budget each month accordingly and check to see if they’re meeting their plans every month. Next, let’s take a look at using Plotly to create trend lines for the total monthly spending in the dataset. To do so, we’ll create a new grouped DataFrame, only this time we only need to group it by the month. df_sum = df.groupby(by=[pd.Grouper(key="Date", freq="1M")])["Amount"]df_sum = df_sum.sum().reset_index() Plotly allows you to create both linear or non-linear trend lines. You can use ordinary least squares (OLS) linear regression or locally weighted scatterplot smoothing (non-linear) trend lines. Similar to how we created the graphs for the previous sections, we’ll now create a list of the possible trend lines and create scatter plots with Plotly using another for loop. trend_lines = ["ols", "lowess"]for trend_line in trend_lines: fig = px.scatter( df_sum, x="Date", y="Amount", trendline=trend_line, title=f"{trend_line} Trend Line" ) fig.show() The code is more or less the same as before, where we pass in the DataFrame and the appropriate columns to the Plotly Express scatterplot. To add the trend lines, we pass in each trend line value from the list we defined into the trendline argument. Running the above code will give you the following graphs. Depending on your dataset, a linear or non-linear trend line can better fit the data points. That’s why it’s useful to try different trendlines to see which one fits the data better. Also, just because there is a trend line does not necessarily mean that a trend is really there (in the same way that correlation does not equal causation). You can also access the model parameters (for charts with an OLS trend line) using the following code. results = px.get_trendline_results(fig)results.px_fit_results.iloc[0].summary() Note that the fig object above is specifically the figure created where the trendline argument in the Plotly Express scatter is set to “ols”. The result of the summary can provide you with an explanation of the parameters used to create the trend line you see in the chart, which can help you understand the significance of the trend line. In our case with randomly generated data, it’s a bit difficult to really see a significant trend. You’ll see the very low R-squared value and a sample size of less than 20 imputes a low correlation (if any at all). However, for a regular person’s expense data, it would be great to see a trend line that’s mostly flat when you look at the spending per month. If you notice a highly sloped positive trend line with a higher R-squared value in your monthly expenses, you would know that you may have increased your spending over time and therefore are spending more than your monthly budget allocation (unless maybe you got a raise and decided to splurge on purpose). And that’s all! I hope you found this very quick introduction to trend lines with Plotly in Python useful for your data analysis. The Plotly library, especially when you use Plotly Express, makes it very easy for you to just plug in a Pandas DataFrame and get straight to visualizing your data. It’s just important to remember that how you choose to show data will affect how others perceive it, so make sure when you are making changes like adding trend lines you’re doing so in a way that truly represents the underlying data, and you’re not just doing so to make an arbitrary point. Thanks a bunch again for reading! If you’re thinking about becoming a paying member on Medium, I’d really appreciate it if you sign up using my referral link below! This would let directly receive a portion of your membership fees, so it would be a big help. byrondolon.medium.com More by me:- Check for a Substring in a Pandas DataFrame- Conditional Selection and Assignment With .loc in Pandas- 2 Easy Ways to Get Tables From a Website With Pandas- Top 4 Repositories on GitHub to Learn Pandas- Better Data Visualization with Dual Axis Graphs in Python
[ { "code": null, "e": 512, "s": 171, "text": "Data visualization is a key part of data analysis. Visualizing data makes it easier for people to understand the trends in a dataset compared to just looking at numbers on a table. Part of this includes picking the right chart types to go with the right type of data you are trying to showcase, like using a line chart for time-series data." }, { "code": null, "e": 964, "s": 512, "text": "You can go further than this by adding some cosmetic changes like color and font to make important data points pop. In addition, trend lines are helpful to clearly outline the general direction of a dataset over all its data points. You could also implement static trend lines to have a value you choose to be a horizontal or vertical line on the graph that you use to easily see if the values in your dataset are higher or lower than the static line." }, { "code": null, "e": 1282, "s": 964, "text": "In this piece, we will take a look at implementing both forms of trend lines using the Plotly library in Python for the data visualization. We’ll also use Pandas for some initial data pre-processing, so make sure you have these two packages installed already. Then, import the following and get ready to follow along!" }, { "code": null, "e": 1342, "s": 1282, "text": "import pandas as pdimport plotly.express as pximport random" }, { "code": null, "e": 1359, "s": 1342, "text": "Let’s get to it!" }, { "code": null, "e": 1432, "s": 1359, "text": "Let’s first generate some sample data. To do so, run the following code." }, { "code": null, "e": 1765, "s": 1432, "text": "expense_data = { \"Person\": random.choices([\"A\", \"B\"], k=20), \"Amount\": random.sample(range(100, 200), 10) + random.sample(range(0, 99), 10), \"Category\": [\"Groceries\"] * 10 + [\"Restaurant\"] * 10, \"Date\": pd.to_datetime(pd.date_range('2020-01-01','2020-10-01', freq='MS').tolist() * 2)}df = pd.DataFrame(data=expense_data)" }, { "code": null, "e": 2030, "s": 1765, "text": "The data we’re going to visualize will be based on some randomly generated personal expense data. Above you can see we’re just randomly creating expense data for 10 months and loading it into a Pandas DataFrame. The above code should output 20 lines worth of data." }, { "code": null, "e": 2180, "s": 2030, "text": "In this piece, the first goal of our data analysis is to compare the average monthly spending per category to each month’s spending in that category." }, { "code": null, "e": 2272, "s": 2180, "text": "As such, let’s use some Pandas to group the total spending per month together per category." }, { "code": null, "e": 2401, "s": 2272, "text": "df_grouped = df.groupby(by=[pd.Grouper(key=\"Date\", freq=\"1M\"), \"Category\"])[\"Amount\"]df_grouped = df_grouped.sum().reset_index()" }, { "code": null, "e": 2437, "s": 2401, "text": "Now, we can get to creating charts." }, { "code": null, "e": 2637, "s": 2437, "text": "Since we want to create a chart for each category of spending with each of its monthly data points and a static average trend line, we can start by creating a list of the categories in our DataFrame." }, { "code": null, "e": 2683, "s": 2637, "text": "categories = df[\"Category\"].unique().tolist()" }, { "code": null, "e": 2781, "s": 2683, "text": "Then, we’ll loop through all the categories and create a graph for each using the following code." }, { "code": null, "e": 3160, "s": 2781, "text": "for category in categories: df_category = df_grouped.loc[df_grouped[\"Category\"] == category].copy() df_category[\"Average Spending\"] = round(df_category[\"Amount\"].mean(), 2) category_graph = px.line( df_category, x=\"Date\", y=[\"Amount\", \"Average Spending\"], title=f\"{category} Spending with Average Trend Line\" ) category_graph.show()" }, { "code": null, "e": 3444, "s": 3160, "text": "This code first creates a new DataFrame with only the rows that have the desired category in each loop. Then, we create a new column “Average Spending” which simply uses the mean method on the “Amount” column in the DataFrame to return a column with only the average spending values." }, { "code": null, "e": 3689, "s": 3444, "text": "Finally, we use the Plotly Express library to create a line chart with the new DataFrame. You’ll notice that we passed a list into the y parameter, which will give us two lines in the line chart. The result of this code is the following graphs." }, { "code": null, "e": 3997, "s": 3689, "text": "Using these graphs, you can easily see which months fall over the average spending for the category and which are under. This would be helpful for someone looking to manage their finances over time so that they could budget each month accordingly and check to see if they’re meeting their plans every month." }, { "code": null, "e": 4208, "s": 3997, "text": "Next, let’s take a look at using Plotly to create trend lines for the total monthly spending in the dataset. To do so, we’ll create a new grouped DataFrame, only this time we only need to group it by the month." }, { "code": null, "e": 4313, "s": 4208, "text": "df_sum = df.groupby(by=[pd.Grouper(key=\"Date\", freq=\"1M\")])[\"Amount\"]df_sum = df_sum.sum().reset_index()" }, { "code": null, "e": 4507, "s": 4313, "text": "Plotly allows you to create both linear or non-linear trend lines. You can use ordinary least squares (OLS) linear regression or locally weighted scatterplot smoothing (non-linear) trend lines." }, { "code": null, "e": 4684, "s": 4507, "text": "Similar to how we created the graphs for the previous sections, we’ll now create a list of the possible trend lines and create scatter plots with Plotly using another for loop." }, { "code": null, "e": 4907, "s": 4684, "text": "trend_lines = [\"ols\", \"lowess\"]for trend_line in trend_lines: fig = px.scatter( df_sum, x=\"Date\", y=\"Amount\", trendline=trend_line, title=f\"{trend_line} Trend Line\" ) fig.show()" }, { "code": null, "e": 5216, "s": 4907, "text": "The code is more or less the same as before, where we pass in the DataFrame and the appropriate columns to the Plotly Express scatterplot. To add the trend lines, we pass in each trend line value from the list we defined into the trendline argument. Running the above code will give you the following graphs." }, { "code": null, "e": 5659, "s": 5216, "text": "Depending on your dataset, a linear or non-linear trend line can better fit the data points. That’s why it’s useful to try different trendlines to see which one fits the data better. Also, just because there is a trend line does not necessarily mean that a trend is really there (in the same way that correlation does not equal causation). You can also access the model parameters (for charts with an OLS trend line) using the following code." }, { "code": null, "e": 5739, "s": 5659, "text": "results = px.get_trendline_results(fig)results.px_fit_results.iloc[0].summary()" }, { "code": null, "e": 6079, "s": 5739, "text": "Note that the fig object above is specifically the figure created where the trendline argument in the Plotly Express scatter is set to “ols”. The result of the summary can provide you with an explanation of the parameters used to create the trend line you see in the chart, which can help you understand the significance of the trend line." }, { "code": null, "e": 6294, "s": 6079, "text": "In our case with randomly generated data, it’s a bit difficult to really see a significant trend. You’ll see the very low R-squared value and a sample size of less than 20 imputes a low correlation (if any at all)." }, { "code": null, "e": 6745, "s": 6294, "text": "However, for a regular person’s expense data, it would be great to see a trend line that’s mostly flat when you look at the spending per month. If you notice a highly sloped positive trend line with a higher R-squared value in your monthly expenses, you would know that you may have increased your spending over time and therefore are spending more than your monthly budget allocation (unless maybe you got a raise and decided to splurge on purpose)." }, { "code": null, "e": 6761, "s": 6745, "text": "And that’s all!" }, { "code": null, "e": 7331, "s": 6761, "text": "I hope you found this very quick introduction to trend lines with Plotly in Python useful for your data analysis. The Plotly library, especially when you use Plotly Express, makes it very easy for you to just plug in a Pandas DataFrame and get straight to visualizing your data. It’s just important to remember that how you choose to show data will affect how others perceive it, so make sure when you are making changes like adding trend lines you’re doing so in a way that truly represents the underlying data, and you’re not just doing so to make an arbitrary point." }, { "code": null, "e": 7590, "s": 7331, "text": "Thanks a bunch again for reading! If you’re thinking about becoming a paying member on Medium, I’d really appreciate it if you sign up using my referral link below! This would let directly receive a portion of your membership fees, so it would be a big help." }, { "code": null, "e": 7612, "s": 7590, "text": "byrondolon.medium.com" } ]
Java Program to Append Text to an Existing File
The Java.io.BufferedWriter class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. To add contents to a file − Instantiate the BufferedWriter class. By passing the FileWriter object as an argument to its constructor. Write data to the file using the write() method. import java.io.File; import java.io.FileWriter; import java.io.BufferedWriter; import java.io.IOException; public class AppendToFileExample { public static void main( String[] args ) { try { String data = " Tutorials Point is a best website in the world"; File f1 = new File("C:\Users\files\abc.txt"); if(!f1.exists()) { f1.createNewFile(); } FileWriter fileWritter = new FileWriter(f1.getName(),true); BufferedWriter bw = new BufferedWriter(fileWritter); bw.write(data); bw.close(); System.out.println("Done"); } catch(IOException e){ e.printStackTrace(); } } } Done
[ { "code": null, "e": 1272, "s": 1062, "text": "The Java.io.BufferedWriter class writes text to a character-output stream, buffering characters so as to provide for the efficient writing of single characters, arrays, and strings. To add contents to a file −" }, { "code": null, "e": 1311, "s": 1272, "text": " Instantiate the BufferedWriter class." }, { "code": null, "e": 1380, "s": 1311, "text": " By passing the FileWriter object as an argument to its constructor." }, { "code": null, "e": 1430, "s": 1380, "text": " Write data to the file using the write() method." }, { "code": null, "e": 2122, "s": 1430, "text": "import java.io.File;\nimport java.io.FileWriter;\nimport java.io.BufferedWriter;\nimport java.io.IOException;\n\npublic class AppendToFileExample {\n public static void main( String[] args ) {\n\n try {\n String data = \" Tutorials Point is a best website in the world\";\n File f1 = new File(\"C:\\Users\\files\\abc.txt\");\n if(!f1.exists()) {\n f1.createNewFile();\n }\n\n FileWriter fileWritter = new FileWriter(f1.getName(),true);\n BufferedWriter bw = new BufferedWriter(fileWritter);\n bw.write(data);\n bw.close();\n System.out.println(\"Done\");\n } catch(IOException e){\n e.printStackTrace();\n }\n }\n}" }, { "code": null, "e": 2127, "s": 2122, "text": "Done" } ]
Create basic graph visualizations with SeaBorn | by Rahul Agarwal | Towards Data Science
When it comes to data preparation and getting acquainted with data, the one step we normally skip is the data visualization. While a part of it could be attributed to the lack of good visualization tools for the platforms we use, most of us also get lazy at times. For most of our plotting needs, I would read up blogs, hack up with StackOverflow solutions and haggle with Matplotlib documentation each and every time I needed to make a simple graph. This led me to think that a Blog post to create common Graph types in Python is in order. But being the procrastinator that I am it always got pushed to the back of my head. One thing that helped me in pursuit of my data visualization needs in Python was this awesome course about Data Visualization and applied plotting from the University of Michigan which is a part of a pretty good Data Science Specialization with Python in itself. Highly Recommended. So I am finally writing this blog post with a basic purpose of creating a code base that provides me with ready to use codes which could be put into analysis in a fairly straight-forward manner. Right. So here Goes. Start by importing the libraries that we will need to use. import matplotlib.pyplot as plt #sets up plotting under plt import seaborn as sns #sets up styles and gives us more plotting options import pandas as pd #lets us handle data as dataframes We will be working with the Tips data that contains the following information. tips = sns.load_dataset("tips")tips.head() Now let us work on visualizing this data. We will use the regplot option in seaborn. Now that required a bit of code but I feel that it looks much better than what either Matplotlib or ggPlot2 could have rendered. We got a lot of customization without too much code. But that is not really what actually made me like Seaborn. The plot type that actually got my attention was lmplot, which lets us use regplot in a faceted mode. A side Note on Palettes: You can build your own color palettes using color_palette() function. color_palette() will accept the name of any seaborn palette or matplotlib colormap(except jet, which you should never use). It can also take a list of colors specified in any valid matplotlib format (RGB tuples, hex color codes, or HTML color names). The return value is always a list of RGB tuples. This allows you to use your own color palettes in a graph. They form another part of my workflow. Let us plot the normal Histogram using seaborn. For this, we will use the function. This function combines the matplotlib hist function (with automatic calculation of a good default bin size) with the seaborn kdeplot() function. It can also fit scipy.stats distributions and plot the estimated PDF over the data. You need to see how variables vary with one another. What is the distribution of variables in the dataset? This is the graph to use with the function. Very helpful And Seaborn males it a joy to use. We will use Iris Dataset here for this example. iris = sns.load_dataset("iris")iris.head() Hope you found this post useful and worth your time. You can find the iPython notebook at github I tried to make this as simple as possible but You may always ask me or see the documentation for doubts. If you have any more ideas on how to use Seaborn or which graphs should I add here, please suggest in the comments section. I will definitely try to add to this post as I start using more visualizations and encounter other libraries as good as seaborn. Also since this is my first visualization post, I would like to call out a good course about Data Visualization and applied plotting from the University of Michigan which is a part of a pretty good Data Science Specialization with Python in itself. Do check it out. Originally published at https://mlwhiz.com
[ { "code": null, "e": 297, "s": 172, "text": "When it comes to data preparation and getting acquainted with data, the one step we normally skip is the data visualization." }, { "code": null, "e": 437, "s": 297, "text": "While a part of it could be attributed to the lack of good visualization tools for the platforms we use, most of us also get lazy at times." }, { "code": null, "e": 623, "s": 437, "text": "For most of our plotting needs, I would read up blogs, hack up with StackOverflow solutions and haggle with Matplotlib documentation each and every time I needed to make a simple graph." }, { "code": null, "e": 713, "s": 623, "text": "This led me to think that a Blog post to create common Graph types in Python is in order." }, { "code": null, "e": 797, "s": 713, "text": "But being the procrastinator that I am it always got pushed to the back of my head." }, { "code": null, "e": 1080, "s": 797, "text": "One thing that helped me in pursuit of my data visualization needs in Python was this awesome course about Data Visualization and applied plotting from the University of Michigan which is a part of a pretty good Data Science Specialization with Python in itself. Highly Recommended." }, { "code": null, "e": 1275, "s": 1080, "text": "So I am finally writing this blog post with a basic purpose of creating a code base that provides me with ready to use codes which could be put into analysis in a fairly straight-forward manner." }, { "code": null, "e": 1296, "s": 1275, "text": "Right. So here Goes." }, { "code": null, "e": 1355, "s": 1296, "text": "Start by importing the libraries that we will need to use." }, { "code": null, "e": 1543, "s": 1355, "text": "import matplotlib.pyplot as plt #sets up plotting under plt import seaborn as sns #sets up styles and gives us more plotting options import pandas as pd #lets us handle data as dataframes" }, { "code": null, "e": 1622, "s": 1543, "text": "We will be working with the Tips data that contains the following information." }, { "code": null, "e": 1665, "s": 1622, "text": "tips = sns.load_dataset(\"tips\")tips.head()" }, { "code": null, "e": 1750, "s": 1665, "text": "Now let us work on visualizing this data. We will use the regplot option in seaborn." }, { "code": null, "e": 1932, "s": 1750, "text": "Now that required a bit of code but I feel that it looks much better than what either Matplotlib or ggPlot2 could have rendered. We got a lot of customization without too much code." }, { "code": null, "e": 1991, "s": 1932, "text": "But that is not really what actually made me like Seaborn." }, { "code": null, "e": 2093, "s": 1991, "text": "The plot type that actually got my attention was lmplot, which lets us use regplot in a faceted mode." }, { "code": null, "e": 2547, "s": 2093, "text": "A side Note on Palettes: You can build your own color palettes using color_palette() function. color_palette() will accept the name of any seaborn palette or matplotlib colormap(except jet, which you should never use). It can also take a list of colors specified in any valid matplotlib format (RGB tuples, hex color codes, or HTML color names). The return value is always a list of RGB tuples. This allows you to use your own color palettes in a graph." }, { "code": null, "e": 2899, "s": 2547, "text": "They form another part of my workflow. Let us plot the normal Histogram using seaborn. For this, we will use the function. This function combines the matplotlib hist function (with automatic calculation of a good default bin size) with the seaborn kdeplot() function. It can also fit scipy.stats distributions and plot the estimated PDF over the data." }, { "code": null, "e": 3146, "s": 2899, "text": "You need to see how variables vary with one another. What is the distribution of variables in the dataset? This is the graph to use with the function. Very helpful And Seaborn males it a joy to use. We will use Iris Dataset here for this example." }, { "code": null, "e": 3189, "s": 3146, "text": "iris = sns.load_dataset(\"iris\")iris.head()" }, { "code": null, "e": 3286, "s": 3189, "text": "Hope you found this post useful and worth your time. You can find the iPython notebook at github" }, { "code": null, "e": 3392, "s": 3286, "text": "I tried to make this as simple as possible but You may always ask me or see the documentation for doubts." }, { "code": null, "e": 3516, "s": 3392, "text": "If you have any more ideas on how to use Seaborn or which graphs should I add here, please suggest in the comments section." }, { "code": null, "e": 3645, "s": 3516, "text": "I will definitely try to add to this post as I start using more visualizations and encounter other libraries as good as seaborn." }, { "code": null, "e": 3911, "s": 3645, "text": "Also since this is my first visualization post, I would like to call out a good course about Data Visualization and applied plotting from the University of Michigan which is a part of a pretty good Data Science Specialization with Python in itself. Do check it out." } ]
How to widen output display to see more columns in Pandas dataframe? - GeeksforGeeks
18 Aug, 2020 In Python, if there are many more number of columns in the dataframe, then not all the columns will be shown in the output display. So, let’s see how to widen output display to see more columns. Method 1: Using pandas.set_option() function. This function is used to set the value of a specified option. Syntax: pandas.set_option(pat, value) Returns: None Example: Python3 # importing numpy library import numpy as np # importing pandas libraryimport pandas as pd # define a dataframe of# 2 rows and 100 columns# with random entriesdf = pd.DataFrame(np.random.random(200).reshape(2, 100)) # show the dataframedf Output: To print the above output in a wider format using pandas.set_option() function. Python3 # using pd.set_option()# to widen the output # displaypd.set_option('display.max_columns', 100) # show the dataframedf Output: Method 2: Using pd.options.display.max_columns attribute. This attribute is used to set the no. of columns to show in the display of the pandas dataframe. Example: Python3 # importing numpy libraryimport numpy as np # importing pandas libraryimport pandas as pd # define a dataframe of# 15 rows and 200 columns# with random entriesdf = pd.DataFrame(np.random.randint(0, 100, size =(15, 200))) # show the dataframedf Output: To print the above output in a wider format using pd.options.display.max_columns attribute. Python3 # using an alternative# way to use # pd.set_option() method# to widen the output # displaypd.options.display.max_columns = 200 # show the dataframedf Output: Python pandas-dataFrame Python Pandas-exercise Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe Python OOPs Concepts Python | Get unique values from a list Check if element exists in list in Python Python Classes and Objects Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24212, "s": 24184, "text": "\n18 Aug, 2020" }, { "code": null, "e": 24407, "s": 24212, "text": "In Python, if there are many more number of columns in the dataframe, then not all the columns will be shown in the output display. So, let’s see how to widen output display to see more columns." }, { "code": null, "e": 24453, "s": 24407, "text": "Method 1: Using pandas.set_option() function." }, { "code": null, "e": 24515, "s": 24453, "text": "This function is used to set the value of a specified option." }, { "code": null, "e": 24553, "s": 24515, "text": "Syntax: pandas.set_option(pat, value)" }, { "code": null, "e": 24567, "s": 24553, "text": "Returns: None" }, { "code": null, "e": 24576, "s": 24567, "text": "Example:" }, { "code": null, "e": 24584, "s": 24576, "text": "Python3" }, { "code": "# importing numpy library import numpy as np # importing pandas libraryimport pandas as pd # define a dataframe of# 2 rows and 100 columns# with random entriesdf = pd.DataFrame(np.random.random(200).reshape(2, 100)) # show the dataframedf", "e": 24826, "s": 24584, "text": null }, { "code": null, "e": 24834, "s": 24826, "text": "Output:" }, { "code": null, "e": 24914, "s": 24834, "text": "To print the above output in a wider format using pandas.set_option() function." }, { "code": null, "e": 24922, "s": 24914, "text": "Python3" }, { "code": "# using pd.set_option()# to widen the output # displaypd.set_option('display.max_columns', 100) # show the dataframedf", "e": 25042, "s": 24922, "text": null }, { "code": null, "e": 25050, "s": 25042, "text": "Output:" }, { "code": null, "e": 25108, "s": 25050, "text": "Method 2: Using pd.options.display.max_columns attribute." }, { "code": null, "e": 25205, "s": 25108, "text": "This attribute is used to set the no. of columns to show in the display of the pandas dataframe." }, { "code": null, "e": 25214, "s": 25205, "text": "Example:" }, { "code": null, "e": 25222, "s": 25214, "text": "Python3" }, { "code": "# importing numpy libraryimport numpy as np # importing pandas libraryimport pandas as pd # define a dataframe of# 15 rows and 200 columns# with random entriesdf = pd.DataFrame(np.random.randint(0, 100, size =(15, 200))) # show the dataframedf", "e": 25505, "s": 25222, "text": null }, { "code": null, "e": 25513, "s": 25505, "text": "Output:" }, { "code": null, "e": 25605, "s": 25513, "text": "To print the above output in a wider format using pd.options.display.max_columns attribute." }, { "code": null, "e": 25613, "s": 25605, "text": "Python3" }, { "code": "# using an alternative# way to use # pd.set_option() method# to widen the output # displaypd.options.display.max_columns = 200 # show the dataframedf", "e": 25764, "s": 25613, "text": null }, { "code": null, "e": 25772, "s": 25764, "text": "Output:" }, { "code": null, "e": 25796, "s": 25772, "text": "Python pandas-dataFrame" }, { "code": null, "e": 25819, "s": 25796, "text": "Python Pandas-exercise" }, { "code": null, "e": 25833, "s": 25819, "text": "Python-pandas" }, { "code": null, "e": 25840, "s": 25833, "text": "Python" }, { "code": null, "e": 25938, "s": 25840, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25947, "s": 25938, "text": "Comments" }, { "code": null, "e": 25960, "s": 25947, "text": "Old Comments" }, { "code": null, "e": 25992, "s": 25960, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26048, "s": 25992, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26069, "s": 26048, "text": "Python OOPs Concepts" }, { "code": null, "e": 26108, "s": 26069, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26150, "s": 26108, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26177, "s": 26150, "text": "Python Classes and Objects" }, { "code": null, "e": 26208, "s": 26177, "text": "Python | os.path.join() method" }, { "code": null, "e": 26250, "s": 26208, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 26286, "s": 26250, "text": "Python | Pandas dataframe.groupby()" } ]
How do I get PHP errors to display? - GeeksforGeeks
20 Dec, 2021 There are four ways to display errors in PHP which are listed below: error_reporting: It does not display the E-STRICT, E-NOTICE and E_DEPRECATED level errors and display all the other level errors. display_errors: Its default value is “off”. Set it to “on”. log_errors: It’s default value is “on” which indicates whether or not error logging should be done. error_log string: It sets the name of the file where scripts error should be logged. Example: To display errors in PHP the fastest and easiest way is by adding the following lines to your code. ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); ini_set: The ini_set function will try to override the configuration found in PHP ini file. display_errors: It is a directive which determine whether the error will be displayed to the user or will be remain hidden. display_startup_errors: It is a directive which is used to find errors during PHP’s startup sequence. The list of the directives that can be overridden by the ini_set function is found in the official documentation. These two directives does not display parse errors.Program 1: php <?phpini_set('display_errors', 1);ini_set('display_startup_errors', 1);error_reporting(E_ALL); include("gfg.php");?> Output: A warning will be shown- No such directory or file found in (location of file) with the specified line of error. To display errors including parse errors following changes must be made at php.ini and restart php-fpm, apche2 display_errors = on Program 2: php <?php // Display number 0 to 5for($i = 0; $i <= 5 $i++) // Semicolon after $i<=5 is missing{echo $i;}?> Output: Output when display_error is disabled in php.ini file: Output when display_error is enabled and restarted: The above directives will display any PHP errors encountered when loading the website on the browser. The display-errors should be disabled when the site is live to prevent any security when not in the development environment. anikaseth98 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. Comments Old Comments How to Insert Form Data into Database using PHP ? How to execute PHP code using command line ? How to pop an alert message box using PHP ? PHP in_array() Function How to convert array to string in PHP ? How to Insert Form Data into Database using PHP ? How to execute PHP code using command line ? How to pop an alert message box using PHP ? How to convert array to string in PHP ? How to delete an array element based on key in PHP?
[ { "code": null, "e": 40503, "s": 40475, "text": "\n20 Dec, 2021" }, { "code": null, "e": 40573, "s": 40503, "text": "There are four ways to display errors in PHP which are listed below: " }, { "code": null, "e": 40703, "s": 40573, "text": "error_reporting: It does not display the E-STRICT, E-NOTICE and E_DEPRECATED level errors and display all the other level errors." }, { "code": null, "e": 40763, "s": 40703, "text": "display_errors: Its default value is “off”. Set it to “on”." }, { "code": null, "e": 40863, "s": 40763, "text": "log_errors: It’s default value is “on” which indicates whether or not error logging should be done." }, { "code": null, "e": 40948, "s": 40863, "text": "error_log string: It sets the name of the file where scripts error should be logged." }, { "code": null, "e": 41059, "s": 40948, "text": "Example: To display errors in PHP the fastest and easiest way is by adding the following lines to your code. " }, { "code": null, "e": 41152, "s": 41059, "text": "ini_set('display_errors', 1);\nini_set('display_startup_errors', 1);\nerror_reporting(E_ALL); " }, { "code": null, "e": 41244, "s": 41152, "text": "ini_set: The ini_set function will try to override the configuration found in PHP ini file." }, { "code": null, "e": 41368, "s": 41244, "text": "display_errors: It is a directive which determine whether the error will be displayed to the user or will be remain hidden." }, { "code": null, "e": 41584, "s": 41368, "text": "display_startup_errors: It is a directive which is used to find errors during PHP’s startup sequence. The list of the directives that can be overridden by the ini_set function is found in the official documentation." }, { "code": null, "e": 41648, "s": 41584, "text": "These two directives does not display parse errors.Program 1: " }, { "code": null, "e": 41652, "s": 41648, "text": "php" }, { "code": "<?phpini_set('display_errors', 1);ini_set('display_startup_errors', 1);error_reporting(E_ALL); include(\"gfg.php\");?>", "e": 41769, "s": 41652, "text": null }, { "code": null, "e": 41778, "s": 41769, "text": "Output: " }, { "code": null, "e": 41891, "s": 41778, "text": "A warning will be shown- No such directory or file found in (location of file)\nwith the specified line of error." }, { "code": null, "e": 42004, "s": 41891, "text": "To display errors including parse errors following changes must be made at php.ini and restart php-fpm, apche2 " }, { "code": null, "e": 42024, "s": 42004, "text": "display_errors = on" }, { "code": null, "e": 42037, "s": 42024, "text": "Program 2: " }, { "code": null, "e": 42041, "s": 42037, "text": "php" }, { "code": "<?php // Display number 0 to 5for($i = 0; $i <= 5 $i++) // Semicolon after $i<=5 is missing{echo $i;}?>", "e": 42145, "s": 42041, "text": null }, { "code": null, "e": 42154, "s": 42145, "text": "Output: " }, { "code": null, "e": 42210, "s": 42154, "text": "Output when display_error is disabled in php.ini file: " }, { "code": null, "e": 42263, "s": 42210, "text": "Output when display_error is enabled and restarted: " }, { "code": null, "e": 42491, "s": 42263, "text": "The above directives will display any PHP errors encountered when loading the website on the browser. The display-errors should be disabled when the site is live to prevent any security when not in the development environment. " }, { "code": null, "e": 42503, "s": 42491, "text": "anikaseth98" }, { "code": null, "e": 42510, "s": 42503, "text": "Picked" }, { "code": null, "e": 42514, "s": 42510, "text": "PHP" }, { "code": null, "e": 42527, "s": 42514, "text": "PHP Programs" }, { "code": null, "e": 42544, "s": 42527, "text": "Web Technologies" }, { "code": null, "e": 42571, "s": 42544, "text": "Web technologies Questions" }, { "code": null, "e": 42575, "s": 42571, "text": "PHP" }, { "code": null, "e": 42673, "s": 42575, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42682, "s": 42673, "text": "Comments" }, { "code": null, "e": 42695, "s": 42682, "text": "Old Comments" }, { "code": null, "e": 42745, "s": 42695, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 42790, "s": 42745, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 42834, "s": 42790, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 42858, "s": 42834, "text": "PHP in_array() Function" }, { "code": null, "e": 42898, "s": 42858, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 42948, "s": 42898, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 42993, "s": 42948, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 43037, "s": 42993, "text": "How to pop an alert message box using PHP ?" }, { "code": null, "e": 43077, "s": 43037, "text": "How to convert array to string in PHP ?" } ]
C# | Check whether a SortedList object contains a specific key - GeeksforGeeks
01 Feb, 2019 SortedList.Contains(Object) Method is used to check whether a SortedList object contains a specific key. Syntax: public virtual bool Contains (object key); Here, key is the Key which is to be located in the SortedList object. Return Value: This method returns the true if the SortedList object contains an element with the specified key otherwise, it returns false Exceptions: ArgumentNullException: If the key is null. InvalidOperationException: If the comparer throws an exception. Below programs illustrate the use of above-discussed method: Example 1: // C# code to Check whether a SortedList// object contains a specific keyusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add("1", "C++"); mylist.Add("2", "Java"); mylist.Add("3", "DSA"); mylist.Add("4", "Python"); mylist.Add("5", "C#"); // Checking whether 4 is present // in SortedList or not Console.Write(mylist.Contains("4")); }} Output: True Example 2: // C# code to Check whether a SortedList// object contains a specific keyusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add("First", "Ram"); mylist.Add("Second", "Shyam"); mylist.Add("Third", "Mohit"); mylist.Add("Fourth", "Rohit"); mylist.Add("Fifth", "Manish"); // Checking whether 10 is present // in SortedList object or not Console.Write(mylist.Contains("Sixth")); }} Output: False Note: Contains implements IDictionary.Contains. It behaves exactly as ContainsKey. This method uses a binary search algorithm; therefore, this method is an O(log n) operation, where n is Count. Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.contains?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-Collections-SortedList CSharp-method 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": "\n01 Feb, 2019" }, { "code": null, "e": 24016, "s": 23911, "text": "SortedList.Contains(Object) Method is used to check whether a SortedList object contains a specific key." }, { "code": null, "e": 24024, "s": 24016, "text": "Syntax:" }, { "code": null, "e": 24067, "s": 24024, "text": "public virtual bool Contains (object key);" }, { "code": null, "e": 24137, "s": 24067, "text": "Here, key is the Key which is to be located in the SortedList object." }, { "code": null, "e": 24276, "s": 24137, "text": "Return Value: This method returns the true if the SortedList object contains an element with the specified key otherwise, it returns false" }, { "code": null, "e": 24288, "s": 24276, "text": "Exceptions:" }, { "code": null, "e": 24331, "s": 24288, "text": "ArgumentNullException: If the key is null." }, { "code": null, "e": 24395, "s": 24331, "text": "InvalidOperationException: If the comparer throws an exception." }, { "code": null, "e": 24456, "s": 24395, "text": "Below programs illustrate the use of above-discussed method:" }, { "code": null, "e": 24467, "s": 24456, "text": "Example 1:" }, { "code": "// C# code to Check whether a SortedList// object contains a specific keyusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add(\"1\", \"C++\"); mylist.Add(\"2\", \"Java\"); mylist.Add(\"3\", \"DSA\"); mylist.Add(\"4\", \"Python\"); mylist.Add(\"5\", \"C#\"); // Checking whether 4 is present // in SortedList or not Console.Write(mylist.Contains(\"4\")); }}", "e": 25075, "s": 24467, "text": null }, { "code": null, "e": 25083, "s": 25075, "text": "Output:" }, { "code": null, "e": 25089, "s": 25083, "text": "True\n" }, { "code": null, "e": 25100, "s": 25089, "text": "Example 2:" }, { "code": "// C# code to Check whether a SortedList// object contains a specific keyusing System;using System.Collections; class Geeks { // Main Method public static void Main(String[] args) { // Creating a SortedList of integers SortedList mylist = new SortedList(); // Adding elements to SortedList mylist.Add(\"First\", \"Ram\"); mylist.Add(\"Second\", \"Shyam\"); mylist.Add(\"Third\", \"Mohit\"); mylist.Add(\"Fourth\", \"Rohit\"); mylist.Add(\"Fifth\", \"Manish\"); // Checking whether 10 is present // in SortedList object or not Console.Write(mylist.Contains(\"Sixth\")); }}", "e": 25748, "s": 25100, "text": null }, { "code": null, "e": 25756, "s": 25748, "text": "Output:" }, { "code": null, "e": 25763, "s": 25756, "text": "False\n" }, { "code": null, "e": 25769, "s": 25763, "text": "Note:" }, { "code": null, "e": 25846, "s": 25769, "text": "Contains implements IDictionary.Contains. It behaves exactly as ContainsKey." }, { "code": null, "e": 25957, "s": 25846, "text": "This method uses a binary search algorithm; therefore, this method is an O(log n) operation, where n is Count." }, { "code": null, "e": 25968, "s": 25957, "text": "Reference:" }, { "code": null, "e": 26075, "s": 25968, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.sortedlist.contains?view=netframework-4.7.2" }, { "code": null, "e": 26104, "s": 26075, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 26134, "s": 26104, "text": "CSharp-Collections-SortedList" }, { "code": null, "e": 26148, "s": 26134, "text": "CSharp-method" }, { "code": null, "e": 26151, "s": 26148, "text": "C#" }, { "code": null, "e": 26249, "s": 26151, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26258, "s": 26249, "text": "Comments" }, { "code": null, "e": 26271, "s": 26258, "text": "Old Comments" }, { "code": null, "e": 26311, "s": 26271, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 26334, "s": 26311, "text": "Extension Method in C#" }, { "code": null, "e": 26362, "s": 26334, "text": "HashSet in C# with Examples" }, { "code": null, "e": 26384, "s": 26362, "text": "Partial Classes in C#" }, { "code": null, "e": 26401, "s": 26384, "text": "C# | Inheritance" }, { "code": null, "e": 26441, "s": 26401, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 26474, "s": 26441, "text": "Linked List Implementation in C#" }, { "code": null, "e": 26517, "s": 26474, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 26533, "s": 26517, "text": "C# | List Class" } ]
C Program to Add two Integers - GeeksforGeeks
12 Jan, 2022 Given two numbers A and B. The task is to write a program to find the addition of these two numbers. Examples: Input: A = 2, B = 3 Output: 5 Input: A = 3, B = 6 Output: 9 In the below program to add two numbers, the user is first asked to enter two numbers and the input is scanned using the scanf() function and stored in the variables and . Then, the variables and are added using the arithmetic operator and the result is stored in the variable sum.Below is the C program to add two numbers: C // C program to add two numbers#include<stdio.h> int main(){ int A, B, sum = 0; // Ask user to enter the two numbers printf("Enter two numbers A and B : \n"); // Read two numbers from the user || A = 2, B = 3 scanf("%d%d", &A, &B); // Calculate the addition of A and B // using '+' operator sum = A + B; // Print the sum printf("Sum of A and B is: %d", sum); return 0;} Output: Enter two numbers A and B : 2 3 Sum of A and B is: 5 sagar0719kumar C-Operators school-programming C Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Producer Consumer Problem in C C program to find the length of a string Exit codes in C/C++ with Examples Difference between break and continue statement in C Python Dictionary Arrays in C/C++ Reverse a string in Java Inheritance in C++ C++ Classes and Objects
[ { "code": null, "e": 24564, "s": 24536, "text": "\n12 Jan, 2022" }, { "code": null, "e": 24666, "s": 24564, "text": "Given two numbers A and B. The task is to write a program to find the addition of these two numbers. " }, { "code": null, "e": 24678, "s": 24666, "text": "Examples: " }, { "code": null, "e": 24739, "s": 24678, "text": "Input: A = 2, B = 3\nOutput: 5\n\nInput: A = 3, B = 6\nOutput: 9" }, { "code": null, "e": 25067, "s": 24741, "text": "In the below program to add two numbers, the user is first asked to enter two numbers and the input is scanned using the scanf() function and stored in the variables and . Then, the variables and are added using the arithmetic operator and the result is stored in the variable sum.Below is the C program to add two numbers: " }, { "code": null, "e": 25069, "s": 25067, "text": "C" }, { "code": "// C program to add two numbers#include<stdio.h> int main(){ int A, B, sum = 0; // Ask user to enter the two numbers printf(\"Enter two numbers A and B : \\n\"); // Read two numbers from the user || A = 2, B = 3 scanf(\"%d%d\", &A, &B); // Calculate the addition of A and B // using '+' operator sum = A + B; // Print the sum printf(\"Sum of A and B is: %d\", sum); return 0;}", "e": 25497, "s": 25069, "text": null }, { "code": null, "e": 25507, "s": 25497, "text": "Output: " }, { "code": null, "e": 25560, "s": 25507, "text": "Enter two numbers A and B : 2 3\nSum of A and B is: 5" }, { "code": null, "e": 25577, "s": 25562, "text": "sagar0719kumar" }, { "code": null, "e": 25589, "s": 25577, "text": "C-Operators" }, { "code": null, "e": 25608, "s": 25589, "text": "school-programming" }, { "code": null, "e": 25619, "s": 25608, "text": "C Programs" }, { "code": null, "e": 25638, "s": 25619, "text": "School Programming" }, { "code": null, "e": 25736, "s": 25638, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25745, "s": 25736, "text": "Comments" }, { "code": null, "e": 25758, "s": 25745, "text": "Old Comments" }, { "code": null, "e": 25799, "s": 25758, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 25830, "s": 25799, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 25871, "s": 25830, "text": "C program to find the length of a string" }, { "code": null, "e": 25905, "s": 25871, "text": "Exit codes in C/C++ with Examples" }, { "code": null, "e": 25958, "s": 25905, "text": "Difference between break and continue statement in C" }, { "code": null, "e": 25976, "s": 25958, "text": "Python Dictionary" }, { "code": null, "e": 25992, "s": 25976, "text": "Arrays in C/C++" }, { "code": null, "e": 26017, "s": 25992, "text": "Reverse a string in Java" }, { "code": null, "e": 26036, "s": 26017, "text": "Inheritance in C++" } ]
How to ping external IP from java Android?
This example demonstrates how do I ping external IP from java 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"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </android.support.constraint.ConstraintLayout> Step 3 − Add the following code to src/MainActivity.java import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import java.io.IOException; public class MainActivity extends AppCompatActivity { Boolean isConnected = false, isWiFi = false, isMobile = false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo activeNetwork = cm.getActiveNetworkInfo(); if (activeNetwork != null) { isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI; isMobile = activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE; isConnected = activeNetwork.isConnectedOrConnecting(); } if (isConnected) { if (isWiFi) { Toast.makeText(this, "Yes, WiF", Toast.LENGTH_SHORT) .show(); if(isConnectedToThisServer("https://www.google.com/")) { Toast.makeText(this, "Yes, Connected to Google", Toast.LENGTH_SHORT) .show(); } else { Toast.makeText(this, "No Google Connection", Toast.LENGTH_SHORT) .show(); } } if (isMobile) { Toast.makeText(this, "Yes, Mobile", Toast.LENGTH_SHORT) .show(); if(isConnectedToThisServer("https://www.google.com/")) { Toast.makeText(this, "Yes, Connected to Google", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(this, "No Google Connection", Toast.LENGTH_SHORT).show(); } } } else { Toast.makeText(this, "No Network", Toast.LENGTH_SHORT).show(); } } public boolean isConnectedToThisServer(String host) { Runtime runtime = Runtime.getRuntime(); try { Process ipProcess = runtime.exec("/system/bin/ping -c 1 8.8.8.8" + host); int exitValue = ipProcess.waitFor(); return (exitValue == 0); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } return false; } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
[ { "code": null, "e": 1133, "s": 1062, "text": "This example demonstrates how do I ping external IP from java android." }, { "code": null, "e": 1262, "s": 1133, "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": 1327, "s": 1262, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2077, "s": 1327, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<android.support.constraint.ConstraintLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Hello World!\"\n app:layout_constraintBottom_toBottomOf=\"parent\"\n app:layout_constraintLeft_toLeftOf=\"parent\"\n app:layout_constraintRight_toRightOf=\"parent\"\n app:layout_constraintTop_toTopOf=\"parent\" />\n</android.support.constraint.ConstraintLayout>" }, { "code": null, "e": 2134, "s": 2077, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 4676, "s": 2134, "text": "import android.content.Context;\nimport android.net.ConnectivityManager;\nimport android.net.NetworkInfo;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.Toast;\nimport java.io.IOException;\npublic class MainActivity extends AppCompatActivity {\n Boolean isConnected = false,\n isWiFi = false,\n isMobile = false;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n ConnectivityManager cm = (ConnectivityManager)\n this.getSystemService(Context.CONNECTIVITY_SERVICE);\n NetworkInfo activeNetwork = cm.getActiveNetworkInfo();\n if (activeNetwork != null) {\n isWiFi = activeNetwork.getType() ==\n ConnectivityManager.TYPE_WIFI;\n isMobile = activeNetwork.getType() ==\n ConnectivityManager.TYPE_MOBILE;\n isConnected =\n activeNetwork.isConnectedOrConnecting();\n }\n if (isConnected) {\n if (isWiFi) {\n Toast.makeText(this, \"Yes, WiF\",\n Toast.LENGTH_SHORT)\n .show();\n if(isConnectedToThisServer(\"https://www.google.com/\")) {\n Toast.makeText(this, \"Yes, Connected to\n Google\", Toast.LENGTH_SHORT)\n .show();\n } else {\n Toast.makeText(this, \"No Google\n Connection\", Toast.LENGTH_SHORT)\n .show();\n }\n }\n if (isMobile) {\n Toast.makeText(this, \"Yes, Mobile\",\n Toast.LENGTH_SHORT)\n .show();\n if(isConnectedToThisServer(\"https://www.google.com/\")) {\n Toast.makeText(this, \"Yes, Connected to\n Google\", Toast.LENGTH_SHORT).show();\n } else {\n Toast.makeText(this, \"No Google\n Connection\", Toast.LENGTH_SHORT).show();\n }\n }\n } else {\n Toast.makeText(this, \"No Network\",\n Toast.LENGTH_SHORT).show();\n }\n }\n public boolean isConnectedToThisServer(String host) {\n Runtime runtime = Runtime.getRuntime();\n try {\n Process ipProcess = runtime.exec(\"/system/bin/ping\n -c 1 8.8.8.8\" + host);\n int exitValue = ipProcess.waitFor();\n return (exitValue == 0);\n } catch (IOException e) {\n e.printStackTrace();\n } catch (InterruptedException e) {\n e.printStackTrace();\n }\n return false;\n }\n}" }, { "code": null, "e": 4731, "s": 4676, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5592, "s": 4731, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <uses-permission\n android:name=\"android.permission.ACCESS_NETWORK_STATE\" />\n <uses-permission\n android:name=\"android.permission.INTERNET\"/>\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action\n android:name=\"android.intent.action.MAIN\" />\n <category\n android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 5939, "s": 5592, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −" } ]
How to filter single column of a matrix with column name in R?
To filter a single column of a matrix in R if the matrix has column names, we can simply use single square brackets but this will result in a vector without the column name. If we want to use the column name then column name or column number needs to be passed with drop=FALSE argument as shown in the below examples. Live Demo > M1<-matrix(sample(0:1,80,replace=TRUE),ncol=4) > colnames(M1)<-c("V1","V2","V3","V4") > M1 V1 V2 V3 V4 [1,] 0 0 1 0 [2,] 1 1 1 1 [3,] 0 0 0 0 [4,] 0 1 1 0 [5,] 1 1 1 1 [6,] 0 1 1 0 [7,] 0 1 0 1 [8,] 1 1 0 1 [9,] 1 1 0 1 [10,] 0 0 1 0 [11,] 0 0 0 1 [12,] 0 1 0 0 [13,] 0 0 0 0 [14,] 1 0 0 0 [15,] 0 1 0 1 [16,] 0 0 1 0 [17,] 1 1 1 1 [18,] 1 0 1 1 [19,] 1 0 1 1 [20,] 0 0 0 0 Extracting column V1 from M1 − > M1[,"V1",drop = FALSE] V1 [1,] 0 [2,] 1 [3,] 0 [4,] 0 [5,] 1 [6,] 0 [7,] 0 [8,] 1 [9,] 1 [10,] 0 [11,] 0 [12,] 0 [13,] 0 [14,] 1 [15,] 0 [16,] 0 [17,] 1 [18,] 1 [19,] 1 [20,] 0 Live Demo > M2<-matrix(sample(c("Yes","No"),40,replace = TRUE),ncol=2) > colnames(M2)<-c("Binary1","Binary2") > M2 Binary1 Binary2 [1,] "Yes" "Yes" [2,] "Yes" "No" [3,] "Yes" "No" [4,] "Yes" "Yes" [5,] "Yes" "Yes" [6,] "No" "No" [7,] "Yes" "Yes" [8,] "No" "Yes" [9,] "No" "No" [10,] "Yes" "Yes" [11,] "Yes" "Yes" [12,] "Yes" "No" [13,] "Yes" "No" [14,] "No" "Yes" [15,] "No" "Yes" [16,] "Yes" "Yes" [17,] "No" "Yes" [18,] "Yes" "Yes" [19,] "Yes" "Yes" [20,] "No" "No" Extracting column Binary2 from M2 − > M2[,"Binary2",drop = FALSE] Binary2 [1,] "Yes" [2,] "No" [3,] "No" [4,] "Yes" [5,] "Yes" [6,] "No" [7,] "Yes" [8,] "Yes" [9,] "No" [10,] "Yes" [11,] "Yes" [12,] "No" [13,] "No" [14,] "Yes" [15,] "Yes" [16,] "Yes" [17,] "Yes" [18,] "Yes" [19,] "Yes" [20,] "No"
[ { "code": null, "e": 1380, "s": 1062, "text": "To filter a single column of a matrix in R if the matrix has column names, we can simply use single square brackets but this will result in a vector without the column name. If we want to use the column name then column name or column number needs to be passed with drop=FALSE argument as shown in the below examples." }, { "code": null, "e": 1390, "s": 1380, "text": "Live Demo" }, { "code": null, "e": 1483, "s": 1390, "text": "> M1<-matrix(sample(0:1,80,replace=TRUE),ncol=4)\n> colnames(M1)<-c(\"V1\",\"V2\",\"V3\",\"V4\")\n> M1" }, { "code": null, "e": 1841, "s": 1483, "text": " V1 V2 V3 V4\n[1,] 0 0 1 0\n[2,] 1 1 1 1\n[3,] 0 0 0 0\n[4,] 0 1 1 0\n[5,] 1 1 1 1\n[6,] 0 1 1 0\n[7,] 0 1 0 1\n[8,] 1 1 0 1\n[9,] 1 1 0 1\n[10,] 0 0 1 0\n[11,] 0 0 0 1\n[12,] 0 1 0 0\n[13,] 0 0 0 0\n[14,] 1 0 0 0\n[15,] 0 1 0 1\n[16,] 0 0 1 0\n[17,] 1 1 1 1\n[18,] 1 0 1 1\n[19,] 1 0 1 1\n[20,] 0 0 0 0" }, { "code": null, "e": 1872, "s": 1841, "text": "Extracting column V1 from M1 −" }, { "code": null, "e": 1897, "s": 1872, "text": "> M1[,\"V1\",drop = FALSE]" }, { "code": null, "e": 2066, "s": 1897, "text": " V1\n[1,] 0\n[2,] 1\n[3,] 0\n[4,] 0\n[5,] 1\n[6,] 0\n[7,] 0\n[8,] 1\n[9,] 1\n[10,] 0\n[11,] 0\n[12,] 0\n[13,] 0\n[14,] 1\n[15,] 0\n[16,] 0\n[17,] 1\n[18,] 1\n[19,] 1\n[20,] 0" }, { "code": null, "e": 2076, "s": 2066, "text": "Live Demo" }, { "code": null, "e": 2181, "s": 2076, "text": "> M2<-matrix(sample(c(\"Yes\",\"No\"),40,replace = TRUE),ncol=2)\n> colnames(M2)<-c(\"Binary1\",\"Binary2\")\n> M2" }, { "code": null, "e": 2554, "s": 2181, "text": " Binary1 Binary2\n[1,] \"Yes\" \"Yes\"\n[2,] \"Yes\" \"No\"\n[3,] \"Yes\" \"No\"\n[4,] \"Yes\" \"Yes\"\n[5,] \"Yes\" \"Yes\"\n[6,] \"No\" \"No\"\n[7,] \"Yes\" \"Yes\"\n[8,] \"No\" \"Yes\"\n[9,] \"No\" \"No\"\n[10,] \"Yes\" \"Yes\"\n[11,] \"Yes\" \"Yes\"\n[12,] \"Yes\" \"No\"\n[13,] \"Yes\" \"No\"\n[14,] \"No\" \"Yes\"\n[15,] \"No\" \"Yes\"\n[16,] \"Yes\" \"Yes\"\n[17,] \"No\" \"Yes\"\n[18,] \"Yes\" \"Yes\"\n[19,] \"Yes\" \"Yes\"\n[20,] \"No\" \"No\"" }, { "code": null, "e": 2590, "s": 2554, "text": "Extracting column Binary2 from M2 −" }, { "code": null, "e": 2620, "s": 2590, "text": "> M2[,\"Binary2\",drop = FALSE]" }, { "code": null, "e": 2866, "s": 2620, "text": " Binary2\n[1,] \"Yes\"\n[2,] \"No\"\n[3,] \"No\"\n[4,] \"Yes\"\n[5,] \"Yes\"\n[6,] \"No\"\n[7,] \"Yes\"\n[8,] \"Yes\"\n[9,] \"No\"\n[10,] \"Yes\"\n[11,] \"Yes\"\n[12,] \"No\"\n[13,] \"No\"\n[14,] \"Yes\"\n[15,] \"Yes\"\n[16,] \"Yes\"\n[17,] \"Yes\"\n[18,] \"Yes\"\n[19,] \"Yes\"\n[20,] \"No\"" } ]
The Three-Dimensional Koch Snowflake — Fun Fractals at Home | by Marc Wouts | Towards Data Science
Welcome! This is an article that we are writing with six hands: Marc, the Father, mathematician and a little bit of a handyman in his spare time, Sasha, 12, and Félix, 8. We started by exploring some mathematical concepts from the Koch Snowflake, everyone brought a lot of enthusiasm to it and we ended up going much further than expected ... to Scratch programming, 3D printing, and ultimately writing this article. Suffice to say that we had a great time on this project ... and now we want to share it with you! Note: the original version of this article (in French), as well as all the attached files, can be found at mwouts/flocon on GitHub. Summary Koch Snowflake Draw the Snowflake A bit of Arithmetic Program the Snowflake in Scratch How about moving to 3D? The Tetrahedron The Snowflake in 3D — Step 1 The Snowflake in 3D — Recurrence Print the Snowflake What to do with these Snowflakes? The Koch snowflake is a very well-known shape among mathematicians! It is easy to draw, it has very funny mathematical properties: its perimeter is infinite, while its area remains finite, and above all, it is a beautiful example of fractal: the parts of the snowflake look like the snowflake itself ... but smaller! Let’s start by drawing the snowflake. We start from an equilateral triangle. Then, we cut each side of the triangle into three equal sub-segments. And we glue an equilateral triangle, three times smaller than the first, on each of the central segments. Now let’s delete the central segments. In other words, we replaced each central segment by two new segments, of the same length, which form an angle of 60 ° with the initial segment: We can start the operation again! We now have 12 segments. Let’s cut them each into 3, and replace each of the central segments with two new segments. So that makes us 48 segments, doesn’t it? And so on! Let’s not be afraid of anything ... here are snowflakes with 768 or even 3072 or 12288 sides ... but it is getting a bit long to draw ... The Koch snowflake is well known for its mathematical properties. At each stage, its perimeter and area increase ... but not in the same proportions! Let’s imagine that the initial triangle has sides of length 7.29cm (we will be able to divide 7.29 many times by 3, hence this choice!) At each step, the number of sides of the snowflake is multiplied by 4, and each side becomes 3x shorter. Each time the snowflake is increased by one degree, the perimeter is multiplied by 4/3. Which means that we can multiply it like this to infinity ... which, obviously, also takes an infinite time! The perimeter will exceed (and stay beyond) any value. For example: It exceeds the meter in step 6 the kilometer at stage 30 and even the light year at step 134! Mathematicians say in this case that the perimeter tends to infinity. And the area of the snowflake? Well, we can calculate it. To each operation, we add triangles which have a side three times smaller than the triangles of the previous level, and which therefore have an area 9 times smaller. And the number of these new triangles is equal to the number of segments of the Snowflake, which is multiplied by 4 at each step. As the calculation is a bit laborious, we wrote a small program: import mathdef compute_snowflake_area(triangle_area, max_degree): # Initialization: the triangle snowflake_area = triangle_area segment_count = 3 for degree in range (0, max_degree + 1): print (f"Snowflake of degree {degree}: {segment_count} sides, {snowflake_area} cm2") # Area of the higher degree snowflake triangle_area /= 9 snowflake_area += triangle_area * segment_count segment_count *= 4triangle_side_length = 7.29triangle_area = math.sqrt (3) / 4 * triangle_side_length ** 2compute_snowflake_area(triangle_area, 120) Which give: Snowflake of degree 0: 3 sides, 23.01207033063029 cm2Snowflake of degree 1: 12 sides, 30.68276044084039 cm2Snowflake of degree 2: 48 sides, 34.09195604537821 cm2Snowflake of degree 3: 192 sides, 35.60715409183946 cm2Snowflake of degree 4: 768 sides, 36.280575445822244 cm2Snowflake of degree 5: 3072 sides, 36.57987382537014 cm2Snowflake of degree 6: 12288 sides, 36.712895327391436 cm2 We can run the program longer, and we see that the area increases less and less quickly! Even after a while the program always gives the same number: 36.81931252900848 cm2. The area continues to increase, but we can no longer see it because the program does not display enough decimal places ... Snowflake of degree 118: 331283824645947061796868281389297221717653230664178554647801162742366208 sides, 36.81931252900848 cm2Snowflake of degree 119: 1325135298583788247187473125557188886870612922656714218591204650969464832 sides, 36.81931252900848 cm2Snowflake of degree 120: 5300541194335152988749892502228755547482451690626856874364818603877859328 sides, 36.81931252900848 cm2 Mathematicians say that the area converge, and they even know how to calculate the value of the limit, equal to 2a2√3/5=36.819312529008464..., cf. the article on the Koch Snowflake at Wikipedia. The Koch snowflake is, therefore, an example of a shape with a finite area, and an infinite perimeter! It was Félix who introduced us to Scratch! Scratch is a great project from the Massachusetts Institute of Technology (MIT). It is a very accessible programming language for children. The instructions are very visual. You can try Scratch directly on the MIT site, without installing anything! Before drawing the Snowflake, we will use Scratch to draw an equilateral triangle. The program is quite simple: we move the character forward and then turn, and this three times: You noticed, didn’t you, that we make the character turn at an angle of 120 °, and not 60 ° ... let’s admit that we started by trying 60 °, but then we obtained a hexagon and not a triangle. This is because the angle should be the change in direction, not the angle made by the two segments! If you want to try out the program that draws the triangle yourself, it is available in the folder of this project — it’s triangle.sb3. To program the snowflake, let’s see which trajectory the Scratch character will have to follow. Each segment of the triangle will be replaced by a series of 4 segments: Let’s do the exercise of describing this trajectory: we draw a segment of length 3 times smaller than the initial segment then, we turn 60 ° counterclockwise we draw another segment turn 120 ° clockwise before drawing the third segment finally, we turn 60 ° in the opposite direction and we draw the last segment. For the triangle, we had already used a block in scratch. Here, we replace the instruction “advance 250 steps” that we had for the triangle by “to make a segment of length 250 steps in the current direction”. And this “make a segment” block will itself make the 4 segments that we described above ... In other words, it will call the same block 4 times! Of course, you have to be careful not to call the same block indefinitely, otherwise the program would never end! So, in our program, we ask the sub-segment to be three times shorter and take one step less We are ready! By the way, if you want to try it with us, the program is also available in the folder — it’s the file. The 2D Koch snowflake is super cool ... are you curious to see what it looks like in 3D? In three dimensions, the equivalent of the triangle is the tetrahedron. It is the regular polyhedron whose 4 faces are equilateral triangles. We started by building the tetrahedron with OpenSCAD. In OpenSCAD, we create the tetrahedron by giving the coordinates of all the points, then by enumerating all the faces. The code is written H = sqrt(3); // It is the height of an equilateral triangle of side 2T = 2 * sqrt(6) / 3; // It is the height of a regular tetrahedron of side 2polyhedron( // The 4 vertices of the tetrahedron points=[ // 4 points with each time the three coordinates: x, y, z [-1,0,0], [1,0,0], [0,H,0], [0,H/3,T] ], // The 4 triangles which make the tetrahedron faces=[ // 4 faces which each connect 3 vertices (the 4 vertices are numbered from 0 to 3) [0,1,2], [3,2,1], [3,1,0], [3,0,2] ] ); How were the coordinates of the vertices determined? We first placed the first two vertices on the x axis, at coordinates -1 and +1. Our tetrahedron will therefore have a side equal to 2. Then we looked for the height of the equilateral triangle on Wikipedia. The height is equal to √3/2 times the side. So we place the third vertex at y=√3. The vertex of the tetrahedron is above the center of gravity of the horizontal triangle, one third of the height of the triangle. It will therefore have for coordinate y=√3/3. Finally, Wikipedia tells us that the height of the tetrahedron is equal to √6/3 times its side. We therefore choose z=2√6/3 for this point. In OpenSCAD, we execute the code with F5 (preview), and we get this: OpenSCAD also allows you to export 3D files in STL format (F6 then F7). You can find our tetrahedron in STL format here, and visualize it in 3D on GitHub, or even print it in 3D! Remember: to advance the construction of the two-dimensional Koch snowflake one step, you had to add a side triangle equal to one third of the segment, to each segment. In three dimensions we will try the same approach. To each equilateral triangle, we will add a new tetrahedron! Let’s do it for only one face: we’ll get a total of six equilateral triangles. The question is ... how are we going to program this? Let’s study the program below: H = sqrt(3);module triangle() {polyhedron( points=[[-1,0,0], [1,0,0], [0,H,0]], faces=[[0,1,2]]);};translate([0,H/3,0])scale(1/2)for (angle = [0,120,240]){ rotate([0,0,angle]) translate([0,H/3,0]) { triangle(); rotate([109.5,0,0]) mirror([0,0,1]) triangle(); };}; With the triangle module, we define a function capable of drawing a triangle with side equal to 2. It is the base of the previous tetrahedron. To draw the 6 triangles, we use a loop which makes us rotate in space, 0, 120 or 240 °: these are the instructions for (angle=[0,120,240]) and rotate ([0,0 , angle]) We want each of these 6 triangles to be 2x smaller than the original triangle, hence the scale (1/2) instruction which reduces the scale by a factor of 2. Finally, the figure must have the same center of gravity (in the (x, y) plane), hence the instruction translate ([0, H/3, 0]) which positions us on this point before doing the rotations Finally, we draw two triangles (and this, three times, thanks to the for loop) at a distance H/3 from the center of rotation, hence the second instruction translate ([0, H/3, 0]) . The first triangle is in the original plane. The other makes an angle of 109.5 ° with respect to this plane. We found this angle by dichotomy: if we put a smaller value, the central tetrahedron is open, and if it is larger, the triangles intersect ... The exact value is probably a little different - it is perhaps the angle Vertex-Center-Vertex equal to 2 arctan (√2)=109.4712 ... according to Wikipedia. To iterate the steps of the Snowflake in 3D, we will replace the call to triangle() by a call to snowflake_face(n-1). The corresponding file is available at flocon_3d.scad in the folder. Open it in OpenSCAD, and change the value in snowflake_face(3) on the last line, then press F5. Be careful not to put too large values... Remember that for n=0 we have only one triangle, but that at each step we create six times more, in other words for n=5 we will already have 7776 triangles ... beyond that, the exponential growth of triangles is likely to get the better of OpenSCAD, or even block your computer. Did you like us find the result a little disappointing? The 3D Snowflake surface converges to a very simple shape ... an irregular tetrahedron (with a height equal to half the height of the regular tetrahedron). To check that we were not mistaken, we again used Wikipedia. Let’s look for example at the face of the 3D Snowflake with n=4: A little too regular for a fractal, isn’t it? In fact, the fractal side of the 3D snowflake only appears when turned over! Click here to interact with the 3D file yourself. We discovered 3D printing during the first lockdown ... It’s very simple: the printer gradually builds the requested shape by melting a plastic wire. It’s great ... but hey, it’s a bit slow ... and not always easy to fix! In the case of Flocon 3D, the first problem we encountered was that our Flocon weighed 0 grams ... in other words, the printer did not print anything at all! You will encounter the same problem if you attempt to print the STL files that we have generated so far. Indeed, our STL files describe only a surface, and not a volume. If we really want to print the Snowflake, we will have to give it a little thickness, and replace the basic shape, i.e. the triangle (), by a volume which _ resembles_ the triangle but which will have a little material. We did this with the following function: module thick_triangle(h) {polyhedron ( points=[ [-1.0, h], [1.0, h], [0, H, h], [-1.0, -h], [1.0, -h], [0, H, -h]], // vertices in clockwise order seen from the outside faces=[[0,1,2], [1,0,3,4], [2,1,4,5], [0,2,5,3], [5,4,3]]) ;}; in the file flocon_3d_imprimable.scad. Note that, to prevent the triangles from getting too thin when we apply the recursion, we multiply the h argument by 2 at each step, to compensate for the change in scale. The result is the following form: You can generate the STL files yourself (F5, F6 then F7 in OpenSCAD, it takes some time already for n=4) or you can get them in the stl_imprimables folder. To print, open the file in Cura Ultimaker: Choose the scaling that’s right for you ... remember if you print 2x smaller the output will be 8x faster ... or be patient! Note that you can change the thickness of the triangles if you want, by opening the file flocon_3d_imprimable.scad in OpenSCAD and changing the h parameter. Here are some pictures of the 3D printing: We preferred to print without support, as extracting the print material seemed almost impossible given the fractal nature of our snowflake. The downside is that the impression is not perfect ... the threads thrown above the void sometimes hang a little. We have printed several models, modulating the size so that the base triangle is always the same size: We found a lot of games to make with these snowflakes! We only printed the faces of the snowflake. Remember that the starting shape is a tetrahedron, not a triangle ... So let’s take four faces, and put them together. Surprise!! We get a CUBE! The small snowflakes hide in the big ones: With six small model faces, the large model can be reproduced. It’s like in our OpenSCAD program! The flakes also inspired our very young 3-year-old milliner: Thank you for accompanying us throughout this article ... see you soon for other fun discoveries with the Wouts family!
[ { "code": null, "e": 688, "s": 172, "text": "Welcome! This is an article that we are writing with six hands: Marc, the Father, mathematician and a little bit of a handyman in his spare time, Sasha, 12, and Félix, 8. We started by exploring some mathematical concepts from the Koch Snowflake, everyone brought a lot of enthusiasm to it and we ended up going much further than expected ... to Scratch programming, 3D printing, and ultimately writing this article. Suffice to say that we had a great time on this project ... and now we want to share it with you!" }, { "code": null, "e": 820, "s": 688, "text": "Note: the original version of this article (in French), as well as all the attached files, can be found at mwouts/flocon on GitHub." }, { "code": null, "e": 828, "s": 820, "text": "Summary" }, { "code": null, "e": 843, "s": 828, "text": "Koch Snowflake" }, { "code": null, "e": 862, "s": 843, "text": "Draw the Snowflake" }, { "code": null, "e": 882, "s": 862, "text": "A bit of Arithmetic" }, { "code": null, "e": 915, "s": 882, "text": "Program the Snowflake in Scratch" }, { "code": null, "e": 939, "s": 915, "text": "How about moving to 3D?" }, { "code": null, "e": 955, "s": 939, "text": "The Tetrahedron" }, { "code": null, "e": 984, "s": 955, "text": "The Snowflake in 3D — Step 1" }, { "code": null, "e": 1017, "s": 984, "text": "The Snowflake in 3D — Recurrence" }, { "code": null, "e": 1037, "s": 1017, "text": "Print the Snowflake" }, { "code": null, "e": 1071, "s": 1037, "text": "What to do with these Snowflakes?" }, { "code": null, "e": 1388, "s": 1071, "text": "The Koch snowflake is a very well-known shape among mathematicians! It is easy to draw, it has very funny mathematical properties: its perimeter is infinite, while its area remains finite, and above all, it is a beautiful example of fractal: the parts of the snowflake look like the snowflake itself ... but smaller!" }, { "code": null, "e": 1641, "s": 1388, "text": "Let’s start by drawing the snowflake. We start from an equilateral triangle. Then, we cut each side of the triangle into three equal sub-segments. And we glue an equilateral triangle, three times smaller than the first, on each of the central segments." }, { "code": null, "e": 1824, "s": 1641, "text": "Now let’s delete the central segments. In other words, we replaced each central segment by two new segments, of the same length, which form an angle of 60 ° with the initial segment:" }, { "code": null, "e": 2028, "s": 1824, "text": "We can start the operation again! We now have 12 segments. Let’s cut them each into 3, and replace each of the central segments with two new segments. So that makes us 48 segments, doesn’t it? And so on!" }, { "code": null, "e": 2166, "s": 2028, "text": "Let’s not be afraid of anything ... here are snowflakes with 768 or even 3072 or 12288 sides ... but it is getting a bit long to draw ..." }, { "code": null, "e": 2316, "s": 2166, "text": "The Koch snowflake is well known for its mathematical properties. At each stage, its perimeter and area increase ... but not in the same proportions!" }, { "code": null, "e": 2557, "s": 2316, "text": "Let’s imagine that the initial triangle has sides of length 7.29cm (we will be able to divide 7.29 many times by 3, hence this choice!) At each step, the number of sides of the snowflake is multiplied by 4, and each side becomes 3x shorter." }, { "code": null, "e": 2754, "s": 2557, "text": "Each time the snowflake is increased by one degree, the perimeter is multiplied by 4/3. Which means that we can multiply it like this to infinity ... which, obviously, also takes an infinite time!" }, { "code": null, "e": 2822, "s": 2754, "text": "The perimeter will exceed (and stay beyond) any value. For example:" }, { "code": null, "e": 2853, "s": 2822, "text": "It exceeds the meter in step 6" }, { "code": null, "e": 2879, "s": 2853, "text": "the kilometer at stage 30" }, { "code": null, "e": 2916, "s": 2879, "text": "and even the light year at step 134!" }, { "code": null, "e": 2986, "s": 2916, "text": "Mathematicians say in this case that the perimeter tends to infinity." }, { "code": null, "e": 3017, "s": 2986, "text": "And the area of the snowflake?" }, { "code": null, "e": 3340, "s": 3017, "text": "Well, we can calculate it. To each operation, we add triangles which have a side three times smaller than the triangles of the previous level, and which therefore have an area 9 times smaller. And the number of these new triangles is equal to the number of segments of the Snowflake, which is multiplied by 4 at each step." }, { "code": null, "e": 3405, "s": 3340, "text": "As the calculation is a bit laborious, we wrote a small program:" }, { "code": null, "e": 3978, "s": 3405, "text": "import mathdef compute_snowflake_area(triangle_area, max_degree): # Initialization: the triangle snowflake_area = triangle_area segment_count = 3 for degree in range (0, max_degree + 1): print (f\"Snowflake of degree {degree}: {segment_count} sides, {snowflake_area} cm2\") # Area of the higher degree snowflake triangle_area /= 9 snowflake_area += triangle_area * segment_count segment_count *= 4triangle_side_length = 7.29triangle_area = math.sqrt (3) / 4 * triangle_side_length ** 2compute_snowflake_area(triangle_area, 120)" }, { "code": null, "e": 3990, "s": 3978, "text": "Which give:" }, { "code": null, "e": 4377, "s": 3990, "text": "Snowflake of degree 0: 3 sides, 23.01207033063029 cm2Snowflake of degree 1: 12 sides, 30.68276044084039 cm2Snowflake of degree 2: 48 sides, 34.09195604537821 cm2Snowflake of degree 3: 192 sides, 35.60715409183946 cm2Snowflake of degree 4: 768 sides, 36.280575445822244 cm2Snowflake of degree 5: 3072 sides, 36.57987382537014 cm2Snowflake of degree 6: 12288 sides, 36.712895327391436 cm2" }, { "code": null, "e": 4673, "s": 4377, "text": "We can run the program longer, and we see that the area increases less and less quickly! Even after a while the program always gives the same number: 36.81931252900848 cm2. The area continues to increase, but we can no longer see it because the program does not display enough decimal places ..." }, { "code": null, "e": 5054, "s": 4673, "text": "Snowflake of degree 118: 331283824645947061796868281389297221717653230664178554647801162742366208 sides, 36.81931252900848 cm2Snowflake of degree 119: 1325135298583788247187473125557188886870612922656714218591204650969464832 sides, 36.81931252900848 cm2Snowflake of degree 120: 5300541194335152988749892502228755547482451690626856874364818603877859328 sides, 36.81931252900848 cm2" }, { "code": null, "e": 5249, "s": 5054, "text": "Mathematicians say that the area converge, and they even know how to calculate the value of the limit, equal to 2a2√3/5=36.819312529008464..., cf. the article on the Koch Snowflake at Wikipedia." }, { "code": null, "e": 5352, "s": 5249, "text": "The Koch snowflake is, therefore, an example of a shape with a finite area, and an infinite perimeter!" }, { "code": null, "e": 5645, "s": 5352, "text": "It was Félix who introduced us to Scratch! Scratch is a great project from the Massachusetts Institute of Technology (MIT). It is a very accessible programming language for children. The instructions are very visual. You can try Scratch directly on the MIT site, without installing anything!" }, { "code": null, "e": 5824, "s": 5645, "text": "Before drawing the Snowflake, we will use Scratch to draw an equilateral triangle. The program is quite simple: we move the character forward and then turn, and this three times:" }, { "code": null, "e": 6116, "s": 5824, "text": "You noticed, didn’t you, that we make the character turn at an angle of 120 °, and not 60 ° ... let’s admit that we started by trying 60 °, but then we obtained a hexagon and not a triangle. This is because the angle should be the change in direction, not the angle made by the two segments!" }, { "code": null, "e": 6252, "s": 6116, "text": "If you want to try out the program that draws the triangle yourself, it is available in the folder of this project — it’s triangle.sb3." }, { "code": null, "e": 6421, "s": 6252, "text": "To program the snowflake, let’s see which trajectory the Scratch character will have to follow. Each segment of the triangle will be replaced by a series of 4 segments:" }, { "code": null, "e": 6474, "s": 6421, "text": "Let’s do the exercise of describing this trajectory:" }, { "code": null, "e": 6543, "s": 6474, "text": "we draw a segment of length 3 times smaller than the initial segment" }, { "code": null, "e": 6579, "s": 6543, "text": "then, we turn 60 ° counterclockwise" }, { "code": null, "e": 6603, "s": 6579, "text": "we draw another segment" }, { "code": null, "e": 6624, "s": 6603, "text": "turn 120 ° clockwise" }, { "code": null, "e": 6657, "s": 6624, "text": "before drawing the third segment" }, { "code": null, "e": 6705, "s": 6657, "text": "finally, we turn 60 ° in the opposite direction" }, { "code": null, "e": 6735, "s": 6705, "text": "and we draw the last segment." }, { "code": null, "e": 7089, "s": 6735, "text": "For the triangle, we had already used a block in scratch. Here, we replace the instruction “advance 250 steps” that we had for the triangle by “to make a segment of length 250 steps in the current direction”. And this “make a segment” block will itself make the 4 segments that we described above ... In other words, it will call the same block 4 times!" }, { "code": null, "e": 7252, "s": 7089, "text": "Of course, you have to be careful not to call the same block indefinitely, otherwise the program would never end! So, in our program, we ask the sub-segment to be" }, { "code": null, "e": 7272, "s": 7252, "text": "three times shorter" }, { "code": null, "e": 7295, "s": 7272, "text": "and take one step less" }, { "code": null, "e": 7413, "s": 7295, "text": "We are ready! By the way, if you want to try it with us, the program is also available in the folder — it’s the file." }, { "code": null, "e": 7502, "s": 7413, "text": "The 2D Koch snowflake is super cool ... are you curious to see what it looks like in 3D?" }, { "code": null, "e": 7644, "s": 7502, "text": "In three dimensions, the equivalent of the triangle is the tetrahedron. It is the regular polyhedron whose 4 faces are equilateral triangles." }, { "code": null, "e": 7698, "s": 7644, "text": "We started by building the tetrahedron with OpenSCAD." }, { "code": null, "e": 7837, "s": 7698, "text": "In OpenSCAD, we create the tetrahedron by giving the coordinates of all the points, then by enumerating all the faces. The code is written" }, { "code": null, "e": 8384, "s": 7837, "text": "H = sqrt(3); // It is the height of an equilateral triangle of side 2T = 2 * sqrt(6) / 3; // It is the height of a regular tetrahedron of side 2polyhedron( // The 4 vertices of the tetrahedron points=[ // 4 points with each time the three coordinates: x, y, z [-1,0,0], [1,0,0], [0,H,0], [0,H/3,T] ], // The 4 triangles which make the tetrahedron faces=[ // 4 faces which each connect 3 vertices (the 4 vertices are numbered from 0 to 3) [0,1,2], [3,2,1], [3,1,0], [3,0,2] ] );" }, { "code": null, "e": 8437, "s": 8384, "text": "How were the coordinates of the vertices determined?" }, { "code": null, "e": 8572, "s": 8437, "text": "We first placed the first two vertices on the x axis, at coordinates -1 and +1. Our tetrahedron will therefore have a side equal to 2." }, { "code": null, "e": 8726, "s": 8572, "text": "Then we looked for the height of the equilateral triangle on Wikipedia. The height is equal to √3/2 times the side. So we place the third vertex at y=√3." }, { "code": null, "e": 8902, "s": 8726, "text": "The vertex of the tetrahedron is above the center of gravity of the horizontal triangle, one third of the height of the triangle. It will therefore have for coordinate y=√3/3." }, { "code": null, "e": 9042, "s": 8902, "text": "Finally, Wikipedia tells us that the height of the tetrahedron is equal to √6/3 times its side. We therefore choose z=2√6/3 for this point." }, { "code": null, "e": 9111, "s": 9042, "text": "In OpenSCAD, we execute the code with F5 (preview), and we get this:" }, { "code": null, "e": 9290, "s": 9111, "text": "OpenSCAD also allows you to export 3D files in STL format (F6 then F7). You can find our tetrahedron in STL format here, and visualize it in 3D on GitHub, or even print it in 3D!" }, { "code": null, "e": 9459, "s": 9290, "text": "Remember: to advance the construction of the two-dimensional Koch snowflake one step, you had to add a side triangle equal to one third of the segment, to each segment." }, { "code": null, "e": 9571, "s": 9459, "text": "In three dimensions we will try the same approach. To each equilateral triangle, we will add a new tetrahedron!" }, { "code": null, "e": 9650, "s": 9571, "text": "Let’s do it for only one face: we’ll get a total of six equilateral triangles." }, { "code": null, "e": 9704, "s": 9650, "text": "The question is ... how are we going to program this?" }, { "code": null, "e": 9735, "s": 9704, "text": "Let’s study the program below:" }, { "code": null, "e": 10034, "s": 9735, "text": "H = sqrt(3);module triangle() {polyhedron( points=[[-1,0,0], [1,0,0], [0,H,0]], faces=[[0,1,2]]);};translate([0,H/3,0])scale(1/2)for (angle = [0,120,240]){ rotate([0,0,angle]) translate([0,H/3,0]) { triangle(); rotate([109.5,0,0]) mirror([0,0,1]) triangle(); };};" }, { "code": null, "e": 10177, "s": 10034, "text": "With the triangle module, we define a function capable of drawing a triangle with side equal to 2. It is the base of the previous tetrahedron." }, { "code": null, "e": 10343, "s": 10177, "text": "To draw the 6 triangles, we use a loop which makes us rotate in space, 0, 120 or 240 °: these are the instructions for (angle=[0,120,240]) and rotate ([0,0 , angle])" }, { "code": null, "e": 10498, "s": 10343, "text": "We want each of these 6 triangles to be 2x smaller than the original triangle, hence the scale (1/2) instruction which reduces the scale by a factor of 2." }, { "code": null, "e": 10684, "s": 10498, "text": "Finally, the figure must have the same center of gravity (in the (x, y) plane), hence the instruction translate ([0, H/3, 0]) which positions us on this point before doing the rotations" }, { "code": null, "e": 11271, "s": 10684, "text": "Finally, we draw two triangles (and this, three times, thanks to the for loop) at a distance H/3 from the center of rotation, hence the second instruction translate ([0, H/3, 0]) . The first triangle is in the original plane. The other makes an angle of 109.5 ° with respect to this plane. We found this angle by dichotomy: if we put a smaller value, the central tetrahedron is open, and if it is larger, the triangles intersect ... The exact value is probably a little different - it is perhaps the angle Vertex-Center-Vertex equal to 2 arctan (√2)=109.4712 ... according to Wikipedia." }, { "code": null, "e": 11458, "s": 11271, "text": "To iterate the steps of the Snowflake in 3D, we will replace the call to triangle() by a call to snowflake_face(n-1). The corresponding file is available at flocon_3d.scad in the folder." }, { "code": null, "e": 11875, "s": 11458, "text": "Open it in OpenSCAD, and change the value in snowflake_face(3) on the last line, then press F5. Be careful not to put too large values... Remember that for n=0 we have only one triangle, but that at each step we create six times more, in other words for n=5 we will already have 7776 triangles ... beyond that, the exponential growth of triangles is likely to get the better of OpenSCAD, or even block your computer." }, { "code": null, "e": 12148, "s": 11875, "text": "Did you like us find the result a little disappointing? The 3D Snowflake surface converges to a very simple shape ... an irregular tetrahedron (with a height equal to half the height of the regular tetrahedron). To check that we were not mistaken, we again used Wikipedia." }, { "code": null, "e": 12213, "s": 12148, "text": "Let’s look for example at the face of the 3D Snowflake with n=4:" }, { "code": null, "e": 12259, "s": 12213, "text": "A little too regular for a fractal, isn’t it?" }, { "code": null, "e": 12386, "s": 12259, "text": "In fact, the fractal side of the 3D snowflake only appears when turned over! Click here to interact with the 3D file yourself." }, { "code": null, "e": 12608, "s": 12386, "text": "We discovered 3D printing during the first lockdown ... It’s very simple: the printer gradually builds the requested shape by melting a plastic wire. It’s great ... but hey, it’s a bit slow ... and not always easy to fix!" }, { "code": null, "e": 12766, "s": 12608, "text": "In the case of Flocon 3D, the first problem we encountered was that our Flocon weighed 0 grams ... in other words, the printer did not print anything at all!" }, { "code": null, "e": 12936, "s": 12766, "text": "You will encounter the same problem if you attempt to print the STL files that we have generated so far. Indeed, our STL files describe only a surface, and not a volume." }, { "code": null, "e": 13156, "s": 12936, "text": "If we really want to print the Snowflake, we will have to give it a little thickness, and replace the basic shape, i.e. the triangle (), by a volume which _ resembles_ the triangle but which will have a little material." }, { "code": null, "e": 13197, "s": 13156, "text": "We did this with the following function:" }, { "code": null, "e": 13444, "s": 13197, "text": "module thick_triangle(h) {polyhedron ( points=[ [-1.0, h], [1.0, h], [0, H, h], [-1.0, -h], [1.0, -h], [0, H, -h]], // vertices in clockwise order seen from the outside faces=[[0,1,2], [1,0,3,4], [2,1,4,5], [0,2,5,3], [5,4,3]]) ;};" }, { "code": null, "e": 13689, "s": 13444, "text": "in the file flocon_3d_imprimable.scad. Note that, to prevent the triangles from getting too thin when we apply the recursion, we multiply the h argument by 2 at each step, to compensate for the change in scale. The result is the following form:" }, { "code": null, "e": 13845, "s": 13689, "text": "You can generate the STL files yourself (F5, F6 then F7 in OpenSCAD, it takes some time already for n=4) or you can get them in the stl_imprimables folder." }, { "code": null, "e": 13888, "s": 13845, "text": "To print, open the file in Cura Ultimaker:" }, { "code": null, "e": 14170, "s": 13888, "text": "Choose the scaling that’s right for you ... remember if you print 2x smaller the output will be 8x faster ... or be patient! Note that you can change the thickness of the triangles if you want, by opening the file flocon_3d_imprimable.scad in OpenSCAD and changing the h parameter." }, { "code": null, "e": 14213, "s": 14170, "text": "Here are some pictures of the 3D printing:" }, { "code": null, "e": 14467, "s": 14213, "text": "We preferred to print without support, as extracting the print material seemed almost impossible given the fractal nature of our snowflake. The downside is that the impression is not perfect ... the threads thrown above the void sometimes hang a little." }, { "code": null, "e": 14570, "s": 14467, "text": "We have printed several models, modulating the size so that the base triangle is always the same size:" }, { "code": null, "e": 14625, "s": 14570, "text": "We found a lot of games to make with these snowflakes!" }, { "code": null, "e": 14814, "s": 14625, "text": "We only printed the faces of the snowflake. Remember that the starting shape is a tetrahedron, not a triangle ... So let’s take four faces, and put them together. Surprise!! We get a CUBE!" }, { "code": null, "e": 14857, "s": 14814, "text": "The small snowflakes hide in the big ones:" }, { "code": null, "e": 14955, "s": 14857, "text": "With six small model faces, the large model can be reproduced. It’s like in our OpenSCAD program!" }, { "code": null, "e": 15016, "s": 14955, "text": "The flakes also inspired our very young 3-year-old milliner:" } ]
Data Science for Fitness: 50 is the new 30 — Part I | by Luis Miguel Sánchez | Towards Data Science
The following article will try to explain a very interesting experience for me, that along with the algorithmic music composition algos (sans neural nets that I developed in 2013–2014) is one of the most rewarding projects I have undertaken: Data Science for Fitness. In these series of practical applications of Data Science (aren’t you tired of tutorials around MNIST, Reddit, Yelp datasets, etc?) I am drafting, I plan to tell mini-stories: how I got there, why, when, etc. and touch subjects that are related to the one in the title. This is not straight code review, although some will be covered. These mini stories will be more about data strategy, data science and its practical applications around a topic, instead of just code. Coming back to fitness, I became sensitive to this subject in September 2008. Back then I was working for Lehman Brothers, ‘ground zero’ of the financial crisis and where I had developed a great deal of expertise developing and launching structured finance deals around exotic data sets. After Lehman’s collapse, I took a long, hard look at myself in the mirror. I saw a depressed, physically unfit (technically, obese) Wall Street executive who had specialized in an area of finance that was taking a lot of heat. But I also saw my inner data scientist. Quants are essentially data scientists with a lot of time series analysis and financial backgrounds. Quants are problem solvers, and at that point I had big problems: the gradual deterioration of my health due to my obesity & work related stress. The quant/data scientist in the mirror looked back at me and said “You can solve your fitness problem with data!” Let me stop right now to tell you that if you’re interested in learning about a quick fix to lose weight fast, then you might as well move to another article because this story is not for you. Or if you are looking to learn data science, or programming, then this article is not for you either. If, on the other hand, you’re looking for unique knowledge to empower you to accomplish your fitness goals, to look at things in new ways, if you like data science, and you are thinking about improving your fitness, maybe this article will provide the right motivation for you, and maybe get you in the right direction to develop your own research and fitness program. Back to the story: I was a fat quant looking for a rational method of getting in shape, and in line with my quant mentality. A good quant knows that asking the right question brings you halfway to the answer. So, in 2008 I committed to researching the topic, developing a scientific and unbiased analysis, and using my own data and the findings on myself. As a good quant / data scientist, I am borderline obsessed with data. In the interview I had with the “Data Science Handbook”, I even tell the story of how in 1992 I wrote an an Expert System (basically, an analytical hierarchy process, a structured technique for organizing and analyzing complex decisions, based on mathematics and psychology), to decide if I should propose to my wife... Anyway, I have been manually collecting certain types of data since 1985 for whatever analysis I was into. Since then, I had been collecting and storing data first in written form, then on 5 1/4-inch disks, 3 1/2-inch floppys, magnetic tapes, zip disks, CDs, DVDs, hard drives, you name it. In 1990 I got my first email and Unix (the granddaddy of Linux) account and that year started to add some rudimentary types of online data collection to my offline data collection, since I had access to the incipient Internet. But first I had to tweak certain tools, or develop my own, since Mosaic (the first browser) had not even been invented yet, and I had to use Gopher, IRC and FTP to collect data. Regarding fitness, my data collection was very sparse from 1987 to 2000: a few data points a week using 2–3 devices. However, since 2000, my data became more dense with hundreds of data points per day, and using over 30 different devices and services. The chart above shows some of the devices and services I have used to capture my own body parameters over the years. With the diverse datasets I had collected, plus knowledge gathered from papers published in medical journals, conversations with people over 40 in good shape, data scraped from sites such as bodybuilding.com, etc. and combining my own experience: Could I use a data science approach to help me get in shape?Could I use data science and elements of quantitative analysis to find what would work best for me in a relatively short period of time?Could I write code to consolidated data from the multiple hardware, software and web based systems that I use and have used?Could I program custom metrics, test hypothesis, and develop near real time alerts for deviations away from my fitness goals?Could I use classification models for the analysis? Could I use regression models?Could I derive actionable intelligence from my data? Could I use a data science approach to help me get in shape? Could I use data science and elements of quantitative analysis to find what would work best for me in a relatively short period of time? Could I write code to consolidated data from the multiple hardware, software and web based systems that I use and have used? Could I program custom metrics, test hypothesis, and develop near real time alerts for deviations away from my fitness goals? Could I use classification models for the analysis? Could I use regression models? Could I derive actionable intelligence from my data? The answer is yes to all. Below are some of the parameters captured over many years. I intend to share an extract of my data and some code in my GitHub or Bitbucket account at some later date. Please follow me in Sourcerer if you want to be up to date, since 99% of my code is in private repos, and Sourcerer consolidates all my coding activity in a very nice format. A little review about Sourcerer: It still has a few bugs, but the work these guys are doing is GREAT and very useful, specially for people like me, whose code is mostly in private repos and with very little contribution to open source projects (Wall Street vs Silicon Valley. Anybody can relate?). Using machine learning, Sourcerer analyzes your code and ranks your coding skills (commits, lines of code, code frequency, style, etc.), against ALL other users in GitHub, BitBucket, GitLab, etc. and summarizes your expertise by technology, programming languages, etc. None of your proprietary code in private repos is shared with Sourcerer, simply, just analyzed. To the left is a sample of my Sourcerer profile. If you are a coder with public and private repos in many places, you should definitely check it out. Coming back the the article, the parameters in bold below will be the ones I will attempt to explain in future series of “Data Science for Fitness: 50 is the new 30”. They are the ones with the highest impact in my transformation from fat to fit, and the ones with the highest explanatory value in the machine models I developed. They are: Total daily calories consumed Breakdown of calories consumed (calories from protein, carbohydrates, fat) Caloric expenditure per exercise: Weightlifting, snowboarding, running, bicycling, golfing, other Muscle mass Fat mass (bodyfat %) Visceral fat VO2 Max Excess post-exercise oxygen consumption (EPOC) Recovery time Training effect T-3 Total Test* T-4 Total Test* Average body temperature* Total fat Saturated fat Fiber Cholesterol Total weight Body age Blood sugar level Body mass index The results of my system were outstanding. This is a summary: More remarkable than the 72 lbs of body fat loss in 2009–2011 is the 30 lbs of muscle gain in 8 years, which is metabolically very difficult if you are in your 40s or 50s and do not use anabolic steroids. Hell, it is difficult to gain that much even in your 20s or 30s! I said that the results were outstanding because we need to consider that over the age of 30, everybody suffers from age-related sarcopenia, responsible for a loss of 3% to 5% of muscle mass each decade (it accelerate at older ages, from 0.5% to 1% of muscle mass loss per year after the age of 50). Even if you are active, you’ll still have some muscle loss. Any loss of muscle matters because it lessens strength and mobility. So, in a way, reversing muscle loss is a way to look and feel younger. In addition to the benefits of diet and exercise, I also experience massive muscular growth for a short period of time (check out my 1/2012 picture above), using a controversial “technique” called “glycogen super compensation”. Gylcogen super compensation was not part of my normal fitness routine, but a “side experiment”, to try to quantify certain parameters of muscle growth. It is not sustainable over time, so I do not recommend it to anybody, but you can read more about it here. So how did I achieve those gains against all odds? Quantitative analysis / data science and discipline. But it all started with data collection and data consolidation & standardization. The start — Data Consolidation The chart below shows my total weight fluctuation over the years, where I tested numerous weight loss systems (Nutrisystem, Atkins, etc.), with mixed results. The shaded areas represent the different characteristics of the knowledge captured and analyzed. Fitness data and knowledge was acquired from the period 1985 to 2008 (over 23 years of random trial and error and training w/o a proper plan). From 2008 and on, I analyzed my own data and included domain expertise from people in the field of fitness and nutrition, optimized for a very specific, double objective function: max fat loss and max muscle gain (tricky since it is metabolically impossible to accomplish both simultaneously). In order to use all the different data types I had captured and spread across different mediums, I had to consolidate them into a single database. I choose MongoDB, since: It is a schema-less database, so my code defines my schema which to me is perfect for data science. Because it stores data in the form of BSON (binary JSON), it helps store very rich, granular data while being capable of holding arrays and other documents. For example, I can see the total calories consumed in a workout, but in a more granular inspection, I can see the second by second caloric consumption captured by one of my devices (ie. FitBit real time heart rate data, calculated calories, etc.) all in the same mongodb “document”. MongoDB supports dynamic queries. It is easy to scale. No complex joins are needed. Performance tuning is easy compared to any relational databases. Enables faster access of the data due to its nature of using internal memory for the storage. Supports search by regex as well. MongoDB follows regular release cycle of its newer versions, like Docker, etc. In a nutshell, I find that it is the best db to work with time series and the different features present in diverse time series. ( As another example, all my algorithmic music dbs were initially stored in HDF files, now migrating to mongodb, as well as the insurance data I have worked with for life and P/C). Below is a chart representing the different stages of this project, and the tools I used: In the next posts, I’ll explain some of the important features of my system, and expand a little more, in no particular order, in some of the key findings in: Nutrition: Types of foods, timing of meals, quantity of food matters.Type & intensity of workouts: Relationship to: a) Improving fitness and muscle mass, b) over training and decreasing muscle mass, and c) maintaining muscle mass. Order of factors matter. Time series matter.Psychological aspects: Compliance to yourself, quantification and motivation. Nutrition: Types of foods, timing of meals, quantity of food matters. Type & intensity of workouts: Relationship to: a) Improving fitness and muscle mass, b) over training and decreasing muscle mass, and c) maintaining muscle mass. Order of factors matter. Time series matter. Psychological aspects: Compliance to yourself, quantification and motivation. In the chart above, I have found that most people who do not make any progress or very little progress (the bulk of the population) are working out under patterns “B” and “C” and they do not have any idea what their optimal values are since they are not collecting data, and if they are collecting it, they don't know how to analyze it and place it in the context of their own goals. As of February 2019, I am currently more in type “C” situation, since it has been difficult for me to keep the strict compliance I had for my own fitness a while back. Nevertheless I have managed to keep most of my acquired muscle mass, and can switch to pattern “A” again for 8–12 weeks to get back in shape from my current baseline. Since this project covered so many areas in data science and also in fitness, I would love to hear your feedback as to where I should focus my next article: Data collection?Data visualization?Machine learning models and validation?Other? Data collection? Data visualization? Machine learning models and validation? Other? Until then, I hope to hear your comments/feedback. If you enjoyed this post, you might want to read my other eclectic posts about data science and finance, fitness, music, etc. You can follow activity in my private repos here, twitter posts here, or you can ask Qs below or email me at SGX Analytics. If you are curious about my time series analysis and simulations applied to algorithmic music composition, you can listen to my AI generated music in Apple Music, Spotify, and SoundCloud. Cheers Parts of this story were originally published in my personal blog a few years back. All the pictures and charts are mine and/or have permission to post. 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": 440, "s": 172, "text": "The following article will try to explain a very interesting experience for me, that along with the algorithmic music composition algos (sans neural nets that I developed in 2013–2014) is one of the most rewarding projects I have undertaken: Data Science for Fitness." }, { "code": null, "e": 710, "s": 440, "text": "In these series of practical applications of Data Science (aren’t you tired of tutorials around MNIST, Reddit, Yelp datasets, etc?) I am drafting, I plan to tell mini-stories: how I got there, why, when, etc. and touch subjects that are related to the one in the title." }, { "code": null, "e": 910, "s": 710, "text": "This is not straight code review, although some will be covered. These mini stories will be more about data strategy, data science and its practical applications around a topic, instead of just code." }, { "code": null, "e": 1465, "s": 910, "text": "Coming back to fitness, I became sensitive to this subject in September 2008. Back then I was working for Lehman Brothers, ‘ground zero’ of the financial crisis and where I had developed a great deal of expertise developing and launching structured finance deals around exotic data sets. After Lehman’s collapse, I took a long, hard look at myself in the mirror. I saw a depressed, physically unfit (technically, obese) Wall Street executive who had specialized in an area of finance that was taking a lot of heat. But I also saw my inner data scientist." }, { "code": null, "e": 1712, "s": 1465, "text": "Quants are essentially data scientists with a lot of time series analysis and financial backgrounds. Quants are problem solvers, and at that point I had big problems: the gradual deterioration of my health due to my obesity & work related stress." }, { "code": null, "e": 1826, "s": 1712, "text": "The quant/data scientist in the mirror looked back at me and said “You can solve your fitness problem with data!”" }, { "code": null, "e": 2121, "s": 1826, "text": "Let me stop right now to tell you that if you’re interested in learning about a quick fix to lose weight fast, then you might as well move to another article because this story is not for you. Or if you are looking to learn data science, or programming, then this article is not for you either." }, { "code": null, "e": 2490, "s": 2121, "text": "If, on the other hand, you’re looking for unique knowledge to empower you to accomplish your fitness goals, to look at things in new ways, if you like data science, and you are thinking about improving your fitness, maybe this article will provide the right motivation for you, and maybe get you in the right direction to develop your own research and fitness program." }, { "code": null, "e": 2846, "s": 2490, "text": "Back to the story: I was a fat quant looking for a rational method of getting in shape, and in line with my quant mentality. A good quant knows that asking the right question brings you halfway to the answer. So, in 2008 I committed to researching the topic, developing a scientific and unbiased analysis, and using my own data and the findings on myself." }, { "code": null, "e": 3236, "s": 2846, "text": "As a good quant / data scientist, I am borderline obsessed with data. In the interview I had with the “Data Science Handbook”, I even tell the story of how in 1992 I wrote an an Expert System (basically, an analytical hierarchy process, a structured technique for organizing and analyzing complex decisions, based on mathematics and psychology), to decide if I should propose to my wife..." }, { "code": null, "e": 3754, "s": 3236, "text": "Anyway, I have been manually collecting certain types of data since 1985 for whatever analysis I was into. Since then, I had been collecting and storing data first in written form, then on 5 1/4-inch disks, 3 1/2-inch floppys, magnetic tapes, zip disks, CDs, DVDs, hard drives, you name it. In 1990 I got my first email and Unix (the granddaddy of Linux) account and that year started to add some rudimentary types of online data collection to my offline data collection, since I had access to the incipient Internet." }, { "code": null, "e": 3932, "s": 3754, "text": "But first I had to tweak certain tools, or develop my own, since Mosaic (the first browser) had not even been invented yet, and I had to use Gopher, IRC and FTP to collect data." }, { "code": null, "e": 4184, "s": 3932, "text": "Regarding fitness, my data collection was very sparse from 1987 to 2000: a few data points a week using 2–3 devices. However, since 2000, my data became more dense with hundreds of data points per day, and using over 30 different devices and services." }, { "code": null, "e": 4301, "s": 4184, "text": "The chart above shows some of the devices and services I have used to capture my own body parameters over the years." }, { "code": null, "e": 4548, "s": 4301, "text": "With the diverse datasets I had collected, plus knowledge gathered from papers published in medical journals, conversations with people over 40 in good shape, data scraped from sites such as bodybuilding.com, etc. and combining my own experience:" }, { "code": null, "e": 5128, "s": 4548, "text": "Could I use a data science approach to help me get in shape?Could I use data science and elements of quantitative analysis to find what would work best for me in a relatively short period of time?Could I write code to consolidated data from the multiple hardware, software and web based systems that I use and have used?Could I program custom metrics, test hypothesis, and develop near real time alerts for deviations away from my fitness goals?Could I use classification models for the analysis? Could I use regression models?Could I derive actionable intelligence from my data?" }, { "code": null, "e": 5189, "s": 5128, "text": "Could I use a data science approach to help me get in shape?" }, { "code": null, "e": 5326, "s": 5189, "text": "Could I use data science and elements of quantitative analysis to find what would work best for me in a relatively short period of time?" }, { "code": null, "e": 5451, "s": 5326, "text": "Could I write code to consolidated data from the multiple hardware, software and web based systems that I use and have used?" }, { "code": null, "e": 5577, "s": 5451, "text": "Could I program custom metrics, test hypothesis, and develop near real time alerts for deviations away from my fitness goals?" }, { "code": null, "e": 5660, "s": 5577, "text": "Could I use classification models for the analysis? Could I use regression models?" }, { "code": null, "e": 5713, "s": 5660, "text": "Could I derive actionable intelligence from my data?" }, { "code": null, "e": 5739, "s": 5713, "text": "The answer is yes to all." }, { "code": null, "e": 6081, "s": 5739, "text": "Below are some of the parameters captured over many years. I intend to share an extract of my data and some code in my GitHub or Bitbucket account at some later date. Please follow me in Sourcerer if you want to be up to date, since 99% of my code is in private repos, and Sourcerer consolidates all my coding activity in a very nice format." }, { "code": null, "e": 6895, "s": 6081, "text": "A little review about Sourcerer: It still has a few bugs, but the work these guys are doing is GREAT and very useful, specially for people like me, whose code is mostly in private repos and with very little contribution to open source projects (Wall Street vs Silicon Valley. Anybody can relate?). Using machine learning, Sourcerer analyzes your code and ranks your coding skills (commits, lines of code, code frequency, style, etc.), against ALL other users in GitHub, BitBucket, GitLab, etc. and summarizes your expertise by technology, programming languages, etc. None of your proprietary code in private repos is shared with Sourcerer, simply, just analyzed. To the left is a sample of my Sourcerer profile. If you are a coder with public and private repos in many places, you should definitely check it out." }, { "code": null, "e": 7235, "s": 6895, "text": "Coming back the the article, the parameters in bold below will be the ones I will attempt to explain in future series of “Data Science for Fitness: 50 is the new 30”. They are the ones with the highest impact in my transformation from fat to fit, and the ones with the highest explanatory value in the machine models I developed. They are:" }, { "code": null, "e": 7265, "s": 7235, "text": "Total daily calories consumed" }, { "code": null, "e": 7340, "s": 7265, "text": "Breakdown of calories consumed (calories from protein, carbohydrates, fat)" }, { "code": null, "e": 7438, "s": 7340, "text": "Caloric expenditure per exercise: Weightlifting, snowboarding, running, bicycling, golfing, other" }, { "code": null, "e": 7450, "s": 7438, "text": "Muscle mass" }, { "code": null, "e": 7471, "s": 7450, "text": "Fat mass (bodyfat %)" }, { "code": null, "e": 7484, "s": 7471, "text": "Visceral fat" }, { "code": null, "e": 7492, "s": 7484, "text": "VO2 Max" }, { "code": null, "e": 7539, "s": 7492, "text": "Excess post-exercise oxygen consumption (EPOC)" }, { "code": null, "e": 7553, "s": 7539, "text": "Recovery time" }, { "code": null, "e": 7569, "s": 7553, "text": "Training effect" }, { "code": null, "e": 7585, "s": 7569, "text": "T-3 Total Test*" }, { "code": null, "e": 7601, "s": 7585, "text": "T-4 Total Test*" }, { "code": null, "e": 7627, "s": 7601, "text": "Average body temperature*" }, { "code": null, "e": 7637, "s": 7627, "text": "Total fat" }, { "code": null, "e": 7651, "s": 7637, "text": "Saturated fat" }, { "code": null, "e": 7657, "s": 7651, "text": "Fiber" }, { "code": null, "e": 7669, "s": 7657, "text": "Cholesterol" }, { "code": null, "e": 7682, "s": 7669, "text": "Total weight" }, { "code": null, "e": 7691, "s": 7682, "text": "Body age" }, { "code": null, "e": 7709, "s": 7691, "text": "Blood sugar level" }, { "code": null, "e": 7725, "s": 7709, "text": "Body mass index" }, { "code": null, "e": 7787, "s": 7725, "text": "The results of my system were outstanding. This is a summary:" }, { "code": null, "e": 8057, "s": 7787, "text": "More remarkable than the 72 lbs of body fat loss in 2009–2011 is the 30 lbs of muscle gain in 8 years, which is metabolically very difficult if you are in your 40s or 50s and do not use anabolic steroids. Hell, it is difficult to gain that much even in your 20s or 30s!" }, { "code": null, "e": 8557, "s": 8057, "text": "I said that the results were outstanding because we need to consider that over the age of 30, everybody suffers from age-related sarcopenia, responsible for a loss of 3% to 5% of muscle mass each decade (it accelerate at older ages, from 0.5% to 1% of muscle mass loss per year after the age of 50). Even if you are active, you’ll still have some muscle loss. Any loss of muscle matters because it lessens strength and mobility. So, in a way, reversing muscle loss is a way to look and feel younger." }, { "code": null, "e": 8785, "s": 8557, "text": "In addition to the benefits of diet and exercise, I also experience massive muscular growth for a short period of time (check out my 1/2012 picture above), using a controversial “technique” called “glycogen super compensation”." }, { "code": null, "e": 9044, "s": 8785, "text": "Gylcogen super compensation was not part of my normal fitness routine, but a “side experiment”, to try to quantify certain parameters of muscle growth. It is not sustainable over time, so I do not recommend it to anybody, but you can read more about it here." }, { "code": null, "e": 9230, "s": 9044, "text": "So how did I achieve those gains against all odds? Quantitative analysis / data science and discipline. But it all started with data collection and data consolidation & standardization." }, { "code": null, "e": 9261, "s": 9230, "text": "The start — Data Consolidation" }, { "code": null, "e": 9420, "s": 9261, "text": "The chart below shows my total weight fluctuation over the years, where I tested numerous weight loss systems (Nutrisystem, Atkins, etc.), with mixed results." }, { "code": null, "e": 9954, "s": 9420, "text": "The shaded areas represent the different characteristics of the knowledge captured and analyzed. Fitness data and knowledge was acquired from the period 1985 to 2008 (over 23 years of random trial and error and training w/o a proper plan). From 2008 and on, I analyzed my own data and included domain expertise from people in the field of fitness and nutrition, optimized for a very specific, double objective function: max fat loss and max muscle gain (tricky since it is metabolically impossible to accomplish both simultaneously)." }, { "code": null, "e": 10126, "s": 9954, "text": "In order to use all the different data types I had captured and spread across different mediums, I had to consolidate them into a single database. I choose MongoDB, since:" }, { "code": null, "e": 10226, "s": 10126, "text": "It is a schema-less database, so my code defines my schema which to me is perfect for data science." }, { "code": null, "e": 10666, "s": 10226, "text": "Because it stores data in the form of BSON (binary JSON), it helps store very rich, granular data while being capable of holding arrays and other documents. For example, I can see the total calories consumed in a workout, but in a more granular inspection, I can see the second by second caloric consumption captured by one of my devices (ie. FitBit real time heart rate data, calculated calories, etc.) all in the same mongodb “document”." }, { "code": null, "e": 10700, "s": 10666, "text": "MongoDB supports dynamic queries." }, { "code": null, "e": 10721, "s": 10700, "text": "It is easy to scale." }, { "code": null, "e": 10750, "s": 10721, "text": "No complex joins are needed." }, { "code": null, "e": 10815, "s": 10750, "text": "Performance tuning is easy compared to any relational databases." }, { "code": null, "e": 10909, "s": 10815, "text": "Enables faster access of the data due to its nature of using internal memory for the storage." }, { "code": null, "e": 10943, "s": 10909, "text": "Supports search by regex as well." }, { "code": null, "e": 11022, "s": 10943, "text": "MongoDB follows regular release cycle of its newer versions, like Docker, etc." }, { "code": null, "e": 11332, "s": 11022, "text": "In a nutshell, I find that it is the best db to work with time series and the different features present in diverse time series. ( As another example, all my algorithmic music dbs were initially stored in HDF files, now migrating to mongodb, as well as the insurance data I have worked with for life and P/C)." }, { "code": null, "e": 11422, "s": 11332, "text": "Below is a chart representing the different stages of this project, and the tools I used:" }, { "code": null, "e": 11581, "s": 11422, "text": "In the next posts, I’ll explain some of the important features of my system, and expand a little more, in no particular order, in some of the key findings in:" }, { "code": null, "e": 11934, "s": 11581, "text": "Nutrition: Types of foods, timing of meals, quantity of food matters.Type & intensity of workouts: Relationship to: a) Improving fitness and muscle mass, b) over training and decreasing muscle mass, and c) maintaining muscle mass. Order of factors matter. Time series matter.Psychological aspects: Compliance to yourself, quantification and motivation." }, { "code": null, "e": 12004, "s": 11934, "text": "Nutrition: Types of foods, timing of meals, quantity of food matters." }, { "code": null, "e": 12211, "s": 12004, "text": "Type & intensity of workouts: Relationship to: a) Improving fitness and muscle mass, b) over training and decreasing muscle mass, and c) maintaining muscle mass. Order of factors matter. Time series matter." }, { "code": null, "e": 12289, "s": 12211, "text": "Psychological aspects: Compliance to yourself, quantification and motivation." }, { "code": null, "e": 12673, "s": 12289, "text": "In the chart above, I have found that most people who do not make any progress or very little progress (the bulk of the population) are working out under patterns “B” and “C” and they do not have any idea what their optimal values are since they are not collecting data, and if they are collecting it, they don't know how to analyze it and place it in the context of their own goals." }, { "code": null, "e": 13008, "s": 12673, "text": "As of February 2019, I am currently more in type “C” situation, since it has been difficult for me to keep the strict compliance I had for my own fitness a while back. Nevertheless I have managed to keep most of my acquired muscle mass, and can switch to pattern “A” again for 8–12 weeks to get back in shape from my current baseline." }, { "code": null, "e": 13165, "s": 13008, "text": "Since this project covered so many areas in data science and also in fitness, I would love to hear your feedback as to where I should focus my next article:" }, { "code": null, "e": 13246, "s": 13165, "text": "Data collection?Data visualization?Machine learning models and validation?Other?" }, { "code": null, "e": 13263, "s": 13246, "text": "Data collection?" }, { "code": null, "e": 13283, "s": 13263, "text": "Data visualization?" }, { "code": null, "e": 13323, "s": 13283, "text": "Machine learning models and validation?" }, { "code": null, "e": 13330, "s": 13323, "text": "Other?" }, { "code": null, "e": 13381, "s": 13330, "text": "Until then, I hope to hear your comments/feedback." }, { "code": null, "e": 13631, "s": 13381, "text": "If you enjoyed this post, you might want to read my other eclectic posts about data science and finance, fitness, music, etc. You can follow activity in my private repos here, twitter posts here, or you can ask Qs below or email me at SGX Analytics." }, { "code": null, "e": 13819, "s": 13631, "text": "If you are curious about my time series analysis and simulations applied to algorithmic music composition, you can listen to my AI generated music in Apple Music, Spotify, and SoundCloud." }, { "code": null, "e": 13826, "s": 13819, "text": "Cheers" }, { "code": null, "e": 13979, "s": 13826, "text": "Parts of this story were originally published in my personal blog a few years back. All the pictures and charts are mine and/or have permission to post." } ]
Decimal to binary list conversion in Python
Python being a versatile language can handle many requirements that comes up during the data processing. When we need to convert a decimal number to a binary number we can use the following python programs. We can Use the letter in the formatter to indicate which number base: decimal, hex, octal, or binary we want our number to be formatted. In the below example we take the formatter as 0:0b then supply the integer to the format function which needs to get converted to binary. Live Demo Dnum = 11 print("Given decimal : " + str(Dnum)) # Decimal to binary number conversion binnum = [int(i) for i in list('{0:0b}'.format(Dnum))] # Printing result print("Converted binary list is : ",binnum) Running the above code gives us the following result − Given decimal : 11 Converted binary list is : [1, 0, 1, 1] The bin() is a in-built function which can also be used in a similar way as above. This function Python bin() function converts an integer number to a binary string prefixed with 0b. So we slice the first two characters. Live Demo Dnum = 11 print("Given decimal : " + str(Dnum)) # Decimal to binary number conversion binnum = [int(i) for i in bin(Dnum)[2:]] # Printing result print("Converted binary list is : ",binnum) Running the above code gives us the following result − Given decimal : 11 Converted binary list is : [1, 0, 1, 1]
[ { "code": null, "e": 1269, "s": 1062, "text": "Python being a versatile language can handle many requirements that comes up during the data processing. When we need to convert a decimal number to a binary number we can use the following python programs." }, { "code": null, "e": 1544, "s": 1269, "text": "We can Use the letter in the formatter to indicate which number base: decimal, hex, octal, or binary we want our number to be formatted. In the below example we take the formatter as 0:0b then supply the integer to the format function which needs to get converted to binary." }, { "code": null, "e": 1555, "s": 1544, "text": " Live Demo" }, { "code": null, "e": 1761, "s": 1555, "text": "Dnum = 11\n\nprint(\"Given decimal : \" + str(Dnum))\n\n# Decimal to binary number conversion\nbinnum = [int(i) for i in list('{0:0b}'.format(Dnum))]\n\n# Printing result\nprint(\"Converted binary list is : \",binnum)" }, { "code": null, "e": 1816, "s": 1761, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 1875, "s": 1816, "text": "Given decimal : 11\nConverted binary list is : [1, 0, 1, 1]" }, { "code": null, "e": 2096, "s": 1875, "text": "The bin() is a in-built function which can also be used in a similar way as above. This function Python bin() function converts an integer number to a binary string prefixed with 0b. So we slice the first two characters." }, { "code": null, "e": 2107, "s": 2096, "text": " Live Demo" }, { "code": null, "e": 2300, "s": 2107, "text": "Dnum = 11\n\nprint(\"Given decimal : \" + str(Dnum))\n\n# Decimal to binary number conversion\nbinnum = [int(i) for i in bin(Dnum)[2:]]\n\n# Printing result\nprint(\"Converted binary list is : \",binnum)\n" }, { "code": null, "e": 2355, "s": 2300, "text": "Running the above code gives us the following result −" }, { "code": null, "e": 2414, "s": 2355, "text": "Given decimal : 11\nConverted binary list is : [1, 0, 1, 1]" } ]
Differences between Collection and Collections in Java?
The Collection is an interface whereas Collections is a utility class in Java. The Set, List, and Queue are some of the subinterfaces of Collection interface, a Map interface is also part of the Collections Framework, but it doesn't inherit Collection interface. The important methods of Collection interface are add(), remove(), size(), clear() etc and Collections class contains only static methods like sort(), min(), max(), fill(), copy(), reverse() etc. public interface Collection<E> extends Iterable<E> public class Collections extends Object import java.util.*; public class CollectionTest { public static void main(String args[]) { ArrayList<Integer> list = new ArrayList<Integer>(); // Adding elements to the ArrayList list.add(5); list.add(20); list.add(35); list.add(50); list.add(65); // Collections.min() method to display minimum value System.out.println("Minimum value: " + Collections.min(list)); // Collections.max() method to display maximum value System.out.println("Maximum value: " + Collections.max(list)); } } Minimum value: 5 Maximum value: 65
[ { "code": null, "e": 1521, "s": 1062, "text": "The Collection is an interface whereas Collections is a utility class in Java. The Set, List, and Queue are some of the subinterfaces of Collection interface, a Map interface is also part of the Collections Framework, but it doesn't inherit Collection interface. The important methods of Collection interface are add(), remove(), size(), clear() etc and Collections class contains only static methods like sort(), min(), max(), fill(), copy(), reverse() etc." }, { "code": null, "e": 1572, "s": 1521, "text": "public interface Collection<E> extends Iterable<E>" }, { "code": null, "e": 1612, "s": 1572, "text": "public class Collections extends Object" }, { "code": null, "e": 2168, "s": 1612, "text": "import java.util.*;\npublic class CollectionTest {\n public static void main(String args[]) {\n ArrayList<Integer> list = new ArrayList<Integer>();\n // Adding elements to the ArrayList\n list.add(5);\n list.add(20);\n list.add(35);\n list.add(50);\n list.add(65);\n // Collections.min() method to display minimum value\n System.out.println(\"Minimum value: \" + Collections.min(list));\n // Collections.max() method to display maximum value\n System.out.println(\"Maximum value: \" + Collections.max(list));\n }\n}" }, { "code": null, "e": 2203, "s": 2168, "text": "Minimum value: 5\nMaximum value: 65" } ]
JSF - Custom Tag
JSF provides the developer with a powerful capability to define own custom tags, which can be used to render custom contents. Defining a custom tag in JSF is a three-step process. <h:body> <ui:composition> <h:commandButton type = "submit" value = "#{okLabel}" /> <h:commandButton type = "reset" value = "#{cancelLabel}" /> </ui:composition> </h:body> As the name mentions a Tag library is a library of tags. Following table describes important attributes of a tag library. facelet-taglib Contains all the tags. namespace Namespace of the tag library and should be unique. tag Contains a single tag tag-name Name of the tag source Tag implementation <facelet-taglib> <namespace>http://tutorialspoint.com/facelets</namespace> <tag> <tag-name>buttonPanel</tag-name> <source>com/tutorialspoint/buttonPanel.xhtml</source> </tag> </facelet-taglib> <context-param> <param-name>javax.faces.FACELETS_LIBRARIES</param-name> <param-value>/WEB-INF/tutorialspoint.taglib.xml</param-value> </context-param> Using a custom tag in JSF is a two-step process. <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:h = "http://java.sun.com/jsf/html" xmlns:ui = "http://java.sun.com/jsf/facelets"> xmlns:tp = "http://tutorialspoint.com/facelets"> <h:body> <tp:buttonPanel okLabel = "Ok" cancelLabel = "Cancel" /> </h:body> 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:body> <ui:composition> <h:commandButton type = "submit" value = "#{okLabel}" /> <h:commandButton type = "reset" value = "#{cancelLabel}" /> </ui:composition> </h:body> </html> <?xml version = "1.0"?> <!DOCTYPE facelet-taglib PUBLIC "-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN" "http://java.sun.com/dtd/facelet-taglib_1_0.dtd"> <facelet-taglib> <namespace>http://tutorialspoint.com/facelets</namespace> <tag> <tag-name>buttonPanel</tag-name> <source>com/tutorialspoint/buttonPanel.xhtml</source> </tag> </facelet-taglib> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd" > <web-app> <display-name>Archetype Created Web Application</display-name> <context-param> <param-name>javax.faces.PROJECT_STAGE</param-name> <param-value>Development</param-value> </context-param> <context-param> <param-name>javax.faces.FACELETS_LIBRARIES</param-name> <param-value>/WEB-INF/tutorialspoint.taglib.xml</param-value> </context-param> <servlet> <servlet-name>Faces Servlet</servlet-name> <servlet-class>javax.faces.webapp.FacesServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Faces Servlet</servlet-name> <url-pattern>*.jsf</url-pattern> </servlet-mapping> </web-app> <?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" xmlns:tp = "http://tutorialspoint.com/facelets"> <h:head> <title>JSF tutorial</title> </h:head> <h:body> <h1>Custom Tags Example</h1> <tp:buttonPanel okLabel = "Ok" cancelLabel = "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, this will produce the following result. 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2078, "s": 1952, "text": "JSF provides the developer with a powerful capability to define own custom tags, which can be used to render custom contents." }, { "code": null, "e": 2132, "s": 2078, "text": "Defining a custom tag in JSF is a three-step process." }, { "code": null, "e": 2323, "s": 2132, "text": "<h:body>\n <ui:composition> \n <h:commandButton type = \"submit\" value = \"#{okLabel}\" />\n <h:commandButton type = \"reset\" value = \"#{cancelLabel}\" /> \n </ui:composition>\n</h:body>" }, { "code": null, "e": 2445, "s": 2323, "text": "As the name mentions a Tag library is a library of tags. Following table describes important attributes of a tag library." }, { "code": null, "e": 2460, "s": 2445, "text": "facelet-taglib" }, { "code": null, "e": 2483, "s": 2460, "text": "Contains all the tags." }, { "code": null, "e": 2493, "s": 2483, "text": "namespace" }, { "code": null, "e": 2544, "s": 2493, "text": "Namespace of the tag library and should be unique." }, { "code": null, "e": 2548, "s": 2544, "text": "tag" }, { "code": null, "e": 2570, "s": 2548, "text": "Contains a single tag" }, { "code": null, "e": 2579, "s": 2570, "text": "tag-name" }, { "code": null, "e": 2595, "s": 2579, "text": "Name of the tag" }, { "code": null, "e": 2602, "s": 2595, "text": "source" }, { "code": null, "e": 2621, "s": 2602, "text": "Tag implementation" }, { "code": null, "e": 2835, "s": 2621, "text": "<facelet-taglib>\n <namespace>http://tutorialspoint.com/facelets</namespace>\n <tag>\n <tag-name>buttonPanel</tag-name>\n <source>com/tutorialspoint/buttonPanel.xhtml</source>\n </tag>\n</facelet-taglib>" }, { "code": null, "e": 2992, "s": 2835, "text": "<context-param>\n <param-name>javax.faces.FACELETS_LIBRARIES</param-name>\n <param-value>/WEB-INF/tutorialspoint.taglib.xml</param-value>\n</context-param>" }, { "code": null, "e": 3041, "s": 2992, "text": "Using a custom tag in JSF is a two-step process." }, { "code": null, "e": 3235, "s": 3041, "text": "<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 xmlns:tp = \"http://tutorialspoint.com/facelets\">" }, { "code": null, "e": 3317, "s": 3235, "text": "<h:body>\n <tp:buttonPanel okLabel = \"Ok\" cancelLabel = \"Cancel\" /> \t\t\n</h:body>" }, { "code": null, "e": 3388, "s": 3317, "text": "Let us create a test JSF application to test the template tags in JSF." }, { "code": null, "e": 3918, "s": 3388, "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:body>\n <ui:composition> \n <h:commandButton type = \"submit\" value = \"#{okLabel}\" />\n <h:commandButton type = \"reset\" value = \"#{cancelLabel}\" /> \n </ui:composition>\n </h:body>\n</html>" }, { "code": null, "e": 4299, "s": 3918, "text": "<?xml version = \"1.0\"?>\n<!DOCTYPE facelet-taglib PUBLIC\n\"-//Sun Microsystems, Inc.//DTD Facelet Taglib 1.0//EN\"\n\"http://java.sun.com/dtd/facelet-taglib_1_0.dtd\">\n\n<facelet-taglib>\n <namespace>http://tutorialspoint.com/facelets</namespace>\n \n <tag>\n <tag-name>buttonPanel</tag-name>\n <source>com/tutorialspoint/buttonPanel.xhtml</source>\n </tag>\n</facelet-taglib>" }, { "code": null, "e": 5113, "s": 4299, "text": "<!DOCTYPE web-app PUBLIC\n\"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN\"\n\"http://java.sun.com/dtd/web-app_2_3.dtd\" >\n\n<web-app>\n <display-name>Archetype Created Web Application</display-name>\n <context-param>\n <param-name>javax.faces.PROJECT_STAGE</param-name>\n <param-value>Development</param-value>\n </context-param>\t\n \n <context-param>\n <param-name>javax.faces.FACELETS_LIBRARIES</param-name>\n <param-value>/WEB-INF/tutorialspoint.taglib.xml</param-value>\n </context-param>\n \n <servlet>\n <servlet-name>Faces Servlet</servlet-name>\n <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>\n </servlet>\n \n <servlet-mapping>\n <servlet-name>Faces Servlet</servlet-name>\n <url-pattern>*.jsf</url-pattern>\n </servlet-mapping>\n</web-app>\t" }, { "code": null, "e": 5674, "s": 5113, "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 xmlns:tp = \"http://tutorialspoint.com/facelets\">\n \n <h:head>\n <title>JSF tutorial</title>\t\t\t\n </h:head>\n \n <h:body>\n <h1>Custom Tags Example</h1>\n <tp:buttonPanel okLabel = \"Ok\" cancelLabel = \"Cancel\" />\n </h:body>\n</html>" }, { "code": null, "e": 5890, "s": 5674, "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": 5925, "s": 5890, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 5940, "s": 5925, "text": " Chaand Sheikh" }, { "code": null, "e": 5947, "s": 5940, "text": " Print" }, { "code": null, "e": 5958, "s": 5947, "text": " Add Notes" } ]
Comparing enum members in Java
The java.lang.Enum class is the common base class of all Java language enumeration types. Following is the declaration for java.lang.Enum class - public abstract class Enum<E extends Enum<E>> extends Object implements Comparable<E>, Serializable We can compare enum variables using the following ways. Using Enum.compareTo() method. compareTo() method compares this enum with the specified object for order. Using Enum.compareTo() method. compareTo() method compares this enum with the specified object for order. Using Enum.equals() method. equals() method returns true if the specified object is equal to this enum constant. Using Enum.equals() method. equals() method returns true if the specified object is equal to this enum constant. Using == operator. The == operator checks the type and makes a null-safe comparison of the same type of enum constants. Using == operator. The == operator checks the type and makes a null-safe comparison of the same type of enum constants. Live Demo public class Tester { // enum showing topics covered under Tutorials enum Tutorials { TOPIC_1, TOPIC_2, TOPIC_3; } public static void main(String[] args) { Tutorials t1, t2, t3; t1 = Tutorials.TOPIC_1; t2 = Tutorials.TOPIC_2; t3 = Tutorials.TOPIC_3; //Comparing using compareTo() method if(t1.compareTo(t2) > 0) { System.out.println(t2 + " completed before " + t1); } if(t1.compareTo(t2) < 0) { System.out.println(t1 + " completed before " + t2); } if(t1.compareTo(t2) == 0) { System.out.println(t1 + " completed with " + t2); } //Comparing using == //In this case t1 can be null as well causing no issue if(t1 == Tutorials.TOPIC_1) { System.out.println("t1 = TOPIC_1"); }else { System.out.println("t1 != TOPIC_1"); } //Comparing using equals() method //In this case t2 cannot be null. It will cause //null pointer exception if(t2.equals(Tutorials.TOPIC_2)) { System.out.println("t2 = TOPIC_2"); }else { System.out.println("t2 != TOPIC_2"); } Tutorials t4 = null; //Comparing using equals() method //in null safe manner if(Tutorials.TOPIC_3.equals(t4)) { System.out.println("t4 = TOPIC_3"); }else { System.out.println("t4 != TOPIC_3"); } } } TOPIC_1 completed before TOPIC_2 t1 = TOPIC_1 t2 = TOPIC_2 t4 != TOPIC_3
[ { "code": null, "e": 1152, "s": 1062, "text": "The java.lang.Enum class is the common base class of all Java language enumeration types." }, { "code": null, "e": 1208, "s": 1152, "text": "Following is the declaration for java.lang.Enum class -" }, { "code": null, "e": 1317, "s": 1208, "text": "public abstract class Enum<E extends Enum<E>>\n extends Object\n implements Comparable<E>, Serializable" }, { "code": null, "e": 1373, "s": 1317, "text": "We can compare enum variables using the following ways." }, { "code": null, "e": 1479, "s": 1373, "text": "Using Enum.compareTo() method. compareTo() method compares this enum with the specified object for order." }, { "code": null, "e": 1585, "s": 1479, "text": "Using Enum.compareTo() method. compareTo() method compares this enum with the specified object for order." }, { "code": null, "e": 1698, "s": 1585, "text": "Using Enum.equals() method. equals() method returns true if the specified object is equal to this enum constant." }, { "code": null, "e": 1811, "s": 1698, "text": "Using Enum.equals() method. equals() method returns true if the specified object is equal to this enum constant." }, { "code": null, "e": 1931, "s": 1811, "text": "Using == operator. The == operator checks the type and makes a null-safe comparison of the same type of enum constants." }, { "code": null, "e": 2051, "s": 1931, "text": "Using == operator. The == operator checks the type and makes a null-safe comparison of the same type of enum constants." }, { "code": null, "e": 2061, "s": 2051, "text": "Live Demo" }, { "code": null, "e": 3567, "s": 2061, "text": "public class Tester {\n // enum showing topics covered under Tutorials\n enum Tutorials { \n TOPIC_1, TOPIC_2, TOPIC_3; \n } \n\n public static void main(String[] args) {\n Tutorials t1, t2, t3;\n \n t1 = Tutorials.TOPIC_1; \n t2 = Tutorials.TOPIC_2; \n t3 = Tutorials.TOPIC_3; \n\n //Comparing using compareTo() method\n if(t1.compareTo(t2) > 0) {\n System.out.println(t2 + \" completed before \" + t1); \n }\n\n if(t1.compareTo(t2) < 0) {\n System.out.println(t1 + \" completed before \" + t2); \n }\n\n if(t1.compareTo(t2) == 0) { \n System.out.println(t1 + \" completed with \" + t2); \n }\n\n //Comparing using == \n //In this case t1 can be null as well causing no issue\n if(t1 == Tutorials.TOPIC_1) {\n System.out.println(\"t1 = TOPIC_1\");\n }else {\n System.out.println(\"t1 != TOPIC_1\");\n }\n\n //Comparing using equals() method\n //In this case t2 cannot be null. It will cause\n //null pointer exception\n if(t2.equals(Tutorials.TOPIC_2)) {\n System.out.println(\"t2 = TOPIC_2\");\n }else {\n System.out.println(\"t2 != TOPIC_2\");\n }\n\n Tutorials t4 = null; \n //Comparing using equals() method\n //in null safe manner\n if(Tutorials.TOPIC_3.equals(t4)) {\n System.out.println(\"t4 = TOPIC_3\");\n }else {\n System.out.println(\"t4 != TOPIC_3\");\n } \n }\n}" }, { "code": null, "e": 3640, "s": 3567, "text": "TOPIC_1 completed before TOPIC_2\nt1 = TOPIC_1\nt2 = TOPIC_2\nt4 != TOPIC_3" } ]
Introduction to Data Pipelines with Singer.io | by Pavneet Singh | Towards Data Science
Data pipelines play a crucial role in all kinds of data platforms, be it for Predictive Analytics or Business Intelligence or maybe just for ETL (Extract — Transport — Load) between various heterogeneous data stores. They all rely on real time or batch ingestion of data which is further processed to derive insights and make predictions or to just summarize and reshape the data for reports. Let’s explore the anatomy of a data pipeline to get a better understanding of the concept and then we’ll get onto creating a data pipeline using an open source ETL tool known as Singer in Python. Just as a water pipeline moves water from a source to a destination, in the same way we use data pipelines to move data from one source system to a destination system. Few scenarios in which data pipelines are used: 1) Synchronizing data between heterogeneous data stores. For example, synchronizing data from an Oracle Database instance to a PostgreSQL database instance. 2) Moving data from staging area to production systems after data cleaning, reshaping, summarizing etc. For example, data scraped from various websites may be collected in a staging area which is then made fit for consumption in a structured manner and then transferred to a database. 3) Distribute segmented data across various sub-systems from a central data source. For example: Survey data for various products collected in Google Sheets by an organization may then be divided and broadcasted to the respective product teams for processing. 1) Data frequency: The speed at which the destination systems require the data i.e. at regular intervals in small batches or real time. The pipeline should be capable enough to maintain the frequency of data transfer required by the destination system. 2) Resiliency: How fault tolerant and resilient is the data pipeline i.e. in case the pipeline crashes due to a sudden data load or an overlooked code bug , there should be no loss of data. 3) Scalability: The tools and technology utilized in developing the data pipeline must possess the capability of re-configuring it to scale out onto more hardware nodes if the data load increases. The core aim of the Singer is to be “The open-source standard for writing scripts that move data”. It involves the use of standardized scripts for data extraction and ingestion which can be mixed and matched with various sources/targets as per the requirement. 1) Tap — The data source from which data will be extracted is called as a Tap and there are ready-made Taps available on the Singer site which can be used as it is, or custom taps can also be created. 2) Targets — The data target which pulls in the data from the Tap is known as Target. Same as Taps, we can use ready-made Targets from the Singer website or create our own. 3) Data exchange format — In singer JSON (JavaScript Object Notation) format is used as the data exchange format making it source/target agnostic. 4) The Taps and targets are easily clubbed with the Unix based pipe operator without the need for any daemons or complicated plugins. 5) It supports incremental extraction by maintaining the state between invocations i.e. a timestamp can be stored in a JSON file between invocations to record the last instance at which the target had consumed data. We can create custom Taps/Sinks for Singer as per our requirement or just install and use the ones which are already available on the Singer website. Let’s create a data pipeline to fetch employee records from a REST API and insert them into a PostgreSQL database table using the tap and sink methodology of Singer. Prerequisites: A Python environment and a PostgreSQL Database instance. Since Singer.io requires setting up a tap and sink, we’ll be creating separate virtualenvs for both to avoid version conflicts as each of them might have dependencies on different libraries. This is considered as a best practice when working with Singer. In this demo we will create our own Tap to fetch the employee records from the REST API. 1) Create and activate the virtualenv python3 -m venv ~/.virtualenvs/Singer.io_rest_tapsource ~/.virtualenvs/Singer.io_rest_tap/bin/activate 2) Install the Singer python library pip install singer-python 3) Open up a new file called tap_emp_api.py in your favorite editor and add the following code import singerimport urllib.requestimport json#Here is a dummy JSON Schema for the sample data passed by our REST API.schema = {‘properties’: {‘id’: {‘type’: ‘string’},‘employee_name’: {‘type’: ‘string’},‘employee_salary’: {‘type’: ‘string’},‘employee_age’: {‘type’: ‘string’},‘profile_image’: {‘type’: ‘string’}}}#Here we make the HTTP request and parse the responsewith urllib.request.urlopen(‘http://dummy.restapiexample.com/api/v1/employees') as response:emp_data = json.loads(response.read().decode(‘utf-8’))#next we call singer.write_schema which writes the schema of the employees streamsinger.write_schema(‘employees’, schema, ‘id’)#then we call singer.write_records to write the records to that streamsinger.write_records(‘employees’, records=emp_data[“data”]) A Target for PostgreSQL is already available on the Singer website so we will set up a virtualenv for installing it. 1) Create and activate the virtualenv python3 -m venv ~/.virtualenvs/Singer.io_postgres_targetsource ~/.virtualenvs/Singer.io_ postgres_target /bin/activate 2) Install the Singer python library pip install singer-target-postgres 3) Next we need to create a config file at ~/.virtualenvs/Singer.io_postgres_target/bin/target_postgres_config.json with postgres connection information and target postgres schema like this: {“postgres_host”: “localhost”,“postgres_port”: 5432,“postgres_database”: “singer_demo”,“postgres_username”: “postgres”,“postgres_password”: “postgres”,“postgres_schema”: “public”} Once we’ve set up the Tap and the Target, the pipeline can be used by simply clubbing the Tap and Target separated by a pipe operator in the shell i.e. python ~/.virtualenvs/Singer.io_rest_tap/bin/tap_emp_api.py | ~/.virtualenvs/Singer.io_postgres_target/bin/target-postgres — config database_config.json There you go! All the records fetched from the API will get inserted into a table as per the database_config file and schema we made for the Tap. Easy peasy wasn’t it?! Explore the Singer.io documentation and try out various Tap/Target combinations as per your use case or create your own Taps and Targets. You can also explore data pipeline orchestration tools like Airflow and Luigi which have got a wide range of features as well. I’ll be coming up with some interesting guides related to Airflow in my upcoming posts. Until then.. stay happy plumbing your Data Pipelines!
[ { "code": null, "e": 761, "s": 172, "text": "Data pipelines play a crucial role in all kinds of data platforms, be it for Predictive Analytics or Business Intelligence or maybe just for ETL (Extract — Transport — Load) between various heterogeneous data stores. They all rely on real time or batch ingestion of data which is further processed to derive insights and make predictions or to just summarize and reshape the data for reports. Let’s explore the anatomy of a data pipeline to get a better understanding of the concept and then we’ll get onto creating a data pipeline using an open source ETL tool known as Singer in Python." }, { "code": null, "e": 977, "s": 761, "text": "Just as a water pipeline moves water from a source to a destination, in the same way we use data pipelines to move data from one source system to a destination system. Few scenarios in which data pipelines are used:" }, { "code": null, "e": 1134, "s": 977, "text": "1) Synchronizing data between heterogeneous data stores. For example, synchronizing data from an Oracle Database instance to a PostgreSQL database instance." }, { "code": null, "e": 1419, "s": 1134, "text": "2) Moving data from staging area to production systems after data cleaning, reshaping, summarizing etc. For example, data scraped from various websites may be collected in a staging area which is then made fit for consumption in a structured manner and then transferred to a database." }, { "code": null, "e": 1679, "s": 1419, "text": "3) Distribute segmented data across various sub-systems from a central data source. For example: Survey data for various products collected in Google Sheets by an organization may then be divided and broadcasted to the respective product teams for processing." }, { "code": null, "e": 1932, "s": 1679, "text": "1) Data frequency: The speed at which the destination systems require the data i.e. at regular intervals in small batches or real time. The pipeline should be capable enough to maintain the frequency of data transfer required by the destination system." }, { "code": null, "e": 2122, "s": 1932, "text": "2) Resiliency: How fault tolerant and resilient is the data pipeline i.e. in case the pipeline crashes due to a sudden data load or an overlooked code bug , there should be no loss of data." }, { "code": null, "e": 2319, "s": 2122, "text": "3) Scalability: The tools and technology utilized in developing the data pipeline must possess the capability of re-configuring it to scale out onto more hardware nodes if the data load increases." }, { "code": null, "e": 2580, "s": 2319, "text": "The core aim of the Singer is to be “The open-source standard for writing scripts that move data”. It involves the use of standardized scripts for data extraction and ingestion which can be mixed and matched with various sources/targets as per the requirement." }, { "code": null, "e": 2781, "s": 2580, "text": "1) Tap — The data source from which data will be extracted is called as a Tap and there are ready-made Taps available on the Singer site which can be used as it is, or custom taps can also be created." }, { "code": null, "e": 2954, "s": 2781, "text": "2) Targets — The data target which pulls in the data from the Tap is known as Target. Same as Taps, we can use ready-made Targets from the Singer website or create our own." }, { "code": null, "e": 3101, "s": 2954, "text": "3) Data exchange format — In singer JSON (JavaScript Object Notation) format is used as the data exchange format making it source/target agnostic." }, { "code": null, "e": 3235, "s": 3101, "text": "4) The Taps and targets are easily clubbed with the Unix based pipe operator without the need for any daemons or complicated plugins." }, { "code": null, "e": 3451, "s": 3235, "text": "5) It supports incremental extraction by maintaining the state between invocations i.e. a timestamp can be stored in a JSON file between invocations to record the last instance at which the target had consumed data." }, { "code": null, "e": 3601, "s": 3451, "text": "We can create custom Taps/Sinks for Singer as per our requirement or just install and use the ones which are already available on the Singer website." }, { "code": null, "e": 3767, "s": 3601, "text": "Let’s create a data pipeline to fetch employee records from a REST API and insert them into a PostgreSQL database table using the tap and sink methodology of Singer." }, { "code": null, "e": 3839, "s": 3767, "text": "Prerequisites: A Python environment and a PostgreSQL Database instance." }, { "code": null, "e": 4094, "s": 3839, "text": "Since Singer.io requires setting up a tap and sink, we’ll be creating separate virtualenvs for both to avoid version conflicts as each of them might have dependencies on different libraries. This is considered as a best practice when working with Singer." }, { "code": null, "e": 4183, "s": 4094, "text": "In this demo we will create our own Tap to fetch the employee records from the REST API." }, { "code": null, "e": 4221, "s": 4183, "text": "1) Create and activate the virtualenv" }, { "code": null, "e": 4324, "s": 4221, "text": "python3 -m venv ~/.virtualenvs/Singer.io_rest_tapsource ~/.virtualenvs/Singer.io_rest_tap/bin/activate" }, { "code": null, "e": 4361, "s": 4324, "text": "2) Install the Singer python library" }, { "code": null, "e": 4387, "s": 4361, "text": "pip install singer-python" }, { "code": null, "e": 4482, "s": 4387, "text": "3) Open up a new file called tap_emp_api.py in your favorite editor and add the following code" }, { "code": null, "e": 5251, "s": 4482, "text": "import singerimport urllib.requestimport json#Here is a dummy JSON Schema for the sample data passed by our REST API.schema = {‘properties’: {‘id’: {‘type’: ‘string’},‘employee_name’: {‘type’: ‘string’},‘employee_salary’: {‘type’: ‘string’},‘employee_age’: {‘type’: ‘string’},‘profile_image’: {‘type’: ‘string’}}}#Here we make the HTTP request and parse the responsewith urllib.request.urlopen(‘http://dummy.restapiexample.com/api/v1/employees') as response:emp_data = json.loads(response.read().decode(‘utf-8’))#next we call singer.write_schema which writes the schema of the employees streamsinger.write_schema(‘employees’, schema, ‘id’)#then we call singer.write_records to write the records to that streamsinger.write_records(‘employees’, records=emp_data[“data”])" }, { "code": null, "e": 5368, "s": 5251, "text": "A Target for PostgreSQL is already available on the Singer website so we will set up a virtualenv for installing it." }, { "code": null, "e": 5406, "s": 5368, "text": "1) Create and activate the virtualenv" }, { "code": null, "e": 5525, "s": 5406, "text": "python3 -m venv ~/.virtualenvs/Singer.io_postgres_targetsource ~/.virtualenvs/Singer.io_ postgres_target /bin/activate" }, { "code": null, "e": 5562, "s": 5525, "text": "2) Install the Singer python library" }, { "code": null, "e": 5597, "s": 5562, "text": "pip install singer-target-postgres" }, { "code": null, "e": 5640, "s": 5597, "text": "3) Next we need to create a config file at" }, { "code": null, "e": 5713, "s": 5640, "text": "~/.virtualenvs/Singer.io_postgres_target/bin/target_postgres_config.json" }, { "code": null, "e": 5788, "s": 5713, "text": "with postgres connection information and target postgres schema like this:" }, { "code": null, "e": 5968, "s": 5788, "text": "{“postgres_host”: “localhost”,“postgres_port”: 5432,“postgres_database”: “singer_demo”,“postgres_username”: “postgres”,“postgres_password”: “postgres”,“postgres_schema”: “public”}" }, { "code": null, "e": 6120, "s": 5968, "text": "Once we’ve set up the Tap and the Target, the pipeline can be used by simply clubbing the Tap and Target separated by a pipe operator in the shell i.e." }, { "code": null, "e": 6273, "s": 6120, "text": "python ~/.virtualenvs/Singer.io_rest_tap/bin/tap_emp_api.py | ~/.virtualenvs/Singer.io_postgres_target/bin/target-postgres — config database_config.json" }, { "code": null, "e": 6442, "s": 6273, "text": "There you go! All the records fetched from the API will get inserted into a table as per the database_config file and schema we made for the Tap. Easy peasy wasn’t it?!" }, { "code": null, "e": 6580, "s": 6442, "text": "Explore the Singer.io documentation and try out various Tap/Target combinations as per your use case or create your own Taps and Targets." }, { "code": null, "e": 6707, "s": 6580, "text": "You can also explore data pipeline orchestration tools like Airflow and Luigi which have got a wide range of features as well." } ]
Introduction to YACC - GeeksforGeeks
29 Apr, 2021 A parser generator is a program that takes as input a specification of a syntax, and produces as output a procedure for recognizing that language. Historically, they are also called compiler-compilers.YACC (yet another compiler-compiler) is an LALR(1) (LookAhead, Left-to-right, Rightmost derivation producer with 1 lookahead token) parser generator. YACC was originally designed for being complemented by Lex.Input File: YACC input file is divided into three parts. /* definitions */ .... %% /* rules */ .... %% /* auxiliary routines */ .... Input File: Definition Part: The definition part includes information about the tokens used in the syntax definition: %token NUMBER %token ID Yacc automatically assigns numbers for tokens, but it can be overridden by %token NUMBER 621 Yacc also recognizes single characters as tokens. Therefore, assigned token numbers should not overlap ASCII codes. The definition part can include C code external to the definition of the parser and variable declarations, within %{ and %} in the first column. It can also include the specification of the starting symbol in the grammar: %start nonterminal Input File: Rule Part: The rules part contains grammar definition in a modified BNF form. Actions is C code in { } and can be embedded inside (Translation schemes). Input File: Auxiliary Routines Part: The auxiliary routines part is only C code. It includes function definitions for every function needed in rules part. It can also contain the main() function definition if the parser is going to be run as a program. The main() function must call the function yyparse(). Input File: If yylex() is not defined in the auxiliary routines sections, then it should be included: #include "lex.yy.c" YACC input file generally finishes with: .y Output Files: The output of YACC is a file named y.tab.c If it contains the main() definition, it must be compiled to be executable. Otherwise, the code can be an external function definition for the function int yyparse() If called with the –d option in the command line, Yacc produces as output a header file y.tab.h with all its specific definition (particularly important are token definitions to be included, for example, in a Lex input file). If called with the –v option, Yacc produces as output a file y.output containing a textual description of the LALR(1) parsing table used by the parser. This is useful for tracking down how the parser solves conflicts. Example: Yacc File (.y) C %{ #include <ctype.h> #include <stdio.h> #define YYSTYPE double /* double type for yacc stack */%} %% Lines : Lines S '\n' { printf("OK \n"); } | S '\n’ | error '\n' {yyerror("Error: reenter last line:"); yyerrok; }; S : '(' S ')’ | '[' S ']’ | /* empty */ ;%% #include "lex.yy.c" void yyerror(char * s)/* yacc error handler */{ fprintf (stderr, "%s\n", s);} int main(void) { return yyparse(); } Lex File (.l) C %{%} %%[ \t] { /* skip blanks and tabs */ }\n|. { return yytext[0]; }%% For Compiling YACC Program: Write lex program in a file file.l and yacc in a file file.y Open Terminal and Navigate to the Directory where you have saved the files. type lex file.l type yacc file.y type cc lex.yy.c y.tab.h -ll type ./a.out Write lex program in a file file.l and yacc in a file file.y Open Terminal and Navigate to the Directory where you have saved the files. type lex file.l type yacc file.y type cc lex.yy.c y.tab.h -ll type ./a.out nani_99 Lex program Compiler Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Symbol Table in Compiler Code Optimization in Compiler Design Directed Acyclic graph in Compiler Design (with examples) Intermediate Code Generation in Compiler Design Introduction of Compiler Design Syntax Directed Translation in Compiler Design Types of Parsers in Compiler Design Ambiguous Grammar Difference between Compiler and Interpreter Peephole Optimization in Compiler Design
[ { "code": null, "e": 26063, "s": 26035, "text": "\n29 Apr, 2021" }, { "code": null, "e": 26532, "s": 26063, "text": "A parser generator is a program that takes as input a specification of a syntax, and produces as output a procedure for recognizing that language. Historically, they are also called compiler-compilers.YACC (yet another compiler-compiler) is an LALR(1) (LookAhead, Left-to-right, Rightmost derivation producer with 1 lookahead token) parser generator. YACC was originally designed for being complemented by Lex.Input File: YACC input file is divided into three parts. " }, { "code": null, "e": 26615, "s": 26532, "text": "/* definitions */\n ....\n\n%% \n/* rules */ \n....\n%% \n\n/* auxiliary routines */\n.... " }, { "code": null, "e": 26645, "s": 26615, "text": "Input File: Definition Part: " }, { "code": null, "e": 26736, "s": 26645, "text": "The definition part includes information about the tokens used in the syntax definition: " }, { "code": null, "e": 26762, "s": 26736, "text": "%token NUMBER \n%token ID " }, { "code": null, "e": 26841, "s": 26764, "text": "Yacc automatically assigns numbers for tokens, but it can be overridden by " }, { "code": null, "e": 26860, "s": 26841, "text": "%token NUMBER 621 " }, { "code": null, "e": 26980, "s": 26862, "text": "Yacc also recognizes single characters as tokens. Therefore, assigned token numbers should not overlap ASCII codes. " }, { "code": null, "e": 27127, "s": 26980, "text": "The definition part can include C code external to the definition of the parser and variable declarations, within %{ and %} in the first column. " }, { "code": null, "e": 27206, "s": 27127, "text": "It can also include the specification of the starting symbol in the grammar: " }, { "code": null, "e": 27226, "s": 27206, "text": "%start nonterminal " }, { "code": null, "e": 27253, "s": 27228, "text": "Input File: Rule Part: " }, { "code": null, "e": 27322, "s": 27253, "text": "The rules part contains grammar definition in a modified BNF form. " }, { "code": null, "e": 27399, "s": 27322, "text": "Actions is C code in { } and can be embedded inside (Translation schemes). " }, { "code": null, "e": 27438, "s": 27399, "text": "Input File: Auxiliary Routines Part: " }, { "code": null, "e": 27484, "s": 27438, "text": "The auxiliary routines part is only C code. " }, { "code": null, "e": 27560, "s": 27484, "text": "It includes function definitions for every function needed in rules part. " }, { "code": null, "e": 27660, "s": 27560, "text": "It can also contain the main() function definition if the parser is going to be run as a program. " }, { "code": null, "e": 27716, "s": 27660, "text": "The main() function must call the function yyparse(). " }, { "code": null, "e": 27729, "s": 27716, "text": "Input File: " }, { "code": null, "e": 27821, "s": 27729, "text": "If yylex() is not defined in the auxiliary routines sections, then it should be included: " }, { "code": null, "e": 27843, "s": 27821, "text": "#include \"lex.yy.c\" " }, { "code": null, "e": 27888, "s": 27845, "text": "YACC input file generally finishes with: " }, { "code": null, "e": 27893, "s": 27888, "text": " .y " }, { "code": null, "e": 27911, "s": 27895, "text": "Output Files: " }, { "code": null, "e": 27956, "s": 27911, "text": "The output of YACC is a file named y.tab.c " }, { "code": null, "e": 28034, "s": 27956, "text": "If it contains the main() definition, it must be compiled to be executable. " }, { "code": null, "e": 28126, "s": 28034, "text": "Otherwise, the code can be an external function definition for the function int yyparse() " }, { "code": null, "e": 28354, "s": 28126, "text": "If called with the –d option in the command line, Yacc produces as output a header file y.tab.h with all its specific definition (particularly important are token definitions to be included, for example, in a Lex input file). " }, { "code": null, "e": 28574, "s": 28354, "text": "If called with the –v option, Yacc produces as output a file y.output containing a textual description of the LALR(1) parsing table used by the parser. This is useful for tracking down how the parser solves conflicts. " }, { "code": null, "e": 28599, "s": 28574, "text": "Example: Yacc File (.y) " }, { "code": null, "e": 28601, "s": 28599, "text": "C" }, { "code": "%{ #include <ctype.h> #include <stdio.h> #define YYSTYPE double /* double type for yacc stack */%} %% Lines : Lines S '\\n' { printf(\"OK \\n\"); } | S '\\n’ | error '\\n' {yyerror(\"Error: reenter last line:\"); yyerrok; }; S : '(' S ')’ | '[' S ']’ | /* empty */ ;%% #include \"lex.yy.c\" void yyerror(char * s)/* yacc error handler */{ fprintf (stderr, \"%s\\n\", s);} int main(void) { return yyparse(); } ", "e": 29069, "s": 28601, "text": null }, { "code": null, "e": 29084, "s": 29069, "text": "Lex File (.l) " }, { "code": null, "e": 29086, "s": 29084, "text": "C" }, { "code": "%{%} %%[ \\t] { /* skip blanks and tabs */ }\\n|. { return yytext[0]; }%%", "e": 29167, "s": 29086, "text": null }, { "code": null, "e": 29197, "s": 29167, "text": "For Compiling YACC Program: " }, { "code": null, "e": 29416, "s": 29197, "text": "Write lex program in a file file.l and yacc in a file file.y Open Terminal and Navigate to the Directory where you have saved the files. type lex file.l type yacc file.y type cc lex.yy.c y.tab.h -ll type ./a.out " }, { "code": null, "e": 29479, "s": 29416, "text": "Write lex program in a file file.l and yacc in a file file.y " }, { "code": null, "e": 29557, "s": 29479, "text": "Open Terminal and Navigate to the Directory where you have saved the files. " }, { "code": null, "e": 29575, "s": 29557, "text": "type lex file.l " }, { "code": null, "e": 29594, "s": 29575, "text": "type yacc file.y " }, { "code": null, "e": 29625, "s": 29594, "text": "type cc lex.yy.c y.tab.h -ll " }, { "code": null, "e": 29640, "s": 29625, "text": "type ./a.out " }, { "code": null, "e": 29650, "s": 29642, "text": "nani_99" }, { "code": null, "e": 29662, "s": 29650, "text": "Lex program" }, { "code": null, "e": 29678, "s": 29662, "text": "Compiler Design" }, { "code": null, "e": 29776, "s": 29678, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29801, "s": 29776, "text": "Symbol Table in Compiler" }, { "code": null, "e": 29838, "s": 29801, "text": "Code Optimization in Compiler Design" }, { "code": null, "e": 29896, "s": 29838, "text": "Directed Acyclic graph in Compiler Design (with examples)" }, { "code": null, "e": 29944, "s": 29896, "text": "Intermediate Code Generation in Compiler Design" }, { "code": null, "e": 29976, "s": 29944, "text": "Introduction of Compiler Design" }, { "code": null, "e": 30023, "s": 29976, "text": "Syntax Directed Translation in Compiler Design" }, { "code": null, "e": 30059, "s": 30023, "text": "Types of Parsers in Compiler Design" }, { "code": null, "e": 30077, "s": 30059, "text": "Ambiguous Grammar" }, { "code": null, "e": 30121, "s": 30077, "text": "Difference between Compiler and Interpreter" } ]
How to auto-resize an image to fit a div container using CSS? - GeeksforGeeks
30 Jul, 2021 To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container. object-fit property: This property is used to specify how an image or video resize and fit the container. It tells the content how to fit in a specific div container in various way such as preserve that aspect ratio or stretch up and take up as much space as possible. Example 1: This example describes the auto-resize image fit to div container. This example does not contain object-fit property.<!DOCTYPE html> <html> <head> <style> .geeks { width:60%; height:300px; } img { width:100%; height:100%; } </style> </head> <body> <div class = "geeks"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png" alt = "Geeks Image" /> </div> </body> </html> Output:In the above example as the object-fit property is not used, the image is being squeezed to fit the container, and its original aspect ratio is destroyed. <!DOCTYPE html> <html> <head> <style> .geeks { width:60%; height:300px; } img { width:100%; height:100%; } </style> </head> <body> <div class = "geeks"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png" alt = "Geeks Image" /> </div> </body> </html> Output:In the above example as the object-fit property is not used, the image is being squeezed to fit the container, and its original aspect ratio is destroyed. Example 2: This example is used to display the part of image when use resize the div container.<!DOCTYPE html> <html> <head> <style> .geeks { width:60%; height:300px; } img { width:100%; height:100%; object-fit:cover; } </style> </head> <body> <div class = "geeks"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png" alt = "Geeks Image" /> </div> </body> </html> Output:Note: Using object-fit: cover; will cut off the sides of the image, preserving the aspect ratio, and also filling in space. <!DOCTYPE html> <html> <head> <style> .geeks { width:60%; height:300px; } img { width:100%; height:100%; object-fit:cover; } </style> </head> <body> <div class = "geeks"> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png" alt = "Geeks Image" /> </div> </body> </html> Output:Note: Using object-fit: cover; will cut off the sides of the image, preserving the aspect ratio, and also filling in space. Example 3: This example displays an image without using object-fit property. In this example, the size of the image is set manually and the image will not be able to maintain it’s aspect ratio and adjust or resize according to div container on resizing the browser window.<!DOCTYPE html> <html> <head> <style> body { text-align:center; } img { width:400px; height:200px; } </style> </head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png" alt="Geeks Image"></body> </html> Output: <!DOCTYPE html> <html> <head> <style> body { text-align:center; } img { width:400px; height:200px; } </style> </head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png" alt="Geeks Image"></body> </html> Output: Example 4: This example display the part of image or image using object-fit property. In this example, the size of the image is set manually and the object-fit property is also used. In this case, on resizing the browser the image will maintain it’s aspect ratio and will not be resized according to div container.<!DOCTYPE html> <html> <head> <style> body { text-align:center; } img { width:400px; height:200px; object-fit: cover; } </style> </head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png" alt="Geeks Image"> </body> </html> Output:Note: The property object-fit: cover; will cut the sides of the image, preserving the aspect ratio, and also filling in space. <!DOCTYPE html> <html> <head> <style> body { text-align:center; } img { width:400px; height:200px; object-fit: cover; } </style> </head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png" alt="Geeks Image"> </body> </html> Output: Note: The property object-fit: cover; will cut the sides of the image, preserving the aspect ratio, and also filling in space. HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples. CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples. Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc Picked Technical Scripter 2018 CSS HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to create footer to stay at the bottom of a Web page? How to apply style to parent if it has child with CSS? How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 25949, "s": 25921, "text": "\n30 Jul, 2021" }, { "code": null, "e": 26102, "s": 25949, "text": "To auto-resize an image or a video to fit in a div container use object-fit property. It is used to specify how an image or video fits in the container." }, { "code": null, "e": 26371, "s": 26102, "text": "object-fit property: This property is used to specify how an image or video resize and fit the container. It tells the content how to fit in a specific div container in various way such as preserve that aspect ratio or stretch up and take up as much space as possible." }, { "code": null, "e": 27128, "s": 26371, "text": "Example 1: This example describes the auto-resize image fit to div container. This example does not contain object-fit property.<!DOCTYPE html> <html> <head> <style> .geeks { width:60%; height:300px; } img { width:100%; height:100%; } </style> </head> <body> <div class = \"geeks\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\" alt = \"Geeks Image\" /> </div> </body> </html> Output:In the above example as the object-fit property is not used, the image is being squeezed to fit the container, and its original aspect ratio is destroyed." }, { "code": "<!DOCTYPE html> <html> <head> <style> .geeks { width:60%; height:300px; } img { width:100%; height:100%; } </style> </head> <body> <div class = \"geeks\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\" alt = \"Geeks Image\" /> </div> </body> </html> ", "e": 27596, "s": 27128, "text": null }, { "code": null, "e": 27758, "s": 27596, "text": "Output:In the above example as the object-fit property is not used, the image is being squeezed to fit the container, and its original aspect ratio is destroyed." }, { "code": null, "e": 28488, "s": 27758, "text": "Example 2: This example is used to display the part of image when use resize the div container.<!DOCTYPE html> <html> <head> <style> .geeks { width:60%; height:300px; } img { width:100%; height:100%; object-fit:cover; } </style> </head> <body> <div class = \"geeks\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\" alt = \"Geeks Image\" /> </div> </body> </html> Output:Note: Using object-fit: cover; will cut off the sides of the image, preserving the aspect ratio, and also filling in space." }, { "code": "<!DOCTYPE html> <html> <head> <style> .geeks { width:60%; height:300px; } img { width:100%; height:100%; object-fit:cover; } </style> </head> <body> <div class = \"geeks\"> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\" alt = \"Geeks Image\" /> </div> </body> </html> ", "e": 28993, "s": 28488, "text": null }, { "code": null, "e": 29124, "s": 28993, "text": "Output:Note: Using object-fit: cover; will cut off the sides of the image, preserving the aspect ratio, and also filling in space." }, { "code": null, "e": 29741, "s": 29124, "text": "Example 3: This example displays an image without using object-fit property. In this example, the size of the image is set manually and the image will not be able to maintain it’s aspect ratio and adjust or resize according to div container on resizing the browser window.<!DOCTYPE html> <html> <head> <style> body { text-align:center; } img { width:400px; height:200px; } </style> </head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\" alt=\"Geeks Image\"></body> </html> Output:" }, { "code": "<!DOCTYPE html> <html> <head> <style> body { text-align:center; } img { width:400px; height:200px; } </style> </head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\" alt=\"Geeks Image\"></body> </html> ", "e": 30079, "s": 29741, "text": null }, { "code": null, "e": 30087, "s": 30079, "text": "Output:" }, { "code": null, "e": 30965, "s": 30087, "text": "Example 4: This example display the part of image or image using object-fit property. In this example, the size of the image is set manually and the object-fit property is also used. In this case, on resizing the browser the image will maintain it’s aspect ratio and will not be resized according to div container.<!DOCTYPE html> <html> <head> <style> body { text-align:center; } img { width:400px; height:200px; object-fit: cover; } </style> </head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\" alt=\"Geeks Image\"> </body> </html> Output:Note: The property object-fit: cover; will cut the sides of the image, preserving the aspect ratio, and also filling in space." }, { "code": "<!DOCTYPE html> <html> <head> <style> body { text-align:center; } img { width:400px; height:200px; object-fit: cover; } </style> </head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-25.png\" alt=\"Geeks Image\"> </body> </html> ", "e": 31396, "s": 30965, "text": null }, { "code": null, "e": 31404, "s": 31396, "text": "Output:" }, { "code": null, "e": 31531, "s": 31404, "text": "Note: The property object-fit: cover; will cut the sides of the image, preserving the aspect ratio, and also filling in space." }, { "code": null, "e": 31725, "s": 31531, "text": "HTML is the foundation of webpages, is used for webpage development by structuring websites and web apps.You can learn HTML from the ground up by following this HTML Tutorial and HTML Examples." }, { "code": null, "e": 31911, "s": 31725, "text": "CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples." }, { "code": null, "e": 32048, "s": 31911, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 32057, "s": 32048, "text": "CSS-Misc" }, { "code": null, "e": 32064, "s": 32057, "text": "Picked" }, { "code": null, "e": 32088, "s": 32064, "text": "Technical Scripter 2018" }, { "code": null, "e": 32092, "s": 32088, "text": "CSS" }, { "code": null, "e": 32097, "s": 32092, "text": "HTML" }, { "code": null, "e": 32116, "s": 32097, "text": "Technical Scripter" }, { "code": null, "e": 32133, "s": 32116, "text": "Web Technologies" }, { "code": null, "e": 32138, "s": 32133, "text": "HTML" }, { "code": null, "e": 32236, "s": 32138, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32286, "s": 32236, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32348, "s": 32286, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32396, "s": 32348, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32454, "s": 32396, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 32509, "s": 32454, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 32559, "s": 32509, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32621, "s": 32559, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32669, "s": 32621, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32729, "s": 32669, "text": "How to set the default value for an HTML <select> element ?" } ]
HTML | <input> accept Attribute - GeeksforGeeks
02 Dec, 2021 The HTML <input> accept Attribute is used to specifies the type of file that the server accepts. This attribute can be used with <input type=”file”> element only. This attribute is not used for validation tool because file uploads should be validated on the Server.Syntax: <input accept = "file_extension | audio/* | video/* | image/* | media_type"> Attribute Values file_extension: It Specify the file extension(s) like .gif, .jpg, .png, .doc) the user can pick from. audio/*: The user can pick all sound files. video/*: The user can pick all video files. image/*: :A valid media type, with no parameters. Look at IANA Media Types for a complete list standard media types media_type: A valid media type without parameters. Example: html <!DOCTYPE html><html> <head> <title> HTML input accept attribute </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2> HTML <input> accept attribute </h2> <form action=" "> <input type="file" name="picture" accept="image/*"> <input type="submit"> </form></body> </html> Output: Supported Browsers: The browsers supported by HTML <input> accept Attribute are listed below: Google Chrome 8.0 Internet Explorer 10.0 Firefox 4.0 Apple Safari 6.0 Opera 15.0 Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. varshagumber28 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 31646, "s": 31618, "text": "\n02 Dec, 2021" }, { "code": null, "e": 31921, "s": 31646, "text": "The HTML <input> accept Attribute is used to specifies the type of file that the server accepts. This attribute can be used with <input type=”file”> element only. This attribute is not used for validation tool because file uploads should be validated on the Server.Syntax: " }, { "code": null, "e": 31998, "s": 31921, "text": "<input accept = \"file_extension | audio/* | video/* | image/* | media_type\">" }, { "code": null, "e": 32017, "s": 31998, "text": "Attribute Values " }, { "code": null, "e": 32119, "s": 32017, "text": "file_extension: It Specify the file extension(s) like .gif, .jpg, .png, .doc) the user can pick from." }, { "code": null, "e": 32163, "s": 32119, "text": "audio/*: The user can pick all sound files." }, { "code": null, "e": 32207, "s": 32163, "text": "video/*: The user can pick all video files." }, { "code": null, "e": 32323, "s": 32207, "text": "image/*: :A valid media type, with no parameters. Look at IANA Media Types for a complete list standard media types" }, { "code": null, "e": 32374, "s": 32323, "text": "media_type: A valid media type without parameters." }, { "code": null, "e": 32384, "s": 32374, "text": "Example: " }, { "code": null, "e": 32389, "s": 32384, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML input accept attribute </title> <style> body { text-align: center; } h1 { color: green; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2> HTML <input> accept attribute </h2> <form action=\" \"> <input type=\"file\" name=\"picture\" accept=\"image/*\"> <input type=\"submit\"> </form></body> </html>", "e": 32864, "s": 32389, "text": null }, { "code": null, "e": 32873, "s": 32864, "text": "Output: " }, { "code": null, "e": 32968, "s": 32873, "text": "Supported Browsers: The browsers supported by HTML <input> accept Attribute are listed below: " }, { "code": null, "e": 32986, "s": 32968, "text": "Google Chrome 8.0" }, { "code": null, "e": 33009, "s": 32986, "text": "Internet Explorer 10.0" }, { "code": null, "e": 33021, "s": 33009, "text": "Firefox 4.0" }, { "code": null, "e": 33038, "s": 33021, "text": "Apple Safari 6.0" }, { "code": null, "e": 33049, "s": 33038, "text": "Opera 15.0" }, { "code": null, "e": 33186, "s": 33049, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 33201, "s": 33186, "text": "varshagumber28" }, { "code": null, "e": 33217, "s": 33201, "text": "HTML-Attributes" }, { "code": null, "e": 33222, "s": 33217, "text": "HTML" }, { "code": null, "e": 33239, "s": 33222, "text": "Web Technologies" }, { "code": null, "e": 33244, "s": 33239, "text": "HTML" }, { "code": null, "e": 33342, "s": 33244, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33392, "s": 33342, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33454, "s": 33392, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33502, "s": 33454, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 33562, "s": 33502, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33615, "s": 33562, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 33655, "s": 33615, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33688, "s": 33655, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33733, "s": 33688, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33776, "s": 33733, "text": "How to fetch data from an API in ReactJS ?" } ]
Filter PySpark DataFrame Columns with None or Null Values - GeeksforGeeks
09 May, 2021 Many times while working on PySpark SQL dataframe, the dataframes contains many NULL/None values in columns, in many of the cases before performing any of the operations of the dataframe firstly we have to handle the NULL/None values in order to get the desired result or output, we have to filter those NULL values from the dataframe. In this article are going to learn how to filter the PySpark dataframe column with NULL/None values. For filtering the NULL/None values we have the function in PySpark API know as a filter() and with this function, we are using isNotNull() function. Syntax: df.filter(condition) : This function returns the new dataframe with the values which satisfies the given condition. df.column_name.isNotNull() : This function is used to filter the rows that are not NULL/None in the dataframe column. Example 1: Filtering PySpark dataframe column with None value In the below code we have created the Spark Session, and then we have created the Dataframe which contains some None values in every column. Now, we have filtered the None values present in the Name column using filter() in which we have passed the condition df.Name.isNotNull() to filter the None values of Name column. Python # importing necessary librariesfrom pyspark.sql import SparkSession # function to create SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Filter_values.com") \ .getOrCreate() return spk # function to create dataframedef create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [("Shivansh", "Data Scientist", "Noida"), (None, "Software Developer", None), ("Swati", "Data Analyst", "Hyderabad"), (None, None, "Noida"), ("Arpit", "Android Developer", "Banglore"), (None, None, None)] schema = ["Name", "Job Profile", "City"] # calling function to create dataframe df = create_df(spark, input_data, schema) # filtering the columns with None values df = df.filter(df.Name.isNotNull()) # visulizing the dataframe df.show() Output: Original Dataframe Dataframe after filtering NULL/None values Example 2: Filtering PySpark dataframe column with NULL/None values using filter() function In the below code we have created the Spark Session, and then we have created the Dataframe which contains some None values in every column. Now, we have filtered the None values present in the City column using filter() in which we have passed the condition in English language form i.e, “City is Not Null” This is the condition to filter the None values of the City column. Note: The condition must be in double-quotes. Python # importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Filter_values.com") \ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [("Shivansh", "Data Scientist", "Noida"), (None, "Software Developer", None), ("Swati", "Data Analyst", "Hyderabad"), (None, None, "Noida"), ("Arpit", "Android Developer", "Banglore"), (None, None, None)] schema = ["Name", "Job Profile", "City"] # calling function to create dataframe df = create_df(spark, input_data, schema) # filtering the columns with None values df = df.filter("City is Not NULL") # visulizing the dataframe df.show() Output: Original Dataframe After filtering NULL/None values from the city column Example 3: Filter columns with None values using filter() when column name has space In the below code, we have created the Spark Session, and then we have created the Dataframe which contains some None values in every column. We have filtered the None values present in the ‘Job Profile’ column using filter() function in which we have passed the condition df[“Job Profile”].isNotNull() to filter the None values of the Job Profile column. Note: For accessing the column name which has space between the words, is accessed by using square brackets [] means with reference to the dataframe we have to give the name using square brackets. Python # importing necessary librariesfrom pyspark.sql import SparkSession # function to create SparkSessiondef create_session(): spk = SparkSession.builder \ .master("local") \ .appName("Filter_values.com") \ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == "__main__": # calling function to create SparkSession spark = create_session() input_data = [("Shivansh", "Data Scientist", "Noida"), (None, "Software Developer", None), ("Swati", "Data Analyst", "Hyderabad"), (None, None, "Noida"), ("Arpit", "Android Developer", "Banglore"), (None, None, None)] schema = ["Name", "Job Profile", "City"] # calling function to create dataframe df = create_df(spark, input_data, schema) # filtering the Job Profile with None values df = df.filter(df["Job Profile"].isNotNull()) # visulizing the dataframe df.show() Output: Original Dataframe After filtering NULL/None values from the Job Profile column Picked Python-Pyspark Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 26207, "s": 26179, "text": "\n09 May, 2021" }, { "code": null, "e": 26543, "s": 26207, "text": "Many times while working on PySpark SQL dataframe, the dataframes contains many NULL/None values in columns, in many of the cases before performing any of the operations of the dataframe firstly we have to handle the NULL/None values in order to get the desired result or output, we have to filter those NULL values from the dataframe." }, { "code": null, "e": 26644, "s": 26543, "text": "In this article are going to learn how to filter the PySpark dataframe column with NULL/None values." }, { "code": null, "e": 26793, "s": 26644, "text": "For filtering the NULL/None values we have the function in PySpark API know as a filter() and with this function, we are using isNotNull() function." }, { "code": null, "e": 26802, "s": 26793, "text": "Syntax: " }, { "code": null, "e": 26918, "s": 26802, "text": "df.filter(condition) : This function returns the new dataframe with the values which satisfies the given condition." }, { "code": null, "e": 27036, "s": 26918, "text": "df.column_name.isNotNull() : This function is used to filter the rows that are not NULL/None in the dataframe column." }, { "code": null, "e": 27098, "s": 27036, "text": "Example 1: Filtering PySpark dataframe column with None value" }, { "code": null, "e": 27419, "s": 27098, "text": "In the below code we have created the Spark Session, and then we have created the Dataframe which contains some None values in every column. Now, we have filtered the None values present in the Name column using filter() in which we have passed the condition df.Name.isNotNull() to filter the None values of Name column." }, { "code": null, "e": 27426, "s": 27419, "text": "Python" }, { "code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Filter_values.com\") \\ .getOrCreate() return spk # function to create dataframedef create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(\"Shivansh\", \"Data Scientist\", \"Noida\"), (None, \"Software Developer\", None), (\"Swati\", \"Data Analyst\", \"Hyderabad\"), (None, None, \"Noida\"), (\"Arpit\", \"Android Developer\", \"Banglore\"), (None, None, None)] schema = [\"Name\", \"Job Profile\", \"City\"] # calling function to create dataframe df = create_df(spark, input_data, schema) # filtering the columns with None values df = df.filter(df.Name.isNotNull()) # visulizing the dataframe df.show()", "e": 28491, "s": 27426, "text": null }, { "code": null, "e": 28499, "s": 28491, "text": "Output:" }, { "code": null, "e": 28518, "s": 28499, "text": "Original Dataframe" }, { "code": null, "e": 28561, "s": 28518, "text": "Dataframe after filtering NULL/None values" }, { "code": null, "e": 28653, "s": 28561, "text": "Example 2: Filtering PySpark dataframe column with NULL/None values using filter() function" }, { "code": null, "e": 29029, "s": 28653, "text": "In the below code we have created the Spark Session, and then we have created the Dataframe which contains some None values in every column. Now, we have filtered the None values present in the City column using filter() in which we have passed the condition in English language form i.e, “City is Not Null” This is the condition to filter the None values of the City column." }, { "code": null, "e": 29075, "s": 29029, "text": "Note: The condition must be in double-quotes." }, { "code": null, "e": 29082, "s": 29075, "text": "Python" }, { "code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create new SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Filter_values.com\") \\ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(\"Shivansh\", \"Data Scientist\", \"Noida\"), (None, \"Software Developer\", None), (\"Swati\", \"Data Analyst\", \"Hyderabad\"), (None, None, \"Noida\"), (\"Arpit\", \"Android Developer\", \"Banglore\"), (None, None, None)] schema = [\"Name\", \"Job Profile\", \"City\"] # calling function to create dataframe df = create_df(spark, input_data, schema) # filtering the columns with None values df = df.filter(\"City is Not NULL\") # visulizing the dataframe df.show()", "e": 30122, "s": 29082, "text": null }, { "code": null, "e": 30130, "s": 30122, "text": "Output:" }, { "code": null, "e": 30149, "s": 30130, "text": "Original Dataframe" }, { "code": null, "e": 30203, "s": 30149, "text": "After filtering NULL/None values from the city column" }, { "code": null, "e": 30288, "s": 30203, "text": "Example 3: Filter columns with None values using filter() when column name has space" }, { "code": null, "e": 30644, "s": 30288, "text": "In the below code, we have created the Spark Session, and then we have created the Dataframe which contains some None values in every column. We have filtered the None values present in the ‘Job Profile’ column using filter() function in which we have passed the condition df[“Job Profile”].isNotNull() to filter the None values of the Job Profile column." }, { "code": null, "e": 30841, "s": 30644, "text": "Note: For accessing the column name which has space between the words, is accessed by using square brackets [] means with reference to the dataframe we have to give the name using square brackets." }, { "code": null, "e": 30848, "s": 30841, "text": "Python" }, { "code": "# importing necessary librariesfrom pyspark.sql import SparkSession # function to create SparkSessiondef create_session(): spk = SparkSession.builder \\ .master(\"local\") \\ .appName(\"Filter_values.com\") \\ .getOrCreate() return spk def create_df(spark, data, schema): df1 = spark.createDataFrame(data, schema) return df1 if __name__ == \"__main__\": # calling function to create SparkSession spark = create_session() input_data = [(\"Shivansh\", \"Data Scientist\", \"Noida\"), (None, \"Software Developer\", None), (\"Swati\", \"Data Analyst\", \"Hyderabad\"), (None, None, \"Noida\"), (\"Arpit\", \"Android Developer\", \"Banglore\"), (None, None, None)] schema = [\"Name\", \"Job Profile\", \"City\"] # calling function to create dataframe df = create_df(spark, input_data, schema) # filtering the Job Profile with None values df = df.filter(df[\"Job Profile\"].isNotNull()) # visulizing the dataframe df.show()", "e": 31899, "s": 30848, "text": null }, { "code": null, "e": 31907, "s": 31899, "text": "Output:" }, { "code": null, "e": 31926, "s": 31907, "text": "Original Dataframe" }, { "code": null, "e": 31987, "s": 31926, "text": "After filtering NULL/None values from the Job Profile column" }, { "code": null, "e": 31994, "s": 31987, "text": "Picked" }, { "code": null, "e": 32009, "s": 31994, "text": "Python-Pyspark" }, { "code": null, "e": 32016, "s": 32009, "text": "Python" }, { "code": null, "e": 32114, "s": 32016, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32132, "s": 32114, "text": "Python Dictionary" }, { "code": null, "e": 32164, "s": 32132, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 32186, "s": 32164, "text": "Enumerate() in Python" }, { "code": null, "e": 32228, "s": 32186, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 32257, "s": 32228, "text": "*args and **kwargs in Python" }, { "code": null, "e": 32301, "s": 32257, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 32338, "s": 32301, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 32374, "s": 32338, "text": "Convert integer to string in Python" }, { "code": null, "e": 32416, "s": 32374, "text": "Check if element exists in list in Python" } ]
Python Program to implement Full Subtractor - GeeksforGeeks
21 Nov, 2021 Prerequisite –Full Subtractor in Digital Logic In this, we will discuss the overview of the full subtractor and will implement the full subtractor logic in the python language. Also, we will cover with the help of examples. Let’s discuss it one by one. Given three inputs of Full Subtractor A, B, Bin. The task is to implement the Full Subtractor circuit and Print output i.e Difference (d) and B-Out of three inputs. Full Subtractor : The full Subtractor is a combinational circuit that is used to perform subtraction of three input bits: the minuend, subtrahend, and borrow in. The full Subtractor generates two output bits: the difference and borrow out. Logical Expression : Difference = (A XOR B) XOR Bin Borrow Out = Ā Bin + Ā B + B Bin Truth Table : Examples : Input : 0 1 1 Output : Difference=0, B-Out=1 Explanation : According to logical expression Difference= (A XOR B) XOR Bin i.e (0 XOR 1) XOR 1 =0 , B-Out=Ā Bin + Ā B + B Bin i.e 1 AND 1 + 1 AND 1 + 1 AND 1 = 1 Input : 1 0 0 Output : Difference=1, B-Out=0 Approach : We take three inputs A, B, and Bin. Applying (A XOR B) XOR Bin gives the Value of Difference. Applying Ā Bin + Ā B + B Bin gives the value of B-Out. Below is the implementation : Python3 # python program to implement full Subtractor# Function to print Difference and B-Out def getResult(A, B, Bin): # Calculating value of Difference Difference = (A ^ B) ^ Bin # calculating NOT value of a A1 = not(A) # Calculating value of B-Out B_Out = A1 & Bin | A1 & B | B & Bin # printing the values print("Difference = ", Difference) print("B-Out = ", B_Out) # Driver codeA = 0B = 1Bin = 1# passing three inputs of fullsubtractor as arguments to get result functiongetResult(A, B, Bin) Output : Difference = 0 B-Out = 1 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. simranarora5sos adnanirshad158 Technical Scripter 2020 Digital Electronics & Logic Design Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Shift Registers in Digital Logic Difference between Unipolar, Polar and Bipolar Line Coding Schemes Flip-flop types, their Conversion and Applications Counters in Digital Logic Introduction to memory and memory units Master-Slave JK Flip Flop Difference between Half adder and full adder Difference between combinational and sequential circuit Design 101 sequence detector (Mealy machine) Analog to Digital Conversion
[ { "code": null, "e": 25279, "s": 25251, "text": "\n21 Nov, 2021" }, { "code": null, "e": 25326, "s": 25279, "text": "Prerequisite –Full Subtractor in Digital Logic" }, { "code": null, "e": 25532, "s": 25326, "text": "In this, we will discuss the overview of the full subtractor and will implement the full subtractor logic in the python language. Also, we will cover with the help of examples. Let’s discuss it one by one." }, { "code": null, "e": 25697, "s": 25532, "text": "Given three inputs of Full Subtractor A, B, Bin. The task is to implement the Full Subtractor circuit and Print output i.e Difference (d) and B-Out of three inputs." }, { "code": null, "e": 25715, "s": 25697, "text": "Full Subtractor :" }, { "code": null, "e": 25937, "s": 25715, "text": "The full Subtractor is a combinational circuit that is used to perform subtraction of three input bits: the minuend, subtrahend, and borrow in. The full Subtractor generates two output bits: the difference and borrow out." }, { "code": null, "e": 25958, "s": 25937, "text": "Logical Expression :" }, { "code": null, "e": 26024, "s": 25958, "text": "Difference = (A XOR B) XOR Bin\nBorrow Out = Ā Bin + Ā B + B Bin" }, { "code": null, "e": 26038, "s": 26024, "text": "Truth Table :" }, { "code": null, "e": 26049, "s": 26038, "text": "Examples :" }, { "code": null, "e": 26331, "s": 26049, "text": "Input : 0 1 1\nOutput : Difference=0, B-Out=1\nExplanation : According to logical expression Difference= (A XOR B) XOR Bin i.e (0 XOR 1) XOR 1 =0 ,\nB-Out=Ā Bin + Ā B + B Bin i.e 1 AND 1 + 1 AND 1 + 1 AND 1 = 1\n\nInput : 1 0 0\nOutput : Difference=1, B-Out=0" }, { "code": null, "e": 26342, "s": 26331, "text": "Approach :" }, { "code": null, "e": 26378, "s": 26342, "text": "We take three inputs A, B, and Bin." }, { "code": null, "e": 26436, "s": 26378, "text": "Applying (A XOR B) XOR Bin gives the Value of Difference." }, { "code": null, "e": 26493, "s": 26436, "text": "Applying Ā Bin + Ā B + B Bin gives the value of B-Out." }, { "code": null, "e": 26523, "s": 26493, "text": "Below is the implementation :" }, { "code": null, "e": 26531, "s": 26523, "text": "Python3" }, { "code": "# python program to implement full Subtractor# Function to print Difference and B-Out def getResult(A, B, Bin): # Calculating value of Difference Difference = (A ^ B) ^ Bin # calculating NOT value of a A1 = not(A) # Calculating value of B-Out B_Out = A1 & Bin | A1 & B | B & Bin # printing the values print(\"Difference = \", Difference) print(\"B-Out = \", B_Out) # Driver codeA = 0B = 1Bin = 1# passing three inputs of fullsubtractor as arguments to get result functiongetResult(A, B, Bin)", "e": 27060, "s": 26531, "text": null }, { "code": null, "e": 27069, "s": 27060, "text": "Output :" }, { "code": null, "e": 27101, "s": 27069, "text": "Difference = 0\nB-Out = 1" }, { "code": null, "e": 27321, "s": 27101, "text": "Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course." }, { "code": null, "e": 27337, "s": 27321, "text": "simranarora5sos" }, { "code": null, "e": 27352, "s": 27337, "text": "adnanirshad158" }, { "code": null, "e": 27376, "s": 27352, "text": "Technical Scripter 2020" }, { "code": null, "e": 27411, "s": 27376, "text": "Digital Electronics & Logic Design" }, { "code": null, "e": 27509, "s": 27411, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27542, "s": 27509, "text": "Shift Registers in Digital Logic" }, { "code": null, "e": 27609, "s": 27542, "text": "Difference between Unipolar, Polar and Bipolar Line Coding Schemes" }, { "code": null, "e": 27660, "s": 27609, "text": "Flip-flop types, their Conversion and Applications" }, { "code": null, "e": 27686, "s": 27660, "text": "Counters in Digital Logic" }, { "code": null, "e": 27726, "s": 27686, "text": "Introduction to memory and memory units" }, { "code": null, "e": 27752, "s": 27726, "text": "Master-Slave JK Flip Flop" }, { "code": null, "e": 27797, "s": 27752, "text": "Difference between Half adder and full adder" }, { "code": null, "e": 27853, "s": 27797, "text": "Difference between combinational and sequential circuit" }, { "code": null, "e": 27898, "s": 27853, "text": "Design 101 sequence detector (Mealy machine)" } ]
Change Formatting of Numbers of ggplot2 Plot Axis in R - GeeksforGeeks
30 Jun, 2021 In this article. we will discuss how to change the formatting of numbers of the ggplot2 plot axis in R Programming Language. The ggplot() method can be used in this package in order to simulate graph customizations and induce flexibility in graph plotting. Syntax: ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) + <GEOM_FUNCTION>() The data can be binded into the scatter plot using the data attribute of the ggplot method. The mapping in the function can be induced using the aes() function to create an aesthetic mapping, by filtering the variables to be plotted on the scatter plot. We can also specify how to depict different components in the graph, for instance, the x and y axes positions, the labels to assign to these points, or characteristics such as size, shape, color, etc. This method also allows the addition of various geoms- that is the components of the graph. geom_point() is used for the creation of a scatter plot. Large numbers are labeled across the axes using scientific notation for each of the numbers. Example: R library(ggplot2)library("scales")set.seed(13482) # creating a data framedf <- data.frame(col1 = rpois(10,2)*100000, col2 = rpois(10,5)*100000 ) print ("Original DataFrame")print (df) # create a plotggplot(df, aes(col1, col2)) + geom_point() Output [1] "Original DataFrame" col1 col2 1 0e+00 8e+05 2 2e+05 3e+05 3 0e+00 7e+05 4 4e+05 7e+05 5 1e+05 3e+05 6 3e+05 7e+05 7 3e+05 6e+05 8 3e+05 6e+05 9 2e+05 6e+05 10 4e+05 4e+05 Now let us look at different ways in which numbers can be formatted. Formatting of axes labels is possible to convert the scientific notation to other formats. The scale_x_continuous() and scale_y_continuous() methods can be used to disable scientific notation and convert scientific labels to discrete form. The x and y parameters can be modified using these methods. Syntax: scale_x_continuous( name, labels) scale_y_continuous( name, labels) Parameter : name – x or y axis labels labels – labels of axis tick marks. Example: R library(ggplot2)library("scales") set.seed(13482) # creating a data framedf <- data.frame(col1 = rpois(10,2)*100000, col2 = rpois(10,5)*100000) print ("Original DataFrame")print (df) # create a plotggplot(df, aes(col1, col2)) + geom_point() + scale_x_continuous(labels = comma) + scale_y_continuous(labels = comma) Output [1] "Original DataFrame" col1 col2 1 0e+00 8e+05 2 2e+05 3e+05 3 0e+00 7e+05 4 4e+05 7e+05 5 1e+05 3e+05 6 3e+05 7e+05 7 3e+05 6e+05 8 3e+05 6e+05 9 2e+05 6e+05 10 4e+05 4e+05 The scale_x_continuous() and scale_y_continuous() methods used to disable scientific notation can be customized further to support different formats to represent numbers on the axes. The comma_format() method can be used to format number with commas separating thousands. Syntax: comma_format( big.mark , decimal.mark) Parameter : big.mark – indicator of the mark between every big.interval decimals before the decimal point. decimal.mark – indicator of the character to be used to indicate the decimal point. Example: R library(ggplot2)library("scales") set.seed(13482) # creating a data framedf <- data.frame(col1 = rpois(10,2)*100000, col2 = rpois(10,5)*100000 ) print ("Original DataFrame")print (df) # create a plotggplot(df, aes(col1, col2)) + geom_point() + scale_x_continuous(labels = comma_format(big.mark = ".", decimal.mark = ","))+ scale_y_continuous(labels = comma_format(big.mark = ".", decimal.mark = ",")) Output [1] "Original DataFrame" col1 col2 1 0e+00 8e+05 2 2e+05 3e+05 3 0e+00 7e+05 4 4e+05 7e+05 5 1e+05 3e+05 6 3e+05 7e+05 7 3e+05 6e+05 8 3e+05 6e+05 9 2e+05 6e+05 10 4e+05 4e+05 Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to Split Column Into Multiple Columns in R DataFrame? Replace Specific Characters in String in R How to filter R DataFrame by values in a column? How to import an Excel File into R ? R - if statement Time Series Analysis in R Plot mean and standard deviation using ggplot2 in R
[ { "code": null, "e": 26487, "s": 26459, "text": "\n30 Jun, 2021" }, { "code": null, "e": 26612, "s": 26487, "text": "In this article. we will discuss how to change the formatting of numbers of the ggplot2 plot axis in R Programming Language." }, { "code": null, "e": 26744, "s": 26612, "text": "The ggplot() method can be used in this package in order to simulate graph customizations and induce flexibility in graph plotting." }, { "code": null, "e": 26752, "s": 26744, "text": "Syntax:" }, { "code": null, "e": 26822, "s": 26752, "text": "ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) + <GEOM_FUNCTION>()" }, { "code": null, "e": 27277, "s": 26822, "text": "The data can be binded into the scatter plot using the data attribute of the ggplot method. The mapping in the function can be induced using the aes() function to create an aesthetic mapping, by filtering the variables to be plotted on the scatter plot. We can also specify how to depict different components in the graph, for instance, the x and y axes positions, the labels to assign to these points, or characteristics such as size, shape, color, etc." }, { "code": null, "e": 27520, "s": 27277, "text": "This method also allows the addition of various geoms- that is the components of the graph. geom_point() is used for the creation of a scatter plot. Large numbers are labeled across the axes using scientific notation for each of the numbers. " }, { "code": null, "e": 27529, "s": 27520, "text": "Example:" }, { "code": null, "e": 27531, "s": 27529, "text": "R" }, { "code": "library(ggplot2)library(\"scales\")set.seed(13482) # creating a data framedf <- data.frame(col1 = rpois(10,2)*100000, col2 = rpois(10,5)*100000 ) print (\"Original DataFrame\")print (df) # create a plotggplot(df, aes(col1, col2)) + geom_point()", "e": 27818, "s": 27531, "text": null }, { "code": null, "e": 27825, "s": 27818, "text": "Output" }, { "code": null, "e": 28026, "s": 27825, "text": "[1] \"Original DataFrame\" \n col1 col2 \n1 0e+00 8e+05 \n2 2e+05 3e+05 \n3 0e+00 7e+05 \n4 4e+05 7e+05 \n5 1e+05 3e+05 \n6 3e+05 7e+05 \n7 3e+05 6e+05 \n8 3e+05 6e+05 \n9 2e+05 6e+05 \n10 4e+05 4e+05" }, { "code": null, "e": 28095, "s": 28026, "text": "Now let us look at different ways in which numbers can be formatted." }, { "code": null, "e": 28396, "s": 28095, "text": "Formatting of axes labels is possible to convert the scientific notation to other formats. The scale_x_continuous() and scale_y_continuous() methods can be used to disable scientific notation and convert scientific labels to discrete form. The x and y parameters can be modified using these methods. " }, { "code": null, "e": 28404, "s": 28396, "text": "Syntax:" }, { "code": null, "e": 28438, "s": 28404, "text": "scale_x_continuous( name, labels)" }, { "code": null, "e": 28472, "s": 28438, "text": "scale_y_continuous( name, labels)" }, { "code": null, "e": 28485, "s": 28472, "text": "Parameter : " }, { "code": null, "e": 28511, "s": 28485, "text": "name – x or y axis labels" }, { "code": null, "e": 28547, "s": 28511, "text": "labels – labels of axis tick marks." }, { "code": null, "e": 28556, "s": 28547, "text": "Example:" }, { "code": null, "e": 28558, "s": 28556, "text": "R" }, { "code": "library(ggplot2)library(\"scales\") set.seed(13482) # creating a data framedf <- data.frame(col1 = rpois(10,2)*100000, col2 = rpois(10,5)*100000) print (\"Original DataFrame\")print (df) # create a plotggplot(df, aes(col1, col2)) + geom_point() + scale_x_continuous(labels = comma) + scale_y_continuous(labels = comma)", "e": 28908, "s": 28558, "text": null }, { "code": null, "e": 28915, "s": 28908, "text": "Output" }, { "code": null, "e": 29116, "s": 28915, "text": "[1] \"Original DataFrame\" \n col1 col2 \n1 0e+00 8e+05 \n2 2e+05 3e+05 \n3 0e+00 7e+05 \n4 4e+05 7e+05 \n5 1e+05 3e+05 \n6 3e+05 7e+05 \n7 3e+05 6e+05 \n8 3e+05 6e+05 \n9 2e+05 6e+05 \n10 4e+05 4e+05" }, { "code": null, "e": 29388, "s": 29116, "text": "The scale_x_continuous() and scale_y_continuous() methods used to disable scientific notation can be customized further to support different formats to represent numbers on the axes. The comma_format() method can be used to format number with commas separating thousands." }, { "code": null, "e": 29396, "s": 29388, "text": "Syntax:" }, { "code": null, "e": 29435, "s": 29396, "text": "comma_format( big.mark , decimal.mark)" }, { "code": null, "e": 29448, "s": 29435, "text": "Parameter : " }, { "code": null, "e": 29543, "s": 29448, "text": "big.mark – indicator of the mark between every big.interval decimals before the decimal point." }, { "code": null, "e": 29628, "s": 29543, "text": "decimal.mark – indicator of the character to be used to indicate the decimal point." }, { "code": null, "e": 29637, "s": 29628, "text": "Example:" }, { "code": null, "e": 29639, "s": 29637, "text": "R" }, { "code": "library(ggplot2)library(\"scales\") set.seed(13482) # creating a data framedf <- data.frame(col1 = rpois(10,2)*100000, col2 = rpois(10,5)*100000 ) print (\"Original DataFrame\")print (df) # create a plotggplot(df, aes(col1, col2)) + geom_point() + scale_x_continuous(labels = comma_format(big.mark = \".\", decimal.mark = \",\"))+ scale_y_continuous(labels = comma_format(big.mark = \".\", decimal.mark = \",\"))", "e": 30174, "s": 29639, "text": null }, { "code": null, "e": 30181, "s": 30174, "text": "Output" }, { "code": null, "e": 30370, "s": 30181, "text": "[1] \"Original DataFrame\"\n col1 col2\n1 0e+00 8e+05\n2 2e+05 3e+05\n3 0e+00 7e+05\n4 4e+05 7e+05\n5 1e+05 3e+05\n6 3e+05 7e+05\n7 3e+05 6e+05\n8 3e+05 6e+05\n9 2e+05 6e+05\n10 4e+05 4e+05" }, { "code": null, "e": 30377, "s": 30370, "text": "Picked" }, { "code": null, "e": 30386, "s": 30377, "text": "R-ggplot" }, { "code": null, "e": 30397, "s": 30386, "text": "R Language" }, { "code": null, "e": 30495, "s": 30397, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30547, "s": 30495, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 30582, "s": 30547, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 30620, "s": 30582, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 30678, "s": 30620, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 30721, "s": 30678, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 30770, "s": 30721, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 30807, "s": 30770, "text": "How to import an Excel File into R ?" }, { "code": null, "e": 30824, "s": 30807, "text": "R - if statement" }, { "code": null, "e": 30850, "s": 30824, "text": "Time Series Analysis in R" } ]
Optimize and Compress JPEG or PNG Images in Linux Command line - GeeksforGeeks
31 Aug, 2021 Today there are many GUI tools that compress and optimize the images, which are very useful. But if you are terminal addicted and want to compress and optimize the images in the terminal before uploading to the cloud, then you can do it. There are two tools by using which we can compress and optimize images. These are – jpegoptim OptiPNG jpegoptim is a command-line utility to optimize and compress JPEG/JFIF and JPG files. This utility support lossless optimization which is based on optimizing the Huffman tables. Now let’s see how to install the jpegoptim on different Linux distributions. The jpegoptim tool is available to install on most of the Linux package managers. Use one of the following commands according to your operating system to install jpegoptim utility. For Ubuntu/Debian/Kali Linux: apt-get install jpegoptim For Alpine: apk add jpegoptim For Arch Linux: pacman -S jpegoptim For Fedora: dnf install jpegoptim For OSX: brew install jpegoptim The syntax of jpegoptim is very simple to use but note that the jpegoptim compresses the file and replaces them with original file and to avoid this we need to mention the directory after jpegoptim command we will see later how to do that. To use the jpegoptim utility for one file, just mention the filename after the jpegoptim command, like: jpegoptim gfg.jpeg Now let’s take one example we are going to compress an image named gfg.jpg but first of all, let’s see what is the actual size of that image. We can use simple ls command to get the size of the image: ls -l gfg.jpg We can see the size of the gfg.jpg image is 5.3 MB. Now let’s use jpegoptim utility on that image: The size is changed by just 200 KB, this is because this tool does not lose the quality of the image while compressing. Instead of actually compressing the file, if you want to simulate the compression of JPEG files and see what will be the size of the image after reducing then use option -n with the jpegoptim command: jpegoptim -n gfg.jpg We can compress the image to a fixed size which we want, for that we have to use the –size option with jpegoptim command and mention the size of the image that we want after compressing. Let’s compress the same gfg.jpg file to 200k using jpegoptim with –size option. jpegoptim --size=200k gfg.jpg We can also compress all .jpg files in the directory. To compress all .jpg files in the current directory, use the following command: jpegoptim *.jpg To compress selective files in the directory, just mention the image names separated by space after jpegoptim command: jpegoptim gfg_1.jpg gfg_2.jpg gfg_3.jpg To save the output of jpegoptim in other folder use option -d and mention the folder name: jpegoptim -d foldername/ image.jpg Here is one example: jpegoptim -d ./compressed/ *.jpg To know more about jpegoptim read the man page of jpegoptim using the man command: man jpegoptim OptiPNG is a command-line tool that compresses portable network graphics (PNG) files without losing semantic information. Now let’s see how to install OptiPNG on different Linux distributions and OSX. Use one of the following commands according to Your operating system: For Debian/Ubuntu/Kali Linux: apt-get install optipng For Alpine: apk add optipng For Arch Linux: pacman -S optipng For CentOS: yum install optipng For Fedora: dnf install optipng For OSX: brew install optipng The syntax of using OptiPng is very simple, we have to just mention the name of the png file after the optipng command. optipng gfg.png Let’s compress the file named gfg.png before that, find out the size of the gfg.png file using the ls command: ls -l gfg.png The size of gfg.png is 534k now let’s use the optipng tool on that file optipng gfg.png We can see that the size gets reduced from 534k to 522k. We can optimize the all .png files in a folder using the following command: optipng *.png To save generated output files into another folder, use the -dir option with optipng command: optipng --dir=compressed gfg.png To compress selective files with the optipng just mention the file names separated by space: optipng gfg1.png gfg2.png To know more about the optipng command, read the man page of optipng using man command: man optipng Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. scp command in Linux with Examples Docker - COPY Instruction mv command in Linux with examples SED command in Linux | Set 2 chown command in Linux with Examples nohup Command in Linux with Examples Named Pipe or FIFO with example C program Thread functions in C/C++ uniq Command in LINUX with examples Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 25651, "s": 25623, "text": "\n31 Aug, 2021" }, { "code": null, "e": 25973, "s": 25651, "text": "Today there are many GUI tools that compress and optimize the images, which are very useful. But if you are terminal addicted and want to compress and optimize the images in the terminal before uploading to the cloud, then you can do it. There are two tools by using which we can compress and optimize images. These are –" }, { "code": null, "e": 25983, "s": 25973, "text": "jpegoptim" }, { "code": null, "e": 25991, "s": 25983, "text": "OptiPNG" }, { "code": null, "e": 26246, "s": 25991, "text": "jpegoptim is a command-line utility to optimize and compress JPEG/JFIF and JPG files. This utility support lossless optimization which is based on optimizing the Huffman tables. Now let’s see how to install the jpegoptim on different Linux distributions." }, { "code": null, "e": 26427, "s": 26246, "text": "The jpegoptim tool is available to install on most of the Linux package managers. Use one of the following commands according to your operating system to install jpegoptim utility." }, { "code": null, "e": 26457, "s": 26427, "text": "For Ubuntu/Debian/Kali Linux:" }, { "code": null, "e": 26483, "s": 26457, "text": "apt-get install jpegoptim" }, { "code": null, "e": 26495, "s": 26483, "text": "For Alpine:" }, { "code": null, "e": 26513, "s": 26495, "text": "apk add jpegoptim" }, { "code": null, "e": 26529, "s": 26513, "text": "For Arch Linux:" }, { "code": null, "e": 26549, "s": 26529, "text": "pacman -S jpegoptim" }, { "code": null, "e": 26561, "s": 26549, "text": "For Fedora:" }, { "code": null, "e": 26583, "s": 26561, "text": "dnf install jpegoptim" }, { "code": null, "e": 26592, "s": 26583, "text": "For OSX:" }, { "code": null, "e": 26615, "s": 26592, "text": "brew install jpegoptim" }, { "code": null, "e": 26959, "s": 26615, "text": "The syntax of jpegoptim is very simple to use but note that the jpegoptim compresses the file and replaces them with original file and to avoid this we need to mention the directory after jpegoptim command we will see later how to do that. To use the jpegoptim utility for one file, just mention the filename after the jpegoptim command, like:" }, { "code": null, "e": 26979, "s": 26959, "text": "jpegoptim gfg.jpeg" }, { "code": null, "e": 27181, "s": 26979, "text": "Now let’s take one example we are going to compress an image named gfg.jpg but first of all, let’s see what is the actual size of that image. We can use simple ls command to get the size of the image:" }, { "code": null, "e": 27195, "s": 27181, "text": "ls -l gfg.jpg" }, { "code": null, "e": 27294, "s": 27195, "text": "We can see the size of the gfg.jpg image is 5.3 MB. Now let’s use jpegoptim utility on that image:" }, { "code": null, "e": 27414, "s": 27294, "text": "The size is changed by just 200 KB, this is because this tool does not lose the quality of the image while compressing." }, { "code": null, "e": 27615, "s": 27414, "text": "Instead of actually compressing the file, if you want to simulate the compression of JPEG files and see what will be the size of the image after reducing then use option -n with the jpegoptim command:" }, { "code": null, "e": 27637, "s": 27615, "text": "jpegoptim -n gfg.jpg" }, { "code": null, "e": 27904, "s": 27637, "text": "We can compress the image to a fixed size which we want, for that we have to use the –size option with jpegoptim command and mention the size of the image that we want after compressing. Let’s compress the same gfg.jpg file to 200k using jpegoptim with –size option." }, { "code": null, "e": 27934, "s": 27904, "text": "jpegoptim --size=200k gfg.jpg" }, { "code": null, "e": 28068, "s": 27934, "text": "We can also compress all .jpg files in the directory. To compress all .jpg files in the current directory, use the following command:" }, { "code": null, "e": 28085, "s": 28068, "text": "jpegoptim *.jpg" }, { "code": null, "e": 28205, "s": 28085, "text": "To compress selective files in the directory, just mention the image names separated by space after jpegoptim command:" }, { "code": null, "e": 28246, "s": 28205, "text": "jpegoptim gfg_1.jpg gfg_2.jpg gfg_3.jpg" }, { "code": null, "e": 28338, "s": 28246, "text": "To save the output of jpegoptim in other folder use option -d and mention the folder name:" }, { "code": null, "e": 28375, "s": 28338, "text": " jpegoptim -d foldername/ image.jpg" }, { "code": null, "e": 28396, "s": 28375, "text": "Here is one example:" }, { "code": null, "e": 28430, "s": 28396, "text": "jpegoptim -d ./compressed/ *.jpg" }, { "code": null, "e": 28514, "s": 28430, "text": "To know more about jpegoptim read the man page of jpegoptim using the man command:" }, { "code": null, "e": 28529, "s": 28514, "text": "man jpegoptim " }, { "code": null, "e": 28800, "s": 28529, "text": "OptiPNG is a command-line tool that compresses portable network graphics (PNG) files without losing semantic information. Now let’s see how to install OptiPNG on different Linux distributions and OSX. Use one of the following commands according to Your operating system:" }, { "code": null, "e": 28830, "s": 28800, "text": "For Debian/Ubuntu/Kali Linux:" }, { "code": null, "e": 28854, "s": 28830, "text": "apt-get install optipng" }, { "code": null, "e": 28866, "s": 28854, "text": "For Alpine:" }, { "code": null, "e": 28882, "s": 28866, "text": "apk add optipng" }, { "code": null, "e": 28898, "s": 28882, "text": "For Arch Linux:" }, { "code": null, "e": 28916, "s": 28898, "text": "pacman -S optipng" }, { "code": null, "e": 28928, "s": 28916, "text": "For CentOS:" }, { "code": null, "e": 28948, "s": 28928, "text": "yum install optipng" }, { "code": null, "e": 28960, "s": 28948, "text": "For Fedora:" }, { "code": null, "e": 28980, "s": 28960, "text": "dnf install optipng" }, { "code": null, "e": 28989, "s": 28980, "text": "For OSX:" }, { "code": null, "e": 29010, "s": 28989, "text": "brew install optipng" }, { "code": null, "e": 29130, "s": 29010, "text": "The syntax of using OptiPng is very simple, we have to just mention the name of the png file after the optipng command." }, { "code": null, "e": 29146, "s": 29130, "text": "optipng gfg.png" }, { "code": null, "e": 29257, "s": 29146, "text": "Let’s compress the file named gfg.png before that, find out the size of the gfg.png file using the ls command:" }, { "code": null, "e": 29271, "s": 29257, "text": "ls -l gfg.png" }, { "code": null, "e": 29343, "s": 29271, "text": "The size of gfg.png is 534k now let’s use the optipng tool on that file" }, { "code": null, "e": 29359, "s": 29343, "text": "optipng gfg.png" }, { "code": null, "e": 29416, "s": 29359, "text": "We can see that the size gets reduced from 534k to 522k." }, { "code": null, "e": 29492, "s": 29416, "text": "We can optimize the all .png files in a folder using the following command:" }, { "code": null, "e": 29506, "s": 29492, "text": "optipng *.png" }, { "code": null, "e": 29600, "s": 29506, "text": "To save generated output files into another folder, use the -dir option with optipng command:" }, { "code": null, "e": 29633, "s": 29600, "text": "optipng --dir=compressed gfg.png" }, { "code": null, "e": 29726, "s": 29633, "text": "To compress selective files with the optipng just mention the file names separated by space:" }, { "code": null, "e": 29752, "s": 29726, "text": "optipng gfg1.png gfg2.png" }, { "code": null, "e": 29840, "s": 29752, "text": "To know more about the optipng command, read the man page of optipng using man command:" }, { "code": null, "e": 29852, "s": 29840, "text": "man optipng" }, { "code": null, "e": 29864, "s": 29852, "text": "Linux-Tools" }, { "code": null, "e": 29875, "s": 29864, "text": "Linux-Unix" }, { "code": null, "e": 29973, "s": 29875, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30008, "s": 29973, "text": "scp command in Linux with Examples" }, { "code": null, "e": 30034, "s": 30008, "text": "Docker - COPY Instruction" }, { "code": null, "e": 30068, "s": 30034, "text": "mv command in Linux with examples" }, { "code": null, "e": 30097, "s": 30068, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 30134, "s": 30097, "text": "chown command in Linux with Examples" }, { "code": null, "e": 30171, "s": 30134, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 30213, "s": 30171, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 30239, "s": 30213, "text": "Thread functions in C/C++" }, { "code": null, "e": 30275, "s": 30239, "text": "uniq Command in LINUX with examples" } ]
How to flatten a Vector of Vectors or 2D Vector in C++ - GeeksforGeeks
07 Apr, 2020 Given a Vector of Vectors (2D vector), the task is to flatten this 2d vector. Examples: Input: vector = [[1, 2, 3, 4], [5, 6], [7, 8]]Output: 1 2 3 4 5 6 7 8 Input: vector = [[1, 2], [3], [4, 5, 6, 8]]Output: 1 2 3 4 5 6 8 Algorithm: 2D Vector can be flattened using iterators.Store starting and ending iterator of every vector in two arrays, iStart & iEnd respectively.Create a hasNext() method to check if it has the vector has next element or not.Print the current element, if hasNext() yields true 2D Vector can be flattened using iterators. Store starting and ending iterator of every vector in two arrays, iStart & iEnd respectively. Create a hasNext() method to check if it has the vector has next element or not. Print the current element, if hasNext() yields true Below is the implementation of the above approach: // C++ program to flatten a// Vector of Vectors or 2D Vector #include <bits/stdc++.h>using namespace std; // Class to flatten the 2d vectorclass FlattenVector { public: int n; vector<vector<int>::iterator> iStart; vector<vector<int>::iterator> iEnd; int currIndex; // Store ending and starting iterators. FlattenVector(vector<vector<int> >& v) { // Get the number // of rows in 2d vector n = v.size(); currIndex = 0; iStart.resize(n); iEnd.resize(n); for (int i = 0; i < n; i++) { iStart[i] = v[i].begin(); iEnd[i] = v[i].end(); } } // Returns true if any element is left. bool hasNext() { for (int i = 0; i < n; i++) { if (iStart[i] != iEnd[i]) return true; } return false; } int next() { // Vector at currIndex is printed, // increment currIndex. if (iStart[currIndex] == iEnd[currIndex]) { currIndex++; return next(); } // Increment iterator // and return the value. else return *iStart[currIndex]++; }}; // Driver codeint main(){ vector<vector<int> > v{ { 1, 2 }, { 3 }, { 4, 5, 6 }, { 7, 8, 9, 10 } }; FlattenVector iter(v); while (iter.hasNext()) cout << iter.next() << " "; return 0;} 1 2 3 4 5 6 7 8 9 10 cpp-iterator cpp-vector Arrays C++ Recursion Arrays Recursion CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Arrays Multidimensional Arrays in Java Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Inheritance in C++ Initialize a vector in C++ (6 different ways) Map in C++ Standard Template Library (STL) std::sort() in C++ STL C++ Classes and Objects
[ { "code": null, "e": 25973, "s": 25945, "text": "\n07 Apr, 2020" }, { "code": null, "e": 26051, "s": 25973, "text": "Given a Vector of Vectors (2D vector), the task is to flatten this 2d vector." }, { "code": null, "e": 26061, "s": 26051, "text": "Examples:" }, { "code": null, "e": 26131, "s": 26061, "text": "Input: vector = [[1, 2, 3, 4], [5, 6], [7, 8]]Output: 1 2 3 4 5 6 7 8" }, { "code": null, "e": 26196, "s": 26131, "text": "Input: vector = [[1, 2], [3], [4, 5, 6, 8]]Output: 1 2 3 4 5 6 8" }, { "code": null, "e": 26207, "s": 26196, "text": "Algorithm:" }, { "code": null, "e": 26475, "s": 26207, "text": "2D Vector can be flattened using iterators.Store starting and ending iterator of every vector in two arrays, iStart & iEnd respectively.Create a hasNext() method to check if it has the vector has next element or not.Print the current element, if hasNext() yields true" }, { "code": null, "e": 26519, "s": 26475, "text": "2D Vector can be flattened using iterators." }, { "code": null, "e": 26613, "s": 26519, "text": "Store starting and ending iterator of every vector in two arrays, iStart & iEnd respectively." }, { "code": null, "e": 26694, "s": 26613, "text": "Create a hasNext() method to check if it has the vector has next element or not." }, { "code": null, "e": 26746, "s": 26694, "text": "Print the current element, if hasNext() yields true" }, { "code": null, "e": 26797, "s": 26746, "text": "Below is the implementation of the above approach:" }, { "code": "// C++ program to flatten a// Vector of Vectors or 2D Vector #include <bits/stdc++.h>using namespace std; // Class to flatten the 2d vectorclass FlattenVector { public: int n; vector<vector<int>::iterator> iStart; vector<vector<int>::iterator> iEnd; int currIndex; // Store ending and starting iterators. FlattenVector(vector<vector<int> >& v) { // Get the number // of rows in 2d vector n = v.size(); currIndex = 0; iStart.resize(n); iEnd.resize(n); for (int i = 0; i < n; i++) { iStart[i] = v[i].begin(); iEnd[i] = v[i].end(); } } // Returns true if any element is left. bool hasNext() { for (int i = 0; i < n; i++) { if (iStart[i] != iEnd[i]) return true; } return false; } int next() { // Vector at currIndex is printed, // increment currIndex. if (iStart[currIndex] == iEnd[currIndex]) { currIndex++; return next(); } // Increment iterator // and return the value. else return *iStart[currIndex]++; }}; // Driver codeint main(){ vector<vector<int> > v{ { 1, 2 }, { 3 }, { 4, 5, 6 }, { 7, 8, 9, 10 } }; FlattenVector iter(v); while (iter.hasNext()) cout << iter.next() << \" \"; return 0;}", "e": 28230, "s": 26797, "text": null }, { "code": null, "e": 28252, "s": 28230, "text": "1 2 3 4 5 6 7 8 9 10\n" }, { "code": null, "e": 28265, "s": 28252, "text": "cpp-iterator" }, { "code": null, "e": 28276, "s": 28265, "text": "cpp-vector" }, { "code": null, "e": 28283, "s": 28276, "text": "Arrays" }, { "code": null, "e": 28287, "s": 28283, "text": "C++" }, { "code": null, "e": 28297, "s": 28287, "text": "Recursion" }, { "code": null, "e": 28304, "s": 28297, "text": "Arrays" }, { "code": null, "e": 28314, "s": 28304, "text": "Recursion" }, { "code": null, "e": 28318, "s": 28314, "text": "CPP" }, { "code": null, "e": 28416, "s": 28318, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28439, "s": 28416, "text": "Introduction to Arrays" }, { "code": null, "e": 28471, "s": 28439, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 28492, "s": 28471, "text": "Linked List vs Array" }, { "code": null, "e": 28577, "s": 28492, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 28622, "s": 28577, "text": "Python | Using 2D arrays/lists the right way" }, { "code": null, "e": 28641, "s": 28622, "text": "Inheritance in C++" }, { "code": null, "e": 28687, "s": 28641, "text": "Initialize a vector in C++ (6 different ways)" }, { "code": null, "e": 28730, "s": 28687, "text": "Map in C++ Standard Template Library (STL)" }, { "code": null, "e": 28753, "s": 28730, "text": "std::sort() in C++ STL" } ]
Convert an Iterable to Collection in Java - GeeksforGeeks
28 Feb, 2022 Iterable and Collection have served to be of great use in Java. Iterators are used in Collection framework in Java to retrieve elements one by one and a Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.But at certain times, it is required to switch from iterable to collection and vice versa. For more details on difference between Iterable and Collection, please refer to the post Iterator vs Collection in Java.The conversion of Iterable to Collection can be carried out in following ways: Creating a utility function: Creating a utility function means creating a function that converts the iterable to a collection by explicitly taking each item into account. This also can be done in many ways as explained below: Using For loop Using For loop Java // Below is the program to convert an Iterable// into a Collection using for loop import java.io.*;import java.util.*; class GFG { // function to convert Iterable into Collection public static <T> Collection<T> getCollectionFromIterable(Iterable<T> itr) { // Create an empty Collection to hold the result Collection<T> cltn = new ArrayList<T>(); // Iterate through the iterable to // add each element into the collection for (T t : itr) cltn.add(t); // Return the converted collection return cltn; } public static void main(String[] args) { Iterable<Integer> i = Arrays.asList(1, 2, 3, 4); System.out.println("Iterable List : " + i); Collection<Integer> cn = getCollectionFromIterable(i); System.out.println("Collection List : " + cn); }} Iterable List : [1, 2, 3, 4] Collection List : [1, 2, 3, 4] Using Iterable.forEach(): It can be used in Java 8 and above. Java // Below is the program to convert an Iterable// into a Collection using iterable.forEach import java.io.*;import java.util.*; class GFG { // function to convert Iterable into Collection public static <T> Collection<T> getCollectionFromIterable(Iterable<T> itr) { // Create an empty Collection to hold the result Collection<T> cltn = new ArrayList<T>(); // Use iterable.forEach() to // Iterate through the iterable and // add each element into the collection itr.forEach(cltn::add); // Return the converted collection return cltn; } public static void main(String[] args) { Iterable<Integer> i = Arrays.asList(1, 2, 3, 4); System.out.println("Iterable List : " + i); Collection<Integer> cn = getCollectionFromIterable(i); System.out.println("Collection List : " + cn); }} Iterable List : [1, 2, 3, 4] Collection List : [1, 2, 3, 4] Using Iterator: The forEach loop uses Iterator in the background. Hence it can be done explicitly in the following way. Java // Below is the program to convert an Iterable// into a Collection using Iterator import java.io.*;import java.util.*; class GFG { // function to convert Iterable into Collection public static <T> Collection<T> getCollectionFromIterable(Iterable<T> itr) { // Create an empty Collection to hold the result Collection<T> cltn = new ArrayList<T>(); // Get the iterator at the iterable Iterator<T> iterator = itr.iterator(); // Iterate through the iterable using // iterator to add each element into the collection while (iterator.hasNext()) { cltn.add(iterator.next()); } // Return the converted collection return cltn; } public static void main(String[] args) { Iterable<Integer> i = Arrays.asList(1, 2, 3, 4); System.out.println("Iterable List : " + i); Collection<Integer> cn = getCollectionFromIterable(i); System.out.println("Collection List : " + cn); }} Iterable List : [1, 2, 3, 4] Collection List : [1, 2, 3, 4] Java 8 Stream: With the introduction of Stream in Java 8, works like this has become quite easy. To convert iterable to Collection, the iterable is first converted into spliterator. Then with the help of StreamSupport.stream(), the spliterator can be traversed and then collected with the help collect() into collection. Java // Program to convert an Iterable// into a Collection import java.io.*;import java.util.*;import java.util.stream.*; class GFG { // function to convert Iterable into Collection public static <T> Collection<T> getCollectionFromIterable(Iterable<T> itr) { // Create an empty Collection to hold the result Collection<T> cltn = new ArrayList<T>(); return StreamSupport.stream(itr.spliterator(), false) .collect(Collectors.toList()); } public static void main(String[] args) { Iterable<Integer> i = Arrays.asList(1, 2, 3, 4); System.out.println("Iterable List : " + i); Collection<Integer> cn = getCollectionFromIterable(i); System.out.println("Collection List : " + cn); }} Iterable List : [1, 2, 3, 4] Collection List : [1, 2, 3, 4] ruhelaa48 varshagumber28 Java-Collections Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 25769, "s": 25741, "text": "\n28 Feb, 2022" }, { "code": null, "e": 26416, "s": 25769, "text": "Iterable and Collection have served to be of great use in Java. Iterators are used in Collection framework in Java to retrieve elements one by one and a Collection is a group of individual objects represented as a single unit. Java provides Collection Framework which defines several classes and interfaces to represent a group of objects as a single unit.But at certain times, it is required to switch from iterable to collection and vice versa. For more details on difference between Iterable and Collection, please refer to the post Iterator vs Collection in Java.The conversion of Iterable to Collection can be carried out in following ways: " }, { "code": null, "e": 26657, "s": 26416, "text": "Creating a utility function: Creating a utility function means creating a function that converts the iterable to a collection by explicitly taking each item into account. This also can be done in many ways as explained below: Using For loop" }, { "code": null, "e": 26672, "s": 26657, "text": "Using For loop" }, { "code": null, "e": 26677, "s": 26672, "text": "Java" }, { "code": "// Below is the program to convert an Iterable// into a Collection using for loop import java.io.*;import java.util.*; class GFG { // function to convert Iterable into Collection public static <T> Collection<T> getCollectionFromIterable(Iterable<T> itr) { // Create an empty Collection to hold the result Collection<T> cltn = new ArrayList<T>(); // Iterate through the iterable to // add each element into the collection for (T t : itr) cltn.add(t); // Return the converted collection return cltn; } public static void main(String[] args) { Iterable<Integer> i = Arrays.asList(1, 2, 3, 4); System.out.println(\"Iterable List : \" + i); Collection<Integer> cn = getCollectionFromIterable(i); System.out.println(\"Collection List : \" + cn); }}", "e": 27547, "s": 26677, "text": null }, { "code": null, "e": 27607, "s": 27547, "text": "Iterable List : [1, 2, 3, 4]\nCollection List : [1, 2, 3, 4]" }, { "code": null, "e": 27671, "s": 27609, "text": "Using Iterable.forEach(): It can be used in Java 8 and above." }, { "code": null, "e": 27676, "s": 27671, "text": "Java" }, { "code": "// Below is the program to convert an Iterable// into a Collection using iterable.forEach import java.io.*;import java.util.*; class GFG { // function to convert Iterable into Collection public static <T> Collection<T> getCollectionFromIterable(Iterable<T> itr) { // Create an empty Collection to hold the result Collection<T> cltn = new ArrayList<T>(); // Use iterable.forEach() to // Iterate through the iterable and // add each element into the collection itr.forEach(cltn::add); // Return the converted collection return cltn; } public static void main(String[] args) { Iterable<Integer> i = Arrays.asList(1, 2, 3, 4); System.out.println(\"Iterable List : \" + i); Collection<Integer> cn = getCollectionFromIterable(i); System.out.println(\"Collection List : \" + cn); }}", "e": 28572, "s": 27676, "text": null }, { "code": null, "e": 28632, "s": 28572, "text": "Iterable List : [1, 2, 3, 4]\nCollection List : [1, 2, 3, 4]" }, { "code": null, "e": 28754, "s": 28634, "text": "Using Iterator: The forEach loop uses Iterator in the background. Hence it can be done explicitly in the following way." }, { "code": null, "e": 28759, "s": 28754, "text": "Java" }, { "code": "// Below is the program to convert an Iterable// into a Collection using Iterator import java.io.*;import java.util.*; class GFG { // function to convert Iterable into Collection public static <T> Collection<T> getCollectionFromIterable(Iterable<T> itr) { // Create an empty Collection to hold the result Collection<T> cltn = new ArrayList<T>(); // Get the iterator at the iterable Iterator<T> iterator = itr.iterator(); // Iterate through the iterable using // iterator to add each element into the collection while (iterator.hasNext()) { cltn.add(iterator.next()); } // Return the converted collection return cltn; } public static void main(String[] args) { Iterable<Integer> i = Arrays.asList(1, 2, 3, 4); System.out.println(\"Iterable List : \" + i); Collection<Integer> cn = getCollectionFromIterable(i); System.out.println(\"Collection List : \" + cn); }}", "e": 29770, "s": 28759, "text": null }, { "code": null, "e": 29830, "s": 29770, "text": "Iterable List : [1, 2, 3, 4]\nCollection List : [1, 2, 3, 4]" }, { "code": null, "e": 30153, "s": 29832, "text": "Java 8 Stream: With the introduction of Stream in Java 8, works like this has become quite easy. To convert iterable to Collection, the iterable is first converted into spliterator. Then with the help of StreamSupport.stream(), the spliterator can be traversed and then collected with the help collect() into collection." }, { "code": null, "e": 30158, "s": 30153, "text": "Java" }, { "code": "// Program to convert an Iterable// into a Collection import java.io.*;import java.util.*;import java.util.stream.*; class GFG { // function to convert Iterable into Collection public static <T> Collection<T> getCollectionFromIterable(Iterable<T> itr) { // Create an empty Collection to hold the result Collection<T> cltn = new ArrayList<T>(); return StreamSupport.stream(itr.spliterator(), false) .collect(Collectors.toList()); } public static void main(String[] args) { Iterable<Integer> i = Arrays.asList(1, 2, 3, 4); System.out.println(\"Iterable List : \" + i); Collection<Integer> cn = getCollectionFromIterable(i); System.out.println(\"Collection List : \" + cn); }}", "e": 30931, "s": 30158, "text": null }, { "code": null, "e": 30991, "s": 30931, "text": "Iterable List : [1, 2, 3, 4]\nCollection List : [1, 2, 3, 4]" }, { "code": null, "e": 31003, "s": 30993, "text": "ruhelaa48" }, { "code": null, "e": 31018, "s": 31003, "text": "varshagumber28" }, { "code": null, "e": 31035, "s": 31018, "text": "Java-Collections" }, { "code": null, "e": 31040, "s": 31035, "text": "Java" }, { "code": null, "e": 31045, "s": 31040, "text": "Java" }, { "code": null, "e": 31062, "s": 31045, "text": "Java-Collections" }, { "code": null, "e": 31160, "s": 31062, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31211, "s": 31160, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31241, "s": 31211, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31256, "s": 31241, "text": "Stream In Java" }, { "code": null, "e": 31275, "s": 31256, "text": "Interfaces in Java" }, { "code": null, "e": 31306, "s": 31275, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31324, "s": 31306, "text": "ArrayList in Java" }, { "code": null, "e": 31356, "s": 31324, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 31376, "s": 31356, "text": "Stack Class in Java" }, { "code": null, "e": 31408, "s": 31376, "text": "Multidimensional Arrays in Java" } ]
Matplotlib.axes.Axes.broken_barh() in Python - GeeksforGeeks
13 Apr, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. The Axes.broken_barh() function in axes module of matplotlib library is used to plot a horizontal sequence of rectangles. Syntax: Axes.broken_barh(self, xranges, yrange, *, data=None, **kwargs) Parameters: This method accept the following parameters that are described below: y: This parameter is the sequence of y coordinates of the bar. xranges: This parameter is the sequence of tuples (xmin, xwidth).It is the x-positions and extends of the rectangles. yrange: This parameter is the sequence of tuples (ymin, yheight).It is the y-positions and extends for all the rectangles. Returns: This returns the following: BrokenBarHCollection:This returns the container with all the broken_barh. Below examples illustrate the matplotlib.axes.Axes.broken_barh() function in matplotlib.axes: Example #1: # Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors ='tab:green') ax.set_xlabel('x')ax.set_ylabel('y')ax.grid(True) ax.set_title('matplotlib.axes.Axes.\broken_barh Example')plt.show() Output: Example #2: # Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors ='tab:green') ax.broken_barh([(100, 20), (130, 10)], (20, 9), facecolors =('tab:green')) ax.set_ylim(5, 35)ax.set_xlim(50, 200)ax.set_xlabel('Learning Rate')ax.set_yticks([15, 25])ax.set_yticklabels(['Geeks1', 'Geeks2'])ax.grid(True) ax.annotate('Broken', (125, 25), xytext =(0.8, 0.9), textcoords ='axes fraction', arrowprops = dict(facecolor ='black', shrink = 0.05), fontsize = 16, horizontalalignment ='right', verticalalignment ='top') ax.set_title('matplotlib.axes.Axes.broken_barh Example') plt.show() Output: Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python
[ { "code": null, "e": 25637, "s": 25609, "text": "\n13 Apr, 2020" }, { "code": null, "e": 25937, "s": 25637, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute." }, { "code": null, "e": 26059, "s": 25937, "text": "The Axes.broken_barh() function in axes module of matplotlib library is used to plot a horizontal sequence of rectangles." }, { "code": null, "e": 26067, "s": 26059, "text": "Syntax:" }, { "code": null, "e": 26131, "s": 26067, "text": "Axes.broken_barh(self, xranges, yrange, *, data=None, **kwargs)" }, { "code": null, "e": 26213, "s": 26131, "text": "Parameters: This method accept the following parameters that are described below:" }, { "code": null, "e": 26276, "s": 26213, "text": "y: This parameter is the sequence of y coordinates of the bar." }, { "code": null, "e": 26394, "s": 26276, "text": "xranges: This parameter is the sequence of tuples (xmin, xwidth).It is the x-positions and extends of the rectangles." }, { "code": null, "e": 26517, "s": 26394, "text": "yrange: This parameter is the sequence of tuples (ymin, yheight).It is the y-positions and extends for all the rectangles." }, { "code": null, "e": 26554, "s": 26517, "text": "Returns: This returns the following:" }, { "code": null, "e": 26628, "s": 26554, "text": "BrokenBarHCollection:This returns the container with all the broken_barh." }, { "code": null, "e": 26722, "s": 26628, "text": "Below examples illustrate the matplotlib.axes.Axes.broken_barh() function in matplotlib.axes:" }, { "code": null, "e": 26734, "s": 26722, "text": "Example #1:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors ='tab:green') ax.set_xlabel('x')ax.set_ylabel('y')ax.grid(True) ax.set_title('matplotlib.axes.Axes.\\broken_barh Example')plt.show()", "e": 27052, "s": 26734, "text": null }, { "code": null, "e": 27060, "s": 27052, "text": "Output:" }, { "code": null, "e": 27072, "s": 27060, "text": "Example #2:" }, { "code": "# Implementation of matplotlib functionimport matplotlib.pyplot as plt fig, ax = plt.subplots()ax.broken_barh([(110, 30), (150, 10)], (10, 9), facecolors ='tab:green') ax.broken_barh([(100, 20), (130, 10)], (20, 9), facecolors =('tab:green')) ax.set_ylim(5, 35)ax.set_xlim(50, 200)ax.set_xlabel('Learning Rate')ax.set_yticks([15, 25])ax.set_yticklabels(['Geeks1', 'Geeks2'])ax.grid(True) ax.annotate('Broken', (125, 25), xytext =(0.8, 0.9), textcoords ='axes fraction', arrowprops = dict(facecolor ='black', shrink = 0.05), fontsize = 16, horizontalalignment ='right', verticalalignment ='top') ax.set_title('matplotlib.axes.Axes.broken_barh Example') plt.show()", "e": 27913, "s": 27072, "text": null }, { "code": null, "e": 27921, "s": 27913, "text": "Output:" }, { "code": null, "e": 27939, "s": 27921, "text": "Python-matplotlib" }, { "code": null, "e": 27946, "s": 27939, "text": "Python" }, { "code": null, "e": 28044, "s": 27946, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28062, "s": 28044, "text": "Python Dictionary" }, { "code": null, "e": 28097, "s": 28062, "text": "Read a file line by line in Python" }, { "code": null, "e": 28129, "s": 28097, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28171, "s": 28129, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28197, "s": 28171, "text": "Python String | replace()" }, { "code": null, "e": 28226, "s": 28197, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28270, "s": 28226, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 28307, "s": 28270, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28343, "s": 28307, "text": "Convert integer to string in Python" } ]
SQL Query to Drop Foreign Key Constraint Using ALTER Command - GeeksforGeeks
13 Apr, 2021 Here, we are going to see How to Drop a Foreign Key Constraint using ALTER Command(SQL Query) using Microsoft SQL Server. A Foreign key is an attribute in one table which takes references from another table where it acts as the primary key in that table. Also, the column acting as a foreign key should be present in both tables. CREATE DATABASE geeks; USE geeks; We have the following emp table in our database : CREATE TABLE emp( empno number(2) constraint pk primary key , empname varchar2(20), deptno number(2), empsal number(20)); To verify table schema use the following query: EXEC SP_COLUMNS emp; Output: EMP TABLE SCHEMA Use the below statement to add data to the emp table: INSERT INTO emp values(1,'abc',5,20000); INSERT INTO emp values(2,'def',6,30000); INSERT INTO emp values(3,'xyz',7,40000); Output: VALUES IN EMP TABLE Now let’s write SQL Query to Drop Foreign Key Constraint Using ALTER Command. For that, we have to create another table called “DEPT”. CREATE TABLE dept( deptno number(2) constraint pk2 primary key , dname varchar2(5), loc varchar2(5)); To check out the current table use the following statement: SELECT * FROM dept; Output: DEPT TABLE SCHEMA Use the below statement to add data to the dept table: INSERT INTO dept values(5,'IT','hyd'); INSERT INTO dept values(6,'sales','bglr'); INSERT INTO dept values(7,'mgr','mumb'); To check out the current table use the following statement: SELECT * FROM dept; DEPT TABLE VALUES Here we have kept the DEPTNO column as common in both EMP and DEPT tables ALTER TABLE emp add constraint fk foreign key(deptno) references dept(deptno); //ADDS FOREIGN KEY CONSTRAINT ON EMP TABLE FOREIGN KEY “FK” HAS BEEN CREATED ALTER TABLE TABLE NAME drop constraint CONSTRAINT_NAME ALTER TABLE emp drop constraint fk; Output: Hence, in this way, we can Drop Foreign Key Constraint Using ALTER Command Picked SQL-Query SQL SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Update Multiple Columns in Single Update Statement in SQL? SQL | Subquery How to Create a Table With Multiple Foreign Keys in SQL? What is Temporary Table in SQL? SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter SQL using Python SQL Query to Convert VARCHAR to INT How to Write a SQL Query For a Specific Date Range and Date Time? How to Select Data Between Two Dates and Times in SQL Server? SQL Query to Compare Two Dates
[ { "code": null, "e": 25539, "s": 25511, "text": "\n13 Apr, 2021" }, { "code": null, "e": 25662, "s": 25539, "text": "Here, we are going to see How to Drop a Foreign Key Constraint using ALTER Command(SQL Query) using Microsoft SQL Server." }, { "code": null, "e": 25871, "s": 25662, "text": "A Foreign key is an attribute in one table which takes references from another table where it acts as the primary key in that table. Also, the column acting as a foreign key should be present in both tables. " }, { "code": null, "e": 25894, "s": 25871, "text": "CREATE DATABASE geeks;" }, { "code": null, "e": 25905, "s": 25894, "text": "USE geeks;" }, { "code": null, "e": 25955, "s": 25905, "text": "We have the following emp table in our database :" }, { "code": null, "e": 26077, "s": 25955, "text": "CREATE TABLE emp(\nempno number(2) constraint pk primary key ,\nempname varchar2(20),\ndeptno number(2),\nempsal number(20));" }, { "code": null, "e": 26125, "s": 26077, "text": "To verify table schema use the following query:" }, { "code": null, "e": 26146, "s": 26125, "text": "EXEC SP_COLUMNS emp;" }, { "code": null, "e": 26154, "s": 26146, "text": "Output:" }, { "code": null, "e": 26171, "s": 26154, "text": "EMP TABLE SCHEMA" }, { "code": null, "e": 26225, "s": 26171, "text": "Use the below statement to add data to the emp table:" }, { "code": null, "e": 26348, "s": 26225, "text": "INSERT INTO emp values(1,'abc',5,20000);\nINSERT INTO emp values(2,'def',6,30000);\nINSERT INTO emp values(3,'xyz',7,40000);" }, { "code": null, "e": 26356, "s": 26348, "text": "Output:" }, { "code": null, "e": 26376, "s": 26356, "text": "VALUES IN EMP TABLE" }, { "code": null, "e": 26511, "s": 26376, "text": "Now let’s write SQL Query to Drop Foreign Key Constraint Using ALTER Command. For that, we have to create another table called “DEPT”." }, { "code": null, "e": 26613, "s": 26511, "text": "CREATE TABLE dept(\ndeptno number(2) constraint pk2 primary key ,\ndname varchar2(5),\nloc varchar2(5));" }, { "code": null, "e": 26673, "s": 26613, "text": "To check out the current table use the following statement:" }, { "code": null, "e": 26693, "s": 26673, "text": "SELECT * FROM dept;" }, { "code": null, "e": 26701, "s": 26693, "text": "Output:" }, { "code": null, "e": 26719, "s": 26701, "text": "DEPT TABLE SCHEMA" }, { "code": null, "e": 26774, "s": 26719, "text": "Use the below statement to add data to the dept table:" }, { "code": null, "e": 26897, "s": 26774, "text": "INSERT INTO dept values(5,'IT','hyd');\nINSERT INTO dept values(6,'sales','bglr');\nINSERT INTO dept values(7,'mgr','mumb');" }, { "code": null, "e": 26957, "s": 26897, "text": "To check out the current table use the following statement:" }, { "code": null, "e": 26977, "s": 26957, "text": "SELECT * FROM dept;" }, { "code": null, "e": 26995, "s": 26977, "text": "DEPT TABLE VALUES" }, { "code": null, "e": 27069, "s": 26995, "text": "Here we have kept the DEPTNO column as common in both EMP and DEPT tables" }, { "code": null, "e": 27192, "s": 27069, "text": "ALTER TABLE emp add constraint fk foreign key(deptno) references dept(deptno);\n //ADDS FOREIGN KEY CONSTRAINT ON EMP TABLE" }, { "code": null, "e": 27226, "s": 27192, "text": "FOREIGN KEY “FK” HAS BEEN CREATED" }, { "code": null, "e": 27281, "s": 27226, "text": "ALTER TABLE TABLE NAME drop constraint CONSTRAINT_NAME" }, { "code": null, "e": 27317, "s": 27281, "text": "ALTER TABLE emp drop constraint fk;" }, { "code": null, "e": 27325, "s": 27317, "text": "Output:" }, { "code": null, "e": 27400, "s": 27325, "text": "Hence, in this way, we can Drop Foreign Key Constraint Using ALTER Command" }, { "code": null, "e": 27407, "s": 27400, "text": "Picked" }, { "code": null, "e": 27417, "s": 27407, "text": "SQL-Query" }, { "code": null, "e": 27421, "s": 27417, "text": "SQL" }, { "code": null, "e": 27425, "s": 27421, "text": "SQL" }, { "code": null, "e": 27523, "s": 27425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27589, "s": 27523, "text": "How to Update Multiple Columns in Single Update Statement in SQL?" }, { "code": null, "e": 27604, "s": 27589, "text": "SQL | Subquery" }, { "code": null, "e": 27661, "s": 27604, "text": "How to Create a Table With Multiple Foreign Keys in SQL?" }, { "code": null, "e": 27693, "s": 27661, "text": "What is Temporary Table in SQL?" }, { "code": null, "e": 27771, "s": 27693, "text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter" }, { "code": null, "e": 27788, "s": 27771, "text": "SQL using Python" }, { "code": null, "e": 27824, "s": 27788, "text": "SQL Query to Convert VARCHAR to INT" }, { "code": null, "e": 27890, "s": 27824, "text": "How to Write a SQL Query For a Specific Date Range and Date Time?" }, { "code": null, "e": 27952, "s": 27890, "text": "How to Select Data Between Two Dates and Times in SQL Server?" } ]
ChronoZonedDateTime isBefore() method in Java with Examples - GeeksforGeeks
29 May, 2019 The isBefore() method of ChronoZonedDateTime interface in Java is used to check if the date, passed as the parameter, is before this ChronoZonedDateTime instance or not. It returns a boolean value showing the same. Syntax: public boolean isBefore(ChronoZonedDateTime otherDate) Parameter: This method accepts a parameter otherDate which specifies the other date-time to be compared to this ChronoZonedDateTime. It should not be null. Returns: The function returns boolean value showing if this date-time is before the specified date-time. Below programs illustrate the ChronoZonedDateTime.isBefore() method: Program 1: // Program to illustrate the isBefore() method import java.util.*;import java.time.*;import java.time.chrono.*; public class GfG { public static void main(String[] args) { // Parses the date ChronoZonedDateTime dt1 = ZonedDateTime.parse( "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); // Prints the date System.out.println(dt1); // Parses the date ChronoZonedDateTime dt2 = ZonedDateTime.parse( "2018-10-06T19:21:12.123+05:30[Asia/Calcutta]"); // Prints the date System.out.println(dt2); // Compares both dates System.out.println(dt1.isBefore(dt2)); }} 2018-12-06T19:21:12.123+05:30[Asia/Calcutta] 2018-10-06T19:21:12.123+05:30[Asia/Calcutta] false Program 2: // Program to illustrate the isBefore() method import java.util.*;import java.time.*;import java.time.chrono.*; public class GfG { public static void main(String[] args) { // Parses the date ChronoZonedDateTime dt1 = ZonedDateTime.parse( "2018-10-06T19:21:12.123+05:30[Asia/Calcutta]"); // Prints the date System.out.println(dt1); // Parses the date ChronoZonedDateTime dt2 = ZonedDateTime.parse( "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]"); // Prints the date System.out.println(dt2); // Compares both dates System.out.println(dt1.isBefore(dt2)); }} 2018-10-06T19:21:12.123+05:30[Asia/Calcutta] 2018-12-06T19:21:12.123+05:30[Asia/Calcutta] true Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoZonedDateTime.html#isBefore-java.time.chrono.ChronoZonedDateTime- Java-ChronoZonedDateTime Java-Functions Java-Time-Chrono package Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Generics in Java Introduction to Java Comparator Interface in Java with Examples Internal Working of HashMap in Java Strings in Java
[ { "code": null, "e": 25225, "s": 25197, "text": "\n29 May, 2019" }, { "code": null, "e": 25440, "s": 25225, "text": "The isBefore() method of ChronoZonedDateTime interface in Java is used to check if the date, passed as the parameter, is before this ChronoZonedDateTime instance or not. It returns a boolean value showing the same." }, { "code": null, "e": 25448, "s": 25440, "text": "Syntax:" }, { "code": null, "e": 25503, "s": 25448, "text": "public boolean isBefore(ChronoZonedDateTime otherDate)" }, { "code": null, "e": 25659, "s": 25503, "text": "Parameter: This method accepts a parameter otherDate which specifies the other date-time to be compared to this ChronoZonedDateTime. It should not be null." }, { "code": null, "e": 25764, "s": 25659, "text": "Returns: The function returns boolean value showing if this date-time is before the specified date-time." }, { "code": null, "e": 25833, "s": 25764, "text": "Below programs illustrate the ChronoZonedDateTime.isBefore() method:" }, { "code": null, "e": 25844, "s": 25833, "text": "Program 1:" }, { "code": "// Program to illustrate the isBefore() method import java.util.*;import java.time.*;import java.time.chrono.*; public class GfG { public static void main(String[] args) { // Parses the date ChronoZonedDateTime dt1 = ZonedDateTime.parse( \"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\"); // Prints the date System.out.println(dt1); // Parses the date ChronoZonedDateTime dt2 = ZonedDateTime.parse( \"2018-10-06T19:21:12.123+05:30[Asia/Calcutta]\"); // Prints the date System.out.println(dt2); // Compares both dates System.out.println(dt1.isBefore(dt2)); }}", "e": 26540, "s": 25844, "text": null }, { "code": null, "e": 26637, "s": 26540, "text": "2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\n2018-10-06T19:21:12.123+05:30[Asia/Calcutta]\nfalse\n" }, { "code": null, "e": 26648, "s": 26637, "text": "Program 2:" }, { "code": "// Program to illustrate the isBefore() method import java.util.*;import java.time.*;import java.time.chrono.*; public class GfG { public static void main(String[] args) { // Parses the date ChronoZonedDateTime dt1 = ZonedDateTime.parse( \"2018-10-06T19:21:12.123+05:30[Asia/Calcutta]\"); // Prints the date System.out.println(dt1); // Parses the date ChronoZonedDateTime dt2 = ZonedDateTime.parse( \"2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\"); // Prints the date System.out.println(dt2); // Compares both dates System.out.println(dt1.isBefore(dt2)); }}", "e": 27344, "s": 26648, "text": null }, { "code": null, "e": 27440, "s": 27344, "text": "2018-10-06T19:21:12.123+05:30[Asia/Calcutta]\n2018-12-06T19:21:12.123+05:30[Asia/Calcutta]\ntrue\n" }, { "code": null, "e": 27582, "s": 27440, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/time/chrono/ChronoZonedDateTime.html#isBefore-java.time.chrono.ChronoZonedDateTime-" }, { "code": null, "e": 27607, "s": 27582, "text": "Java-ChronoZonedDateTime" }, { "code": null, "e": 27622, "s": 27607, "text": "Java-Functions" }, { "code": null, "e": 27647, "s": 27622, "text": "Java-Time-Chrono package" }, { "code": null, "e": 27652, "s": 27647, "text": "Java" }, { "code": null, "e": 27657, "s": 27652, "text": "Java" }, { "code": null, "e": 27755, "s": 27657, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27770, "s": 27755, "text": "Stream In Java" }, { "code": null, "e": 27791, "s": 27770, "text": "Constructors in Java" }, { "code": null, "e": 27810, "s": 27791, "text": "Exceptions in Java" }, { "code": null, "e": 27840, "s": 27810, "text": "Functional Interfaces in Java" }, { "code": null, "e": 27886, "s": 27840, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27903, "s": 27886, "text": "Generics in Java" }, { "code": null, "e": 27924, "s": 27903, "text": "Introduction to Java" }, { "code": null, "e": 27967, "s": 27924, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 28003, "s": 27967, "text": "Internal Working of HashMap in Java" } ]
C++ Program For Rearranging A Linked List In Zig-Zag Fashion - GeeksforGeeks
30 Dec, 2021 Given a linked list, rearrange it such that the converted list should be of the form a < b > c < d > e < f ... where a, b, c... are consecutive data nodes of the linked list. Examples: Input: 1->2->3->4 Output: 1->3->2->4 Explanation: 1 and 3 should come first before 2 and 4 in zig-zag fashion, So resultant linked-list will be 1->3->2->4. Input: 11->15->20->5->10 Output: 11->20->5->15->10 A simple approach to do this is to sort the linked list using merge sort and then swap alternate, but that requires O(n Log n) time complexity. Here n is a number of elements in the linked list. An efficient approach that requires O(n) time is, using a single scan similar to bubble sort and then maintain a flag for representing which order () currently we are. If the current two elements are not in that order then swap those elements otherwise not. Please refer to this for a detailed explanation of the swapping order. C++ // C++ program to arrange linked// list in zigzag fashion#include <bits/stdc++.h>using namespace std; // Link list Node struct Node { int data; struct Node* next;}; // This function distributes the// Node in zigzag fashionvoid zigZagList(Node* head){ // If flag is true, then next // node should be greater // in the desired output. bool flag = true; // Traverse linked list starting // from head. Node* current = head; while (current->next != NULL) { // "<" relation expected if (flag) { /* If we have a situation like A > B > C where A, B and C are consecutive Nodes in list we get A > B < C by swapping B and C */ if (current->data > current->next->data) swap(current->data, current->next->data); } // ">" relation expected else { /* If we have a situation like A < B < C where A, B and C are consecutive Nodes in list we get A < C > B by swapping B and C */ if (current->data < current->next->data) swap(current->data, current->next->data); } current = current->next; // flip flag for reverse checking flag = !flag; }} // UTILITY FUNCTIONS // Function to push a Node void push(Node** head_ref, int new_data){ // Allocate Node struct Node* new_Node = new Node; // Put in the data new_Node->data = new_data; // Link the old list off the // new Node new_Node->next = (*head_ref); // Move the head to point to // the new Node (*head_ref) = new_Node;} // Function to print linked list void printList(struct Node* Node){ while (Node != NULL) { printf("%d->", Node->data); Node = Node->next; } printf("NULL");} // Driver codeint main(void){ // Start with the empty list struct Node* head = NULL; // create a list 4 -> 3 -> 7 -> // 8 -> 6 -> 2 -> 1 // answer should be -> 3 7 4 // 8 2 6 1 push(&head, 1); push(&head, 2); push(&head, 6); push(&head, 8); push(&head, 7); push(&head, 3); push(&head, 4); printf("Given linked list "); printList(head); zigZagList(head); printf("Zig Zag Linked list "); printList(head); return (0);} Output: Given linked list 4->3->7->8->6->2->1->NULL Zig Zag Linked list 3->7->4->8->2->6->1->NULL Please refer complete article on Rearrange a Linked List in Zig-Zag fashion for more details! Amazon C++ Programs Linked List Amazon Linked List Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Dynamic _Cast in C++ Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 25851, "s": 25823, "text": "\n30 Dec, 2021" }, { "code": null, "e": 26026, "s": 25851, "text": "Given a linked list, rearrange it such that the converted list should be of the form a < b > c < d > e < f ... where a, b, c... are consecutive data nodes of the linked list." }, { "code": null, "e": 26037, "s": 26026, "text": "Examples: " }, { "code": null, "e": 26277, "s": 26037, "text": "Input: 1->2->3->4\nOutput: 1->3->2->4 \nExplanation: 1 and 3 should come first before 2 and 4 in\n zig-zag fashion, So resultant linked-list \n will be 1->3->2->4. \n\nInput: 11->15->20->5->10\nOutput: 11->20->5->15->10 " }, { "code": null, "e": 26472, "s": 26277, "text": "A simple approach to do this is to sort the linked list using merge sort and then swap alternate, but that requires O(n Log n) time complexity. Here n is a number of elements in the linked list." }, { "code": null, "e": 26802, "s": 26472, "text": "An efficient approach that requires O(n) time is, using a single scan similar to bubble sort and then maintain a flag for representing which order () currently we are. If the current two elements are not in that order then swap those elements otherwise not. Please refer to this for a detailed explanation of the swapping order. " }, { "code": null, "e": 26806, "s": 26802, "text": "C++" }, { "code": "// C++ program to arrange linked// list in zigzag fashion#include <bits/stdc++.h>using namespace std; // Link list Node struct Node { int data; struct Node* next;}; // This function distributes the// Node in zigzag fashionvoid zigZagList(Node* head){ // If flag is true, then next // node should be greater // in the desired output. bool flag = true; // Traverse linked list starting // from head. Node* current = head; while (current->next != NULL) { // \"<\" relation expected if (flag) { /* If we have a situation like A > B > C where A, B and C are consecutive Nodes in list we get A > B < C by swapping B and C */ if (current->data > current->next->data) swap(current->data, current->next->data); } // \">\" relation expected else { /* If we have a situation like A < B < C where A, B and C are consecutive Nodes in list we get A < C > B by swapping B and C */ if (current->data < current->next->data) swap(current->data, current->next->data); } current = current->next; // flip flag for reverse checking flag = !flag; }} // UTILITY FUNCTIONS // Function to push a Node void push(Node** head_ref, int new_data){ // Allocate Node struct Node* new_Node = new Node; // Put in the data new_Node->data = new_data; // Link the old list off the // new Node new_Node->next = (*head_ref); // Move the head to point to // the new Node (*head_ref) = new_Node;} // Function to print linked list void printList(struct Node* Node){ while (Node != NULL) { printf(\"%d->\", Node->data); Node = Node->next; } printf(\"NULL\");} // Driver codeint main(void){ // Start with the empty list struct Node* head = NULL; // create a list 4 -> 3 -> 7 -> // 8 -> 6 -> 2 -> 1 // answer should be -> 3 7 4 // 8 2 6 1 push(&head, 1); push(&head, 2); push(&head, 6); push(&head, 8); push(&head, 7); push(&head, 3); push(&head, 4); printf(\"Given linked list \"); printList(head); zigZagList(head); printf(\"Zig Zag Linked list \"); printList(head); return (0);}", "e": 29271, "s": 26806, "text": null }, { "code": null, "e": 29279, "s": 29271, "text": "Output:" }, { "code": null, "e": 29371, "s": 29279, "text": "Given linked list \n4->3->7->8->6->2->1->NULL\nZig Zag Linked list \n3->7->4->8->2->6->1->NULL" }, { "code": null, "e": 29465, "s": 29371, "text": "Please refer complete article on Rearrange a Linked List in Zig-Zag fashion for more details!" }, { "code": null, "e": 29472, "s": 29465, "text": "Amazon" }, { "code": null, "e": 29485, "s": 29472, "text": "C++ Programs" }, { "code": null, "e": 29497, "s": 29485, "text": "Linked List" }, { "code": null, "e": 29504, "s": 29497, "text": "Amazon" }, { "code": null, "e": 29516, "s": 29504, "text": "Linked List" }, { "code": null, "e": 29614, "s": 29516, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29655, "s": 29614, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 29714, "s": 29655, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 29735, "s": 29714, "text": "Const keyword in C++" }, { "code": null, "e": 29747, "s": 29735, "text": "cout in C++" }, { "code": null, "e": 29768, "s": 29747, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 29803, "s": 29768, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 29842, "s": 29803, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 29864, "s": 29842, "text": "Reverse a linked list" }, { "code": null, "e": 29912, "s": 29864, "text": "Stack Data Structure (Introduction and Program)" } ]
GATE | GATE-CS-2014-(Set-1) | Question 21 - GeeksforGeeks
28 Jun, 2021 Consider a rooted Binary tree represented using pointers. The best upper bound on the time required to determine the number of subtrees having having exactly 4 nodes O(na Logn b). Then the value of a + 10b is ________(A) 1(B) 11(C) 12(D) 21Answer: (A)Explanation: We can find the subtree with 4 nodes in O(n) time. Following can be a simple approach.1) Traverse the tree in bottom up manner and find size of subtree rooted with current node2) If size becomes 4, then print the current node. Following is C implementation #include<stdio.h>#include<stdlib.h> struct Node{ int data; struct Node *left, *right;}; // A utility function to create a new Binary Tree Nodestruct Node *newNode(int item){ struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); temp->data = item; temp->left = temp->right = NULL; return temp;} int print4Subtree(struct Node *root){ if (root == NULL) return 0; int l = print4Subtree(root->left); int r = print4Subtree(root->right); if ((l + r + 1) == 4) printf("%d ", root->data); return (l + r + 1);} // Driver Program to test above functionsint main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); print4Subtree(root); return 0;} Quiz of this Question GATE-CS-2014-(Set-1) GATE-GATE-CS-2014-(Set-1) GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25757, "s": 25729, "text": "\n28 Jun, 2021" }, { "code": null, "e": 26248, "s": 25757, "text": "Consider a rooted Binary tree represented using pointers. The best upper bound on the time required to determine the number of subtrees having having exactly 4 nodes O(na Logn b). Then the value of a + 10b is ________(A) 1(B) 11(C) 12(D) 21Answer: (A)Explanation: We can find the subtree with 4 nodes in O(n) time. Following can be a simple approach.1) Traverse the tree in bottom up manner and find size of subtree rooted with current node2) If size becomes 4, then print the current node." }, { "code": null, "e": 26278, "s": 26248, "text": "Following is C implementation" }, { "code": "#include<stdio.h>#include<stdlib.h> struct Node{ int data; struct Node *left, *right;}; // A utility function to create a new Binary Tree Nodestruct Node *newNode(int item){ struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); temp->data = item; temp->left = temp->right = NULL; return temp;} int print4Subtree(struct Node *root){ if (root == NULL) return 0; int l = print4Subtree(root->left); int r = print4Subtree(root->right); if ((l + r + 1) == 4) printf(\"%d \", root->data); return (l + r + 1);} // Driver Program to test above functionsint main(){ struct Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); print4Subtree(root); return 0;}", "e": 27210, "s": 26278, "text": null }, { "code": null, "e": 27232, "s": 27210, "text": "Quiz of this Question" }, { "code": null, "e": 27253, "s": 27232, "text": "GATE-CS-2014-(Set-1)" }, { "code": null, "e": 27279, "s": 27253, "text": "GATE-GATE-CS-2014-(Set-1)" }, { "code": null, "e": 27284, "s": 27279, "text": "GATE" }, { "code": null, "e": 27382, "s": 27284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27416, "s": 27382, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 27450, "s": 27416, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 27484, "s": 27450, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 27517, "s": 27484, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 27553, "s": 27517, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 27589, "s": 27553, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 27623, "s": 27589, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 27657, "s": 27623, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 27691, "s": 27657, "text": "GATE | GATE-CS-2009 | Question 38" } ]
Control Statements Usage - GeeksforGeeks
13 May, 2022 Continue StatementIt returns the control to the beginning of the loop. # Prints all letters except 'e' and 's'for letter in 'geeksforgeeks': if letter == 'e' or letter == 's': continue print 'Current Letter :', letter var = 10 Output: Current Letter : g Current Letter : k Current Letter : f Current Letter : o Current Letter : r Current Letter : g Current Letter : k Break StatementIt brings control out of the loop for letter in 'geeksforgeeks': # break the loop as soon it sees 'e' # or 's' if letter == 'e' or letter == 's': break print 'Current Letter :', letter Output: Current Letter : e Pass StatementWe use pass statement to write empty loops. Pass is also used for empty control statement, function and classes. # An empty loopfor letter in 'geeksforgeeks': passprint 'Last Letter :', letter Output: Last Letter : s Exercise:How to print a list in reverse order (from last to first item) using while and for in loops. Python School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Read a file line by line in Python Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects Interfaces in Java
[ { "code": null, "e": 24953, "s": 24925, "text": "\n13 May, 2022" }, { "code": null, "e": 25024, "s": 24953, "text": "Continue StatementIt returns the control to the beginning of the loop." }, { "code": "# Prints all letters except 'e' and 's'for letter in 'geeksforgeeks': if letter == 'e' or letter == 's': continue print 'Current Letter :', letter var = 10", "e": 25198, "s": 25024, "text": null }, { "code": null, "e": 25206, "s": 25198, "text": "Output:" }, { "code": null, "e": 25340, "s": 25206, "text": "Current Letter : g\nCurrent Letter : k\nCurrent Letter : f\nCurrent Letter : o\nCurrent Letter : r\nCurrent Letter : g\nCurrent Letter : k\n" }, { "code": null, "e": 25389, "s": 25340, "text": "Break StatementIt brings control out of the loop" }, { "code": "for letter in 'geeksforgeeks': # break the loop as soon it sees 'e' # or 's' if letter == 'e' or letter == 's': break print 'Current Letter :', letter", "e": 25562, "s": 25389, "text": null }, { "code": null, "e": 25570, "s": 25562, "text": "Output:" }, { "code": null, "e": 25589, "s": 25570, "text": "Current Letter : e" }, { "code": null, "e": 25716, "s": 25589, "text": "Pass StatementWe use pass statement to write empty loops. Pass is also used for empty control statement, function and classes." }, { "code": "# An empty loopfor letter in 'geeksforgeeks': passprint 'Last Letter :', letter", "e": 25799, "s": 25716, "text": null }, { "code": null, "e": 25807, "s": 25799, "text": "Output:" }, { "code": null, "e": 25823, "s": 25807, "text": "Last Letter : s" }, { "code": null, "e": 25925, "s": 25823, "text": "Exercise:How to print a list in reverse order (from last to first item) using while and for in loops." }, { "code": null, "e": 25932, "s": 25925, "text": "Python" }, { "code": null, "e": 25951, "s": 25932, "text": "School Programming" }, { "code": null, "e": 26049, "s": 25951, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26077, "s": 26049, "text": "Read JSON file using Python" }, { "code": null, "e": 26127, "s": 26077, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 26149, "s": 26127, "text": "Python map() function" }, { "code": null, "e": 26193, "s": 26149, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 26228, "s": 26193, "text": "Read a file line by line in Python" }, { "code": null, "e": 26244, "s": 26228, "text": "Arrays in C/C++" }, { "code": null, "e": 26263, "s": 26244, "text": "Inheritance in C++" }, { "code": null, "e": 26288, "s": 26263, "text": "Reverse a string in Java" }, { "code": null, "e": 26312, "s": 26288, "text": "C++ Classes and Objects" } ]
Space and time efficient Binomial Coefficient - GeeksforGeeks
17 Jan, 2022 Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k). Example: Input: n = 4 and k = 2 Output: 6 Explanation: 4 C 2 is 4!/(2!*2!) = 6 Input: n = 5 and k = 2 Output: 10 Explanation: 5 C 2 is 5!/(3!*2!) = 20 We have discussed a O(n*k) time and O(k) extra space algorithm in this post. The value of C(n, k) can be calculated in O(k) time and O(1) extra space. Solution: C(n, k) = n! / (n-k)! * k! = [n * (n-1) *....* 1] / [ ( (n-k) * (n-k-1) * .... * 1) * ( k * (k-1) * .... * 1 ) ] After simplifying, we get C(n, k) = [n * (n-1) * .... * (n-k+1)] / [k * (k-1) * .... * 1] Also, C(n, k) = C(n, n-k) // r can be changed to n-r if r > n-r Change r to n-r if r is greater than n-r. and create a variable to store the answer.Run a loop from 0 to r-1In every iteration update ans as (ans*(n-i))/(i+1) where i is the loop counter.So the answer will be equal to ((n/1)*((n-1)/2)*...*((n-r+1)/r!) which is equal to nCr. Change r to n-r if r is greater than n-r. and create a variable to store the answer. Run a loop from 0 to r-1 In every iteration update ans as (ans*(n-i))/(i+1) where i is the loop counter. So the answer will be equal to ((n/1)*((n-1)/2)*...*((n-r+1)/r!) which is equal to nCr. Following implementation uses above formula to calculate C(n, k). C++ C Java Python3 C# PHP Javascript // Program to calculate C(n, k)#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // Driver Codeint main(){ int n = 8, k = 2; cout << "Value of C(" << n << ", " << k << ") is " << binomialCoeff(n, k); return 0;} // This is code is contributed by rathbhupendra // Program to calculate C(n, k)#include <stdio.h> // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} /* Driver program to test above function*/int main(){ int n = 8, k = 2; printf( "Value of C(%d, %d) is %d ", n, k, binomialCoeff(n, k)); return 0;} // Program to calculate C(n, k) in javaclass BinomialCoefficient { // Returns value of Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } /* Driver program to test above function*/ public static void main(String[] args) { int n = 8; int k = 2; System.out.println("Value of C(" + n + ", " + k + ") " + "is" + " " + binomialCoeff(n, k)); }}// This Code is Contributed by Saket Kumar # Python program to calculate C(n, k) # Returns value of Binomial Coefficient# C(n, k)def binomialCoefficient(n, k): # since C(n, k) = C(n, n - k) if(k > n - k): k = n - k # initialize result res = 1 # Calculate value of # [n * (n-1) *---* (n-k + 1)] / [k * (k-1) *----* 1] for i in range(k): res = res * (n - i) res = res // (i + 1) return res # Driver program to test above functionn = 8k = 2res = binomialCoefficient(n, k)print("Value of C(% d, % d) is % d" %(n, k, res)) # This code is contributed by Aditi Sharma // C# Program to calculate C(n, k)using System; class BinomialCoefficient { // Returns value of Binomial // Coefficient C(n, k) static int binomialCoeff(int n, int k) { int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n * ( n - 1) *---* ( // n - k + 1)] / [k * (k - 1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // Driver Code public static void Main() { int n = 8; int k = 2; Console.Write("Value of C(" + n + ", " + k + ") " + "is" + " " + binomialCoeff(n, k)); }} // This Code is Contributed by// Smitha Dinesh Semwal. <?php// Program to calculate C(n, k)// Returns value of Binomial// Coefficient C(n, k) function binomialCoeff($n, $k){ $res = 1; // Since C(n, k) = C(n, n-k) if ( $k > $n - $k ) $k = $n - $k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / // [k * (k-1) *----* 1] for ($i = 0; $i < $k; ++$i) { $res *= ($n - $i); $res /= ($i + 1); } return $res;} // Driver Code $n = 8; $k = 2; echo " Value of C ($n, $k) is ", binomialCoeff($n, $k); // This code is contributed by ajit.?> <script> // Program to calculate C(n, k) // Returns value of Binomial Coefficient C(n, k)function binomialCoeff(n, k){ let res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (let i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // Driver Code let n = 8; let k = 2; document.write("Value of C(" + n + ", " + k + ") " + "is" + " " + binomialCoeff(n, k)); </script> Output: Value of C(8, 2) is 28 Complexity Analysis: Time Complexity: O(r). A loop has to be run from 0 to r. So, the time complexity is O(r). Auxiliary Space: O(1). As no extra space is required. YouTubeGeeksforGeeks507K subscribersSpace and time efficient Binomial Coefficient | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=d1Mtfs7dWlg" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is compiled by Aashish Barnwal 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. Smitha Dinesh Semwal jit_t rathbhupendra nidhi_biet andrew1234 souravghosh0416 singhalyash8080 amartyaghoshgfg binomial coefficient Dynamic Programming Mathematical Dynamic Programming Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bellman–Ford Algorithm | DP-23 Floyd Warshall Algorithm | DP-16 Matrix Chain Multiplication | DP-8 Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Edit Distance | DP-5 Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples
[ { "code": null, "e": 25839, "s": 25811, "text": "\n17 Jan, 2022" }, { "code": null, "e": 25956, "s": 25839, "text": "Write a function that takes two parameters n and k and returns the value of Binomial Coefficient C(n, k). Example: " }, { "code": null, "e": 26099, "s": 25956, "text": "Input: n = 4 and k = 2\nOutput: 6\nExplanation: 4 C 2 is 4!/(2!*2!) = 6\n\nInput: n = 5 and k = 2\nOutput: 10\nExplanation: 5 C 2 is 5!/(3!*2!) = 20" }, { "code": null, "e": 26251, "s": 26099, "text": "We have discussed a O(n*k) time and O(k) extra space algorithm in this post. The value of C(n, k) can be calculated in O(k) time and O(1) extra space. " }, { "code": null, "e": 26261, "s": 26251, "text": "Solution:" }, { "code": null, "e": 26564, "s": 26261, "text": "C(n, k) \n= n! / (n-k)! * k!\n= [n * (n-1) *....* 1] / [ ( (n-k) * (n-k-1) * .... * 1) * \n ( k * (k-1) * .... * 1 ) ]\nAfter simplifying, we get\nC(n, k) \n= [n * (n-1) * .... * (n-k+1)] / [k * (k-1) * .... * 1]\n\nAlso, C(n, k) = C(n, n-k) \n// r can be changed to n-r if r > n-r " }, { "code": null, "e": 26839, "s": 26564, "text": "Change r to n-r if r is greater than n-r. and create a variable to store the answer.Run a loop from 0 to r-1In every iteration update ans as (ans*(n-i))/(i+1) where i is the loop counter.So the answer will be equal to ((n/1)*((n-1)/2)*...*((n-r+1)/r!) which is equal to nCr." }, { "code": null, "e": 26924, "s": 26839, "text": "Change r to n-r if r is greater than n-r. and create a variable to store the answer." }, { "code": null, "e": 26949, "s": 26924, "text": "Run a loop from 0 to r-1" }, { "code": null, "e": 27029, "s": 26949, "text": "In every iteration update ans as (ans*(n-i))/(i+1) where i is the loop counter." }, { "code": null, "e": 27117, "s": 27029, "text": "So the answer will be equal to ((n/1)*((n-1)/2)*...*((n-r+1)/r!) which is equal to nCr." }, { "code": null, "e": 27185, "s": 27117, "text": "Following implementation uses above formula to calculate C(n, k). " }, { "code": null, "e": 27189, "s": 27185, "text": "C++" }, { "code": null, "e": 27191, "s": 27189, "text": "C" }, { "code": null, "e": 27196, "s": 27191, "text": "Java" }, { "code": null, "e": 27204, "s": 27196, "text": "Python3" }, { "code": null, "e": 27207, "s": 27204, "text": "C#" }, { "code": null, "e": 27211, "s": 27207, "text": "PHP" }, { "code": null, "e": 27222, "s": 27211, "text": "Javascript" }, { "code": "// Program to calculate C(n, k)#include <bits/stdc++.h>using namespace std; // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // Driver Codeint main(){ int n = 8, k = 2; cout << \"Value of C(\" << n << \", \" << k << \") is \" << binomialCoeff(n, k); return 0;} // This is code is contributed by rathbhupendra", "e": 27841, "s": 27222, "text": null }, { "code": "// Program to calculate C(n, k)#include <stdio.h> // Returns value of Binomial Coefficient C(n, k)int binomialCoeff(int n, int k){ int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} /* Driver program to test above function*/int main(){ int n = 8, k = 2; printf( \"Value of C(%d, %d) is %d \", n, k, binomialCoeff(n, k)); return 0;}", "e": 28410, "s": 27841, "text": null }, { "code": "// Program to calculate C(n, k) in javaclass BinomialCoefficient { // Returns value of Binomial Coefficient C(n, k) static int binomialCoeff(int n, int k) { int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } /* Driver program to test above function*/ public static void main(String[] args) { int n = 8; int k = 2; System.out.println(\"Value of C(\" + n + \", \" + k + \") \" + \"is\" + \" \" + binomialCoeff(n, k)); }}// This Code is Contributed by Saket Kumar", "e": 29220, "s": 28410, "text": null }, { "code": "# Python program to calculate C(n, k) # Returns value of Binomial Coefficient# C(n, k)def binomialCoefficient(n, k): # since C(n, k) = C(n, n - k) if(k > n - k): k = n - k # initialize result res = 1 # Calculate value of # [n * (n-1) *---* (n-k + 1)] / [k * (k-1) *----* 1] for i in range(k): res = res * (n - i) res = res // (i + 1) return res # Driver program to test above functionn = 8k = 2res = binomialCoefficient(n, k)print(\"Value of C(% d, % d) is % d\" %(n, k, res)) # This code is contributed by Aditi Sharma", "e": 29783, "s": 29220, "text": null }, { "code": "// C# Program to calculate C(n, k)using System; class BinomialCoefficient { // Returns value of Binomial // Coefficient C(n, k) static int binomialCoeff(int n, int k) { int res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of [n * ( n - 1) *---* ( // n - k + 1)] / [k * (k - 1) *----* 1] for (int i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res; } // Driver Code public static void Main() { int n = 8; int k = 2; Console.Write(\"Value of C(\" + n + \", \" + k + \") \" + \"is\" + \" \" + binomialCoeff(n, k)); }} // This Code is Contributed by// Smitha Dinesh Semwal.", "e": 30576, "s": 29783, "text": null }, { "code": "<?php// Program to calculate C(n, k)// Returns value of Binomial// Coefficient C(n, k) function binomialCoeff($n, $k){ $res = 1; // Since C(n, k) = C(n, n-k) if ( $k > $n - $k ) $k = $n - $k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / // [k * (k-1) *----* 1] for ($i = 0; $i < $k; ++$i) { $res *= ($n - $i); $res /= ($i + 1); } return $res;} // Driver Code $n = 8; $k = 2; echo \" Value of C ($n, $k) is \", binomialCoeff($n, $k); // This code is contributed by ajit.?>", "e": 31133, "s": 30576, "text": null }, { "code": "<script> // Program to calculate C(n, k) // Returns value of Binomial Coefficient C(n, k)function binomialCoeff(n, k){ let res = 1; // Since C(n, k) = C(n, n-k) if (k > n - k) k = n - k; // Calculate value of // [n * (n-1) *---* (n-k+1)] / [k * (k-1) *----* 1] for (let i = 0; i < k; ++i) { res *= (n - i); res /= (i + 1); } return res;} // Driver Code let n = 8; let k = 2; document.write(\"Value of C(\" + n + \", \" + k + \") \" + \"is\" + \" \" + binomialCoeff(n, k)); </script>", "e": 31699, "s": 31133, "text": null }, { "code": null, "e": 31708, "s": 31699, "text": "Output: " }, { "code": null, "e": 31731, "s": 31708, "text": "Value of C(8, 2) is 28" }, { "code": null, "e": 31753, "s": 31731, "text": "Complexity Analysis: " }, { "code": null, "e": 31843, "s": 31753, "text": "Time Complexity: O(r). A loop has to be run from 0 to r. So, the time complexity is O(r)." }, { "code": null, "e": 31897, "s": 31843, "text": "Auxiliary Space: O(1). As no extra space is required." }, { "code": null, "e": 32741, "s": 31897, "text": "YouTubeGeeksforGeeks507K subscribersSpace and time efficient Binomial Coefficient | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:56•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=d1Mtfs7dWlg\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 32947, "s": 32741, "text": "This article is compiled by Aashish Barnwal 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": 32968, "s": 32947, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 32974, "s": 32968, "text": "jit_t" }, { "code": null, "e": 32988, "s": 32974, "text": "rathbhupendra" }, { "code": null, "e": 32999, "s": 32988, "text": "nidhi_biet" }, { "code": null, "e": 33010, "s": 32999, "text": "andrew1234" }, { "code": null, "e": 33026, "s": 33010, "text": "souravghosh0416" }, { "code": null, "e": 33042, "s": 33026, "text": "singhalyash8080" }, { "code": null, "e": 33058, "s": 33042, "text": "amartyaghoshgfg" }, { "code": null, "e": 33079, "s": 33058, "text": "binomial coefficient" }, { "code": null, "e": 33099, "s": 33079, "text": "Dynamic Programming" }, { "code": null, "e": 33112, "s": 33099, "text": "Mathematical" }, { "code": null, "e": 33132, "s": 33112, "text": "Dynamic Programming" }, { "code": null, "e": 33145, "s": 33132, "text": "Mathematical" }, { "code": null, "e": 33243, "s": 33145, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33274, "s": 33243, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 33307, "s": 33274, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 33342, "s": 33307, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 33410, "s": 33342, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 33431, "s": 33410, "text": "Edit Distance | DP-5" }, { "code": null, "e": 33491, "s": 33431, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 33506, "s": 33491, "text": "C++ Data Types" }, { "code": null, "e": 33549, "s": 33506, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 33573, "s": 33549, "text": "Merge two sorted arrays" } ]
How to Truncate a File in Golang? - GeeksforGeeks
23 Mar, 2020 In Go language, you are allowed to truncate the size of the file with the help of the Truncate() function. This function is used to truncate the size of the given file in the specified size. If the given file is a symbolic link, then it changes the size of the link’s target. If this method throws an error, then it will be of type *PathError. It is defined under the os package so, you have to import os package in your program for accessing Truncate() function. Suppose if the truncate file if of 100 bytes and the original file is less than 100 bytes, then the original content remains at the beginning and the remaining space is filled with the null bytes. And if the original file is greater than 100 bytes, then the truncated file lost content after 100 bytes. If you pass 0 in the Truncate() function, then you will get an empty file. Syntax: func Truncate(name string, size int64) error Example 1: // Golang program to illustrate how to// truncate the size of the given filepackage main import ( "log" "os") var ( myfile *os.FileInfo e error) func main() { // Truncate the size of the // given file to 200 bytes // Using Truncate() function err := os.Truncate("gfg.txt", 200) if err != nil { log.Fatal(err) }} Output: Before: After: Example 2: // Golang program to illustrate how to// truncate the size of the given filepackage main import ( "log" "os") var ( myfile *os.FileInfo e error) func main() { // Truncate the size of the given // file to 0 bytes or empty file // Using Truncate() function err := os.Truncate("gfg.txt",0) if err != nil { log.Fatal(err) }} Output: Before: After: Example 3: // Golang program to illustrate how to // truncate the size of the given filepackage main import ( "log" "os") var ( myfile *os.FileInfo e error) func main() { // Truncate the size of the // given file to 300 bytes // Using Truncate() function err := os.Truncate("/Users/anki/Documents/new_folder/bingo.txt", 300) if err != nil { log.Fatal(err) }} Output: Before: After: Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language How to Parse JSON in Golang? Strings in Golang Time Durations in Golang Structures in Golang How to iterate over an Array using for loop in Golang? Rune in Golang Loops in Go Language Defer Keyword in Golang Class and Object in Golang
[ { "code": null, "e": 25703, "s": 25675, "text": "\n23 Mar, 2020" }, { "code": null, "e": 25894, "s": 25703, "text": "In Go language, you are allowed to truncate the size of the file with the help of the Truncate() function. This function is used to truncate the size of the given file in the specified size." }, { "code": null, "e": 25979, "s": 25894, "text": "If the given file is a symbolic link, then it changes the size of the link’s target." }, { "code": null, "e": 26047, "s": 25979, "text": "If this method throws an error, then it will be of type *PathError." }, { "code": null, "e": 26167, "s": 26047, "text": "It is defined under the os package so, you have to import os package in your program for accessing Truncate() function." }, { "code": null, "e": 26470, "s": 26167, "text": "Suppose if the truncate file if of 100 bytes and the original file is less than 100 bytes, then the original content remains at the beginning and the remaining space is filled with the null bytes. And if the original file is greater than 100 bytes, then the truncated file lost content after 100 bytes." }, { "code": null, "e": 26545, "s": 26470, "text": "If you pass 0 in the Truncate() function, then you will get an empty file." }, { "code": null, "e": 26553, "s": 26545, "text": "Syntax:" }, { "code": null, "e": 26598, "s": 26553, "text": "func Truncate(name string, size int64) error" }, { "code": null, "e": 26609, "s": 26598, "text": "Example 1:" }, { "code": "// Golang program to illustrate how to// truncate the size of the given filepackage main import ( \"log\" \"os\") var ( myfile *os.FileInfo e error) func main() { // Truncate the size of the // given file to 200 bytes // Using Truncate() function err := os.Truncate(\"gfg.txt\", 200) if err != nil { log.Fatal(err) }}", "e": 26964, "s": 26609, "text": null }, { "code": null, "e": 26972, "s": 26964, "text": "Output:" }, { "code": null, "e": 26980, "s": 26972, "text": "Before:" }, { "code": null, "e": 26987, "s": 26980, "text": "After:" }, { "code": null, "e": 26998, "s": 26987, "text": "Example 2:" }, { "code": "// Golang program to illustrate how to// truncate the size of the given filepackage main import ( \"log\" \"os\") var ( myfile *os.FileInfo e error) func main() { // Truncate the size of the given // file to 0 bytes or empty file // Using Truncate() function err := os.Truncate(\"gfg.txt\",0) if err != nil { log.Fatal(err) }}", "e": 27361, "s": 26998, "text": null }, { "code": null, "e": 27369, "s": 27361, "text": "Output:" }, { "code": null, "e": 27377, "s": 27369, "text": "Before:" }, { "code": null, "e": 27384, "s": 27377, "text": "After:" }, { "code": null, "e": 27395, "s": 27384, "text": "Example 3:" }, { "code": "// Golang program to illustrate how to // truncate the size of the given filepackage main import ( \"log\" \"os\") var ( myfile *os.FileInfo e error) func main() { // Truncate the size of the // given file to 300 bytes // Using Truncate() function err := os.Truncate(\"/Users/anki/Documents/new_folder/bingo.txt\", 300) if err != nil { log.Fatal(err) }}", "e": 27786, "s": 27395, "text": null }, { "code": null, "e": 27794, "s": 27786, "text": "Output:" }, { "code": null, "e": 27802, "s": 27794, "text": "Before:" }, { "code": null, "e": 27809, "s": 27802, "text": "After:" }, { "code": null, "e": 27821, "s": 27809, "text": "Go Language" }, { "code": null, "e": 27919, "s": 27821, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27965, "s": 27919, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 27994, "s": 27965, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 28012, "s": 27994, "text": "Strings in Golang" }, { "code": null, "e": 28037, "s": 28012, "text": "Time Durations in Golang" }, { "code": null, "e": 28058, "s": 28037, "text": "Structures in Golang" }, { "code": null, "e": 28113, "s": 28058, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 28128, "s": 28113, "text": "Rune in Golang" }, { "code": null, "e": 28149, "s": 28128, "text": "Loops in Go Language" }, { "code": null, "e": 28173, "s": 28149, "text": "Defer Keyword in Golang" } ]
Count of Subarrays in an array containing numbers from 1 to the length of subarray - GeeksforGeeks
19 Jan, 2022 Given an array arr[] of length N containing all elements from 1 to N, the task is to find the number of sub-arrays that contain numbers from 1 to M, where M is the length of the sub-array. Examples: Input: arr[] = {4, 1, 3, 2, 5, 6} Output: 5 Explanation: Desired Sub-arrays = { {4, 1, 3, 2}, {1}, {1, 3, 2}, {4, 1, 3, 2, 5}, {4, 1, 3, 2, 5, 6} } Count(Sub-arrays) = 5 Input: arr[] = {3, 2, 4, 1} Output: 2 Explanation: Desired Sub-arrays = { {1}, {3, 2, 4, 1} } Count(Sub-arrays) = 2 Naive Approach: Generate all subarrays of the array and check for each subarray that it contains each element 1 to the length of the subarray. Efficient Approach: Create a vector that maps each element of the array with its index in sorted order. Now iterate over this vector and check whether the difference of maximum and minimum index till the ith element is less than the number of elements iterated till now, which is the value of i itself. Below is the implementation of the above approach C++ Java Python3 C# Javascript // C++ Implementation to Count the no. of// Sub-arrays which contains all elements// from 1 to length of subarray #include <bits/stdc++.h>using namespace std; // Function to count the number// Sub-arrays which contains all elements// 1 to length of subarrayint countOfSubarrays(int* arr, int n){ int count = 0; vector<int> v(n + 1); // Map all elements of array with their index for (int i = 0; i < n; i++) v[arr[i]] = i; // Set the max and min index equal to the // min and max value of integer respectively. int maximum = INT_MIN; int minimum = INT_MAX; for (int i = 1; i <= n; i++) { // Update the value of maximum index maximum = max(maximum, v[i]); // Update the value of minimum index minimum = min(minimum, v[i]); // Increase the counter if difference of // max. and min. index is less than the // elements iterated till now if (maximum - minimum < i) count = count + 1; } return count;} // Driver Functionint main(){ int arr[] = { 4, 1, 3, 2, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countOfSubarrays(arr, n) << endl; return 0;} // Java Implementation to Count the no. of// Sub-arrays which contains all elements// from 1 to length of subarrayclass GFG{ // Function to count the number// Sub-arrays which contains all elements// 1 to length of subarraystatic int countOfSubarrays(int []arr, int n){ int count = 0; int []v = new int[n + 1]; // Map all elements of array with their index for (int i = 0; i < n; i++) v[arr[i]] = i; // Set the max and min index equal to the // min and max value of integer respectively. int maximum = Integer.MIN_VALUE; int minimum = Integer.MAX_VALUE; for (int i = 1; i <= n; i++) { // Update the value of maximum index maximum = Math.max(maximum, v[i]); // Update the value of minimum index minimum = Math.min(minimum, v[i]); // Increase the counter if difference of // max. and min. index is less than the // elements iterated till now if (maximum - minimum < i) count = count + 1; } return count;} // Driver codepublic static void main(String[] args){ int arr[] = { 4, 1, 3, 2, 5, 6 }; int n = arr.length; System.out.print(countOfSubarrays(arr, n) +"\n");}} // This code is contributed by PrinciRaj1992 # Python3 Implementation to Count the no. of# Sub-arrays which contains all elements# from 1 to length of subarrayimport sys INT_MAX = sys.maxsize;INT_MIN = -(sys.maxsize - 1); # Function to count the number# Sub-arrays which contains all elements# 1 to length of subarraydef countOfSubarrays(arr, n) : count = 0; v = [0]*(n + 1); # Map all elements of array with their index for i in range(n) : v[arr[i]] = i; # Set the max and min index equal to the # min and max value of integer respectively. maximum = INT_MIN; minimum = INT_MAX; for i in range(1, n + 1) : # Update the value of maximum index maximum = max(maximum, v[i]); # Update the value of minimum index minimum = min(minimum, v[i]); # Increase the counter if difference of # max. and min. index is less than the # elements iterated till now if (maximum - minimum < i) : count = count + 1; return count; # Driver codeif __name__ == "__main__" : arr = [ 4, 1, 3, 2, 5, 6 ]; n = len(arr); print(countOfSubarrays(arr, n)); # This code is contributed by AnkitRai01 // C# Implementation to Count the no. of// Sub-arrays which contains all elements// from 1 to length of subarrayusing System; class GFG{ // Function to count the number// Sub-arrays which contains all elements// 1 to length of subarraystatic int countOfSubarrays(int []arr, int n){ int count = 0; int []v = new int[n + 1]; // Map all elements of array with their index for (int i = 0; i < n; i++) v[arr[i]] = i; // Set the max and min index equal to the // min and max value of integer respectively. int maximum = int.MinValue; int minimum = int.MaxValue; for (int i = 1; i <= n; i++) { // Update the value of maximum index maximum = Math.Max(maximum, v[i]); // Update the value of minimum index minimum = Math.Min(minimum, v[i]); // Increase the counter if difference of // max. and min. index is less than the // elements iterated till now if (maximum - minimum < i) count = count + 1; } return count;} // Driver codepublic static void Main(String[] args){ int []arr = { 4, 1, 3, 2, 5, 6 }; int n = arr.Length; Console.Write(countOfSubarrays(arr, n) +"\n");}} // This code is contributed by PrinciRaj1992 <script> // Javascript Implementation to Count the no. of// Sub-arrays which contains all elements// from 1 to length of subarray // Function to count the number// Sub-arrays which contains all elements// 1 to length of subarrayfunction countOfSubarrays(arr, n){ var count = 0; var v = Array(n + 1); // Map all elements of array with their index for (var i = 0; i < n; i++) v[arr[i]] = i; // Set the max and min index equal to the // min and max value of integer respectively. var maximum = -1000000000; var minimum = 10000000000; for (var i = 1; i <= n; i++) { // Update the value of maximum index maximum = Math.max(maximum, v[i]); // Update the value of minimum index minimum = Math.min(minimum, v[i]); // Increase the counter if difference of // max. and min. index is less than the // elements iterated till now if (maximum - minimum < i) count = count + 1; } return count;} // Driver Functionvar arr = [4, 1, 3, 2, 5, 6 ];var n = arr.length;document.write( countOfSubarrays(arr, n) ); // This code is contributed by importantly.</script> 5 Time Complexity: O(N) ankthon princiraj1992 importantly khushboogoyal499 sumitgumber28 subarray Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Linear Search Linked List vs Array Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Python | Using 2D arrays/lists the right way Search an element in a sorted and rotated array
[ { "code": null, "e": 26607, "s": 26579, "text": "\n19 Jan, 2022" }, { "code": null, "e": 26796, "s": 26607, "text": "Given an array arr[] of length N containing all elements from 1 to N, the task is to find the number of sub-arrays that contain numbers from 1 to M, where M is the length of the sub-array." }, { "code": null, "e": 26807, "s": 26796, "text": "Examples: " }, { "code": null, "e": 26978, "s": 26807, "text": "Input: arr[] = {4, 1, 3, 2, 5, 6} Output: 5 Explanation: Desired Sub-arrays = { {4, 1, 3, 2}, {1}, {1, 3, 2}, {4, 1, 3, 2, 5}, {4, 1, 3, 2, 5, 6} } Count(Sub-arrays) = 5 " }, { "code": null, "e": 27096, "s": 26978, "text": "Input: arr[] = {3, 2, 4, 1} Output: 2 Explanation: Desired Sub-arrays = { {1}, {3, 2, 4, 1} } Count(Sub-arrays) = 2 " }, { "code": null, "e": 27239, "s": 27096, "text": "Naive Approach: Generate all subarrays of the array and check for each subarray that it contains each element 1 to the length of the subarray." }, { "code": null, "e": 27542, "s": 27239, "text": "Efficient Approach: Create a vector that maps each element of the array with its index in sorted order. Now iterate over this vector and check whether the difference of maximum and minimum index till the ith element is less than the number of elements iterated till now, which is the value of i itself." }, { "code": null, "e": 27593, "s": 27542, "text": "Below is the implementation of the above approach " }, { "code": null, "e": 27597, "s": 27593, "text": "C++" }, { "code": null, "e": 27602, "s": 27597, "text": "Java" }, { "code": null, "e": 27610, "s": 27602, "text": "Python3" }, { "code": null, "e": 27613, "s": 27610, "text": "C#" }, { "code": null, "e": 27624, "s": 27613, "text": "Javascript" }, { "code": "// C++ Implementation to Count the no. of// Sub-arrays which contains all elements// from 1 to length of subarray #include <bits/stdc++.h>using namespace std; // Function to count the number// Sub-arrays which contains all elements// 1 to length of subarrayint countOfSubarrays(int* arr, int n){ int count = 0; vector<int> v(n + 1); // Map all elements of array with their index for (int i = 0; i < n; i++) v[arr[i]] = i; // Set the max and min index equal to the // min and max value of integer respectively. int maximum = INT_MIN; int minimum = INT_MAX; for (int i = 1; i <= n; i++) { // Update the value of maximum index maximum = max(maximum, v[i]); // Update the value of minimum index minimum = min(minimum, v[i]); // Increase the counter if difference of // max. and min. index is less than the // elements iterated till now if (maximum - minimum < i) count = count + 1; } return count;} // Driver Functionint main(){ int arr[] = { 4, 1, 3, 2, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); cout << countOfSubarrays(arr, n) << endl; return 0;}", "e": 28800, "s": 27624, "text": null }, { "code": "// Java Implementation to Count the no. of// Sub-arrays which contains all elements// from 1 to length of subarrayclass GFG{ // Function to count the number// Sub-arrays which contains all elements// 1 to length of subarraystatic int countOfSubarrays(int []arr, int n){ int count = 0; int []v = new int[n + 1]; // Map all elements of array with their index for (int i = 0; i < n; i++) v[arr[i]] = i; // Set the max and min index equal to the // min and max value of integer respectively. int maximum = Integer.MIN_VALUE; int minimum = Integer.MAX_VALUE; for (int i = 1; i <= n; i++) { // Update the value of maximum index maximum = Math.max(maximum, v[i]); // Update the value of minimum index minimum = Math.min(minimum, v[i]); // Increase the counter if difference of // max. and min. index is less than the // elements iterated till now if (maximum - minimum < i) count = count + 1; } return count;} // Driver codepublic static void main(String[] args){ int arr[] = { 4, 1, 3, 2, 5, 6 }; int n = arr.length; System.out.print(countOfSubarrays(arr, n) +\"\\n\");}} // This code is contributed by PrinciRaj1992", "e": 30034, "s": 28800, "text": null }, { "code": "# Python3 Implementation to Count the no. of# Sub-arrays which contains all elements# from 1 to length of subarrayimport sys INT_MAX = sys.maxsize;INT_MIN = -(sys.maxsize - 1); # Function to count the number# Sub-arrays which contains all elements# 1 to length of subarraydef countOfSubarrays(arr, n) : count = 0; v = [0]*(n + 1); # Map all elements of array with their index for i in range(n) : v[arr[i]] = i; # Set the max and min index equal to the # min and max value of integer respectively. maximum = INT_MIN; minimum = INT_MAX; for i in range(1, n + 1) : # Update the value of maximum index maximum = max(maximum, v[i]); # Update the value of minimum index minimum = min(minimum, v[i]); # Increase the counter if difference of # max. and min. index is less than the # elements iterated till now if (maximum - minimum < i) : count = count + 1; return count; # Driver codeif __name__ == \"__main__\" : arr = [ 4, 1, 3, 2, 5, 6 ]; n = len(arr); print(countOfSubarrays(arr, n)); # This code is contributed by AnkitRai01", "e": 31177, "s": 30034, "text": null }, { "code": "// C# Implementation to Count the no. of// Sub-arrays which contains all elements// from 1 to length of subarrayusing System; class GFG{ // Function to count the number// Sub-arrays which contains all elements// 1 to length of subarraystatic int countOfSubarrays(int []arr, int n){ int count = 0; int []v = new int[n + 1]; // Map all elements of array with their index for (int i = 0; i < n; i++) v[arr[i]] = i; // Set the max and min index equal to the // min and max value of integer respectively. int maximum = int.MinValue; int minimum = int.MaxValue; for (int i = 1; i <= n; i++) { // Update the value of maximum index maximum = Math.Max(maximum, v[i]); // Update the value of minimum index minimum = Math.Min(minimum, v[i]); // Increase the counter if difference of // max. and min. index is less than the // elements iterated till now if (maximum - minimum < i) count = count + 1; } return count;} // Driver codepublic static void Main(String[] args){ int []arr = { 4, 1, 3, 2, 5, 6 }; int n = arr.Length; Console.Write(countOfSubarrays(arr, n) +\"\\n\");}} // This code is contributed by PrinciRaj1992", "e": 32410, "s": 31177, "text": null }, { "code": "<script> // Javascript Implementation to Count the no. of// Sub-arrays which contains all elements// from 1 to length of subarray // Function to count the number// Sub-arrays which contains all elements// 1 to length of subarrayfunction countOfSubarrays(arr, n){ var count = 0; var v = Array(n + 1); // Map all elements of array with their index for (var i = 0; i < n; i++) v[arr[i]] = i; // Set the max and min index equal to the // min and max value of integer respectively. var maximum = -1000000000; var minimum = 10000000000; for (var i = 1; i <= n; i++) { // Update the value of maximum index maximum = Math.max(maximum, v[i]); // Update the value of minimum index minimum = Math.min(minimum, v[i]); // Increase the counter if difference of // max. and min. index is less than the // elements iterated till now if (maximum - minimum < i) count = count + 1; } return count;} // Driver Functionvar arr = [4, 1, 3, 2, 5, 6 ];var n = arr.length;document.write( countOfSubarrays(arr, n) ); // This code is contributed by importantly.</script>", "e": 33568, "s": 32410, "text": null }, { "code": null, "e": 33570, "s": 33568, "text": "5" }, { "code": null, "e": 33595, "s": 33572, "text": "Time Complexity: O(N) " }, { "code": null, "e": 33603, "s": 33595, "text": "ankthon" }, { "code": null, "e": 33617, "s": 33603, "text": "princiraj1992" }, { "code": null, "e": 33629, "s": 33617, "text": "importantly" }, { "code": null, "e": 33646, "s": 33629, "text": "khushboogoyal499" }, { "code": null, "e": 33660, "s": 33646, "text": "sumitgumber28" }, { "code": null, "e": 33669, "s": 33660, "text": "subarray" }, { "code": null, "e": 33676, "s": 33669, "text": "Arrays" }, { "code": null, "e": 33683, "s": 33676, "text": "Arrays" }, { "code": null, "e": 33781, "s": 33683, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33849, "s": 33781, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 33893, "s": 33849, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33941, "s": 33893, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 33964, "s": 33941, "text": "Introduction to Arrays" }, { "code": null, "e": 33996, "s": 33964, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34010, "s": 33996, "text": "Linear Search" }, { "code": null, "e": 34031, "s": 34010, "text": "Linked List vs Array" }, { "code": null, "e": 34116, "s": 34031, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 34161, "s": 34116, "text": "Python | Using 2D arrays/lists the right way" } ]
Count of natural numbers in range [L, R] which are relatively prime with N - GeeksforGeeks
17 Jun, 2021 Given three integers N, L, and R. The task is to calculate the number of natural numbers in the range [L, R] (both inclusive) which are relatively prime with N. Examples: Input: N = 10, L = 1, R = 25 Output: 10 Explanation: 10 natural numbers (in the range 1 to 25) are relatively prime to 10. They are 1, 3, 7, 9, 11, 13, 17, 19, 21, 23. Input: N = 12, L = 7, R = 38 Output: 11 Explanation: 11 natural numbers (in the range 1 to 38) are relatively prime to 12. They are 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37. Approach: At first, factorize the number N. Thus, find out all the prime factors of N.Store prime factors of the number N in an array.We can determine the total number of natural numbers which are not greater than R and are divisible by prime factors of N.Suppose that the value is y. So, exactly y natural numbers not greater than R have at least a single common divisor with N.So, these y numbers can not be relatively prime to N.Thus, the number of natural number not greater than R which are relatively prime to N will be R – y .Now, similarly we need to find out the number of relatively prime numbers of N which are not greater than L-1.Then, subtract the result for L-1 from the answer for R. At first, factorize the number N. Thus, find out all the prime factors of N. Store prime factors of the number N in an array. We can determine the total number of natural numbers which are not greater than R and are divisible by prime factors of N. Suppose that the value is y. So, exactly y natural numbers not greater than R have at least a single common divisor with N. So, these y numbers can not be relatively prime to N. Thus, the number of natural number not greater than R which are relatively prime to N will be R – y . Now, similarly we need to find out the number of relatively prime numbers of N which are not greater than L-1. Then, subtract the result for L-1 from the answer for R. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ code to count of natural// numbers in range [L, R] which// are relatively prime with N #include <bits/stdc++.h>using namespace std;#define maxN (long long)1000000000000 // container of all the primes// up to sqrt(n)vector<int> prime; // Function to calculate prime// factors of nvoid sieve(long long n){ // run the sieve of Eratosthenes bool check[1000007] = { 0 }; long long i, j; // 0(false) means prime, // 1(true) means not prime check[0] = 1, check[1] = 1, check[2] = 0; // no even number is // prime except for 2 for (i = 4; i <= n; i += 2) check[i] = true; for (i = 3; i * i <= n; i += 2) if (!check[i]) { // all the multiples of each // each prime numbers are // non-prime for (j = i * i; j <= n; j += 2 * i) check[j] = true; } prime.push_back(2); // get all the primes // in prime vector for (int i = 3; i <= n; i += 2) if (!check[i]) prime.push_back(i); return;} // Count the number of numbers// up to m which are divisible// by given prime numberslong long count(long long a[], int n, long long m){ long long parity[3] = { 0 }; // Run from i= 000..0 to i= 111..1 // or check all possible // subsets of the array for (int i = 1; i < (1 << n); i++) { long long mult = 1; for (int j = 0; j < n; j++) if (i & (1 << j)) mult *= a[j]; // take the multiplication // of all the set bits // if the number of set bits // is odd, then add to the // number of multiples parity[__builtin_popcount(i) & 1] += (m / mult); } return parity[1] - parity[0];} // Function calculates all number// not greater than 'm' which are// relatively prime with n.long long countRelPrime( long long n, long long m){ long long a[20]; int i = 0, j = 0; long long pz = prime.size(); while (n != 1 && i < pz) { // if square of the prime number // is greater than 'n', it can't // be a factor of 'n' if ((long long)prime[i] * (long long)prime[i] > n) break; // if prime is a factor of // n then increment count if (n % prime[i] == 0) a[j] = (long long)prime[i], j++; while (n % prime[i] == 0) n /= prime[i]; i++; } if (n != 1) a[j] = n, j++; return m - count(a, j, m);} void countRelPrimeInRange( long long n, long long l, long long r){ sieve(sqrt(maxN)); long long result = countRelPrime(n, r) - countRelPrime(n, l - 1); cout << result << "\n";} // Driver codeint main(){ long long N = 7, L = 3, R = 9; countRelPrimeInRange(N, L, R); return 0;} // Java code to count of natural// numbers in range [L, R] which// are relatively prime with Nimport java.util.*; class GFG{ static int maxN = 100000000; // Container of all the primes// up to sqrt(n)static Vector<Integer> prime = new Vector<Integer>(); // Function to calculate prime// factors of nstatic void sieve(int n){ // Run the sieve of Eratosthenes boolean[] check = new boolean[1000007]; for(int i = 0; i < 1000007; i++) check[i] = false; int i, j; // 0(false) means prime, // 1(true) means not prime check[0] = false; check[1] = true; check[2] = false; // No even number is // prime except for 2 for(i = 4; i <= n; i += 2) check[i] = true; for(i = 3; i * i <= n; i += 2) if (!check[i]) { // All the multiples of each // each prime numbers are // non-prime for(j = i * i; j <= n; j += 2 * i) check[j] = true; } prime.add(2); // Get all the primes // in prime vector for(i = 3; i <= n; i += 2) if (!check[i]) prime.add(i); return;} static int countSetBits(int n){ int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count;} // Count the number of numbers// up to m which are divisible// by given prime numbersstatic int count(int a[], int n, int m){ int[] parity = new int[3]; for(int i = 0; i < 3; i++) parity[i] = 0; // Run from i= 000..0 to i= 111..1 // or check all possible // subsets of the array for(int i = 1; i < (1 << n); i++) { int mult = 1; for(int j = 0; j < n; j++) if ((i & (1 << j)) != 0) mult *= a[j]; // Take the multiplication // of all the set bits // If the number of set bits // is odd, then add to the // number of multiples parity[countSetBits(i) & 1] += (m / mult); } return parity[1] - parity[0];} // Function calculates all number// not greater than 'm' which are// relatively prime with n.static int countRelPrime(int n, int m){ int[] a = new int[20]; int i = 0, j = 0; int pz = prime.size(); while(n != 1 && i < pz) { // If square of the prime number // is greater than 'n', it can't // be a factor of 'n' if ((int)prime.get(i) * (int)prime.get(i) > n) break; // If prime is a factor of // n then increment count if (n % prime.get(i) == 0) { a[j] = (int)prime.get(i); j++; } while (n % prime.get(i) == 0) n /= prime.get(i); i++; } if (n != 1) { a[j] = n; j++; } return m - count(a, j, m);} static void countRelPrimeInRange(int n, int l, int r){ sieve((int)Math.sqrt(maxN)); int result = countRelPrime(n, r) - countRelPrime(n, l - 1); System.out.println(result);} // Driver codepublic static void main(String[] args){ int N = 7, L = 3, R = 9; countRelPrimeInRange(N, L, R);}} // This code is contributed by grand_master # Python3 code to count of natural# numbers in range [L, R] which# are relatively prime with Nfrom math import sqrt, floor maxN = 1000000000000 # Container of all the primes# up to sqrt(n)prime = [] # Function to calculate prime# factors of ndef sieve(n): # Run the sieve of Eratosthenes check = [0] * (1000007) i, j = 0, 0 # 0(false) means prime, # 1(True) means not prime check[0] = 1 check[1] = 1 check[2] = 0 # No even number is # prime except for 2 for i in range(4, n + 1, 2): check[i] = True for i in range(3, n + 1, 2): if i * i > n: break if (not check[i]): # All the multiples of each # each prime numbers are # non-prime for j in range(2 * i, n + 1, 2 * i): check[j] = True prime.append(2) # Get all the primes # in prime vector for i in range(3, n + 1, 2): if (not check[i]): prime.append(i) return # Count the number of numbers# up to m which are divisible# by given prime numbersdef count(a, n, m): parity = [0] * 3 # Run from i = 000..0 to i = 111..1 # or check all possible # subsets of the array for i in range(1, 1 << n): mult = 1 for j in range(n): if (i & (1 << j)): mult *= a[j] # Take the multiplication # of all the set bits # If the number of set bits # is odd, then add to the # number of multiples parity[bin(i).count('1') & 1] += (m // mult) return parity[1] - parity[0] # Function calculates all number# not greater than 'm' which are# relatively prime with n.def countRelPrime(n, m): a = [0] * 20 i = 0 j = 0 pz = len(prime) while (n != 1 and i < pz): # If square of the prime number # is greater than 'n', it can't # be a factor of 'n' if (prime[i] * prime[i] > n): break # If prime is a factor of # n then increment count if (n % prime[i] == 0): a[j] = prime[i] j += 1 while (n % prime[i] == 0): n //= prime[i] i += 1 if (n != 1): a[j] = n j += 1 return m - count(a, j, m) def countRelPrimeInRange(n, l, r): sieve(floor(sqrt(maxN))) result = (countRelPrime(n, r) - countRelPrime(n, l - 1)) print(result) # Driver codeif __name__ == '__main__': N = 7 L = 3 R = 9 countRelPrimeInRange(N, L, R) # This code is contributed by mohit kumar 29 // C# code to count of natural// numbers in range [L, R] which// are relatively prime with Nusing System;using System.Collections.Generic; class GFG{ static int maxN = 100000000; // Container of all the primes// up to sqrt(n)static List<int> prime = new List<int>(); // Function to calculate prime// factors of nstatic void sieve(int n){ // Run the sieve of Eratosthenes bool[] check = new bool[1000007]; for(int I = 0; I < 1000007; I++) check[I] = false; int i, j; // 0(false) means prime, // 1(true) means not prime check[0] = false; check[1] = true; check[2] = false; // No even number is // prime except for 2 for(i = 4; i <= n; i += 2) check[i] = true; for(i = 3; i * i <= n; i += 2) if (!check[i]) { // All the multiples of each // each prime numbers are // non-prime for(j = i * i; j <= n; j += 2 * i) check[j] = true; } prime.Add(2); // Get all the primes // in prime vector for(i = 3; i <= n; i += 2) if (!check[i]) prime.Add(i); return;} static int countSetBits(int n){ int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count;} // Count the number of numbers// up to m which are divisible// by given prime numbersstatic int count(int[] a, int n, int m){ int[] parity = new int[3]; for(int i = 0; i < 3; i++) parity[i] = 0; // Run from i= 000..0 to i= 111..1 // or check all possible // subsets of the array for(int i = 1; i < (1 << n); i++) { int mult = 1; for(int j = 0; j < n; j++) if ((i & (1 << j)) != 0) mult *= a[j]; // Take the multiplication // of all the set bits // If the number of set bits // is odd, then add to the // number of multiples parity[countSetBits(i) & 1] += (m / mult); } return parity[1] - parity[0];} // Function calculates all number// not greater than 'm' which are// relatively prime with n.static int countRelPrime(int n, int m){ int[] a = new int[20]; int i = 0, j = 0; int pz = prime.Count; while (n != 1 && i < pz) { // If square of the prime number // is greater than 'n', it can't // be a factor of 'n' if ((int)prime[i] * (int)prime[i] > n) break; // If prime is a factor of // n then increment count if (n % prime[i] == 0) { a[j] = (int)prime[i]; j++; } while (n % prime[i] == 0) n /= prime[i]; i++; } if (n != 1) { a[j] = n; j++; } return m - count(a, j, m);} static void countRelPrimeInRange(int n, int l, int r){ sieve((int)Math.Sqrt(maxN)); int result = countRelPrime(n, r) - countRelPrime(n, l - 1); Console.WriteLine(result);} // Driver Codestatic void Main(){ int N = 7, L = 3, R = 9; countRelPrimeInRange(N, L, R);}} // This code is contributed by divyeshrabadiya07 <script> // Javascript code to count of natural// numbers in range [L, R] which// are relatively prime with Nlet maxN = 100000000; // Container of all the primes// up to sqrt(n)let prime = []; // Function to calculate prime// factors of nfunction sieve(n){ // Run the sieve of Eratosthenes let check = new Array(1000007); for(let i = 0; i < 1000007; i++) check[i] = false; let i, j; // 0(false) means prime, // 1(true) means not prime check[0] = false; check[1] = true; check[2] = false; // No even number is // prime except for 2 for(i = 4; i <= n; i += 2) check[i] = true; for(i = 3; i * i <= n; i += 2) if (!check[i]) { // All the multiples of each // each prime numbers are // non-prime for(j = i * i; j <= n; j += 2 * i) check[j] = true; } prime.push(2); // Get all the primes // in prime vector for(i = 3; i <= n; i += 2) if (!check[i]) prime.push(i); return;} function countSetBits(n){ let count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count;} // Count the number of numbers// up to m which are divisible// by given prime numbersfunction count(a, n, m){ let parity = new Array(3); for(let i = 0; i < 3; i++) parity[i] = 0; // Run from i= 000..0 to i= 111..1 // or check all possible // subsets of the array for(let i = 1; i < (1 << n); i++) { let mult = 1; for(let j = 0; j < n; j++) if ((i & (1 << j)) != 0) mult *= a[j]; // Take the multiplication // of all the set bits // If the number of set bits // is odd, then add to the // number of multiples parity[countSetBits(i) & 1] += (m / mult); } return parity[1] - parity[0];} // Function calculates all number// not greater than 'm' which are// relatively prime with n.function countRelPrime(n, m){ let a = new Array(20); let i = 0, j = 0; let pz = prime.length; while(n != 1 && i < pz) { // If square of the prime number // is greater than 'n', it can't // be a factor of 'n' if (prime[i] * prime[i] > n) break; // If prime is a factor of // n then increment count if (n % prime[i] == 0) { a[j] = prime[i]; j++; } while (n % prime[i] == 0) n = Math.floor(n/prime[i]); i++; } if (n != 1) { a[j] = n; j++; } return m - count(a, j, m);} function countRelPrimeInRange(n, l, r){ sieve(Math.floor(Math.sqrt(maxN))); let result = countRelPrime(n, r) - countRelPrime(n, l - 1); document.write(result);} // Driver codelet N = 7, L = 3, R = 9; countRelPrimeInRange(N, L, R); // This code is contributed by unknown2108 </script> 6 mohit kumar 29 grand_master divyeshrabadiya07 unknown2108 array-range-queries Maths Natural Numbers number-theory Prime Number Competitive Programming Mathematical number-theory Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Bits manipulation (Important tactics) Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Formatted output in Java Breadth First Traversal ( BFS ) on a 2D array Program for Fibonacci numbers Write a program to print all permutations of a given string C++ Data Types Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 25052, "s": 25024, "text": "\n17 Jun, 2021" }, { "code": null, "e": 25213, "s": 25052, "text": "Given three integers N, L, and R. The task is to calculate the number of natural numbers in the range [L, R] (both inclusive) which are relatively prime with N." }, { "code": null, "e": 25225, "s": 25213, "text": "Examples: " }, { "code": null, "e": 25393, "s": 25225, "text": "Input: N = 10, L = 1, R = 25 Output: 10 Explanation: 10 natural numbers (in the range 1 to 25) are relatively prime to 10. They are 1, 3, 7, 9, 11, 13, 17, 19, 21, 23." }, { "code": null, "e": 25569, "s": 25393, "text": "Input: N = 12, L = 7, R = 38 Output: 11 Explanation: 11 natural numbers (in the range 1 to 38) are relatively prime to 12. They are 7, 11, 13, 17, 19, 23, 25, 29, 31, 35, 37. " }, { "code": null, "e": 25581, "s": 25569, "text": "Approach: " }, { "code": null, "e": 26271, "s": 25581, "text": "At first, factorize the number N. Thus, find out all the prime factors of N.Store prime factors of the number N in an array.We can determine the total number of natural numbers which are not greater than R and are divisible by prime factors of N.Suppose that the value is y. So, exactly y natural numbers not greater than R have at least a single common divisor with N.So, these y numbers can not be relatively prime to N.Thus, the number of natural number not greater than R which are relatively prime to N will be R – y .Now, similarly we need to find out the number of relatively prime numbers of N which are not greater than L-1.Then, subtract the result for L-1 from the answer for R." }, { "code": null, "e": 26348, "s": 26271, "text": "At first, factorize the number N. Thus, find out all the prime factors of N." }, { "code": null, "e": 26397, "s": 26348, "text": "Store prime factors of the number N in an array." }, { "code": null, "e": 26520, "s": 26397, "text": "We can determine the total number of natural numbers which are not greater than R and are divisible by prime factors of N." }, { "code": null, "e": 26644, "s": 26520, "text": "Suppose that the value is y. So, exactly y natural numbers not greater than R have at least a single common divisor with N." }, { "code": null, "e": 26698, "s": 26644, "text": "So, these y numbers can not be relatively prime to N." }, { "code": null, "e": 26800, "s": 26698, "text": "Thus, the number of natural number not greater than R which are relatively prime to N will be R – y ." }, { "code": null, "e": 26911, "s": 26800, "text": "Now, similarly we need to find out the number of relatively prime numbers of N which are not greater than L-1." }, { "code": null, "e": 26968, "s": 26911, "text": "Then, subtract the result for L-1 from the answer for R." }, { "code": null, "e": 27020, "s": 26968, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 27024, "s": 27020, "text": "C++" }, { "code": null, "e": 27029, "s": 27024, "text": "Java" }, { "code": null, "e": 27037, "s": 27029, "text": "Python3" }, { "code": null, "e": 27040, "s": 27037, "text": "C#" }, { "code": null, "e": 27051, "s": 27040, "text": "Javascript" }, { "code": "// C++ code to count of natural// numbers in range [L, R] which// are relatively prime with N #include <bits/stdc++.h>using namespace std;#define maxN (long long)1000000000000 // container of all the primes// up to sqrt(n)vector<int> prime; // Function to calculate prime// factors of nvoid sieve(long long n){ // run the sieve of Eratosthenes bool check[1000007] = { 0 }; long long i, j; // 0(false) means prime, // 1(true) means not prime check[0] = 1, check[1] = 1, check[2] = 0; // no even number is // prime except for 2 for (i = 4; i <= n; i += 2) check[i] = true; for (i = 3; i * i <= n; i += 2) if (!check[i]) { // all the multiples of each // each prime numbers are // non-prime for (j = i * i; j <= n; j += 2 * i) check[j] = true; } prime.push_back(2); // get all the primes // in prime vector for (int i = 3; i <= n; i += 2) if (!check[i]) prime.push_back(i); return;} // Count the number of numbers// up to m which are divisible// by given prime numberslong long count(long long a[], int n, long long m){ long long parity[3] = { 0 }; // Run from i= 000..0 to i= 111..1 // or check all possible // subsets of the array for (int i = 1; i < (1 << n); i++) { long long mult = 1; for (int j = 0; j < n; j++) if (i & (1 << j)) mult *= a[j]; // take the multiplication // of all the set bits // if the number of set bits // is odd, then add to the // number of multiples parity[__builtin_popcount(i) & 1] += (m / mult); } return parity[1] - parity[0];} // Function calculates all number// not greater than 'm' which are// relatively prime with n.long long countRelPrime( long long n, long long m){ long long a[20]; int i = 0, j = 0; long long pz = prime.size(); while (n != 1 && i < pz) { // if square of the prime number // is greater than 'n', it can't // be a factor of 'n' if ((long long)prime[i] * (long long)prime[i] > n) break; // if prime is a factor of // n then increment count if (n % prime[i] == 0) a[j] = (long long)prime[i], j++; while (n % prime[i] == 0) n /= prime[i]; i++; } if (n != 1) a[j] = n, j++; return m - count(a, j, m);} void countRelPrimeInRange( long long n, long long l, long long r){ sieve(sqrt(maxN)); long long result = countRelPrime(n, r) - countRelPrime(n, l - 1); cout << result << \"\\n\";} // Driver codeint main(){ long long N = 7, L = 3, R = 9; countRelPrimeInRange(N, L, R); return 0;}", "e": 29867, "s": 27051, "text": null }, { "code": "// Java code to count of natural// numbers in range [L, R] which// are relatively prime with Nimport java.util.*; class GFG{ static int maxN = 100000000; // Container of all the primes// up to sqrt(n)static Vector<Integer> prime = new Vector<Integer>(); // Function to calculate prime// factors of nstatic void sieve(int n){ // Run the sieve of Eratosthenes boolean[] check = new boolean[1000007]; for(int i = 0; i < 1000007; i++) check[i] = false; int i, j; // 0(false) means prime, // 1(true) means not prime check[0] = false; check[1] = true; check[2] = false; // No even number is // prime except for 2 for(i = 4; i <= n; i += 2) check[i] = true; for(i = 3; i * i <= n; i += 2) if (!check[i]) { // All the multiples of each // each prime numbers are // non-prime for(j = i * i; j <= n; j += 2 * i) check[j] = true; } prime.add(2); // Get all the primes // in prime vector for(i = 3; i <= n; i += 2) if (!check[i]) prime.add(i); return;} static int countSetBits(int n){ int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count;} // Count the number of numbers// up to m which are divisible// by given prime numbersstatic int count(int a[], int n, int m){ int[] parity = new int[3]; for(int i = 0; i < 3; i++) parity[i] = 0; // Run from i= 000..0 to i= 111..1 // or check all possible // subsets of the array for(int i = 1; i < (1 << n); i++) { int mult = 1; for(int j = 0; j < n; j++) if ((i & (1 << j)) != 0) mult *= a[j]; // Take the multiplication // of all the set bits // If the number of set bits // is odd, then add to the // number of multiples parity[countSetBits(i) & 1] += (m / mult); } return parity[1] - parity[0];} // Function calculates all number// not greater than 'm' which are// relatively prime with n.static int countRelPrime(int n, int m){ int[] a = new int[20]; int i = 0, j = 0; int pz = prime.size(); while(n != 1 && i < pz) { // If square of the prime number // is greater than 'n', it can't // be a factor of 'n' if ((int)prime.get(i) * (int)prime.get(i) > n) break; // If prime is a factor of // n then increment count if (n % prime.get(i) == 0) { a[j] = (int)prime.get(i); j++; } while (n % prime.get(i) == 0) n /= prime.get(i); i++; } if (n != 1) { a[j] = n; j++; } return m - count(a, j, m);} static void countRelPrimeInRange(int n, int l, int r){ sieve((int)Math.sqrt(maxN)); int result = countRelPrime(n, r) - countRelPrime(n, l - 1); System.out.println(result);} // Driver codepublic static void main(String[] args){ int N = 7, L = 3, R = 9; countRelPrimeInRange(N, L, R);}} // This code is contributed by grand_master", "e": 33089, "s": 29867, "text": null }, { "code": "# Python3 code to count of natural# numbers in range [L, R] which# are relatively prime with Nfrom math import sqrt, floor maxN = 1000000000000 # Container of all the primes# up to sqrt(n)prime = [] # Function to calculate prime# factors of ndef sieve(n): # Run the sieve of Eratosthenes check = [0] * (1000007) i, j = 0, 0 # 0(false) means prime, # 1(True) means not prime check[0] = 1 check[1] = 1 check[2] = 0 # No even number is # prime except for 2 for i in range(4, n + 1, 2): check[i] = True for i in range(3, n + 1, 2): if i * i > n: break if (not check[i]): # All the multiples of each # each prime numbers are # non-prime for j in range(2 * i, n + 1, 2 * i): check[j] = True prime.append(2) # Get all the primes # in prime vector for i in range(3, n + 1, 2): if (not check[i]): prime.append(i) return # Count the number of numbers# up to m which are divisible# by given prime numbersdef count(a, n, m): parity = [0] * 3 # Run from i = 000..0 to i = 111..1 # or check all possible # subsets of the array for i in range(1, 1 << n): mult = 1 for j in range(n): if (i & (1 << j)): mult *= a[j] # Take the multiplication # of all the set bits # If the number of set bits # is odd, then add to the # number of multiples parity[bin(i).count('1') & 1] += (m // mult) return parity[1] - parity[0] # Function calculates all number# not greater than 'm' which are# relatively prime with n.def countRelPrime(n, m): a = [0] * 20 i = 0 j = 0 pz = len(prime) while (n != 1 and i < pz): # If square of the prime number # is greater than 'n', it can't # be a factor of 'n' if (prime[i] * prime[i] > n): break # If prime is a factor of # n then increment count if (n % prime[i] == 0): a[j] = prime[i] j += 1 while (n % prime[i] == 0): n //= prime[i] i += 1 if (n != 1): a[j] = n j += 1 return m - count(a, j, m) def countRelPrimeInRange(n, l, r): sieve(floor(sqrt(maxN))) result = (countRelPrime(n, r) - countRelPrime(n, l - 1)) print(result) # Driver codeif __name__ == '__main__': N = 7 L = 3 R = 9 countRelPrimeInRange(N, L, R) # This code is contributed by mohit kumar 29", "e": 35634, "s": 33089, "text": null }, { "code": "// C# code to count of natural// numbers in range [L, R] which// are relatively prime with Nusing System;using System.Collections.Generic; class GFG{ static int maxN = 100000000; // Container of all the primes// up to sqrt(n)static List<int> prime = new List<int>(); // Function to calculate prime// factors of nstatic void sieve(int n){ // Run the sieve of Eratosthenes bool[] check = new bool[1000007]; for(int I = 0; I < 1000007; I++) check[I] = false; int i, j; // 0(false) means prime, // 1(true) means not prime check[0] = false; check[1] = true; check[2] = false; // No even number is // prime except for 2 for(i = 4; i <= n; i += 2) check[i] = true; for(i = 3; i * i <= n; i += 2) if (!check[i]) { // All the multiples of each // each prime numbers are // non-prime for(j = i * i; j <= n; j += 2 * i) check[j] = true; } prime.Add(2); // Get all the primes // in prime vector for(i = 3; i <= n; i += 2) if (!check[i]) prime.Add(i); return;} static int countSetBits(int n){ int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count;} // Count the number of numbers// up to m which are divisible// by given prime numbersstatic int count(int[] a, int n, int m){ int[] parity = new int[3]; for(int i = 0; i < 3; i++) parity[i] = 0; // Run from i= 000..0 to i= 111..1 // or check all possible // subsets of the array for(int i = 1; i < (1 << n); i++) { int mult = 1; for(int j = 0; j < n; j++) if ((i & (1 << j)) != 0) mult *= a[j]; // Take the multiplication // of all the set bits // If the number of set bits // is odd, then add to the // number of multiples parity[countSetBits(i) & 1] += (m / mult); } return parity[1] - parity[0];} // Function calculates all number// not greater than 'm' which are// relatively prime with n.static int countRelPrime(int n, int m){ int[] a = new int[20]; int i = 0, j = 0; int pz = prime.Count; while (n != 1 && i < pz) { // If square of the prime number // is greater than 'n', it can't // be a factor of 'n' if ((int)prime[i] * (int)prime[i] > n) break; // If prime is a factor of // n then increment count if (n % prime[i] == 0) { a[j] = (int)prime[i]; j++; } while (n % prime[i] == 0) n /= prime[i]; i++; } if (n != 1) { a[j] = n; j++; } return m - count(a, j, m);} static void countRelPrimeInRange(int n, int l, int r){ sieve((int)Math.Sqrt(maxN)); int result = countRelPrime(n, r) - countRelPrime(n, l - 1); Console.WriteLine(result);} // Driver Codestatic void Main(){ int N = 7, L = 3, R = 9; countRelPrimeInRange(N, L, R);}} // This code is contributed by divyeshrabadiya07", "e": 38840, "s": 35634, "text": null }, { "code": "<script> // Javascript code to count of natural// numbers in range [L, R] which// are relatively prime with Nlet maxN = 100000000; // Container of all the primes// up to sqrt(n)let prime = []; // Function to calculate prime// factors of nfunction sieve(n){ // Run the sieve of Eratosthenes let check = new Array(1000007); for(let i = 0; i < 1000007; i++) check[i] = false; let i, j; // 0(false) means prime, // 1(true) means not prime check[0] = false; check[1] = true; check[2] = false; // No even number is // prime except for 2 for(i = 4; i <= n; i += 2) check[i] = true; for(i = 3; i * i <= n; i += 2) if (!check[i]) { // All the multiples of each // each prime numbers are // non-prime for(j = i * i; j <= n; j += 2 * i) check[j] = true; } prime.push(2); // Get all the primes // in prime vector for(i = 3; i <= n; i += 2) if (!check[i]) prime.push(i); return;} function countSetBits(n){ let count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count;} // Count the number of numbers// up to m which are divisible// by given prime numbersfunction count(a, n, m){ let parity = new Array(3); for(let i = 0; i < 3; i++) parity[i] = 0; // Run from i= 000..0 to i= 111..1 // or check all possible // subsets of the array for(let i = 1; i < (1 << n); i++) { let mult = 1; for(let j = 0; j < n; j++) if ((i & (1 << j)) != 0) mult *= a[j]; // Take the multiplication // of all the set bits // If the number of set bits // is odd, then add to the // number of multiples parity[countSetBits(i) & 1] += (m / mult); } return parity[1] - parity[0];} // Function calculates all number// not greater than 'm' which are// relatively prime with n.function countRelPrime(n, m){ let a = new Array(20); let i = 0, j = 0; let pz = prime.length; while(n != 1 && i < pz) { // If square of the prime number // is greater than 'n', it can't // be a factor of 'n' if (prime[i] * prime[i] > n) break; // If prime is a factor of // n then increment count if (n % prime[i] == 0) { a[j] = prime[i]; j++; } while (n % prime[i] == 0) n = Math.floor(n/prime[i]); i++; } if (n != 1) { a[j] = n; j++; } return m - count(a, j, m);} function countRelPrimeInRange(n, l, r){ sieve(Math.floor(Math.sqrt(maxN))); let result = countRelPrime(n, r) - countRelPrime(n, l - 1); document.write(result);} // Driver codelet N = 7, L = 3, R = 9; countRelPrimeInRange(N, L, R); // This code is contributed by unknown2108 </script>", "e": 41843, "s": 38840, "text": null }, { "code": null, "e": 41845, "s": 41843, "text": "6" }, { "code": null, "e": 41862, "s": 41847, "text": "mohit kumar 29" }, { "code": null, "e": 41875, "s": 41862, "text": "grand_master" }, { "code": null, "e": 41893, "s": 41875, "text": "divyeshrabadiya07" }, { "code": null, "e": 41905, "s": 41893, "text": "unknown2108" }, { "code": null, "e": 41925, "s": 41905, "text": "array-range-queries" }, { "code": null, "e": 41931, "s": 41925, "text": "Maths" }, { "code": null, "e": 41947, "s": 41931, "text": "Natural Numbers" }, { "code": null, "e": 41961, "s": 41947, "text": "number-theory" }, { "code": null, "e": 41974, "s": 41961, "text": "Prime Number" }, { "code": null, "e": 41998, "s": 41974, "text": "Competitive Programming" }, { "code": null, "e": 42011, "s": 41998, "text": "Mathematical" }, { "code": null, "e": 42025, "s": 42011, "text": "number-theory" }, { "code": null, "e": 42038, "s": 42025, "text": "Mathematical" }, { "code": null, "e": 42051, "s": 42038, "text": "Prime Number" }, { "code": null, "e": 42149, "s": 42051, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42187, "s": 42149, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 42214, "s": 42187, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 42292, "s": 42214, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 42317, "s": 42292, "text": "Formatted output in Java" }, { "code": null, "e": 42363, "s": 42317, "text": "Breadth First Traversal ( BFS ) on a 2D array" }, { "code": null, "e": 42393, "s": 42363, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 42453, "s": 42393, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 42468, "s": 42453, "text": "C++ Data Types" }, { "code": null, "e": 42511, "s": 42468, "text": "Set in C++ Standard Template Library (STL)" } ]
Tryit Editor v3.7
Tryit: Using the list-style shorthand property
[]
Four Ways to Filter a Spark Dataset Against a Collection of Data Values | by Ajay Gupta | Towards Data Science
Let us assume there is a very large Dataset ‘A’ with the following schema: root:| — empId: Integer| — sal: Integer| — name: String| — address: String| — dept: Integer The Dataset ‘A’ needs to be filtered against a set of employee IDs (empIds), ‘B’ (can be broadcasted to executors), to get a filtered Dataset ‘A`’. The filter operation can be represented as: A` = A.filter(A.empId contains in 'B') To achieve this most common filtering scenario, you can use four types of transformation in Spark, each one having its own pros and cons. Here is a description of the usage of all these four transformations to execute this particular filtering scenario along with detailed notes on the reliability and efficiency aspects of each of these. Filter: Filter transformation (filtering Dataset records on a boolean condition expression or a boolean returning filter function), on a Dataset, can be used in the following ways: 1. Dataset<T> A` = A.filter(Column condition)2. Dataset<T> A` = A.filter(FilterFunction<T> func)3. Dataset<T> A` = A.filter(String conditionExpr) For the filtering scenario, as described earlier, one can use the ‘Filter’ transformation on ‘A’ that takes a ‘FilterFunction’ as an input. The ‘FilterFunction’ is invoked on each of the records contained in the partitions of the corresponding Dataset and returns either ‘true’ or ‘false’. In our filtering scenario, the FilterFunction would be invoked on each of the record of the Dataset ‘A’ and check if the ‘empId’ of the record exists in the broadcasted set of empIds, ‘B’ ( ‘B’ being backed by a corresponding HashTable). The use of Filter transformation as described above is quite simple, robust, and efficient irrespective of the size of Dataset ‘A’. This is because, the transformation is invoked record by record. Further, since, broadcasted set of empIds is backed by hashtable on the executor, filtering lookup in the filter function for each of the record remain efficient. Map: Map transformation (applies a function on each of the records of a Dataset to return either a null, same or different record type), on a Dataset, is used in the following way: Dataset<U> A` = A.map(MapFunction<T,U> func, Encoder<U> encoder) For the filtering scenario, as described earlier, one can use the ‘Map’ transformation on ‘A’ that takes a ‘MapFunction’ as an input. In our filtering scenario, the ‘MapFunction’ would be invoked on each of the record of the Dataset ‘A’ and check if the ‘empId’ of the record exists in the broadcasted set of empIds, ‘B’ (backed by a corresponding HashTable). In case, the record exists, the same would be returned from the MapFunction. In case, the record does not exist, NULL would be returned. Also, the Encoder input for the MapFunction would be the same as for Dataset ‘A’. Although, the semantics of the ‘MapFunction’ is similar to the ‘FilterFunction’, the use of ‘Map’ transformation as described above, for the filtering scenario, is not as simple and elegant as compared to direct ‘Filter’ transformation approach. One has to explicity provision additional Encoder input in the transformation. Also, after, ‘Map’ transformation is invoked, the output needs to be filtered for NULL values, therefore, making ‘Map’ approach to be less efficient than ‘Filter’ approach. However, the reliability of the approach is similar to the ‘Filter’ approach since it would run without problems irrespective of the size of ‘A’. This is because, the ‘Map’ transformation is also invoked record by record. MapPartitions: Mappartitions transformation (applies a function on each of the partition of a Dataset returning either a null or an iterator to a new collection of same or different record type), on a Dataset, is used in the following way: Dataset<U> A` = A.map(MapPartitionsFunction<T,U> func, Encoder<U> encoder) For the filtering scenario, as described earlier, one can also use the ‘MapPartitions’ transformation on ‘A’ that takes a ‘MapPartitionsFunction’ as an input. In our filtering scenario, the ‘MapPartitionsFunction’ would be invoked on each partition of the Dataset ‘A’, iterating on all the records of the partition, and checking for each of the records, if the ‘empId’ of the record exists in the broadcasted set of empIds, ‘B’ (backed by a corresponding HashTable). In case, the record exists, the same would be added to a returnable collection initialized in the ‘MapPartitionsFunction’. Finally, an iterator to the returnable collection is returned from the ‘MapPartitionsFunction’. As compared to ‘Map’ and ‘Filter’ approach, ‘MapPartitions’ approach is generally more efficient because it is operating partition wise, and not the record wise. However, similar to ‘Map’, one has to explicity provision Encoder input in the transformation. Also, the ‘MapPartitions’ approach can become highly unreliable in case the size of certain partitions of Dataset ‘A’ exceeds the memory provisioned for executing each of partition computing task. This is because of the fact that larger partition can lead to a potential larger returnable collection leading to memory overruns. Inner Join: Inner Join transformation applies to two input Datasets, A & B, in the following way: Dataset<Row> A` = A.join(Dataset<?> B, Column joinExprs) For the filtering scenario, as described earlier, one can also use the ‘Inner Join’ transformation on ‘A’ that joins Dataset representation of ‘B’ on the join condition (A.empId equals B.empId) and selects only the fields of ‘A’ from each of the joined record. ‘Inner Join’ approach returns Dataset of generic ‘Row’ objects, hence one needs to use a Encoder to convert it back into Dataset of A’s record type to match the exact filter semantics. However, similar to ‘Filter’ apporach, the ‘Inner Join’ approach is efficient and reliable. Efficiency comes from the fact that since ‘B’ is broadcastable, the most efficient ‘Boradcast Hash Join’ approach would be chosen by the Spark to execute the Join. Also, the reliablility comes from the fact that ‘Inner Join’ approach would be applicable to large data sets of ‘A’ as was the case with ‘Filter’ approach. Considering all the approaches, I would pick the ‘Filter’ approach as the safest bet from a reliability and efficiency perspective. Also, to note, the ‘Filter’ approach would also allow me to perform an anti search with similar efficiency and robustness which ‘Inner Join’ won’t allow. In case of feedback or queries on this story, do write in the comments section. I hope, you would find it useful. Here is the link to my other comprehensive stories on Apache Spark. Also, Get a copy of my recently published book on Spark Partitioning: “Guide to Spark Partitioning: Spark Partitioning Explained in Depth”
[ { "code": null, "e": 246, "s": 171, "text": "Let us assume there is a very large Dataset ‘A’ with the following schema:" }, { "code": null, "e": 338, "s": 246, "text": "root:| — empId: Integer| — sal: Integer| — name: String| — address: String| — dept: Integer" }, { "code": null, "e": 530, "s": 338, "text": "The Dataset ‘A’ needs to be filtered against a set of employee IDs (empIds), ‘B’ (can be broadcasted to executors), to get a filtered Dataset ‘A`’. The filter operation can be represented as:" }, { "code": null, "e": 569, "s": 530, "text": "A` = A.filter(A.empId contains in 'B')" }, { "code": null, "e": 908, "s": 569, "text": "To achieve this most common filtering scenario, you can use four types of transformation in Spark, each one having its own pros and cons. Here is a description of the usage of all these four transformations to execute this particular filtering scenario along with detailed notes on the reliability and efficiency aspects of each of these." }, { "code": null, "e": 1089, "s": 908, "text": "Filter: Filter transformation (filtering Dataset records on a boolean condition expression or a boolean returning filter function), on a Dataset, can be used in the following ways:" }, { "code": null, "e": 1235, "s": 1089, "text": "1. Dataset<T> A` = A.filter(Column condition)2. Dataset<T> A` = A.filter(FilterFunction<T> func)3. Dataset<T> A` = A.filter(String conditionExpr)" }, { "code": null, "e": 1763, "s": 1235, "text": "For the filtering scenario, as described earlier, one can use the ‘Filter’ transformation on ‘A’ that takes a ‘FilterFunction’ as an input. The ‘FilterFunction’ is invoked on each of the records contained in the partitions of the corresponding Dataset and returns either ‘true’ or ‘false’. In our filtering scenario, the FilterFunction would be invoked on each of the record of the Dataset ‘A’ and check if the ‘empId’ of the record exists in the broadcasted set of empIds, ‘B’ ( ‘B’ being backed by a corresponding HashTable)." }, { "code": null, "e": 2123, "s": 1763, "text": "The use of Filter transformation as described above is quite simple, robust, and efficient irrespective of the size of Dataset ‘A’. This is because, the transformation is invoked record by record. Further, since, broadcasted set of empIds is backed by hashtable on the executor, filtering lookup in the filter function for each of the record remain efficient." }, { "code": null, "e": 2304, "s": 2123, "text": "Map: Map transformation (applies a function on each of the records of a Dataset to return either a null, same or different record type), on a Dataset, is used in the following way:" }, { "code": null, "e": 2369, "s": 2304, "text": "Dataset<U> A` = A.map(MapFunction<T,U> func, Encoder<U> encoder)" }, { "code": null, "e": 2948, "s": 2369, "text": "For the filtering scenario, as described earlier, one can use the ‘Map’ transformation on ‘A’ that takes a ‘MapFunction’ as an input. In our filtering scenario, the ‘MapFunction’ would be invoked on each of the record of the Dataset ‘A’ and check if the ‘empId’ of the record exists in the broadcasted set of empIds, ‘B’ (backed by a corresponding HashTable). In case, the record exists, the same would be returned from the MapFunction. In case, the record does not exist, NULL would be returned. Also, the Encoder input for the MapFunction would be the same as for Dataset ‘A’." }, { "code": null, "e": 3668, "s": 2948, "text": "Although, the semantics of the ‘MapFunction’ is similar to the ‘FilterFunction’, the use of ‘Map’ transformation as described above, for the filtering scenario, is not as simple and elegant as compared to direct ‘Filter’ transformation approach. One has to explicity provision additional Encoder input in the transformation. Also, after, ‘Map’ transformation is invoked, the output needs to be filtered for NULL values, therefore, making ‘Map’ approach to be less efficient than ‘Filter’ approach. However, the reliability of the approach is similar to the ‘Filter’ approach since it would run without problems irrespective of the size of ‘A’. This is because, the ‘Map’ transformation is also invoked record by record." }, { "code": null, "e": 3908, "s": 3668, "text": "MapPartitions: Mappartitions transformation (applies a function on each of the partition of a Dataset returning either a null or an iterator to a new collection of same or different record type), on a Dataset, is used in the following way:" }, { "code": null, "e": 3983, "s": 3908, "text": "Dataset<U> A` = A.map(MapPartitionsFunction<T,U> func, Encoder<U> encoder)" }, { "code": null, "e": 4669, "s": 3983, "text": "For the filtering scenario, as described earlier, one can also use the ‘MapPartitions’ transformation on ‘A’ that takes a ‘MapPartitionsFunction’ as an input. In our filtering scenario, the ‘MapPartitionsFunction’ would be invoked on each partition of the Dataset ‘A’, iterating on all the records of the partition, and checking for each of the records, if the ‘empId’ of the record exists in the broadcasted set of empIds, ‘B’ (backed by a corresponding HashTable). In case, the record exists, the same would be added to a returnable collection initialized in the ‘MapPartitionsFunction’. Finally, an iterator to the returnable collection is returned from the ‘MapPartitionsFunction’." }, { "code": null, "e": 5254, "s": 4669, "text": "As compared to ‘Map’ and ‘Filter’ approach, ‘MapPartitions’ approach is generally more efficient because it is operating partition wise, and not the record wise. However, similar to ‘Map’, one has to explicity provision Encoder input in the transformation. Also, the ‘MapPartitions’ approach can become highly unreliable in case the size of certain partitions of Dataset ‘A’ exceeds the memory provisioned for executing each of partition computing task. This is because of the fact that larger partition can lead to a potential larger returnable collection leading to memory overruns." }, { "code": null, "e": 5352, "s": 5254, "text": "Inner Join: Inner Join transformation applies to two input Datasets, A & B, in the following way:" }, { "code": null, "e": 5409, "s": 5352, "text": "Dataset<Row> A` = A.join(Dataset<?> B, Column joinExprs)" }, { "code": null, "e": 5670, "s": 5409, "text": "For the filtering scenario, as described earlier, one can also use the ‘Inner Join’ transformation on ‘A’ that joins Dataset representation of ‘B’ on the join condition (A.empId equals B.empId) and selects only the fields of ‘A’ from each of the joined record." }, { "code": null, "e": 6267, "s": 5670, "text": "‘Inner Join’ approach returns Dataset of generic ‘Row’ objects, hence one needs to use a Encoder to convert it back into Dataset of A’s record type to match the exact filter semantics. However, similar to ‘Filter’ apporach, the ‘Inner Join’ approach is efficient and reliable. Efficiency comes from the fact that since ‘B’ is broadcastable, the most efficient ‘Boradcast Hash Join’ approach would be chosen by the Spark to execute the Join. Also, the reliablility comes from the fact that ‘Inner Join’ approach would be applicable to large data sets of ‘A’ as was the case with ‘Filter’ approach." }, { "code": null, "e": 6553, "s": 6267, "text": "Considering all the approaches, I would pick the ‘Filter’ approach as the safest bet from a reliability and efficiency perspective. Also, to note, the ‘Filter’ approach would also allow me to perform an anti search with similar efficiency and robustness which ‘Inner Join’ won’t allow." } ]
Fuzzy matching with Levenshtein and PostgreSQL | by Dhanesh Budhrani | Towards Data Science
User experience is the result of a combination of factors: UI design, response time, tolerance of user errors, etc. The scope of this post falls into the third category. More specifically, I’ll be explaining how to handle user errors in search forms using PostgreSQL and Levenshtein’s distance algorithm. For instance, we may be looking for a user in our site called “Markus”, although we may be searching for him as “Marcus” (both of these names exist, and would be equivalent in different languages). Let’s get started by getting familiarized with Levenshtein’s distance algorithm. Levenshtein’s distance (we’ll call it LD from now on, just to be concise) intends to calculate the dissimilitude between two strings (hence, the higher the value, the less similar they are). This metric represents the number of operations that need to be applied to one of the strings to make it equal to the other one. Such operations include the following: inserting a character, deleting it or substituting it. It is worth mentioning that each operation has an associated cost, although it’s common to set the cost to 1 for all operations. You’ll rarely need to implement the LD algorithm, given that it’s already present in many libraries of the major programming languages. However, it’s worth understanding how it works. We’ll work through an example to determine the LD between “Marcus” and “Markus”, setting an equivalent cost of 1 to all operations: We create a matrix D of dimension m x n, where m and n represent the length of our two strings (referenced onwards as A and B).We iterate the matrix top-down and from left to right, computing the LD between the corresponding substrings.We compute the added cost (ac), being 0 if A[i] is equal to B[j] and 1 otherwise.We perform the following operation: We create a matrix D of dimension m x n, where m and n represent the length of our two strings (referenced onwards as A and B). We iterate the matrix top-down and from left to right, computing the LD between the corresponding substrings. We compute the added cost (ac), being 0 if A[i] is equal to B[j] and 1 otherwise. We perform the following operation: D[i, j] = min(D[i-1, j] + 1, D[i, j-1] + 1, D[i-1, j-1] + ac) which means that a cell (i, j) has a LD determined by the minimum of: The cell right above plus one (due to an insertion operation). The cell to the left plus one (due to an insertion operation). The cell above and to the left plus ac (due to a substitution operation). The following matrix represents the final result of this process: The matrix above does not only offer us the LD between the full strings, but also the LD between any combination of substrings. The LD between the full strings can be found in position (m, n). In this case, we can see that “Marcus” and “Markus” have a LD of 1 (in red), which is caused by the substitution of “c” by “k”. Now that you have an understanding of the algorithm, it’s time to get to the practical part. Applying the LD algorithm with PostgreSQL is very simple, all thanks to the fuzzystrmatch extension. This extension offers different algorithms for fuzzy string matching. The available options are the LD algorithm and a set of phonetic functions. Note that these phonetic functions (Soundex, Metaphone and Double Metaphone) may not perform optimally with non-English strings. For this reason, I consider LD to be the most robust option in international applications. Nevertheless, let’s continue and add this extension to our PostgreSQL database: CREATE EXTENSION fuzzystrmatch; At this point, computing LD becomes as simple as running the following query: SELECT levenshtein(str1, str2); For instance: SELECT levenshtein('Marcus', 'Markus'); Therefore, if you have a table of users and want to find all users that have a similar name to the user input (setting, for instance, a maximum LD of 1), your query may look like the following: SELECT name FROM user WHERE levenshtein('Marcus', name) <= 1; In this case, “Marcus” represents the user input. In this query, we’d be searching for user that are, either called Marcus, or have a name with a LD of 1 (e.g., “Markus”). Note that fuzzystrmatch offers another interesting function that would be a bit more efficient in this scenario: levenshtein_less_equal. This function allows you to define a maximum distance threshold, after which PostgreSQL stops computing. In other words, if we set a maximum threshold of 1, and our pair of strings have a LD of 6, fuzzystrmatch will stop computing after reaching a LD of 2 considering that, anyway, we are not interested in the LD of such pair of strings, saving some computation resources (and yielding a LD of 2). Finally, it’s also worth noting that both of these functions have a version that allows you to define the cost of each operation (insertion, deletion and substitution).
[ { "code": null, "e": 674, "s": 171, "text": "User experience is the result of a combination of factors: UI design, response time, tolerance of user errors, etc. The scope of this post falls into the third category. More specifically, I’ll be explaining how to handle user errors in search forms using PostgreSQL and Levenshtein’s distance algorithm. For instance, we may be looking for a user in our site called “Markus”, although we may be searching for him as “Marcus” (both of these names exist, and would be equivalent in different languages)." }, { "code": null, "e": 755, "s": 674, "text": "Let’s get started by getting familiarized with Levenshtein’s distance algorithm." }, { "code": null, "e": 1298, "s": 755, "text": "Levenshtein’s distance (we’ll call it LD from now on, just to be concise) intends to calculate the dissimilitude between two strings (hence, the higher the value, the less similar they are). This metric represents the number of operations that need to be applied to one of the strings to make it equal to the other one. Such operations include the following: inserting a character, deleting it or substituting it. It is worth mentioning that each operation has an associated cost, although it’s common to set the cost to 1 for all operations." }, { "code": null, "e": 1614, "s": 1298, "text": "You’ll rarely need to implement the LD algorithm, given that it’s already present in many libraries of the major programming languages. However, it’s worth understanding how it works. We’ll work through an example to determine the LD between “Marcus” and “Markus”, setting an equivalent cost of 1 to all operations:" }, { "code": null, "e": 1967, "s": 1614, "text": "We create a matrix D of dimension m x n, where m and n represent the length of our two strings (referenced onwards as A and B).We iterate the matrix top-down and from left to right, computing the LD between the corresponding substrings.We compute the added cost (ac), being 0 if A[i] is equal to B[j] and 1 otherwise.We perform the following operation:" }, { "code": null, "e": 2095, "s": 1967, "text": "We create a matrix D of dimension m x n, where m and n represent the length of our two strings (referenced onwards as A and B)." }, { "code": null, "e": 2205, "s": 2095, "text": "We iterate the matrix top-down and from left to right, computing the LD between the corresponding substrings." }, { "code": null, "e": 2287, "s": 2205, "text": "We compute the added cost (ac), being 0 if A[i] is equal to B[j] and 1 otherwise." }, { "code": null, "e": 2323, "s": 2287, "text": "We perform the following operation:" }, { "code": null, "e": 2385, "s": 2323, "text": "D[i, j] = min(D[i-1, j] + 1, D[i, j-1] + 1, D[i-1, j-1] + ac)" }, { "code": null, "e": 2455, "s": 2385, "text": "which means that a cell (i, j) has a LD determined by the minimum of:" }, { "code": null, "e": 2518, "s": 2455, "text": "The cell right above plus one (due to an insertion operation)." }, { "code": null, "e": 2581, "s": 2518, "text": "The cell to the left plus one (due to an insertion operation)." }, { "code": null, "e": 2655, "s": 2581, "text": "The cell above and to the left plus ac (due to a substitution operation)." }, { "code": null, "e": 2721, "s": 2655, "text": "The following matrix represents the final result of this process:" }, { "code": null, "e": 3042, "s": 2721, "text": "The matrix above does not only offer us the LD between the full strings, but also the LD between any combination of substrings. The LD between the full strings can be found in position (m, n). In this case, we can see that “Marcus” and “Markus” have a LD of 1 (in red), which is caused by the substitution of “c” by “k”." }, { "code": null, "e": 3602, "s": 3042, "text": "Now that you have an understanding of the algorithm, it’s time to get to the practical part. Applying the LD algorithm with PostgreSQL is very simple, all thanks to the fuzzystrmatch extension. This extension offers different algorithms for fuzzy string matching. The available options are the LD algorithm and a set of phonetic functions. Note that these phonetic functions (Soundex, Metaphone and Double Metaphone) may not perform optimally with non-English strings. For this reason, I consider LD to be the most robust option in international applications." }, { "code": null, "e": 3682, "s": 3602, "text": "Nevertheless, let’s continue and add this extension to our PostgreSQL database:" }, { "code": null, "e": 3714, "s": 3682, "text": "CREATE EXTENSION fuzzystrmatch;" }, { "code": null, "e": 3792, "s": 3714, "text": "At this point, computing LD becomes as simple as running the following query:" }, { "code": null, "e": 3824, "s": 3792, "text": "SELECT levenshtein(str1, str2);" }, { "code": null, "e": 3838, "s": 3824, "text": "For instance:" }, { "code": null, "e": 3878, "s": 3838, "text": "SELECT levenshtein('Marcus', 'Markus');" }, { "code": null, "e": 4072, "s": 3878, "text": "Therefore, if you have a table of users and want to find all users that have a similar name to the user input (setting, for instance, a maximum LD of 1), your query may look like the following:" }, { "code": null, "e": 4134, "s": 4072, "text": "SELECT name FROM user WHERE levenshtein('Marcus', name) <= 1;" }, { "code": null, "e": 4306, "s": 4134, "text": "In this case, “Marcus” represents the user input. In this query, we’d be searching for user that are, either called Marcus, or have a name with a LD of 1 (e.g., “Markus”)." } ]
Static and non static blank final variables in Java
Static variable: Declared with the help of the keyword ‘static’, they are also known as class variables. They are defined within a constructor or outside a class function. When a variable is static, it is shared between all objects of the class, irrespective of the number of objects that are created. Demonstrating how the ‘static’ keyword, when used with variable works − Live Demo public class Demo{ String name; static String designation; public void display_data(){ System.out.println("The name is: " + name); System.out.println("The designation of this team members is : " + designation); } public static void main(String s[]){ Demo.designation = "Intern"; Demo my_obj = new Demo(); my_obj.name = "Joe"; Demo my_obj_2 = new Demo(); my_obj_2.name = "Joanna"; my_obj.display_data(); my_obj_2.display_data(); my_obj.designation = "Senior dev"; System.out.println("\nAfter the changes, the data is :\n"); my_obj.display_data(); my_obj_2.display_data(); } } The name is: Joe The designation of this team members is : Intern The name is: Joanna The designation of this team members is : Intern After the changes, the data is : The name is: Joe The designation of this team members is : Senior dev The name is: Joanna The designation of this team members is : Senior dev A class named Demo contains variables and a function named ‘display_data’ that is used to display the class variables. In the main function, an instance of the class is created and a name and designation is assigned to the object variable. It is displayed and another object is created and the same is done. The data is displayed on the console. The changes reflect here. Static final blank variable − The same definition as that of blank final variable along with the keyword ‘static’, meaning it can be initialized within a static block of code only. Blank final variable − As the name suggests, the final variable that has no value assigned to it is known as a blank final variable. It can be initialized within a constructor only, and failing to initiate a blank final variable results in a compilation error. Blank final variable’s working − Live Demo public class Demo{ private static final int val_1; private final int val_2; static{ val_1 = 1; } Demo(int val_3){ val_2 = val_3; } public static void main(String s[]){ Demo obj_1 = new Demo(95); Demo obj_2 = new Demo(99); System.out.println("The value of first variable is : "); System.out.println(Demo.val_1); System.out.println("The value of first variable accessed using the object : "); System.out.println(obj_1.val_2); } } The value of first variable is : 1 The value of first variable accessed using the object : 95 A class named Demo contains variables and a constructor named ‘Demo’ that is used to assign one value to another class variable. In the main function, two instances of the class are created and their values are displayed on the console.
[ { "code": null, "e": 1364, "s": 1062, "text": "Static variable: Declared with the help of the keyword ‘static’, they are also known as class variables. They are defined within a constructor or outside a class function. When a variable is static, it is shared between all objects of the class, irrespective of the number of objects that are created." }, { "code": null, "e": 1436, "s": 1364, "text": "Demonstrating how the ‘static’ keyword, when used with variable works −" }, { "code": null, "e": 1447, "s": 1436, "text": " Live Demo" }, { "code": null, "e": 2118, "s": 1447, "text": "public class Demo{\n String name;\n static String designation;\n public void display_data(){\n System.out.println(\"The name is: \" + name);\n System.out.println(\"The designation of this team members is : \" + designation);\n }\n public static void main(String s[]){\n Demo.designation = \"Intern\";\n Demo my_obj = new Demo();\n my_obj.name = \"Joe\";\n Demo my_obj_2 = new Demo();\n my_obj_2.name = \"Joanna\";\n my_obj.display_data();\n my_obj_2.display_data();\n my_obj.designation = \"Senior dev\";\n System.out.println(\"\\nAfter the changes, the data is :\\n\");\n my_obj.display_data();\n my_obj_2.display_data();\n }\n}" }, { "code": null, "e": 2429, "s": 2118, "text": "The name is: Joe\nThe designation of this team members is : Intern\nThe name is: Joanna\nThe designation of this team members is : Intern\nAfter the changes, the data is :\nThe name is: Joe\nThe designation of this team members is : Senior dev\nThe name is: Joanna\nThe designation of this team members is : Senior dev" }, { "code": null, "e": 2801, "s": 2429, "text": "A class named Demo contains variables and a function named ‘display_data’ that is used to display the class variables. In the main function, an instance of the class is created and a name and designation is assigned to the object variable. It is displayed and another object is created and the same is done. The data is displayed on the console. The changes reflect here." }, { "code": null, "e": 2982, "s": 2801, "text": "Static final blank variable − The same definition as that of blank final variable along with the keyword ‘static’, meaning it can be initialized within a static block of code only." }, { "code": null, "e": 3243, "s": 2982, "text": "Blank final variable − As the name suggests, the final variable that has no value assigned to it is known as a blank final variable. It can be initialized within a constructor only, and failing to initiate a blank final variable results in a compilation error." }, { "code": null, "e": 3276, "s": 3243, "text": "Blank final variable’s working −" }, { "code": null, "e": 3287, "s": 3276, "text": " Live Demo" }, { "code": null, "e": 3781, "s": 3287, "text": "public class Demo{\n private static final int val_1;\n private final int val_2;\n static{ val_1 = 1;\n }\n Demo(int val_3){\n val_2 = val_3;\n }\n public static void main(String s[]){\n Demo obj_1 = new Demo(95);\n Demo obj_2 = new Demo(99);\n System.out.println(\"The value of first variable is : \");\n System.out.println(Demo.val_1);\n System.out.println(\"The value of first variable accessed using the object : \");\n System.out.println(obj_1.val_2);\n }\n}" }, { "code": null, "e": 3875, "s": 3781, "text": "The value of first variable is :\n1\nThe value of first variable accessed using the object :\n95" }, { "code": null, "e": 4112, "s": 3875, "text": "A class named Demo contains variables and a constructor named ‘Demo’ that is used to assign one value to another class variable. In the main function, two instances of the class are created and their values are displayed on the console." } ]
Queue add() method in Java
26 Sep, 2018 The add(E e) method of Queue Interface inserts the element passed in the parameter to the end of the queue if there is space. If the Queue is capacity restricted and no space is left for insertion, it returns an IllegalStateException. The function returns true on successful insertion. Syntax: boolean add(E e) Parameters: This method accepts a mandatory parameter e which is the element to be inserted in the end of the Queue. Returns: This method returns true on successful insertion. Exceptions: The function throws four exceptions which are described as below: ClassCastException: when the class of the element to be entered prevents it from being added to this container. IllegalStateException: when the capacity of the container is full and insertion is done. IllegalArgumentException: when some property of the element prevents it to be added to the queue. NullPointerException: when the element to be inserted is passed as null and the Queue’s interface does not allow null elements. Below programs illustrate add() method of Queue: Program 1: With the help of LinkedList. // Java Program Demonstrate add()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // before removing print queue System.out.println("Queue: " + Q); }} Queue: [7855642, 35658786, 5278367, 74381793] Program 2: With the help of ArrayDeque. // Java Program Demonstrate add()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ArrayDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // before removing print queue System.out.println("Queue: " + Q); }} Queue: [7855642, 35658786, 5278367, 74381793] Program 3: With the help of LinkedBlockingDeque. // Java Program Demonstrate add()// method of Queue import java.util.*;import java.util.concurrent.LinkedBlockingDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // before removing print queue System.out.println("Queue: " + Q); }} Queue: [7855642, 35658786, 5278367, 74381793] Program 4: With the help of ConcurrentLinkedDeque. // Java Program Demonstrate add()// method of Queue import java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ConcurrentLinkedDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // before removing print queue System.out.println("Queue: " + Q); }} Queue: [7855642, 35658786, 5278367, 74381793] Below programs illustrate exceptions thrown by this method: Program 5: To show NullPointerException. // Java Program Demonstrate add()// method of Queue when Null is passed import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingQueue<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); try { // when null is inserted Q.add(null); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.NullPointerException Program 6: To show IllegalStateException. // Java Program Demonstrate add()// method of Queue when capacity is fullimport java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingQueue<Integer>(3); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); try { // when capacity is full Q.add(10); } catch (Exception e) { System.out.println("Exception: " + e); } }} Exception: java.lang.IllegalStateException: Queue full Note: The other two exceptions are internal and are caused depending on the compiler hence cannot be shown in the compiler. Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html#add-E- Java - util package java-basics Java-Collections Java-Functions java-queue Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Sep, 2018" }, { "code": null, "e": 314, "s": 28, "text": "The add(E e) method of Queue Interface inserts the element passed in the parameter to the end of the queue if there is space. If the Queue is capacity restricted and no space is left for insertion, it returns an IllegalStateException. The function returns true on successful insertion." }, { "code": null, "e": 322, "s": 314, "text": "Syntax:" }, { "code": null, "e": 339, "s": 322, "text": "boolean add(E e)" }, { "code": null, "e": 456, "s": 339, "text": "Parameters: This method accepts a mandatory parameter e which is the element to be inserted in the end of the Queue." }, { "code": null, "e": 515, "s": 456, "text": "Returns: This method returns true on successful insertion." }, { "code": null, "e": 593, "s": 515, "text": "Exceptions: The function throws four exceptions which are described as below:" }, { "code": null, "e": 705, "s": 593, "text": "ClassCastException: when the class of the element to be entered prevents it from being added to this container." }, { "code": null, "e": 794, "s": 705, "text": "IllegalStateException: when the capacity of the container is full and insertion is done." }, { "code": null, "e": 892, "s": 794, "text": "IllegalArgumentException: when some property of the element prevents it to be added to the queue." }, { "code": null, "e": 1020, "s": 892, "text": "NullPointerException: when the element to be inserted is passed as null and the Queue’s interface does not allow null elements." }, { "code": null, "e": 1069, "s": 1020, "text": "Below programs illustrate add() method of Queue:" }, { "code": null, "e": 1109, "s": 1069, "text": "Program 1: With the help of LinkedList." }, { "code": "// Java Program Demonstrate add()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // before removing print queue System.out.println(\"Queue: \" + Q); }}", "e": 1606, "s": 1109, "text": null }, { "code": null, "e": 1653, "s": 1606, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\n" }, { "code": null, "e": 1693, "s": 1653, "text": "Program 2: With the help of ArrayDeque." }, { "code": "// Java Program Demonstrate add()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ArrayDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // before removing print queue System.out.println(\"Queue: \" + Q); }}", "e": 2190, "s": 1693, "text": null }, { "code": null, "e": 2237, "s": 2190, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\n" }, { "code": null, "e": 2286, "s": 2237, "text": "Program 3: With the help of LinkedBlockingDeque." }, { "code": "// Java Program Demonstrate add()// method of Queue import java.util.*;import java.util.concurrent.LinkedBlockingDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // before removing print queue System.out.println(\"Queue: \" + Q); }}", "e": 2840, "s": 2286, "text": null }, { "code": null, "e": 2887, "s": 2840, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\n" }, { "code": null, "e": 2938, "s": 2887, "text": "Program 4: With the help of ConcurrentLinkedDeque." }, { "code": "// Java Program Demonstrate add()// method of Queue import java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ConcurrentLinkedDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // before removing print queue System.out.println(\"Queue: \" + Q); }}", "e": 3496, "s": 2938, "text": null }, { "code": null, "e": 3543, "s": 3496, "text": "Queue: [7855642, 35658786, 5278367, 74381793]\n" }, { "code": null, "e": 3603, "s": 3543, "text": "Below programs illustrate exceptions thrown by this method:" }, { "code": null, "e": 3644, "s": 3603, "text": "Program 5: To show NullPointerException." }, { "code": "// Java Program Demonstrate add()// method of Queue when Null is passed import java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingQueue<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); try { // when null is inserted Q.add(null); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 4284, "s": 3644, "text": null }, { "code": null, "e": 4327, "s": 4284, "text": "Exception: java.lang.NullPointerException\n" }, { "code": null, "e": 4369, "s": 4327, "text": "Program 6: To show IllegalStateException." }, { "code": "// Java Program Demonstrate add()// method of Queue when capacity is fullimport java.util.*;import java.util.concurrent.LinkedBlockingQueue; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingQueue<Integer>(3); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); try { // when capacity is full Q.add(10); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}", "e": 5008, "s": 4369, "text": null }, { "code": null, "e": 5064, "s": 5008, "text": "Exception: java.lang.IllegalStateException: Queue full\n" }, { "code": null, "e": 5188, "s": 5064, "text": "Note: The other two exceptions are internal and are caused depending on the compiler hence cannot be shown in the compiler." }, { "code": null, "e": 5269, "s": 5188, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html#add-E-" }, { "code": null, "e": 5289, "s": 5269, "text": "Java - util package" }, { "code": null, "e": 5301, "s": 5289, "text": "java-basics" }, { "code": null, "e": 5318, "s": 5301, "text": "Java-Collections" }, { "code": null, "e": 5333, "s": 5318, "text": "Java-Functions" }, { "code": null, "e": 5344, "s": 5333, "text": "java-queue" }, { "code": null, "e": 5349, "s": 5344, "text": "Java" }, { "code": null, "e": 5354, "s": 5349, "text": "Java" }, { "code": null, "e": 5371, "s": 5354, "text": "Java-Collections" } ]
Floyd Warshall Algorithm | DP-16
14 Jun, 2022 The Floyd Warshall Algorithm is for solving the All Pairs Shortest Path problem. The problem is to find shortest distances between every pair of vertices in a given edge weighted directed Graph. Example: Input: graph[][] = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} } which represents the following graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 Note that the value of graph[i][j] is 0 if i is equal to j And graph[i][j] is INF (infinite) if there is no edge from vertex i to j. Output: Shortest distance matrix 0 5 8 9 INF 0 3 4 INF INF 0 1 INF INF INF 0 Floyd Warshall Algorithm We initialize the solution matrix same as the input graph matrix as a first step. Then we update the solution matrix by considering all vertices as an intermediate vertex. The idea is to one by one pick all vertices and updates all shortest paths which include the picked vertex as an intermediate vertex in the shortest path. When we pick vertex number k as an intermediate vertex, we already have considered vertices {0, 1, 2, .. k-1} as intermediate vertices. For every pair (i, j) of the source and destination vertices respectively, there are two possible cases. 1) k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j] as it is. 2) k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j] as dist[i][k] + dist[k][j] if dist[i][j] > dist[i][k] + dist[k][j]The following figure shows the above optimal substructure property in the all-pairs shortest path problem. Following is implementations of the Floyd Warshall algorithm. C++ C Java Python3 C# PHP Javascript // C++ Program for Floyd Warshall Algorithm#include <bits/stdc++.h>using namespace std; // Number of vertices in the graph#define V 4 /* Define Infinite as a large enoughvalue.This value will be used forvertices not connected to each other */#define INF 99999 // A function to print the solution matrixvoid printSolution(int dist[][V]); // Solves the all-pairs shortest path// problem using Floyd Warshall algorithmvoid floydWarshall(int graph[][V]){ /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int dist[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of // dist[i][j] if (dist[i][j] > (dist[i][k] + dist[k][j]) && (dist[k][j] != INF && dist[i][k] != INF)) dist[i][j] = dist[i][k] + dist[k][j]; } } } // Print the shortest distance matrix printSolution(dist);} /* A utility function to print solution */void printSolution(int dist[][V]){ cout << "The following matrix shows the shortest " "distances" " between every pair of vertices \n"; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][j] == INF) cout << "INF" << " "; else cout << dist[i][j] << " "; } cout << endl; }} // Driver codeint main(){ /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ int graph[V][V] = { { 0, 5, INF, 10 }, { INF, 0, 3, INF }, { INF, INF, 0, 1 }, { INF, INF, INF, 0 } }; // Print the solution floydWarshall(graph); return 0;} // This code is contributed by Mythri J L // C Program for Floyd Warshall Algorithm#include<stdio.h> // Number of vertices in the graph#define V 4 /* Define Infinite as a large enough value. This value will be used for vertices not connected to each other */#define INF 99999 // A function to print the solution matrixvoid printSolution(int dist[][V]); // Solves the all-pairs shortest path// problem using Floyd Warshall algorithmvoid floydWarshall (int graph[][V]){ /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int dist[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } // Print the shortest distance matrix printSolution(dist);} /* A utility function to print solution */void printSolution(int dist[][V]){ printf ("The following matrix shows the shortest distances" " between every pair of vertices \n"); for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][j] == INF) printf("%7s", "INF"); else printf ("%7d", dist[i][j]); } printf("\n"); }} // driver program to test above functionint main(){ /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ int graph[V][V] = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} }; // Print the solution floydWarshall(graph); return 0;} // A Java program for Floyd Warshall All Pairs Shortest// Path algorithm.import java.util.*;import java.lang.*;import java.io.*; class AllPairShortestPath{ final static int INF = 99999, V = 4; void floydWarshall(int graph[][]) { int dist[][] = new int[V][V]; int i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } // Print the shortest distance matrix printSolution(dist); } void printSolution(int dist[][]) { System.out.println("The following matrix shows the shortest "+ "distances between every pair of vertices"); for (int i=0; i<V; ++i) { for (int j=0; j<V; ++j) { if (dist[i][j]==INF) System.out.print("INF "); else System.out.print(dist[i][j]+" "); } System.out.println(); } } // Driver program to test above function public static void main (String[] args) { /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ int graph[][] = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} }; AllPairShortestPath a = new AllPairShortestPath(); // Print the solution a.floydWarshall(graph); }} // Contributed by Aakash Hasija # Python Program for Floyd Warshall Algorithm # Number of vertices in the graphV = 4 # Define infinity as the large# enough value. This value will be# used for vertices not connected to each otherINF = 99999 # Solves all pair shortest path# via Floyd Warshall Algorithm def floydWarshall(graph): """ dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices """ """ initializing the solution matrix same as input graph matrix OR we can say that the initial values of shortest distances are based on shortest paths considering no intermediate vertices """ dist = list(map(lambda i: list(map(lambda j: j, i)), graph)) """ Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in the set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} """ for k in range(V): # pick all vertices as source one by one for i in range(V): # Pick all vertices as destination for the # above picked source for j in range(V): # If vertex k is on the shortest path from # i to j, then update the value of dist[i][j] dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j] ) printSolution(dist) # A utility function to print the solutiondef printSolution(dist): print ("Following matrix shows the shortest distances\ between every pair of vertices") for i in range(V): for j in range(V): if(dist[i][j] == INF): print ("%7s" % ("INF"),end=" ") else: print ("%7d\t" % (dist[i][j]),end=' ') if j == V-1: print () # Driver program to test the above program# Let us create the following weighted graph""" 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 """graph = [[0, 5, INF, 10], [INF, 0, 3, INF], [INF, INF, 0, 1], [INF, INF, INF, 0] ]# Print the solutionfloydWarshall(graph)# This code is contributed by Mythri J L // A C# program for Floyd Warshall All// Pairs Shortest Path algorithm. using System; public class AllPairShortestPath{ readonly static int INF = 99999, V = 4; void floydWarshall(int[,] graph) { int[,] dist = new int[V, V]; int i, j, k; // Initialize the solution matrix // same as input graph matrix // Or we can say the initial // values of shortest distances // are based on shortest paths // considering no intermediate // vertex for (i = 0; i < V; i++) { for (j = 0; j < V; j++) { dist[i, j] = graph[i, j]; } } /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ---> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source // one by one for (i = 0; i < V; i++) { // Pick all vertices as destination // for the above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest // path from i to j, then update // the value of dist[i][j] if (dist[i, k] + dist[k, j] < dist[i, j]) { dist[i, j] = dist[i, k] + dist[k, j]; } } } } // Print the shortest distance matrix printSolution(dist); } void printSolution(int[,] dist) { Console.WriteLine("Following matrix shows the shortest "+ "distances between every pair of vertices"); for (int i = 0; i < V; ++i) { for (int j = 0; j < V; ++j) { if (dist[i, j] == INF) { Console.Write("INF "); } else { Console.Write(dist[i, j] + " "); } } Console.WriteLine(); } } // Driver Code public static void Main(string[] args) { /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ int[,] graph = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} }; AllPairShortestPath a = new AllPairShortestPath(); // Print the solution a.floydWarshall(graph); }} // This article is contributed by// Abdul Mateen Mohammed <?php// PHP Program for Floyd Warshall Algorithm // Solves the all-pairs shortest path problem// using Floyd Warshall algorithmfunction floydWarshall ($graph, $V, $INF){ /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ $dist = array(array(0,0,0,0), array(0,0,0,0), array(0,0,0,0), array(0,0,0,0)); /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for ($i = 0; $i < $V; $i++) for ($j = 0; $j < $V; $j++) $dist[$i][$j] = $graph[$i][$j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for ($k = 0; $k < $V; $k++) { // Pick all vertices as source one by one for ($i = 0; $i < $V; $i++) { // Pick all vertices as destination // for the above picked source for ($j = 0; $j < $V; $j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if ($dist[$i][$k] + $dist[$k][$j] < $dist[$i][$j]) $dist[$i][$j] = $dist[$i][$k] + $dist[$k][$j]; } } } // Print the shortest distance matrix printSolution($dist, $V, $INF);} /* A utility function to print solution */function printSolution($dist, $V, $INF){ echo "The following matrix shows the " . "shortest distances between " . "every pair of vertices \n"; for ($i = 0; $i < $V; $i++) { for ($j = 0; $j < $V; $j++) { if ($dist[$i][$j] == $INF) echo "INF " ; else echo $dist[$i][$j], " "; } echo "\n"; }} // Driver Code // Number of vertices in the graph$V = 4 ; /* Define Infinite as a large enoughvalue. This value will be used forvertices not connected to each other */$INF = 99999 ; /* Let us create the following weighted graph 10(0)------->(3) | /|\5 | | | | 1\|/ |(1)------->(2) 3 */$graph = array(array(0, 5, $INF, 10), array($INF, 0, 3, $INF), array($INF, $INF, 0, 1), array($INF, $INF, $INF, 0)); // Print the solutionfloydWarshall($graph, $V, $INF); // This code is contributed by Ryuga?> <script> // A JavaScript program for Floyd Warshall All // Pairs Shortest Path algorithm. var INF = 99999; class AllPairShortestPath { constructor() { this.V = 4; } floydWarshall(graph) { var dist = Array.from(Array(this.V), () => new Array(this.V).fill(0)); var i, j, k; // Initialize the solution matrix // same as input graph matrix // Or we can say the initial // values of shortest distances // are based on shortest paths // considering no intermediate // vertex for (i = 0; i < this.V; i++) { for (j = 0; j < this.V; j++) { dist[i][j] = graph[i][j]; } } /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ---> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < this.V; k++) { // Pick all vertices as source // one by one for (i = 0; i < this.V; i++) { // Pick all vertices as destination // for the above picked source for (j = 0; j < this.V; j++) { // If vertex k is on the shortest // path from i to j, then update // the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } // Print the shortest distance matrix this.printSolution(dist); } printSolution(dist) { document.write( "Following matrix shows the shortest " + "distances between every pair of vertices<br>" ); for (var i = 0; i < this.V; ++i) { for (var j = 0; j < this.V; ++j) { if (dist[i][j] == INF) { document.write(" INF "); } else { document.write(" " + dist[i][j] + " "); } } document.write("<br>"); } } } // Driver Code /* Let us create the following weighted graph 10 (0)------->(3) | /|\ 5 | | | | 1 \|/ | (1)------->(2) 3 */ var graph = [ [0, 5, INF, 10], [INF, 0, 3, INF], [INF, INF, 0, 1], [INF, INF, INF, 0], ]; var a = new AllPairShortestPath(); // Print the solution a.floydWarshall(graph); // This code is contributed by rdtaank. </script> Output: Following matrix shows the shortest distances between every pair of vertices 0 5 8 9 INF 0 3 4 INF INF 0 1 INF INF INF 0 Time Complexity: O(V3) Auxiliary Space: O(V2)The above program only prints the shortest distances. We can modify the solution to print the shortest paths also by storing the predecessor information in a separate 2D matrix. Also, the value of INF can be taken as INT_MAX from limits.h to make sure that we handle maximum possible value. When we take INF as INT_MAX, we need to change the if condition in the above program to avoid arithmetic overflow. #include #define INF INT_MAX .......................... if ( dist[i][k] != INF && dist[k][j] != INF && dist[i][k] + dist[k][j] < dist[i][j] ) dist[i][j] = dist[i][k] + dist[k][j]; ........................... Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Abdul Mateen Mohammed abhayscholar1995 ankthon rathbhupendra mythri1020 mitrukahitesh NikitaRana07 rdtank amartyaghoshgfg technophpfij Samsung Shortest Path Dynamic Programming Graph Samsung Dynamic Programming Graph Shortest Path Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Jun, 2022" }, { "code": null, "e": 259, "s": 54, "text": "The Floyd Warshall Algorithm is for solving the All Pairs Shortest Path problem. The problem is to find shortest distances between every pair of vertices in a given edge weighted directed Graph. Example: " }, { "code": null, "e": 918, "s": 259, "text": "Input:\n graph[][] = { {0, 5, INF, 10},\n {INF, 0, 3, INF},\n {INF, INF, 0, 1},\n {INF, INF, INF, 0} }\nwhich represents the following graph\n 10\n (0)------->(3)\n | /|\\\n 5 | |\n | | 1\n \\|/ |\n (1)------->(2)\n 3 \nNote that the value of graph[i][j] is 0 if i is equal to j \nAnd graph[i][j] is INF (infinite) if there is no edge from vertex i to j.\n\nOutput:\nShortest distance matrix\n 0 5 8 9\n INF 0 3 4\n INF INF 0 1\n INF INF INF 0" }, { "code": null, "e": 1887, "s": 918, "text": "Floyd Warshall Algorithm We initialize the solution matrix same as the input graph matrix as a first step. Then we update the solution matrix by considering all vertices as an intermediate vertex. The idea is to one by one pick all vertices and updates all shortest paths which include the picked vertex as an intermediate vertex in the shortest path. When we pick vertex number k as an intermediate vertex, we already have considered vertices {0, 1, 2, .. k-1} as intermediate vertices. For every pair (i, j) of the source and destination vertices respectively, there are two possible cases. 1) k is not an intermediate vertex in shortest path from i to j. We keep the value of dist[i][j] as it is. 2) k is an intermediate vertex in shortest path from i to j. We update the value of dist[i][j] as dist[i][k] + dist[k][j] if dist[i][j] > dist[i][k] + dist[k][j]The following figure shows the above optimal substructure property in the all-pairs shortest path problem. " }, { "code": null, "e": 1950, "s": 1887, "text": "Following is implementations of the Floyd Warshall algorithm. " }, { "code": null, "e": 1954, "s": 1950, "text": "C++" }, { "code": null, "e": 1956, "s": 1954, "text": "C" }, { "code": null, "e": 1961, "s": 1956, "text": "Java" }, { "code": null, "e": 1969, "s": 1961, "text": "Python3" }, { "code": null, "e": 1972, "s": 1969, "text": "C#" }, { "code": null, "e": 1976, "s": 1972, "text": "PHP" }, { "code": null, "e": 1987, "s": 1976, "text": "Javascript" }, { "code": "// C++ Program for Floyd Warshall Algorithm#include <bits/stdc++.h>using namespace std; // Number of vertices in the graph#define V 4 /* Define Infinite as a large enoughvalue.This value will be used forvertices not connected to each other */#define INF 99999 // A function to print the solution matrixvoid printSolution(int dist[][V]); // Solves the all-pairs shortest path// problem using Floyd Warshall algorithmvoid floydWarshall(int graph[][V]){ /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int dist[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of // dist[i][j] if (dist[i][j] > (dist[i][k] + dist[k][j]) && (dist[k][j] != INF && dist[i][k] != INF)) dist[i][j] = dist[i][k] + dist[k][j]; } } } // Print the shortest distance matrix printSolution(dist);} /* A utility function to print solution */void printSolution(int dist[][V]){ cout << \"The following matrix shows the shortest \" \"distances\" \" between every pair of vertices \\n\"; for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][j] == INF) cout << \"INF\" << \" \"; else cout << dist[i][j] << \" \"; } cout << endl; }} // Driver codeint main(){ /* Let us create the following weighted graph 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 */ int graph[V][V] = { { 0, 5, INF, 10 }, { INF, 0, 3, INF }, { INF, INF, 0, 1 }, { INF, INF, INF, 0 } }; // Print the solution floydWarshall(graph); return 0;} // This code is contributed by Mythri J L", "e": 4955, "s": 1987, "text": null }, { "code": "// C Program for Floyd Warshall Algorithm#include<stdio.h> // Number of vertices in the graph#define V 4 /* Define Infinite as a large enough value. This value will be used for vertices not connected to each other */#define INF 99999 // A function to print the solution matrixvoid printSolution(int dist[][V]); // Solves the all-pairs shortest path// problem using Floyd Warshall algorithmvoid floydWarshall (int graph[][V]){ /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ int dist[V][V], i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } // Print the shortest distance matrix printSolution(dist);} /* A utility function to print solution */void printSolution(int dist[][V]){ printf (\"The following matrix shows the shortest distances\" \" between every pair of vertices \\n\"); for (int i = 0; i < V; i++) { for (int j = 0; j < V; j++) { if (dist[i][j] == INF) printf(\"%7s\", \"INF\"); else printf (\"%7d\", dist[i][j]); } printf(\"\\n\"); }} // driver program to test above functionint main(){ /* Let us create the following weighted graph 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 */ int graph[V][V] = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} }; // Print the solution floydWarshall(graph); return 0;}", "e": 7867, "s": 4955, "text": null }, { "code": "// A Java program for Floyd Warshall All Pairs Shortest// Path algorithm.import java.util.*;import java.lang.*;import java.io.*; class AllPairShortestPath{ final static int INF = 99999, V = 4; void floydWarshall(int graph[][]) { int dist[][] = new int[V][V]; int i, j, k; /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for (i = 0; i < V; i++) for (j = 0; j < V; j++) dist[i][j] = graph[i][j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source one by one for (i = 0; i < V; i++) { // Pick all vertices as destination for the // above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) dist[i][j] = dist[i][k] + dist[k][j]; } } } // Print the shortest distance matrix printSolution(dist); } void printSolution(int dist[][]) { System.out.println(\"The following matrix shows the shortest \"+ \"distances between every pair of vertices\"); for (int i=0; i<V; ++i) { for (int j=0; j<V; ++j) { if (dist[i][j]==INF) System.out.print(\"INF \"); else System.out.print(dist[i][j]+\" \"); } System.out.println(); } } // Driver program to test above function public static void main (String[] args) { /* Let us create the following weighted graph 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 */ int graph[][] = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} }; AllPairShortestPath a = new AllPairShortestPath(); // Print the solution a.floydWarshall(graph); }} // Contributed by Aakash Hasija", "e": 10956, "s": 7867, "text": null }, { "code": "# Python Program for Floyd Warshall Algorithm # Number of vertices in the graphV = 4 # Define infinity as the large# enough value. This value will be# used for vertices not connected to each otherINF = 99999 # Solves all pair shortest path# via Floyd Warshall Algorithm def floydWarshall(graph): \"\"\" dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices \"\"\" \"\"\" initializing the solution matrix same as input graph matrix OR we can say that the initial values of shortest distances are based on shortest paths considering no intermediate vertices \"\"\" dist = list(map(lambda i: list(map(lambda j: j, i)), graph)) \"\"\" Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in the set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} \"\"\" for k in range(V): # pick all vertices as source one by one for i in range(V): # Pick all vertices as destination for the # above picked source for j in range(V): # If vertex k is on the shortest path from # i to j, then update the value of dist[i][j] dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j] ) printSolution(dist) # A utility function to print the solutiondef printSolution(dist): print (\"Following matrix shows the shortest distances\\ between every pair of vertices\") for i in range(V): for j in range(V): if(dist[i][j] == INF): print (\"%7s\" % (\"INF\"),end=\" \") else: print (\"%7d\\t\" % (dist[i][j]),end=' ') if j == V-1: print () # Driver program to test the above program# Let us create the following weighted graph\"\"\" 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 \"\"\"graph = [[0, 5, INF, 10], [INF, 0, 3, INF], [INF, INF, 0, 1], [INF, INF, INF, 0] ]# Print the solutionfloydWarshall(graph)# This code is contributed by Mythri J L", "e": 13498, "s": 10956, "text": null }, { "code": "// A C# program for Floyd Warshall All// Pairs Shortest Path algorithm. using System; public class AllPairShortestPath{ readonly static int INF = 99999, V = 4; void floydWarshall(int[,] graph) { int[,] dist = new int[V, V]; int i, j, k; // Initialize the solution matrix // same as input graph matrix // Or we can say the initial // values of shortest distances // are based on shortest paths // considering no intermediate // vertex for (i = 0; i < V; i++) { for (j = 0; j < V; j++) { dist[i, j] = graph[i, j]; } } /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ---> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < V; k++) { // Pick all vertices as source // one by one for (i = 0; i < V; i++) { // Pick all vertices as destination // for the above picked source for (j = 0; j < V; j++) { // If vertex k is on the shortest // path from i to j, then update // the value of dist[i][j] if (dist[i, k] + dist[k, j] < dist[i, j]) { dist[i, j] = dist[i, k] + dist[k, j]; } } } } // Print the shortest distance matrix printSolution(dist); } void printSolution(int[,] dist) { Console.WriteLine(\"Following matrix shows the shortest \"+ \"distances between every pair of vertices\"); for (int i = 0; i < V; ++i) { for (int j = 0; j < V; ++j) { if (dist[i, j] == INF) { Console.Write(\"INF \"); } else { Console.Write(dist[i, j] + \" \"); } } Console.WriteLine(); } } // Driver Code public static void Main(string[] args) { /* Let us create the following weighted graph 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 */ int[,] graph = { {0, 5, INF, 10}, {INF, 0, 3, INF}, {INF, INF, 0, 1}, {INF, INF, INF, 0} }; AllPairShortestPath a = new AllPairShortestPath(); // Print the solution a.floydWarshall(graph); }} // This article is contributed by// Abdul Mateen Mohammed", "e": 16633, "s": 13498, "text": null }, { "code": "<?php// PHP Program for Floyd Warshall Algorithm // Solves the all-pairs shortest path problem// using Floyd Warshall algorithmfunction floydWarshall ($graph, $V, $INF){ /* dist[][] will be the output matrix that will finally have the shortest distances between every pair of vertices */ $dist = array(array(0,0,0,0), array(0,0,0,0), array(0,0,0,0), array(0,0,0,0)); /* Initialize the solution matrix same as input graph matrix. Or we can say the initial values of shortest distances are based on shortest paths considering no intermediate vertex. */ for ($i = 0; $i < $V; $i++) for ($j = 0; $j < $V; $j++) $dist[$i][$j] = $graph[$i][$j]; /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of an iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ----> After the end of an iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for ($k = 0; $k < $V; $k++) { // Pick all vertices as source one by one for ($i = 0; $i < $V; $i++) { // Pick all vertices as destination // for the above picked source for ($j = 0; $j < $V; $j++) { // If vertex k is on the shortest path from // i to j, then update the value of dist[i][j] if ($dist[$i][$k] + $dist[$k][$j] < $dist[$i][$j]) $dist[$i][$j] = $dist[$i][$k] + $dist[$k][$j]; } } } // Print the shortest distance matrix printSolution($dist, $V, $INF);} /* A utility function to print solution */function printSolution($dist, $V, $INF){ echo \"The following matrix shows the \" . \"shortest distances between \" . \"every pair of vertices \\n\"; for ($i = 0; $i < $V; $i++) { for ($j = 0; $j < $V; $j++) { if ($dist[$i][$j] == $INF) echo \"INF \" ; else echo $dist[$i][$j], \" \"; } echo \"\\n\"; }} // Driver Code // Number of vertices in the graph$V = 4 ; /* Define Infinite as a large enoughvalue. This value will be used forvertices not connected to each other */$INF = 99999 ; /* Let us create the following weighted graph 10(0)------->(3) | /|\\5 | | | | 1\\|/ |(1)------->(2) 3 */$graph = array(array(0, 5, $INF, 10), array($INF, 0, 3, $INF), array($INF, $INF, 0, 1), array($INF, $INF, $INF, 0)); // Print the solutionfloydWarshall($graph, $V, $INF); // This code is contributed by Ryuga?>", "e": 19534, "s": 16633, "text": null }, { "code": "<script> // A JavaScript program for Floyd Warshall All // Pairs Shortest Path algorithm. var INF = 99999; class AllPairShortestPath { constructor() { this.V = 4; } floydWarshall(graph) { var dist = Array.from(Array(this.V), () => new Array(this.V).fill(0)); var i, j, k; // Initialize the solution matrix // same as input graph matrix // Or we can say the initial // values of shortest distances // are based on shortest paths // considering no intermediate // vertex for (i = 0; i < this.V; i++) { for (j = 0; j < this.V; j++) { dist[i][j] = graph[i][j]; } } /* Add all vertices one by one to the set of intermediate vertices. ---> Before start of a iteration, we have shortest distances between all pairs of vertices such that the shortest distances consider only the vertices in set {0, 1, 2, .. k-1} as intermediate vertices. ---> After the end of a iteration, vertex no. k is added to the set of intermediate vertices and the set becomes {0, 1, 2, .. k} */ for (k = 0; k < this.V; k++) { // Pick all vertices as source // one by one for (i = 0; i < this.V; i++) { // Pick all vertices as destination // for the above picked source for (j = 0; j < this.V; j++) { // If vertex k is on the shortest // path from i to j, then update // the value of dist[i][j] if (dist[i][k] + dist[k][j] < dist[i][j]) { dist[i][j] = dist[i][k] + dist[k][j]; } } } } // Print the shortest distance matrix this.printSolution(dist); } printSolution(dist) { document.write( \"Following matrix shows the shortest \" + \"distances between every pair of vertices<br>\" ); for (var i = 0; i < this.V; ++i) { for (var j = 0; j < this.V; ++j) { if (dist[i][j] == INF) { document.write(\" INF \"); } else { document.write(\" \" + dist[i][j] + \" \"); } } document.write(\"<br>\"); } } } // Driver Code /* Let us create the following weighted graph 10 (0)------->(3) | /|\\ 5 | | | | 1 \\|/ | (1)------->(2) 3 */ var graph = [ [0, 5, INF, 10], [INF, 0, 3, INF], [INF, INF, 0, 1], [INF, INF, INF, 0], ]; var a = new AllPairShortestPath(); // Print the solution a.floydWarshall(graph); // This code is contributed by rdtaank. </script>", "e": 22567, "s": 19534, "text": null }, { "code": null, "e": 22576, "s": 22567, "text": "Output: " }, { "code": null, "e": 22769, "s": 22576, "text": "Following matrix shows the shortest distances between every pair of vertices\n 0 5 8 9\n INF 0 3 4\n INF INF 0 1\n INF INF INF 0" }, { "code": null, "e": 22792, "s": 22769, "text": "Time Complexity: O(V3)" }, { "code": null, "e": 23221, "s": 22792, "text": "Auxiliary Space: O(V2)The above program only prints the shortest distances. We can modify the solution to print the shortest paths also by storing the predecessor information in a separate 2D matrix. Also, the value of INF can be taken as INT_MAX from limits.h to make sure that we handle maximum possible value. When we take INF as INT_MAX, we need to change the if condition in the above program to avoid arithmetic overflow. " }, { "code": null, "e": 23448, "s": 23221, "text": "#include \n\n#define INF INT_MAX\n..........................\nif ( dist[i][k] != INF && \n dist[k][j] != INF && \n dist[i][k] + dist[k][j] < dist[i][j]\n )\n dist[i][j] = dist[i][k] + dist[k][j];\n..........................." }, { "code": null, "e": 23572, "s": 23448, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 23594, "s": 23572, "text": "Abdul Mateen Mohammed" }, { "code": null, "e": 23611, "s": 23594, "text": "abhayscholar1995" }, { "code": null, "e": 23619, "s": 23611, "text": "ankthon" }, { "code": null, "e": 23633, "s": 23619, "text": "rathbhupendra" }, { "code": null, "e": 23644, "s": 23633, "text": "mythri1020" }, { "code": null, "e": 23658, "s": 23644, "text": "mitrukahitesh" }, { "code": null, "e": 23671, "s": 23658, "text": "NikitaRana07" }, { "code": null, "e": 23678, "s": 23671, "text": "rdtank" }, { "code": null, "e": 23694, "s": 23678, "text": "amartyaghoshgfg" }, { "code": null, "e": 23707, "s": 23694, "text": "technophpfij" }, { "code": null, "e": 23715, "s": 23707, "text": "Samsung" }, { "code": null, "e": 23729, "s": 23715, "text": "Shortest Path" }, { "code": null, "e": 23749, "s": 23729, "text": "Dynamic Programming" }, { "code": null, "e": 23755, "s": 23749, "text": "Graph" }, { "code": null, "e": 23763, "s": 23755, "text": "Samsung" }, { "code": null, "e": 23783, "s": 23763, "text": "Dynamic Programming" }, { "code": null, "e": 23789, "s": 23783, "text": "Graph" }, { "code": null, "e": 23803, "s": 23789, "text": "Shortest Path" } ]
numpy.radians() and deg2rad() in Python
04 Dec, 2020 The numpy.radians() is a mathematical function that helps user to convert angles from degree to radians. Syntax : numpy.radians(x[, out]) = ufunc ‘radians’)Parameters : array : [array_like] elements are in degrees.out : [ndaaray, optional]Output array of same shape as x. 2pi Radians = 36o degrees Return : An array with radian values in place of degree values. Code #1 : Working # Python3 program explaining# degrees() function import numpy as npimport math in_array = np.arange(10.) * 90print ("Degree values : \n", in_array) radian_Values = np.radians(in_array)print ("\nRadian values : \n", radian_Values) Output : Degree values : [ 0. 90. 180. 270. 360. 450. 540. 630. 720. 810.] Radian values : [ 0. 1.57079633 3.14159265 4.71238898 6.28318531 7.85398163 9.42477796 10.99557429 12.56637061 14.13716694] numpy.deg2rad(x[, out]) = ufunc ‘deg2rad’) : This mathematical function helps user to convert angles from degrees to radians Parameters : array : [array_like] elements are in radians.out : [ndaaray, optional]Output array of same shape as x. 2pi Radians = 36o degrees Return : Corresponding angles in radians. Code #2 : deg2rad() Equivalent to radians() # Python3 program explaining# rad2deg() function import numpy as npimport math degree = np.arange(10.) * 90print ("Degree values : \n", degree) radian = np.deg2rad(degree)print ("\nradian values : \n", radian) Output : Degree values : [ 0. 90. 180. 270. 360. 450. 540. 630. 720. 810.] radian values : [ 0. 1.57079633 3.14159265 4.71238898 6.28318531 7.85398163 9.42477796 10.99557429 12.56637061 14.13716694] References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.radians.html#numpy.radians. 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 How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Dec, 2020" }, { "code": null, "e": 133, "s": 28, "text": "The numpy.radians() is a mathematical function that helps user to convert angles from degree to radians." }, { "code": null, "e": 197, "s": 133, "text": "Syntax : numpy.radians(x[, out]) = ufunc ‘radians’)Parameters :" }, { "code": null, "e": 335, "s": 197, "text": "array : [array_like] elements are in degrees.out : [ndaaray, optional]Output array of same shape as x. 2pi Radians = 36o degrees" }, { "code": null, "e": 399, "s": 335, "text": "Return : An array with radian values in place of degree values." }, { "code": null, "e": 418, "s": 399, "text": " Code #1 : Working" }, { "code": "# Python3 program explaining# degrees() function import numpy as npimport math in_array = np.arange(10.) * 90print (\"Degree values : \\n\", in_array) radian_Values = np.radians(in_array)print (\"\\nRadian values : \\n\", radian_Values)", "e": 651, "s": 418, "text": null }, { "code": null, "e": 660, "s": 651, "text": "Output :" }, { "code": null, "e": 893, "s": 660, "text": "Degree values : \n [ 0. 90. 180. 270. 360. 450. 540. 630. 720. 810.]\n\nRadian values : \n [ 0. 1.57079633 3.14159265 4.71238898 6.28318531\n 7.85398163 9.42477796 10.99557429 12.56637061 14.13716694]\n" }, { "code": null, "e": 1020, "s": 895, "text": "numpy.deg2rad(x[, out]) = ufunc ‘deg2rad’) : This mathematical function helps user to convert angles from degrees to radians" }, { "code": null, "e": 1033, "s": 1020, "text": "Parameters :" }, { "code": null, "e": 1171, "s": 1033, "text": "array : [array_like] elements are in radians.out : [ndaaray, optional]Output array of same shape as x. 2pi Radians = 36o degrees" }, { "code": null, "e": 1213, "s": 1171, "text": "Return : Corresponding angles in radians." }, { "code": null, "e": 1258, "s": 1213, "text": " Code #2 : deg2rad() Equivalent to radians()" }, { "code": "# Python3 program explaining# rad2deg() function import numpy as npimport math degree = np.arange(10.) * 90print (\"Degree values : \\n\", degree) radian = np.deg2rad(degree)print (\"\\nradian values : \\n\", radian)", "e": 1471, "s": 1258, "text": null }, { "code": null, "e": 1480, "s": 1471, "text": "Output :" }, { "code": null, "e": 1713, "s": 1480, "text": "Degree values : \n [ 0. 90. 180. 270. 360. 450. 540. 630. 720. 810.]\n\nradian values : \n [ 0. 1.57079633 3.14159265 4.71238898 6.28318531\n 7.85398163 9.42477796 10.99557429 12.56637061 14.13716694]\n" }, { "code": null, "e": 1818, "s": 1713, "text": " References : https://docs.scipy.org/doc/numpy-dev/reference/generated/numpy.radians.html#numpy.radians." }, { "code": null, "e": 1853, "s": 1818, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 1866, "s": 1853, "text": "Python-numpy" }, { "code": null, "e": 1873, "s": 1866, "text": "Python" }, { "code": null, "e": 1971, "s": 1873, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1989, "s": 1971, "text": "Python Dictionary" }, { "code": null, "e": 2031, "s": 1989, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2053, "s": 2031, "text": "Enumerate() in Python" }, { "code": null, "e": 2088, "s": 2053, "text": "Read a file line by line in Python" }, { "code": null, "e": 2120, "s": 2088, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2146, "s": 2120, "text": "Python String | replace()" }, { "code": null, "e": 2175, "s": 2146, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2202, "s": 2175, "text": "Python Classes and Objects" }, { "code": null, "e": 2223, "s": 2202, "text": "Python OOPs Concepts" } ]
Minimum squares to cover a rectangle
13 Jun, 2022 Given a rectangle with length l and breadth b, we need to find the minimum number of squares that can cover the surface of the rectangle, given that each square has a side of length a. It is allowed to cover the surface larger than the rectangle, but the rectangle has to be covered. It is not allowed to break the square.Examples: Input : 1 2 3 Output :1 We have a 3x3 square and we need to make a rectangle of size 1x2. So we need only 1 square to cover the rectangle. Input : 11 23 14 Output :2 The only way to actually fill the rectangle optimally is to arrange each square such that it is parallel to the sides of the rectangle. So we just need to find the number of squares to fully cover the length and breadth of the rectangle. The length of the rectangle is l, and if the side length of the square is a divided l, then there must be l/a squares to cover the full length of l. If l isn’t divisible by a, we need to add 1 to l/a, to round it down. For this, we can use the ceil function, as ceil(x) returns the least integer which is above or equal to x. We can do the same with the rectangle width and take the number of squares across the width to be ceil(b/a). So, total number of squares=ceil(m/a) * ceil(n/a). C++ Java Python 3 C# PHP Javascript // C++ program to find the minimum number// of squares to cover the surface of the// rectangle with given dimensions#include <bits/stdc++.h>using namespace std;int squares(int l, int b, int a){ // function to count // the number of squares that can // cover the surface of the rectangle return ceil(l / (double)a) * ceil(b / (double)a);} // Driver codeint main(){ int l = 11, b = 23, a = 14; cout << squares(l, b, a) << endl; return 0;} // Java program to find the minimum number// of squares to cover the surface of the// rectangle with given dimensionsclass GFG{static int squares(int l, int b, int a){ // function to count// the number of squares that can// cover the surface of the rectanglereturn (int)(Math.ceil(l / (double)a) * Math.ceil(b / (double)a));} // Driver codepublic static void main(String[] args){ int l = 11, b = 23, a = 14; System.out.println(squares(l, b, a));}} // This code is contributed by ChitraNayal # Python3 program to find the minimum number# of squares to cover the surface of the# rectangle with given dimensionsimport math def squares(l, b, a): # function to count # the number of squares that can # cover the surface of the rectangle return math.ceil(l / a) * math.ceil(b / a) # Driver codeif __name__ == "__main__": l = 11 b = 23 a = 14 print(squares(l, b, a)) # This code is contributed# by ChitraNayal // C# program to find the minimum number// of squares to cover the surface of the// rectangle with given dimensionsusing System; class GFG{static int squares(int l, int b, int a){ // function to count// the number of squares that can// cover the surface of the rectanglereturn (int)(Math.Ceiling(l / (double)a) * Math.Ceiling(b / (double)a));} // Driver codepublic static void Main(){ int l = 11, b = 23, a = 14; Console.Write(squares(l, b, a));}} // This code is contributed by ChitraNayal <?php// PHP program to find the minimum number// of squares to cover the surface of the// rectangle with given dimensions function squares($l, $b, $a){ // function to count // the number of squares that can // cover the surface of the rectangle return ceil($l / (double)$a) * ceil($b / (double)$a);} // Driver code$l = 11;$b = 23;$a = 14;echo squares($l, $b, $a); // This code is contributed// by ChitraNayal?> <script> // javascript program to find the minimum number// of squares to cover the surface of the// rectangle with given dimensions function squares(l , b , a){ // function to count // the number of squares that can // cover the surface of the rectangle return parseInt(Math.ceil(l / a) * Math.ceil(b / a));} // Driver code var l = 11, b = 23, a = 14;document.write(squares(l, b, a)); // This code is contributed by Amit Katiyar </script> 2 Time complexity: O(1) Auxiliary Space: O(1) YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=5M08zWeC6x4" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ukasp amit143katiyar everyonemaurya7 hasani square-rectangle Geometric Mathematical School Programming Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Optimum location of point to minimize total distance Check whether a given point lies inside a triangle or not Program for Point of Intersection of Two Lines Given n line segments, find if any two segments intersect Window to Viewport Transformation in Computer Graphics with Implementation Program for Fibonacci numbers Set in C++ Standard Template Library (STL) Write a program to print all permutations of a given string C++ Data Types Merge two sorted arrays
[ { "code": null, "e": 52, "s": 24, "text": "\n13 Jun, 2022" }, { "code": null, "e": 386, "s": 52, "text": "Given a rectangle with length l and breadth b, we need to find the minimum number of squares that can cover the surface of the rectangle, given that each square has a side of length a. It is allowed to cover the surface larger than the rectangle, but the rectangle has to be covered. It is not allowed to break the square.Examples: " }, { "code": null, "e": 553, "s": 386, "text": "Input : 1 2 3\nOutput :1\nWe have a 3x3 square and we need\nto make a rectangle of size 1x2.\nSo we need only 1 square to cover the\nrectangle.\n\nInput : 11 23 14\nOutput :2" }, { "code": null, "e": 1280, "s": 555, "text": "The only way to actually fill the rectangle optimally is to arrange each square such that it is parallel to the sides of the rectangle. So we just need to find the number of squares to fully cover the length and breadth of the rectangle. The length of the rectangle is l, and if the side length of the square is a divided l, then there must be l/a squares to cover the full length of l. If l isn’t divisible by a, we need to add 1 to l/a, to round it down. For this, we can use the ceil function, as ceil(x) returns the least integer which is above or equal to x. We can do the same with the rectangle width and take the number of squares across the width to be ceil(b/a). So, total number of squares=ceil(m/a) * ceil(n/a). " }, { "code": null, "e": 1284, "s": 1280, "text": "C++" }, { "code": null, "e": 1289, "s": 1284, "text": "Java" }, { "code": null, "e": 1298, "s": 1289, "text": "Python 3" }, { "code": null, "e": 1301, "s": 1298, "text": "C#" }, { "code": null, "e": 1305, "s": 1301, "text": "PHP" }, { "code": null, "e": 1316, "s": 1305, "text": "Javascript" }, { "code": "// C++ program to find the minimum number// of squares to cover the surface of the// rectangle with given dimensions#include <bits/stdc++.h>using namespace std;int squares(int l, int b, int a){ // function to count // the number of squares that can // cover the surface of the rectangle return ceil(l / (double)a) * ceil(b / (double)a);} // Driver codeint main(){ int l = 11, b = 23, a = 14; cout << squares(l, b, a) << endl; return 0;}", "e": 1774, "s": 1316, "text": null }, { "code": "// Java program to find the minimum number// of squares to cover the surface of the// rectangle with given dimensionsclass GFG{static int squares(int l, int b, int a){ // function to count// the number of squares that can// cover the surface of the rectanglereturn (int)(Math.ceil(l / (double)a) * Math.ceil(b / (double)a));} // Driver codepublic static void main(String[] args){ int l = 11, b = 23, a = 14; System.out.println(squares(l, b, a));}} // This code is contributed by ChitraNayal", "e": 2287, "s": 1774, "text": null }, { "code": "# Python3 program to find the minimum number# of squares to cover the surface of the# rectangle with given dimensionsimport math def squares(l, b, a): # function to count # the number of squares that can # cover the surface of the rectangle return math.ceil(l / a) * math.ceil(b / a) # Driver codeif __name__ == \"__main__\": l = 11 b = 23 a = 14 print(squares(l, b, a)) # This code is contributed# by ChitraNayal", "e": 2728, "s": 2287, "text": null }, { "code": "// C# program to find the minimum number// of squares to cover the surface of the// rectangle with given dimensionsusing System; class GFG{static int squares(int l, int b, int a){ // function to count// the number of squares that can// cover the surface of the rectanglereturn (int)(Math.Ceiling(l / (double)a) * Math.Ceiling(b / (double)a));} // Driver codepublic static void Main(){ int l = 11, b = 23, a = 14; Console.Write(squares(l, b, a));}} // This code is contributed by ChitraNayal", "e": 3241, "s": 2728, "text": null }, { "code": "<?php// PHP program to find the minimum number// of squares to cover the surface of the// rectangle with given dimensions function squares($l, $b, $a){ // function to count // the number of squares that can // cover the surface of the rectangle return ceil($l / (double)$a) * ceil($b / (double)$a);} // Driver code$l = 11;$b = 23;$a = 14;echo squares($l, $b, $a); // This code is contributed// by ChitraNayal?>", "e": 3674, "s": 3241, "text": null }, { "code": "<script> // javascript program to find the minimum number// of squares to cover the surface of the// rectangle with given dimensions function squares(l , b , a){ // function to count // the number of squares that can // cover the surface of the rectangle return parseInt(Math.ceil(l / a) * Math.ceil(b / a));} // Driver code var l = 11, b = 23, a = 14;document.write(squares(l, b, a)); // This code is contributed by Amit Katiyar </script>", "e": 4147, "s": 3674, "text": null }, { "code": null, "e": 4149, "s": 4147, "text": "2" }, { "code": null, "e": 4173, "s": 4151, "text": "Time complexity: O(1)" }, { "code": null, "e": 4195, "s": 4173, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 4487, "s": 4195, "text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=5M08zWeC6x4\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 4493, "s": 4487, "text": "ukasp" }, { "code": null, "e": 4508, "s": 4493, "text": "amit143katiyar" }, { "code": null, "e": 4524, "s": 4508, "text": "everyonemaurya7" }, { "code": null, "e": 4531, "s": 4524, "text": "hasani" }, { "code": null, "e": 4548, "s": 4531, "text": "square-rectangle" }, { "code": null, "e": 4558, "s": 4548, "text": "Geometric" }, { "code": null, "e": 4571, "s": 4558, "text": "Mathematical" }, { "code": null, "e": 4590, "s": 4571, "text": "School Programming" }, { "code": null, "e": 4603, "s": 4590, "text": "Mathematical" }, { "code": null, "e": 4613, "s": 4603, "text": "Geometric" }, { "code": null, "e": 4711, "s": 4613, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4764, "s": 4711, "text": "Optimum location of point to minimize total distance" }, { "code": null, "e": 4822, "s": 4764, "text": "Check whether a given point lies inside a triangle or not" }, { "code": null, "e": 4869, "s": 4822, "text": "Program for Point of Intersection of Two Lines" }, { "code": null, "e": 4927, "s": 4869, "text": "Given n line segments, find if any two segments intersect" }, { "code": null, "e": 5002, "s": 4927, "text": "Window to Viewport Transformation in Computer Graphics with Implementation" }, { "code": null, "e": 5032, "s": 5002, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 5075, "s": 5032, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 5135, "s": 5075, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 5150, "s": 5135, "text": "C++ Data Types" } ]
Scala Console | println, printf and readLine
10 Apr, 2019 Console implements functions for displaying the stated values on the terminal i.e, with print, println, and printf we can post to the display. It is also utilized in reading values from the Console with the function from scala.io.StdIn. It is even helpful in constructing interactive programs.Let’s discuss it in detail and also lets see some examples related to it. println:It is utilized in putting down values to the Console and moreover computes a trailing newline. we can pass any types as argument to it. Print:It is equivalent to println but it does not computes any trailing line. It puts down the data to the beginning of the line. printf:This is helpful in writing format strings and also places extra arguments.Example:// Scala program of print// functions // Creating an objectobject GfG{ // Main method def main(args: Array[String]) { // Applying console with println Console.println("GeeksfoGeeks") // Displays output with no // trailing lines print("CS") print("_portal") // Used for a newline println() // Displays format string printf("Age = %d", 24) }}Output:GeeksfoGeeks CS_portal Age = 24 The println and Console.println both are equivalent. // Scala program of print// functions // Creating an objectobject GfG{ // Main method def main(args: Array[String]) { // Applying console with println Console.println("GeeksfoGeeks") // Displays output with no // trailing lines print("CS") print("_portal") // Used for a newline println() // Displays format string printf("Age = %d", 24) }} GeeksfoGeeks CS_portal Age = 24 The println and Console.println both are equivalent. readLine():It is a method in which user gives inputs in the pattern of String from the keyboard.Example:// Scala program of readLine()// method // Creating an objectobject GfG {// Main methoddef main(args: Array[String]) {// Applying a loopwhile (true) { // Reads the line from the Console val result = scala.io.StdIn.readLine() // Displays the string that is // given by the user printf("Enter the String: %s", result) //prints newline println() } }}Output://giving user defined inputs GfG //output by readline Enter the String: Gfg //again giving inputs Nidhi //output Enter the String: Nidhi Here, the while loop is infinite in nature and after giving user inputs the variable will contains that (GfG) string and if again we given any input then the variable will contain that (Nidhi) input. // Scala program of readLine()// method // Creating an objectobject GfG {// Main methoddef main(args: Array[String]) {// Applying a loopwhile (true) { // Reads the line from the Console val result = scala.io.StdIn.readLine() // Displays the string that is // given by the user printf("Enter the String: %s", result) //prints newline println() } }} //giving user defined inputs GfG //output by readline Enter the String: Gfg //again giving inputs Nidhi //output Enter the String: Nidhi Here, the while loop is infinite in nature and after giving user inputs the variable will contains that (GfG) string and if again we given any input then the variable will contain that (Nidhi) input. Scala Scala-Basics Scala Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Apr, 2019" }, { "code": null, "e": 395, "s": 28, "text": "Console implements functions for displaying the stated values on the terminal i.e, with print, println, and printf we can post to the display. It is also utilized in reading values from the Console with the function from scala.io.StdIn. It is even helpful in constructing interactive programs.Let’s discuss it in detail and also lets see some examples related to it." }, { "code": null, "e": 539, "s": 395, "text": "println:It is utilized in putting down values to the Console and moreover computes a trailing newline. we can pass any types as argument to it." }, { "code": null, "e": 669, "s": 539, "text": "Print:It is equivalent to println but it does not computes any trailing line. It puts down the data to the beginning of the line." }, { "code": null, "e": 1284, "s": 669, "text": "printf:This is helpful in writing format strings and also places extra arguments.Example:// Scala program of print// functions // Creating an objectobject GfG{ // Main method def main(args: Array[String]) { // Applying console with println Console.println(\"GeeksfoGeeks\") // Displays output with no // trailing lines print(\"CS\") print(\"_portal\") // Used for a newline println() // Displays format string printf(\"Age = %d\", 24) }}Output:GeeksfoGeeks\nCS_portal\nAge = 24\nThe println and Console.println both are equivalent." }, { "code": "// Scala program of print// functions // Creating an objectobject GfG{ // Main method def main(args: Array[String]) { // Applying console with println Console.println(\"GeeksfoGeeks\") // Displays output with no // trailing lines print(\"CS\") print(\"_portal\") // Used for a newline println() // Displays format string printf(\"Age = %d\", 24) }}", "e": 1719, "s": 1284, "text": null }, { "code": null, "e": 1752, "s": 1719, "text": "GeeksfoGeeks\nCS_portal\nAge = 24\n" }, { "code": null, "e": 1805, "s": 1752, "text": "The println and Console.println both are equivalent." }, { "code": null, "e": 2644, "s": 1805, "text": "readLine():It is a method in which user gives inputs in the pattern of String from the keyboard.Example:// Scala program of readLine()// method // Creating an objectobject GfG {// Main methoddef main(args: Array[String]) {// Applying a loopwhile (true) { // Reads the line from the Console val result = scala.io.StdIn.readLine() // Displays the string that is // given by the user printf(\"Enter the String: %s\", result) //prints newline println() } }}Output://giving user defined inputs\nGfG \n//output by readline\nEnter the String: Gfg \n//again giving inputs\nNidhi \n//output\nEnter the String: Nidhi \nHere, the while loop is infinite in nature and after giving user inputs the variable will contains that (GfG) string and if again we given any input then the variable will contain that (Nidhi) input." }, { "code": "// Scala program of readLine()// method // Creating an objectobject GfG {// Main methoddef main(args: Array[String]) {// Applying a loopwhile (true) { // Reads the line from the Console val result = scala.io.StdIn.readLine() // Displays the string that is // given by the user printf(\"Enter the String: %s\", result) //prints newline println() } }}", "e": 3032, "s": 2644, "text": null }, { "code": null, "e": 3174, "s": 3032, "text": "//giving user defined inputs\nGfG \n//output by readline\nEnter the String: Gfg \n//again giving inputs\nNidhi \n//output\nEnter the String: Nidhi \n" }, { "code": null, "e": 3374, "s": 3174, "text": "Here, the while loop is infinite in nature and after giving user inputs the variable will contains that (GfG) string and if again we given any input then the variable will contain that (Nidhi) input." }, { "code": null, "e": 3380, "s": 3374, "text": "Scala" }, { "code": null, "e": 3393, "s": 3380, "text": "Scala-Basics" }, { "code": null, "e": 3399, "s": 3393, "text": "Scala" } ]
Tensorflow | tf.data.Dataset.from_tensor_slices()
03 Oct, 2019 With the help of tf.data.Dataset.from_tensor_slices() method, we can get the slices of an array in the form of objects by using tf.data.Dataset.from_tensor_slices() method. Syntax : tf.data.Dataset.from_tensor_slices(list)Return : Return the objects of sliced elements. Example #1 :In this example we can see that by using tf.data.Dataset.from_tensor_slices() method, we are able to get the slices of list or array. # import tensorflowimport tensorflow as tf # using tf.data.Dataset.from_tensor_slices() methodgfg = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5]) for ele in gfg: print(ele.numpy()) Output : 12345 Example #2 : # import tensorflowimport tensorflow as tf # using tf.data.Dataset.from_tensor_slices() methodgfg = tf.data.Dataset.from_tensor_slices([[5, 10], [3, 6]]) for ele in gfg: print(ele.numpy()) Output : [5, 10][3, 6] Tensorflow Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n03 Oct, 2019" }, { "code": null, "e": 226, "s": 53, "text": "With the help of tf.data.Dataset.from_tensor_slices() method, we can get the slices of an array in the form of objects by using tf.data.Dataset.from_tensor_slices() method." }, { "code": null, "e": 323, "s": 226, "text": "Syntax : tf.data.Dataset.from_tensor_slices(list)Return : Return the objects of sliced elements." }, { "code": null, "e": 469, "s": 323, "text": "Example #1 :In this example we can see that by using tf.data.Dataset.from_tensor_slices() method, we are able to get the slices of list or array." }, { "code": "# import tensorflowimport tensorflow as tf # using tf.data.Dataset.from_tensor_slices() methodgfg = tf.data.Dataset.from_tensor_slices([1, 2, 3, 4, 5]) for ele in gfg: print(ele.numpy())", "e": 661, "s": 469, "text": null }, { "code": null, "e": 670, "s": 661, "text": "Output :" }, { "code": null, "e": 676, "s": 670, "text": "12345" }, { "code": null, "e": 689, "s": 676, "text": "Example #2 :" }, { "code": "# import tensorflowimport tensorflow as tf # using tf.data.Dataset.from_tensor_slices() methodgfg = tf.data.Dataset.from_tensor_slices([[5, 10], [3, 6]]) for ele in gfg: print(ele.numpy())", "e": 883, "s": 689, "text": null }, { "code": null, "e": 892, "s": 883, "text": "Output :" }, { "code": null, "e": 906, "s": 892, "text": "[5, 10][3, 6]" }, { "code": null, "e": 917, "s": 906, "text": "Tensorflow" }, { "code": null, "e": 924, "s": 917, "text": "Python" }, { "code": null, "e": 943, "s": 924, "text": "Technical Scripter" } ]
Internet Message Access Protocol (IMAP)
22 Jan, 2021 Prerequisite – Protocols in Application Layer Internet Message Access Protocol (IMAP) is an application layer protocol that operates as a contract for receiving emails from the mail server. It was designed by Mark Crispin in 1986 as a remote access mailbox protocol, the current version of IMAP is IMAP4. It is used as the most commonly used protocol for retrieving emails. This term is also known as Internet mail access protocol, Interactive mail access protocol, and Interim mail access protocol. Features of IMAP : It is capable of managing multiple mailboxes and organizing them into various categories. Provides adding of message flags to keep track of which messages are being seen. It is capable of deciding whether to retrieve email from a mail server before downloading. It makes it easy to download media when multiple files are attached. Working of IMAP :IMAP follows Client-server Architecture and is the most commonly used email protocol. It is a combination of client and server process running on other computers that are connected through a network. This protocol resides over the TCP/IP protocol for communication. Once the communication is set up the server listens on port 143 by default which is non-encrypted. For the secure encrypted communication port, 993 is used. Architecture of IMAP : Advantages : It offers synchronization across all the maintained sessions by the user. It provides security over POP3 protocol as the email only exists on the IMAP server. Users have remote access to all the contents. It offers easy migration between the devices as it is synchronized by a centralized server. There is no need to physically allocate any storage to save contents. Disadvantages : IMAP is complex to maintain. Emails of the user are only available when there is an internet connection. It is slower to load messages. Some emails don’t support IMAP which makes it difficult to manage. Many browser-based solutions are unavailable due to not support of IMAP. Computer Networks GATE CS Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Jan, 2021" }, { "code": null, "e": 98, "s": 52, "text": "Prerequisite – Protocols in Application Layer" }, { "code": null, "e": 552, "s": 98, "text": "Internet Message Access Protocol (IMAP) is an application layer protocol that operates as a contract for receiving emails from the mail server. It was designed by Mark Crispin in 1986 as a remote access mailbox protocol, the current version of IMAP is IMAP4. It is used as the most commonly used protocol for retrieving emails. This term is also known as Internet mail access protocol, Interactive mail access protocol, and Interim mail access protocol." }, { "code": null, "e": 571, "s": 552, "text": "Features of IMAP :" }, { "code": null, "e": 661, "s": 571, "text": "It is capable of managing multiple mailboxes and organizing them into various categories." }, { "code": null, "e": 742, "s": 661, "text": "Provides adding of message flags to keep track of which messages are being seen." }, { "code": null, "e": 833, "s": 742, "text": "It is capable of deciding whether to retrieve email from a mail server before downloading." }, { "code": null, "e": 902, "s": 833, "text": "It makes it easy to download media when multiple files are attached." }, { "code": null, "e": 1342, "s": 902, "text": "Working of IMAP :IMAP follows Client-server Architecture and is the most commonly used email protocol. It is a combination of client and server process running on other computers that are connected through a network. This protocol resides over the TCP/IP protocol for communication. Once the communication is set up the server listens on port 143 by default which is non-encrypted. For the secure encrypted communication port, 993 is used." }, { "code": null, "e": 1365, "s": 1342, "text": "Architecture of IMAP :" }, { "code": null, "e": 1378, "s": 1365, "text": "Advantages :" }, { "code": null, "e": 1452, "s": 1378, "text": "It offers synchronization across all the maintained sessions by the user." }, { "code": null, "e": 1537, "s": 1452, "text": "It provides security over POP3 protocol as the email only exists on the IMAP server." }, { "code": null, "e": 1583, "s": 1537, "text": "Users have remote access to all the contents." }, { "code": null, "e": 1675, "s": 1583, "text": "It offers easy migration between the devices as it is synchronized by a centralized server." }, { "code": null, "e": 1745, "s": 1675, "text": "There is no need to physically allocate any storage to save contents." }, { "code": null, "e": 1761, "s": 1745, "text": "Disadvantages :" }, { "code": null, "e": 1790, "s": 1761, "text": "IMAP is complex to maintain." }, { "code": null, "e": 1866, "s": 1790, "text": "Emails of the user are only available when there is an internet connection." }, { "code": null, "e": 1897, "s": 1866, "text": "It is slower to load messages." }, { "code": null, "e": 1964, "s": 1897, "text": "Some emails don’t support IMAP which makes it difficult to manage." }, { "code": null, "e": 2037, "s": 1964, "text": "Many browser-based solutions are unavailable due to not support of IMAP." }, { "code": null, "e": 2055, "s": 2037, "text": "Computer Networks" }, { "code": null, "e": 2063, "s": 2055, "text": "GATE CS" }, { "code": null, "e": 2081, "s": 2063, "text": "Computer Networks" } ]
Default Interface Methods in C# 8.0
06 Dec, 2019 Before C# 8.0 interfaces only contain the declaration of the members(methods, properties, events, and indexers), but from C# 8.0 it is allowed to add members as well as their implementation to the interface. Now you are allowed to add a method with their implementation to the interface without breaking the existing implementation of the interface, such type of methods is known as default interface methods(also known as the virtual extension methods). This feature allows programmers to use the traits programming technique (Traits are object-oriented programming technique which allows the reuse of the methods between unrelated classes). Important Points: You are allowed to implement indexer, property, or event accessor in the interface. You are allowed to use access modifiers like private, protected, internal, public, virtual, abstract, override, sealed, static, extern with default methods, properties, etc. in the interface. And be careful while using modifier keywords. You are allowed to create static fields, methods, properties, indexers, and events in the interface. You can override modifiers. The explicit access modifiers with default access are public. If an interface contains default method and inherited by some specified class, then the class does not know anything about the existence of the default methods of that interface and also does not contain the implementation of the default method. If you override a default method, then there is no need to use any modifier. As shown in example 2. You are allowed to use parameters in the default method. As shown in example 3. You are allowed to use the same name methods in the interface, but they must have different parameter lists. As shown in example 3. You are allowed to extend the default method. Now discuss this concept with the help of the given example. In this example, we have an interface named I_interface which contains two methods, i.e. display_1 and display_2. Here, the display_1() method is only declared in the I_interface and does not contain its definition, whereas the display_2() method contains both declaration and its definition, such type of method is known as default interface methods. Example 1: // C# program to illustrate the concept// of the default interface methodusing System; // A simple interfaceinterface I_interface { // This method is only // have its declaration // not its definition void display_1(); // Default method with both // declaration and definition public void display_2() { Console.WriteLine("Hello!! Default Method"); }} // A class that implements// the I_interface interface.class Example_Class : I_interface { // Providing the body // part of the method public void display_1() { Console.WriteLine("Hello!! Method"); } // Main Method public static void Main(String[] args) { // Creating an object Example_Class t = new Example_Class(); // Calling method t.display_1(); // Creating an object I_interface obj = t; // Calling default method obj.display_2(); }} Output: Hello!! Method Hello!! Default Method Now, we call the display_2() method with the help of the I_interface interface. If you try to call this method with the class object // Calling default method // With the help of Example_Class object t.display_2(); then the compiler will give an error as shown below: Error CS1061: ‘Example_Class’ does not contain a definition for ‘display_2’ and no accessible extension method ‘display_2’ accepting a first argument of type ‘Example_Class’ could be found (are you missing a using directive or an assembly reference?) Example 2: // C# program to illustrate how to override// the default interface methodusing System; // A simple interfaceinterface I_interface { // This method having // only declaration // not its definition void display_1(); // Default method has both // declaration and definition public void display_2() { Console.WriteLine("Hello!! Default Method of I_interface"); }} // Interface which inherits I_interfaceinterface A_interface : I_interface { // Here, we override the display_2() method // Here you are not allowed to use any access modifier // if you use, then the compiler will give an error void I_interface.display_2() { Console.WriteLine("Hello!! Overriden default method"); }} // A class that implements both interfaces.class Example_Class : I_interface, A_interface { // Providing the body part of the method public void display_1() { Console.WriteLine("Hello!! Method of I_interface"); } // Main Method public static void Main(String[] args) { // Creating object Example_Class t = new Example_Class(); // Calling method t.display_1(); // Creating an object I_interface obj1 = t; // Calling default method obj1.display_2(); // Creating an object A_interface obj2 = t; obj2.display_2(); }} Output: Hello!! Method of I_interface Hello!! Overriden default method Hello!! Overriden default method Example 3: // C# program to illustrate how // to pass parameters in the// default interface methodusing System; // A simple interfaceinterface I_interface { // This method only // have declaration // not its definition void display_1(); // Default method with both // declaration and definition // Here, the name of both methods are same // but the parameter list is different public void display_1(int a, int b) { int sum; sum = a + b; Console.WriteLine("Sum: " + sum); }} // A class which // implement I_interface interfaceclass Example_Class : I_interface { // Providing the body // part of the method public void display_1() { Console.WriteLine("Hello!! Method of I_interface"); } // Main Method public static void Main(String[] args) { // Creating an object Example_Class t = new Example_Class(); // Calling method t.display_1(); // Creating an object I_interface obj = t; // Calling and passing parameters in the default method obj.display_1(1, 4); }} Output: Hello!! Method of I_interface Sum: 5 CSharp-8.0 CSharp-Interfaces C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n06 Dec, 2019" }, { "code": null, "e": 695, "s": 52, "text": "Before C# 8.0 interfaces only contain the declaration of the members(methods, properties, events, and indexers), but from C# 8.0 it is allowed to add members as well as their implementation to the interface. Now you are allowed to add a method with their implementation to the interface without breaking the existing implementation of the interface, such type of methods is known as default interface methods(also known as the virtual extension methods). This feature allows programmers to use the traits programming technique (Traits are object-oriented programming technique which allows the reuse of the methods between unrelated classes)." }, { "code": null, "e": 713, "s": 695, "text": "Important Points:" }, { "code": null, "e": 797, "s": 713, "text": "You are allowed to implement indexer, property, or event accessor in the interface." }, { "code": null, "e": 1035, "s": 797, "text": "You are allowed to use access modifiers like private, protected, internal, public, virtual, abstract, override, sealed, static, extern with default methods, properties, etc. in the interface. And be careful while using modifier keywords." }, { "code": null, "e": 1136, "s": 1035, "text": "You are allowed to create static fields, methods, properties, indexers, and events in the interface." }, { "code": null, "e": 1164, "s": 1136, "text": "You can override modifiers." }, { "code": null, "e": 1226, "s": 1164, "text": "The explicit access modifiers with default access are public." }, { "code": null, "e": 1472, "s": 1226, "text": "If an interface contains default method and inherited by some specified class, then the class does not know anything about the existence of the default methods of that interface and also does not contain the implementation of the default method." }, { "code": null, "e": 1572, "s": 1472, "text": "If you override a default method, then there is no need to use any modifier. As shown in example 2." }, { "code": null, "e": 1652, "s": 1572, "text": "You are allowed to use parameters in the default method. As shown in example 3." }, { "code": null, "e": 1784, "s": 1652, "text": "You are allowed to use the same name methods in the interface, but they must have different parameter lists. As shown in example 3." }, { "code": null, "e": 1830, "s": 1784, "text": "You are allowed to extend the default method." }, { "code": null, "e": 2243, "s": 1830, "text": "Now discuss this concept with the help of the given example. In this example, we have an interface named I_interface which contains two methods, i.e. display_1 and display_2. Here, the display_1() method is only declared in the I_interface and does not contain its definition, whereas the display_2() method contains both declaration and its definition, such type of method is known as default interface methods." }, { "code": null, "e": 2254, "s": 2243, "text": "Example 1:" }, { "code": "// C# program to illustrate the concept// of the default interface methodusing System; // A simple interfaceinterface I_interface { // This method is only // have its declaration // not its definition void display_1(); // Default method with both // declaration and definition public void display_2() { Console.WriteLine(\"Hello!! Default Method\"); }} // A class that implements// the I_interface interface.class Example_Class : I_interface { // Providing the body // part of the method public void display_1() { Console.WriteLine(\"Hello!! Method\"); } // Main Method public static void Main(String[] args) { // Creating an object Example_Class t = new Example_Class(); // Calling method t.display_1(); // Creating an object I_interface obj = t; // Calling default method obj.display_2(); }}", "e": 3187, "s": 2254, "text": null }, { "code": null, "e": 3195, "s": 3187, "text": "Output:" }, { "code": null, "e": 3234, "s": 3195, "text": "Hello!! Method\nHello!! Default Method\n" }, { "code": null, "e": 3367, "s": 3234, "text": "Now, we call the display_2() method with the help of the I_interface interface. If you try to call this method with the class object" }, { "code": null, "e": 3450, "s": 3367, "text": "// Calling default method\n// With the help of Example_Class object\nt.display_2();\n" }, { "code": null, "e": 3503, "s": 3450, "text": "then the compiler will give an error as shown below:" }, { "code": null, "e": 3754, "s": 3503, "text": "Error CS1061: ‘Example_Class’ does not contain a definition for ‘display_2’ and no accessible extension method ‘display_2’ accepting a first argument of type ‘Example_Class’ could be found (are you missing a using directive or an assembly reference?)" }, { "code": null, "e": 3765, "s": 3754, "text": "Example 2:" }, { "code": "// C# program to illustrate how to override// the default interface methodusing System; // A simple interfaceinterface I_interface { // This method having // only declaration // not its definition void display_1(); // Default method has both // declaration and definition public void display_2() { Console.WriteLine(\"Hello!! Default Method of I_interface\"); }} // Interface which inherits I_interfaceinterface A_interface : I_interface { // Here, we override the display_2() method // Here you are not allowed to use any access modifier // if you use, then the compiler will give an error void I_interface.display_2() { Console.WriteLine(\"Hello!! Overriden default method\"); }} // A class that implements both interfaces.class Example_Class : I_interface, A_interface { // Providing the body part of the method public void display_1() { Console.WriteLine(\"Hello!! Method of I_interface\"); } // Main Method public static void Main(String[] args) { // Creating object Example_Class t = new Example_Class(); // Calling method t.display_1(); // Creating an object I_interface obj1 = t; // Calling default method obj1.display_2(); // Creating an object A_interface obj2 = t; obj2.display_2(); }}", "e": 5148, "s": 3765, "text": null }, { "code": null, "e": 5156, "s": 5148, "text": "Output:" }, { "code": null, "e": 5253, "s": 5156, "text": "Hello!! Method of I_interface\nHello!! Overriden default method\nHello!! Overriden default method\n" }, { "code": null, "e": 5264, "s": 5253, "text": "Example 3:" }, { "code": "// C# program to illustrate how // to pass parameters in the// default interface methodusing System; // A simple interfaceinterface I_interface { // This method only // have declaration // not its definition void display_1(); // Default method with both // declaration and definition // Here, the name of both methods are same // but the parameter list is different public void display_1(int a, int b) { int sum; sum = a + b; Console.WriteLine(\"Sum: \" + sum); }} // A class which // implement I_interface interfaceclass Example_Class : I_interface { // Providing the body // part of the method public void display_1() { Console.WriteLine(\"Hello!! Method of I_interface\"); } // Main Method public static void Main(String[] args) { // Creating an object Example_Class t = new Example_Class(); // Calling method t.display_1(); // Creating an object I_interface obj = t; // Calling and passing parameters in the default method obj.display_1(1, 4); }}", "e": 6373, "s": 5264, "text": null }, { "code": null, "e": 6381, "s": 6373, "text": "Output:" }, { "code": null, "e": 6419, "s": 6381, "text": "Hello!! Method of I_interface\nSum: 5\n" }, { "code": null, "e": 6430, "s": 6419, "text": "CSharp-8.0" }, { "code": null, "e": 6448, "s": 6430, "text": "CSharp-Interfaces" }, { "code": null, "e": 6451, "s": 6448, "text": "C#" } ]
Loops in C and C++
01 Jun, 2022 In programming, sometimes there is a need to perform some operation more than once or (say) n number of times. Loops come into use when we need to repeatedly execute a block of statements. For example: Suppose we want to print “Hello World” 10 times. This can be done in two ways as shown below: Manually we have to write the print() for C and cout for the C++ statement 10 times. Let’s say you have to write it 20 times (it would surely take more time to write 20 statements) now imagine you have to write it 100 times, it would be really hectic to re-write the same statement again and again. So, here loops have their role. C C++ // C program to illustrate need of loops#include <stdio.h> int main(){ printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); printf( "Hello World\n"); return 0;} // C++ program to illustrate need of loops#include <iostream>using namespace std; int main(){ cout << "Hello World\n"; cout << "Hello World\n"; cout << "Hello World\n"; cout << "Hello World\n"; cout << "Hello World\n"; cout << "Hello World\n"; cout << "Hello World\n"; cout << "Hello World\n"; cout << "Hello World\n"; cout << "Hello World\n"; return 0;} Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below. In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached. An operation is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number. Counter not Reached: If the counter has not reached the desired number, the next instruction in the sequence returns to the first instruction in the sequence and repeats it. Counter reached: If the condition has been reached, the next instruction “falls through” to the next sequential instruction or branches outside the loop. There are mainly two types of loops: Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loop is entry-controlled loops.Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop. Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loop is entry-controlled loops. Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop. A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line. Syntax: for (initialization expr; test expr; update expr) { // body of the loop // statements we want to execute } Example: for(int i = 0; i < n; i++){ } In for loop, a loop variable is used to control the loop. First, initialize this loop variable to some value, then check whether this variable is less than or greater than the counter value. If the statement is true, then the loop body is executed and the loop variable gets updated. Steps are repeated till the exit condition comes. Initialization Expression: In this expression, we have to initialize the loop counter to some value. for example: int i=1; Test Expression: In this expression, we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression otherwise we will exit from the for a loop. For example: i <= 10; Update Expression: After executing the loop body this expression increments/decrements the loop variable by some value. for example: i++; Equivalent Flow Diagram for loop: Example: C C++ // C program to illustrate for loop#include <stdio.h> int main(){ int i=0; for (i = 1; i <= 10; i++) { printf( "Hello World\n"); } return 0;} // C++ program to illustrate for loop#include <iostream>using namespace std; int main(){ for (int i = 1; i <= 10; i++) { cout << "Hello World\n"; } return 0;} Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World Hello World While studying for loop we have seen that the number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known to us. while loops are used in situations where we do not know the exact number of iterations of the loop beforehand. The loop execution is terminated on the basis of the test conditions.Syntax: We have already stated that a loop mainly consists of three statements – initialization expression, test expression, and update expression. The syntax of the three loops – For, while, and do while mainly differs in the placement of these three statements. initialization expression; while (test_expression) { // statements update_expression; } Flow Diagram: Example: C C++ // C program to illustrate while loop#include <stdio.h> int main(){ // initialization expression int i = 1; // test expression while (i < 6) { printf( "Hello World\n"); // update expression i++; } return 0;} // C++ program to illustrate while loop#include <iostream>using namespace std; int main(){ // initialization expression int i = 1; // test expression while (i < 6) { cout << "Hello World\n"; // update expression i++; } return 0;} Hello World Hello World Hello World Hello World Hello World In do-while loops also the loop execution is terminated on the basis of test conditions. The main difference between a do-while loop and the while loop is in the do-while loop the condition is tested at the end of the loop body, i.e do-while loop is exit controlled whereas the other two loops are entry controlled loops. Note: In a do-while loop, the loop body will execute at least once irrespective of the test condition.Syntax: initialization expression; do { // statements update_expression; } while (test_expression); Note: Notice the semi – colon(“;”) in the end of loop.Flow Diagram: Example: C C++ // C program to illustrate do-while loop#include <stdio.h> int main(){ int i = 2; // Initialization expression do { // loop body printf( "Hello World\n"); // update expression i++; } while (i < 1); // test expression return 0;} // C++ program to illustrate do-while loop#include <iostream>using namespace std; int main(){ int i = 2; // Initialization expression do { // loop body cout << "Hello World\n"; // update expression i++; } while (i < 1); // test expression return 0;} Hello World In the above program, the test condition (i<1) evaluates to false. But still, as the loop is an exit – controlled the loop body will execute once. An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. An infinite loop occurs when a condition is always evaluated to be true. Usually, this is an error. Using For loop: C C++ // C program to demonstrate infinite loops// using for and while// Uncomment the sections to see the output #include <stdio.h> int main (){ int i; // This is an infinite for loop as the condition // expression is blank for ( ; ; ) { printf("This loop will run forever.\n"); } // This is an infinite for loop as the condition // given in while loop will keep repeating infinitely /* while (i != 0) { i-- ; printf( "This loop will run forever.\n"); } */ // This is an infinite for loop as the condition // given in while loop is "true" /* while (true) { printf( "This loop will run forever.\n"); } */} // C++ program to demonstrate infinite loops// using for and while// Uncomment the sections to see the output #include <iostream>using namespace std;int main (){ int i; // This is an infinite for loop as the condition // expression is blank for ( ; ; ) { cout << "This loop will run forever.\n"; } // This is an infinite for loop as the condition // given in while loop will keep repeating infinitely /* while (i != 0) { i-- ; cout << "This loop will run forever.\n"; } */ // This is an infinite for loop as the condition // given in while loop is "true" /* while (true) { cout << "This loop will run forever.\n"; } */} Output: This loop will run forever. This loop will run forever. ................... Using While loop: C C++ #include <stdio.h> int main() { while (1) printf("This loop will run forever.\n"); return 0;} #include <iostream>using namespace std; int main(){ while (1) cout << "This loop will run forever.\n"; return 0;} Output: This loop will run forever. This loop will run forever. ................... Using Do-While loop: C C++ #include <stdio.h> int main() { do{ printf("This loop will run forever.\n"); } while(1); return 0;} #include <iostream>using namespace std; int main() { do{ cout << "This loop will run forever.\n"; } while(1); return 0;} Output: This loop will run forever. This loop will run forever. ................... More Advanced Looping Techniques Range-based for loop in C++ for_each loop in C++ Important Points: Use for loop when a number of iterations are known beforehand, i.e. the number of times the loop body is needed to be executed is known. Use while loops, where an exact number of iterations is not known but the loop termination condition, is known. Use do while loop if the code needs to be executed at least once like in Menu-driven programs Related Articles: What happens if loop till Maximum of Signed and Unsigned in C/C++? Quiz on Loops This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above. RishabhPrabhu sackshamsharmaintern susobhanakhuli C Basics CBSE - Class 11 CPP-Basics school-programming C++ School Programming CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n01 Jun, 2022" }, { "code": null, "e": 242, "s": 52, "text": "In programming, sometimes there is a need to perform some operation more than once or (say) n number of times. Loops come into use when we need to repeatedly execute a block of statements. " }, { "code": null, "e": 350, "s": 242, "text": "For example: Suppose we want to print “Hello World” 10 times. This can be done in two ways as shown below: " }, { "code": null, "e": 681, "s": 350, "text": "Manually we have to write the print() for C and cout for the C++ statement 10 times. Let’s say you have to write it 20 times (it would surely take more time to write 20 statements) now imagine you have to write it 100 times, it would be really hectic to re-write the same statement again and again. So, here loops have their role." }, { "code": null, "e": 683, "s": 681, "text": "C" }, { "code": null, "e": 687, "s": 683, "text": "C++" }, { "code": "// C program to illustrate need of loops#include <stdio.h> int main(){ printf( \"Hello World\\n\"); printf( \"Hello World\\n\"); printf( \"Hello World\\n\"); printf( \"Hello World\\n\"); printf( \"Hello World\\n\"); printf( \"Hello World\\n\"); printf( \"Hello World\\n\"); printf( \"Hello World\\n\"); printf( \"Hello World\\n\"); printf( \"Hello World\\n\"); return 0;}", "e": 1067, "s": 687, "text": null }, { "code": "// C++ program to illustrate need of loops#include <iostream>using namespace std; int main(){ cout << \"Hello World\\n\"; cout << \"Hello World\\n\"; cout << \"Hello World\\n\"; cout << \"Hello World\\n\"; cout << \"Hello World\\n\"; cout << \"Hello World\\n\"; cout << \"Hello World\\n\"; cout << \"Hello World\\n\"; cout << \"Hello World\\n\"; cout << \"Hello World\\n\"; return 0;}", "e": 1455, "s": 1067, "text": null }, { "code": null, "e": 1575, "s": 1455, "text": "Hello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World" }, { "code": null, "e": 1804, "s": 1577, "text": "In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below. In computer programming, a loop is a sequence of instructions that is repeated until a certain condition is reached. " }, { "code": null, "e": 1969, "s": 1804, "text": "An operation is done, such as getting an item of data and changing it, and then some condition is checked such as whether a counter has reached a prescribed number." }, { "code": null, "e": 2143, "s": 1969, "text": "Counter not Reached: If the counter has not reached the desired number, the next instruction in the sequence returns to the first instruction in the sequence and repeats it." }, { "code": null, "e": 2297, "s": 2143, "text": "Counter reached: If the condition has been reached, the next instruction “falls through” to the next sequential instruction or branches outside the loop." }, { "code": null, "e": 2336, "s": 2297, "text": "There are mainly two types of loops: " }, { "code": null, "e": 2764, "s": 2336, "text": "Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loop is entry-controlled loops.Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop." }, { "code": null, "e": 2921, "s": 2764, "text": "Entry Controlled loops: In this type of loop, the test condition is tested before entering the loop body. For Loop and While Loop is entry-controlled loops." }, { "code": null, "e": 3193, "s": 2921, "text": "Exit Controlled Loops: In this type of loop the test condition is tested or evaluated at the end of the loop body. Therefore, the loop body will execute at least once, irrespective of whether the test condition is true or false. the do-while loop is exit controlled loop." }, { "code": null, "e": 3394, "s": 3193, "text": "A for loop is a repetition control structure that allows us to write a loop that is executed a specific number of times. The loop enables us to perform n number of steps together in one line. Syntax: " }, { "code": null, "e": 3515, "s": 3394, "text": "for (initialization expr; test expr; update expr)\n{ \n // body of the loop\n // statements we want to execute\n}" }, { "code": null, "e": 3524, "s": 3515, "text": "Example:" }, { "code": null, "e": 3554, "s": 3524, "text": "for(int i = 0; i < n; i++){\n}" }, { "code": null, "e": 3889, "s": 3554, "text": "In for loop, a loop variable is used to control the loop. First, initialize this loop variable to some value, then check whether this variable is less than or greater than the counter value. If the statement is true, then the loop body is executed and the loop variable gets updated. Steps are repeated till the exit condition comes. " }, { "code": null, "e": 4012, "s": 3889, "text": "Initialization Expression: In this expression, we have to initialize the loop counter to some value. for example: int i=1;" }, { "code": null, "e": 4251, "s": 4012, "text": "Test Expression: In this expression, we have to test the condition. If the condition evaluates to true then we will execute the body of the loop and go to update expression otherwise we will exit from the for a loop. For example: i <= 10;" }, { "code": null, "e": 4389, "s": 4251, "text": "Update Expression: After executing the loop body this expression increments/decrements the loop variable by some value. for example: i++;" }, { "code": null, "e": 4425, "s": 4389, "text": "Equivalent Flow Diagram for loop: " }, { "code": null, "e": 4435, "s": 4425, "text": "Example: " }, { "code": null, "e": 4437, "s": 4435, "text": "C" }, { "code": null, "e": 4441, "s": 4437, "text": "C++" }, { "code": "// C program to illustrate for loop#include <stdio.h> int main(){ int i=0; for (i = 1; i <= 10; i++) { printf( \"Hello World\\n\"); } return 0;}", "e": 4614, "s": 4441, "text": null }, { "code": "// C++ program to illustrate for loop#include <iostream>using namespace std; int main(){ for (int i = 1; i <= 10; i++) { cout << \"Hello World\\n\"; } return 0;}", "e": 4793, "s": 4614, "text": null }, { "code": null, "e": 4913, "s": 4793, "text": "Hello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World\nHello World" }, { "code": null, "e": 5528, "s": 4915, "text": "While studying for loop we have seen that the number of iterations is known beforehand, i.e. the number of times the loop body is needed to be executed is known to us. while loops are used in situations where we do not know the exact number of iterations of the loop beforehand. The loop execution is terminated on the basis of the test conditions.Syntax: We have already stated that a loop mainly consists of three statements – initialization expression, test expression, and update expression. The syntax of the three loops – For, while, and do while mainly differs in the placement of these three statements. " }, { "code": null, "e": 5623, "s": 5528, "text": "initialization expression;\nwhile (test_expression)\n{\n // statements\n \n update_expression;\n}" }, { "code": null, "e": 5639, "s": 5623, "text": "Flow Diagram: " }, { "code": null, "e": 5649, "s": 5639, "text": "Example: " }, { "code": null, "e": 5651, "s": 5649, "text": "C" }, { "code": null, "e": 5655, "s": 5651, "text": "C++" }, { "code": "// C program to illustrate while loop#include <stdio.h> int main(){ // initialization expression int i = 1; // test expression while (i < 6) { printf( \"Hello World\\n\"); // update expression i++; } return 0;}", "e": 5911, "s": 5655, "text": null }, { "code": "// C++ program to illustrate while loop#include <iostream>using namespace std; int main(){ // initialization expression int i = 1; // test expression while (i < 6) { cout << \"Hello World\\n\"; // update expression i++; } return 0;}", "e": 6186, "s": 5911, "text": null }, { "code": null, "e": 6246, "s": 6186, "text": "Hello World\nHello World\nHello World\nHello World\nHello World" }, { "code": null, "e": 6681, "s": 6248, "text": "In do-while loops also the loop execution is terminated on the basis of test conditions. The main difference between a do-while loop and the while loop is in the do-while loop the condition is tested at the end of the loop body, i.e do-while loop is exit controlled whereas the other two loops are entry controlled loops. Note: In a do-while loop, the loop body will execute at least once irrespective of the test condition.Syntax: " }, { "code": null, "e": 6780, "s": 6681, "text": "initialization expression;\ndo\n{\n // statements\n\n update_expression;\n} while (test_expression);" }, { "code": null, "e": 6850, "s": 6780, "text": "Note: Notice the semi – colon(“;”) in the end of loop.Flow Diagram: " }, { "code": null, "e": 6860, "s": 6850, "text": "Example: " }, { "code": null, "e": 6862, "s": 6860, "text": "C" }, { "code": null, "e": 6866, "s": 6862, "text": "C++" }, { "code": "// C program to illustrate do-while loop#include <stdio.h> int main(){ int i = 2; // Initialization expression do { // loop body printf( \"Hello World\\n\"); // update expression i++; } while (i < 1); // test expression return 0;}", "e": 7147, "s": 6866, "text": null }, { "code": "// C++ program to illustrate do-while loop#include <iostream>using namespace std; int main(){ int i = 2; // Initialization expression do { // loop body cout << \"Hello World\\n\"; // update expression i++; } while (i < 1); // test expression return 0;}", "e": 7447, "s": 7147, "text": null }, { "code": null, "e": 7459, "s": 7447, "text": "Hello World" }, { "code": null, "e": 7609, "s": 7461, "text": "In the above program, the test condition (i<1) evaluates to false. But still, as the loop is an exit – controlled the loop body will execute once. " }, { "code": null, "e": 7861, "s": 7609, "text": "An infinite loop (sometimes called an endless loop ) is a piece of coding that lacks a functional exit so that it repeats indefinitely. An infinite loop occurs when a condition is always evaluated to be true. Usually, this is an error. Using For loop:" }, { "code": null, "e": 7863, "s": 7861, "text": "C" }, { "code": null, "e": 7867, "s": 7863, "text": "C++" }, { "code": "// C program to demonstrate infinite loops// using for and while// Uncomment the sections to see the output #include <stdio.h> int main (){ int i; // This is an infinite for loop as the condition // expression is blank for ( ; ; ) { printf(\"This loop will run forever.\\n\"); } // This is an infinite for loop as the condition // given in while loop will keep repeating infinitely /* while (i != 0) { i-- ; printf( \"This loop will run forever.\\n\"); } */ // This is an infinite for loop as the condition // given in while loop is \"true\" /* while (true) { printf( \"This loop will run forever.\\n\"); } */}", "e": 8558, "s": 7867, "text": null }, { "code": "// C++ program to demonstrate infinite loops// using for and while// Uncomment the sections to see the output #include <iostream>using namespace std;int main (){ int i; // This is an infinite for loop as the condition // expression is blank for ( ; ; ) { cout << \"This loop will run forever.\\n\"; } // This is an infinite for loop as the condition // given in while loop will keep repeating infinitely /* while (i != 0) { i-- ; cout << \"This loop will run forever.\\n\"; } */ // This is an infinite for loop as the condition // given in while loop is \"true\" /* while (true) { cout << \"This loop will run forever.\\n\"; } */}", "e": 9270, "s": 8558, "text": null }, { "code": null, "e": 9280, "s": 9270, "text": "Output: " }, { "code": null, "e": 9357, "s": 9280, "text": "This loop will run forever.\nThis loop will run forever.\n................... " }, { "code": null, "e": 9375, "s": 9357, "text": "Using While loop:" }, { "code": null, "e": 9377, "s": 9375, "text": "C" }, { "code": null, "e": 9381, "s": 9377, "text": "C++" }, { "code": "#include <stdio.h> int main() { while (1) printf(\"This loop will run forever.\\n\"); return 0;}", "e": 9489, "s": 9381, "text": null }, { "code": "#include <iostream>using namespace std; int main(){ while (1) cout << \"This loop will run forever.\\n\"; return 0;}", "e": 9617, "s": 9489, "text": null }, { "code": null, "e": 9627, "s": 9617, "text": "Output: " }, { "code": null, "e": 9704, "s": 9627, "text": "This loop will run forever.\nThis loop will run forever.\n................... " }, { "code": null, "e": 9725, "s": 9704, "text": "Using Do-While loop:" }, { "code": null, "e": 9727, "s": 9725, "text": "C" }, { "code": null, "e": 9731, "s": 9727, "text": "C++" }, { "code": "#include <stdio.h> int main() { do{ printf(\"This loop will run forever.\\n\"); } while(1); return 0;}", "e": 9853, "s": 9731, "text": null }, { "code": "#include <iostream>using namespace std; int main() { do{ cout << \"This loop will run forever.\\n\"; } while(1); return 0;}", "e": 9994, "s": 9853, "text": null }, { "code": null, "e": 10002, "s": 9994, "text": "Output:" }, { "code": null, "e": 10079, "s": 10002, "text": "This loop will run forever.\nThis loop will run forever.\n................... " }, { "code": null, "e": 10112, "s": 10079, "text": "More Advanced Looping Techniques" }, { "code": null, "e": 10140, "s": 10112, "text": "Range-based for loop in C++" }, { "code": null, "e": 10161, "s": 10140, "text": "for_each loop in C++" }, { "code": null, "e": 10179, "s": 10161, "text": "Important Points:" }, { "code": null, "e": 10316, "s": 10179, "text": "Use for loop when a number of iterations are known beforehand, i.e. the number of times the loop body is needed to be executed is known." }, { "code": null, "e": 10428, "s": 10316, "text": "Use while loops, where an exact number of iterations is not known but the loop termination condition, is known." }, { "code": null, "e": 10522, "s": 10428, "text": "Use do while loop if the code needs to be executed at least once like in Menu-driven programs" }, { "code": null, "e": 10540, "s": 10522, "text": "Related Articles:" }, { "code": null, "e": 10607, "s": 10540, "text": "What happens if loop till Maximum of Signed and Unsigned in C/C++?" }, { "code": null, "e": 10621, "s": 10607, "text": "Quiz on Loops" }, { "code": null, "e": 11046, "s": 10621, "text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above." }, { "code": null, "e": 11060, "s": 11046, "text": "RishabhPrabhu" }, { "code": null, "e": 11081, "s": 11060, "text": "sackshamsharmaintern" }, { "code": null, "e": 11096, "s": 11081, "text": "susobhanakhuli" }, { "code": null, "e": 11105, "s": 11096, "text": "C Basics" }, { "code": null, "e": 11121, "s": 11105, "text": "CBSE - Class 11" }, { "code": null, "e": 11132, "s": 11121, "text": "CPP-Basics" }, { "code": null, "e": 11151, "s": 11132, "text": "school-programming" }, { "code": null, "e": 11155, "s": 11151, "text": "C++" }, { "code": null, "e": 11174, "s": 11155, "text": "School Programming" }, { "code": null, "e": 11178, "s": 11174, "text": "CPP" } ]
Convert a negative number to positive in JavaScript
29 May, 2019 We can convert a negative number to a positive number in javascript by the methods described below. Method 1: This is a general method in which we will first check whether the number is already positive or negative, if the number is negative then we will multiply the number with -1 to make it positive. Syntax: if (a < 0) { a = a * -1; } Example: Below is the implementation of the above approach: <script> // Javascript script // to convert negative number // to positive number // Function to convert // given number to // positive number function convert_positive(a) { // Check the number is negative if (a < 0) { // Multiply number with -1 // to make it positive a = a * -1; } // Return the positive number return a; } //Driver codevar n = -10;var m = 5; // Call functionn = convert_positive(n); // Print resultdocument.write(n + "<br>"); // Call functionm = convert_positive(m); // Print resultdocument.write(m + "<br>"); </script> Output: 10 5 Method 2: In this method we will use Math.abs() function to convert negative number to positive number. Syntax: Math.abs(value) Example: Below is the implementation of the above approach: <script> // Javascript script // to convert negative number // to positive number //Driver code var n = -30; var m = 15; // Using Math.abs() function n = Math.abs(n); // Print result document.write(n + "<br>"); // Using Math.abs() function m = Math.abs(m); // Print result document.write(m + "<br>");</script> Output: 30 15 javascript-math Picked JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 May, 2019" }, { "code": null, "e": 128, "s": 28, "text": "We can convert a negative number to a positive number in javascript by the methods described below." }, { "code": null, "e": 332, "s": 128, "text": "Method 1: This is a general method in which we will first check whether the number is already positive or negative, if the number is negative then we will multiply the number with -1 to make it positive." }, { "code": null, "e": 340, "s": 332, "text": "Syntax:" }, { "code": null, "e": 372, "s": 340, "text": "if (a < 0) {\n a = a * -1;\n}\n" }, { "code": null, "e": 432, "s": 372, "text": "Example: Below is the implementation of the above approach:" }, { "code": "<script> // Javascript script // to convert negative number // to positive number // Function to convert // given number to // positive number function convert_positive(a) { // Check the number is negative if (a < 0) { // Multiply number with -1 // to make it positive a = a * -1; } // Return the positive number return a; } //Driver codevar n = -10;var m = 5; // Call functionn = convert_positive(n); // Print resultdocument.write(n + \"<br>\"); // Call functionm = convert_positive(m); // Print resultdocument.write(m + \"<br>\"); </script>", "e": 1072, "s": 432, "text": null }, { "code": null, "e": 1080, "s": 1072, "text": "Output:" }, { "code": null, "e": 1086, "s": 1080, "text": "10\n5\n" }, { "code": null, "e": 1190, "s": 1086, "text": "Method 2: In this method we will use Math.abs() function to convert negative number to positive number." }, { "code": null, "e": 1198, "s": 1190, "text": "Syntax:" }, { "code": null, "e": 1214, "s": 1198, "text": "Math.abs(value)" }, { "code": null, "e": 1274, "s": 1214, "text": "Example: Below is the implementation of the above approach:" }, { "code": "<script> // Javascript script // to convert negative number // to positive number //Driver code var n = -30; var m = 15; // Using Math.abs() function n = Math.abs(n); // Print result document.write(n + \"<br>\"); // Using Math.abs() function m = Math.abs(m); // Print result document.write(m + \"<br>\");</script> ", "e": 1695, "s": 1274, "text": null }, { "code": null, "e": 1703, "s": 1695, "text": "Output:" }, { "code": null, "e": 1710, "s": 1703, "text": "30\n15\n" }, { "code": null, "e": 1726, "s": 1710, "text": "javascript-math" }, { "code": null, "e": 1733, "s": 1726, "text": "Picked" }, { "code": null, "e": 1744, "s": 1733, "text": "JavaScript" }, { "code": null, "e": 1761, "s": 1744, "text": "Web Technologies" } ]
Find the size of a Tuple in Python
17 May, 2020 Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers.Values of a tuple are syntactically separated by ‘commas’. Although it is not necessary, it is more common to define a tuple by closing the sequence of values in parentheses.The size of a Tuple means the amount of memory (in bytes) taken by a Tuple object. In this article, we will learn various ways to get the size of a python Tuple. 1.Using getsizeof() function: The getsizeof() function belongs to the python’s sys module. It has been implemented in the below example. Example 1: import sys # sample TuplesTuple1 = ("A", 1, "B", 2, "C", 3)Tuple2 = ("Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu")Tuple3 = ((1, "Lion"), ( 2, "Tiger"), (3, "Fox"), (4, "Wolf")) # print the sizes of sample Tuplesprint("Size of Tuple1: " + str(sys.getsizeof(Tuple1)) + "bytes")print("Size of Tuple2: " + str(sys.getsizeof(Tuple2)) + "bytes")print("Size of Tuple3: " + str(sys.getsizeof(Tuple3)) + "bytes") Output: Size of Tuple1: 96bytes Size of Tuple2: 96bytes Size of Tuple3: 80bytes Note:The sys.getsizeof() function includes the marginal space usage, which includes the garbage collection overhead for the object. Meaning it returns the total space occupied by the object in addition to the garbage collection overhead for the spaces being used. 1.Using inbuilt __sizeof__() method: Python also has an inbuilt __sizeof__() method to determine the space allocation of an object without any additional garbage value. It has been implemented in the below example.Example 2: # sample TuplesTuple1 = ("A", 1, "B", 2, "C", 3)Tuple2 = ("Geek1", "Raju", "Geek2", "Nikhil", "Geek3", "Deepanshu")Tuple3 = ((1, "Lion"), ( 2, "Tiger"), (3, "Fox"), (4, "Wolf")) # print the sizes of sample Tuplesprint("Size of Tuple1: " + str(Tuple1.__sizeof__()) + "bytes")print("Size of Tuple2: " + str(Tuple2.__sizeof__()) + "bytes")print("Size of Tuple3: " + str(Tuple3.__sizeof__()) + "bytes") Output: Size of Tuple1: 72bytes Size of Tuple2: 72bytes Size of Tuple3: 56bytes Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python 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 Program for Fibonacci numbers
[ { "code": null, "e": 52, "s": 24, "text": "\n17 May, 2020" }, { "code": null, "e": 540, "s": 52, "text": "Tuple is a collection of Python objects much like a list. The sequence of values stored in a tuple can be of any type, and they are indexed by integers.Values of a tuple are syntactically separated by ‘commas’. Although it is not necessary, it is more common to define a tuple by closing the sequence of values in parentheses.The size of a Tuple means the amount of memory (in bytes) taken by a Tuple object. In this article, we will learn various ways to get the size of a python Tuple." }, { "code": null, "e": 570, "s": 540, "text": "1.Using getsizeof() function:" }, { "code": null, "e": 677, "s": 570, "text": "The getsizeof() function belongs to the python’s sys module. It has been implemented in the below example." }, { "code": null, "e": 688, "s": 677, "text": "Example 1:" }, { "code": "import sys # sample TuplesTuple1 = (\"A\", 1, \"B\", 2, \"C\", 3)Tuple2 = (\"Geek1\", \"Raju\", \"Geek2\", \"Nikhil\", \"Geek3\", \"Deepanshu\")Tuple3 = ((1, \"Lion\"), ( 2, \"Tiger\"), (3, \"Fox\"), (4, \"Wolf\")) # print the sizes of sample Tuplesprint(\"Size of Tuple1: \" + str(sys.getsizeof(Tuple1)) + \"bytes\")print(\"Size of Tuple2: \" + str(sys.getsizeof(Tuple2)) + \"bytes\")print(\"Size of Tuple3: \" + str(sys.getsizeof(Tuple3)) + \"bytes\")", "e": 1106, "s": 688, "text": null }, { "code": null, "e": 1114, "s": 1106, "text": "Output:" }, { "code": null, "e": 1186, "s": 1114, "text": "Size of Tuple1: 96bytes\nSize of Tuple2: 96bytes\nSize of Tuple3: 80bytes" }, { "code": null, "e": 1450, "s": 1186, "text": "Note:The sys.getsizeof() function includes the marginal space usage, which includes the garbage collection overhead for the object. Meaning it returns the total space occupied by the object in addition to the garbage collection overhead for the spaces being used." }, { "code": null, "e": 1487, "s": 1450, "text": "1.Using inbuilt __sizeof__() method:" }, { "code": null, "e": 1675, "s": 1487, "text": "Python also has an inbuilt __sizeof__() method to determine the space allocation of an object without any additional garbage value. It has been implemented in the below example.Example 2:" }, { "code": "# sample TuplesTuple1 = (\"A\", 1, \"B\", 2, \"C\", 3)Tuple2 = (\"Geek1\", \"Raju\", \"Geek2\", \"Nikhil\", \"Geek3\", \"Deepanshu\")Tuple3 = ((1, \"Lion\"), ( 2, \"Tiger\"), (3, \"Fox\"), (4, \"Wolf\")) # print the sizes of sample Tuplesprint(\"Size of Tuple1: \" + str(Tuple1.__sizeof__()) + \"bytes\")print(\"Size of Tuple2: \" + str(Tuple2.__sizeof__()) + \"bytes\")print(\"Size of Tuple3: \" + str(Tuple3.__sizeof__()) + \"bytes\")", "e": 2075, "s": 1675, "text": null }, { "code": null, "e": 2083, "s": 2075, "text": "Output:" }, { "code": null, "e": 2155, "s": 2083, "text": "Size of Tuple1: 72bytes\nSize of Tuple2: 72bytes\nSize of Tuple3: 56bytes" }, { "code": null, "e": 2177, "s": 2155, "text": "Python tuple-programs" }, { "code": null, "e": 2184, "s": 2177, "text": "Python" }, { "code": null, "e": 2200, "s": 2184, "text": "Python Programs" }, { "code": null, "e": 2298, "s": 2200, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2316, "s": 2298, "text": "Python Dictionary" }, { "code": null, "e": 2358, "s": 2316, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2380, "s": 2358, "text": "Enumerate() in Python" }, { "code": null, "e": 2412, "s": 2380, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2441, "s": 2412, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2484, "s": 2441, "text": "Python program to convert a list to string" }, { "code": null, "e": 2506, "s": 2484, "text": "Defaultdict in Python" }, { "code": null, "e": 2545, "s": 2506, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2583, "s": 2545, "text": "Python | Convert a list to dictionary" } ]
Express.js express.raw() Function - GeeksforGeeks
03 Jul, 2020 The express.raw() function is a built-in middleware function in Express. It parses incoming request payloads into a Buffer and is based on body-parser. Syntax: express.raw( [options] ) Parameter: The options parameter contains various property like inflate, limit, type, etc. Return Value: It returns an Object. Installation of express module: You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js You can visit the link to Install express module. You can install this package by using this command.npm install express npm install express After installing the express module, you can check your express version in command prompt using the command.npm version express npm version express After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js node index.js Example 1: Filename: index.js var express = require('express');var app = express();var PORT = 3000; app.use(express.raw()); app.post('/', function (req, res) { console.log(req.body); res.end();}) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Steps to run the program: The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000 Now make a POST request to http://localhost:3000/ with header set to ‘content-type’ – ‘application/octet-stream’ and body { “name”:”GeeksforGeeks” }, then you will see the following output on your screen: The project structure will look like this: Make sure you have installed express module using the following command:npm install express npm install express Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000 node index.js Output: Server listening on PORT 3000 Now make a POST request to http://localhost:3000/ with header set to ‘content-type’ – ‘application/octet-stream’ and body { “name”:”GeeksforGeeks” }, then you will see the following output on your screen: Example 2: Filename: index.js var express = require('express');var app = express();var PORT = 3000; // Without this middleware// app.use(express.raw());app.post('/', function (req, res) { console.log(req.body); res.end();}) app.listen(PORT, function(err){ if (err) console.log(err); console.log("Server listening on PORT", PORT);}); Run index.js file using below command: node index.js Now make a POST request to http://localhost:3000/ with header set to ‘content-type’ – ‘application/octet-stream’ and body { “name”:”GeeksforGeeks” }, then you will see the following output on your screen: Server listening on PORT 3000 undefined Reference: Offical Documentation Express.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments 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 ? Top 10 Front End Developer Skills That You Need 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": 29199, "s": 29171, "text": "\n03 Jul, 2020" }, { "code": null, "e": 29351, "s": 29199, "text": "The express.raw() function is a built-in middleware function in Express. It parses incoming request payloads into a Buffer and is based on body-parser." }, { "code": null, "e": 29359, "s": 29351, "text": "Syntax:" }, { "code": null, "e": 29384, "s": 29359, "text": "express.raw( [options] )" }, { "code": null, "e": 29475, "s": 29384, "text": "Parameter: The options parameter contains various property like inflate, limit, type, etc." }, { "code": null, "e": 29511, "s": 29475, "text": "Return Value: It returns an Object." }, { "code": null, "e": 29543, "s": 29511, "text": "Installation of express module:" }, { "code": null, "e": 29938, "s": 29543, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install expressAfter installing the express module, you can check your express version in command prompt using the command.npm version expressAfter that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 30059, "s": 29938, "text": "You can visit the link to Install express module. You can install this package by using this command.npm install express" }, { "code": null, "e": 30079, "s": 30059, "text": "npm install express" }, { "code": null, "e": 30207, "s": 30079, "text": "After installing the express module, you can check your express version in command prompt using the command.npm version express" }, { "code": null, "e": 30227, "s": 30207, "text": "npm version express" }, { "code": null, "e": 30375, "s": 30227, "text": "After that, you can just create a folder and add a file for example, index.js. To run this file you need to run the following command.node index.js" }, { "code": null, "e": 30389, "s": 30375, "text": "node index.js" }, { "code": null, "e": 30419, "s": 30389, "text": "Example 1: Filename: index.js" }, { "code": "var express = require('express');var app = express();var PORT = 3000; app.use(express.raw()); app.post('/', function (req, res) { console.log(req.body); res.end();}) app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 30711, "s": 30419, "text": null }, { "code": null, "e": 30737, "s": 30711, "text": "Steps to run the program:" }, { "code": null, "e": 31163, "s": 30737, "text": "The project structure will look like this:Make sure you have installed express module using the following command:npm install expressRun index.js file using below command:node index.jsOutput:Server listening on PORT 3000\nNow make a POST request to http://localhost:3000/ with header set to ‘content-type’ – ‘application/octet-stream’ and body { “name”:”GeeksforGeeks” }, then you will see the following output on your screen:" }, { "code": null, "e": 31206, "s": 31163, "text": "The project structure will look like this:" }, { "code": null, "e": 31298, "s": 31206, "text": "Make sure you have installed express module using the following command:npm install express" }, { "code": null, "e": 31318, "s": 31298, "text": "npm install express" }, { "code": null, "e": 31407, "s": 31318, "text": "Run index.js file using below command:node index.jsOutput:Server listening on PORT 3000\n" }, { "code": null, "e": 31421, "s": 31407, "text": "node index.js" }, { "code": null, "e": 31429, "s": 31421, "text": "Output:" }, { "code": null, "e": 31460, "s": 31429, "text": "Server listening on PORT 3000\n" }, { "code": null, "e": 31665, "s": 31460, "text": "Now make a POST request to http://localhost:3000/ with header set to ‘content-type’ – ‘application/octet-stream’ and body { “name”:”GeeksforGeeks” }, then you will see the following output on your screen:" }, { "code": null, "e": 31695, "s": 31665, "text": "Example 2: Filename: index.js" }, { "code": "var express = require('express');var app = express();var PORT = 3000; // Without this middleware// app.use(express.raw());app.post('/', function (req, res) { console.log(req.body); res.end();}) app.listen(PORT, function(err){ if (err) console.log(err); console.log(\"Server listening on PORT\", PORT);});", "e": 32012, "s": 31695, "text": null }, { "code": null, "e": 32051, "s": 32012, "text": "Run index.js file using below command:" }, { "code": null, "e": 32065, "s": 32051, "text": "node index.js" }, { "code": null, "e": 32270, "s": 32065, "text": "Now make a POST request to http://localhost:3000/ with header set to ‘content-type’ – ‘application/octet-stream’ and body { “name”:”GeeksforGeeks” }, then you will see the following output on your screen:" }, { "code": null, "e": 32311, "s": 32270, "text": "Server listening on PORT 3000\nundefined\n" }, { "code": null, "e": 32344, "s": 32311, "text": "Reference: Offical Documentation" }, { "code": null, "e": 32355, "s": 32344, "text": "Express.js" }, { "code": null, "e": 32363, "s": 32355, "text": "Node.js" }, { "code": null, "e": 32380, "s": 32363, "text": "Web Technologies" }, { "code": null, "e": 32478, "s": 32380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32487, "s": 32478, "text": "Comments" }, { "code": null, "e": 32500, "s": 32487, "text": "Old Comments" }, { "code": null, "e": 32533, "s": 32500, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32581, "s": 32533, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32614, "s": 32581, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 32643, "s": 32614, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 32663, "s": 32643, "text": "How to update NPM ?" }, { "code": null, "e": 32719, "s": 32663, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 32752, "s": 32719, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 32814, "s": 32752, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32857, "s": 32814, "text": "How to fetch data from an API in ReactJS ?" } ]
Contains Duplicate in Python
Suppose we have a list of numbers. We have to check whether the list is holding some duplicate elements or not. So if the list is like [1,5,6,2,1,3], then it will return 1 as there are two 1s, but if the list is [1,2,3,4], then it will be false, as there is no duplicate present. To solve this, we will follow this approach − We know that the set data structure only holds unique data. But the list can fold duplicate contents. So if we convert the list into the set, its size will be reduced if there are any duplicate elements, by matching the length, we can solve this problem. Let us see the following implementation to get a better understanding − Live Demo class Solution(object): def containsDuplicate(self, nums): """ :type nums: List[int] :rtype: bool """ return not len(nums) == len(set(nums)) ob1 = Solution() print(ob1.containsDuplicate([1,5,6,2,1,3])) print(ob1.containsDuplicate([1,2,3,4])) nums = [1,5,6,2,1,3] nums = [1,2,3,4] True False
[ { "code": null, "e": 1342, "s": 1062, "text": "Suppose we have a list of numbers. We have to check whether the list is holding some duplicate elements or not. So if the list is like [1,5,6,2,1,3], then it will return 1 as there are two 1s, but if the list is [1,2,3,4], then it will be false, as there is no duplicate present." }, { "code": null, "e": 1388, "s": 1342, "text": "To solve this, we will follow this approach −" }, { "code": null, "e": 1643, "s": 1388, "text": "We know that the set data structure only holds unique data. But the list can fold duplicate contents. So if we convert the list into the set, its size will be reduced if there are any duplicate elements, by matching the length, we can solve this problem." }, { "code": null, "e": 1715, "s": 1643, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 1726, "s": 1715, "text": " Live Demo" }, { "code": null, "e": 2001, "s": 1726, "text": "class Solution(object):\n def containsDuplicate(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: bool\n \"\"\"\n return not len(nums) == len(set(nums))\nob1 = Solution()\nprint(ob1.containsDuplicate([1,5,6,2,1,3]))\nprint(ob1.containsDuplicate([1,2,3,4]))" }, { "code": null, "e": 2039, "s": 2001, "text": "nums = [1,5,6,2,1,3]\nnums = [1,2,3,4]" }, { "code": null, "e": 2050, "s": 2039, "text": "True\nFalse" } ]
Tryit Editor v3.6 - Show Python
mydb = mysql.connector.connect( host="localhost", user="myusername", password="mypassword" ) ​ mycursor = mydb.cursor()
[ { "code": null, "e": 57, "s": 25, "text": "mydb = mysql.connector.connect(" }, { "code": null, "e": 77, "s": 57, "text": " host=\"localhost\"," }, { "code": null, "e": 98, "s": 77, "text": " user=\"myusername\"," }, { "code": null, "e": 122, "s": 98, "text": " password=\"mypassword\"" }, { "code": null, "e": 124, "s": 122, "text": ")" }, { "code": null, "e": 126, "s": 124, "text": "​" } ]
Find a triplet in an array whose sum is closest to a given number - GeeksforGeeks
05 Dec, 2021 Given an array arr[] of N integers and an integer X, the task is to find three integers in arr[] such that the sum is closest to X. Examples: Input: arr[] = {-1, 2, 1, -4}, X = 1 Output: 2 Explanation: Sums of triplets: (-1) + 2 + 1 = 2 (-1) + 2 + (-4) = -3 2 + 1 + (-4) = -1 2 is closest to 1. Input: arr[] = {1, 2, 3, 4, -5}, X = 10 Output: 9 Explanation: Sums of triplets: 1 + 2 + 3 = 6 2 + 3 + 4 = 9 1 + 3 + 4 = 7 ... 9 is closest to 10. Simple Approach: The naive approach is to explore all the subsets of size 3 and keep a track of the difference between X and the sum of this subset. Then return the subset whose difference between its sum and X is minimum. Algorithm: Create three nested loops with counter i, j and k respectively.The first loop will start from start to end, the second loop will run from i+1 to end, the third loop will run from j+1 to end.Check if the difference of the sum of the ith, jth and kth element with the given sum is less than the current minimum or not. Update the current minimumPrint the closest sum. Create three nested loops with counter i, j and k respectively. The first loop will start from start to end, the second loop will run from i+1 to end, the third loop will run from j+1 to end. Check if the difference of the sum of the ith, jth and kth element with the given sum is less than the current minimum or not. Update the current minimum Print the closest sum. Implementation: C++14 Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of a// triplet which is closest to xint solution(vector<int>& arr, int x){ // To store the closest sum int closestSum = INT_MAX; // Run three nested loops each loop // for each element of triplet for (int i = 0; i < arr.size() ; i++) { for(int j =i + 1; j < arr.size(); j++) { for(int k =j + 1; k < arr.size(); k++) { //update the closestSum if(abs(x - closestSum) > abs(x - (arr[i] + arr[j] + arr[k]))) closestSum = (arr[i] + arr[j] + arr[k]); } } } // Return the closest sum found return closestSum;} // Driver codeint main(){ vector<int> arr = { -1, 2, 1, -4 }; int x = 1; cout << solution(arr, x); return 0;} // Java implementation of the above approachclass GFG{ // Function to return the sum of a// triplet which is closest to xpublic static int solution(int arr[], int x){ // To store the closest sum int closestSum = Integer.MAX_VALUE; // Run three nested loops each loop // for each element of triplet for(int i = 0; i < arr.length ; i++) { for(int j = i + 1; j < arr.length; j++) { for(int k = j + 1; k < arr.length; k++) { // Update the closestSum if (Math.abs(x - closestSum) > Math.abs(x - (arr[i] + arr[j] + arr[k]))) closestSum = (arr[i] + arr[j] + arr[k]); } } } // Return the closest sum found return closestSum;} // Driver codepublic static void main(String[] args){ int arr[] = { -1, 2, 1, -4 }; int x = 1; System.out.print(solution(arr, x));}} // This code is contributed by divyeshrabadiya07 # Python3 implementation of the above approachimport sys # Function to return the sum of a# triplet which is closest to xdef solution(arr, x): # To store the closest sum closestSum = sys.maxsize # Run three nested loops each loop # for each element of triplet for i in range (len(arr)) : for j in range(i + 1, len(arr)): for k in range(j + 1, len( arr)): # Update the closestSum if(abs(x - closestSum) > abs(x - (arr[i] + arr[j] + arr[k]))): closestSum = (arr[i] + arr[j] + arr[k]) # Return the closest sum found return closestSum # Driver codeif __name__ == "__main__": arr = [ -1, 2, 1, -4 ] x = 1 print(solution(arr, x)) # This code is contributed by chitranayal // C# implementation of the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to return the sum of a// triplet which is closest to xstatic int solution(ArrayList arr, int x){ // To store the closest sum int closestSum = int.MaxValue; // Run three nested loops each loop // for each element of triplet for(int i = 0; i < arr.Count; i++) { for(int j = i + 1; j < arr.Count; j++) { for(int k = j + 1; k < arr.Count; k++) { if (Math.Abs(x - closestSum) > Math.Abs(x - ((int)arr[i] + (int)arr[j] + (int)arr[k]))) { closestSum = ((int)arr[i] + (int)arr[j] + (int)arr[k]); } } } } // Return the closest sum found return closestSum;} // Driver codepublic static void Main(string[] args){ ArrayList arr = new ArrayList(){ -1, 2, 1, -4 }; int x = 1; Console.Write(solution(arr, x));}} // This code is contributed by rutvik_56 <script> // Javascript implementation of the approach // Function to return the sum of a// triplet which is closest to xfunction solution(arr, x){ // To store the closest sum let closestSum = Number.MAX_VALUE; // Run three nested loops each loop // for each element of triplet for(let i = 0; i < arr.length ; i++) { for(let j =i + 1; j < arr.length; j++) { for(let k =j + 1; k < arr.length; k++) { // Update the closestSum if (Math.abs(x - closestSum) > Math.abs(x - (arr[i] + arr[j] + arr[k]))) closestSum = (arr[i] + arr[j] + arr[k]); } } } // Return the closest sum found return closestSum;} // Driver codelet arr = [ -1, 2, 1, -4 ];let x = 1; document.write(solution(arr, x)); // This code is contributed by rishavmahato348 </script> 2 Complexity Analysis: Time complexity: O(N3). Three nested loops are traversing in the array, so time complexity is O(n^3). Space Complexity: O(1). As no extra space is required. Efficient approach: By Sorting the array the efficiency of the algorithm can be improved. This efficient approach uses the two-pointer technique. Traverse the array and fix the first element of the triplet. Now use the Two Pointers algorithm to find the closest number to x – array[i]. Update the closest sum. The two-pointers algorithm takes linear time so it is better than a nested loop. Algorithm: Sort the given array.Loop over the array and fix the first element of the possible triplet, arr[i].Then fix two pointers, one at I + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the sum we need to get to, we increase the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Update the closest sum found so far. Sort the given array. Loop over the array and fix the first element of the possible triplet, arr[i]. Then fix two pointers, one at I + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the sum we need to get to, we increase the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Update the closest sum found so far. If the sum is smaller than the sum we need to get to, we increase the first pointer. Else, If the sum is bigger, Decrease the end pointer to reduce the sum. Update the closest sum found so far. Implementation: C++14 Java Python3 C# Javascript // C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of a// triplet which is closest to xint solution(vector<int>& arr, int x){ // Sort the array sort(arr.begin(), arr.end()); // To store the closest sum //not using INT_MAX to avoid overflowing condition int closestSum = 1000000000; // Fix the smallest number among // the three integers for (int i = 0; i < arr.size() - 2; i++) { // Two pointers initially pointing at // the last and the element // next to the fixed element int ptr1 = i + 1, ptr2 = arr.size() - 1; // While there could be more pairs to check while (ptr1 < ptr2) { // Calculate the sum of the current triplet int sum = arr[i] + arr[ptr1] + arr[ptr2]; // if sum is equal to x, return sum as if (sum == x) return sum; // If the sum is more closer than // the current closest sum if (abs(x - sum) < abs(x - closestSum)) { closestSum = sum; } // If sum is greater then x then decrement // the second pointer to get a smaller sum if (sum > x) { ptr2--; } // Else increment the first pointer // to get a larger sum else { ptr1++; } } } // Return the closest sum found return closestSum;} // Driver codeint main(){ vector<int> arr = { -1, 2, 1, -4 }; int x = 1; cout << solution(arr, x); return 0;} // Java implementation of the above approachimport static java.lang.Math.abs;import java.util.*; class GFG{ // Function to return the sum of a// triplet which is closest to xstatic int solution(Vector<Integer> arr, int x){ // Sort the array Collections.sort(arr); // To store the closest sum // Assigning long to avoid overflow condition // when array has negative integers long closestSum = Integer.MAX_VALUE; // Fix the smallest number among // the three integers for (int i = 0; i < arr.size() - 2; i++) { // Two pointers initially pointing at // the last and the element // next to the fixed element int ptr1 = i + 1, ptr2 = arr.size() - 1; // While there could be more pairs to check while (ptr1 < ptr2) { // Calculate the sum of the current triplet int sum = arr.get(i) + arr.get(ptr1) + arr.get(ptr2); // If the sum is more closer than // the current closest sum if (abs(x - sum) < abs(x - closestSum)) { closestSum = sum; } // If sum is greater then x then decrement // the second pointer to get a smaller sum if (sum > x) { ptr2--; } // Else increment the first pointer // to get a larger sum else { ptr1++; } } } // Return the closest sum found return (int)closestSum;} // Driver codepublic static void main(String[] args){ Vector arr = new Vector(Arrays.asList( -1, 2, 1, -4 )); int x = 1; System.out.println(solution(arr, x));}} /* This code is contributed by PrinciRaj1992 */ # Python3 implementation of the approach import sys # Function to return the sum of a# triplet which is closest to xdef solution(arr, x) : # Sort the array arr.sort(); # To store the closest sum closestSum = sys.maxsize; # Fix the smallest number among # the three integers for i in range(len(arr)-2) : # Two pointers initially pointing at # the last and the element # next to the fixed element ptr1 = i + 1; ptr2 = len(arr) - 1; # While there could be more pairs to check while (ptr1 < ptr2) : # Calculate the sum of the current triplet sum = arr[i] + arr[ptr1] + arr[ptr2]; # If the sum is more closer than # the current closest sum if (abs(x - sum) < abs(x - closestSum)) : closestSum = sum; # If sum is greater then x then decrement # the second pointer to get a smaller sum if (sum > x) : ptr2 -= 1; # Else increment the first pointer # to get a larger sum else : ptr1 += 1; # Return the closest sum found return closestSum; # Driver codeif __name__ == "__main__" : arr = [ -1, 2, 1, -4 ]; x = 1; print(solution(arr, x)); # This code is contributed by AnkitRai01 // C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return the sum of a// triplet which is closest to xstatic int solution(List<int> arr, int x){ // Sort the array arr.Sort(); // To store the closest sum int closestSum = int.MaxValue; // Fix the smallest number among // the three integers for (int i = 0; i < arr.Count - 2; i++) { // Two pointers initially pointing at // the last and the element // next to the fixed element int ptr1 = i + 1, ptr2 = arr.Count - 1; // While there could be more pairs to check while (ptr1 < ptr2) { // Calculate the sum of the current triplet int sum = arr[i] + arr[ptr1] + arr[ptr2]; // If the sum is more closer than // the current closest sum if (Math.Abs(x - sum) < Math.Abs(x - closestSum)) { closestSum = sum; } // If sum is greater then x then decrement // the second pointer to get a smaller sum if (sum > x) { ptr2--; } // Else increment the first pointer // to get a larger sum else { ptr1++; } } } // Return the closest sum found return closestSum;} // Driver codepublic static void Main(String[] args){ int []ar = { -1, 2, 1, -4 }; List<int> arr = new List<int>(ar); int x = 1; Console.WriteLine(solution(arr, x));}} // This code is contributed by Princi Singh <script> // JavaScript implementation of the approach // Function to return the sum of a// triplet which is closest to xfunction solution(arr, x){ // Sort the array arr.sort((a, b) => a - b); // To store the closest sum // not using INT_MAX to avoid // overflowing condition let closestSum = 1000000000; // Fix the smallest number among // the three integers for (let i = 0; i < arr.length - 2; i++) { // Two pointers initially pointing at // the last and the element // next to the fixed element let ptr1 = i + 1, ptr2 = arr.length - 1; // While there could be more pairs to check while (ptr1 < ptr2) { // Calculate the sum of the current triplet let sum = arr[i] + arr[ptr1] + arr[ptr2]; // If the sum is more closer than // the current closest sum if (Math.abs(1*x - sum) < Math.abs(1*x - closestSum)) { closestSum = sum; } // If sum is greater then x then decrement // the second pointer to get a smaller sum if (sum > x) { ptr2--; } // Else increment the first pointer // to get a larger sum else { ptr1++; } } } // Return the closest sum found return closestSum;} // Driver code let arr = [ -1, 2, 1, -4 ]; let x = 1; document.write(solution(arr, x)); // This code is contributed by Surbhi Tyagi. </script> 2 Complexity Analysis: Time complexity: O(N2). There are only two nested loops traversing the array, so time complexity is O(n^2). Two pointer algorithm take O(n) time and the first element can be fixed using another nested traversal. Space Complexity: O(1). As no extra space is required. princiraj1992 ankthon princi singh anvy2 andrew1234 ukasp rutvik_56 divyeshrabadiya07 manish kumar 77 rishavmahato348 surbhityagi15 vaibhavpatel1904 arorakashish0911 ashutoshsinghgeeksforgeeks two-pointer-algorithm Algorithms Arrays Mathematical Sorting two-pointer-algorithm Arrays Mathematical Sorting Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments DSA Sheet by Love Babbar Difference between Informed and Uninformed Search in AI SCAN (Elevator) Disk Scheduling Algorithms Quadratic Probing in Hashing K means Clustering - Introduction Arrays in Java Arrays in C/C++ Program for array rotation Stack Data Structure (Introduction and Program) Largest Sum Contiguous Subarray
[ { "code": null, "e": 24301, "s": 24273, "text": "\n05 Dec, 2021" }, { "code": null, "e": 24433, "s": 24301, "text": "Given an array arr[] of N integers and an integer X, the task is to find three integers in arr[] such that the sum is closest to X." }, { "code": null, "e": 24443, "s": 24433, "text": "Examples:" }, { "code": null, "e": 24744, "s": 24443, "text": "Input: arr[] = {-1, 2, 1, -4}, X = 1\nOutput: 2\nExplanation:\nSums of triplets:\n(-1) + 2 + 1 = 2\n(-1) + 2 + (-4) = -3\n2 + 1 + (-4) = -1\n2 is closest to 1.\n\nInput: arr[] = {1, 2, 3, 4, -5}, X = 10\nOutput: 9\nExplanation:\nSums of triplets:\n1 + 2 + 3 = 6\n2 + 3 + 4 = 9\n1 + 3 + 4 = 7\n...\n9 is closest to 10." }, { "code": null, "e": 24967, "s": 24744, "text": "Simple Approach: The naive approach is to explore all the subsets of size 3 and keep a track of the difference between X and the sum of this subset. Then return the subset whose difference between its sum and X is minimum." }, { "code": null, "e": 24978, "s": 24967, "text": "Algorithm:" }, { "code": null, "e": 25344, "s": 24978, "text": "Create three nested loops with counter i, j and k respectively.The first loop will start from start to end, the second loop will run from i+1 to end, the third loop will run from j+1 to end.Check if the difference of the sum of the ith, jth and kth element with the given sum is less than the current minimum or not. Update the current minimumPrint the closest sum." }, { "code": null, "e": 25408, "s": 25344, "text": "Create three nested loops with counter i, j and k respectively." }, { "code": null, "e": 25536, "s": 25408, "text": "The first loop will start from start to end, the second loop will run from i+1 to end, the third loop will run from j+1 to end." }, { "code": null, "e": 25690, "s": 25536, "text": "Check if the difference of the sum of the ith, jth and kth element with the given sum is less than the current minimum or not. Update the current minimum" }, { "code": null, "e": 25713, "s": 25690, "text": "Print the closest sum." }, { "code": null, "e": 25729, "s": 25713, "text": "Implementation:" }, { "code": null, "e": 25735, "s": 25729, "text": "C++14" }, { "code": null, "e": 25740, "s": 25735, "text": "Java" }, { "code": null, "e": 25748, "s": 25740, "text": "Python3" }, { "code": null, "e": 25751, "s": 25748, "text": "C#" }, { "code": null, "e": 25762, "s": 25751, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of a// triplet which is closest to xint solution(vector<int>& arr, int x){ // To store the closest sum int closestSum = INT_MAX; // Run three nested loops each loop // for each element of triplet for (int i = 0; i < arr.size() ; i++) { for(int j =i + 1; j < arr.size(); j++) { for(int k =j + 1; k < arr.size(); k++) { //update the closestSum if(abs(x - closestSum) > abs(x - (arr[i] + arr[j] + arr[k]))) closestSum = (arr[i] + arr[j] + arr[k]); } } } // Return the closest sum found return closestSum;} // Driver codeint main(){ vector<int> arr = { -1, 2, 1, -4 }; int x = 1; cout << solution(arr, x); return 0;}", "e": 26631, "s": 25762, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // Function to return the sum of a// triplet which is closest to xpublic static int solution(int arr[], int x){ // To store the closest sum int closestSum = Integer.MAX_VALUE; // Run three nested loops each loop // for each element of triplet for(int i = 0; i < arr.length ; i++) { for(int j = i + 1; j < arr.length; j++) { for(int k = j + 1; k < arr.length; k++) { // Update the closestSum if (Math.abs(x - closestSum) > Math.abs(x - (arr[i] + arr[j] + arr[k]))) closestSum = (arr[i] + arr[j] + arr[k]); } } } // Return the closest sum found return closestSum;} // Driver codepublic static void main(String[] args){ int arr[] = { -1, 2, 1, -4 }; int x = 1; System.out.print(solution(arr, x));}} // This code is contributed by divyeshrabadiya07", "e": 27631, "s": 26631, "text": null }, { "code": "# Python3 implementation of the above approachimport sys # Function to return the sum of a# triplet which is closest to xdef solution(arr, x): # To store the closest sum closestSum = sys.maxsize # Run three nested loops each loop # for each element of triplet for i in range (len(arr)) : for j in range(i + 1, len(arr)): for k in range(j + 1, len( arr)): # Update the closestSum if(abs(x - closestSum) > abs(x - (arr[i] + arr[j] + arr[k]))): closestSum = (arr[i] + arr[j] + arr[k]) # Return the closest sum found return closestSum # Driver codeif __name__ == \"__main__\": arr = [ -1, 2, 1, -4 ] x = 1 print(solution(arr, x)) # This code is contributed by chitranayal", "e": 28497, "s": 27631, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Collections;using System.Collections.Generic; class GFG{ // Function to return the sum of a// triplet which is closest to xstatic int solution(ArrayList arr, int x){ // To store the closest sum int closestSum = int.MaxValue; // Run three nested loops each loop // for each element of triplet for(int i = 0; i < arr.Count; i++) { for(int j = i + 1; j < arr.Count; j++) { for(int k = j + 1; k < arr.Count; k++) { if (Math.Abs(x - closestSum) > Math.Abs(x - ((int)arr[i] + (int)arr[j] + (int)arr[k]))) { closestSum = ((int)arr[i] + (int)arr[j] + (int)arr[k]); } } } } // Return the closest sum found return closestSum;} // Driver codepublic static void Main(string[] args){ ArrayList arr = new ArrayList(){ -1, 2, 1, -4 }; int x = 1; Console.Write(solution(arr, x));}} // This code is contributed by rutvik_56", "e": 29640, "s": 28497, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the sum of a// triplet which is closest to xfunction solution(arr, x){ // To store the closest sum let closestSum = Number.MAX_VALUE; // Run three nested loops each loop // for each element of triplet for(let i = 0; i < arr.length ; i++) { for(let j =i + 1; j < arr.length; j++) { for(let k =j + 1; k < arr.length; k++) { // Update the closestSum if (Math.abs(x - closestSum) > Math.abs(x - (arr[i] + arr[j] + arr[k]))) closestSum = (arr[i] + arr[j] + arr[k]); } } } // Return the closest sum found return closestSum;} // Driver codelet arr = [ -1, 2, 1, -4 ];let x = 1; document.write(solution(arr, x)); // This code is contributed by rishavmahato348 </script>", "e": 30555, "s": 29640, "text": null }, { "code": null, "e": 30557, "s": 30555, "text": "2" }, { "code": null, "e": 30578, "s": 30557, "text": "Complexity Analysis:" }, { "code": null, "e": 30680, "s": 30578, "text": "Time complexity: O(N3). Three nested loops are traversing in the array, so time complexity is O(n^3)." }, { "code": null, "e": 30735, "s": 30680, "text": "Space Complexity: O(1). As no extra space is required." }, { "code": null, "e": 31126, "s": 30735, "text": "Efficient approach: By Sorting the array the efficiency of the algorithm can be improved. This efficient approach uses the two-pointer technique. Traverse the array and fix the first element of the triplet. Now use the Two Pointers algorithm to find the closest number to x – array[i]. Update the closest sum. The two-pointers algorithm takes linear time so it is better than a nested loop." }, { "code": null, "e": 31138, "s": 31126, "text": "Algorithm: " }, { "code": null, "e": 31510, "s": 31138, "text": "Sort the given array.Loop over the array and fix the first element of the possible triplet, arr[i].Then fix two pointers, one at I + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the sum we need to get to, we increase the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Update the closest sum found so far." }, { "code": null, "e": 31532, "s": 31510, "text": "Sort the given array." }, { "code": null, "e": 31611, "s": 31532, "text": "Loop over the array and fix the first element of the possible triplet, arr[i]." }, { "code": null, "e": 31884, "s": 31611, "text": "Then fix two pointers, one at I + 1 and the other at n – 1. And look at the sum, If the sum is smaller than the sum we need to get to, we increase the first pointer.Else, If the sum is bigger, Decrease the end pointer to reduce the sum.Update the closest sum found so far." }, { "code": null, "e": 31969, "s": 31884, "text": "If the sum is smaller than the sum we need to get to, we increase the first pointer." }, { "code": null, "e": 32041, "s": 31969, "text": "Else, If the sum is bigger, Decrease the end pointer to reduce the sum." }, { "code": null, "e": 32078, "s": 32041, "text": "Update the closest sum found so far." }, { "code": null, "e": 32094, "s": 32078, "text": "Implementation:" }, { "code": null, "e": 32100, "s": 32094, "text": "C++14" }, { "code": null, "e": 32105, "s": 32100, "text": "Java" }, { "code": null, "e": 32113, "s": 32105, "text": "Python3" }, { "code": null, "e": 32116, "s": 32113, "text": "C#" }, { "code": null, "e": 32127, "s": 32116, "text": "Javascript" }, { "code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the sum of a// triplet which is closest to xint solution(vector<int>& arr, int x){ // Sort the array sort(arr.begin(), arr.end()); // To store the closest sum //not using INT_MAX to avoid overflowing condition int closestSum = 1000000000; // Fix the smallest number among // the three integers for (int i = 0; i < arr.size() - 2; i++) { // Two pointers initially pointing at // the last and the element // next to the fixed element int ptr1 = i + 1, ptr2 = arr.size() - 1; // While there could be more pairs to check while (ptr1 < ptr2) { // Calculate the sum of the current triplet int sum = arr[i] + arr[ptr1] + arr[ptr2]; // if sum is equal to x, return sum as if (sum == x) return sum; // If the sum is more closer than // the current closest sum if (abs(x - sum) < abs(x - closestSum)) { closestSum = sum; } // If sum is greater then x then decrement // the second pointer to get a smaller sum if (sum > x) { ptr2--; } // Else increment the first pointer // to get a larger sum else { ptr1++; } } } // Return the closest sum found return closestSum;} // Driver codeint main(){ vector<int> arr = { -1, 2, 1, -4 }; int x = 1; cout << solution(arr, x); return 0;}", "e": 33750, "s": 32127, "text": null }, { "code": "// Java implementation of the above approachimport static java.lang.Math.abs;import java.util.*; class GFG{ // Function to return the sum of a// triplet which is closest to xstatic int solution(Vector<Integer> arr, int x){ // Sort the array Collections.sort(arr); // To store the closest sum // Assigning long to avoid overflow condition // when array has negative integers long closestSum = Integer.MAX_VALUE; // Fix the smallest number among // the three integers for (int i = 0; i < arr.size() - 2; i++) { // Two pointers initially pointing at // the last and the element // next to the fixed element int ptr1 = i + 1, ptr2 = arr.size() - 1; // While there could be more pairs to check while (ptr1 < ptr2) { // Calculate the sum of the current triplet int sum = arr.get(i) + arr.get(ptr1) + arr.get(ptr2); // If the sum is more closer than // the current closest sum if (abs(x - sum) < abs(x - closestSum)) { closestSum = sum; } // If sum is greater then x then decrement // the second pointer to get a smaller sum if (sum > x) { ptr2--; } // Else increment the first pointer // to get a larger sum else { ptr1++; } } } // Return the closest sum found return (int)closestSum;} // Driver codepublic static void main(String[] args){ Vector arr = new Vector(Arrays.asList( -1, 2, 1, -4 )); int x = 1; System.out.println(solution(arr, x));}} /* This code is contributed by PrinciRaj1992 */", "e": 35489, "s": 33750, "text": null }, { "code": "# Python3 implementation of the approach import sys # Function to return the sum of a# triplet which is closest to xdef solution(arr, x) : # Sort the array arr.sort(); # To store the closest sum closestSum = sys.maxsize; # Fix the smallest number among # the three integers for i in range(len(arr)-2) : # Two pointers initially pointing at # the last and the element # next to the fixed element ptr1 = i + 1; ptr2 = len(arr) - 1; # While there could be more pairs to check while (ptr1 < ptr2) : # Calculate the sum of the current triplet sum = arr[i] + arr[ptr1] + arr[ptr2]; # If the sum is more closer than # the current closest sum if (abs(x - sum) < abs(x - closestSum)) : closestSum = sum; # If sum is greater then x then decrement # the second pointer to get a smaller sum if (sum > x) : ptr2 -= 1; # Else increment the first pointer # to get a larger sum else : ptr1 += 1; # Return the closest sum found return closestSum; # Driver codeif __name__ == \"__main__\" : arr = [ -1, 2, 1, -4 ]; x = 1; print(solution(arr, x)); # This code is contributed by AnkitRai01", "e": 36817, "s": 35489, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Collections.Generic; class GFG{ // Function to return the sum of a// triplet which is closest to xstatic int solution(List<int> arr, int x){ // Sort the array arr.Sort(); // To store the closest sum int closestSum = int.MaxValue; // Fix the smallest number among // the three integers for (int i = 0; i < arr.Count - 2; i++) { // Two pointers initially pointing at // the last and the element // next to the fixed element int ptr1 = i + 1, ptr2 = arr.Count - 1; // While there could be more pairs to check while (ptr1 < ptr2) { // Calculate the sum of the current triplet int sum = arr[i] + arr[ptr1] + arr[ptr2]; // If the sum is more closer than // the current closest sum if (Math.Abs(x - sum) < Math.Abs(x - closestSum)) { closestSum = sum; } // If sum is greater then x then decrement // the second pointer to get a smaller sum if (sum > x) { ptr2--; } // Else increment the first pointer // to get a larger sum else { ptr1++; } } } // Return the closest sum found return closestSum;} // Driver codepublic static void Main(String[] args){ int []ar = { -1, 2, 1, -4 }; List<int> arr = new List<int>(ar); int x = 1; Console.WriteLine(solution(arr, x));}} // This code is contributed by Princi Singh", "e": 38445, "s": 36817, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to return the sum of a// triplet which is closest to xfunction solution(arr, x){ // Sort the array arr.sort((a, b) => a - b); // To store the closest sum // not using INT_MAX to avoid // overflowing condition let closestSum = 1000000000; // Fix the smallest number among // the three integers for (let i = 0; i < arr.length - 2; i++) { // Two pointers initially pointing at // the last and the element // next to the fixed element let ptr1 = i + 1, ptr2 = arr.length - 1; // While there could be more pairs to check while (ptr1 < ptr2) { // Calculate the sum of the current triplet let sum = arr[i] + arr[ptr1] + arr[ptr2]; // If the sum is more closer than // the current closest sum if (Math.abs(1*x - sum) < Math.abs(1*x - closestSum)) { closestSum = sum; } // If sum is greater then x then decrement // the second pointer to get a smaller sum if (sum > x) { ptr2--; } // Else increment the first pointer // to get a larger sum else { ptr1++; } } } // Return the closest sum found return closestSum;} // Driver code let arr = [ -1, 2, 1, -4 ]; let x = 1; document.write(solution(arr, x)); // This code is contributed by Surbhi Tyagi. </script>", "e": 39973, "s": 38445, "text": null }, { "code": null, "e": 39975, "s": 39973, "text": "2" }, { "code": null, "e": 39996, "s": 39975, "text": "Complexity Analysis:" }, { "code": null, "e": 40208, "s": 39996, "text": "Time complexity: O(N2). There are only two nested loops traversing the array, so time complexity is O(n^2). Two pointer algorithm take O(n) time and the first element can be fixed using another nested traversal." }, { "code": null, "e": 40263, "s": 40208, "text": "Space Complexity: O(1). As no extra space is required." }, { "code": null, "e": 40277, "s": 40263, "text": "princiraj1992" }, { "code": null, "e": 40285, "s": 40277, "text": "ankthon" }, { "code": null, "e": 40298, "s": 40285, "text": "princi singh" }, { "code": null, "e": 40304, "s": 40298, "text": "anvy2" }, { "code": null, "e": 40315, "s": 40304, "text": "andrew1234" }, { "code": null, "e": 40321, "s": 40315, "text": "ukasp" }, { "code": null, "e": 40331, "s": 40321, "text": "rutvik_56" }, { "code": null, "e": 40349, "s": 40331, "text": "divyeshrabadiya07" }, { "code": null, "e": 40365, "s": 40349, "text": "manish kumar 77" }, { "code": null, "e": 40381, "s": 40365, "text": "rishavmahato348" }, { "code": null, "e": 40395, "s": 40381, "text": "surbhityagi15" }, { "code": null, "e": 40412, "s": 40395, "text": "vaibhavpatel1904" }, { "code": null, "e": 40429, "s": 40412, "text": "arorakashish0911" }, { "code": null, "e": 40456, "s": 40429, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 40478, "s": 40456, "text": "two-pointer-algorithm" }, { "code": null, "e": 40489, "s": 40478, "text": "Algorithms" }, { "code": null, "e": 40496, "s": 40489, "text": "Arrays" }, { "code": null, "e": 40509, "s": 40496, "text": "Mathematical" }, { "code": null, "e": 40517, "s": 40509, "text": "Sorting" }, { "code": null, "e": 40539, "s": 40517, "text": "two-pointer-algorithm" }, { "code": null, "e": 40546, "s": 40539, "text": "Arrays" }, { "code": null, "e": 40559, "s": 40546, "text": "Mathematical" }, { "code": null, "e": 40567, "s": 40559, "text": "Sorting" }, { "code": null, "e": 40578, "s": 40567, "text": "Algorithms" }, { "code": null, "e": 40676, "s": 40578, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40685, "s": 40676, "text": "Comments" }, { "code": null, "e": 40698, "s": 40685, "text": "Old Comments" }, { "code": null, "e": 40723, "s": 40698, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 40779, "s": 40723, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 40822, "s": 40779, "text": "SCAN (Elevator) Disk Scheduling Algorithms" }, { "code": null, "e": 40851, "s": 40822, "text": "Quadratic Probing in Hashing" }, { "code": null, "e": 40885, "s": 40851, "text": "K means Clustering - Introduction" }, { "code": null, "e": 40900, "s": 40885, "text": "Arrays in Java" }, { "code": null, "e": 40916, "s": 40900, "text": "Arrays in C/C++" }, { "code": null, "e": 40943, "s": 40916, "text": "Program for array rotation" }, { "code": null, "e": 40991, "s": 40943, "text": "Stack Data Structure (Introduction and Program)" } ]
Consonants and Vowels check | Practice | GeeksforGeeks
Let's learn about CPP strings here. CPP strings are quite different from their C counterpart and have various methods that can be invoked on them. We hope you've read the articles. You are given a string s containing only lowercase letters. You need to count the number of vowels and the number of consonants. If vowel count > consonant count then print - Yes(without quotes). If vowel count < consonant count then print - No(without quotes). If vowel count = consonant count then print - Same(without quotes). Example 1: Input:s = "aaaaaa"Output:Yes Example 2: Input:s = "the quick brown fox jumps over the lazy dog"Output:No Your Task:Since this is a function problem, you don't need to take any input. Just complete the function checkString(string s) that take s as input and produces output. In a new line, print the output. Constraints:1 <= |s| <= 100 0 starrlord3 weeks ago void checkString(string s) { int v=0; int c=0; int n=s.length(); int x=s.length(); for(int i=0;i<n;i++){ if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u') v++; else if(s[i]==' ') x--; } c=x-v; //Your code here if(v>c) cout<<"Yes"; else if(c>v) cout<<"No"; else cout<<"Same"; cout<<endl; } 0 sahilrawat6801 month ago // { Driver Code Starts//Initial Template for C++ #include <bits/stdc++.h>using namespace std; void checkString(string s); // } Driver Code Ends//User function Template for C++ void checkString(string s){ int v=0; int c=0; for(int i=0; i<s.size();i++) { if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')){ if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'){ v++; } else{ c++; } } } //Your code here if(v>c) cout<<"Yes"; else if(c>v) cout<<"No"; else cout<<"Same"; cout<<endl;} // { Driver Code Starts. int main() {int t;cin>>t;cin.ignore();while(t--){ string s; getline(cin,s); //function call checkString(s); }return 0;} // } Driver Code Ends 0 amityadav101 month ago //what's mistake in this code// //last case failed// int v=0; int c=0; int n=s.length(); //Your code here for(int i=0;i<=n;i++) { if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u') { v=v+1; } else { c=c+1; } } if(v>c) cout<<"Yes"; else if(c>v) cout<<"No"; else cout<<"Same"; cout<<endl; 0 diptendunandi3 months ago void checkString(string s) { int v=0; int c=0; //Your code here for(int i=0;i<s.length();i++){ if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')){ if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u') v++; else c++; } } if(v>c) cout<<"Yes"; else if(c>v) cout<<"No"; else cout<<"Same"; cout<<endl; } 0 mayank20213 months ago The catch in this question is the "space" in between characters of string. This space should be taken into account and should be avoided getting counted both in vowels and consonants. 0 kritigupta70315 months ago void checkString(string s){ int v=0; int c=0; //Your code here for(int i=0;i<s.length();i++){ if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')){ if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u' ) v++; else c++; } } if(v>c) cout<<"Yes"; else if(c>v) cout<<"No"; else cout<<"Same"; cout<<endl; } 0 kritigupta7031 This comment was deleted. 0 ayushnautiyal11106 months ago void checkString(string s){ int v=0; int c=0; for(int i=0;i<s.length();i++){ if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u'){ v++; } else if(s[i]== ' '){ continue; } else{ c++; } } if(v>c) cout<<"Yes"; else if(c>v) cout<<"No"; else cout<<"Same"; cout<<endl;} 0 bawarisuresh1236 months ago int v=0; int c=0; int i=0;int n=s.size();while(i<n){ if(s[i]!='a'&&s[i]!='e'&&s[i]!='i'&&s[i]!='o'&&s[i]!='u'&&s[i]!='A'&&s[i]!='E'&&s[i]!='I'&&s[i]!='O'&&s[i]!='U'&&s[i]!=' ') { c++; i++; } else if(s[i]==' '){ i++; } else{ v++; i++; }} if(v>c) cout<<"Yes"; else if(c>v) cout<<"No"; else cout<<"Same"; cout<<endl;} 0 PRJ9 months ago PRJ Tip: //EXCLUDE ' ' (space) void checkString(string s){ int v=0; int c=0; //Your code here for(int i=0;i<s.length();i++) {="" if((s[i]="='a'" ||s[i]="='e'" ||s[i]="='i'" ||s[i]="='o'" ||s[i]="='u')" )="" v++;="" else="" if(s[i]!=" " )="" else="" c++;="" }="" cout<<v;="" cout<<c;="" if(v="">c) cout<<"Yes"; else if(c>v) cout<<"No"; else if(c==v) cout<<"Same"; cout<<endl; }=""> We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 407, "s": 226, "text": "Let's learn about CPP strings here. CPP strings are quite different from their C counterpart and have various methods that can be invoked on them. We hope you've read the articles." }, { "code": null, "e": 537, "s": 407, "text": "You are given a string s containing only lowercase letters. You need to count the number of vowels and the number of consonants. " }, { "code": null, "e": 604, "s": 537, "text": "If vowel count > consonant count then print - Yes(without quotes)." }, { "code": null, "e": 670, "s": 604, "text": "If vowel count < consonant count then print - No(without quotes)." }, { "code": null, "e": 738, "s": 670, "text": "If vowel count = consonant count then print - Same(without quotes)." }, { "code": null, "e": 749, "s": 738, "text": "Example 1:" }, { "code": null, "e": 778, "s": 749, "text": "Input:s = \"aaaaaa\"Output:Yes" }, { "code": null, "e": 789, "s": 778, "text": "Example 2:" }, { "code": null, "e": 854, "s": 789, "text": "Input:s = \"the quick brown fox jumps over the lazy dog\"Output:No" }, { "code": null, "e": 1056, "s": 854, "text": "Your Task:Since this is a function problem, you don't need to take any input. Just complete the function checkString(string s) that take s as input and produces output. In a new line, print the output." }, { "code": null, "e": 1084, "s": 1056, "text": "Constraints:1 <= |s| <= 100" }, { "code": null, "e": 1086, "s": 1084, "text": "0" }, { "code": null, "e": 1107, "s": 1086, "text": "starrlord3 weeks ago" }, { "code": null, "e": 1526, "s": 1107, "text": "void checkString(string s)\n{\n int v=0;\n int c=0;\n int n=s.length();\n int x=s.length();\n for(int i=0;i<n;i++){\n if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u')\n v++;\n else if(s[i]==' ')\n x--;\n }\n c=x-v;\n //Your code here\n \n if(v>c)\n cout<<\"Yes\";\n else if(c>v)\n cout<<\"No\";\n else\n cout<<\"Same\";\n \n cout<<endl;\n}" }, { "code": null, "e": 1528, "s": 1526, "text": "0" }, { "code": null, "e": 1553, "s": 1528, "text": "sahilrawat6801 month ago" }, { "code": null, "e": 1603, "s": 1553, "text": "// { Driver Code Starts//Initial Template for C++" }, { "code": null, "e": 1648, "s": 1603, "text": "#include <bits/stdc++.h>using namespace std;" }, { "code": null, "e": 1676, "s": 1648, "text": "void checkString(string s);" }, { "code": null, "e": 1730, "s": 1676, "text": "// } Driver Code Ends//User function Template for C++" }, { "code": null, "e": 2143, "s": 1730, "text": "void checkString(string s){ int v=0; int c=0; for(int i=0; i<s.size();i++) { if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')){ if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u'){ v++; } else{ c++; } } } //Your code here if(v>c) cout<<\"Yes\"; else if(c>v) cout<<\"No\"; else cout<<\"Same\"; cout<<endl;}" }, { "code": null, "e": 2168, "s": 2143, "text": "// { Driver Code Starts." }, { "code": null, "e": 2310, "s": 2168, "text": "int main() {int t;cin>>t;cin.ignore();while(t--){ string s; getline(cin,s); //function call checkString(s); }return 0;}" }, { "code": null, "e": 2333, "s": 2310, "text": " // } Driver Code Ends" }, { "code": null, "e": 2335, "s": 2333, "text": "0" }, { "code": null, "e": 2358, "s": 2335, "text": "amityadav101 month ago" }, { "code": null, "e": 2390, "s": 2358, "text": "//what's mistake in this code//" }, { "code": null, "e": 2412, "s": 2390, "text": "//last case failed// " }, { "code": null, "e": 2756, "s": 2412, "text": "int v=0; int c=0; int n=s.length(); //Your code here for(int i=0;i<=n;i++) { if(s[i]=='a'||s[i]=='e'||s[i]=='i'||s[i]=='o'||s[i]=='u') { v=v+1; } else { c=c+1; } } if(v>c) cout<<\"Yes\"; else if(c>v) cout<<\"No\"; else cout<<\"Same\"; cout<<endl;" }, { "code": null, "e": 2758, "s": 2756, "text": "0" }, { "code": null, "e": 2784, "s": 2758, "text": "diptendunandi3 months ago" }, { "code": null, "e": 3224, "s": 2784, "text": "void checkString(string s)\n{\n int v=0;\n int c=0;\n \n //Your code here\n for(int i=0;i<s.length();i++){\n if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')){\n if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u')\n v++;\n \n else\n c++;\n }\n }\n \n if(v>c)\n cout<<\"Yes\";\n else if(c>v)\n cout<<\"No\";\n else\n cout<<\"Same\";\n \n cout<<endl;\n}" }, { "code": null, "e": 3226, "s": 3224, "text": "0" }, { "code": null, "e": 3249, "s": 3226, "text": "mayank20213 months ago" }, { "code": null, "e": 3434, "s": 3249, "text": "The catch in this question is the \"space\" in between characters of string. This space should be taken into account and should be avoided getting counted both in vowels and consonants." }, { "code": null, "e": 3436, "s": 3434, "text": "0" }, { "code": null, "e": 3463, "s": 3436, "text": "kritigupta70315 months ago" }, { "code": null, "e": 3893, "s": 3463, "text": "void checkString(string s){ int v=0; int c=0; //Your code here for(int i=0;i<s.length();i++){ if((s[i]>='a' && s[i]<='z') || (s[i]>='A' && s[i]<='Z')){ if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u' ) v++; else c++; } } if(v>c) cout<<\"Yes\"; else if(c>v) cout<<\"No\"; else cout<<\"Same\"; cout<<endl;" }, { "code": null, "e": 3895, "s": 3893, "text": "}" }, { "code": null, "e": 3897, "s": 3895, "text": "0" }, { "code": null, "e": 3912, "s": 3897, "text": "kritigupta7031" }, { "code": null, "e": 3938, "s": 3912, "text": "This comment was deleted." }, { "code": null, "e": 3940, "s": 3938, "text": "0" }, { "code": null, "e": 3970, "s": 3940, "text": "ayushnautiyal11106 months ago" }, { "code": null, "e": 4356, "s": 3970, "text": "void checkString(string s){ int v=0; int c=0; for(int i=0;i<s.length();i++){ if(s[i]=='a' || s[i]=='e' || s[i]=='i' || s[i]=='o' || s[i]=='u'){ v++; } else if(s[i]== ' '){ continue; } else{ c++; } } if(v>c) cout<<\"Yes\"; else if(c>v) cout<<\"No\"; else cout<<\"Same\"; cout<<endl;}" }, { "code": null, "e": 4358, "s": 4356, "text": "0" }, { "code": null, "e": 4386, "s": 4358, "text": "bawarisuresh1236 months ago" }, { "code": null, "e": 4778, "s": 4386, "text": " int v=0; int c=0; int i=0;int n=s.size();while(i<n){ if(s[i]!='a'&&s[i]!='e'&&s[i]!='i'&&s[i]!='o'&&s[i]!='u'&&s[i]!='A'&&s[i]!='E'&&s[i]!='I'&&s[i]!='O'&&s[i]!='U'&&s[i]!=' ') { c++; i++; } else if(s[i]==' '){ i++; } else{ v++; i++; }} if(v>c) cout<<\"Yes\"; else if(c>v) cout<<\"No\"; else cout<<\"Same\"; cout<<endl;}" }, { "code": null, "e": 4780, "s": 4778, "text": "0" }, { "code": null, "e": 4796, "s": 4780, "text": "PRJ9 months ago" }, { "code": null, "e": 4800, "s": 4796, "text": "PRJ" }, { "code": null, "e": 4829, "s": 4800, "text": "Tip: //EXCLUDE ' ' (space) " }, { "code": null, "e": 4881, "s": 4829, "text": "void checkString(string s){ int v=0; int c=0;" }, { "code": null, "e": 5201, "s": 4881, "text": " //Your code here for(int i=0;i<s.length();i++) {=\"\" if((s[i]=\"='a'\" ||s[i]=\"='e'\" ||s[i]=\"='i'\" ||s[i]=\"='o'\" ||s[i]=\"='u')\" )=\"\" v++;=\"\" else=\"\" if(s[i]!=\" \" )=\"\" else=\"\" c++;=\"\" }=\"\" cout<<v;=\"\" cout<<c;=\"\" if(v=\"\">c) cout<<\"Yes\"; else if(c>v) cout<<\"No\"; else if(c==v) cout<<\"Same\";" }, { "code": null, "e": 5223, "s": 5201, "text": " cout<<endl; }=\"\">" }, { "code": null, "e": 5369, "s": 5223, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5405, "s": 5369, "text": " Login to access your submissions. " }, { "code": null, "e": 5415, "s": 5405, "text": "\nProblem\n" }, { "code": null, "e": 5425, "s": 5415, "text": "\nContest\n" }, { "code": null, "e": 5488, "s": 5425, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 5636, "s": 5488, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 5844, "s": 5636, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 5950, "s": 5844, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Find out if a varchar contains a percent sign in MySQL?
To find out a varchar contains a percent sign in MySQL, you can use LIKE operator. The syntax is as follows − SELECT * FROM yourTableName WHERE yourColumnName like '%|%%' escape '|'; To understand the above syntax, let us create a table. The query to create a table is as follows − mysql> create table FindPercentInVarcharDemo -> ( -> Id int NOT NULL AUTO_INCREMENT, -> Words varchar(30), -> PRIMARY KEY(Id) -> ); Query OK, 0 rows affected (0.51 sec) Insert some records with % sign using insert command. The query is as follows − mysql> insert into FindPercentInVarcharDemo(Words) values('This is a My%SQL Program'); Query OK, 1 row affected (0.19 sec) mysql> insert into FindPercentInVarcharDemo(Words) values('Java is an object oriented'); Query OK, 1 row affected (0.19 sec) mysql> insert into FindPercentInVarcharDemo(Words) values('C# is also an object%oriented'); Query OK, 1 row affected (0.57 sec) Display all records from the table using select statement. The query is as follows − mysql> select *from FindPercentInVarcharDemo; The following is the output − +----+-------------------------------+ | Id | Words | +----+-------------------------------+ | 1 | This is a My%SQL Program | | 2 | Java is an object oriented | | 4 | C# is also an object%oriented | +----+-------------------------------+ 3 rows in set (0.00 sec) The following is the query to find out varchar contains % sign. The query is as follows − mysql> select *from FindPercentInVarcharDemo where Words like '%|%%' escape '|'; The following is the output displaying only the values with a % sign − +----+-------------------------------+ | Id | Words | +----+-------------------------------+ | 1 | This is a My%SQL Program | | 4 | C# is also an object%oriented | +----+-------------------------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1172, "s": 1062, "text": "To find out a varchar contains a percent sign in MySQL, you can use LIKE operator. The syntax is as follows −" }, { "code": null, "e": 1245, "s": 1172, "text": "SELECT * FROM yourTableName WHERE yourColumnName like '%|%%' escape '|';" }, { "code": null, "e": 1344, "s": 1245, "text": "To understand the above syntax, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1528, "s": 1344, "text": "mysql> create table FindPercentInVarcharDemo\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> Words varchar(30),\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.51 sec)" }, { "code": null, "e": 1608, "s": 1528, "text": "Insert some records with % sign using insert command. The query is as follows −" }, { "code": null, "e": 1986, "s": 1608, "text": "mysql> insert into FindPercentInVarcharDemo(Words) values('This is a My%SQL Program');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into FindPercentInVarcharDemo(Words) values('Java is an object oriented');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into FindPercentInVarcharDemo(Words) values('C# is also an object%oriented');\nQuery OK, 1 row affected (0.57 sec)" }, { "code": null, "e": 2071, "s": 1986, "text": "Display all records from the table using select statement. The query is as follows −" }, { "code": null, "e": 2117, "s": 2071, "text": "mysql> select *from FindPercentInVarcharDemo;" }, { "code": null, "e": 2147, "s": 2117, "text": "The following is the output −" }, { "code": null, "e": 2445, "s": 2147, "text": "+----+-------------------------------+\n| Id | Words |\n+----+-------------------------------+\n| 1 | This is a My%SQL Program |\n| 2 | Java is an object oriented |\n| 4 | C# is also an object%oriented |\n+----+-------------------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2535, "s": 2445, "text": "The following is the query to find out varchar contains % sign. The query is as follows −" }, { "code": null, "e": 2616, "s": 2535, "text": "mysql> select *from FindPercentInVarcharDemo where Words like '%|%%' escape '|';" }, { "code": null, "e": 2687, "s": 2616, "text": "The following is the output displaying only the values with a % sign −" }, { "code": null, "e": 2946, "s": 2687, "text": "+----+-------------------------------+\n| Id | Words |\n+----+-------------------------------+\n| 1 | This is a My%SQL Program |\n| 4 | C# is also an object%oriented |\n+----+-------------------------------+\n2 rows in set (0.00 sec)" } ]
Logging with Weights & Biases. Monitoring your Neural Network’s... | by Abdur Rahman Kalim | Towards Data Science
Logging the loss and accuracy curves has never been an easy job. We often save these values in arrays or lists and then plot them at the end of the training. Sharing these graphs is even harder where sending screenshots of these graphs seems the only choice. In this tutorial, we will address this issue with Weights & Biases. Weights & Biases (WandB) is a python package that allows us to monitor our training in real-time. It can be easily integrated with popular deep learning frameworks like Pytorch, Tensorflow, or Keras. Additionally, it allows us to organize our Runs into Projects where we can easily compare them and identify the best performing model. In this guide, we will learn how to use WandB for logging. First, let’s create a free WandB account here. WandB provides a 200GB limited storage on the free account, where we can log graphs, images, videos, and much more. Running the code snippet below will install WandB to our Colab Notebook instance. After installing and importing WandB, it will prompt us to authenticate the same way as we do when mounting Google Drive to the notebook instance. In this tutorial, we will train a Convolutional Neural Network on Fashion MNIST Dataset which is available in PyTorch’s torchvision.datasets. We will split the datasets into batches and shuffle them before feeding them to our Neural Network. For simplicity, we will not use any data augmentation except transforming the images and labels into torch tensors. We will use a simple Convolutional Neural Network with 2 Conv layers and 3 Linear layers. In the input Conv layer, we will keep the input channel count as 1 for the neural network to accept grayscale images. Similarly, in the final hidden layer, the output channel count should be 10 for the model to output scores for each of the 10 classes. Before training, we must run wandb.init(). This will initialize a new Run in the WandB database. wandb.init() has the following parameters: Name of the Run (string) Name of the Project where this Run should be created (string) Notes about this Run (string)[optional] Tags to associate with this Run (list of strings) [optional] Entity is the username of our WandB account (string). Any hyperparameter that we want to log can be defined as an attribute of wandb.config. Note that wandb.config should be used to log only those values which do not change during training. Here, we have logged the learning rate using this method. Logging weight histograms is as simple as calling wandb.watch() and passing the network object as the argument. At the end of each epoch, we can log the loss and accuracy values using wandb.log(). This method takes a dictionary, mapping names (string) with the corresponding values, as the argument. Note that this method is called at the end of every epoch. wandb.log({"Epoch": epoch, "Train Loss": loss_train, "Train Acc": acc_train, "Valid Loss": loss_valid, "Valid Acc": acc_valid}) The complete training code is given below. Please note that train and validate are two helper functions that are defined in the Colab Notebook. Now that our model is training, we can view the training graphs in real-time. Before the training starts, the Run Link and Project Link will be printed in the cell output. Click on the Run Link to get redirected to the Run page. There, you can see the live graphs (the graphs will keep updating as the model trains). Please note that the graphs are interactive, we can merge multiple graphs, smoothen them, change the color or legends, and much more. Recall that we are logging the network weight histograms as well. These can be viewed under the histogram section. We can easily compare multiple Runs in the same project using a Parallel Coordinate Chart. It represents the model’s performance, in terms of minimum loss or maximum accuracy, with the neural network’s hyperparameters. This tool proves to be very powerful when dealing with a large number of Runs. It provides a deeper insight into how each hyperparameter affects the model’s performance. We can also go to the project page and compare the accuracy and loss curves of selected or all the Runs within that project. The screenshot below shows one of my projects. Sharing your model’s training graphs with WandB is as simple as sharing the Run Link or Project Link, just make sure that the project is public for others to view. People with the Project Link or Run Link can view the live graphs too. Isn’t that cool! This guide taught us how to use Weights & Biases to monitor our model’s training and also how to share your Runs with others. To explore WandB further, check out the links below.
[ { "code": null, "e": 499, "s": 172, "text": "Logging the loss and accuracy curves has never been an easy job. We often save these values in arrays or lists and then plot them at the end of the training. Sharing these graphs is even harder where sending screenshots of these graphs seems the only choice. In this tutorial, we will address this issue with Weights & Biases." }, { "code": null, "e": 893, "s": 499, "text": "Weights & Biases (WandB) is a python package that allows us to monitor our training in real-time. It can be easily integrated with popular deep learning frameworks like Pytorch, Tensorflow, or Keras. Additionally, it allows us to organize our Runs into Projects where we can easily compare them and identify the best performing model. In this guide, we will learn how to use WandB for logging." }, { "code": null, "e": 1056, "s": 893, "text": "First, let’s create a free WandB account here. WandB provides a 200GB limited storage on the free account, where we can log graphs, images, videos, and much more." }, { "code": null, "e": 1285, "s": 1056, "text": "Running the code snippet below will install WandB to our Colab Notebook instance. After installing and importing WandB, it will prompt us to authenticate the same way as we do when mounting Google Drive to the notebook instance." }, { "code": null, "e": 1643, "s": 1285, "text": "In this tutorial, we will train a Convolutional Neural Network on Fashion MNIST Dataset which is available in PyTorch’s torchvision.datasets. We will split the datasets into batches and shuffle them before feeding them to our Neural Network. For simplicity, we will not use any data augmentation except transforming the images and labels into torch tensors." }, { "code": null, "e": 1986, "s": 1643, "text": "We will use a simple Convolutional Neural Network with 2 Conv layers and 3 Linear layers. In the input Conv layer, we will keep the input channel count as 1 for the neural network to accept grayscale images. Similarly, in the final hidden layer, the output channel count should be 10 for the model to output scores for each of the 10 classes." }, { "code": null, "e": 2126, "s": 1986, "text": "Before training, we must run wandb.init(). This will initialize a new Run in the WandB database. wandb.init() has the following parameters:" }, { "code": null, "e": 2151, "s": 2126, "text": "Name of the Run (string)" }, { "code": null, "e": 2213, "s": 2151, "text": "Name of the Project where this Run should be created (string)" }, { "code": null, "e": 2253, "s": 2213, "text": "Notes about this Run (string)[optional]" }, { "code": null, "e": 2314, "s": 2253, "text": "Tags to associate with this Run (list of strings) [optional]" }, { "code": null, "e": 2368, "s": 2314, "text": "Entity is the username of our WandB account (string)." }, { "code": null, "e": 2613, "s": 2368, "text": "Any hyperparameter that we want to log can be defined as an attribute of wandb.config. Note that wandb.config should be used to log only those values which do not change during training. Here, we have logged the learning rate using this method." }, { "code": null, "e": 2725, "s": 2613, "text": "Logging weight histograms is as simple as calling wandb.watch() and passing the network object as the argument." }, { "code": null, "e": 2972, "s": 2725, "text": "At the end of each epoch, we can log the loss and accuracy values using wandb.log(). This method takes a dictionary, mapping names (string) with the corresponding values, as the argument. Note that this method is called at the end of every epoch." }, { "code": null, "e": 3172, "s": 2972, "text": "wandb.log({\"Epoch\": epoch, \"Train Loss\": loss_train, \"Train Acc\": acc_train, \"Valid Loss\": loss_valid, \"Valid Acc\": acc_valid})" }, { "code": null, "e": 3316, "s": 3172, "text": "The complete training code is given below. Please note that train and validate are two helper functions that are defined in the Colab Notebook." }, { "code": null, "e": 3767, "s": 3316, "text": "Now that our model is training, we can view the training graphs in real-time. Before the training starts, the Run Link and Project Link will be printed in the cell output. Click on the Run Link to get redirected to the Run page. There, you can see the live graphs (the graphs will keep updating as the model trains). Please note that the graphs are interactive, we can merge multiple graphs, smoothen them, change the color or legends, and much more." }, { "code": null, "e": 3882, "s": 3767, "text": "Recall that we are logging the network weight histograms as well. These can be viewed under the histogram section." }, { "code": null, "e": 4271, "s": 3882, "text": "We can easily compare multiple Runs in the same project using a Parallel Coordinate Chart. It represents the model’s performance, in terms of minimum loss or maximum accuracy, with the neural network’s hyperparameters. This tool proves to be very powerful when dealing with a large number of Runs. It provides a deeper insight into how each hyperparameter affects the model’s performance." }, { "code": null, "e": 4443, "s": 4271, "text": "We can also go to the project page and compare the accuracy and loss curves of selected or all the Runs within that project. The screenshot below shows one of my projects." }, { "code": null, "e": 4695, "s": 4443, "text": "Sharing your model’s training graphs with WandB is as simple as sharing the Run Link or Project Link, just make sure that the project is public for others to view. People with the Project Link or Run Link can view the live graphs too. Isn’t that cool!" }, { "code": null, "e": 4821, "s": 4695, "text": "This guide taught us how to use Weights & Biases to monitor our model’s training and also how to share your Runs with others." } ]
How can we create multiple MySQL triggers for the same trigger event and action time?
MySQL 5.7.2+ allows us to create multiple triggers for the same event and action time in a table. Both the triggers will activate sequentially when the event occurs. It can be understood with the help of an example − In this example, we are creating multiple triggers for the same event say BEFORE UPDATE. The names of the triggers are ‘Studentdetail_before_update’ and ‘Studentdetail_before_update2’. They will activate sequentially when an event occurs. We are creating these triggers on the table ‘Student_detail’ having the following data − mysql> Select * from Student_detail; +-----------+-------------+------------+ | Studentid | StudentName | address | +-----------+-------------+------------+ | 100 | Gaurav | Delhi | | 101 | Raman | Shimla | | 103 | Rahul | Jaipur | | 104 | Ram | Chandigarh | | 105 | Mohan | Chandigarh | +-----------+-------------+------------+ 5 rows in set (0.06 sec) mysql> Delimiter // Now with the help of the following query, we will create the first trigger, which will be created by the same query as earlier. mysql> Create Trigger studentdetail_before_update -> BEFORE UPDATE -> ON Student_detail -> FOR EACH ROW -> BEGIN -> DECLARE AUSER Varchar(40); -> SELECT USER() into AUSER; ->INSERT INTO Student_detail_updated(studentid, Updated_date,Updated_by) values(OLD.studentid,NOW(),AUSER); -> END; // Query OK, 0 rows affected (0.17 sec) mysql> Update student_detail SET Address = 'Ludhiana' Where studentName = 'Ram'; Query OK, 1 row affected (0.15 sec) Rows matched: 1 Changed: 1 Warnings: 0 After invoking the above-created trigger we got the following result − mysql> Select * from student_detail_updated; +-----------+---------------------+----------------+ | studentid | Updated_date | Updated_by | +-----------+---------------------+----------------+ | 104 | 2017-11-22 16:17:16 | root@localhost | +-----------+---------------------+----------------+ 1 row in set (0.00 sec) Now, the second trigger of the same event and action time can be created as follows − mysql> Create Trigger studentdetail_before_update2 -> BEFORE UPDATE -> ON Student_detail -> FOR EACH ROW FOLLOWS studentdetail_before_update -> BEGIN -> DECLARE AUSER Varchar(40); -> SELECT USER() into AUSER; -> INSERT INTO Student_detail_updated(studentid, Updated_date,Updated_by) values(OLD.studentid,NOW(),AUSER); -> END; // Query OK, 0 rows affected (0.15 sec) The above trigger will activate after the first trigger because we are using the keyword ‘FOLLOWS’. mysql> Update Student_detail SET Address = 'Patiala' WHERE studentname = 'Mohan'; Query OK, 1 row affected (0.08 sec) Rows matched: 1 Changed: 1 Warnings: 0 Now, when we update the value, the following result set is showing two rows for the same event and action time. Second row represents the value after studentdetail_before_update trigger and third row represents the value after studentdetail_before_update2 trigger. mysql> Select * from student_detail_updated; +-----------+---------------------+----------------+ | studentid | Updated_date | Updated_by | +-----------+---------------------+----------------+ | 104 | 2017-11-22 16:17:16 | root@localhost | | 105 | 2017-11-22 16:19:28 | root@localhost | | 105 | 2017-11-22 16:19:28 | root@localhost | +-----------+---------------------+----------------+ 3 rows in set (0.00 sec)
[ { "code": null, "e": 1279, "s": 1062, "text": "MySQL 5.7.2+ allows us to create multiple triggers for the same event and action time in a table. Both the triggers will activate sequentially when the event occurs. It can be understood with the help of an example −" }, { "code": null, "e": 1607, "s": 1279, "text": "In this example, we are creating multiple triggers for the same event say BEFORE UPDATE. The names of the triggers are ‘Studentdetail_before_update’ and ‘Studentdetail_before_update2’. They will activate sequentially when an event occurs. We are creating these triggers on the table ‘Student_detail’ having the following data −" }, { "code": null, "e": 2059, "s": 1607, "text": "mysql> Select * from Student_detail;\n+-----------+-------------+------------+\n| Studentid | StudentName | address |\n+-----------+-------------+------------+\n| 100 | Gaurav | Delhi |\n| 101 | Raman | Shimla |\n| 103 | Rahul | Jaipur |\n| 104 | Ram | Chandigarh |\n| 105 | Mohan | Chandigarh |\n+-----------+-------------+------------+\n5 rows in set (0.06 sec)\n\nmysql> Delimiter //" }, { "code": null, "e": 2187, "s": 2059, "text": "Now with the help of the following query, we will create the first trigger, which will be created by the same query as earlier." }, { "code": null, "e": 2704, "s": 2187, "text": "mysql> Create Trigger studentdetail_before_update\n -> BEFORE UPDATE\n -> ON Student_detail\n -> FOR EACH ROW\n -> BEGIN\n -> DECLARE AUSER Varchar(40);\n -> SELECT USER() into AUSER;\n ->INSERT INTO Student_detail_updated(studentid, Updated_date,Updated_by) values(OLD.studentid,NOW(),AUSER);\n -> END; //\nQuery OK, 0 rows affected (0.17 sec)\n\nmysql> Update student_detail SET Address = 'Ludhiana' Where studentName = 'Ram';\nQuery OK, 1 row affected (0.15 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 2775, "s": 2704, "text": "After invoking the above-created trigger we got the following result −" }, { "code": null, "e": 3109, "s": 2775, "text": "mysql> Select * from student_detail_updated;\n+-----------+---------------------+----------------+\n| studentid | Updated_date | Updated_by |\n+-----------+---------------------+----------------+\n| 104 | 2017-11-22 16:17:16 | root@localhost |\n+-----------+---------------------+----------------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 3195, "s": 3109, "text": "Now, the second trigger of the same event and action time can be created as follows −" }, { "code": null, "e": 3593, "s": 3195, "text": "mysql> Create Trigger studentdetail_before_update2\n -> BEFORE UPDATE\n -> ON Student_detail\n -> FOR EACH ROW FOLLOWS studentdetail_before_update\n -> BEGIN\n -> DECLARE AUSER Varchar(40);\n -> SELECT USER() into AUSER;\n -> INSERT INTO Student_detail_updated(studentid, Updated_date,Updated_by) values(OLD.studentid,NOW(),AUSER);\n -> END; //\nQuery OK, 0 rows affected (0.15 sec)" }, { "code": null, "e": 3693, "s": 3593, "text": "The above trigger will activate after the first trigger because we are using the keyword ‘FOLLOWS’." }, { "code": null, "e": 3850, "s": 3693, "text": "mysql> Update Student_detail SET Address = 'Patiala' WHERE studentname = 'Mohan';\nQuery OK, 1 row affected (0.08 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 4115, "s": 3850, "text": "Now, when we update the value, the following result set is showing two rows for the same event and action time. Second row represents the value after studentdetail_before_update trigger and third row represents the value after studentdetail_before_update2 trigger." }, { "code": null, "e": 4556, "s": 4115, "text": "mysql> Select * from student_detail_updated;\n+-----------+---------------------+----------------+\n| studentid | Updated_date | Updated_by |\n+-----------+---------------------+----------------+\n| 104 | 2017-11-22 16:17:16 | root@localhost |\n| 105 | 2017-11-22 16:19:28 | root@localhost |\n| 105 | 2017-11-22 16:19:28 | root@localhost |\n+-----------+---------------------+----------------+\n3 rows in set (0.00 sec)" } ]
Build a useful ML Model in hours on GCP to Predict The Beatles’ listeners | by Brian Ray | Towards Data Science
AutoML “Automated Machine Learning” is under fire lately by the Data Science Community. I had some criticism published in on Google Cloud ML Google Cloud’s AutoML first look (the Google AutoML Team did answer some of my requests, see **new** things at the end of this article) This post will show it is completely reasonable for a Citizen Data Scientists to handle the whole Machine Learning life cycle under ML. The goals are: Solve a real business problem Host the data in GCP Use GCP’s Cloud AutoML Conduct some EDA “Exploratory Data Analysis” How the EDA impacts the results Data Processing on GCP AutoML Tables Taking advantage of the built in Data Pipeline Validation of the model using a holdout Putting the model in production Improving the model over time **new** things in AutoML Tables just released from Google Start your timer, ready, set, go.... The goal is to determine if a listener of music based on their listening patterns would they likely listen to The Beatles; we will build a Recommendation system. Wouldn’t John Lennon be impressed with the power of AI?! Certainly you would not want to recommend The Beatle so someone would not likely listen to the Beatles. Who wouldn’t love The Beatles? Regardless, this model would work with any artists where you have enough data on listening patterns. You simple switch out the Target variable and away you go. The data source is Music listening histories of ListenBrainz users. We pick the top top 300 most popular artists by number of listens. The data is available thanks to BigQuery’s 1TB/mo of free tier processing. The Code for creating the data set is available here on my github. If you are impatient and you just want to download the data here (2.19 MB). I already posted more detail on how to get started with GCP Cloud AutoML tables in Google Cloud’s AutoML first look From Cloud AutoML we can investigate the data in greater depth. This is nowhere close to the level of detail you could do as a Data Scientists working on AI Platform. Nonetheless, there are some worthwhile observations here. For example, the most listened to artists are those with the fewest Nulls. What do we do with Nulls in this case: we leave them empty. The reason why is that Null really does mean no-listens in our data set; hence same as zero. A median value here would be a mistake. Know thy Data! We need to remove “The Beatles” Column as our target is based directly on this. Otherwise, we would get a 100% accurate model always, duh. The huge advantage is you an pipeline the building of the model without a lot of code. In fact, you can write your entire training code using the Client libraries that support multiple languages including Python. We use the Automatic Data Split feature in AutoML. They say: The way your dataset is split between training, validation, and test subsets. By default, AutoML Tables randomly select 80% of your data rows for training, 10% for testing, and 10% for validation. The model worked very well! We saw a .937 AUC ROC. And here is the confusion matrix with 50% score threshold: Is it this easy: There is a cost. If I will host this particular model it will cost $.126 per hour, or $91.98/month (multiplier 730 hours in a month assumed). Here is the equation I used: $0.005 * 2.8 * 9 = $.126. The $0.005 is the number of machines (they use 9 for low latency and I believe it is hard coded). 2.8 is because my model is 2.8G in size. import jsonfrom google.cloud import automl_v1beta1 as automlproject_id = 'mwpmltr'compute_region = 'us-central1'model_display_name = 'beatles_machine_l_20191104025339'input = ['usr', 5.0, None, None, 10, ... ] # list of valuesclient = automl.TablesClient(project=project_id, region=compute_region)response = client.predict( model_display_name=model_display_name, inputs=inputs)response###############################################################payload { tables { score: 0.9896599650382996 value { string_value: "True" } }}payload { tables { score: 0.010340098291635513 value { string_value: "False" } }} By finding patterns in recommendations by using a tagging system we saw a 3.5% increase in overall accuracy. The “Trick” is the correction of bad records (improving ground truth data) and the introduction of new data. This new data in this case is the “tag” applied to the music by experts. Those tags are very predictive. For example the tag “60s” and “british_invasion” are highly predictive. On the flip side, as with all machine-learning it can be predictive what tag the artist does NOT belong too; for example those who have a high level of plays that are tagged as “electronica” they are much less likely to listen to the Beatles. Here are 3 of the meaningful new features Google has added to AutoML Tables: You can see what final model architecture was trained as well as the experiments attempted in each training round. You can see what final model architecture was trained as well as the experiments attempted in each training round. The details are stored in Stackdriver. I haven’t looked closely at these logs. At this time, I do not know if the logs contain all the information needed to recreate the models. 2) you can get prediction-level feature attributions on the online prediction. TypeError: list_models() got an unexpected keyword argument 'feature_importance' I will probably need to update my packages. 3) you can export your model container (now available for everyone) Embarking on the AutoML journey is not as scary as I once thought. The Data Scientist complained that the black-box nature of the AutoML is slowly being opened. The ease of use is increasing. The bugs and other issues seem to be getting resolved. I cautiously recommend folks start putting their eyes on AutoML as a jump starter. This does not relieve the need for Data Modeling outside of what it provides for Data Science. It does not alleviate the need for data handling and EDA outside of the toolset (for this take a look at AI Platform Notebooks!). Likewise it does not mean that Business Analyst type which these tools target do not still need a good understanding of predictive modeling theories, terms, and best practices.
[ { "code": null, "e": 474, "s": 46, "text": "AutoML “Automated Machine Learning” is under fire lately by the Data Science Community. I had some criticism published in on Google Cloud ML Google Cloud’s AutoML first look (the Google AutoML Team did answer some of my requests, see **new** things at the end of this article) This post will show it is completely reasonable for a Citizen Data Scientists to handle the whole Machine Learning life cycle under ML. The goals are:" }, { "code": null, "e": 504, "s": 474, "text": "Solve a real business problem" }, { "code": null, "e": 525, "s": 504, "text": "Host the data in GCP" }, { "code": null, "e": 548, "s": 525, "text": "Use GCP’s Cloud AutoML" }, { "code": null, "e": 593, "s": 548, "text": "Conduct some EDA “Exploratory Data Analysis”" }, { "code": null, "e": 625, "s": 593, "text": "How the EDA impacts the results" }, { "code": null, "e": 662, "s": 625, "text": "Data Processing on GCP AutoML Tables" }, { "code": null, "e": 709, "s": 662, "text": "Taking advantage of the built in Data Pipeline" }, { "code": null, "e": 749, "s": 709, "text": "Validation of the model using a holdout" }, { "code": null, "e": 781, "s": 749, "text": "Putting the model in production" }, { "code": null, "e": 811, "s": 781, "text": "Improving the model over time" }, { "code": null, "e": 869, "s": 811, "text": "**new** things in AutoML Tables just released from Google" }, { "code": null, "e": 906, "s": 869, "text": "Start your timer, ready, set, go...." }, { "code": null, "e": 1125, "s": 906, "text": "The goal is to determine if a listener of music based on their listening patterns would they likely listen to The Beatles; we will build a Recommendation system. Wouldn’t John Lennon be impressed with the power of AI?!" }, { "code": null, "e": 1420, "s": 1125, "text": "Certainly you would not want to recommend The Beatle so someone would not likely listen to the Beatles. Who wouldn’t love The Beatles? Regardless, this model would work with any artists where you have enough data on listening patterns. You simple switch out the Target variable and away you go." }, { "code": null, "e": 1488, "s": 1420, "text": "The data source is Music listening histories of ListenBrainz users." }, { "code": null, "e": 1630, "s": 1488, "text": "We pick the top top 300 most popular artists by number of listens. The data is available thanks to BigQuery’s 1TB/mo of free tier processing." }, { "code": null, "e": 1773, "s": 1630, "text": "The Code for creating the data set is available here on my github. If you are impatient and you just want to download the data here (2.19 MB)." }, { "code": null, "e": 1889, "s": 1773, "text": "I already posted more detail on how to get started with GCP Cloud AutoML tables in Google Cloud’s AutoML first look" }, { "code": null, "e": 2189, "s": 1889, "text": "From Cloud AutoML we can investigate the data in greater depth. This is nowhere close to the level of detail you could do as a Data Scientists working on AI Platform. Nonetheless, there are some worthwhile observations here. For example, the most listened to artists are those with the fewest Nulls." }, { "code": null, "e": 2397, "s": 2189, "text": "What do we do with Nulls in this case: we leave them empty. The reason why is that Null really does mean no-listens in our data set; hence same as zero. A median value here would be a mistake. Know thy Data!" }, { "code": null, "e": 2536, "s": 2397, "text": "We need to remove “The Beatles” Column as our target is based directly on this. Otherwise, we would get a 100% accurate model always, duh." }, { "code": null, "e": 2749, "s": 2536, "text": "The huge advantage is you an pipeline the building of the model without a lot of code. In fact, you can write your entire training code using the Client libraries that support multiple languages including Python." }, { "code": null, "e": 2810, "s": 2749, "text": "We use the Automatic Data Split feature in AutoML. They say:" }, { "code": null, "e": 3007, "s": 2810, "text": "The way your dataset is split between training, validation, and test subsets. By default, AutoML Tables randomly select 80% of your data rows for training, 10% for testing, and 10% for validation." }, { "code": null, "e": 3058, "s": 3007, "text": "The model worked very well! We saw a .937 AUC ROC." }, { "code": null, "e": 3117, "s": 3058, "text": "And here is the confusion matrix with 50% score threshold:" }, { "code": null, "e": 3134, "s": 3117, "text": "Is it this easy:" }, { "code": null, "e": 3276, "s": 3134, "text": "There is a cost. If I will host this particular model it will cost $.126 per hour, or $91.98/month (multiplier 730 hours in a month assumed)." }, { "code": null, "e": 3470, "s": 3276, "text": "Here is the equation I used: $0.005 * 2.8 * 9 = $.126. The $0.005 is the number of machines (they use 9 for low latency and I believe it is hard coded). 2.8 is because my model is 2.8G in size." }, { "code": null, "e": 4116, "s": 3470, "text": "import jsonfrom google.cloud import automl_v1beta1 as automlproject_id = 'mwpmltr'compute_region = 'us-central1'model_display_name = 'beatles_machine_l_20191104025339'input = ['usr', 5.0, None, None, 10, ... ] # list of valuesclient = automl.TablesClient(project=project_id, region=compute_region)response = client.predict( model_display_name=model_display_name, inputs=inputs)response###############################################################payload { tables { score: 0.9896599650382996 value { string_value: \"True\" } }}payload { tables { score: 0.010340098291635513 value { string_value: \"False\" } }}" }, { "code": null, "e": 4225, "s": 4116, "text": "By finding patterns in recommendations by using a tagging system we saw a 3.5% increase in overall accuracy." }, { "code": null, "e": 4334, "s": 4225, "text": "The “Trick” is the correction of bad records (improving ground truth data) and the introduction of new data." }, { "code": null, "e": 4754, "s": 4334, "text": "This new data in this case is the “tag” applied to the music by experts. Those tags are very predictive. For example the tag “60s” and “british_invasion” are highly predictive. On the flip side, as with all machine-learning it can be predictive what tag the artist does NOT belong too; for example those who have a high level of plays that are tagged as “electronica” they are much less likely to listen to the Beatles." }, { "code": null, "e": 4831, "s": 4754, "text": "Here are 3 of the meaningful new features Google has added to AutoML Tables:" }, { "code": null, "e": 4946, "s": 4831, "text": "You can see what final model architecture was trained as well as the experiments attempted in each training round." }, { "code": null, "e": 5061, "s": 4946, "text": "You can see what final model architecture was trained as well as the experiments attempted in each training round." }, { "code": null, "e": 5100, "s": 5061, "text": "The details are stored in Stackdriver." }, { "code": null, "e": 5239, "s": 5100, "text": "I haven’t looked closely at these logs. At this time, I do not know if the logs contain all the information needed to recreate the models." }, { "code": null, "e": 5318, "s": 5239, "text": "2) you can get prediction-level feature attributions on the online prediction." }, { "code": null, "e": 5399, "s": 5318, "text": "TypeError: list_models() got an unexpected keyword argument 'feature_importance'" }, { "code": null, "e": 5443, "s": 5399, "text": "I will probably need to update my packages." }, { "code": null, "e": 5511, "s": 5443, "text": "3) you can export your model container (now available for everyone)" }, { "code": null, "e": 5758, "s": 5511, "text": "Embarking on the AutoML journey is not as scary as I once thought. The Data Scientist complained that the black-box nature of the AutoML is slowly being opened. The ease of use is increasing. The bugs and other issues seem to be getting resolved." } ]
Rotate Array | Practice | GeeksforGeeks
Given an unsorted array arr[] of size N, rotate it by D elements (Anti - clockwise). Input: The first line of the input contains T denoting the number of testcases. First line of each test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation. Subsequent line will be the N space separated array elements. Output: For each testcase, in a new line, output the rotated array. Constraints: 1 <= T <= 200 1 <= N <= 107 1 <= D <= N 0 <= arr[i] <= 105 Example: Input: 2 5 2 1 2 3 4 5 10 3 2 4 6 8 10 12 14 16 18 20 Output: 3 4 5 1 2 8 10 12 14 16 18 20 2 4 6 Explanation : Testcase 1: 1 2 3 4 5 when rotated by 2 elements, it becomes 3 4 5 1 2. 0 manishkumar8969012 weeks ago #include <iostream>#include<bits/stdc++.h>using namespace std; void rotation(int nums[],int D,int N){ int arr[N]; for(int i=0;i<N;i++) { arr[i]=nums[i]; } for(int i=0;i<N;i++) { nums[(i-D+N)%N]=arr[i]; } for(int x=0;x<N;x++) { cout<<nums[x]<<" "; }}int main() {int T;cin>>T;for(int i=0;i<T;i++){ int N,D;cin>>N>>D;int nums[N];for(int i=0;i<N;i++){ cin>>nums[i];}rotation(nums,D,N);cout<<"\n"; }return 0;} 0 geeky_kuldeep1 month ago JS Solution function rotate(arr, n, d) { let res = []; for (let i = d; i < n; i++) { res.push(arr[i]); } for (let i = 0; i < d; i++) { res.push(arr[i]); } return res; } 0 ashutosh0366tripathi1 month ago a=int(input())for i in range(a): n,s1=map(int,input().split()) arr=list(map(int,input().split())) for i in range(s1): temp=arr[0] for j in range(len(arr)-1): arr[j]=arr[j+1] arr[len(arr)-1]=temp print(" ".join(list(map(str,arr)))) 0 shantanupatil9582 months ago class GFG {public static void main (String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i = 0; i < t; i++){ int n = sc.nextInt(); int d = sc.nextInt(); int[] arr = new int[n]; for(int index = 0; index < n; index++){ arr[index] = sc.nextInt(); } for(int index2 = d; index2 < arr.length; index2++ ){ System.out.print(arr[index2] + " "); } for(int index3 = 0; index3 < d; index3++){ System.out.print(arr[index3]+ " "); } System.out.println(" "); } }} -1 ssatyamlal2 months ago //JAVA CODE import java.util.*;import java.lang.*;import java.io.*;class GFG{public static void main (String[] args) { Scanner user = new Scanner(System.in); int t = user.nextInt(); while(t > 0){ int n = user.nextInt(); int rotation = user.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++){ arr[i] = user.nextInt(); } for(int i = rotation; i < n; i++){ System.out.print(arr[i] + " "); } for(int i = 0; i < rotation; i++){ System.out.print(arr[i] + " "); } System.out.println(); t--; } }} 0 ramdurgasais2 months ago In Python for _ in range(int(input())): n, d = list(map(int,input().split(" "))) elements = list(map(int,input().split())) print(" ".join(list(map(str,elements[d:] + elements[:d])))) 0 ramdurgasais2 months ago #In Python for _ in range(int(input())): n, d = list(map(int,input().split(" "))) elements = list(map(int,input().split())) print(" ".join(list(map(str,elements[d:] + elements[:d])))) 0 ayazmrz982 months ago public static void main (String[] args) { Scanner scanner = new Scanner(System.in); int testcases= scanner.nextInt(); while(testcases-- >0) { int size = scanner.nextInt(); int rotatingindex = scanner.nextInt(); int[] array = new int[size]; for(int i=0;i<size;i++) { array[i]=scanner.nextInt(); } for(int i=rotatingindex;i<size;i++) { System.out.print(array[i]+" "); } for(int i=0;i<rotatingindex;i++) { System.out.print(array[i]+" "); } System.out.println(); } } 0 muskang87012 months ago Java Code- class GFG { public static void main (String[] args) { //code Scanner sc = new Scanner(System.in); int t = sc.nextInt(); while(t-- > 0) { int n = sc.nextInt(); int d = sc.nextInt(); int a[] = new int[n]; ArrayList<Integer> b = new ArrayList<>(); for(int i = 0; i < n; i++) { a[i] = sc.nextInt(); } for(int i = 0; i < n; i++) { if((i+d) == n) break; b.add(a[i+d]); } for(int i = 0; i < n-(n-d); i++) { b.add(a[i]); } for(int i = 0; i < b.size(); i++) { System.out.print(b.get(i) + " "); } System.out.println(); } } } +1 codewithaddy2 months ago C++ Solution (Basic) #include <iostream>using namespace std; void rotate(int a[], int n, int r){ int b[r]; for(int i=0; i<r; i++){ b[i]=a[i]; } for(int i=0; i<n-r; i++){ a[i]=a[i+r]; } for(int i=0; i<n-r; i++){ cout<<a[i]<<" "; } for(int i=0; i<r; i++){ cout<<b[i]<<" "; } } int main() {int t;cin>>t;while(t--){ int n,r; cin>>n>>r; int a[n]; for(int i=0; i<n; i++){ cin>>a[i]; } rotate(a,n,r); cout<<endl;}return 0;} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 324, "s": 238, "text": "Given an unsorted array arr[] of size N, rotate it by D elements (Anti - clockwise). " }, { "code": null, "e": 626, "s": 324, "text": "Input:\nThe first line of the input contains T denoting the number of testcases. First line of each test case contains two space separated elements, N denoting the size of the array and an integer D denoting the number size of the rotation. Subsequent line will be the N space separated array elements." }, { "code": null, "e": 695, "s": 626, "text": "Output: \nFor each testcase, in a new line, output the rotated array." }, { "code": null, "e": 767, "s": 695, "text": "Constraints:\n1 <= T <= 200\n1 <= N <= 107\n1 <= D <= N\n0 <= arr[i] <= 105" }, { "code": null, "e": 831, "s": 767, "text": "Example:\nInput:\n2\n5 2\n1 2 3 4 5 \n10 3\n2 4 6 8 10 12 14 16 18 20" }, { "code": null, "e": 875, "s": 831, "text": "Output:\n3 4 5 1 2\n8 10 12 14 16 18 20 2 4 6" }, { "code": null, "e": 964, "s": 875, "text": "Explanation :\nTestcase 1: 1 2 3 4 5 when rotated by 2 elements, it becomes 3 4 5 1 2.\n " }, { "code": null, "e": 966, "s": 964, "text": "0" }, { "code": null, "e": 995, "s": 966, "text": "manishkumar8969012 weeks ago" }, { "code": null, "e": 1058, "s": 995, "text": "#include <iostream>#include<bits/stdc++.h>using namespace std;" }, { "code": null, "e": 1475, "s": 1058, "text": "void rotation(int nums[],int D,int N){ int arr[N]; for(int i=0;i<N;i++) { arr[i]=nums[i]; } for(int i=0;i<N;i++) { nums[(i-D+N)%N]=arr[i]; } for(int x=0;x<N;x++) { cout<<nums[x]<<\" \"; }}int main() {int T;cin>>T;for(int i=0;i<T;i++){ int N,D;cin>>N>>D;int nums[N];for(int i=0;i<N;i++){ cin>>nums[i];}rotation(nums,D,N);cout<<\"\\n\"; }return 0;}" }, { "code": null, "e": 1477, "s": 1475, "text": "0" }, { "code": null, "e": 1502, "s": 1477, "text": "geeky_kuldeep1 month ago" }, { "code": null, "e": 1704, "s": 1502, "text": "JS Solution\n\nfunction rotate(arr, n, d) {\n let res = [];\n for (let i = d; i < n; i++) {\n res.push(arr[i]);\n }\n for (let i = 0; i < d; i++) {\n res.push(arr[i]);\n }\n return res;\n}" }, { "code": null, "e": 1706, "s": 1704, "text": "0" }, { "code": null, "e": 1738, "s": 1706, "text": "ashutosh0366tripathi1 month ago" }, { "code": null, "e": 2032, "s": 1738, "text": "a=int(input())for i in range(a): n,s1=map(int,input().split()) arr=list(map(int,input().split())) for i in range(s1): temp=arr[0] for j in range(len(arr)-1): arr[j]=arr[j+1] arr[len(arr)-1]=temp print(\" \".join(list(map(str,arr))))" }, { "code": null, "e": 2034, "s": 2032, "text": "0" }, { "code": null, "e": 2063, "s": 2034, "text": "shantanupatil9582 months ago" }, { "code": null, "e": 2624, "s": 2063, "text": "class GFG {public static void main (String[] args) { Scanner sc = new Scanner(System.in); int t = sc.nextInt(); for(int i = 0; i < t; i++){ int n = sc.nextInt(); int d = sc.nextInt(); int[] arr = new int[n]; for(int index = 0; index < n; index++){ arr[index] = sc.nextInt(); } for(int index2 = d; index2 < arr.length; index2++ ){ System.out.print(arr[index2] + \" \"); } for(int index3 = 0; index3 < d; index3++){ System.out.print(arr[index3]+ \" \"); } System.out.println(\" \"); } }}" }, { "code": null, "e": 2627, "s": 2624, "text": "-1" }, { "code": null, "e": 2650, "s": 2627, "text": "ssatyamlal2 months ago" }, { "code": null, "e": 2662, "s": 2650, "text": "//JAVA CODE" }, { "code": null, "e": 3324, "s": 2664, "text": "import java.util.*;import java.lang.*;import java.io.*;class GFG{public static void main (String[] args) { Scanner user = new Scanner(System.in); int t = user.nextInt(); while(t > 0){ int n = user.nextInt(); int rotation = user.nextInt(); int[] arr = new int[n]; for(int i = 0; i < n; i++){ arr[i] = user.nextInt(); } for(int i = rotation; i < n; i++){ System.out.print(arr[i] + \" \"); } for(int i = 0; i < rotation; i++){ System.out.print(arr[i] + \" \"); } System.out.println(); t--; } }}" }, { "code": null, "e": 3326, "s": 3324, "text": "0" }, { "code": null, "e": 3351, "s": 3326, "text": "ramdurgasais2 months ago" }, { "code": null, "e": 3362, "s": 3351, "text": " In Python" }, { "code": null, "e": 3563, "s": 3362, "text": "\nfor _ in range(int(input())):\n \n n, d = list(map(int,input().split(\" \")))\n \n elements = list(map(int,input().split()))\n \n print(\" \".join(list(map(str,elements[d:] + elements[:d]))))" }, { "code": null, "e": 3565, "s": 3563, "text": "0" }, { "code": null, "e": 3590, "s": 3565, "text": "ramdurgasais2 months ago" }, { "code": null, "e": 3601, "s": 3590, "text": "#In Python" }, { "code": null, "e": 3789, "s": 3601, "text": "for _ in range(int(input())): n, d = list(map(int,input().split(\" \"))) elements = list(map(int,input().split())) print(\" \".join(list(map(str,elements[d:] + elements[:d]))))" }, { "code": null, "e": 3791, "s": 3789, "text": "0" }, { "code": null, "e": 3813, "s": 3791, "text": "ayazmrz982 months ago" }, { "code": null, "e": 4403, "s": 3813, "text": " public static void main (String[] args) {\n Scanner scanner = new Scanner(System.in);\n int testcases= scanner.nextInt();\n while(testcases-- >0)\n {\n int size = scanner.nextInt();\n int rotatingindex = scanner.nextInt();\n int[] array = new int[size];\n for(int i=0;i<size;i++)\n {\n array[i]=scanner.nextInt();\n }\n \n for(int i=rotatingindex;i<size;i++)\n {\n System.out.print(array[i]+\" \");\n }\n \n for(int i=0;i<rotatingindex;i++)\n {\n System.out.print(array[i]+\" \");\n }\n \n System.out.println();\n \n \n }\n}" }, { "code": null, "e": 4405, "s": 4403, "text": "0" }, { "code": null, "e": 4429, "s": 4405, "text": "muskang87012 months ago" }, { "code": null, "e": 4440, "s": 4429, "text": "Java Code-" }, { "code": null, "e": 5081, "s": 4442, "text": "class GFG {\npublic static void main (String[] args) {\n //code\n Scanner sc = new Scanner(System.in);\n int t = sc.nextInt();\n while(t-- > 0) {\n int n = sc.nextInt();\n int d = sc.nextInt();\n int a[] = new int[n];\n ArrayList<Integer> b = new ArrayList<>();\n for(int i = 0; i < n; i++) {\n a[i] = sc.nextInt();\n }\n for(int i = 0; i < n; i++) {\n if((i+d) == n)\n break;\n b.add(a[i+d]);\n }\n for(int i = 0; i < n-(n-d); i++) {\n b.add(a[i]);\n }\n for(int i = 0; i < b.size(); i++) {\n System.out.print(b.get(i) + \" \");\n }\n System.out.println();\n }\n}\n}" }, { "code": null, "e": 5084, "s": 5081, "text": "+1" }, { "code": null, "e": 5109, "s": 5084, "text": "codewithaddy2 months ago" }, { "code": null, "e": 5130, "s": 5109, "text": "C++ Solution (Basic)" }, { "code": null, "e": 5172, "s": 5132, "text": "#include <iostream>using namespace std;" }, { "code": null, "e": 5437, "s": 5172, "text": "void rotate(int a[], int n, int r){ int b[r]; for(int i=0; i<r; i++){ b[i]=a[i]; } for(int i=0; i<n-r; i++){ a[i]=a[i+r]; } for(int i=0; i<n-r; i++){ cout<<a[i]<<\" \"; } for(int i=0; i<r; i++){ cout<<b[i]<<\" \"; } }" }, { "code": null, "e": 5611, "s": 5437, "text": "int main() {int t;cin>>t;while(t--){ int n,r; cin>>n>>r; int a[n]; for(int i=0; i<n; i++){ cin>>a[i]; } rotate(a,n,r); cout<<endl;}return 0;}" }, { "code": null, "e": 5757, "s": 5611, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 5793, "s": 5757, "text": " Login to access your submissions. " }, { "code": null, "e": 5803, "s": 5793, "text": "\nProblem\n" }, { "code": null, "e": 5813, "s": 5803, "text": "\nContest\n" }, { "code": null, "e": 5876, "s": 5813, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 6024, "s": 5876, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 6232, "s": 6024, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 6338, "s": 6232, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
AWS Quicksight - Embedding Dashboard
You can also embed your Quicksight dashboards into external applications/web pages or can control user access using AWS Cognito service. To perform user control, you can create user pool and identity pool in Cognito and assign Embed dashboard policies to identity pool. AWS Cognito is an IAM service which allows administrators to create and manage temporary users to provide access to applications. With the use of identity pool, you can manage permissions on these user pools. Let us see how we can generate secure dashboard URL and perform user control − Create user pool in AWS Cognito and create users. Go to Amazon Cognito → Manage User Pools → Create a User Pool. When user pool is created, next step is to create an identity pool. Go to https://console.aws.amazon.com/cognito/home?region=us-east-1 Click on “Create New Identity Pool”. Enter the appropriate name of an identity pool. Go to the Authentication Providers section and select “Cognito” option. Enter the User Pool ID (your User pool ID) and App Client ID (go to App Clients in user pool and copy id). Next is to click on ‘Create Pool’ and click on ‘Allow’ to create roles of the identity pool in IAM. It will create 2 Cognito roles. Next step is to assign custom policy to identity roles created in the above step − { "Version": "2012-10-17", "Statement": [ { "Action": "quicksight:RegisterUser", "Resource": "*", "Effect": "Allow" }, { "Action": "quicksight:GetDashboardEmbedUrl", "Resource": "*", "Effect": "Allow" }, { "Action": "sts:AssumeRole", "Resource": "*", "Effect": "Allow" } ] } You can pass dashboard Amazon Resource Name (ARN) under quicksight:GetDashboardEmbedUrl” instead of “*” to restrict user to access only one dashboard. Next step is to login to Cognito application with user credentials in user pool. When user logins into application, Cognito generates 3 tokens − IDToken AccessToken Refresh Token To create a temporary IAM user, credentials are as shown below − AWS.config.region = 'us-east-1'; AWS.config.credentials = new AWS.CognitoIdentityCredentials({ IdentityPoolId:"Identity pool ID", Logins: { 'cognito-idp.us-east-1.amazonaws.com/UserPoolID': AccessToken } }); For generating temporary IAM credentials, you need to call sts.assume role method with the below parameters − var params = { RoleArn: "Cognito Identity role arn", RoleSessionName: "Session name" }; sts.assumeRole(params, function (err, data) { if (err) console.log( err, err.stack); // an error occurred else { console.log(data); }) } Next step is to register the user in Quicksight using “quicksight.registerUser” for credentials generated in step 3 with the below parameters − var params = { AwsAccountId: “account id”, Email: 'email', IdentityType: 'IAM' , Namespace: 'default', UserRole: ADMIN | AUTHOR | READER | RESTRICTED_AUTHOR | RESTRICTED_READER, IamArn: 'Cognito Identity role arn', SessionName: 'session name given in the assume role creation', }; quicksight.registerUser(params, function (err, data1) { if (err) console.log("err register user”); // an error occurred else { // console.log("Register User1”); } }) Next is to update AWS configuration for user generated in step 5. AWS.config.update({ accessKeyId: AccessToken, secretAccessKey: SecretAccessKey , sessionToken: SessionToken, "region": Region }); With credentials created in step 5, call the quicksight.getDashboardEmbedUrl with the below parameters to generate URL. var params = { AwsAccountId: "Enter AWS account ID", DashboardId: "Enter dashboard Id", IdentityType: "IAM", ResetDisabled: true, SessionLifetimeInMinutes: between 15 to 600 minutes, UndoRedoDisabled: True | False } quicksight.getDashboardEmbedUrl(params,function (err, data) { if (!err) { console.log(data); } else { console.log(err); } }); You have to call “QuickSightEmbedding.embedDashboard” from your application using the above generated URL. Like Amazon Quicksight, embedded dashboard also supports the following features − Drill-down option Custom actions (link to a new tab) On-screen filters Download to CSV Sorting on visuals Email report opt-in Reset dashboard to defaults option Undo/redo actions on the dashboard 35 Lectures 7.5 hours Mr. Pradeep Kshetrapal 30 Lectures 3.5 hours Priyanka Choudhary 44 Lectures 7.5 hours Eduonix Learning Solutions 51 Lectures 6 hours Manuj Aggarwal 41 Lectures 5 hours AR Shankar 14 Lectures 1 hours Zach Miller Print Add Notes Bookmark this page
[ { "code": null, "e": 2501, "s": 2231, "text": "You can also embed your Quicksight dashboards into external applications/web pages or can control user access using AWS Cognito service. To perform user control, you can create user pool and identity pool in Cognito and assign Embed dashboard policies to identity pool." }, { "code": null, "e": 2710, "s": 2501, "text": "AWS Cognito is an IAM service which allows administrators to create and manage temporary users to provide access to applications. With the use of identity pool, you can manage permissions on these user pools." }, { "code": null, "e": 2789, "s": 2710, "text": "Let us see how we can generate secure dashboard URL and perform user control −" }, { "code": null, "e": 2902, "s": 2789, "text": "Create user pool in AWS Cognito and create users. Go to Amazon Cognito → Manage User Pools → Create a User Pool." }, { "code": null, "e": 3037, "s": 2902, "text": "When user pool is created, next step is to create an identity pool. Go to https://console.aws.amazon.com/cognito/home?region=us-east-1" }, { "code": null, "e": 3074, "s": 3037, "text": "Click on “Create New Identity Pool”." }, { "code": null, "e": 3194, "s": 3074, "text": "Enter the appropriate name of an identity pool. Go to the Authentication Providers section and select “Cognito” option." }, { "code": null, "e": 3301, "s": 3194, "text": "Enter the User Pool ID (your User pool ID) and App Client ID (go to App Clients in user pool and copy id)." }, { "code": null, "e": 3433, "s": 3301, "text": "Next is to click on ‘Create Pool’ and click on ‘Allow’ to create roles of the identity pool in IAM. It will create 2 Cognito roles." }, { "code": null, "e": 3516, "s": 3433, "text": "Next step is to assign custom policy to identity roles created in the above step −" }, { "code": null, "e": 3917, "s": 3516, "text": "{\n \"Version\": \"2012-10-17\",\n \"Statement\": [\n {\n \"Action\": \"quicksight:RegisterUser\",\n \"Resource\": \"*\",\n \"Effect\": \"Allow\"\n },\n {\n \"Action\": \"quicksight:GetDashboardEmbedUrl\",\n \"Resource\": \"*\",\n \"Effect\": \"Allow\"\n },\n {\n \"Action\": \"sts:AssumeRole\",\n \"Resource\": \"*\",\n \"Effect\": \"Allow\"\n }\n ]\n}" }, { "code": null, "e": 4068, "s": 3917, "text": "You can pass dashboard Amazon Resource Name (ARN) under quicksight:GetDashboardEmbedUrl” instead of “*” to restrict user to access only one dashboard." }, { "code": null, "e": 4213, "s": 4068, "text": "Next step is to login to Cognito application with user credentials in user pool. When user logins into application, Cognito generates 3 tokens −" }, { "code": null, "e": 4221, "s": 4213, "text": "IDToken" }, { "code": null, "e": 4233, "s": 4221, "text": "AccessToken" }, { "code": null, "e": 4247, "s": 4233, "text": "Refresh Token" }, { "code": null, "e": 4312, "s": 4247, "text": "To create a temporary IAM user, credentials are as shown below −" }, { "code": null, "e": 4532, "s": 4312, "text": "AWS.config.region = 'us-east-1';\nAWS.config.credentials = new AWS.CognitoIdentityCredentials({\n IdentityPoolId:\"Identity pool ID\", Logins: {\n 'cognito-idp.us-east-1.amazonaws.com/UserPoolID': AccessToken\n }\n});" }, { "code": null, "e": 4642, "s": 4532, "text": "For generating temporary IAM credentials, you need to call sts.assume role method with the below parameters −" }, { "code": null, "e": 4889, "s": 4642, "text": "var params = {\n RoleArn: \"Cognito Identity role arn\", RoleSessionName: \"Session name\"\n};\nsts.assumeRole(params, function (err, data) {\n if (err) console.log( err, err.stack); \n // an error occurred\n else {\n console.log(data);\n })\n}" }, { "code": null, "e": 5033, "s": 4889, "text": "Next step is to register the user in Quicksight using “quicksight.registerUser” for credentials generated in step 3 with the below parameters −" }, { "code": null, "e": 5520, "s": 5033, "text": "var params = {\n AwsAccountId: “account id”,\n Email: 'email',\n IdentityType: 'IAM' ,\n Namespace: 'default',\n UserRole: ADMIN | AUTHOR | READER | RESTRICTED_AUTHOR | RESTRICTED_READER,\n IamArn: 'Cognito Identity role arn',\n SessionName: 'session name given in the assume role creation',\n};\nquicksight.registerUser(params, function (err, data1) {\n if (err) console.log(\"err register user”); \n // an error occurred\n else {\n // console.log(\"Register User1”);\n }\n})" }, { "code": null, "e": 5586, "s": 5520, "text": "Next is to update AWS configuration for user generated in step 5." }, { "code": null, "e": 5728, "s": 5586, "text": "AWS.config.update({\n accessKeyId: AccessToken,\n secretAccessKey: SecretAccessKey ,\n sessionToken: SessionToken,\n \"region\": Region\n});" }, { "code": null, "e": 5848, "s": 5728, "text": "With credentials created in step 5, call the quicksight.getDashboardEmbedUrl with the below parameters to generate URL." }, { "code": null, "e": 6229, "s": 5848, "text": "var params = {\n AwsAccountId: \"Enter AWS account ID\",\n DashboardId: \"Enter dashboard Id\",\n IdentityType: \"IAM\",\n ResetDisabled: true,\n SessionLifetimeInMinutes: between 15 to 600 minutes,\n UndoRedoDisabled: True | False\n}\nquicksight.getDashboardEmbedUrl(params,function (err, data) {\n if (!err) {\n console.log(data);\n } else {\n console.log(err);\n }\n});" }, { "code": null, "e": 6336, "s": 6229, "text": "You have to call “QuickSightEmbedding.embedDashboard” from your application using the above generated URL." }, { "code": null, "e": 6418, "s": 6336, "text": "Like Amazon Quicksight, embedded dashboard also supports the following features −" }, { "code": null, "e": 6436, "s": 6418, "text": "Drill-down option" }, { "code": null, "e": 6471, "s": 6436, "text": "Custom actions (link to a new tab)" }, { "code": null, "e": 6489, "s": 6471, "text": "On-screen filters" }, { "code": null, "e": 6505, "s": 6489, "text": "Download to CSV" }, { "code": null, "e": 6524, "s": 6505, "text": "Sorting on visuals" }, { "code": null, "e": 6544, "s": 6524, "text": "Email report opt-in" }, { "code": null, "e": 6579, "s": 6544, "text": "Reset dashboard to defaults option" }, { "code": null, "e": 6614, "s": 6579, "text": "Undo/redo actions on the dashboard" }, { "code": null, "e": 6649, "s": 6614, "text": "\n 35 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6673, "s": 6649, "text": " Mr. Pradeep Kshetrapal" }, { "code": null, "e": 6708, "s": 6673, "text": "\n 30 Lectures \n 3.5 hours \n" }, { "code": null, "e": 6728, "s": 6708, "text": " Priyanka Choudhary" }, { "code": null, "e": 6763, "s": 6728, "text": "\n 44 Lectures \n 7.5 hours \n" }, { "code": null, "e": 6791, "s": 6763, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 6824, "s": 6791, "text": "\n 51 Lectures \n 6 hours \n" }, { "code": null, "e": 6840, "s": 6824, "text": " Manuj Aggarwal" }, { "code": null, "e": 6873, "s": 6840, "text": "\n 41 Lectures \n 5 hours \n" }, { "code": null, "e": 6885, "s": 6873, "text": " AR Shankar" }, { "code": null, "e": 6918, "s": 6885, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 6931, "s": 6918, "text": " Zach Miller" }, { "code": null, "e": 6938, "s": 6931, "text": " Print" }, { "code": null, "e": 6949, "s": 6938, "text": " Add Notes" } ]
How can we check if a JSON object is empty or not in Java?
A JSON is a lightweight data-interchange format and the format of JSON is a key with value pair. The JSONObject can parse a text from a String to produce a map-like object and supports java.util.Map interface. We can check whether the JSON object is empty or not in the below example import java.util.*; import org.json.*; public class JSONObjectTest { public static void main(String[] args) { JSONObject jsonObj = new JSONObject( "{" + "Name : Jai," + "Age : 25, " + "Salary: 25000.00 " + "}" ); if(jsonObj.isEmpty()) { System.out.println("JSON is empty"); } else { System.out.println("JSON is not empty"); } } } JSON is not empty
[ { "code": null, "e": 1273, "s": 1062, "text": "A JSON is a lightweight data-interchange format and the format of JSON is a key with value pair. The JSONObject can parse a text from a String to produce a map-like object and supports java.util.Map interface. " }, { "code": null, "e": 1347, "s": 1273, "text": "We can check whether the JSON object is empty or not in the below example" }, { "code": null, "e": 1785, "s": 1347, "text": "import java.util.*;\nimport org.json.*;\npublic class JSONObjectTest {\n public static void main(String[] args) {\n JSONObject jsonObj = new JSONObject(\n \"{\" +\n \"Name : Jai,\" +\n \"Age : 25, \" +\n \"Salary: 25000.00 \" +\n \"}\"\n );\n if(jsonObj.isEmpty()) {\n System.out.println(\"JSON is empty\");\n } else {\n System.out.println(\"JSON is not empty\");\n }\n }\n}" }, { "code": null, "e": 1803, "s": 1785, "text": "JSON is not empty" } ]
Can HTML be embedded inside PHP “if” statement?
Yes, HTML can be embedded inside an ‘if’ statement with the help of PHP. Below are a few methods. Using the if condition − <?php if($condition) : ?> <a href="website_name.com">it is displayed iff $condition is met</a> <?php endif; ?> Using the if and else if conditions − <?php if($condition) : ?> <a href=" website_name.com "> it is displayed iff $condition is met </a> <?php elseif($another_condition) : ?> HTML TAG HERE <?php else : ?> HTML TAG HERE <?php endif; ?> Embedding HTML inside PHP − <?php if ( $condition met ) { ?> HTML TAG HERE <?php; } ?>
[ { "code": null, "e": 1160, "s": 1062, "text": "Yes, HTML can be embedded inside an ‘if’ statement with the help of PHP. Below are a few methods." }, { "code": null, "e": 1185, "s": 1160, "text": "Using the if condition −" }, { "code": null, "e": 1299, "s": 1185, "text": "<?php if($condition) : ?>\n <a href=\"website_name.com\">it is displayed iff $condition is met</a>\n<?php endif; ?>" }, { "code": null, "e": 1337, "s": 1299, "text": "Using the if and else if conditions −" }, { "code": null, "e": 1543, "s": 1337, "text": "<?php if($condition) : ?>\n <a href=\" website_name.com \"> it is displayed iff $condition is met </a>\n<?php elseif($another_condition) : ?>\n HTML TAG HERE\n<?php else : ?>\n HTML TAG HERE\n<?php endif; ?>" }, { "code": null, "e": 1571, "s": 1543, "text": "Embedding HTML inside PHP −" }, { "code": null, "e": 1639, "s": 1571, "text": "<?php\n if ( $condition met ) {\n ?> HTML TAG HERE\n<?php;\n}\n?>" } ]
JLabel | Java Swing - GeeksforGeeks
15 Apr, 2021 JLabel is a class of java Swing . JLabel is used to display a short string or an image icon. JLabel can display text, image or both . JLabel is only a display of text or image and it cannot get focus . JLabel is inactive to input events such a mouse focus or keyboard focus. By default labels are vertically centered but the user can change the alignment of label.Constructor of the class are : JLabel() : creates a blank label with no text or image in it.JLabel(String s) : creates a new label with the string specified.JLabel(Icon i) : creates a new label with a image on it.JLabel(String s, Icon i, int align) : creates a new label with a string, an image and a specified horizontal alignment JLabel() : creates a blank label with no text or image in it. JLabel(String s) : creates a new label with the string specified. JLabel(Icon i) : creates a new label with a image on it. JLabel(String s, Icon i, int align) : creates a new label with a string, an image and a specified horizontal alignment Commonly used methods of the class are : getIcon() : returns the image that the label displayssetIcon(Icon i) : sets the icon that the label will display to image igetText() : returns the text that the label will displaysetText(String s) : sets the text that the label will display to string s getIcon() : returns the image that the label displays setIcon(Icon i) : sets the icon that the label will display to image i getText() : returns the text that the label will display setText(String s) : sets the text that the label will display to string s 1. Program to create a blank label and add text to it. Java // Java Program to create a// blank label and add text to it.import java.awt.event.*;import java.awt.*;import javax.swing.*;class text extends JFrame { // frame static JFrame f; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame("label"); // create a label to display text l = new JLabel(); // add text to label l.setText("label text"); // create a panel JPanel p = new JPanel(); // add label to panel p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); }} Output : 2. Program to create a new label using constructor – JLabel(String s) Java // Java Program to create a new label// using constructor - JLabel(String s)import java.awt.event.*;import java.awt.*;import javax.swing.*;class text extends JFrame { // frame static JFrame f; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame("label"); // create a label to display text l = new JLabel("new text "); // create a panel JPanel p = new JPanel(); // add label to panel p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); }} Output : 3. Program to create a label and add image to it . Java // Java Program to create a label// and add image to it .import java.awt.event.*;import java.awt.*;import javax.swing.*;class text extends JFrame { // frame static JFrame f; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame("label"); // create a new image icon ImageIcon i = new ImageIcon("f:/image.png"); // create a label to display image l = new JLabel(i); // create a panel JPanel p = new JPanel(); // add label to panel p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(500, 500); f.show(); }} Output : 4. Program to add a image and string to a label Java // Java Program to add a image and string// to a label with horizontal alignmentimport java.awt.event.*;import java.awt.*;import javax.swing.*;class text extends JFrame { // frame static JFrame f; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame("label"); // create a new image icon ImageIcon i = new ImageIcon("f:/image.png"); // create a label to display text and image l = new JLabel("new image text ", i, SwingConstants.HORIZONTAL); // create a panel JPanel p = new JPanel(); // add label to panel p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(600, 500); f.show(); }} Output : Note : This programs might not run in an online compiler please use an offline IDE. nidhi_biet Akanksha_Rai sweetyty java-swing Java Programming Language Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java Modulo Operator (%) in C/C++ with Examples Arrow operator -> in C/C++ with Examples Differences between Procedural and Object Oriented Programming Structures in C++ Top 10 Programming Languages to Learn in 2022
[ { "code": null, "e": 25803, "s": 25775, "text": "\n15 Apr, 2021" }, { "code": null, "e": 26200, "s": 25803, "text": "JLabel is a class of java Swing . JLabel is used to display a short string or an image icon. JLabel can display text, image or both . JLabel is only a display of text or image and it cannot get focus . JLabel is inactive to input events such a mouse focus or keyboard focus. By default labels are vertically centered but the user can change the alignment of label.Constructor of the class are : " }, { "code": null, "e": 26501, "s": 26200, "text": "JLabel() : creates a blank label with no text or image in it.JLabel(String s) : creates a new label with the string specified.JLabel(Icon i) : creates a new label with a image on it.JLabel(String s, Icon i, int align) : creates a new label with a string, an image and a specified horizontal alignment" }, { "code": null, "e": 26563, "s": 26501, "text": "JLabel() : creates a blank label with no text or image in it." }, { "code": null, "e": 26629, "s": 26563, "text": "JLabel(String s) : creates a new label with the string specified." }, { "code": null, "e": 26686, "s": 26629, "text": "JLabel(Icon i) : creates a new label with a image on it." }, { "code": null, "e": 26805, "s": 26686, "text": "JLabel(String s, Icon i, int align) : creates a new label with a string, an image and a specified horizontal alignment" }, { "code": null, "e": 26848, "s": 26805, "text": "Commonly used methods of the class are : " }, { "code": null, "e": 27102, "s": 26848, "text": "getIcon() : returns the image that the label displayssetIcon(Icon i) : sets the icon that the label will display to image igetText() : returns the text that the label will displaysetText(String s) : sets the text that the label will display to string s" }, { "code": null, "e": 27157, "s": 27102, "text": "getIcon() : returns the image that the label displays" }, { "code": null, "e": 27228, "s": 27157, "text": "setIcon(Icon i) : sets the icon that the label will display to image i" }, { "code": null, "e": 27285, "s": 27228, "text": "getText() : returns the text that the label will display" }, { "code": null, "e": 27359, "s": 27285, "text": "setText(String s) : sets the text that the label will display to string s" }, { "code": null, "e": 27416, "s": 27359, "text": "1. Program to create a blank label and add text to it. " }, { "code": null, "e": 27421, "s": 27416, "text": "Java" }, { "code": "// Java Program to create a// blank label and add text to it.import java.awt.event.*;import java.awt.*;import javax.swing.*;class text extends JFrame { // frame static JFrame f; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame(\"label\"); // create a label to display text l = new JLabel(); // add text to label l.setText(\"label text\"); // create a panel JPanel p = new JPanel(); // add label to panel p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); }}", "e": 28224, "s": 27421, "text": null }, { "code": null, "e": 28235, "s": 28224, "text": "Output : " }, { "code": null, "e": 28307, "s": 28235, "text": "2. Program to create a new label using constructor – JLabel(String s) " }, { "code": null, "e": 28312, "s": 28307, "text": "Java" }, { "code": "// Java Program to create a new label// using constructor - JLabel(String s)import java.awt.event.*;import java.awt.*;import javax.swing.*;class text extends JFrame { // frame static JFrame f; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame(\"label\"); // create a label to display text l = new JLabel(\"new text \"); // create a panel JPanel p = new JPanel(); // add label to panel p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(300, 300); f.show(); }}", "e": 29080, "s": 28312, "text": null }, { "code": null, "e": 29091, "s": 29080, "text": "Output : " }, { "code": null, "e": 29143, "s": 29091, "text": "3. Program to create a label and add image to it . " }, { "code": null, "e": 29148, "s": 29143, "text": "Java" }, { "code": "// Java Program to create a label// and add image to it .import java.awt.event.*;import java.awt.*;import javax.swing.*;class text extends JFrame { // frame static JFrame f; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame(\"label\"); // create a new image icon ImageIcon i = new ImageIcon(\"f:/image.png\"); // create a label to display image l = new JLabel(i); // create a panel JPanel p = new JPanel(); // add label to panel p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(500, 500); f.show(); }}", "e": 29976, "s": 29148, "text": null }, { "code": null, "e": 29986, "s": 29976, "text": "Output : " }, { "code": null, "e": 30036, "s": 29986, "text": "4. Program to add a image and string to a label " }, { "code": null, "e": 30041, "s": 30036, "text": "Java" }, { "code": "// Java Program to add a image and string// to a label with horizontal alignmentimport java.awt.event.*;import java.awt.*;import javax.swing.*;class text extends JFrame { // frame static JFrame f; // label to display text static JLabel l; // default constructor text() { } // main class public static void main(String[] args) { // create a new frame to store text field and button f = new JFrame(\"label\"); // create a new image icon ImageIcon i = new ImageIcon(\"f:/image.png\"); // create a label to display text and image l = new JLabel(\"new image text \", i, SwingConstants.HORIZONTAL); // create a panel JPanel p = new JPanel(); // add label to panel p.add(l); // add panel to frame f.add(p); // set the size of frame f.setSize(600, 500); f.show(); }}", "e": 30946, "s": 30041, "text": null }, { "code": null, "e": 30957, "s": 30946, "text": "Output : " }, { "code": null, "e": 31042, "s": 30957, "text": "Note : This programs might not run in an online compiler please use an offline IDE. " }, { "code": null, "e": 31053, "s": 31042, "text": "nidhi_biet" }, { "code": null, "e": 31066, "s": 31053, "text": "Akanksha_Rai" }, { "code": null, "e": 31075, "s": 31066, "text": "sweetyty" }, { "code": null, "e": 31086, "s": 31075, "text": "java-swing" }, { "code": null, "e": 31091, "s": 31086, "text": "Java" }, { "code": null, "e": 31112, "s": 31091, "text": "Programming Language" }, { "code": null, "e": 31117, "s": 31112, "text": "Java" }, { "code": null, "e": 31215, "s": 31117, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31266, "s": 31215, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 31296, "s": 31266, "text": "HashMap in Java with Examples" }, { "code": null, "e": 31311, "s": 31296, "text": "Stream In Java" }, { "code": null, "e": 31330, "s": 31311, "text": "Interfaces in Java" }, { "code": null, "e": 31361, "s": 31330, "text": "How to iterate any Map in Java" }, { "code": null, "e": 31404, "s": 31361, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 31445, "s": 31404, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 31508, "s": 31445, "text": "Differences between Procedural and Object Oriented Programming" }, { "code": null, "e": 31526, "s": 31508, "text": "Structures in C++" } ]
Hashtable in Java - GeeksforGeeks
11 May, 2022 The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. Features of Hashtable It is similar to HashMap, but is synchronized. Hashtable stores key/value pair in hash table. In Hashtable we specify an object that is used as a key, and the value we want to associate to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table. The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75. HashMap doesn’t provide any Enumeration, while Hashtable provides not fail-fast Enumeration. Declaration: public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable Type Parameters: K – the type of keys maintained by this map V – the type of mapped values Hashtable implements Serializable, Cloneable, Map<K,V> interfaces and extends Dictionary<K,V>. The direct subclasses are Properties, UIDefaults. In order to create a Hashtable, we need to import it from java.util.Hashtable. There are various ways in which we can create a Hashtable. 1. Hashtable(): This creates an empty hashtable with the default load factor of 0.75 and an initial capacity is 11. Hashtable<K, V> ht = new Hashtable<K, V>(); Java // Java program to demonstrate// adding elements to Hashtable import java.io.*;import java.util.*; class AddElementsToHashtable { public static void main(String args[]) { // No need to mention the // Generic type twice Hashtable<Integer, String> ht1 = new Hashtable<>(); // Initialization of a Hashtable // using Generics Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>(); // Inserting the Elements // using put() method ht1.put(1, "one"); ht1.put(2, "two"); ht1.put(3, "three"); ht2.put(4, "four"); ht2.put(5, "five"); ht2.put(6, "six"); // Print mappings to the console System.out.println("Mappings of ht1 : " + ht1); System.out.println("Mappings of ht2 : " + ht2); }} Mappings of ht1 : {3=three, 2=two, 1=one} Mappings of ht2 : {6=six, 5=five, 4=four} 2. Hashtable(int initialCapacity): This creates a hash table that has an initial size specified by initialCapacity and the default load factor is 0.75. Hashtable<K, V> ht = new Hashtable<K, V>(int initialCapacity); Java // Java program to demonstrate// adding elements to Hashtable import java.io.*;import java.util.*; class AddElementsToHashtable { public static void main(String args[]) { // No need to mention the // Generic type twice Hashtable<Integer, String> ht1 = new Hashtable<>(4); // Initialization of a Hashtable // using Generics Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>(2); // Inserting the Elements // using put() method ht1.put(1, "one"); ht1.put(2, "two"); ht1.put(3, "three"); ht2.put(4, "four"); ht2.put(5, "five"); ht2.put(6, "six"); // Print mappings to the console System.out.println("Mappings of ht1 : " + ht1); System.out.println("Mappings of ht2 : " + ht2); }} Mappings of ht1 : {3=three, 2=two, 1=one} Mappings of ht2 : {4=four, 6=six, 5=five} 3. Hashtable(int size, float fillRatio): This version creates a hash table that has an initial size specified by size and fill ratio specified by fillRatio. fill ratio: Basically, it determines how full a hash table can be before it is resized upward and its Value lies between 0.0 to 1.0. Hashtable<K, V> ht = new Hashtable<K, V>(int size, float fillRatio); Java // Java program to demonstrate// adding elements to Hashtable import java.io.*;import java.util.*; class AddElementsToHashtable { public static void main(String args[]) { // No need to mention the // Generic type twice Hashtable<Integer, String> ht1 = new Hashtable<>(4, 0.75f); // Initialization of a Hashtable // using Generics Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>(3, 0.5f); // Inserting the Elements // using put() method ht1.put(1, "one"); ht1.put(2, "two"); ht1.put(3, "three"); ht2.put(4, "four"); ht2.put(5, "five"); ht2.put(6, "six"); // Print mappings to the console System.out.println("Mappings of ht1 : " + ht1); System.out.println("Mappings of ht2 : " + ht2); }} Mappings of ht1 : {3=three, 2=two, 1=one} Mappings of ht2 : {6=six, 5=five, 4=four} 4. Hashtable(Map<? extends K,? extends V> m): This creates a hash table that is initialized with the elements in m. Hashtable<K, V> ht = new Hashtable<K, V>(Map m); Java // Java program to demonstrate// adding elements to Hashtable import java.io.*;import java.util.*; class AddElementsToHashtable { public static void main(String args[]) { // No need to mention the // Generic type twice Map<Integer, String> hm = new HashMap<>(); // Inserting the Elements // using put() method hm.put(1, "one"); hm.put(2, "two"); hm.put(3, "three"); // Initialization of a Hashtable // using Generics Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>(hm); // Print mappings to the console System.out.println("Mappings of ht2 : " + ht2); }} Mappings of ht2 : {3=three, 2=two, 1=one} Example: Java // Java program to illustrate// Java.util.Hashtable import java.util.*; public class GFG { public static void main(String[] args) { // Create an empty Hashtable Hashtable<String, Integer> ht = new Hashtable<>(); // Add elements to the hashtable ht.put("vishal", 10); ht.put("sachin", 30); ht.put("vaibhav", 20); // Print size and content System.out.println("Size of map is:- " + ht.size()); System.out.println(ht); // Check if a key is present and if // present, print value if (ht.containsKey("vishal")) { Integer a = ht.get("vishal"); System.out.println("value for key" + " \"vishal\" is:- " + a); } }} Size of map is:- 3 {vaibhav=20, vishal=10, sachin=30} value for key "vishal" is:- 10 1. Adding Elements: In order to add an element to the hashtable, we can use the put() method. However, the insertion order is not retained in the hashtable. Internally, for every element, a separate hash is generated and the elements are indexed based on this hash to make it more efficient. Java // Java program to demonstrate// adding elements to Hashtable import java.io.*;import java.util.*; class AddElementsToHashtable { public static void main(String args[]) { // No need to mention the // Generic type twice Hashtable<Integer, String> ht1 = new Hashtable<>(); // Initialization of a Hashtable // using Generics Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>(); // Inserting the Elements // using put() method ht1.put(1, "Geeks"); ht1.put(2, "For"); ht1.put(3, "Geeks"); ht2.put(1, "Geeks"); ht2.put(2, "For"); ht2.put(3, "Geeks"); // Print mappings to the console System.out.println("Mappings of ht1 : " + ht1); System.out.println("Mappings of ht2 : " + ht2); }} Mappings of ht1 : {3=Geeks, 2=For, 1=Geeks} Mappings of ht2 : {3=Geeks, 2=For, 1=Geeks} 2. Changing Elements: After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the hashtable are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change. Java // Java program to demonstrate// updating Hashtable import java.io.*;import java.util.*;class UpdatesOnHashtable { public static void main(String args[]) { // Initialization of a Hashtable Hashtable<Integer, String> ht = new Hashtable<Integer, String>(); // Inserting the Elements // using put method ht.put(1, "Geeks"); ht.put(2, "Geeks"); ht.put(3, "Geeks"); // print initial map to the console System.out.println("Initial Map " + ht); // Update the value at key 2 ht.put(2, "For"); // print the updated map System.out.println("Updated Map " + ht); }} Initial Map {3=Geeks, 2=Geeks, 1=Geeks} Updated Map {3=Geeks, 2=For, 1=Geeks} 3. Removing Element: In order to remove an element from the Map, we can use the remove() method. This method takes the key value and removes the mapping for a key from this map if it is present in the map. Java // Java program to demonstrate// the removing mappings from Hashtable import java.io.*;import java.util.*;class RemovingMappingsFromHashtable { public static void main(String args[]) { // Initialization of a Hashtable Map<Integer, String> ht = new Hashtable<Integer, String>(); // Inserting the Elements // using put method ht.put(1, "Geeks"); ht.put(2, "For"); ht.put(3, "Geeks"); ht.put(4, "For"); // Initial HashMap System.out.println("Initial map : " + ht); // Remove the map entry with key 4 ht.remove(4); // Final Hashtable System.out.println("Updated map : " + ht); }} Initial map : {4=For, 3=Geeks, 2=For, 1=Geeks} Updated map : {3=Geeks, 2=For, 1=Geeks} 4. Traversal of a Hashtable: To iterate the table, we can make use of an advanced for loop. Below is the example of iterating a hashtable. Java // Java program to illustrate// traversal of Hashtable import java.util.Hashtable;import java.util.Map; public class IteratingHashtable { public static void main(String[] args) { // Create an instance of Hashtable Hashtable<String, Integer> ht = new Hashtable<>(); // Adding elements using put method ht.put("vishal", 10); ht.put("sachin", 30); ht.put("vaibhav", 20); // Iterating using enhanced for loop for (Map.Entry<String, Integer> e : ht.entrySet()) System.out.println(e.getKey() + " " + e.getValue()); }} vaibhav 20 vishal 10 sachin 30 Hashtable datastructure is an array of buckets which stores the key/value pairs in them. It makes use of hashCode() method to determine which bucket the key/value pair should map.The hash function helps to determine the location for a given key in the bucket list. Generally, hashcode is a non-negative integer that is equal for equal Objects and may or may not be equal for unequal Objects. To determine whether two objects are equal or not, hashtable makes use of the equals() method. It is possible that two unequal Objects have the same hashcode. This is called a collision. To resolve collisions, hashtable uses an array of lists. The pairs mapped to a single bucket (array index) are stored in a list and list reference is stored in the array index. K – The type of the keys in the map. V – The type of values mapped in the map. METHOD DESCRIPTION compute(K key, BiFunction<? super K,? super V,? extends V> remappingFunction) computeIfAbsent(K key, Function<? super K,? extends V> mappingFunction) METHOD DESCRIPTION remove​(Object key, Object value) Must Read: Differences between HashMap and HashTable in Java Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Hashtable.html OwiesAAlomari nidhi_biet bishnoisunil007 Ganeshchowdharysadanala HashTable Java - util package Java-Collections Java-HashTable Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Reverse a string in Java Arrays.sort() in Java with examples Stream In Java How to iterate any Map in Java Initialize an ArrayList in Java Singleton Class in Java Initializing a List in Java Different ways of Reading a text file in Java Generics in Java
[ { "code": null, "e": 30197, "s": 30169, "text": "\n11 May, 2022" }, { "code": null, "e": 30471, "s": 30197, "text": "The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a hashtable, the objects used as keys must implement the hashCode method and the equals method. " }, { "code": null, "e": 30493, "s": 30471, "text": "Features of Hashtable" }, { "code": null, "e": 30540, "s": 30493, "text": "It is similar to HashMap, but is synchronized." }, { "code": null, "e": 30587, "s": 30540, "text": "Hashtable stores key/value pair in hash table." }, { "code": null, "e": 30812, "s": 30587, "text": "In Hashtable we specify an object that is used as a key, and the value we want to associate to that key. The key is then hashed, and the resulting hash code is used as the index at which the value is stored within the table." }, { "code": null, "e": 30894, "s": 30812, "text": "The initial default capacity of Hashtable class is 11 whereas loadFactor is 0.75." }, { "code": null, "e": 30987, "s": 30894, "text": "HashMap doesn’t provide any Enumeration, while Hashtable provides not fail-fast Enumeration." }, { "code": null, "e": 31000, "s": 30987, "text": "Declaration:" }, { "code": null, "e": 31097, "s": 31000, "text": "public class Hashtable<K,V> extends Dictionary<K,V> implements Map<K,V>, Cloneable, Serializable" }, { "code": null, "e": 31114, "s": 31097, "text": "Type Parameters:" }, { "code": null, "e": 31158, "s": 31114, "text": "K – the type of keys maintained by this map" }, { "code": null, "e": 31188, "s": 31158, "text": "V – the type of mapped values" }, { "code": null, "e": 31334, "s": 31188, "text": "Hashtable implements Serializable, Cloneable, Map<K,V> interfaces and extends Dictionary<K,V>. The direct subclasses are Properties, UIDefaults. " }, { "code": null, "e": 31472, "s": 31334, "text": "In order to create a Hashtable, we need to import it from java.util.Hashtable. There are various ways in which we can create a Hashtable." }, { "code": null, "e": 31589, "s": 31472, "text": "1. Hashtable(): This creates an empty hashtable with the default load factor of 0.75 and an initial capacity is 11. " }, { "code": null, "e": 31633, "s": 31589, "text": "Hashtable<K, V> ht = new Hashtable<K, V>();" }, { "code": null, "e": 31638, "s": 31633, "text": "Java" }, { "code": "// Java program to demonstrate// adding elements to Hashtable import java.io.*;import java.util.*; class AddElementsToHashtable { public static void main(String args[]) { // No need to mention the // Generic type twice Hashtable<Integer, String> ht1 = new Hashtable<>(); // Initialization of a Hashtable // using Generics Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>(); // Inserting the Elements // using put() method ht1.put(1, \"one\"); ht1.put(2, \"two\"); ht1.put(3, \"three\"); ht2.put(4, \"four\"); ht2.put(5, \"five\"); ht2.put(6, \"six\"); // Print mappings to the console System.out.println(\"Mappings of ht1 : \" + ht1); System.out.println(\"Mappings of ht2 : \" + ht2); }}", "e": 32474, "s": 31638, "text": null }, { "code": null, "e": 32558, "s": 32474, "text": "Mappings of ht1 : {3=three, 2=two, 1=one}\nMappings of ht2 : {6=six, 5=five, 4=four}" }, { "code": null, "e": 32710, "s": 32558, "text": "2. Hashtable(int initialCapacity): This creates a hash table that has an initial size specified by initialCapacity and the default load factor is 0.75." }, { "code": null, "e": 32773, "s": 32710, "text": "Hashtable<K, V> ht = new Hashtable<K, V>(int initialCapacity);" }, { "code": null, "e": 32778, "s": 32773, "text": "Java" }, { "code": "// Java program to demonstrate// adding elements to Hashtable import java.io.*;import java.util.*; class AddElementsToHashtable { public static void main(String args[]) { // No need to mention the // Generic type twice Hashtable<Integer, String> ht1 = new Hashtable<>(4); // Initialization of a Hashtable // using Generics Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>(2); // Inserting the Elements // using put() method ht1.put(1, \"one\"); ht1.put(2, \"two\"); ht1.put(3, \"three\"); ht2.put(4, \"four\"); ht2.put(5, \"five\"); ht2.put(6, \"six\"); // Print mappings to the console System.out.println(\"Mappings of ht1 : \" + ht1); System.out.println(\"Mappings of ht2 : \" + ht2); }}", "e": 33616, "s": 32778, "text": null }, { "code": null, "e": 33700, "s": 33616, "text": "Mappings of ht1 : {3=three, 2=two, 1=one}\nMappings of ht2 : {4=four, 6=six, 5=five}" }, { "code": null, "e": 33990, "s": 33700, "text": "3. Hashtable(int size, float fillRatio): This version creates a hash table that has an initial size specified by size and fill ratio specified by fillRatio. fill ratio: Basically, it determines how full a hash table can be before it is resized upward and its Value lies between 0.0 to 1.0." }, { "code": null, "e": 34059, "s": 33990, "text": "Hashtable<K, V> ht = new Hashtable<K, V>(int size, float fillRatio);" }, { "code": null, "e": 34064, "s": 34059, "text": "Java" }, { "code": "// Java program to demonstrate// adding elements to Hashtable import java.io.*;import java.util.*; class AddElementsToHashtable { public static void main(String args[]) { // No need to mention the // Generic type twice Hashtable<Integer, String> ht1 = new Hashtable<>(4, 0.75f); // Initialization of a Hashtable // using Generics Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>(3, 0.5f); // Inserting the Elements // using put() method ht1.put(1, \"one\"); ht1.put(2, \"two\"); ht1.put(3, \"three\"); ht2.put(4, \"four\"); ht2.put(5, \"five\"); ht2.put(6, \"six\"); // Print mappings to the console System.out.println(\"Mappings of ht1 : \" + ht1); System.out.println(\"Mappings of ht2 : \" + ht2); }}", "e": 34926, "s": 34064, "text": null }, { "code": null, "e": 35010, "s": 34926, "text": "Mappings of ht1 : {3=three, 2=two, 1=one}\nMappings of ht2 : {6=six, 5=five, 4=four}" }, { "code": null, "e": 35126, "s": 35010, "text": "4. Hashtable(Map<? extends K,? extends V> m): This creates a hash table that is initialized with the elements in m." }, { "code": null, "e": 35175, "s": 35126, "text": "Hashtable<K, V> ht = new Hashtable<K, V>(Map m);" }, { "code": null, "e": 35180, "s": 35175, "text": "Java" }, { "code": "// Java program to demonstrate// adding elements to Hashtable import java.io.*;import java.util.*; class AddElementsToHashtable { public static void main(String args[]) { // No need to mention the // Generic type twice Map<Integer, String> hm = new HashMap<>(); // Inserting the Elements // using put() method hm.put(1, \"one\"); hm.put(2, \"two\"); hm.put(3, \"three\"); // Initialization of a Hashtable // using Generics Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>(hm); // Print mappings to the console System.out.println(\"Mappings of ht2 : \" + ht2); }}", "e": 35871, "s": 35180, "text": null }, { "code": null, "e": 35913, "s": 35871, "text": "Mappings of ht2 : {3=three, 2=two, 1=one}" }, { "code": null, "e": 35922, "s": 35913, "text": "Example:" }, { "code": null, "e": 35927, "s": 35922, "text": "Java" }, { "code": "// Java program to illustrate// Java.util.Hashtable import java.util.*; public class GFG { public static void main(String[] args) { // Create an empty Hashtable Hashtable<String, Integer> ht = new Hashtable<>(); // Add elements to the hashtable ht.put(\"vishal\", 10); ht.put(\"sachin\", 30); ht.put(\"vaibhav\", 20); // Print size and content System.out.println(\"Size of map is:- \" + ht.size()); System.out.println(ht); // Check if a key is present and if // present, print value if (ht.containsKey(\"vishal\")) { Integer a = ht.get(\"vishal\"); System.out.println(\"value for key\" + \" \\\"vishal\\\" is:- \" + a); } }}", "e": 36692, "s": 35927, "text": null }, { "code": null, "e": 36780, "s": 36695, "text": "Size of map is:- 3\n{vaibhav=20, vishal=10, sachin=30}\nvalue for key \"vishal\" is:- 10" }, { "code": null, "e": 37094, "s": 36780, "text": "1. Adding Elements: In order to add an element to the hashtable, we can use the put() method. However, the insertion order is not retained in the hashtable. Internally, for every element, a separate hash is generated and the elements are indexed based on this hash to make it more efficient. " }, { "code": null, "e": 37099, "s": 37094, "text": "Java" }, { "code": "// Java program to demonstrate// adding elements to Hashtable import java.io.*;import java.util.*; class AddElementsToHashtable { public static void main(String args[]) { // No need to mention the // Generic type twice Hashtable<Integer, String> ht1 = new Hashtable<>(); // Initialization of a Hashtable // using Generics Hashtable<Integer, String> ht2 = new Hashtable<Integer, String>(); // Inserting the Elements // using put() method ht1.put(1, \"Geeks\"); ht1.put(2, \"For\"); ht1.put(3, \"Geeks\"); ht2.put(1, \"Geeks\"); ht2.put(2, \"For\"); ht2.put(3, \"Geeks\"); // Print mappings to the console System.out.println(\"Mappings of ht1 : \" + ht1); System.out.println(\"Mappings of ht2 : \" + ht2); }}", "e": 37951, "s": 37099, "text": null }, { "code": null, "e": 38041, "s": 37953, "text": "Mappings of ht1 : {3=Geeks, 2=For, 1=Geeks}\nMappings of ht2 : {3=Geeks, 2=For, 1=Geeks}" }, { "code": null, "e": 38368, "s": 38041, "text": "2. Changing Elements: After adding the elements if we wish to change the element, it can be done by again adding the element with the put() method. Since the elements in the hashtable are indexed using the keys, the value of the key can be changed by simply inserting the updated value for the key for which we wish to change." }, { "code": null, "e": 38373, "s": 38368, "text": "Java" }, { "code": "// Java program to demonstrate// updating Hashtable import java.io.*;import java.util.*;class UpdatesOnHashtable { public static void main(String args[]) { // Initialization of a Hashtable Hashtable<Integer, String> ht = new Hashtable<Integer, String>(); // Inserting the Elements // using put method ht.put(1, \"Geeks\"); ht.put(2, \"Geeks\"); ht.put(3, \"Geeks\"); // print initial map to the console System.out.println(\"Initial Map \" + ht); // Update the value at key 2 ht.put(2, \"For\"); // print the updated map System.out.println(\"Updated Map \" + ht); }}", "e": 39081, "s": 38373, "text": null }, { "code": null, "e": 39161, "s": 39083, "text": "Initial Map {3=Geeks, 2=Geeks, 1=Geeks}\nUpdated Map {3=Geeks, 2=For, 1=Geeks}" }, { "code": null, "e": 39367, "s": 39161, "text": "3. Removing Element: In order to remove an element from the Map, we can use the remove() method. This method takes the key value and removes the mapping for a key from this map if it is present in the map." }, { "code": null, "e": 39372, "s": 39367, "text": "Java" }, { "code": "// Java program to demonstrate// the removing mappings from Hashtable import java.io.*;import java.util.*;class RemovingMappingsFromHashtable { public static void main(String args[]) { // Initialization of a Hashtable Map<Integer, String> ht = new Hashtable<Integer, String>(); // Inserting the Elements // using put method ht.put(1, \"Geeks\"); ht.put(2, \"For\"); ht.put(3, \"Geeks\"); ht.put(4, \"For\"); // Initial HashMap System.out.println(\"Initial map : \" + ht); // Remove the map entry with key 4 ht.remove(4); // Final Hashtable System.out.println(\"Updated map : \" + ht); }}", "e": 40081, "s": 39372, "text": null }, { "code": null, "e": 40168, "s": 40081, "text": "Initial map : {4=For, 3=Geeks, 2=For, 1=Geeks}\nUpdated map : {3=Geeks, 2=For, 1=Geeks}" }, { "code": null, "e": 40307, "s": 40168, "text": "4. Traversal of a Hashtable: To iterate the table, we can make use of an advanced for loop. Below is the example of iterating a hashtable." }, { "code": null, "e": 40312, "s": 40307, "text": "Java" }, { "code": "// Java program to illustrate// traversal of Hashtable import java.util.Hashtable;import java.util.Map; public class IteratingHashtable { public static void main(String[] args) { // Create an instance of Hashtable Hashtable<String, Integer> ht = new Hashtable<>(); // Adding elements using put method ht.put(\"vishal\", 10); ht.put(\"sachin\", 30); ht.put(\"vaibhav\", 20); // Iterating using enhanced for loop for (Map.Entry<String, Integer> e : ht.entrySet()) System.out.println(e.getKey() + \" \" + e.getValue()); }}", "e": 40946, "s": 40312, "text": null }, { "code": null, "e": 40977, "s": 40946, "text": "vaibhav 20\nvishal 10\nsachin 30" }, { "code": null, "e": 41464, "s": 40977, "text": "Hashtable datastructure is an array of buckets which stores the key/value pairs in them. It makes use of hashCode() method to determine which bucket the key/value pair should map.The hash function helps to determine the location for a given key in the bucket list. Generally, hashcode is a non-negative integer that is equal for equal Objects and may or may not be equal for unequal Objects. To determine whether two objects are equal or not, hashtable makes use of the equals() method." }, { "code": null, "e": 41733, "s": 41464, "text": "It is possible that two unequal Objects have the same hashcode. This is called a collision. To resolve collisions, hashtable uses an array of lists. The pairs mapped to a single bucket (array index) are stored in a list and list reference is stored in the array index." }, { "code": null, "e": 41772, "s": 41735, "text": "K – The type of the keys in the map." }, { "code": null, "e": 41814, "s": 41772, "text": "V – The type of values mapped in the map." }, { "code": null, "e": 41821, "s": 41814, "text": "METHOD" }, { "code": null, "e": 41833, "s": 41821, "text": "DESCRIPTION" }, { "code": null, "e": 41868, "s": 41833, "text": "compute(K key, BiFunction<? super " }, { "code": null, "e": 41912, "s": 41868, "text": "K,? super V,? extends V> remappingFunction)" }, { "code": null, "e": 41957, "s": 41912, "text": "computeIfAbsent(K key, Function<? super K,? " }, { "code": null, "e": 41985, "s": 41957, "text": "extends V> mappingFunction)" }, { "code": null, "e": 41992, "s": 41985, "text": "METHOD" }, { "code": null, "e": 42004, "s": 41992, "text": "DESCRIPTION" }, { "code": null, "e": 42024, "s": 42004, "text": "remove​(Object key," }, { "code": null, "e": 42059, "s": 42024, "text": " Object value)" }, { "code": null, "e": 42070, "s": 42059, "text": "Must Read:" }, { "code": null, "e": 42120, "s": 42070, "text": "Differences between HashMap and HashTable in Java" }, { "code": null, "e": 42217, "s": 42120, "text": "Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Hashtable.html" }, { "code": null, "e": 42231, "s": 42217, "text": "OwiesAAlomari" }, { "code": null, "e": 42242, "s": 42231, "text": "nidhi_biet" }, { "code": null, "e": 42258, "s": 42242, "text": "bishnoisunil007" }, { "code": null, "e": 42282, "s": 42258, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 42292, "s": 42282, "text": "HashTable" }, { "code": null, "e": 42312, "s": 42292, "text": "Java - util package" }, { "code": null, "e": 42329, "s": 42312, "text": "Java-Collections" }, { "code": null, "e": 42344, "s": 42329, "text": "Java-HashTable" }, { "code": null, "e": 42349, "s": 42344, "text": "Java" }, { "code": null, "e": 42354, "s": 42349, "text": "Java" }, { "code": null, "e": 42371, "s": 42354, "text": "Java-Collections" }, { "code": null, "e": 42469, "s": 42371, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42513, "s": 42469, "text": "Split() String method in Java with examples" }, { "code": null, "e": 42538, "s": 42513, "text": "Reverse a string in Java" }, { "code": null, "e": 42574, "s": 42538, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 42589, "s": 42574, "text": "Stream In Java" }, { "code": null, "e": 42620, "s": 42589, "text": "How to iterate any Map in Java" }, { "code": null, "e": 42652, "s": 42620, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 42676, "s": 42652, "text": "Singleton Class in Java" }, { "code": null, "e": 42704, "s": 42676, "text": "Initializing a List in Java" }, { "code": null, "e": 42750, "s": 42704, "text": "Different ways of Reading a text file in Java" } ]
Python Library for Self-Balancing BST - GeeksforGeeks
10 Jan, 2022 Here we will see simulating the library framework TreeSet which is available in Java on Python. There are situations that arise to disallow duplicate entries especially in any management software where an object is uniquely identified by its uniqueness. In this post, let us see how to do that in Pythonic way. In our implementation, “TreeSet” class is a Binary-tree set like the Java TreeSet. The TreeSet will be sorted automatically when adding/removing elements. Duplicate elements will not be added. The functionalities that have been included are : Inserting an element into the TreeSet. Inserting multiple elements into the TreeSet. Fetching the ceil value from the TreeSet. Fetching the floor value from the TreeSet. Deleting an element from the TreeSet. Deleting all the elements from the TreeSet. Fetching the shallow copy of the TreeSet. Popping an element from the TreeSet. Python3 # The bisect module ensures the automatic sort after insertionimport bisect class TreeSet(object): """ Binary-tree set like java Treeset. Duplicate elements will not be added. When added new element, TreeSet will be sorted automatically. """ def __init__(self, elements): self._treeset = [] self.addAllElements(elements) # To add many elements def addAllElements(self, elements): for element in elements: if element in self: continue self.addElement(element) # To add an element def addElement(self, element): if element not in self: bisect.insort(self._treeset, element) # To get ceiling value def ceiling(self, e): index = bisect.bisect_right(self._treeset, e) if self[index - 1] == e: return e return self._treeset[bisect.bisect_right(self._treeset, e)] def floor(self, e): index = bisect.bisect_left(self._treeset, e) if self[index] == e: return e else: return self._treeset[bisect.bisect_left(self._treeset, e) - 1] def __getitem__(self, num): return self._treeset[num] def __len__(self): return len(self._treeset) def clearElements(self): """ Delete all elements in TreeSet. """ self._treeset = [] def clone(self): """ Return shallow copy of self. """ return TreeSet(self._treeset) def removeElement(self, element): """ Remove element if element in TreeSet. """ try: self._treeset.remove(element) except ValueError: return False return True def __iter__(self): """ Do ascending iteration for TreeSet """ for element in self._treeset: yield element def pop(self, index): return self._treeset.pop(index) def __str__(self): return str(self._treeset) def __eq__(self, target): if isinstance(target, TreeSet): return self._treeset == target.treeset elif isinstance(target, list): return self._treeset == target def __contains__(self, e): """ Fast attribution judgement by bisect """ try: return e == self._treeset[bisect.bisect_left(self._treeset, e)] except: return False if __name__ == '__main__': treeSet = TreeSet([3, 7, 7, 1, 3, 10]) # As there is no 5, floor of this gives the # next least value in the treeset i.e. 3 print("treeSet.floor(5) : ", treeSet.floor(5)) # As there is no 4, ceil of this gives the # next highest value in the treeset i.e. 7 print("treeSet.ceiling(4) : ", treeSet.ceiling(4)) # As there is no 2, floor of this gives the next # least value in the treeset i.e. 1 print("treeSet.floor(2) : ", treeSet.floor(2)) # As there is 3, ceil will give 3 as it is print("treeSet.ceiling(3) : ", treeSet.ceiling(3)) # As there is 10, floor will give 10 as it is print("treeSet.floor(10) : ", treeSet.floor(10)) # No duplicates printed print("treeSet : ", treeSet) # 2nd example treeSet = TreeSet([30, 70, 20, 70, 10, 30]) # No duplicates printed print("2nd example treeSet :", treeSet) treeSet.addElement(40) print("Adding 40 to the above, it is arranged in\ sorted order : ", treeSet) treeSet.removeElement(70) print("After removing 70 ", treeSet) treeSet.removeElement(50) print("After removing 50, no issue even if not\ available ", treeSet) # There is no 50 available treeSet.addAllElements([30, 40, 50, 60]) print("After adding many elements, duplicate are\ not taken :", treeSet) # Getting first element of treeset print(treeSet[0]) # See, how elements can be retrieved print(treeSet[-1], treeSet[5], treeSet[-2], treeSet[-3], treeSet[-4], treeSet[-5]) # Check for the existence of 10 and since # found, it returns true print(10 in treeSet) # Check for the existence of 100 and since # not found, it returns false print(100 in treeSet) for i in TreeSet([10, 30, 40]): print(i) treeSet.floor(5) : 3treeSet.ceiling(4) : 7treeSet.floor(2) : 1treeSet.ceiling(3) : 3treeSet.floor(10) : 10treeSet : [1, 3, 7, 10]treeSet : [10, 20, 30, 70]Adding 40 to the above, it is arranged in sorted order : [10, 20, 30, 40, 70]After removing 70 [10, 20, 30, 40]After removing 50 [10, 20, 30, 40]After adding many elements : [10, 20, 30, 40, 50, 60]1060 60 50 40 30 20TrueFalse103040 adnanirshad158 python-modules Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25561, "s": 25533, "text": "\n10 Jan, 2022" }, { "code": null, "e": 25872, "s": 25561, "text": "Here we will see simulating the library framework TreeSet which is available in Java on Python. There are situations that arise to disallow duplicate entries especially in any management software where an object is uniquely identified by its uniqueness. In this post, let us see how to do that in Pythonic way." }, { "code": null, "e": 26065, "s": 25872, "text": "In our implementation, “TreeSet” class is a Binary-tree set like the Java TreeSet. The TreeSet will be sorted automatically when adding/removing elements. Duplicate elements will not be added." }, { "code": null, "e": 26115, "s": 26065, "text": "The functionalities that have been included are :" }, { "code": null, "e": 26154, "s": 26115, "text": "Inserting an element into the TreeSet." }, { "code": null, "e": 26200, "s": 26154, "text": "Inserting multiple elements into the TreeSet." }, { "code": null, "e": 26242, "s": 26200, "text": "Fetching the ceil value from the TreeSet." }, { "code": null, "e": 26285, "s": 26242, "text": "Fetching the floor value from the TreeSet." }, { "code": null, "e": 26323, "s": 26285, "text": "Deleting an element from the TreeSet." }, { "code": null, "e": 26367, "s": 26323, "text": "Deleting all the elements from the TreeSet." }, { "code": null, "e": 26409, "s": 26367, "text": "Fetching the shallow copy of the TreeSet." }, { "code": null, "e": 26446, "s": 26409, "text": "Popping an element from the TreeSet." }, { "code": null, "e": 26454, "s": 26446, "text": "Python3" }, { "code": "# The bisect module ensures the automatic sort after insertionimport bisect class TreeSet(object): \"\"\" Binary-tree set like java Treeset. Duplicate elements will not be added. When added new element, TreeSet will be sorted automatically. \"\"\" def __init__(self, elements): self._treeset = [] self.addAllElements(elements) # To add many elements def addAllElements(self, elements): for element in elements: if element in self: continue self.addElement(element) # To add an element def addElement(self, element): if element not in self: bisect.insort(self._treeset, element) # To get ceiling value def ceiling(self, e): index = bisect.bisect_right(self._treeset, e) if self[index - 1] == e: return e return self._treeset[bisect.bisect_right(self._treeset, e)] def floor(self, e): index = bisect.bisect_left(self._treeset, e) if self[index] == e: return e else: return self._treeset[bisect.bisect_left(self._treeset, e) - 1] def __getitem__(self, num): return self._treeset[num] def __len__(self): return len(self._treeset) def clearElements(self): \"\"\" Delete all elements in TreeSet. \"\"\" self._treeset = [] def clone(self): \"\"\" Return shallow copy of self. \"\"\" return TreeSet(self._treeset) def removeElement(self, element): \"\"\" Remove element if element in TreeSet. \"\"\" try: self._treeset.remove(element) except ValueError: return False return True def __iter__(self): \"\"\" Do ascending iteration for TreeSet \"\"\" for element in self._treeset: yield element def pop(self, index): return self._treeset.pop(index) def __str__(self): return str(self._treeset) def __eq__(self, target): if isinstance(target, TreeSet): return self._treeset == target.treeset elif isinstance(target, list): return self._treeset == target def __contains__(self, e): \"\"\" Fast attribution judgement by bisect \"\"\" try: return e == self._treeset[bisect.bisect_left(self._treeset, e)] except: return False if __name__ == '__main__': treeSet = TreeSet([3, 7, 7, 1, 3, 10]) # As there is no 5, floor of this gives the # next least value in the treeset i.e. 3 print(\"treeSet.floor(5) : \", treeSet.floor(5)) # As there is no 4, ceil of this gives the # next highest value in the treeset i.e. 7 print(\"treeSet.ceiling(4) : \", treeSet.ceiling(4)) # As there is no 2, floor of this gives the next # least value in the treeset i.e. 1 print(\"treeSet.floor(2) : \", treeSet.floor(2)) # As there is 3, ceil will give 3 as it is print(\"treeSet.ceiling(3) : \", treeSet.ceiling(3)) # As there is 10, floor will give 10 as it is print(\"treeSet.floor(10) : \", treeSet.floor(10)) # No duplicates printed print(\"treeSet : \", treeSet) # 2nd example treeSet = TreeSet([30, 70, 20, 70, 10, 30]) # No duplicates printed print(\"2nd example treeSet :\", treeSet) treeSet.addElement(40) print(\"Adding 40 to the above, it is arranged in\\ sorted order : \", treeSet) treeSet.removeElement(70) print(\"After removing 70 \", treeSet) treeSet.removeElement(50) print(\"After removing 50, no issue even if not\\ available \", treeSet) # There is no 50 available treeSet.addAllElements([30, 40, 50, 60]) print(\"After adding many elements, duplicate are\\ not taken :\", treeSet) # Getting first element of treeset print(treeSet[0]) # See, how elements can be retrieved print(treeSet[-1], treeSet[5], treeSet[-2], treeSet[-3], treeSet[-4], treeSet[-5]) # Check for the existence of 10 and since # found, it returns true print(10 in treeSet) # Check for the existence of 100 and since # not found, it returns false print(100 in treeSet) for i in TreeSet([10, 30, 40]): print(i) ", "e": 30749, "s": 26454, "text": null }, { "code": null, "e": 31137, "s": 30749, "text": "treeSet.floor(5) : 3treeSet.ceiling(4) : 7treeSet.floor(2) : 1treeSet.ceiling(3) : 3treeSet.floor(10) : 10treeSet : [1, 3, 7, 10]treeSet : [10, 20, 30, 70]Adding 40 to the above, it is arranged in sorted order : [10, 20, 30, 40, 70]After removing 70 [10, 20, 30, 40]After removing 50 [10, 20, 30, 40]After adding many elements : [10, 20, 30, 40, 50, 60]1060 60 50 40 30 20TrueFalse103040" }, { "code": null, "e": 31152, "s": 31137, "text": "adnanirshad158" }, { "code": null, "e": 31167, "s": 31152, "text": "python-modules" }, { "code": null, "e": 31174, "s": 31167, "text": "Python" }, { "code": null, "e": 31272, "s": 31174, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31304, "s": 31272, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 31346, "s": 31304, "text": "Check if element exists in list in Python" }, { "code": null, "e": 31388, "s": 31346, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 31415, "s": 31388, "text": "Python Classes and Objects" }, { "code": null, "e": 31471, "s": 31415, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 31493, "s": 31471, "text": "Defaultdict in Python" }, { "code": null, "e": 31532, "s": 31493, "text": "Python | Get unique values from a list" }, { "code": null, "e": 31563, "s": 31532, "text": "Python | os.path.join() method" }, { "code": null, "e": 31592, "s": 31563, "text": "Create a directory in Python" } ]
Python | Database management in PostgreSQL - GeeksforGeeks
25 Jun, 2019 PostgreSQL is an open source object-relational database management system. It is well known for its reliability, robustness, and performance. PostgreSQL has a variety of libraries of API (Application programmable interface) that are available for a variety of popular programming languages such as Python. It provides a lot of features for Database management such as Views, Triggers, Indexes (using B-Trees), etc. There are several python modules that allow us to connect to and manipulate the database using PostgreSQL: Psycopg2 pg8000 py-postgresql PyGreSQL Psycopg2 is one of the most popular python drivers for PostgreSQL. It is actively maintained and provides support for different versions of python. It also provides support for Threads and can be used in multithreaded applications. For these reasons, it is a popular choice for developers. In this article, we shall explore the features of PostgreSQl using psycopg2 by building a simple database management system in python. Installation: sudo pip3 install psycopg2 Note: if you are using Python2, use pip install instead of pip3 Once psycopg has been installed in your system, we can connect to the database and execute queries in Python. before we can access the database in python, we need to create the database in postgresql. To create the database, follow the steps given below: Log in to PostgreSQL:sudo -u postgres psqlConfigure the password:\passwordYou will then be prompted to enter the password. remember this as we will use it to connect to the database in Python.Create a database called “test”. we will connect to this database.CREATE DATABASE test; Once the database and password have been configured, exit the psql server.Connecting to the databaseThe connect() method is used to establish connection with the database. It takes 5 parameters:database: The name of the database you are connecting touser: the username of your local systempassword: the password to log in to psqlhost: The host, which is set to localhost by defaultport: The port number which is 5432 by defaultconn = psycopg2.connect( database="test", user = "adith", password = "password", host = "localhost", port = "5432")Once the connection has been established, we can manipulate the database in python.The Cursor object is used to execute sql queries. we can create a cursor object using the connecting object (conn) cur = conn.cursor() Using this object, we can make changes to the database that we are connected to.After you have executed all the queries, we need to disconnect from the connection. Not disconnecting will not cause any errors but it is generally considered a good practice to disconnect. conn.close() Executing queriesThe execute() method takes in one parameter, the SQL query to be executed. The SQL query is taken in the form of a string that contains the SQL statement. cur.execute("SELECT * FROM emp") Fetching the dataOnce the query has been executed, the results of the query can be obtained using the fetchall() method. This method takes no parameters and returns the result of select queries. res = cur.fetchall() The result of the query is stored in the res variable.Putting it all togetherOnce we have created the database in PostgreSQL, we can access that database in python. We first create an emp table in the database called test with the schema: (id INTEGER PRIMARY KEY, name VARCHAR(10), salary INT, dept INT). Once the table is created without any errors, we insert values into the table.Once the values are inserted, we can query the table to select all the rows and display them to the user using the fetchall() function.# importing librariesimport psycopg2 # a function to connect to# the database.def connect(): # connecting to the database called test # using the connect function try: conn = psycopg2.connect(database ="test", user = "adith", password = "password", host = "localhost", port = "5432") # creating the cursor object cur = conn.cursor() except (Exception, psycopg2.DatabaseError) as error: print ("Error while creating PostgreSQL table", error) # returing the conn and cur # objects to be used later return conn, cur # a function to create the # emp table.def create_table(): # connect to the database. conn, cur = connect() try: # the test database contains a table called emp # the schema : (id INTEGER PRIMARY KEY, # name VARCHAR(10), salary INT, dept INT) # create the emp table cur.execute('CREATE TABLE emp (id INT PRIMARY KEY, name VARCHAR(10), salary INT, dept INT)') # the commit function permanently # saves the changes made to the database # the rollback() function can be used if # there are any undesirable changes and # it simply undoes the changes of the # previous query except: print('error') conn.commit() # a function to insert data# into the emp tabledef insert_data(id = 1, name = '', salary = 1000, dept = 1): conn, cur = connect() try: # inserting values into the emp table cur.execute('INSERT INTO emp VALUES(%s, %s, %s, %s)', (id, name, salary, dept)) except Exception as e: print('error', e) # commiting the transaction. conn.commit() # a function to fetch the data # from the tabledef fetch_data(): conn, cur = connect() # select all the rows from emp try: cur.execute('SELECT * FROM emp') except: print('error !') # store the result in data data = cur.fetchall() # return the result return data # a function to print the datadef print_data(data): print('Query result: ') print() # iterating over all the # rows in the table for row in data: # printing the columns print('id: ', row[0]) print('name: ', row[1]) print('salary: ', row[2]) print('dept: ', row[3]) print('----------------------------------') # function to delete the tabledef delete_table(): conn, cur = connect() # delete the table try: cur.execute('DROP TABLE emp') except Exception as e: print('error', e) conn.commit() # driver functionif __name__ == '__main__': # create the table create_table() # inserting some values insert_data(1, 'adith', 1000, 2) insert_data(2, 'tyrion', 100000, 2) insert_data(3, 'jon', 100, 3) insert_data(4, 'daenerys', 10000, 4) # getting all the rows data = fetch_data() # printing the rows print_data(data) # deleting the table # once we are done with # the program delete_table()Output :My Personal Notes arrow_drop_upSave Log in to PostgreSQL:sudo -u postgres psql sudo -u postgres psql Configure the password:\passwordYou will then be prompted to enter the password. remember this as we will use it to connect to the database in Python. \password You will then be prompted to enter the password. remember this as we will use it to connect to the database in Python. Create a database called “test”. we will connect to this database.CREATE DATABASE test; Once the database and password have been configured, exit the psql server.Connecting to the databaseThe connect() method is used to establish connection with the database. It takes 5 parameters:database: The name of the database you are connecting touser: the username of your local systempassword: the password to log in to psqlhost: The host, which is set to localhost by defaultport: The port number which is 5432 by defaultconn = psycopg2.connect( database="test", user = "adith", password = "password", host = "localhost", port = "5432")Once the connection has been established, we can manipulate the database in python.The Cursor object is used to execute sql queries. we can create a cursor object using the connecting object (conn) cur = conn.cursor() Using this object, we can make changes to the database that we are connected to.After you have executed all the queries, we need to disconnect from the connection. Not disconnecting will not cause any errors but it is generally considered a good practice to disconnect. conn.close() Executing queriesThe execute() method takes in one parameter, the SQL query to be executed. The SQL query is taken in the form of a string that contains the SQL statement. cur.execute("SELECT * FROM emp") Fetching the dataOnce the query has been executed, the results of the query can be obtained using the fetchall() method. This method takes no parameters and returns the result of select queries. res = cur.fetchall() The result of the query is stored in the res variable.Putting it all togetherOnce we have created the database in PostgreSQL, we can access that database in python. We first create an emp table in the database called test with the schema: (id INTEGER PRIMARY KEY, name VARCHAR(10), salary INT, dept INT). Once the table is created without any errors, we insert values into the table.Once the values are inserted, we can query the table to select all the rows and display them to the user using the fetchall() function.# importing librariesimport psycopg2 # a function to connect to# the database.def connect(): # connecting to the database called test # using the connect function try: conn = psycopg2.connect(database ="test", user = "adith", password = "password", host = "localhost", port = "5432") # creating the cursor object cur = conn.cursor() except (Exception, psycopg2.DatabaseError) as error: print ("Error while creating PostgreSQL table", error) # returing the conn and cur # objects to be used later return conn, cur # a function to create the # emp table.def create_table(): # connect to the database. conn, cur = connect() try: # the test database contains a table called emp # the schema : (id INTEGER PRIMARY KEY, # name VARCHAR(10), salary INT, dept INT) # create the emp table cur.execute('CREATE TABLE emp (id INT PRIMARY KEY, name VARCHAR(10), salary INT, dept INT)') # the commit function permanently # saves the changes made to the database # the rollback() function can be used if # there are any undesirable changes and # it simply undoes the changes of the # previous query except: print('error') conn.commit() # a function to insert data# into the emp tabledef insert_data(id = 1, name = '', salary = 1000, dept = 1): conn, cur = connect() try: # inserting values into the emp table cur.execute('INSERT INTO emp VALUES(%s, %s, %s, %s)', (id, name, salary, dept)) except Exception as e: print('error', e) # commiting the transaction. conn.commit() # a function to fetch the data # from the tabledef fetch_data(): conn, cur = connect() # select all the rows from emp try: cur.execute('SELECT * FROM emp') except: print('error !') # store the result in data data = cur.fetchall() # return the result return data # a function to print the datadef print_data(data): print('Query result: ') print() # iterating over all the # rows in the table for row in data: # printing the columns print('id: ', row[0]) print('name: ', row[1]) print('salary: ', row[2]) print('dept: ', row[3]) print('----------------------------------') # function to delete the tabledef delete_table(): conn, cur = connect() # delete the table try: cur.execute('DROP TABLE emp') except Exception as e: print('error', e) conn.commit() # driver functionif __name__ == '__main__': # create the table create_table() # inserting some values insert_data(1, 'adith', 1000, 2) insert_data(2, 'tyrion', 100000, 2) insert_data(3, 'jon', 100, 3) insert_data(4, 'daenerys', 10000, 4) # getting all the rows data = fetch_data() # printing the rows print_data(data) # deleting the table # once we are done with # the program delete_table()Output :My Personal Notes arrow_drop_upSave CREATE DATABASE test; Once the database and password have been configured, exit the psql server. The connect() method is used to establish connection with the database. It takes 5 parameters: database: The name of the database you are connecting touser: the username of your local systempassword: the password to log in to psqlhost: The host, which is set to localhost by defaultport: The port number which is 5432 by default database: The name of the database you are connecting to user: the username of your local system password: the password to log in to psql host: The host, which is set to localhost by default port: The port number which is 5432 by default conn = psycopg2.connect( database="test", user = "adith", password = "password", host = "localhost", port = "5432") Once the connection has been established, we can manipulate the database in python. The Cursor object is used to execute sql queries. we can create a cursor object using the connecting object (conn) cur = conn.cursor() Using this object, we can make changes to the database that we are connected to. After you have executed all the queries, we need to disconnect from the connection. Not disconnecting will not cause any errors but it is generally considered a good practice to disconnect. conn.close() The execute() method takes in one parameter, the SQL query to be executed. The SQL query is taken in the form of a string that contains the SQL statement. cur.execute("SELECT * FROM emp") Once the query has been executed, the results of the query can be obtained using the fetchall() method. This method takes no parameters and returns the result of select queries. res = cur.fetchall() The result of the query is stored in the res variable. Once we have created the database in PostgreSQL, we can access that database in python. We first create an emp table in the database called test with the schema: (id INTEGER PRIMARY KEY, name VARCHAR(10), salary INT, dept INT). Once the table is created without any errors, we insert values into the table.Once the values are inserted, we can query the table to select all the rows and display them to the user using the fetchall() function. # importing librariesimport psycopg2 # a function to connect to# the database.def connect(): # connecting to the database called test # using the connect function try: conn = psycopg2.connect(database ="test", user = "adith", password = "password", host = "localhost", port = "5432") # creating the cursor object cur = conn.cursor() except (Exception, psycopg2.DatabaseError) as error: print ("Error while creating PostgreSQL table", error) # returing the conn and cur # objects to be used later return conn, cur # a function to create the # emp table.def create_table(): # connect to the database. conn, cur = connect() try: # the test database contains a table called emp # the schema : (id INTEGER PRIMARY KEY, # name VARCHAR(10), salary INT, dept INT) # create the emp table cur.execute('CREATE TABLE emp (id INT PRIMARY KEY, name VARCHAR(10), salary INT, dept INT)') # the commit function permanently # saves the changes made to the database # the rollback() function can be used if # there are any undesirable changes and # it simply undoes the changes of the # previous query except: print('error') conn.commit() # a function to insert data# into the emp tabledef insert_data(id = 1, name = '', salary = 1000, dept = 1): conn, cur = connect() try: # inserting values into the emp table cur.execute('INSERT INTO emp VALUES(%s, %s, %s, %s)', (id, name, salary, dept)) except Exception as e: print('error', e) # commiting the transaction. conn.commit() # a function to fetch the data # from the tabledef fetch_data(): conn, cur = connect() # select all the rows from emp try: cur.execute('SELECT * FROM emp') except: print('error !') # store the result in data data = cur.fetchall() # return the result return data # a function to print the datadef print_data(data): print('Query result: ') print() # iterating over all the # rows in the table for row in data: # printing the columns print('id: ', row[0]) print('name: ', row[1]) print('salary: ', row[2]) print('dept: ', row[3]) print('----------------------------------') # function to delete the tabledef delete_table(): conn, cur = connect() # delete the table try: cur.execute('DROP TABLE emp') except Exception as e: print('error', e) conn.commit() # driver functionif __name__ == '__main__': # create the table create_table() # inserting some values insert_data(1, 'adith', 1000, 2) insert_data(2, 'tyrion', 100000, 2) insert_data(3, 'jon', 100, 3) insert_data(4, 'daenerys', 10000, 4) # getting all the rows data = fetch_data() # printing the rows print_data(data) # deleting the table # once we are done with # the program delete_table() Output : Python-database Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() *args and **kwargs in Python Create a Pandas DataFrame from Lists Convert integer to string in Python Check if element exists in list in Python How To Convert Python Dictionary To JSON? sum() function in Python
[ { "code": null, "e": 26089, "s": 26061, "text": "\n25 Jun, 2019" }, { "code": null, "e": 26504, "s": 26089, "text": "PostgreSQL is an open source object-relational database management system. It is well known for its reliability, robustness, and performance. PostgreSQL has a variety of libraries of API (Application programmable interface) that are available for a variety of popular programming languages such as Python. It provides a lot of features for Database management such as Views, Triggers, Indexes (using B-Trees), etc." }, { "code": null, "e": 26611, "s": 26504, "text": "There are several python modules that allow us to connect to and manipulate the database using PostgreSQL:" }, { "code": null, "e": 26620, "s": 26611, "text": "Psycopg2" }, { "code": null, "e": 26627, "s": 26620, "text": "pg8000" }, { "code": null, "e": 26641, "s": 26627, "text": "py-postgresql" }, { "code": null, "e": 26650, "s": 26641, "text": "PyGreSQL" }, { "code": null, "e": 26940, "s": 26650, "text": "Psycopg2 is one of the most popular python drivers for PostgreSQL. It is actively maintained and provides support for different versions of python. It also provides support for Threads and can be used in multithreaded applications. For these reasons, it is a popular choice for developers." }, { "code": null, "e": 27075, "s": 26940, "text": "In this article, we shall explore the features of PostgreSQl using psycopg2 by building a simple database management system in python." }, { "code": null, "e": 27089, "s": 27075, "text": "Installation:" }, { "code": null, "e": 27117, "s": 27089, "text": "sudo pip3 install psycopg2 " }, { "code": null, "e": 27181, "s": 27117, "text": "Note: if you are using Python2, use pip install instead of pip3" }, { "code": null, "e": 27291, "s": 27181, "text": "Once psycopg has been installed in your system, we can connect to the database and execute queries in Python." }, { "code": null, "e": 27436, "s": 27291, "text": "before we can access the database in python, we need to create the database in postgresql. To create the database, follow the steps given below:" }, { "code": null, "e": 33071, "s": 27436, "text": "Log in to PostgreSQL:sudo -u postgres psqlConfigure the password:\\passwordYou will then be prompted to enter the password. remember this as we will use it to connect to the database in Python.Create a database called “test”. we will connect to this database.CREATE DATABASE test; Once the database and password have been configured, exit the psql server.Connecting to the databaseThe connect() method is used to establish connection with the database. It takes 5 parameters:database: The name of the database you are connecting touser: the username of your local systempassword: the password to log in to psqlhost: The host, which is set to localhost by defaultport: The port number which is 5432 by defaultconn = psycopg2.connect(\n database=\"test\", \n user = \"adith\", \n password = \"password\", \n host = \"localhost\", \n port = \"5432\")Once the connection has been established, we can manipulate the database in python.The Cursor object is used to execute sql queries. we can create a cursor object using the connecting object (conn) cur = conn.cursor() Using this object, we can make changes to the database that we are connected to.After you have executed all the queries, we need to disconnect from the connection. Not disconnecting will not cause any errors but it is generally considered a good practice to disconnect. conn.close() Executing queriesThe execute() method takes in one parameter, the SQL query to be executed. The SQL query is taken in the form of a string that contains the SQL statement. cur.execute(\"SELECT * FROM emp\") Fetching the dataOnce the query has been executed, the results of the query can be obtained using the fetchall() method. This method takes no parameters and returns the result of select queries. res = cur.fetchall() The result of the query is stored in the res variable.Putting it all togetherOnce we have created the database in PostgreSQL, we can access that database in python. We first create an emp table in the database called test with the schema: (id INTEGER PRIMARY KEY, name VARCHAR(10), salary INT, dept INT). Once the table is created without any errors, we insert values into the table.Once the values are inserted, we can query the table to select all the rows and display them to the user using the fetchall() function.# importing librariesimport psycopg2 # a function to connect to# the database.def connect(): # connecting to the database called test # using the connect function try: conn = psycopg2.connect(database =\"test\", user = \"adith\", password = \"password\", host = \"localhost\", port = \"5432\") # creating the cursor object cur = conn.cursor() except (Exception, psycopg2.DatabaseError) as error: print (\"Error while creating PostgreSQL table\", error) # returing the conn and cur # objects to be used later return conn, cur # a function to create the # emp table.def create_table(): # connect to the database. conn, cur = connect() try: # the test database contains a table called emp # the schema : (id INTEGER PRIMARY KEY, # name VARCHAR(10), salary INT, dept INT) # create the emp table cur.execute('CREATE TABLE emp (id INT PRIMARY KEY, name VARCHAR(10), salary INT, dept INT)') # the commit function permanently # saves the changes made to the database # the rollback() function can be used if # there are any undesirable changes and # it simply undoes the changes of the # previous query except: print('error') conn.commit() # a function to insert data# into the emp tabledef insert_data(id = 1, name = '', salary = 1000, dept = 1): conn, cur = connect() try: # inserting values into the emp table cur.execute('INSERT INTO emp VALUES(%s, %s, %s, %s)', (id, name, salary, dept)) except Exception as e: print('error', e) # commiting the transaction. conn.commit() # a function to fetch the data # from the tabledef fetch_data(): conn, cur = connect() # select all the rows from emp try: cur.execute('SELECT * FROM emp') except: print('error !') # store the result in data data = cur.fetchall() # return the result return data # a function to print the datadef print_data(data): print('Query result: ') print() # iterating over all the # rows in the table for row in data: # printing the columns print('id: ', row[0]) print('name: ', row[1]) print('salary: ', row[2]) print('dept: ', row[3]) print('----------------------------------') # function to delete the tabledef delete_table(): conn, cur = connect() # delete the table try: cur.execute('DROP TABLE emp') except Exception as e: print('error', e) conn.commit() # driver functionif __name__ == '__main__': # create the table create_table() # inserting some values insert_data(1, 'adith', 1000, 2) insert_data(2, 'tyrion', 100000, 2) insert_data(3, 'jon', 100, 3) insert_data(4, 'daenerys', 10000, 4) # getting all the rows data = fetch_data() # printing the rows print_data(data) # deleting the table # once we are done with # the program delete_table()Output :My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 33114, "s": 33071, "text": "Log in to PostgreSQL:sudo -u postgres psql" }, { "code": null, "e": 33136, "s": 33114, "text": "sudo -u postgres psql" }, { "code": null, "e": 33287, "s": 33136, "text": "Configure the password:\\passwordYou will then be prompted to enter the password. remember this as we will use it to connect to the database in Python." }, { "code": null, "e": 33297, "s": 33287, "text": "\\password" }, { "code": null, "e": 33416, "s": 33297, "text": "You will then be prompted to enter the password. remember this as we will use it to connect to the database in Python." }, { "code": null, "e": 38859, "s": 33416, "text": "Create a database called “test”. we will connect to this database.CREATE DATABASE test; Once the database and password have been configured, exit the psql server.Connecting to the databaseThe connect() method is used to establish connection with the database. It takes 5 parameters:database: The name of the database you are connecting touser: the username of your local systempassword: the password to log in to psqlhost: The host, which is set to localhost by defaultport: The port number which is 5432 by defaultconn = psycopg2.connect(\n database=\"test\", \n user = \"adith\", \n password = \"password\", \n host = \"localhost\", \n port = \"5432\")Once the connection has been established, we can manipulate the database in python.The Cursor object is used to execute sql queries. we can create a cursor object using the connecting object (conn) cur = conn.cursor() Using this object, we can make changes to the database that we are connected to.After you have executed all the queries, we need to disconnect from the connection. Not disconnecting will not cause any errors but it is generally considered a good practice to disconnect. conn.close() Executing queriesThe execute() method takes in one parameter, the SQL query to be executed. The SQL query is taken in the form of a string that contains the SQL statement. cur.execute(\"SELECT * FROM emp\") Fetching the dataOnce the query has been executed, the results of the query can be obtained using the fetchall() method. This method takes no parameters and returns the result of select queries. res = cur.fetchall() The result of the query is stored in the res variable.Putting it all togetherOnce we have created the database in PostgreSQL, we can access that database in python. We first create an emp table in the database called test with the schema: (id INTEGER PRIMARY KEY, name VARCHAR(10), salary INT, dept INT). Once the table is created without any errors, we insert values into the table.Once the values are inserted, we can query the table to select all the rows and display them to the user using the fetchall() function.# importing librariesimport psycopg2 # a function to connect to# the database.def connect(): # connecting to the database called test # using the connect function try: conn = psycopg2.connect(database =\"test\", user = \"adith\", password = \"password\", host = \"localhost\", port = \"5432\") # creating the cursor object cur = conn.cursor() except (Exception, psycopg2.DatabaseError) as error: print (\"Error while creating PostgreSQL table\", error) # returing the conn and cur # objects to be used later return conn, cur # a function to create the # emp table.def create_table(): # connect to the database. conn, cur = connect() try: # the test database contains a table called emp # the schema : (id INTEGER PRIMARY KEY, # name VARCHAR(10), salary INT, dept INT) # create the emp table cur.execute('CREATE TABLE emp (id INT PRIMARY KEY, name VARCHAR(10), salary INT, dept INT)') # the commit function permanently # saves the changes made to the database # the rollback() function can be used if # there are any undesirable changes and # it simply undoes the changes of the # previous query except: print('error') conn.commit() # a function to insert data# into the emp tabledef insert_data(id = 1, name = '', salary = 1000, dept = 1): conn, cur = connect() try: # inserting values into the emp table cur.execute('INSERT INTO emp VALUES(%s, %s, %s, %s)', (id, name, salary, dept)) except Exception as e: print('error', e) # commiting the transaction. conn.commit() # a function to fetch the data # from the tabledef fetch_data(): conn, cur = connect() # select all the rows from emp try: cur.execute('SELECT * FROM emp') except: print('error !') # store the result in data data = cur.fetchall() # return the result return data # a function to print the datadef print_data(data): print('Query result: ') print() # iterating over all the # rows in the table for row in data: # printing the columns print('id: ', row[0]) print('name: ', row[1]) print('salary: ', row[2]) print('dept: ', row[3]) print('----------------------------------') # function to delete the tabledef delete_table(): conn, cur = connect() # delete the table try: cur.execute('DROP TABLE emp') except Exception as e: print('error', e) conn.commit() # driver functionif __name__ == '__main__': # create the table create_table() # inserting some values insert_data(1, 'adith', 1000, 2) insert_data(2, 'tyrion', 100000, 2) insert_data(3, 'jon', 100, 3) insert_data(4, 'daenerys', 10000, 4) # getting all the rows data = fetch_data() # printing the rows print_data(data) # deleting the table # once we are done with # the program delete_table()Output :My Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 38882, "s": 38859, "text": "CREATE DATABASE test; " }, { "code": null, "e": 38957, "s": 38882, "text": "Once the database and password have been configured, exit the psql server." }, { "code": null, "e": 39052, "s": 38957, "text": "The connect() method is used to establish connection with the database. It takes 5 parameters:" }, { "code": null, "e": 39286, "s": 39052, "text": "database: The name of the database you are connecting touser: the username of your local systempassword: the password to log in to psqlhost: The host, which is set to localhost by defaultport: The port number which is 5432 by default" }, { "code": null, "e": 39343, "s": 39286, "text": "database: The name of the database you are connecting to" }, { "code": null, "e": 39383, "s": 39343, "text": "user: the username of your local system" }, { "code": null, "e": 39424, "s": 39383, "text": "password: the password to log in to psql" }, { "code": null, "e": 39477, "s": 39424, "text": "host: The host, which is set to localhost by default" }, { "code": null, "e": 39524, "s": 39477, "text": "port: The port number which is 5432 by default" }, { "code": null, "e": 39704, "s": 39524, "text": "conn = psycopg2.connect(\n database=\"test\", \n user = \"adith\", \n password = \"password\", \n host = \"localhost\", \n port = \"5432\")" }, { "code": null, "e": 39788, "s": 39704, "text": "Once the connection has been established, we can manipulate the database in python." }, { "code": null, "e": 39903, "s": 39788, "text": "The Cursor object is used to execute sql queries. we can create a cursor object using the connecting object (conn)" }, { "code": null, "e": 39926, "s": 39903, "text": " cur = conn.cursor() " }, { "code": null, "e": 40007, "s": 39926, "text": "Using this object, we can make changes to the database that we are connected to." }, { "code": null, "e": 40197, "s": 40007, "text": "After you have executed all the queries, we need to disconnect from the connection. Not disconnecting will not cause any errors but it is generally considered a good practice to disconnect." }, { "code": null, "e": 40212, "s": 40197, "text": " conn.close() " }, { "code": null, "e": 40367, "s": 40212, "text": "The execute() method takes in one parameter, the SQL query to be executed. The SQL query is taken in the form of a string that contains the SQL statement." }, { "code": null, "e": 40402, "s": 40367, "text": " cur.execute(\"SELECT * FROM emp\") " }, { "code": null, "e": 40580, "s": 40402, "text": "Once the query has been executed, the results of the query can be obtained using the fetchall() method. This method takes no parameters and returns the result of select queries." }, { "code": null, "e": 40603, "s": 40580, "text": " res = cur.fetchall() " }, { "code": null, "e": 40658, "s": 40603, "text": "The result of the query is stored in the res variable." }, { "code": null, "e": 41100, "s": 40658, "text": "Once we have created the database in PostgreSQL, we can access that database in python. We first create an emp table in the database called test with the schema: (id INTEGER PRIMARY KEY, name VARCHAR(10), salary INT, dept INT). Once the table is created without any errors, we insert values into the table.Once the values are inserted, we can query the table to select all the rows and display them to the user using the fetchall() function." }, { "code": "# importing librariesimport psycopg2 # a function to connect to# the database.def connect(): # connecting to the database called test # using the connect function try: conn = psycopg2.connect(database =\"test\", user = \"adith\", password = \"password\", host = \"localhost\", port = \"5432\") # creating the cursor object cur = conn.cursor() except (Exception, psycopg2.DatabaseError) as error: print (\"Error while creating PostgreSQL table\", error) # returing the conn and cur # objects to be used later return conn, cur # a function to create the # emp table.def create_table(): # connect to the database. conn, cur = connect() try: # the test database contains a table called emp # the schema : (id INTEGER PRIMARY KEY, # name VARCHAR(10), salary INT, dept INT) # create the emp table cur.execute('CREATE TABLE emp (id INT PRIMARY KEY, name VARCHAR(10), salary INT, dept INT)') # the commit function permanently # saves the changes made to the database # the rollback() function can be used if # there are any undesirable changes and # it simply undoes the changes of the # previous query except: print('error') conn.commit() # a function to insert data# into the emp tabledef insert_data(id = 1, name = '', salary = 1000, dept = 1): conn, cur = connect() try: # inserting values into the emp table cur.execute('INSERT INTO emp VALUES(%s, %s, %s, %s)', (id, name, salary, dept)) except Exception as e: print('error', e) # commiting the transaction. conn.commit() # a function to fetch the data # from the tabledef fetch_data(): conn, cur = connect() # select all the rows from emp try: cur.execute('SELECT * FROM emp') except: print('error !') # store the result in data data = cur.fetchall() # return the result return data # a function to print the datadef print_data(data): print('Query result: ') print() # iterating over all the # rows in the table for row in data: # printing the columns print('id: ', row[0]) print('name: ', row[1]) print('salary: ', row[2]) print('dept: ', row[3]) print('----------------------------------') # function to delete the tabledef delete_table(): conn, cur = connect() # delete the table try: cur.execute('DROP TABLE emp') except Exception as e: print('error', e) conn.commit() # driver functionif __name__ == '__main__': # create the table create_table() # inserting some values insert_data(1, 'adith', 1000, 2) insert_data(2, 'tyrion', 100000, 2) insert_data(3, 'jon', 100, 3) insert_data(4, 'daenerys', 10000, 4) # getting all the rows data = fetch_data() # printing the rows print_data(data) # deleting the table # once we are done with # the program delete_table()", "e": 44365, "s": 41100, "text": null }, { "code": null, "e": 44374, "s": 44365, "text": "Output :" }, { "code": null, "e": 44390, "s": 44374, "text": "Python-database" }, { "code": null, "e": 44397, "s": 44390, "text": "Python" }, { "code": null, "e": 44495, "s": 44397, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44527, "s": 44495, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 44549, "s": 44527, "text": "Enumerate() in Python" }, { "code": null, "e": 44591, "s": 44549, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 44617, "s": 44591, "text": "Python String | replace()" }, { "code": null, "e": 44646, "s": 44617, "text": "*args and **kwargs in Python" }, { "code": null, "e": 44683, "s": 44646, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 44719, "s": 44683, "text": "Convert integer to string in Python" }, { "code": null, "e": 44761, "s": 44719, "text": "Check if element exists in list in Python" }, { "code": null, "e": 44803, "s": 44761, "text": "How To Convert Python Dictionary To JSON?" } ]
Implementation of Perceptron Algorithm for NOR Logic Gate with 2-bit Binary Input - GeeksforGeeks
08 Jul, 2020 In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function: For a particular choice of the weight vector and bias parameter , the model predicts output for the corresponding input vector . NOR logical function truth table for 2-bit binary variables, i.e, the input vector and the corresponding output – We can observe that, Now for the corresponding weight vector of the input vector to the OR node, the associated Perceptron Function can be defined as: Later on, the output of OR node is the input to the NOT node with weight . Then the corresponding output is the final output of the NOR logic function and the associated Perceptron Function can be defined as: For the implementation, considered weight parameters are and the bias parameters are . Python Implementation: # importing Python libraryimport numpy as np # define Unit Step Functiondef unitStep(v): if v >= 0: return 1 else: return 0 # design Perceptron Modeldef perceptronModel(x, w, b): v = np.dot(w, x) + b y = unitStep(v) return y # NOT Logic Function# wNOT = -1, bNOT = 0.5def NOT_logicFunction(x): wNOT = -1 bNOT = 0.5 return perceptronModel(x, wNOT, bNOT) # OR Logic Function# w1 = 1, w2 = 1, bOR = -0.5def OR_logicFunction(x): w = np.array([1, 1]) bOR = -0.5 return perceptronModel(x, w, bOR) # NOR Logic Function# with OR and NOT # function calls in sequencedef NOR_logicFunction(x): output_OR = OR_logicFunction(x) output_NOT = NOT_logicFunction(output_OR) return output_NOT # testing the Perceptron Modeltest1 = np.array([0, 1])test2 = np.array([1, 1])test3 = np.array([0, 0])test4 = np.array([1, 0]) print("NOR({}, {}) = {}".format(0, 1, NOR_logicFunction(test1)))print("NOR({}, {}) = {}".format(1, 1, NOR_logicFunction(test2)))print("NOR({}, {}) = {}".format(0, 0, NOR_logicFunction(test3)))print("NOR({}, {}) = {}".format(1, 0, NOR_logicFunction(test4))) NOR(0, 1) = 0 NOR(1, 1) = 0 NOR(0, 0) = 1 NOR(1, 0) = 0 Here, the model predicted output () for each of the test inputs are exactly matched with the NOR logic gate conventional output () according to the truth table for 2-bit binary input.Hence, it is verified that the perceptron algorithm for NOR logic gate is correctly implemented. Akanksha_Rai Neural Network Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Recurrent Neural Network Support Vector Machine Algorithm Intuition of Adam Optimizer CNN | Introduction to Pooling Layer Convolutional Neural Network (CNN) in Machine Learning 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": 25589, "s": 25561, "text": "\n08 Jul, 2020" }, { "code": null, "e": 25753, "s": 25589, "text": "In the field of Machine Learning, the Perceptron is a Supervised Learning Algorithm for binary classifiers. The Perceptron Model implements the following function:" }, { "code": null, "e": 25889, "s": 25758, "text": "For a particular choice of the weight vector and bias parameter , the model predicts output for the corresponding input vector ." }, { "code": null, "e": 26005, "s": 25889, "text": "NOR logical function truth table for 2-bit binary variables, i.e, the input vector and the corresponding output –" }, { "code": null, "e": 26158, "s": 26005, "text": "We can observe that, Now for the corresponding weight vector of the input vector to the OR node, the associated Perceptron Function can be defined as:" }, { "code": null, "e": 26374, "s": 26163, "text": "Later on, the output of OR node is the input to the NOT node with weight . Then the corresponding output is the final output of the NOR logic function and the associated Perceptron Function can be defined as:" }, { "code": null, "e": 26467, "s": 26379, "text": "For the implementation, considered weight parameters are and the bias parameters are ." }, { "code": null, "e": 26490, "s": 26467, "text": "Python Implementation:" }, { "code": "# importing Python libraryimport numpy as np # define Unit Step Functiondef unitStep(v): if v >= 0: return 1 else: return 0 # design Perceptron Modeldef perceptronModel(x, w, b): v = np.dot(w, x) + b y = unitStep(v) return y # NOT Logic Function# wNOT = -1, bNOT = 0.5def NOT_logicFunction(x): wNOT = -1 bNOT = 0.5 return perceptronModel(x, wNOT, bNOT) # OR Logic Function# w1 = 1, w2 = 1, bOR = -0.5def OR_logicFunction(x): w = np.array([1, 1]) bOR = -0.5 return perceptronModel(x, w, bOR) # NOR Logic Function# with OR and NOT # function calls in sequencedef NOR_logicFunction(x): output_OR = OR_logicFunction(x) output_NOT = NOT_logicFunction(output_OR) return output_NOT # testing the Perceptron Modeltest1 = np.array([0, 1])test2 = np.array([1, 1])test3 = np.array([0, 0])test4 = np.array([1, 0]) print(\"NOR({}, {}) = {}\".format(0, 1, NOR_logicFunction(test1)))print(\"NOR({}, {}) = {}\".format(1, 1, NOR_logicFunction(test2)))print(\"NOR({}, {}) = {}\".format(0, 0, NOR_logicFunction(test3)))print(\"NOR({}, {}) = {}\".format(1, 0, NOR_logicFunction(test4)))", "e": 27613, "s": 26490, "text": null }, { "code": null, "e": 27670, "s": 27613, "text": "NOR(0, 1) = 0\nNOR(1, 1) = 0\nNOR(0, 0) = 1\nNOR(1, 0) = 0\n" }, { "code": null, "e": 27950, "s": 27670, "text": "Here, the model predicted output () for each of the test inputs are exactly matched with the NOR logic gate conventional output () according to the truth table for 2-bit binary input.Hence, it is verified that the perceptron algorithm for NOR logic gate is correctly implemented." }, { "code": null, "e": 27963, "s": 27950, "text": "Akanksha_Rai" }, { "code": null, "e": 27978, "s": 27963, "text": "Neural Network" }, { "code": null, "e": 27995, "s": 27978, "text": "Machine Learning" }, { "code": null, "e": 28002, "s": 27995, "text": "Python" }, { "code": null, "e": 28019, "s": 28002, "text": "Machine Learning" }, { "code": null, "e": 28117, "s": 28019, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28158, "s": 28117, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 28191, "s": 28158, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 28219, "s": 28191, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 28255, "s": 28219, "text": "CNN | Introduction to Pooling Layer" }, { "code": null, "e": 28310, "s": 28255, "text": "Convolutional Neural Network (CNN) in Machine Learning" }, { "code": null, "e": 28338, "s": 28310, "text": "Read JSON file using Python" }, { "code": null, "e": 28388, "s": 28338, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28410, "s": 28388, "text": "Python map() function" } ]
Slicing a Vector in C++ - GeeksforGeeks
19 Jul, 2021 Pre-requisite: Vectors in C++Slicing a vector means to make a subvector from a given vector. Given N integers in a vector arr and to positive numbers X and Y, the task is to slice the given vector from index X to Y in a given vector.Examples: Input: vector arr = { 1, 3, 4, 2, 4, 2, 1 }, X = 2, Y = 5Output: 4 2 4 2Input: vector arr = { 1, 3, 4, 2 }, X = 1, Y = 2 Output: 3 4 Method 1: The idea is to copy the elements from this range X to Y to a new vector and return it. Get the starting iterator of element at index X as: Get the starting iterator of element at index X as: auto start = arr.begin() + X Get the ending iterator of element at index Y as: Get the ending iterator of element at index Y as: auto end = arr.begin() + Y + 1 Copy the elements in these range between these iterators using copy() function in vector. Copy the elements in these range between these iterators using copy() function in vector. Below is the implementation of the above approach: CPP // C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Function to slice a given vector// from range X to Yvector<int> slicing(vector<int>& arr, int X, int Y){ // Starting and Ending iterators auto start = arr.begin() + X; auto end = arr.begin() + Y + 1; // To store the sliced vector vector<int> result(Y - X + 1); // Copy vector using copy function() copy(start, end, result.begin()); // Return the final sliced vector return result;} // Function to print the vector ansvoid printResult(vector<int>& ans){ // Traverse the vector ans for (auto& it : ans) { // Print elements cout << it << ' '; }} // Driver Codeint main(){ // Given vector vector<int> arr = { 1, 3, 4, 2, 4, 2, 1 }; // Given range int X = 2, Y = 5; // Function Call vector<int> ans; ans = slicing(arr, X, Y); // Print the sliced vector printResult(ans);} 4 2 4 2 Method 2: The above approach can be implemented using Range Constructor. Below is the implementation of the above approach: CPP // C++ program for the above approach#include "bits/stdc++.h"using namespace std; // Template class to slice a vector// from range X to Ytemplate <typename T>vector<T> slicing(vector<T> const& v, int X, int Y){ // Begin and End iterator auto first = v.begin() + X; auto last = v.begin() + Y + 1; // Copy the element vector<T> vector(first, last); // Return the results return vector;} // Template class to print the element// in vector vtemplate <typename T>void printResult(vector<T> const& v){ // Traverse the vector v for (auto i : v) { cout << i << ' '; } cout << '\n';} // Driver Codeint main(){ // Given vector vector<int> arr = { 1, 3, 4, 2, 4, 2, 1 }; // Given range int X = 2, Y = 5; // To store the sliced vector vector<int> ans; // Function Call ans = slicing(arr, X, Y); // Print the sliced vector printResult(ans);} 4 2 4 2 Method 3: We can also use inbuilt function slice() in C++ STL to slice the given vector. Below is the implementation of the above approach: CPP // C++ program for the above approach#include "bits/stdc++.h"#include "valarray"using namespace std; // Function to slice the given array// elements from range (X, Y)valarray<int> slicing(valarray<int> arr, int X, int Y){ // Return the slicing of array return arr[slice(X, Y - X + 1, 1)];} // Print the resultant array// after slicingvoid printResult(valarray<int> v){ // Traverse the vector v for (auto i : v) { cout << i << ' '; } cout << '\n';} // Driver Codeint main(){ // Given vector valarray<int> arr = { 1, 3, 4, 2, 4, 2, 1 }; // Given range int X = 2, Y = 5; // To store the sliced vector valarray<int> ans; // Function Call ans = slicing(arr, X, Y); // Print the sliced vector printResult(ans);} 4 2 4 2 muheeth17 cpp-vector Arrays Articles C++ C++ Programs Arrays CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Stack Data Structure (Introduction and Program) Introduction to Arrays Multidimensional Arrays in Java Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples How to write a Pseudo Code? Analysis of Algorithms | Set 1 (Asymptotic Analysis)
[ { "code": null, "e": 25815, "s": 25787, "text": "\n19 Jul, 2021" }, { "code": null, "e": 26060, "s": 25815, "text": "Pre-requisite: Vectors in C++Slicing a vector means to make a subvector from a given vector. Given N integers in a vector arr and to positive numbers X and Y, the task is to slice the given vector from index X to Y in a given vector.Examples: " }, { "code": null, "e": 26195, "s": 26060, "text": "Input: vector arr = { 1, 3, 4, 2, 4, 2, 1 }, X = 2, Y = 5Output: 4 2 4 2Input: vector arr = { 1, 3, 4, 2 }, X = 1, Y = 2 Output: 3 4 " }, { "code": null, "e": 26296, "s": 26197, "text": "Method 1: The idea is to copy the elements from this range X to Y to a new vector and return it. " }, { "code": null, "e": 26350, "s": 26296, "text": "Get the starting iterator of element at index X as: " }, { "code": null, "e": 26404, "s": 26350, "text": "Get the starting iterator of element at index X as: " }, { "code": null, "e": 26433, "s": 26404, "text": "auto start = arr.begin() + X" }, { "code": null, "e": 26486, "s": 26433, "text": " Get the ending iterator of element at index Y as: " }, { "code": null, "e": 26540, "s": 26488, "text": "Get the ending iterator of element at index Y as: " }, { "code": null, "e": 26571, "s": 26540, "text": "auto end = arr.begin() + Y + 1" }, { "code": null, "e": 26662, "s": 26571, "text": " Copy the elements in these range between these iterators using copy() function in vector." }, { "code": null, "e": 26754, "s": 26664, "text": "Copy the elements in these range between these iterators using copy() function in vector." }, { "code": null, "e": 26806, "s": 26754, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26810, "s": 26806, "text": "CPP" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Function to slice a given vector// from range X to Yvector<int> slicing(vector<int>& arr, int X, int Y){ // Starting and Ending iterators auto start = arr.begin() + X; auto end = arr.begin() + Y + 1; // To store the sliced vector vector<int> result(Y - X + 1); // Copy vector using copy function() copy(start, end, result.begin()); // Return the final sliced vector return result;} // Function to print the vector ansvoid printResult(vector<int>& ans){ // Traverse the vector ans for (auto& it : ans) { // Print elements cout << it << ' '; }} // Driver Codeint main(){ // Given vector vector<int> arr = { 1, 3, 4, 2, 4, 2, 1 }; // Given range int X = 2, Y = 5; // Function Call vector<int> ans; ans = slicing(arr, X, Y); // Print the sliced vector printResult(ans);}", "e": 27791, "s": 26810, "text": null }, { "code": null, "e": 27799, "s": 27791, "text": "4 2 4 2" }, { "code": null, "e": 27926, "s": 27801, "text": "Method 2: The above approach can be implemented using Range Constructor. Below is the implementation of the above approach: " }, { "code": null, "e": 27930, "s": 27926, "text": "CPP" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"using namespace std; // Template class to slice a vector// from range X to Ytemplate <typename T>vector<T> slicing(vector<T> const& v, int X, int Y){ // Begin and End iterator auto first = v.begin() + X; auto last = v.begin() + Y + 1; // Copy the element vector<T> vector(first, last); // Return the results return vector;} // Template class to print the element// in vector vtemplate <typename T>void printResult(vector<T> const& v){ // Traverse the vector v for (auto i : v) { cout << i << ' '; } cout << '\\n';} // Driver Codeint main(){ // Given vector vector<int> arr = { 1, 3, 4, 2, 4, 2, 1 }; // Given range int X = 2, Y = 5; // To store the sliced vector vector<int> ans; // Function Call ans = slicing(arr, X, Y); // Print the sliced vector printResult(ans);}", "e": 28878, "s": 27930, "text": null }, { "code": null, "e": 28886, "s": 28878, "text": "4 2 4 2" }, { "code": null, "e": 29029, "s": 28888, "text": "Method 3: We can also use inbuilt function slice() in C++ STL to slice the given vector. Below is the implementation of the above approach: " }, { "code": null, "e": 29033, "s": 29029, "text": "CPP" }, { "code": "// C++ program for the above approach#include \"bits/stdc++.h\"#include \"valarray\"using namespace std; // Function to slice the given array// elements from range (X, Y)valarray<int> slicing(valarray<int> arr, int X, int Y){ // Return the slicing of array return arr[slice(X, Y - X + 1, 1)];} // Print the resultant array// after slicingvoid printResult(valarray<int> v){ // Traverse the vector v for (auto i : v) { cout << i << ' '; } cout << '\\n';} // Driver Codeint main(){ // Given vector valarray<int> arr = { 1, 3, 4, 2, 4, 2, 1 }; // Given range int X = 2, Y = 5; // To store the sliced vector valarray<int> ans; // Function Call ans = slicing(arr, X, Y); // Print the sliced vector printResult(ans);}", "e": 29847, "s": 29033, "text": null }, { "code": null, "e": 29855, "s": 29847, "text": "4 2 4 2" }, { "code": null, "e": 29867, "s": 29857, "text": "muheeth17" }, { "code": null, "e": 29878, "s": 29867, "text": "cpp-vector" }, { "code": null, "e": 29885, "s": 29878, "text": "Arrays" }, { "code": null, "e": 29894, "s": 29885, "text": "Articles" }, { "code": null, "e": 29898, "s": 29894, "text": "C++" }, { "code": null, "e": 29911, "s": 29898, "text": "C++ Programs" }, { "code": null, "e": 29918, "s": 29911, "text": "Arrays" }, { "code": null, "e": 29922, "s": 29918, "text": "CPP" }, { "code": null, "e": 30020, "s": 29922, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30088, "s": 30020, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 30132, "s": 30088, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 30180, "s": 30132, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 30203, "s": 30180, "text": "Introduction to Arrays" }, { "code": null, "e": 30235, "s": 30203, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 30285, "s": 30235, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 30332, "s": 30285, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 30368, "s": 30332, "text": "find command in Linux with examples" }, { "code": null, "e": 30396, "s": 30368, "text": "How to write a Pseudo Code?" } ]
Remove first adjacent pairs of similar characters until possible - GeeksforGeeks
27 May, 2021 Given a string Str, the task is to remove first adjacent pairs of similar characters until we can. Note: Remove adjacent characters to get a new string and then again remove adjacent duplicates from the new string and keep repeating this process until all similar adjacent character pairs are removed.Examples: Input: str = “keexxllx” Output: kx Step 0: Remove ee to get “kxxllx” Step 1: Remove xx to get “kllx” Step 2: Remove ll to get “kx” Input: str = “abbaca” Output: ca Approach: Use string’s back() and pop_back() method STL in C++ to solve the above problem. Iterate for every character in the string, and if the adjacent characters are same, then remove the adjacent characters using pop_back() function. At the end, return the final string. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to remove adjacent duplicatesstring removeDuplicates(string S){ string ans = ""; // Iterate for every character // in the string for (auto it : S) { // If ans string is empty or its last // character does not match with the // current character then append this // character to the string if (ans.empty() or ans.back() != it) ans.push_back(it); // Matches with the previous one else if (ans.back() == it) ans.pop_back(); } // Return the answer return ans;} // Driver Codeint main(){ string str = "keexxllx"; cout << removeDuplicates(str);} // Java implementation of the above approachclass GFG{ // Function to remove adjacent duplicates static String removeDuplicates(String S) { String ans = ""; // Iterate for every character // in the string for (int i = 0; i < S.length(); i++) { // If ans string is empty or its last // character does not match with the // current character then append this // character to the string if (ans.isEmpty() || ans.charAt(ans.length() - 1) != S.charAt(i)) ans += S.charAt(i); // Matches with the previous one else if (ans.charAt(ans.length() - 1) == S.charAt(i)) ans = ans.substring(0, ans.length() - 1); } // Return the answer return ans; } // Driver Code public static void main(String[] args) { String str = "keexxllx"; System.out.println(removeDuplicates(str)); }} // This code is contributed by// sanjeev2552 # Python3 implementation of the above approach # Function to remove adjacent duplicatesdef removeDuplicates(S) : ans = ""; # Iterate for every character # in the string for it in S : # If ans string is empty or its last # character does not match with the # current character then append this # character to the string if (ans == "" or ans[-1] != it) : ans += it ; # Matches with the previous one elif (ans[-1] == it) : ans = ans[:-1]; # Return the answer return ans; # Driver Codeif __name__ == "__main__" : string = "keexxllx"; print(removeDuplicates(string)); # This code is contributed by AnkitRai01 // C# implementation of the above approachusing System; class GFG{ // Function to remove adjacent duplicates static String removeDuplicates(String S) { String ans = ""; // Iterate for every character // in the string for (int i = 0; i < S.Length; i++) { // If ans string is empty or its last // character does not match with the // current character then append this // character to the string if (ans == "" || ans[ans.Length - 1] != S[i]) ans += S[i]; // Matches with the previous one else if (ans[ans.Length - 1] == S[i]) ans = ans.Substring(0, ans.Length - 1); } // Return the answer return ans; } // Driver Code public static void Main(String[] args) { String str = "keexxllx"; Console.WriteLine(removeDuplicates(str)); }} // This code is contributed by Rajput-Ji <script> // JavaScript implementation of the above approach // Function to remove adjacent duplicates function removeDuplicates( S) { var ans = ""; // Iterate for every character // in the string for (i = 0; i < S.length; i++) { // If ans string is empty or its last // character does not match with the // current character then append this // character to the string if (ans.length==0 || ans.charAt(ans.length - 1) != S.charAt(i)) ans += S.charAt(i); // Matches with the previous one else if (ans.charAt(ans.length - 1) == S.charAt(i)) ans = ans.substring(0, ans.length - 1); } // Return the answer return ans; } // Driver Code var str = "keexxllx"; document.write(removeDuplicates(str)); // This code contributed by Rajput-Ji </script> kx ankthon sanjeev2552 Rajput-Ji STL C++ Programs Strings Strings STL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Passing a function as a parameter in C++ Program to implement Singly Linked List in C++ using class Const keyword in C++ cout in C++ Dynamic _Cast in C++ Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 25799, "s": 25771, "text": "\n27 May, 2021" }, { "code": null, "e": 26112, "s": 25799, "text": "Given a string Str, the task is to remove first adjacent pairs of similar characters until we can. Note: Remove adjacent characters to get a new string and then again remove adjacent duplicates from the new string and keep repeating this process until all similar adjacent character pairs are removed.Examples: " }, { "code": null, "e": 26278, "s": 26112, "text": "Input: str = “keexxllx” Output: kx Step 0: Remove ee to get “kxxllx” Step 1: Remove xx to get “kllx” Step 2: Remove ll to get “kx” Input: str = “abbaca” Output: ca " }, { "code": null, "e": 26608, "s": 26280, "text": "Approach: Use string’s back() and pop_back() method STL in C++ to solve the above problem. Iterate for every character in the string, and if the adjacent characters are same, then remove the adjacent characters using pop_back() function. At the end, return the final string. Below is the implementation of the above approach: " }, { "code": null, "e": 26612, "s": 26608, "text": "C++" }, { "code": null, "e": 26617, "s": 26612, "text": "Java" }, { "code": null, "e": 26625, "s": 26617, "text": "Python3" }, { "code": null, "e": 26628, "s": 26625, "text": "C#" }, { "code": null, "e": 26639, "s": 26628, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to remove adjacent duplicatesstring removeDuplicates(string S){ string ans = \"\"; // Iterate for every character // in the string for (auto it : S) { // If ans string is empty or its last // character does not match with the // current character then append this // character to the string if (ans.empty() or ans.back() != it) ans.push_back(it); // Matches with the previous one else if (ans.back() == it) ans.pop_back(); } // Return the answer return ans;} // Driver Codeint main(){ string str = \"keexxllx\"; cout << removeDuplicates(str);}", "e": 27381, "s": 26639, "text": null }, { "code": "// Java implementation of the above approachclass GFG{ // Function to remove adjacent duplicates static String removeDuplicates(String S) { String ans = \"\"; // Iterate for every character // in the string for (int i = 0; i < S.length(); i++) { // If ans string is empty or its last // character does not match with the // current character then append this // character to the string if (ans.isEmpty() || ans.charAt(ans.length() - 1) != S.charAt(i)) ans += S.charAt(i); // Matches with the previous one else if (ans.charAt(ans.length() - 1) == S.charAt(i)) ans = ans.substring(0, ans.length() - 1); } // Return the answer return ans; } // Driver Code public static void main(String[] args) { String str = \"keexxllx\"; System.out.println(removeDuplicates(str)); }} // This code is contributed by// sanjeev2552", "e": 28411, "s": 27381, "text": null }, { "code": "# Python3 implementation of the above approach # Function to remove adjacent duplicatesdef removeDuplicates(S) : ans = \"\"; # Iterate for every character # in the string for it in S : # If ans string is empty or its last # character does not match with the # current character then append this # character to the string if (ans == \"\" or ans[-1] != it) : ans += it ; # Matches with the previous one elif (ans[-1] == it) : ans = ans[:-1]; # Return the answer return ans; # Driver Codeif __name__ == \"__main__\" : string = \"keexxllx\"; print(removeDuplicates(string)); # This code is contributed by AnkitRai01", "e": 29121, "s": 28411, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to remove adjacent duplicates static String removeDuplicates(String S) { String ans = \"\"; // Iterate for every character // in the string for (int i = 0; i < S.Length; i++) { // If ans string is empty or its last // character does not match with the // current character then append this // character to the string if (ans == \"\" || ans[ans.Length - 1] != S[i]) ans += S[i]; // Matches with the previous one else if (ans[ans.Length - 1] == S[i]) ans = ans.Substring(0, ans.Length - 1); } // Return the answer return ans; } // Driver Code public static void Main(String[] args) { String str = \"keexxllx\"; Console.WriteLine(removeDuplicates(str)); }} // This code is contributed by Rajput-Ji", "e": 30115, "s": 29121, "text": null }, { "code": "<script> // JavaScript implementation of the above approach // Function to remove adjacent duplicates function removeDuplicates( S) { var ans = \"\"; // Iterate for every character // in the string for (i = 0; i < S.length; i++) { // If ans string is empty or its last // character does not match with the // current character then append this // character to the string if (ans.length==0 || ans.charAt(ans.length - 1) != S.charAt(i)) ans += S.charAt(i); // Matches with the previous one else if (ans.charAt(ans.length - 1) == S.charAt(i)) ans = ans.substring(0, ans.length - 1); } // Return the answer return ans; } // Driver Code var str = \"keexxllx\"; document.write(removeDuplicates(str)); // This code contributed by Rajput-Ji </script>", "e": 31055, "s": 30115, "text": null }, { "code": null, "e": 31058, "s": 31055, "text": "kx" }, { "code": null, "e": 31068, "s": 31060, "text": "ankthon" }, { "code": null, "e": 31080, "s": 31068, "text": "sanjeev2552" }, { "code": null, "e": 31090, "s": 31080, "text": "Rajput-Ji" }, { "code": null, "e": 31094, "s": 31090, "text": "STL" }, { "code": null, "e": 31107, "s": 31094, "text": "C++ Programs" }, { "code": null, "e": 31115, "s": 31107, "text": "Strings" }, { "code": null, "e": 31123, "s": 31115, "text": "Strings" }, { "code": null, "e": 31127, "s": 31123, "text": "STL" }, { "code": null, "e": 31225, "s": 31127, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31266, "s": 31225, "text": "Passing a function as a parameter in C++" }, { "code": null, "e": 31325, "s": 31266, "text": "Program to implement Singly Linked List in C++ using class" }, { "code": null, "e": 31346, "s": 31325, "text": "Const keyword in C++" }, { "code": null, "e": 31358, "s": 31346, "text": "cout in C++" }, { "code": null, "e": 31379, "s": 31358, "text": "Dynamic _Cast in C++" }, { "code": null, "e": 31425, "s": 31379, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 31450, "s": 31425, "text": "Reverse a string in Java" }, { "code": null, "e": 31510, "s": 31450, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 31525, "s": 31510, "text": "C++ Data Types" } ]
Python Dictionary to find mirror characters in a string - GeeksforGeeks
26 May, 2021 Given a string and a number N, we need to mirror the characters from the N-th position up to the length of the string in alphabetical order. In mirror operation, we change ‘a’ to ‘z’, ‘b’ to ‘y’, and so on.Examples: Input : N = 3 paradox Output : paizwlc We mirror characters from position 3 to end. Input : N = 6 pneumonia Output : pneumlmrz We have an existing solution for this problem please refer to Mirror characters of a string link. We can solve this problem in Python using Dictionary Data Structure. The mirror value of ‘a’ is ‘z’,’b’ is ‘y’, etc, so we create a dictionary data structure and one-to-one map reverse sequence of alphabets onto the original sequence of alphabets. Now traverse characters from length k in given string and change characters into their mirror value using a dictionary. Python3 # function to mirror characters of a string def mirrorChars(input,k): # create dictionary original = 'abcdefghijklmnopqrstuvwxyz' reverse = 'zyxwvutsrqponmlkjihgfedcba' dictChars = dict(zip(original,reverse)) # separate out string after length k to change # characters in mirror prefix = input[0:k-1] suffix = input[k-1:] mirror = '' # change into mirror for i in range(0,len(suffix)): mirror = mirror + dictChars[suffix[i]] # concat prefix and mirrored part print (prefix+mirror) # Driver programif __name__ == "__main__": input = 'paradox' k = 3 mirrorChars(input,k) Output: paizwlc rvpooja Python dictionary-programs python-dict Python Strings python-dict Strings Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Write a program to reverse an array or string Reverse a string in Java Write a program to print all permutations of a given string C++ Data Types Longest Common Subsequence | DP-4
[ { "code": null, "e": 26031, "s": 26003, "text": "\n26 May, 2021" }, { "code": null, "e": 26249, "s": 26031, "text": "Given a string and a number N, we need to mirror the characters from the N-th position up to the length of the string in alphabetical order. In mirror operation, we change ‘a’ to ‘z’, ‘b’ to ‘y’, and so on.Examples: " }, { "code": null, "e": 26393, "s": 26249, "text": "Input : N = 3\n paradox\nOutput : paizwlc\nWe mirror characters from position 3 to end.\n\nInput : N = 6\n pneumonia\nOutput : pneumlmrz" }, { "code": null, "e": 26862, "s": 26395, "text": "We have an existing solution for this problem please refer to Mirror characters of a string link. We can solve this problem in Python using Dictionary Data Structure. The mirror value of ‘a’ is ‘z’,’b’ is ‘y’, etc, so we create a dictionary data structure and one-to-one map reverse sequence of alphabets onto the original sequence of alphabets. Now traverse characters from length k in given string and change characters into their mirror value using a dictionary. " }, { "code": null, "e": 26870, "s": 26862, "text": "Python3" }, { "code": "# function to mirror characters of a string def mirrorChars(input,k): # create dictionary original = 'abcdefghijklmnopqrstuvwxyz' reverse = 'zyxwvutsrqponmlkjihgfedcba' dictChars = dict(zip(original,reverse)) # separate out string after length k to change # characters in mirror prefix = input[0:k-1] suffix = input[k-1:] mirror = '' # change into mirror for i in range(0,len(suffix)): mirror = mirror + dictChars[suffix[i]] # concat prefix and mirrored part print (prefix+mirror) # Driver programif __name__ == \"__main__\": input = 'paradox' k = 3 mirrorChars(input,k)", "e": 27508, "s": 26870, "text": null }, { "code": null, "e": 27518, "s": 27508, "text": "Output: " }, { "code": null, "e": 27526, "s": 27518, "text": "paizwlc" }, { "code": null, "e": 27536, "s": 27528, "text": "rvpooja" }, { "code": null, "e": 27563, "s": 27536, "text": "Python dictionary-programs" }, { "code": null, "e": 27575, "s": 27563, "text": "python-dict" }, { "code": null, "e": 27582, "s": 27575, "text": "Python" }, { "code": null, "e": 27590, "s": 27582, "text": "Strings" }, { "code": null, "e": 27602, "s": 27590, "text": "python-dict" }, { "code": null, "e": 27610, "s": 27602, "text": "Strings" }, { "code": null, "e": 27708, "s": 27610, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27726, "s": 27708, "text": "Python Dictionary" }, { "code": null, "e": 27761, "s": 27726, "text": "Read a file line by line in Python" }, { "code": null, "e": 27793, "s": 27761, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27815, "s": 27793, "text": "Enumerate() in Python" }, { "code": null, "e": 27857, "s": 27815, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27903, "s": 27857, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 27928, "s": 27903, "text": "Reverse a string in Java" }, { "code": null, "e": 27988, "s": 27928, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 28003, "s": 27988, "text": "C++ Data Types" } ]
To check a number is palindrome or not without using any extra space - GeeksforGeeks
06 May, 2021 Given a number ‘n’ and our goal is to find out it is palindrome or not without using any extra space. We can’t make a new copy of number .Examples: Input : 2332 Output : Yes it is Palindrome. Explanation: original number = 2332 reversed number = 2332 Both are same hence the number is palindrome. Input :1111 Output :Yes it is Palindrome. Input : 1234 Output : No not Palindrome. A recursive solution is discussed in below post. Check if a number is PalindromeIn this post a different solution is discussed. 1) We can compare the first digit and the last digit, then we repeat the process. 2) For the first digit, we need the order of the number. Say, 12321. Dividing this by 10000 would get us the leading 1. The trailing 1 can be retrieved by taking the mod with 10. 3 ) Now, to reduce this to 232. (12321 % 10000)/10 = (2321)/10 = 232 4 ) And now, the 10000 would need to be reduced by a factor of 100. Here is the implementation of the above algorithm : C++ Java Python3 C# PHP Javascript // C++ program to find number is palindrome// or not without using any extra space#include <bits/stdc++.h>using namespace std;bool isPalindrome(int); bool isPalindrome(int n){ // Find the appropriate divisor // to extract the leading digit int divisor = 1; while (n / divisor >= 10) divisor *= 10; while (n != 0) { int leading = n / divisor; int trailing = n % 10; // If first and last digit // not same return false if (leading != trailing) return false; // Removing the leading and trailing // digit from number n = (n % divisor) / 10; // Reducing divisor by a factor // of 2 as 2 digits are dropped divisor = divisor / 100; } return true;} // Driver codeint main(){ isPalindrome(1001) ? cout << "Yes, it is Palindrome" : cout << "No, not Palindrome"; return 0;} // Java program to find number is palindrome// or not without using any extra spacepublic class GFG{ static boolean isPalindrome(int n) { // Find the appropriate divisor // to extract the leading digit int divisor = 1; while (n / divisor >= 10) divisor *= 10; while (n != 0) { int leading = n / divisor; int trailing = n % 10; // If first and last digit // not same return false if (leading != trailing) return false; // Removing the leading and trailing // digit from number n = (n % divisor) / 10; // Reducing divisor by a factor // of 2 as 2 digits are dropped divisor = divisor / 100; } return true; } // Driver code public static void main(String args[]) { if(isPalindrome(1001)) System.out.println("Yes, it is Palindrome"); else System.out.println("No, not Palindrome"); }}// This code is contributed by Sumit Ghosh # Python program to find number# is palindrome or not without# using any extra space # Function to check if given number# is palindrome or not without# using the extra spacedef isPalindrome(n): # Find the appropriate divisor # to extract the leading digit divisor = 1 while (n / divisor >= 10): divisor *= 10 while (n != 0): leading = n // divisor trailing = n % 10 # If first and last digit # not same return false if (leading != trailing): return False # Removing the leading and # trailing digit from number n = (n % divisor)//10 # Reducing divisor by a factor # of 2 as 2 digits are dropped divisor = divisor/100 return True # Driver codeif(isPalindrome(1001)): print('Yes, it is palindrome')else: print('No, not palindrome') # This code is contributed by Danish Raza // C# program to find number// is palindrome or not without// using any extra spaceusing System; class GFG{ static bool isPalindrome(int n) { // Find the appropriate // divisor to extract // the leading digit int divisor = 1; while (n / divisor >= 10) divisor *= 10; while (n != 0) { int leading = n / divisor; int trailing = n % 10; // If first and last digit // not same return false if (leading != trailing) return false; // Removing the leading and // trailing digit from number n = (n % divisor) / 10; // Reducing divisor by // a factor of 2 as 2 // digits are dropped divisor = divisor / 100; } return true; } // Driver code static public void Main () { if(isPalindrome(1001)) Console.WriteLine("Yes, it " + "is Palindrome"); else Console.WriteLine("No, not " + "Palindrome"); }} // This code is contributed by m_kit <?php// PHP program to find// number is palindrome// or not without using// any extra space function isPalindrome($n){ // Find the appropriate divisor // to extract the leading digit $divisor = 1; while ($n / $divisor >= 10) $divisor *= 10; while ($n != 0) { $leading = floor($n / $divisor); $trailing = $n % 10; // If first and last digit // not same return false if ($leading != $trailing) return false; // Removing the leading and // trailing digit from number $n = ($n % $divisor) / 10; // Reducing divisor by a // factor of 2 as 2 digits // are dropped $divisor = $divisor / 100; } return true;} // Driver codeif(isPalindrome(1001) == true)echo "Yes, it is Palindrome" ;else echo "No, not Palindrome"; // This code is contributed by ajit?> <script>// javascript program to find number is palindrome// or not without using any extra space function isPalindrome(n) { // Find the appropriate divisor // to extract the leading digit var divisor = 1; while (parseInt(n / divisor) >= 10) divisor *= 10; while (n != 0) { var leading = parseInt(n / divisor); var trailing = n % 10; // If first and last digit // not same return false if (leading != trailing) return false; // Removing the leading and trailing // digit from number n = parseInt((n % divisor) / 10); // Reducing divisor by a factor // of 2 as 2 digits are dropped divisor = divisor / 100; } return true; } // Driver code if (isPalindrome(1001)) document.write("Yes, it is Palindrome"); else document.write("No, not Palindrome"); // This code is contributed by todaysgaurav</script> Output: Yes, it is Palindrome This article is contributed by Abhijit Shankhdhar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t todaysgaurav number-digits palindrome Mathematical Mathematical palindrome Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Sieve of Eratosthenes Program to find GCD or HCF of two numbers Program for factorial of a number Print all possible combinations of r elements in a given array of size n Program for Decimal to Binary Conversion The Knight's tour problem | Backtracking-1 Operators in C / C++
[ { "code": null, "e": 26117, "s": 26089, "text": "\n06 May, 2021" }, { "code": null, "e": 26267, "s": 26117, "text": "Given a number ‘n’ and our goal is to find out it is palindrome or not without using any extra space. We can’t make a new copy of number .Examples: " }, { "code": null, "e": 26502, "s": 26267, "text": "Input : 2332\nOutput : Yes it is Palindrome.\nExplanation:\noriginal number = 2332\nreversed number = 2332\nBoth are same hence the number is palindrome.\n\nInput :1111\nOutput :Yes it is Palindrome.\n\nInput : 1234\nOutput : No not Palindrome." }, { "code": null, "e": 26926, "s": 26504, "text": "A recursive solution is discussed in below post. Check if a number is PalindromeIn this post a different solution is discussed. 1) We can compare the first digit and the last digit, then we repeat the process. 2) For the first digit, we need the order of the number. Say, 12321. Dividing this by 10000 would get us the leading 1. The trailing 1 can be retrieved by taking the mod with 10. 3 ) Now, to reduce this to 232. " }, { "code": null, "e": 26964, "s": 26926, "text": "(12321 % 10000)/10 = (2321)/10 = 232 " }, { "code": null, "e": 27086, "s": 26964, "text": "4 ) And now, the 10000 would need to be reduced by a factor of 100. Here is the implementation of the above algorithm : " }, { "code": null, "e": 27090, "s": 27086, "text": "C++" }, { "code": null, "e": 27095, "s": 27090, "text": "Java" }, { "code": null, "e": 27103, "s": 27095, "text": "Python3" }, { "code": null, "e": 27106, "s": 27103, "text": "C#" }, { "code": null, "e": 27110, "s": 27106, "text": "PHP" }, { "code": null, "e": 27121, "s": 27110, "text": "Javascript" }, { "code": "// C++ program to find number is palindrome// or not without using any extra space#include <bits/stdc++.h>using namespace std;bool isPalindrome(int); bool isPalindrome(int n){ // Find the appropriate divisor // to extract the leading digit int divisor = 1; while (n / divisor >= 10) divisor *= 10; while (n != 0) { int leading = n / divisor; int trailing = n % 10; // If first and last digit // not same return false if (leading != trailing) return false; // Removing the leading and trailing // digit from number n = (n % divisor) / 10; // Reducing divisor by a factor // of 2 as 2 digits are dropped divisor = divisor / 100; } return true;} // Driver codeint main(){ isPalindrome(1001) ? cout << \"Yes, it is Palindrome\" : cout << \"No, not Palindrome\"; return 0;}", "e": 28021, "s": 27121, "text": null }, { "code": "// Java program to find number is palindrome// or not without using any extra spacepublic class GFG{ static boolean isPalindrome(int n) { // Find the appropriate divisor // to extract the leading digit int divisor = 1; while (n / divisor >= 10) divisor *= 10; while (n != 0) { int leading = n / divisor; int trailing = n % 10; // If first and last digit // not same return false if (leading != trailing) return false; // Removing the leading and trailing // digit from number n = (n % divisor) / 10; // Reducing divisor by a factor // of 2 as 2 digits are dropped divisor = divisor / 100; } return true; } // Driver code public static void main(String args[]) { if(isPalindrome(1001)) System.out.println(\"Yes, it is Palindrome\"); else System.out.println(\"No, not Palindrome\"); }}// This code is contributed by Sumit Ghosh", "e": 29141, "s": 28021, "text": null }, { "code": "# Python program to find number# is palindrome or not without# using any extra space # Function to check if given number# is palindrome or not without# using the extra spacedef isPalindrome(n): # Find the appropriate divisor # to extract the leading digit divisor = 1 while (n / divisor >= 10): divisor *= 10 while (n != 0): leading = n // divisor trailing = n % 10 # If first and last digit # not same return false if (leading != trailing): return False # Removing the leading and # trailing digit from number n = (n % divisor)//10 # Reducing divisor by a factor # of 2 as 2 digits are dropped divisor = divisor/100 return True # Driver codeif(isPalindrome(1001)): print('Yes, it is palindrome')else: print('No, not palindrome') # This code is contributed by Danish Raza", "e": 30079, "s": 29141, "text": null }, { "code": "// C# program to find number// is palindrome or not without// using any extra spaceusing System; class GFG{ static bool isPalindrome(int n) { // Find the appropriate // divisor to extract // the leading digit int divisor = 1; while (n / divisor >= 10) divisor *= 10; while (n != 0) { int leading = n / divisor; int trailing = n % 10; // If first and last digit // not same return false if (leading != trailing) return false; // Removing the leading and // trailing digit from number n = (n % divisor) / 10; // Reducing divisor by // a factor of 2 as 2 // digits are dropped divisor = divisor / 100; } return true; } // Driver code static public void Main () { if(isPalindrome(1001)) Console.WriteLine(\"Yes, it \" + \"is Palindrome\"); else Console.WriteLine(\"No, not \" + \"Palindrome\"); }} // This code is contributed by m_kit", "e": 31256, "s": 30079, "text": null }, { "code": "<?php// PHP program to find// number is palindrome// or not without using// any extra space function isPalindrome($n){ // Find the appropriate divisor // to extract the leading digit $divisor = 1; while ($n / $divisor >= 10) $divisor *= 10; while ($n != 0) { $leading = floor($n / $divisor); $trailing = $n % 10; // If first and last digit // not same return false if ($leading != $trailing) return false; // Removing the leading and // trailing digit from number $n = ($n % $divisor) / 10; // Reducing divisor by a // factor of 2 as 2 digits // are dropped $divisor = $divisor / 100; } return true;} // Driver codeif(isPalindrome(1001) == true)echo \"Yes, it is Palindrome\" ;else echo \"No, not Palindrome\"; // This code is contributed by ajit?>", "e": 32131, "s": 31256, "text": null }, { "code": "<script>// javascript program to find number is palindrome// or not without using any extra space function isPalindrome(n) { // Find the appropriate divisor // to extract the leading digit var divisor = 1; while (parseInt(n / divisor) >= 10) divisor *= 10; while (n != 0) { var leading = parseInt(n / divisor); var trailing = n % 10; // If first and last digit // not same return false if (leading != trailing) return false; // Removing the leading and trailing // digit from number n = parseInt((n % divisor) / 10); // Reducing divisor by a factor // of 2 as 2 digits are dropped divisor = divisor / 100; } return true; } // Driver code if (isPalindrome(1001)) document.write(\"Yes, it is Palindrome\"); else document.write(\"No, not Palindrome\"); // This code is contributed by todaysgaurav</script>", "e": 33182, "s": 32131, "text": null }, { "code": null, "e": 33192, "s": 33182, "text": "Output: " }, { "code": null, "e": 33214, "s": 33192, "text": "Yes, it is Palindrome" }, { "code": null, "e": 33645, "s": 33214, "text": "This article is contributed by Abhijit Shankhdhar. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 33651, "s": 33645, "text": "jit_t" }, { "code": null, "e": 33664, "s": 33651, "text": "todaysgaurav" }, { "code": null, "e": 33678, "s": 33664, "text": "number-digits" }, { "code": null, "e": 33689, "s": 33678, "text": "palindrome" }, { "code": null, "e": 33702, "s": 33689, "text": "Mathematical" }, { "code": null, "e": 33715, "s": 33702, "text": "Mathematical" }, { "code": null, "e": 33726, "s": 33715, "text": "palindrome" }, { "code": null, "e": 33824, "s": 33726, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33848, "s": 33824, "text": "Merge two sorted arrays" }, { "code": null, "e": 33891, "s": 33848, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 33905, "s": 33891, "text": "Prime Numbers" }, { "code": null, "e": 33927, "s": 33905, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 33969, "s": 33927, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 34003, "s": 33969, "text": "Program for factorial of a number" }, { "code": null, "e": 34076, "s": 34003, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 34117, "s": 34076, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 34160, "s": 34117, "text": "The Knight's tour problem | Backtracking-1" } ]
How to set dropdown and search box in same line using Bootstrap ? - GeeksforGeeks
21 Dec, 2020 A dropdown menu is a type of menu, by using the dropdown menu user can select something from the given predefined set. It is a toggleable menu, which means it appears when the user clicks on the menu. A search box is a type of box in which you can write the string which you want to search. The main aim is to align the dropdown menu and search box in a straight line. Example 1: We will create a navigation bar and create a dropdown menu and search box, which will initially not appear in a straight line. We can use the unordered list “ul” of HTML structure which is in the form of a list. HTML <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <!-- Bootstrap CSS library --> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href= "https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity= "sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous"> <!-- jQuery library --> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"> </script> </head> <body> <!-- Navigation Bar --> <nav class="navbar navbar-expand-sm bg-dark navbar-dark"> <h5 class="navbar-brand">Geeks For Geeks</h5> <ul class="navbar nav ml-auto"> <!-- Dropdown list --> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false" style="color:white;"> Courses </a> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Live courses </a> <a class="dropdown-item" href="#">Online courses </a> </div> </li> <li> <!-- Search Box --> <input type="text" placeholder="Search.."> </li> </ul> </nav> </body> </html> Output: Example 2: HTML <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <!-- Bootstrap CSS library --> <link rel="stylesheet" href= "https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css"> <link rel="stylesheet" href= "https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity= "sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/" crossorigin="anonymous"> <!-- jQuery library --> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script> <script src= "https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"> </script> <script src= "https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"> </script> </head> <body> <h2 align="Center" style="color:green;"> Dropdown menu and search box without navigation bar </h2> <ul class="navbar nav ml-auto" style="color:white;background-color:green"> <!-- Dropdown list --> <li> <a class="nav-link dropdown-toggle" data-toggle="dropdown" href="#" role="button" aria-haspopup="true" aria-expanded="false" style="color:white;"> Courses </a> <div class="dropdown-menu"> <a class="dropdown-item" href="#">Live courses </a> <a class="dropdown-item" href="#">Online courses </a> </div> <!-- Search Box --> <li> <input class="form-control form-control-sm mr-3 w-75" type="text" placeholder="Search" aria-label="Search"> </li> </li> </ul> </body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Bootstrap-4 Bootstrap-Misc HTML-Misc Picked Bootstrap HTML Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? How to keep gap between columns using Bootstrap? Tailwind CSS vs Bootstrap Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 26937, "s": 26906, "text": " \n21 Dec, 2020\n" }, { "code": null, "e": 27228, "s": 26937, "text": "A dropdown menu is a type of menu, by using the dropdown menu user can select something from the given predefined set. It is a toggleable menu, which means it appears when the user clicks on the menu. A search box is a type of box in which you can write the string which you want to search." }, { "code": null, "e": 27306, "s": 27228, "text": "The main aim is to align the dropdown menu and search box in a straight line." }, { "code": null, "e": 27529, "s": 27306, "text": "Example 1: We will create a navigation bar and create a dropdown menu and search box, which will initially not appear in a straight line. We can use the unordered list “ul” of HTML structure which is in the form of a list." }, { "code": null, "e": 27534, "s": 27529, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html> \n \n<head> \n <meta charset=\"utf-8\"> \n <meta name=\"viewport\" content= \n \"width=device-width, initial-scale=1\"> \n \n <!-- Bootstrap CSS library -->\n <link rel=\"stylesheet\" href= \n\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\"> \n \n <link rel=\"stylesheet\" href= \n\"https://use.fontawesome.com/releases/v5.6.3/css/all.css\"\n integrity= \n\"sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/\"\n crossorigin=\"anonymous\"> \n \n <!-- jQuery library -->\n <script src= \n\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> \n </script> \n \n <script src= \n\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> \n </script> \n \n <script src= \n\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\"> \n </script> \n</head> \n \n<body> \n \n <!-- Navigation Bar -->\n <nav class=\"navbar navbar-expand-sm \n bg-dark navbar-dark\"> \n \n <h5 class=\"navbar-brand\">Geeks For Geeks</h5> \n \n <ul class=\"navbar nav ml-auto\"> \n <!-- Dropdown list -->\n <li class=\"nav-item dropdown\"> \n <a class=\"nav-link dropdown-toggle\" \n data-toggle=\"dropdown\" href=\"#\" \n role=\"button\" aria-haspopup=\"true\"\n aria-expanded=\"false\" \n style=\"color:white;\"> \n Courses \n </a> \n \n <div class=\"dropdown-menu\"> \n <a class=\"dropdown-item\" \n href=\"#\">Live courses \n </a> \n \n <a class=\"dropdown-item\" \n href=\"#\">Online courses \n </a> \n </div> \n </li> \n <li> \n <!-- Search Box -->\n <input type=\"text\" placeholder=\"Search..\"> \n </li> \n </ul> \n </nav> \n</body> \n \n</html> \n\n\n\n\n\n", "e": 29583, "s": 27544, "text": null }, { "code": null, "e": 29591, "s": 29583, "text": "Output:" }, { "code": null, "e": 29602, "s": 29591, "text": "Example 2:" }, { "code": null, "e": 29607, "s": 29602, "text": "HTML" }, { "code": "\n\n\n\n\n\n\n<!DOCTYPE html> \n<html> \n \n<head> \n <meta charset=\"utf-8\"> \n <meta name=\"viewport\" content= \n \"width=device-width, initial-scale=1\"> \n \n <!-- Bootstrap CSS library -->\n <link rel=\"stylesheet\" href= \n\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css\"> \n \n <link rel=\"stylesheet\" href= \n \"https://use.fontawesome.com/releases/v5.6.3/css/all.css\"\n integrity= \n\"sha384-UHRtZLI+pbxtHCWp1t77Bi1L4ZtiqrqD80Kn4Z8NTSRyMA2Fd33n5dQ8lWUE00s/\"\n crossorigin=\"anonymous\"> \n \n <!-- jQuery library -->\n <script src= \n\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> \n </script> \n \n <script src= \n\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js\"> \n </script> \n \n <script src= \n\"https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js\"> \n </script> \n</head> \n \n<body> \n <h2 align=\"Center\" style=\"color:green;\"> \n Dropdown menu and search box \n without navigation bar \n </h2> \n \n <ul class=\"navbar nav ml-auto\" \n style=\"color:white;background-color:green\"> \n <!-- Dropdown list -->\n <li> \n <a class=\"nav-link dropdown-toggle\" \n data-toggle=\"dropdown\" href=\"#\" \n role=\"button\" aria-haspopup=\"true\"\n aria-expanded=\"false\" \n style=\"color:white;\"> \n Courses \n </a> \n \n <div class=\"dropdown-menu\"> \n <a class=\"dropdown-item\" \n href=\"#\">Live courses \n </a> \n \n <a class=\"dropdown-item\" \n href=\"#\">Online courses \n </a> \n </div> \n \n <!-- Search Box -->\n <li> \n <input class=\"form-control \n form-control-sm mr-3 w-75\" \n type=\"text\" placeholder=\"Search\" \n aria-label=\"Search\"> \n </li> \n </li> \n </ul> \n</body> \n \n</html> \n\n\n\n\n\n", "e": 31645, "s": 29617, "text": null }, { "code": null, "e": 31653, "s": 31645, "text": "Output:" }, { "code": null, "e": 31792, "s": 31655, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 31806, "s": 31792, "text": "\nBootstrap-4\n" }, { "code": null, "e": 31823, "s": 31806, "text": "\nBootstrap-Misc\n" }, { "code": null, "e": 31835, "s": 31823, "text": "\nHTML-Misc\n" }, { "code": null, "e": 31844, "s": 31835, "text": "\nPicked\n" }, { "code": null, "e": 31856, "s": 31844, "text": "\nBootstrap\n" }, { "code": null, "e": 31863, "s": 31856, "text": "\nHTML\n" }, { "code": null, "e": 31882, "s": 31863, "text": "\nWeb Technologies\n" }, { "code": null, "e": 32087, "s": 31882, "text": "Writing code in comment? \n Please use ide.geeksforgeeks.org, \n generate link and share the link here.\n " }, { "code": null, "e": 32128, "s": 32087, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 32191, "s": 32128, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 32224, "s": 32191, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 32273, "s": 32224, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 32299, "s": 32273, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 32361, "s": 32299, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 32411, "s": 32361, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 32459, "s": 32411, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32519, "s": 32459, "text": "How to set the default value for an HTML <select> element ?" } ]
How to check the specified rune in Golang String? - GeeksforGeeks
05 Sep, 2019 In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In the Go strings, you are allowed to check the given string contain the specified rune in it using ContainsRune() function. This function returns true if the given string contains the specified rune in it, or this function returns false if the given string does not contain the specified rune. It is defined under the string package so, you have to import string package in your program for accessing ContainsRune function. Syntax: func ContainsRune(str string, r rune) bool Here, str is the string and r is s rune. The return type of this function is bool. Let us discuss this concept with the help of the given examples: Example 1: // Go program to illustrate how to check// the given string containing the runepackage main import ( "fmt" "strings") func main() { // Creating and initializing a string // Using shorthand declaration string_1 := "Welcome to GeeksforGeeks" string_2 := "AppleAppleAppleAppleAppleApple" string_3 := "%G%E%E%K%S" // Creating and initializing rune var r1, r2, r3 rune r1 = 'R' r2 = 'p' r3 = 42 // Check the given string // containing the rune // Using ContainsRune function res1 := strings.ContainsRune(string_1, r1) res2 := strings.ContainsRune(string_2, r2) res3 := strings.ContainsRune(string_3, r3) // Display the results fmt.Printf("String 1: %s , Rune 1: %q , Present or Not: %t", string_1, r1, res1) fmt.Printf("\nString 2: %s , Rune 2: %q , Present or Not: %t", string_2, r2, res2) fmt.Printf("\nString 3: %s , Rune 3: %q , Present or Not: %t", string_3, r3, res3) } Output: String 1: Welcome to GeeksforGeeks , Rune 1: 'R' , Present or Not: false String 2: AppleAppleAppleAppleAppleApple , Rune 2: 'p' , Present or Not: true String 3: %G%E%E%K%S , Rune 3: '*' , Present or Not: false Example 2: // Go program to illustrate how to check// the given string containing the runepackage main import ( "fmt" "strings") func main() { // Creating and Checking the given // rune present in the given string // Using ContainsRune function res1 := strings.ContainsRune("****Welcome, to,"+ " GeeksforGeeks****", 60) res2 := strings.ContainsRune("Learning x how x to "+ "x trim x a x slice of bytes", 'r') res3 := strings.ContainsRune("Geeks,for,Geeks, Geek", 'G') // Display the results fmt.Println("Final Result:") fmt.Println("Result 1: ", res1) fmt.Println("Result 2: ", res2) fmt.Println("Result 3: ", res3) } Output: Final Result: Result 1: false Result 2: true Result 3: true Golang Golang-String Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language Arrays in Go Golang Maps Slices in Golang Different Ways to Find the Type of Variable in Golang Inheritance in GoLang Interfaces in Golang How to Trim a String in Golang? How to compare times in Golang? How to Parse JSON in Golang?
[ { "code": null, "e": 25653, "s": 25625, "text": "\n05 Sep, 2019" }, { "code": null, "e": 26300, "s": 25653, "text": "In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In the Go strings, you are allowed to check the given string contain the specified rune in it using ContainsRune() function. This function returns true if the given string contains the specified rune in it, or this function returns false if the given string does not contain the specified rune. It is defined under the string package so, you have to import string package in your program for accessing ContainsRune function." }, { "code": null, "e": 26308, "s": 26300, "text": "Syntax:" }, { "code": null, "e": 26351, "s": 26308, "text": "func ContainsRune(str string, r rune) bool" }, { "code": null, "e": 26499, "s": 26351, "text": "Here, str is the string and r is s rune. The return type of this function is bool. Let us discuss this concept with the help of the given examples:" }, { "code": null, "e": 26510, "s": 26499, "text": "Example 1:" }, { "code": "// Go program to illustrate how to check// the given string containing the runepackage main import ( \"fmt\" \"strings\") func main() { // Creating and initializing a string // Using shorthand declaration string_1 := \"Welcome to GeeksforGeeks\" string_2 := \"AppleAppleAppleAppleAppleApple\" string_3 := \"%G%E%E%K%S\" // Creating and initializing rune var r1, r2, r3 rune r1 = 'R' r2 = 'p' r3 = 42 // Check the given string // containing the rune // Using ContainsRune function res1 := strings.ContainsRune(string_1, r1) res2 := strings.ContainsRune(string_2, r2) res3 := strings.ContainsRune(string_3, r3) // Display the results fmt.Printf(\"String 1: %s , Rune 1: %q , Present or Not: %t\", string_1, r1, res1) fmt.Printf(\"\\nString 2: %s , Rune 2: %q , Present or Not: %t\", string_2, r2, res2) fmt.Printf(\"\\nString 3: %s , Rune 3: %q , Present or Not: %t\", string_3, r3, res3) }", "e": 27607, "s": 26510, "text": null }, { "code": null, "e": 27615, "s": 27607, "text": "Output:" }, { "code": null, "e": 27826, "s": 27615, "text": "String 1: Welcome to GeeksforGeeks , Rune 1: 'R' , Present or Not: false\nString 2: AppleAppleAppleAppleAppleApple , Rune 2: 'p' , Present or Not: true\nString 3: %G%E%E%K%S , Rune 3: '*' , Present or Not: false\n" }, { "code": null, "e": 27837, "s": 27826, "text": "Example 2:" }, { "code": "// Go program to illustrate how to check// the given string containing the runepackage main import ( \"fmt\" \"strings\") func main() { // Creating and Checking the given // rune present in the given string // Using ContainsRune function res1 := strings.ContainsRune(\"****Welcome, to,\"+ \" GeeksforGeeks****\", 60) res2 := strings.ContainsRune(\"Learning x how x to \"+ \"x trim x a x slice of bytes\", 'r') res3 := strings.ContainsRune(\"Geeks,for,Geeks, Geek\", 'G') // Display the results fmt.Println(\"Final Result:\") fmt.Println(\"Result 1: \", res1) fmt.Println(\"Result 2: \", res2) fmt.Println(\"Result 3: \", res3) }", "e": 28541, "s": 27837, "text": null }, { "code": null, "e": 28549, "s": 28541, "text": "Output:" }, { "code": null, "e": 28613, "s": 28549, "text": "Final Result:\nResult 1: false\nResult 2: true\nResult 3: true\n" }, { "code": null, "e": 28620, "s": 28613, "text": "Golang" }, { "code": null, "e": 28634, "s": 28620, "text": "Golang-String" }, { "code": null, "e": 28646, "s": 28634, "text": "Go Language" }, { "code": null, "e": 28744, "s": 28646, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28790, "s": 28744, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 28803, "s": 28790, "text": "Arrays in Go" }, { "code": null, "e": 28815, "s": 28803, "text": "Golang Maps" }, { "code": null, "e": 28832, "s": 28815, "text": "Slices in Golang" }, { "code": null, "e": 28886, "s": 28832, "text": "Different Ways to Find the Type of Variable in Golang" }, { "code": null, "e": 28908, "s": 28886, "text": "Inheritance in GoLang" }, { "code": null, "e": 28929, "s": 28908, "text": "Interfaces in Golang" }, { "code": null, "e": 28961, "s": 28929, "text": "How to Trim a String in Golang?" }, { "code": null, "e": 28993, "s": 28961, "text": "How to compare times in Golang?" } ]
Introduction to Markov Chains. What are Markov chains, when to use... | by Devin Soni 👑 | Towards Data Science
Markov chains are a fairly common, and relatively simple, way to statistically model random processes. They have been used in many different domains, ranging from text generation to financial modeling. A popular example is r/SubredditSimulator, which uses Markov chains to automate the creation of content for an entire subreddit. Overall, Markov Chains are conceptually quite intuitive, and are very accessible in that they can be implemented without the use of any advanced statistical or mathematical concepts. They are a great way to start learning about probabilistic modeling and data science techniques. To begin, I will describe them with a very common example: Imagine that there were two possible states for weather: sunny or cloudy. You can always directly observe the current weather state, and it is guaranteed to always be one of the two aforementioned states.Now, you decide you want to be able to predict what the weather will be like tomorrow. Intuitively, you assume that there is an inherent transition in this process, in that the current weather has some bearing on what the next day’s weather will be. So, being the dedicated person that you are, you collect weather data over several years, and calculate that the chance of a sunny day occurring after a cloudy day is 0.25. You also note that, by extension, the chance of a cloudy day occurring after a cloudy day must be 0.75, since there are only two possible states.You can now use this distribution to predict weather for days to come, based on what the current weather state is at the time. This example illustrates many of the key concepts of a Markov chain. A Markov chain essentially consists of a set of transitions, which are determined by some probability distribution, that satisfy the Markov property. Observe how in the example, the probability distribution is obtained solely by observing transitions from the current day to the next. This illustrates the Markov property, the unique characteristic of Markov processes that renders them memoryless. This typically leaves them unable to successfully produce sequences in which some underlying trend would be expected to occur. For example, while a Markov chain may be able to mimic the writing style of an author based on word frequencies, it would be unable to produce text that contains deep meaning or thematic significance since these are developed over much longer sequences of text. They therefore lack the ability to produce context-dependent content since they cannot take into account the full chain of prior states. Formally, a Markov chain is a probabilistic automaton. The probability distribution of state transitions is typically represented as the Markov chain’s transition matrix. If the Markov chain has N possible states, the matrix will be an N x N matrix, such that entry (I, J) is the probability of transitioning from state I to state J. Additionally, the transition matrix must be a stochastic matrix, a matrix whose entries in each row must add up to exactly 1. This makes complete sense, since each row represents its own probability distribution. Additionally, a Markov chain also has an initial state vector, represented as an N x 1 matrix (a vector), that describes the probability distribution of starting at each of the N possible states. Entry I of the vector describes the probability of the chain beginning at state I. These two entities are typically all that is needed to represent a Markov chain. We now know how to obtain the chance of transitioning from one state to another, but how about finding the chance of that transition occurring over multiple steps? To formalize this, we now want to determine the probability of moving from state I to state J over M steps. As it turns out, this is actually very simple to find out. Given a transition matrix P, this can be determined by calculating the value of entry (I, J) of the matrix obtained by raising P to the power of M. For small values of M, this can easily be done by hand with repeated multiplication. However, for large values of M, if you are familiar with simple Linear Algebra, a more efficient way to raise a matrix to a power is to first diagonalize the matrix. Now that you know the basics of Markov chains, you should now be able to easily implement them in a language of your choice. If coding is not your forte, there are also many more advanced properties of Markov chains and Markov processes to dive into. In my opinion, the natural progression along the theory route would be toward Hidden Markov Processes or MCMC. Simple Markov chains are the building blocks of other, more sophisticated, modeling techniques, so with this knowledge, you can now move onto various techniques within topics such as belief modeling and sampling.
[ { "code": null, "e": 782, "s": 171, "text": "Markov chains are a fairly common, and relatively simple, way to statistically model random processes. They have been used in many different domains, ranging from text generation to financial modeling. A popular example is r/SubredditSimulator, which uses Markov chains to automate the creation of content for an entire subreddit. Overall, Markov Chains are conceptually quite intuitive, and are very accessible in that they can be implemented without the use of any advanced statistical or mathematical concepts. They are a great way to start learning about probabilistic modeling and data science techniques." }, { "code": null, "e": 841, "s": 782, "text": "To begin, I will describe them with a very common example:" }, { "code": null, "e": 1740, "s": 841, "text": "Imagine that there were two possible states for weather: sunny or cloudy. You can always directly observe the current weather state, and it is guaranteed to always be one of the two aforementioned states.Now, you decide you want to be able to predict what the weather will be like tomorrow. Intuitively, you assume that there is an inherent transition in this process, in that the current weather has some bearing on what the next day’s weather will be. So, being the dedicated person that you are, you collect weather data over several years, and calculate that the chance of a sunny day occurring after a cloudy day is 0.25. You also note that, by extension, the chance of a cloudy day occurring after a cloudy day must be 0.75, since there are only two possible states.You can now use this distribution to predict weather for days to come, based on what the current weather state is at the time." }, { "code": null, "e": 1959, "s": 1740, "text": "This example illustrates many of the key concepts of a Markov chain. A Markov chain essentially consists of a set of transitions, which are determined by some probability distribution, that satisfy the Markov property." }, { "code": null, "e": 2734, "s": 1959, "text": "Observe how in the example, the probability distribution is obtained solely by observing transitions from the current day to the next. This illustrates the Markov property, the unique characteristic of Markov processes that renders them memoryless. This typically leaves them unable to successfully produce sequences in which some underlying trend would be expected to occur. For example, while a Markov chain may be able to mimic the writing style of an author based on word frequencies, it would be unable to produce text that contains deep meaning or thematic significance since these are developed over much longer sequences of text. They therefore lack the ability to produce context-dependent content since they cannot take into account the full chain of prior states." }, { "code": null, "e": 3281, "s": 2734, "text": "Formally, a Markov chain is a probabilistic automaton. The probability distribution of state transitions is typically represented as the Markov chain’s transition matrix. If the Markov chain has N possible states, the matrix will be an N x N matrix, such that entry (I, J) is the probability of transitioning from state I to state J. Additionally, the transition matrix must be a stochastic matrix, a matrix whose entries in each row must add up to exactly 1. This makes complete sense, since each row represents its own probability distribution." }, { "code": null, "e": 3560, "s": 3281, "text": "Additionally, a Markov chain also has an initial state vector, represented as an N x 1 matrix (a vector), that describes the probability distribution of starting at each of the N possible states. Entry I of the vector describes the probability of the chain beginning at state I." }, { "code": null, "e": 3641, "s": 3560, "text": "These two entities are typically all that is needed to represent a Markov chain." }, { "code": null, "e": 4371, "s": 3641, "text": "We now know how to obtain the chance of transitioning from one state to another, but how about finding the chance of that transition occurring over multiple steps? To formalize this, we now want to determine the probability of moving from state I to state J over M steps. As it turns out, this is actually very simple to find out. Given a transition matrix P, this can be determined by calculating the value of entry (I, J) of the matrix obtained by raising P to the power of M. For small values of M, this can easily be done by hand with repeated multiplication. However, for large values of M, if you are familiar with simple Linear Algebra, a more efficient way to raise a matrix to a power is to first diagonalize the matrix." } ]
How to make text bold, italic and underline using jQuery
To make text bold, italic and underline using jQuery, use the jQuery css() method with the CSS properties font-style, font-weight and text-decoration. You can try to run the following code to learn how to make text bold, italic and underline using jQuery − Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script> $(document).ready(function(){ $("p").on({ mouseenter: function(){ $(this).css({"font-style": "italic", "font-weight": "bold","text-decoration": "underline"}); } }); }); </script> </head> <body> <p>Move the mouse pointer on the text to make text bold, italic and underline.</p> </body> </html>
[ { "code": null, "e": 1319, "s": 1062, "text": "To make text bold, italic and underline using jQuery, use the jQuery css() method with the CSS properties font-style, font-weight and text-decoration. You can try to run the following code to learn how to make text bold, italic and underline using jQuery −" }, { "code": null, "e": 1329, "s": 1319, "text": "Live Demo" }, { "code": null, "e": 1786, "s": 1329, "text": "<!DOCTYPE html>\n<html>\n<head>\n<script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script>\n$(document).ready(function(){\n $(\"p\").on({\n mouseenter: function(){\n $(this).css({\"font-style\": \"italic\", \"font-weight\": \"bold\",\"text-decoration\": \"underline\"});\n }\n }); \n});\n</script>\n</head>\n<body>\n<p>Move the mouse pointer on the text to make text bold, italic and underline.</p>\n</body>\n</html>" } ]
C# | Boolean.Parse() Method - GeeksforGeeks
13 Sep, 2021 This method is used to convert the specified string representation of a logical value to its Boolean equivalent. Syntax: public static bool Parse (string value); Here, the value is the string which contains the value to convert.Return Value: This method returns true if value is equivalent to TrueString false if value is equivalent to FalseString.Exceptions: ArgumentNullException: If the string value is null. FormatException: If the value is not equivalent to TrueString or FalseString. Below programs illustrate the use of Boolean.Parse(String) Method:Example 1: CSHARP // C# program to demonstrate// Boolean.Parse(String)// Methodusing System; class GFG { // Main Method public static void Main() { try { // passing different values // to the method to check checkParse("true"); checkParse("TRUE"); checkParse("false"); checkParse("FALSE"); checkParse(bool.TrueString); checkParse(bool.FalseString); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (FormatException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining checkParse method public static void checkParse(string input) { // declaring bool variable bool val; // getting parsed value val = bool.Parse(input); Console.WriteLine("'{0}' parsed as {1}", input, val); }} 'true' parsed as True 'TRUE' parsed as True 'false' parsed as False 'FALSE' parsed as False 'True' parsed as True 'False' parsed as False Example 2: For ArgumentNullException CSHARP // C# program to demonstrate// Boolean.Parse(String)// Method for ArgumentNullExceptionusing System; class GFG { // Main Method public static void Main() { try { // passing null value as a input checkParse(null); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (FormatException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining checkparse method public static void checkParse(string input) { // declaring bool variable bool val; // getting parsed value val = bool.Parse(input); Console.WriteLine("'{0}' parsed as {1}", input, val); }} Exception Thrown: System.ArgumentNullException Example 3: For FormatException CSharp // C# program to demonstrate// Boolean.Parse(String)// Method for FormatExceptionusing System; class GFG { // Main Methodpublic static void Main() { try { // passing true is not equivalent // to true value as a input checkParse("true"); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (FormatException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } } // Defining checkParse method public static void checkParse(string input) { // declaring bool variable bool val; // getting parsed value val = bool.Parse(input); Console.WriteLine("'{0}' parsed as {1}", input, val); }} Exception Thrown: System.FormatException Note: The value parameter, optionally preceded or trailed by white space, must contain either TrueString or FalseString otherwise, it will throw an exception and the comparison is case-insensitive.Reference: https://docs.microsoft.com/en-us/dotnet/api/system.boolean.parse?view=netframework-4.7.2 surinderdawra388 CSharp Boolean Struct CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C# | Method Overriding C# Dictionary with examples Difference between Ref and Out keywords in C# C# | Delegates Top 50 C# Interview Questions & Answers C# | Constructors Extension Method in C# Introduction to .NET Framework C# | Abstract Classes C# | Class and Object
[ { "code": null, "e": 24161, "s": 24133, "text": "\n13 Sep, 2021" }, { "code": null, "e": 24275, "s": 24161, "text": "This method is used to convert the specified string representation of a logical value to its Boolean equivalent. " }, { "code": null, "e": 24285, "s": 24275, "text": "Syntax: " }, { "code": null, "e": 24326, "s": 24285, "text": "public static bool Parse (string value);" }, { "code": null, "e": 24526, "s": 24326, "text": "Here, the value is the string which contains the value to convert.Return Value: This method returns true if value is equivalent to TrueString false if value is equivalent to FalseString.Exceptions: " }, { "code": null, "e": 24578, "s": 24526, "text": "ArgumentNullException: If the string value is null." }, { "code": null, "e": 24656, "s": 24578, "text": "FormatException: If the value is not equivalent to TrueString or FalseString." }, { "code": null, "e": 24734, "s": 24656, "text": "Below programs illustrate the use of Boolean.Parse(String) Method:Example 1: " }, { "code": null, "e": 24741, "s": 24734, "text": "CSHARP" }, { "code": "// C# program to demonstrate// Boolean.Parse(String)// Methodusing System; class GFG { // Main Method public static void Main() { try { // passing different values // to the method to check checkParse(\"true\"); checkParse(\"TRUE\"); checkParse(\"false\"); checkParse(\"FALSE\"); checkParse(bool.TrueString); checkParse(bool.FalseString); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (FormatException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining checkParse method public static void checkParse(string input) { // declaring bool variable bool val; // getting parsed value val = bool.Parse(input); Console.WriteLine(\"'{0}' parsed as {1}\", input, val); }}", "e": 25769, "s": 24741, "text": null }, { "code": null, "e": 25907, "s": 25769, "text": "'true' parsed as True\n'TRUE' parsed as True\n'false' parsed as False\n'FALSE' parsed as False\n'True' parsed as True\n'False' parsed as False" }, { "code": null, "e": 25946, "s": 25909, "text": "Example 2: For ArgumentNullException" }, { "code": null, "e": 25953, "s": 25946, "text": "CSHARP" }, { "code": "// C# program to demonstrate// Boolean.Parse(String)// Method for ArgumentNullExceptionusing System; class GFG { // Main Method public static void Main() { try { // passing null value as a input checkParse(null); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (FormatException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining checkparse method public static void checkParse(string input) { // declaring bool variable bool val; // getting parsed value val = bool.Parse(input); Console.WriteLine(\"'{0}' parsed as {1}\", input, val); }}", "e": 26796, "s": 25953, "text": null }, { "code": null, "e": 26843, "s": 26796, "text": "Exception Thrown: System.ArgumentNullException" }, { "code": null, "e": 26876, "s": 26845, "text": "Example 3: For FormatException" }, { "code": null, "e": 26883, "s": 26876, "text": "CSharp" }, { "code": "// C# program to demonstrate// Boolean.Parse(String)// Method for FormatExceptionusing System; class GFG { // Main Methodpublic static void Main() { try { // passing true is not equivalent // to true value as a input checkParse(\"true\"); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (FormatException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } } // Defining checkParse method public static void checkParse(string input) { // declaring bool variable bool val; // getting parsed value val = bool.Parse(input); Console.WriteLine(\"'{0}' parsed as {1}\", input, val); }}", "e": 27762, "s": 26883, "text": null }, { "code": null, "e": 27803, "s": 27762, "text": "Exception Thrown: System.FormatException" }, { "code": null, "e": 28014, "s": 27805, "text": "Note: The value parameter, optionally preceded or trailed by white space, must contain either TrueString or FalseString otherwise, it will throw an exception and the comparison is case-insensitive.Reference: " }, { "code": null, "e": 28103, "s": 28014, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.boolean.parse?view=netframework-4.7.2" }, { "code": null, "e": 28120, "s": 28103, "text": "surinderdawra388" }, { "code": null, "e": 28142, "s": 28120, "text": "CSharp Boolean Struct" }, { "code": null, "e": 28156, "s": 28142, "text": "CSharp-method" }, { "code": null, "e": 28159, "s": 28156, "text": "C#" }, { "code": null, "e": 28257, "s": 28159, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28266, "s": 28257, "text": "Comments" }, { "code": null, "e": 28279, "s": 28266, "text": "Old Comments" }, { "code": null, "e": 28302, "s": 28279, "text": "C# | Method Overriding" }, { "code": null, "e": 28330, "s": 28302, "text": "C# Dictionary with examples" }, { "code": null, "e": 28376, "s": 28330, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 28391, "s": 28376, "text": "C# | Delegates" }, { "code": null, "e": 28431, "s": 28391, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28449, "s": 28431, "text": "C# | Constructors" }, { "code": null, "e": 28472, "s": 28449, "text": "Extension Method in C#" }, { "code": null, "e": 28503, "s": 28472, "text": "Introduction to .NET Framework" }, { "code": null, "e": 28525, "s": 28503, "text": "C# | Abstract Classes" } ]
Publishing to Medium From Jupyter Notebooks | by Kurtis Pykes | Towards Data Science
Programmers, we all know the struggle of writing a notebook then having to copy and paste the code into Medium when we write a technical post... HEADACHE! To my delight, and probably yours, I’ve found the package that I believe is the saving grace for our programming on Medium woes. Jupyter-to-Medium was created by a fellow Medium writer Ted Petrou. Ted channelled this frustration into what I believe is a very creative package — Click here to read more. My motivations in this post are quite simple. I aim to demonstrate, as well as test the full capability of the Jupyter-to-Notebook package then add my thoughts on the package and advice for those that decide to adopt it as part of their blogging workflow. Disclaimer: I am not a paid promoter and have not been asked in any way to write this story on Jupyter-to-Medium — I just thought it was a cool idea. Those well versed with Jupyter Notebooks would know that LaTex is a built-in feature — and if you didn’t know, now you know. I constantly find myself having to search for images of mathematical expressions on google (that do not violate any copyright agreements), or in the worst case scenario I’d have to go on paint to design it myself before importing it into Medium as an image. This process can be extremely laborious, talk less of how tedious it is. There have been numerous post I’ve had to delay publishing for up to an hour because I am creating images of my mathematical expressions — A disaster of an idea to not incorporate LaTex into Medium, but if there are justified reasons as to why it’s not (or if I just do not know how to do it) then I take that back. As stated prior, LaTex is a feature of Jupyter Notebooks so I was hoping that when I implement LaTex within the notebook it would automatically be parsed as an image when imported into Medium. But — Clearly this was not the case (above is an example of the LaTex code I wrote in my Jupyter Notebook). Nonetheless, whenever I open a Jupyter Notebook environment it’s usually not for writing LaTex code in a markdown cell. Instead, I generally use the notebook to perform some type of prototyping, visualizations, analysis, etc. Ergo this property not meeting my initial expectation does not in anyway harm the prospects of this package. A very annoying feat of writing technical stories on Medium is when you have to copy and paste all of your code that you have written in your Jupyter Notebook into Medium — thinking about it is getting me even more annoyed! Jupyter-to-Medium translates the code cells we write in our notebook into a code block in Medium once we publish it across. # example of code cell being translated to code block on mediumprint("Hello World")Hello World Pretty cool right! To further extend, when working in our Jupyter Notebook environment we often have some data that we are trying to explore. I’m not sure how others incorporate their DataFrames into their technical blogs, but I have to take a screenshot of each individual DataFrame and crop it so that I can upload it as an image in my Medium story — another process that takes unnecessarily long! Having to screenshot, crop then save before uploading is also quite long and tedious. When the DataFrame has many columns the notebook adds an ellipses to the dataframe and scrollbar for any further columns that... I wanted to see how Jupyter-to-Medium handles this feat and to my joy, I was extremely impressed. In Figure 1 you can see that the ellipses are present but the parser extracted the table and pasted it on Medium in a suitable size. The demo data is from Kaggle Categorical Feature Engineering competition — Click here for access to the Dataset. import pandas as pd df = pd.read_csv("../data/categorical_feature_engineering_raw/train.csv")df.head() I often use Plotly for my visualizations, however when I initially tried to use it for this blog post my post resulted in a 60 minute long read for the exact same content I have in this current post. Upon further inspection, I realised that all my Plotly code had been converted into a long sequence of numbers (I also accidently published this to Towards Data Science — Sorry guys). Long story short, I use Matplotlib for this overview. The failure to incorporate Plotly may upset those that have made a complete switch from static plots to interactive, and those that didn’t even experience matplotlib. But, if you aren’t all that fussy about frameworks, you’ll be fine and matplotlib is pretty easy to learn! Note: I didn’t test Seaborn, so if you do use it please let me know the result. # https://matplotlib.org/api/pyplot_api.htmlimport numpy as npimport matplotlib.pyplot as pltx = np.arange(0, 5, 0.1);y = np.sin(x)plt.plot(x, y)plt.show() # https://matplotlib.org/3.1.1/gallery/images_contours_and_fields/image_annotated_heatmap.htmlvegetables = ["cucumber", "tomato", "lettuce", "asparagus", "potato", "wheat", "barley"]farmers = ["Farmer Joe", "Upland Bros.", "Smith Gardening", "Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp."]harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0], [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0], [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0], [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0], [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0], [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1], [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])fig, ax = plt.subplots(figsize=(8, 10))im = ax.imshow(harvest)# We want to show all ticks...ax.set_xticks(np.arange(len(farmers)))ax.set_yticks(np.arange(len(vegetables)))# ... and label them with the respective list entriesax.set_xticklabels(farmers)ax.set_yticklabels(vegetables)# Rotate the tick labels and set their alignment.plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")# Loop over data dimensions and create text annotations.for i in range(len(vegetables)): for j in range(len(farmers)): text = ax.text(j, i, harvest[i, j], ha="center", va="center", color="w")ax.set_title("Harvest of local farmers (in tons/year)")fig.tight_layout()plt.show() Those of you that follow my stories would know that I love to label my images. If you are wondering whether I labelled the Figures in Jupyter Notebook or Medium — the answer is “I done it on Medium”. Last but not least, animations. I have never used animations before so I thought it may be cool to try it out. # http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-as-interactive-javascript-widgets/from matplotlib import animationfrom IPython.display import Image%matplotlib inlinefig, ax = plt.subplots()ax.set_xlim(( 0, 2))ax.set_ylim((-2, 2))line, = ax.plot([], [], lw=2)def init(): line.set_data([], []) return (line,)def animate(i): x = np.linspace(0, 2, 1000) y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) return (line,)anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=20, blit=True)anim.save('animation.gif', writer='imagemagick', fps=60)print("Static plot")Static plot anim.save('animation.gif', writer='imagemagick', fps=60)Image(url='animation.gif') Note: I did have to import the gif manually, but this may just be a result of my lack of familiarity of using gifs since in the main article Ted done there is a fully working gif there. For full access to the code click on the link below, but beware that the initial upload from my Jupyter Notebook was my first rough draft hence you may notice significant changes from the markdown in the Notebook. github.com I think I have already made my opinion clear — I think the package is very creative and I would truly recommend that everyone that writes technical posts on Medium should avert to using this package. Despite this I would warn anyone that decides to adopt this package to beware that the purpose of Jupyter Notebooks and Medium contrast significantly and this should be taken into account. Sharing on Medium is optimised to make writing more presentable and Jupyter Notebooks is for doing neat explorations. This becomes very apparent when we publish to Medium from our Notebooks since there are going to be quite a few tweaks to do for your Medium story to be presentable — at least in my opinion. I do not think publishing directly from Jupyter Notebooks is a good idea, you’d almost always want to edit the formatting and style (i.e. drop caps). My best advice is to use both of platforms to their strengths thereby you should have an expectation to make adjustments from your initial Jupyter Notebook, but at the same time, it is important to appreciate that the majority of the heavy lifting has been done for you! If you’d like to get in contact with me the best way is via LinkedIn
[ { "code": null, "e": 456, "s": 172, "text": "Programmers, we all know the struggle of writing a notebook then having to copy and paste the code into Medium when we write a technical post... HEADACHE! To my delight, and probably yours, I’ve found the package that I believe is the saving grace for our programming on Medium woes." }, { "code": null, "e": 630, "s": 456, "text": "Jupyter-to-Medium was created by a fellow Medium writer Ted Petrou. Ted channelled this frustration into what I believe is a very creative package — Click here to read more." }, { "code": null, "e": 886, "s": 630, "text": "My motivations in this post are quite simple. I aim to demonstrate, as well as test the full capability of the Jupyter-to-Notebook package then add my thoughts on the package and advice for those that decide to adopt it as part of their blogging workflow." }, { "code": null, "e": 1036, "s": 886, "text": "Disclaimer: I am not a paid promoter and have not been asked in any way to write this story on Jupyter-to-Medium — I just thought it was a cool idea." }, { "code": null, "e": 1419, "s": 1036, "text": "Those well versed with Jupyter Notebooks would know that LaTex is a built-in feature — and if you didn’t know, now you know. I constantly find myself having to search for images of mathematical expressions on google (that do not violate any copyright agreements), or in the worst case scenario I’d have to go on paint to design it myself before importing it into Medium as an image." }, { "code": null, "e": 1808, "s": 1419, "text": "This process can be extremely laborious, talk less of how tedious it is. There have been numerous post I’ve had to delay publishing for up to an hour because I am creating images of my mathematical expressions — A disaster of an idea to not incorporate LaTex into Medium, but if there are justified reasons as to why it’s not (or if I just do not know how to do it) then I take that back." }, { "code": null, "e": 2007, "s": 1808, "text": "As stated prior, LaTex is a feature of Jupyter Notebooks so I was hoping that when I implement LaTex within the notebook it would automatically be parsed as an image when imported into Medium. But —" }, { "code": null, "e": 2109, "s": 2007, "text": "Clearly this was not the case (above is an example of the LaTex code I wrote in my Jupyter Notebook)." }, { "code": null, "e": 2444, "s": 2109, "text": "Nonetheless, whenever I open a Jupyter Notebook environment it’s usually not for writing LaTex code in a markdown cell. Instead, I generally use the notebook to perform some type of prototyping, visualizations, analysis, etc. Ergo this property not meeting my initial expectation does not in anyway harm the prospects of this package." }, { "code": null, "e": 2668, "s": 2444, "text": "A very annoying feat of writing technical stories on Medium is when you have to copy and paste all of your code that you have written in your Jupyter Notebook into Medium — thinking about it is getting me even more annoyed!" }, { "code": null, "e": 2792, "s": 2668, "text": "Jupyter-to-Medium translates the code cells we write in our notebook into a code block in Medium once we publish it across." }, { "code": null, "e": 2887, "s": 2792, "text": "# example of code cell being translated to code block on mediumprint(\"Hello World\")Hello World" }, { "code": null, "e": 2906, "s": 2887, "text": "Pretty cool right!" }, { "code": null, "e": 3287, "s": 2906, "text": "To further extend, when working in our Jupyter Notebook environment we often have some data that we are trying to explore. I’m not sure how others incorporate their DataFrames into their technical blogs, but I have to take a screenshot of each individual DataFrame and crop it so that I can upload it as an image in my Medium story — another process that takes unnecessarily long!" }, { "code": null, "e": 3600, "s": 3287, "text": "Having to screenshot, crop then save before uploading is also quite long and tedious. When the DataFrame has many columns the notebook adds an ellipses to the dataframe and scrollbar for any further columns that... I wanted to see how Jupyter-to-Medium handles this feat and to my joy, I was extremely impressed." }, { "code": null, "e": 3733, "s": 3600, "text": "In Figure 1 you can see that the ellipses are present but the parser extracted the table and pasted it on Medium in a suitable size." }, { "code": null, "e": 3846, "s": 3733, "text": "The demo data is from Kaggle Categorical Feature Engineering competition — Click here for access to the Dataset." }, { "code": null, "e": 3949, "s": 3846, "text": "import pandas as pd df = pd.read_csv(\"../data/categorical_feature_engineering_raw/train.csv\")df.head()" }, { "code": null, "e": 4333, "s": 3949, "text": "I often use Plotly for my visualizations, however when I initially tried to use it for this blog post my post resulted in a 60 minute long read for the exact same content I have in this current post. Upon further inspection, I realised that all my Plotly code had been converted into a long sequence of numbers (I also accidently published this to Towards Data Science — Sorry guys)." }, { "code": null, "e": 4387, "s": 4333, "text": "Long story short, I use Matplotlib for this overview." }, { "code": null, "e": 4661, "s": 4387, "text": "The failure to incorporate Plotly may upset those that have made a complete switch from static plots to interactive, and those that didn’t even experience matplotlib. But, if you aren’t all that fussy about frameworks, you’ll be fine and matplotlib is pretty easy to learn!" }, { "code": null, "e": 4741, "s": 4661, "text": "Note: I didn’t test Seaborn, so if you do use it please let me know the result." }, { "code": null, "e": 4897, "s": 4741, "text": "# https://matplotlib.org/api/pyplot_api.htmlimport numpy as npimport matplotlib.pyplot as pltx = np.arange(0, 5, 0.1);y = np.sin(x)plt.plot(x, y)plt.show()" }, { "code": null, "e": 6341, "s": 4897, "text": "# https://matplotlib.org/3.1.1/gallery/images_contours_and_fields/image_annotated_heatmap.htmlvegetables = [\"cucumber\", \"tomato\", \"lettuce\", \"asparagus\", \"potato\", \"wheat\", \"barley\"]farmers = [\"Farmer Joe\", \"Upland Bros.\", \"Smith Gardening\", \"Agrifun\", \"Organiculture\", \"BioGoods Ltd.\", \"Cornylee Corp.\"]harvest = np.array([[0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0], [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0], [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0], [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0], [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0], [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1], [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]])fig, ax = plt.subplots(figsize=(8, 10))im = ax.imshow(harvest)# We want to show all ticks...ax.set_xticks(np.arange(len(farmers)))ax.set_yticks(np.arange(len(vegetables)))# ... and label them with the respective list entriesax.set_xticklabels(farmers)ax.set_yticklabels(vegetables)# Rotate the tick labels and set their alignment.plt.setp(ax.get_xticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")# Loop over data dimensions and create text annotations.for i in range(len(vegetables)): for j in range(len(farmers)): text = ax.text(j, i, harvest[i, j], ha=\"center\", va=\"center\", color=\"w\")ax.set_title(\"Harvest of local farmers (in tons/year)\")fig.tight_layout()plt.show()" }, { "code": null, "e": 6541, "s": 6341, "text": "Those of you that follow my stories would know that I love to label my images. If you are wondering whether I labelled the Figures in Jupyter Notebook or Medium — the answer is “I done it on Medium”." }, { "code": null, "e": 6652, "s": 6541, "text": "Last but not least, animations. I have never used animations before so I thought it may be cool to try it out." }, { "code": null, "e": 7371, "s": 6652, "text": "# http://louistiao.me/posts/notebooks/embedding-matplotlib-animations-in-jupyter-as-interactive-javascript-widgets/from matplotlib import animationfrom IPython.display import Image%matplotlib inlinefig, ax = plt.subplots()ax.set_xlim(( 0, 2))ax.set_ylim((-2, 2))line, = ax.plot([], [], lw=2)def init(): line.set_data([], []) return (line,)def animate(i): x = np.linspace(0, 2, 1000) y = np.sin(2 * np.pi * (x - 0.01 * i)) line.set_data(x, y) return (line,)anim = animation.FuncAnimation(fig, animate, init_func=init, frames=100, interval=20, blit=True)anim.save('animation.gif', writer='imagemagick', fps=60)print(\"Static plot\")Static plot" }, { "code": null, "e": 7454, "s": 7371, "text": "anim.save('animation.gif', writer='imagemagick', fps=60)Image(url='animation.gif')" }, { "code": null, "e": 7640, "s": 7454, "text": "Note: I did have to import the gif manually, but this may just be a result of my lack of familiarity of using gifs since in the main article Ted done there is a fully working gif there." }, { "code": null, "e": 7854, "s": 7640, "text": "For full access to the code click on the link below, but beware that the initial upload from my Jupyter Notebook was my first rough draft hence you may notice significant changes from the markdown in the Notebook." }, { "code": null, "e": 7865, "s": 7854, "text": "github.com" }, { "code": null, "e": 8254, "s": 7865, "text": "I think I have already made my opinion clear — I think the package is very creative and I would truly recommend that everyone that writes technical posts on Medium should avert to using this package. Despite this I would warn anyone that decides to adopt this package to beware that the purpose of Jupyter Notebooks and Medium contrast significantly and this should be taken into account." }, { "code": null, "e": 8713, "s": 8254, "text": "Sharing on Medium is optimised to make writing more presentable and Jupyter Notebooks is for doing neat explorations. This becomes very apparent when we publish to Medium from our Notebooks since there are going to be quite a few tweaks to do for your Medium story to be presentable — at least in my opinion. I do not think publishing directly from Jupyter Notebooks is a good idea, you’d almost always want to edit the formatting and style (i.e. drop caps)." }, { "code": null, "e": 8984, "s": 8713, "text": "My best advice is to use both of platforms to their strengths thereby you should have an expectation to make adjustments from your initial Jupyter Notebook, but at the same time, it is important to appreciate that the majority of the heavy lifting has been done for you!" } ]
How to set the size of the browser window in Selenium?
We can set the size of the browser window by the following methods − getSize() method getSize() method Javascript executor Javascript executor With setSize() method. 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; import java.util.List; public class BrowserDimension { 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); // maximize the browser driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); // fetching the current window size with getSize() System.out.println(driver.manage().window().getSize()); //Create object of Dimensions class Dimension dm = new Dimension(450,630); //Setting the current window to that dimension driver.manage().window().setSize(dm); driver.close(); } } With Javascript executor. 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; import org.openqa.selenium.JavascriptExecutor; public class BrowserDimensionJS { 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); // maximize the browser driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS); JavascriptExecutor js = (JavascriptExecutor) driver; // set size with window.resizeTo() method js.executeScript("window.resizeTo(450,630);"); driver.close(); } }
[ { "code": null, "e": 1131, "s": 1062, "text": "We can set the size of the browser window by the following methods −" }, { "code": null, "e": 1148, "s": 1131, "text": "getSize() method" }, { "code": null, "e": 1165, "s": 1148, "text": "getSize() method" }, { "code": null, "e": 1185, "s": 1165, "text": "Javascript executor" }, { "code": null, "e": 1205, "s": 1185, "text": "Javascript executor" }, { "code": null, "e": 1228, "s": 1205, "text": "With setSize() method." }, { "code": null, "e": 2229, "s": 1228, "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;\nimport java.util.List;\npublic class BrowserDimension {\n public static void main(String[] args) {\n System.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 // maximize the browser\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n // fetching the current window size with getSize()\n System.out.println(driver.manage().window().getSize());\n //Create object of Dimensions class\n Dimension dm = new Dimension(450,630);\n //Setting the current window to that dimension\n driver.manage().window().setSize(dm);\n driver.close();\n }\n}" }, { "code": null, "e": 2255, "s": 2229, "text": "With Javascript executor." }, { "code": null, "e": 3136, "s": 2255, "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;\nimport org.openqa.selenium.JavascriptExecutor;\npublic class BrowserDimensionJS {\n public static void main(String[] args) {\n System.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 // maximize the browser\n driver.manage().timeouts().implicitlyWait(12, TimeUnit.SECONDS);\n JavascriptExecutor js = (JavascriptExecutor) driver;\n // set size with window.resizeTo() method\n js.executeScript(\"window.resizeTo(450,630);\");\n driver.close();\n }\n}" } ]
Python/STAN Implementation of Multiplicative Marketing Mix Model | by Sibyl He | Towards Data Science
Full code and simulated dataset are posted on my Github repo: https://github.com/sibylhe/mmm_stan The methodology of this project is based on this paper by Google, but is applied to a more complicated, real-world setting, where 1) there are 13 media channels and 46 control variables; 2) models are built in a stacked way. Marketing Mix Model, or Media Mix Model (MMM) is used by advertisers to measure how their media spending contributes to sales, so as to optimize future budget allocation. ROAS (return on ad spend) and mROAS (marginal ROAS) are the key metrics to look at. High ROAS indicates the channel is efficient, high mROAS means increasing spend in the channel will yield a high return based on the current spending level. Procedures 1. Fit a regression model with priors on coefficients, using media channels’ impressions (or spending) and control variables to predict sales; 2. Decompose sales to each media channel’s contribution. Channel contribution is calculated by comparing original sales and predicted sales upon removal of the channel; 3. Compute ROAS and mROAS using channel contribution and spending. Intuition of MMM Offline channel’s influence is hard to track. E.g., a customer saw a TV ad, and made a purchase at store. Media channels’ influences are intertwined. Actual Customer Journey: Multiple TouchpointsA customer saw a product on TV > clicked on a display ad > clicked on a paid search ad > made a purchase of $30. In this case, 3 touchpoints contributed to the conversion, and they should all get credits for this conversion. ​What’s trackable: Last Digital TouchpointUsually, only the last digital touchpoint can be tracked. In this case, SEM, and it will get all credits for this conversion. So, a good attribution model should take into account all the relevant variables leading to conversion.​ Since media channels work interactively, a multiplicative model structure is adopted: Take log of both sides, we get the linear form (log-log model): Constraints on Coefficients 1. Media coefficients are positive. 2. Control variables like discount, macroeconomy, event/retail holiday are expected to have positive impact on sales, their coefficients should also be positive. Media effect on sales may lag behind the original exposure and extend several weeks. The carry-over effect is modeled by Adstock: L: length of the media effect P: peak/delay of the media effect, how many weeks it’s lagging behind first exposure D: decay/retention rate of the media channel, concentration of the effect The media effect of the current weeks is a weighted average of the current week and previous (L− 1) weeks. Adstock Example Adstock with Varying DecayThe higher the decay, the more scattered the effect. Adstock with Varying LengthThe impact of length is relatively minor. In model training, the length could be fixed to 8 weeks or a period long enough for the media effect to finish. import numpy as npimport pandas as pddef apply_adstock(x, L, P, D): ‘’’ params: x: original media variable, array L: length P: peak, delay in effect D: decay, retain rate returns: array, adstocked media variable ‘’’ x = np.append(np.zeros(L-1), x) weights = np.zeros(L) for l in range(L): weight = D**((l-P)**2) weights[L-1-l] = weight adstocked_x = [] for i in range(L-1, len(x)): x_array = x[i-L+1:i+1] xi = sum(x_array * weights)/sum(weights) adstocked_x.append(xi) adstocked_x = np.array(adstocked_x) return adstocked_x After a certain saturation point, increasing spend will yield diminishing marginal return, the channel will be losing efficiency as you keep overspending on it. The diminishing return is modeled by Hill function: K: half-saturation point S: slope Hill function with varying K and S def hill_transform(x, ec, slope): return 1 / (1 + (x / ec)**(-slope)) Dataset Four years’ (209 weeks) records of sales, media impression, and media spending at a weekly level. 1. Media Variables- Media Impression (prefix=’mdip_’): impressions of 13 media channels: direct mail, insert, newspaper, digital audio, radio, TV, digital video, social media, online display, email, SMS, affiliates, SEM.- Media Spending (prefix=’mdsp_’): spending of media channels. 2. Control Variables- Macro Economy (prefix=’me_’): CPI, gas price.- Markdown (prefix=’mrkdn_’): markdown/discount.- Store Count (‘st_ct’)- Retail Holidays (prefix=’hldy_’): one-hot encoded.- Seasonality (prefix=’seas_’): month, with Nov and Dec broke into weeks. One-hot encoded. 3. Sales Variable (‘sales’) df = pd.read_csv(‘data.csv’)# 1. media variables# media impressionmdip_cols=[col for col in df.columns if ‘mdip_’ in col]# media spendingmdsp_cols=[col for col in df.columns if ‘mdsp_’ in col]# 2. control variables# macro economics variablesme_cols = [col for col in df.columns if ‘me_’ in col]# store count variablesst_cols = [‘st_ct’]# markdown/discount variablesmrkdn_cols = [col for col in df.columns if ‘mrkdn_’ in col]# holiday variableshldy_cols = [col for col in df.columns if ‘hldy_’ in col]# seasonality variablesseas_cols = [col for col in df.columns if ‘seas_’ in col]base_vars = me_cols+st_cols+mrkdn_cols+va_cols+hldy_cols+seas_cols# 3. sales variablessales_cols =[‘sales’] The model is built in a stacked way. Three models are trained: - Control Model- Marketing Mix Model- Diminishing Return Model Goal: predict base sales (X_ctrl) as an input variable to MMM, this represents the baseline sales trend without any marketing activities. X1: control variables positively related to sales, including macro economy, store count, markdown, holiday. X2: control variables that may have either positive or negtive impact on sales: seasonality. Target variable: ln(sales). The variables are centralized by mean. Priors import pystanimport osos.environ[‘CC’] = ‘gcc-10’os.environ[‘CXX’] = ‘g++-10’# helper functionsdef apply_mean_center(x): mu = np.mean(x) xm = x/mu return xm, mudef mean_center_trandform(df, cols): df_new = pd.DataFrame() sc = {} for col in cols: x = df[col].values df_new[col], mu = apply_mean_center(x) sc[col] = mu return df_new, scdef mean_log1p_trandform(df, cols): df_new = pd.DataFrame() sc = {} for col in cols: x = df[col].values xm, mu = apply_mean_center(x) sc[col] = mu df_new[col] = np.log1p(xm) return df_new, sc# mean-centralize: sales, numeric base_varsdf_ctrl, sc_ctrl = mean_center_trandform(df, [‘sales’]+me_cols+st_cols+mrkdn_cols)df_ctrl = pd.concat([df_ctrl, df[hldy_cols+seas_cols]], axis=1)# variables positively related to sales: macro economy, store count, markdown, holidaypos_vars = [col for col in base_vars if col not in seas_cols]X1 = df_ctrl[pos_vars].values# variables may have either positive or negtive impact on sales: seasonalitypn_vars = seas_colsX2 = df_ctrl[pn_vars].valuesctrl_data = { ’N’: len(df_ctrl), ‘K1’: len(pos_vars), ‘K2’: len(pn_vars), ‘X1’: X1, ‘X2’: X2, ‘y’: df_ctrl[‘sales’].values, ‘max_intercept’: min(df_ctrl[‘sales’])}ctrl_code1 = ‘’’data { int N; // number of observations int K1; // number of positive predictors int K2; // number of positive/negative predictors real max_intercept; // restrict the intercept to be less than the minimum y matrix[N, K1] X1; matrix[N, K2] X2; vector[N] y; }parameters { vector<lower=0>[K1] beta1; // regression coefficients for X1 (positive) vector[K2] beta2; // regression coefficients for X2 real<lower=0, upper=max_intercept> alpha; // intercept real<lower=0> noise_var; // residual variance}model { // Define the priors beta1 ~ normal(0, 1); beta2 ~ normal(0, 1); noise_var ~ inv_gamma(0.05, 0.05 * 0.01); // The likelihood y ~ normal(X1*beta1 + X2*beta2 + alpha, sqrt(noise_var));}‘’’sm1 = pystan.StanModel(model_code=ctrl_code1, verbose=True)fit1 = sm1.sampling(data=ctrl_data, iter=2000, chains=4)fit1_result = fit1.extract() MAPE of control model: 8.63% Extract control model parameters from the fit object and predict base sales -> df[‘base_sales’] Goal: - Find appropriate adstock parameters for media channels;- Decompose sales to media channels’ contribution (and non-marketing contribution). L: length of media impact P: peak of media impact D: decay of media impact X: adstocked media impression variables and base sales Target variable: ln(sales) Variables are centralized by means. Priors df_mmm, sc_mmm = mean_log1p_trandform(df, [‘sales’, ‘base_sales’])mu_mdip = df[mdip_cols].apply(np.mean, axis=0).valuesmax_lag = 8num_media = len(mdip_cols)X_media = np.concatenate((np.zeros((max_lag-1, num_media)), df[mdip_cols].values), axis=0) # padding zero * (max_lag-1) rowsX_ctrl = df_mmm[‘base_sales’].values.reshape(len(df),1)model_data2 = { ’N’: len(df), ‘max_lag’: max_lag, ‘num_media’: num_media, ‘X_media’: X_media, ‘mu_mdip’: mu_mdip, ‘num_ctrl’: X_ctrl.shape[1], ‘X_ctrl’: X_ctrl, ‘y’: df_mmm[‘sales’].values}model_code2 = ‘’’functions { // the adstock transformation with a vector of weights real Adstock(vector t, row_vector weights) { return dot_product(t, weights) / sum(weights); }}data { // the total number of observations int<lower=1> N; // the vector of sales real y[N]; // the maximum duration of lag effect, in weeks int<lower=1> max_lag; // the number of media channels int<lower=1> num_media; // matrix of media variables matrix[N+max_lag-1, num_media] X_media; // vector of media variables’ mean real mu_mdip[num_media]; // the number of other control variables int<lower=1> num_ctrl; // a matrix of control variables matrix[N, num_ctrl] X_ctrl;}parameters { // residual variance real<lower=0> noise_var; // the intercept real tau; // the coefficients for media variables and base sales vector<lower=0>[num_media+num_ctrl] beta; // the decay and peak parameter for the adstock transformation of // each media vector<lower=0,upper=1>[num_media] decay; vector<lower=0,upper=ceil(max_lag/2)>[num_media] peak;}transformed parameters { // the cumulative media effect after adstock real cum_effect; // matrix of media variables after adstock matrix[N, num_media] X_media_adstocked; // matrix of all predictors matrix[N, num_media+num_ctrl] X; // adstock, mean-center, log1p transformation row_vector[max_lag] lag_weights; for (nn in 1:N) { for (media in 1 : num_media) { for (lag in 1 : max_lag) { lag_weights[max_lag-lag+1] <- pow(decay[media], (lag — 1 — peak[media]) ^ 2); } cum_effect <- Adstock(sub_col(X_media, nn, media, max_lag), lag_weights); X_media_adstocked[nn, media] <- log1p(cum_effect/mu_mdip[media]); } X <- append_col(X_media_adstocked, X_ctrl); } }model { decay ~ beta(3,3); peak ~ uniform(0, ceil(max_lag/2)); tau ~ normal(0, 5); for (i in 1 : num_media+num_ctrl) { beta[i] ~ normal(0, 1); } noise_var ~ inv_gamma(0.05, 0.05 * 0.01); y ~ normal(tau + X * beta, sqrt(noise_var));}‘’’sm2 = pystan.StanModel(model_code=model_code2, verbose=True)fit2 = sm2.sampling(data=model_data2, iter=1000, chains=3)fit2_result = fit2.extract() RMSE (log-log model): 0.04977 MAPE (multiplicative model): 15.71% Distribution of Media Coefficients Adstock Parameters {‘dm’: {‘L’: 8, ‘P’: 0.8147, ‘D’: 0.5048}, ‘inst’: {‘L’: 8, ‘P’: 0.6339, ‘D’: 0.4053}, ‘nsp’: {‘L’: 8, ‘P’: 1.1077, ‘D’: 0.4613}, ‘auddig’: {‘L’: 8, ‘P’: 1.883, ‘D’: 0.5118}, ‘audtr’: {‘L’: 8, ‘P’: 1.9893, ‘D’: 0.5046}, ‘vidtr’: {‘L’: 8, ‘P’: 0.0552, ‘D’: 0.0846}, ‘viddig’: {‘L’: 8, ‘P’: 1.8626, ‘D’: 0.5075}, ‘so’: {‘L’: 8, ‘P’: 1.7027, ‘D’: 0.5046}, ‘on’: {‘L’: 8, ‘P’: 1.4170, ‘D’: 0.4907}, ‘em’: {‘L’: 8, ‘P’: 1.0590, ‘D’: 0.4442}, ‘sms’: {‘L’: 8, ‘P’: 1.8488, ‘D’: 0.5090}, ‘aff’: {‘L’: 8, ‘P’: 0.6019, ‘D’: 0.3989}, ‘sem’: {‘L’: 8, ‘P’: 1.3495, ‘D’: 0.4788}} Notes:- For SEM, P=1.3, D=0.48 does not make a lot of sense to me, because SEM is expected to have an immediate and concentrated impact (P=0, low decay). Same with online display. - Try more specific priors in future models.​ Decompose sales to media channels’ contribution Each media channel’s contribution = total sales — sales upon removal of the channelIn the previous model fitting step, parameters of the log-log model have been found: Plug them into the multiplicative model: Goal: for each channel, find the relationship (fit a Hill function) between spending and contribution, so that ROAS and marginal ROAS can be calculated. x: adstocked media channel spending K: half-saturation point S: shape Target variable: the media channel’s contribution Variables are centralized by means.Priors def create_hill_model_data(df, mc_df, adstock_params, media): y = mc_df[‘mdip_’+media].values L, P, D = adstock_params[media][‘L’], adstock_params[media][‘P’], adstock_params[media][‘D’] x = df[‘mdsp_’+media].values x_adstocked = apply_adstock(x, L, P, D) mu_x, mu_y = x_adstocked.mean(), y.mean() sc = {‘x’: mu_x, ‘y’: mu_y} x = x_adstocked/mu_x y = y/mu_y model_data = { ’N’: len(y), ‘y’: y, ‘X’: x } return model_data, scmodel_code3 = ‘’’functions { // the Hill function real Hill(real t, real ec, real slope) { return 1 / (1 + (t / ec)^(-slope)); }}data { // the total number of observations int<lower=1> N; // y: vector of media contribution vector[N] y; // X: vector of adstocked media spending vector[N] X;}parameters { // residual variance real<lower=0> noise_var; // regression coefficient real<lower=0> beta_hill; // ec50 and slope for Hill function of the media real<lower=0,upper=1> ec; real<lower=0> slope;}transformed parameters { // a vector of the mean response vector[N] mu; for (i in 1:N) { mu[i] <- beta_hill * Hill(X[i], ec, slope); }}model { slope ~ gamma(3, 1); ec ~ beta(2, 2); beta_hill ~ normal(0, 1); noise_var ~ inv_gamma(0.05, 0.05 * 0.01); y ~ normal(mu, sqrt(noise_var));}‘’’# train hill models for all media channelssm3 = pystan.StanModel(model_code=model_code3, verbose=True)hill_models = {}to_train = [‘dm’, ‘inst’, ‘nsp’, ‘auddig’, ‘audtr’, ‘vidtr’, ‘viddig’, ‘so’, ‘on’, ‘sem’]for media in to_train: print(‘training for media: ‘, media) hill_model = train_hill_model(df, mc_df, adstock_params, media, sm3) hill_models[media] = hill_model Diminishing Return Model Calculate overall ROAS and weekly ROAS- Overall ROAS = total media contribution / total media spending- Weekly ROAS = weekly media contribution / weekly media spending Distribution of Weekly ROAS (Recent 1 Year) Calculate mROAS Marginal ROAS represents the return of incremental spending based on current spending. For example, I’ve spent $100 on SEM, how much sales will the next $1 bring. mROAS is calculated by increasing the current spending level by 1%, the incremental channel contribution over incremental channel spending.1. Current spending level cur_sp is a list of weekly spending in a given period. Next spending level next_sp is increasing cur_sp by 1%.2. Plug cur_sp and next_sp into the Hill function: Current media contribution cur_mc = beta * Hill(cur_sp, K, S) Next-level media contribution next_mc = beta * Hill(next_sp, K, S)3. mROAS = (sum(next_mc) - sum(cur_mc)) / sum(0.01 * cur_sp) Media Channel ContributionAbout 80% sales are contributed by non-marketing factors, media channels contributed 20% sales. Top media contributors: TV (31.18%) Affiliates (19.49%) Insert (6.99%) SEM (6.56%) ROASHigh ROAS: TV (11.04), insert (5.85), online display (4.83)ROAS shows the historic channel efficiency, how much sales $1 channel spend has brought. (y: contribution percentage, x: ROAS, size: contribution percentage) TV: yields both high contribution and ROAS. Followed by insert. Online display: its contribution volume (5.24%) is not large, but its ROAS is high (4.83). SEM: low ROAS (2.06), the channel is a big spender but not quite efficient. mROASHigh mROAS: TV (16.40), insert (9.35), radio (7.00), online display (6.58)Marginal ROAS indicates the future potential of the channel, how much sales will the next $1 spend on this channel bring. The idea of budget optimization is moving money from low mROAS channels to high mROAS channels. Since TV, insert, radio, insert yield high mROAS, SEM has a low mROAS, part of SEM budget will be reallocated to TV, insert, radio, insert. Run simulations with different optimation combinations, for example: SEM: -10%, -20%, -30% TV: +10%, +20%, +30% Insert: +10%, +20%, +30% Radio: +10%, +20%, +30% Online display: +10%, +20%, +30% Plug them into the MMM, see which option leads to the highest total contribution. Note: trivial channels: newspaper, digital audio, digital video, social (spending/impression too small to be qualified, so that their results are not trustworthy). Please check this running list of FAQ. If you have questions, comments, suggestions, and practical problems (when applying this script to your datasets) that are unaddressed in this list, feel free to open a discussion or response to this article. [1] Bayesian Methods for Media Mix Modeling with Carryover and Shape Effects. https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/46001.pdf [2] STAN tutorials: Prior Choice Recommendations. https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations Pystan Workflow. https://mc-stan.org/users/documentation/case-studies/pystan_workflow.html A quick-start introduction to Stan for economists. https://nbviewer.jupyter.org/github/QuantEcon/QuantEcon.notebooks/blob/master/IntroToStan_basics_workflow.ipynb HMC Sampling and STAN. https://education.illinois.edu/docs/default-source/carolyn-anderson/edpsy590ca/lectures/9-hmc-and-stan/hmc_n_stan_post.pdf I previously installed pystan directly using “pip install pystan”, but got “CompileError: command ‘gcc’ failed with exit status 1” when compiling the model. After many tries, the following method works for me. 1. In bash (terminal): (create a stan environment, install pystan, current version is 2.19)conda create -n stan_env python=3.7 -c conda-forgeconda activate stan_envconda install pystan -c conda-forge(install gcc5, pystan 2.19 requires gcc4.9.3 and above)brew install gcc@5(look for ‘gcc-10’, ‘g++-10’)ls /usr/local/bin | grep gccls /usr/local/bin | grep g++2. Open Anaconda Navigator > Home > Applications on: select stan_env as environment, launch Notebook 3. In python: import osos.environ[‘CC’] = ‘gcc-10’os.environ[‘CXX’] = ‘g++-10’ Thanks for reading! If you like this project, please leave a star on my Github for motivation:)
[ { "code": null, "e": 269, "s": 171, "text": "Full code and simulated dataset are posted on my Github repo: https://github.com/sibylhe/mmm_stan" }, { "code": null, "e": 494, "s": 269, "text": "The methodology of this project is based on this paper by Google, but is applied to a more complicated, real-world setting, where 1) there are 13 media channels and 46 control variables; 2) models are built in a stacked way." }, { "code": null, "e": 906, "s": 494, "text": "Marketing Mix Model, or Media Mix Model (MMM) is used by advertisers to measure how their media spending contributes to sales, so as to optimize future budget allocation. ROAS (return on ad spend) and mROAS (marginal ROAS) are the key metrics to look at. High ROAS indicates the channel is efficient, high mROAS means increasing spend in the channel will yield a high return based on the current spending level." }, { "code": null, "e": 917, "s": 906, "text": "Procedures" }, { "code": null, "e": 1060, "s": 917, "text": "1. Fit a regression model with priors on coefficients, using media channels’ impressions (or spending) and control variables to predict sales;" }, { "code": null, "e": 1229, "s": 1060, "text": "2. Decompose sales to each media channel’s contribution. Channel contribution is calculated by comparing original sales and predicted sales upon removal of the channel;" }, { "code": null, "e": 1296, "s": 1229, "text": "3. Compute ROAS and mROAS using channel contribution and spending." }, { "code": null, "e": 1313, "s": 1296, "text": "Intuition of MMM" }, { "code": null, "e": 1419, "s": 1313, "text": "Offline channel’s influence is hard to track. E.g., a customer saw a TV ad, and made a purchase at store." }, { "code": null, "e": 1463, "s": 1419, "text": "Media channels’ influences are intertwined." }, { "code": null, "e": 1733, "s": 1463, "text": "Actual Customer Journey: Multiple TouchpointsA customer saw a product on TV > clicked on a display ad > clicked on a paid search ad > made a purchase of $30. In this case, 3 touchpoints contributed to the conversion, and they should all get credits for this conversion." }, { "code": null, "e": 1901, "s": 1733, "text": "​What’s trackable: Last Digital TouchpointUsually, only the last digital touchpoint can be tracked. In this case, SEM, and it will get all credits for this conversion." }, { "code": null, "e": 2006, "s": 1901, "text": "So, a good attribution model should take into account all the relevant variables leading to conversion.​" }, { "code": null, "e": 2092, "s": 2006, "text": "Since media channels work interactively, a multiplicative model structure is adopted:" }, { "code": null, "e": 2156, "s": 2092, "text": "Take log of both sides, we get the linear form (log-log model):" }, { "code": null, "e": 2184, "s": 2156, "text": "Constraints on Coefficients" }, { "code": null, "e": 2220, "s": 2184, "text": "1. Media coefficients are positive." }, { "code": null, "e": 2382, "s": 2220, "text": "2. Control variables like discount, macroeconomy, event/retail holiday are expected to have positive impact on sales, their coefficients should also be positive." }, { "code": null, "e": 2512, "s": 2382, "text": "Media effect on sales may lag behind the original exposure and extend several weeks. The carry-over effect is modeled by Adstock:" }, { "code": null, "e": 2825, "s": 2512, "text": "L: length of the media effect P: peak/delay of the media effect, how many weeks it’s lagging behind first exposure D: decay/retention rate of the media channel, concentration of the effect The media effect of the current weeks is a weighted average of the current week and previous (L− 1) weeks. Adstock Example" }, { "code": null, "e": 2904, "s": 2825, "text": "Adstock with Varying DecayThe higher the decay, the more scattered the effect." }, { "code": null, "e": 3085, "s": 2904, "text": "Adstock with Varying LengthThe impact of length is relatively minor. In model training, the length could be fixed to 8 weeks or a period long enough for the media effect to finish." }, { "code": null, "e": 3677, "s": 3085, "text": "import numpy as npimport pandas as pddef apply_adstock(x, L, P, D): ‘’’ params: x: original media variable, array L: length P: peak, delay in effect D: decay, retain rate returns: array, adstocked media variable ‘’’ x = np.append(np.zeros(L-1), x) weights = np.zeros(L) for l in range(L): weight = D**((l-P)**2) weights[L-1-l] = weight adstocked_x = [] for i in range(L-1, len(x)): x_array = x[i-L+1:i+1] xi = sum(x_array * weights)/sum(weights) adstocked_x.append(xi) adstocked_x = np.array(adstocked_x) return adstocked_x" }, { "code": null, "e": 3890, "s": 3677, "text": "After a certain saturation point, increasing spend will yield diminishing marginal return, the channel will be losing efficiency as you keep overspending on it. The diminishing return is modeled by Hill function:" }, { "code": null, "e": 3959, "s": 3890, "text": "K: half-saturation point S: slope Hill function with varying K and S" }, { "code": null, "e": 4032, "s": 3959, "text": "def hill_transform(x, ec, slope): return 1 / (1 + (x / ec)**(-slope))" }, { "code": null, "e": 4422, "s": 4032, "text": "Dataset Four years’ (209 weeks) records of sales, media impression, and media spending at a weekly level. 1. Media Variables- Media Impression (prefix=’mdip_’): impressions of 13 media channels: direct mail, insert, newspaper, digital audio, radio, TV, digital video, social media, online display, email, SMS, affiliates, SEM.- Media Spending (prefix=’mdsp_’): spending of media channels." }, { "code": null, "e": 4703, "s": 4422, "text": "2. Control Variables- Macro Economy (prefix=’me_’): CPI, gas price.- Markdown (prefix=’mrkdn_’): markdown/discount.- Store Count (‘st_ct’)- Retail Holidays (prefix=’hldy_’): one-hot encoded.- Seasonality (prefix=’seas_’): month, with Nov and Dec broke into weeks. One-hot encoded." }, { "code": null, "e": 4731, "s": 4703, "text": "3. Sales Variable (‘sales’)" }, { "code": null, "e": 5419, "s": 4731, "text": "df = pd.read_csv(‘data.csv’)# 1. media variables# media impressionmdip_cols=[col for col in df.columns if ‘mdip_’ in col]# media spendingmdsp_cols=[col for col in df.columns if ‘mdsp_’ in col]# 2. control variables# macro economics variablesme_cols = [col for col in df.columns if ‘me_’ in col]# store count variablesst_cols = [‘st_ct’]# markdown/discount variablesmrkdn_cols = [col for col in df.columns if ‘mrkdn_’ in col]# holiday variableshldy_cols = [col for col in df.columns if ‘hldy_’ in col]# seasonality variablesseas_cols = [col for col in df.columns if ‘seas_’ in col]base_vars = me_cols+st_cols+mrkdn_cols+va_cols+hldy_cols+seas_cols# 3. sales variablessales_cols =[‘sales’]" }, { "code": null, "e": 5545, "s": 5419, "text": "The model is built in a stacked way. Three models are trained: - Control Model- Marketing Mix Model- Diminishing Return Model" }, { "code": null, "e": 5683, "s": 5545, "text": "Goal: predict base sales (X_ctrl) as an input variable to MMM, this represents the baseline sales trend without any marketing activities." }, { "code": null, "e": 5958, "s": 5683, "text": "X1: control variables positively related to sales, including macro economy, store count, markdown, holiday. X2: control variables that may have either positive or negtive impact on sales: seasonality. Target variable: ln(sales). The variables are centralized by mean. Priors" }, { "code": null, "e": 8057, "s": 5958, "text": "import pystanimport osos.environ[‘CC’] = ‘gcc-10’os.environ[‘CXX’] = ‘g++-10’# helper functionsdef apply_mean_center(x): mu = np.mean(x) xm = x/mu return xm, mudef mean_center_trandform(df, cols): df_new = pd.DataFrame() sc = {} for col in cols: x = df[col].values df_new[col], mu = apply_mean_center(x) sc[col] = mu return df_new, scdef mean_log1p_trandform(df, cols): df_new = pd.DataFrame() sc = {} for col in cols: x = df[col].values xm, mu = apply_mean_center(x) sc[col] = mu df_new[col] = np.log1p(xm) return df_new, sc# mean-centralize: sales, numeric base_varsdf_ctrl, sc_ctrl = mean_center_trandform(df, [‘sales’]+me_cols+st_cols+mrkdn_cols)df_ctrl = pd.concat([df_ctrl, df[hldy_cols+seas_cols]], axis=1)# variables positively related to sales: macro economy, store count, markdown, holidaypos_vars = [col for col in base_vars if col not in seas_cols]X1 = df_ctrl[pos_vars].values# variables may have either positive or negtive impact on sales: seasonalitypn_vars = seas_colsX2 = df_ctrl[pn_vars].valuesctrl_data = { ’N’: len(df_ctrl), ‘K1’: len(pos_vars), ‘K2’: len(pn_vars), ‘X1’: X1, ‘X2’: X2, ‘y’: df_ctrl[‘sales’].values, ‘max_intercept’: min(df_ctrl[‘sales’])}ctrl_code1 = ‘’’data { int N; // number of observations int K1; // number of positive predictors int K2; // number of positive/negative predictors real max_intercept; // restrict the intercept to be less than the minimum y matrix[N, K1] X1; matrix[N, K2] X2; vector[N] y; }parameters { vector<lower=0>[K1] beta1; // regression coefficients for X1 (positive) vector[K2] beta2; // regression coefficients for X2 real<lower=0, upper=max_intercept> alpha; // intercept real<lower=0> noise_var; // residual variance}model { // Define the priors beta1 ~ normal(0, 1); beta2 ~ normal(0, 1); noise_var ~ inv_gamma(0.05, 0.05 * 0.01); // The likelihood y ~ normal(X1*beta1 + X2*beta2 + alpha, sqrt(noise_var));}‘’’sm1 = pystan.StanModel(model_code=ctrl_code1, verbose=True)fit1 = sm1.sampling(data=ctrl_data, iter=2000, chains=4)fit1_result = fit1.extract()" }, { "code": null, "e": 8086, "s": 8057, "text": "MAPE of control model: 8.63%" }, { "code": null, "e": 8182, "s": 8086, "text": "Extract control model parameters from the fit object and predict base sales -> df[‘base_sales’]" }, { "code": null, "e": 8188, "s": 8182, "text": "Goal:" }, { "code": null, "e": 8329, "s": 8188, "text": "- Find appropriate adstock parameters for media channels;- Decompose sales to media channels’ contribution (and non-marketing contribution)." }, { "code": null, "e": 8529, "s": 8329, "text": "L: length of media impact P: peak of media impact D: decay of media impact X: adstocked media impression variables and base sales Target variable: ln(sales) Variables are centralized by means. Priors" }, { "code": null, "e": 11105, "s": 8529, "text": "df_mmm, sc_mmm = mean_log1p_trandform(df, [‘sales’, ‘base_sales’])mu_mdip = df[mdip_cols].apply(np.mean, axis=0).valuesmax_lag = 8num_media = len(mdip_cols)X_media = np.concatenate((np.zeros((max_lag-1, num_media)), df[mdip_cols].values), axis=0) # padding zero * (max_lag-1) rowsX_ctrl = df_mmm[‘base_sales’].values.reshape(len(df),1)model_data2 = { ’N’: len(df), ‘max_lag’: max_lag, ‘num_media’: num_media, ‘X_media’: X_media, ‘mu_mdip’: mu_mdip, ‘num_ctrl’: X_ctrl.shape[1], ‘X_ctrl’: X_ctrl, ‘y’: df_mmm[‘sales’].values}model_code2 = ‘’’functions { // the adstock transformation with a vector of weights real Adstock(vector t, row_vector weights) { return dot_product(t, weights) / sum(weights); }}data { // the total number of observations int<lower=1> N; // the vector of sales real y[N]; // the maximum duration of lag effect, in weeks int<lower=1> max_lag; // the number of media channels int<lower=1> num_media; // matrix of media variables matrix[N+max_lag-1, num_media] X_media; // vector of media variables’ mean real mu_mdip[num_media]; // the number of other control variables int<lower=1> num_ctrl; // a matrix of control variables matrix[N, num_ctrl] X_ctrl;}parameters { // residual variance real<lower=0> noise_var; // the intercept real tau; // the coefficients for media variables and base sales vector<lower=0>[num_media+num_ctrl] beta; // the decay and peak parameter for the adstock transformation of // each media vector<lower=0,upper=1>[num_media] decay; vector<lower=0,upper=ceil(max_lag/2)>[num_media] peak;}transformed parameters { // the cumulative media effect after adstock real cum_effect; // matrix of media variables after adstock matrix[N, num_media] X_media_adstocked; // matrix of all predictors matrix[N, num_media+num_ctrl] X; // adstock, mean-center, log1p transformation row_vector[max_lag] lag_weights; for (nn in 1:N) { for (media in 1 : num_media) { for (lag in 1 : max_lag) { lag_weights[max_lag-lag+1] <- pow(decay[media], (lag — 1 — peak[media]) ^ 2); } cum_effect <- Adstock(sub_col(X_media, nn, media, max_lag), lag_weights); X_media_adstocked[nn, media] <- log1p(cum_effect/mu_mdip[media]); } X <- append_col(X_media_adstocked, X_ctrl); } }model { decay ~ beta(3,3); peak ~ uniform(0, ceil(max_lag/2)); tau ~ normal(0, 5); for (i in 1 : num_media+num_ctrl) { beta[i] ~ normal(0, 1); } noise_var ~ inv_gamma(0.05, 0.05 * 0.01); y ~ normal(tau + X * beta, sqrt(noise_var));}‘’’sm2 = pystan.StanModel(model_code=model_code2, verbose=True)fit2 = sm2.sampling(data=model_data2, iter=1000, chains=3)fit2_result = fit2.extract()" }, { "code": null, "e": 11171, "s": 11105, "text": "RMSE (log-log model): 0.04977 MAPE (multiplicative model): 15.71%" }, { "code": null, "e": 11206, "s": 11171, "text": "Distribution of Media Coefficients" }, { "code": null, "e": 11225, "s": 11206, "text": "Adstock Parameters" }, { "code": null, "e": 11791, "s": 11225, "text": "{‘dm’: {‘L’: 8, ‘P’: 0.8147, ‘D’: 0.5048}, ‘inst’: {‘L’: 8, ‘P’: 0.6339, ‘D’: 0.4053}, ‘nsp’: {‘L’: 8, ‘P’: 1.1077, ‘D’: 0.4613}, ‘auddig’: {‘L’: 8, ‘P’: 1.883, ‘D’: 0.5118}, ‘audtr’: {‘L’: 8, ‘P’: 1.9893, ‘D’: 0.5046}, ‘vidtr’: {‘L’: 8, ‘P’: 0.0552, ‘D’: 0.0846}, ‘viddig’: {‘L’: 8, ‘P’: 1.8626, ‘D’: 0.5075}, ‘so’: {‘L’: 8, ‘P’: 1.7027, ‘D’: 0.5046}, ‘on’: {‘L’: 8, ‘P’: 1.4170, ‘D’: 0.4907}, ‘em’: {‘L’: 8, ‘P’: 1.0590, ‘D’: 0.4442}, ‘sms’: {‘L’: 8, ‘P’: 1.8488, ‘D’: 0.5090}, ‘aff’: {‘L’: 8, ‘P’: 0.6019, ‘D’: 0.3989}, ‘sem’: {‘L’: 8, ‘P’: 1.3495, ‘D’: 0.4788}}" }, { "code": null, "e": 12017, "s": 11791, "text": "Notes:- For SEM, P=1.3, D=0.48 does not make a lot of sense to me, because SEM is expected to have an immediate and concentrated impact (P=0, low decay). Same with online display. - Try more specific priors in future models.​" }, { "code": null, "e": 12065, "s": 12017, "text": "Decompose sales to media channels’ contribution" }, { "code": null, "e": 12233, "s": 12065, "text": "Each media channel’s contribution = total sales — sales upon removal of the channelIn the previous model fitting step, parameters of the log-log model have been found:" }, { "code": null, "e": 12274, "s": 12233, "text": "Plug them into the multiplicative model:" }, { "code": null, "e": 12427, "s": 12274, "text": "Goal: for each channel, find the relationship (fit a Hill function) between spending and contribution, so that ROAS and marginal ROAS can be calculated." }, { "code": null, "e": 12589, "s": 12427, "text": "x: adstocked media channel spending K: half-saturation point S: shape Target variable: the media channel’s contribution Variables are centralized by means.Priors" }, { "code": null, "e": 14215, "s": 12589, "text": "def create_hill_model_data(df, mc_df, adstock_params, media): y = mc_df[‘mdip_’+media].values L, P, D = adstock_params[media][‘L’], adstock_params[media][‘P’], adstock_params[media][‘D’] x = df[‘mdsp_’+media].values x_adstocked = apply_adstock(x, L, P, D) mu_x, mu_y = x_adstocked.mean(), y.mean() sc = {‘x’: mu_x, ‘y’: mu_y} x = x_adstocked/mu_x y = y/mu_y model_data = { ’N’: len(y), ‘y’: y, ‘X’: x } return model_data, scmodel_code3 = ‘’’functions { // the Hill function real Hill(real t, real ec, real slope) { return 1 / (1 + (t / ec)^(-slope)); }}data { // the total number of observations int<lower=1> N; // y: vector of media contribution vector[N] y; // X: vector of adstocked media spending vector[N] X;}parameters { // residual variance real<lower=0> noise_var; // regression coefficient real<lower=0> beta_hill; // ec50 and slope for Hill function of the media real<lower=0,upper=1> ec; real<lower=0> slope;}transformed parameters { // a vector of the mean response vector[N] mu; for (i in 1:N) { mu[i] <- beta_hill * Hill(X[i], ec, slope); }}model { slope ~ gamma(3, 1); ec ~ beta(2, 2); beta_hill ~ normal(0, 1); noise_var ~ inv_gamma(0.05, 0.05 * 0.01); y ~ normal(mu, sqrt(noise_var));}‘’’# train hill models for all media channelssm3 = pystan.StanModel(model_code=model_code3, verbose=True)hill_models = {}to_train = [‘dm’, ‘inst’, ‘nsp’, ‘auddig’, ‘audtr’, ‘vidtr’, ‘viddig’, ‘so’, ‘on’, ‘sem’]for media in to_train: print(‘training for media: ‘, media) hill_model = train_hill_model(df, mc_df, adstock_params, media, sm3) hill_models[media] = hill_model" }, { "code": null, "e": 14240, "s": 14215, "text": "Diminishing Return Model" }, { "code": null, "e": 14408, "s": 14240, "text": "Calculate overall ROAS and weekly ROAS- Overall ROAS = total media contribution / total media spending- Weekly ROAS = weekly media contribution / weekly media spending" }, { "code": null, "e": 14452, "s": 14408, "text": "Distribution of Weekly ROAS (Recent 1 Year)" }, { "code": null, "e": 14468, "s": 14452, "text": "Calculate mROAS" }, { "code": null, "e": 14631, "s": 14468, "text": "Marginal ROAS represents the return of incremental spending based on current spending. For example, I’ve spent $100 on SEM, how much sales will the next $1 bring." }, { "code": null, "e": 15146, "s": 14631, "text": "mROAS is calculated by increasing the current spending level by 1%, the incremental channel contribution over incremental channel spending.1. Current spending level cur_sp is a list of weekly spending in a given period. Next spending level next_sp is increasing cur_sp by 1%.2. Plug cur_sp and next_sp into the Hill function: Current media contribution cur_mc = beta * Hill(cur_sp, K, S) Next-level media contribution next_mc = beta * Hill(next_sp, K, S)3. mROAS = (sum(next_mc) - sum(cur_mc)) / sum(0.01 * cur_sp)" }, { "code": null, "e": 15268, "s": 15146, "text": "Media Channel ContributionAbout 80% sales are contributed by non-marketing factors, media channels contributed 20% sales." }, { "code": null, "e": 15292, "s": 15268, "text": "Top media contributors:" }, { "code": null, "e": 15304, "s": 15292, "text": "TV (31.18%)" }, { "code": null, "e": 15324, "s": 15304, "text": "Affiliates (19.49%)" }, { "code": null, "e": 15339, "s": 15324, "text": "Insert (6.99%)" }, { "code": null, "e": 15351, "s": 15339, "text": "SEM (6.56%)" }, { "code": null, "e": 15503, "s": 15351, "text": "ROASHigh ROAS: TV (11.04), insert (5.85), online display (4.83)ROAS shows the historic channel efficiency, how much sales $1 channel spend has brought." }, { "code": null, "e": 15572, "s": 15503, "text": "(y: contribution percentage, x: ROAS, size: contribution percentage)" }, { "code": null, "e": 15636, "s": 15572, "text": "TV: yields both high contribution and ROAS. Followed by insert." }, { "code": null, "e": 15727, "s": 15636, "text": "Online display: its contribution volume (5.24%) is not large, but its ROAS is high (4.83)." }, { "code": null, "e": 15803, "s": 15727, "text": "SEM: low ROAS (2.06), the channel is a big spender but not quite efficient." }, { "code": null, "e": 16100, "s": 15803, "text": "mROASHigh mROAS: TV (16.40), insert (9.35), radio (7.00), online display (6.58)Marginal ROAS indicates the future potential of the channel, how much sales will the next $1 spend on this channel bring. The idea of budget optimization is moving money from low mROAS channels to high mROAS channels." }, { "code": null, "e": 16240, "s": 16100, "text": "Since TV, insert, radio, insert yield high mROAS, SEM has a low mROAS, part of SEM budget will be reallocated to TV, insert, radio, insert." }, { "code": null, "e": 16309, "s": 16240, "text": "Run simulations with different optimation combinations, for example:" }, { "code": null, "e": 16331, "s": 16309, "text": "SEM: -10%, -20%, -30%" }, { "code": null, "e": 16352, "s": 16331, "text": "TV: +10%, +20%, +30%" }, { "code": null, "e": 16377, "s": 16352, "text": "Insert: +10%, +20%, +30%" }, { "code": null, "e": 16401, "s": 16377, "text": "Radio: +10%, +20%, +30%" }, { "code": null, "e": 16434, "s": 16401, "text": "Online display: +10%, +20%, +30%" }, { "code": null, "e": 16516, "s": 16434, "text": "Plug them into the MMM, see which option leads to the highest total contribution." }, { "code": null, "e": 16680, "s": 16516, "text": "Note: trivial channels: newspaper, digital audio, digital video, social (spending/impression too small to be qualified, so that their results are not trustworthy)." }, { "code": null, "e": 16928, "s": 16680, "text": "Please check this running list of FAQ. If you have questions, comments, suggestions, and practical problems (when applying this script to your datasets) that are unaddressed in this list, feel free to open a discussion or response to this article." }, { "code": null, "e": 17613, "s": 16928, "text": "[1] Bayesian Methods for Media Mix Modeling with Carryover and Shape Effects. https://static.googleusercontent.com/media/research.google.com/en//pubs/archive/46001.pdf [2] STAN tutorials: Prior Choice Recommendations. https://github.com/stan-dev/stan/wiki/Prior-Choice-Recommendations Pystan Workflow. https://mc-stan.org/users/documentation/case-studies/pystan_workflow.html A quick-start introduction to Stan for economists. https://nbviewer.jupyter.org/github/QuantEcon/QuantEcon.notebooks/blob/master/IntroToStan_basics_workflow.ipynb HMC Sampling and STAN. https://education.illinois.edu/docs/default-source/carolyn-anderson/edpsy590ca/lectures/9-hmc-and-stan/hmc_n_stan_post.pdf" }, { "code": null, "e": 17823, "s": 17613, "text": "I previously installed pystan directly using “pip install pystan”, but got “CompileError: command ‘gcc’ failed with exit status 1” when compiling the model. After many tries, the following method works for me." }, { "code": null, "e": 18360, "s": 17823, "text": "1. In bash (terminal): (create a stan environment, install pystan, current version is 2.19)conda create -n stan_env python=3.7 -c conda-forgeconda activate stan_envconda install pystan -c conda-forge(install gcc5, pystan 2.19 requires gcc4.9.3 and above)brew install gcc@5(look for ‘gcc-10’, ‘g++-10’)ls /usr/local/bin | grep gccls /usr/local/bin | grep g++2. Open Anaconda Navigator > Home > Applications on: select stan_env as environment, launch Notebook 3. In python: import osos.environ[‘CC’] = ‘gcc-10’os.environ[‘CXX’] = ‘g++-10’" } ]
Binary Tree to CDLL | Practice | GeeksforGeeks
Given a Binary Tree of N edges. The task is to convert this to a Circular Doubly Linked List(CDLL) in-place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted CDLL. The order of nodes in CDLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (left most node in BT) must be head node of the CDLL. Example 1: Input: 1 / \ 3 2 Output: 3 1 2 2 1 3 Explanation: After converting tree to CDLL when CDLL is is traversed from head to tail and then tail to head, elements are displayed as in the output. Example 2: Input: 10 / \ 20 30 / \ 40 60 Output: 40 20 60 10 30 30 10 60 20 40 Explanation:After converting tree to CDLL, when CDLL is is traversed from head to tail and then tail to head, elements are displayed as in the output. Your Task: You don't have to take input. Complete the function bTreeToCList() that takes root as a parameter and returns the head of the list. The printing is done by the driver code. Constraints: 1 <= N <= 103 1 <= Data of a node <= 104 Expected time complexity: O(N) Expected auxiliary space: O(h) , where h = height of tree 0 prateeks200056 minutes ago class Solution{ private: void solve(Node* root , Node* &head , Node* &tail){ if(!root) return; solve(root->left,head,tail); if(head==NULL){ head = tail = root; }else{ tail->right = root; root->left = tail; tail = root; } solve(root->right,head,tail); } public: //Function to convert binary tree into circular doubly linked list. Node *bTreeToCList(Node *root) { //add code here. Node* head = NULL , *tail=NULL; solve(root,head,tail); if(head!=NULL){ head->left = tail; tail->right = head; } return head; }}; 0 tthakare731 day ago //java solution -> TC -> 1.72 class Solution{ static ArrayList<Node> adj; void triv(Node root){ if(root == null) return; triv(root.left); adj.add(root); triv(root.right); } Node bTreeToClist(Node root){ adj = new ArrayList<>(); triv(root); Node Result = null, dummy = null; for(int i = 0; i < adj.size(); i++){ Node newNode = adj.get(i); if(Result == null){ Result = newNode; dummy = newNode; } else { dummy.right = newNode; newNode.left = dummy; dummy = dummy.right; } if(i == adj.size() - 1){ Result.left = dummy; dummy.right = Result; } } return Result; } } 0 rmn51242 days ago class Solution { public: //Function to convert binary tree into circular doubly linked list. void inorder(Node*root,Node* &head,Node* &prev,int& f){ if(!root) return; inorder(root->left,head,prev,f); if(f==0){ head=root; prev=head; f=1; } else{ prev->right=root; prev->right->left=prev; prev=prev->right; } inorder(root->right,head,prev,f); // only diff is that connect last to head prev->right=head; head->left=prev; } Node *bTreeToCList(Node *root) { int f=0; Node*head=NULL; Node*prev=NULL; inorder(root,head,prev,f); return head; } }; +1 triloki351 week ago Node *prev = NULL; Node *head = NULL; Node *bTreeToCList(Node *root) { if(root==NULL) return NULL; bTreeToCList(root->left); if(prev==NULL) { head = root; } else { prev->right = root; root->left = prev; head->left = root; } prev = root; Node* temp = bTreeToCList(root->right); if(temp==NULL) root->right = head; return head; } 0 subhamk472 weeks ago class Solution{ Node prev = null, tail = null; Node bTreeToClist(Node root) { Node res = convert(root); tail.right=res; res.left=tail; return res; } Node convert(Node root){ if(root==null) { return root; } Node head = convert(root.left); if(prev == null) head = root; else{ prev.right = root; root.left = prev; } prev = root; convert(root.right); if (root.right==null) tail = root; return head; } } -1 cs200152 weeks ago class Solution{ public: //Function to convert binary tree into circular doubly linked list. Node *bTreeToCList(Node *root) { struct Node*head=NULL; struct Node*pre=NULL; if(!root) return NULL; bTreeToCList(root->left); if(!pre){ head=root; } else{ pre->right=root; root->left=pre; } pre=root; bTreeToCList(root->right); pre->right=head; head->left=pre; return head;}}; 0 crawler1 month ago void add(Node *&head, Node *&tail, int dat){ if(!head || !tail){ Node *newnode = new Node(); newnode->data = dat; head = tail = newnode; tail->right = head; head->left = tail; return; } else{ Node *newnode = new Node(); newnode->data = dat; newnode->left = tail; tail->right=newnode; head->left = newnode; newnode->right = head; tail = newnode; } } void inorder(Node *root, Node *&head, Node *&tail){ if(root){ inorder(root->left, head, tail); add(head, tail, root->data); inorder(root->right, head, tail); } } Node *bTreeToCList(Node *root) { if(!root) return nullptr; Node *head = nullptr; Node *tail = nullptr; inorder(root, head, tail); return head; } +1 shirurrohit1 month ago PYTHON - EASY - DLL class Solution: def __init__(self): self.prev = None self.head = None def helper(self, root): if root == None: return self.helper(root.left) if self.head == None: self.head = root else: self.prev.right = root root.left = self.prev self.prev = root self.helper(root.right) def bTreeToClist(self, root): self.helper(root) self.prev.right = self.head self.head.left = self.prev return self.head 0 psadv1 month ago For this problem> we can reduce the complexity of CDLL to just DLL step1: just build DLL during inorder traversal step2: after inorder completion, set tail.right = head and head.left = tail 0 priyeshanand92 months ago class Solution{ public: //Function to convert binary tree into circular doubly linked list. void convert(Node *&prev, Node *&head, Node *root) { if(root==NULL) return; convert(prev,head,root->left); if(prev==NULL){ head=root; prev=root; } else{ prev->right=root; prev->right->left=prev; prev=root; } convert(prev,head,root->right); } Node *bTreeToCList(Node *root) { Node *prev=NULL; Node *head=NULL; convert(prev,head,root); Node *p=head; prev->right=NULL; while(p){ if(p->right==NULL){ p->right=head; head->left=p; break; } p=p->right; } return head; }}; We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 628, "s": 238, "text": "Given a Binary Tree of N edges. The task is to convert this to a Circular Doubly Linked List(CDLL) in-place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted CDLL. The order of nodes in CDLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (left most node in BT) must be head node of the CDLL." }, { "code": null, "e": 639, "s": 628, "text": "Example 1:" }, { "code": null, "e": 848, "s": 639, "text": "Input:\n 1\n / \\\n 3 2\nOutput:\n3 1 2 \n2 1 3\nExplanation: After converting tree to CDLL\nwhen CDLL is is traversed from head to\ntail and then tail to head, elements\nare displayed as in the output.\n" }, { "code": null, "e": 859, "s": 848, "text": "Example 2:" }, { "code": null, "e": 1098, "s": 859, "text": "Input:\n 10\n / \\\n 20 30\n / \\\n40 60\nOutput:\n40 20 60 10 30 \n30 10 60 20 40\nExplanation:After converting tree to CDLL,\nwhen CDLL is is traversed from head to\ntail and then tail to head, elements\nare displayed as in the output." }, { "code": null, "e": 1283, "s": 1098, "text": "Your Task:\nYou don't have to take input. Complete the function bTreeToCList() that takes root as a parameter and returns the head of the list. The printing is done by the driver code. " }, { "code": null, "e": 1337, "s": 1283, "text": "Constraints:\n1 <= N <= 103\n1 <= Data of a node <= 104" }, { "code": null, "e": 1368, "s": 1337, "text": "Expected time complexity: O(N)" }, { "code": null, "e": 1426, "s": 1368, "text": "Expected auxiliary space: O(h) , where h = height of tree" }, { "code": null, "e": 1428, "s": 1426, "text": "0" }, { "code": null, "e": 1455, "s": 1428, "text": "prateeks200056 minutes ago" }, { "code": null, "e": 2103, "s": 1455, "text": "class Solution{ private: void solve(Node* root , Node* &head , Node* &tail){ if(!root) return; solve(root->left,head,tail); if(head==NULL){ head = tail = root; }else{ tail->right = root; root->left = tail; tail = root; } solve(root->right,head,tail); } public: //Function to convert binary tree into circular doubly linked list. Node *bTreeToCList(Node *root) { //add code here. Node* head = NULL , *tail=NULL; solve(root,head,tail); if(head!=NULL){ head->left = tail; tail->right = head; } return head; }};" }, { "code": null, "e": 2105, "s": 2103, "text": "0" }, { "code": null, "e": 2125, "s": 2105, "text": "tthakare731 day ago" }, { "code": null, "e": 3000, "s": 2125, "text": "//java solution -> TC -> 1.72\nclass Solution{\n static ArrayList<Node> adj;\n void triv(Node root){\n if(root == null) return;\n triv(root.left);\n adj.add(root);\n triv(root.right);\n }\n \n Node bTreeToClist(Node root){\n adj = new ArrayList<>();\n triv(root);\n \n Node Result = null, dummy = null;\n for(int i = 0; i < adj.size(); i++){\n Node newNode = adj.get(i);\n \n if(Result == null){\n Result = newNode;\n dummy = newNode;\n } else {\n dummy.right = newNode;\n newNode.left = dummy;\n dummy = dummy.right;\n }\n if(i == adj.size() - 1){\n Result.left = dummy;\n dummy.right = Result;\n }\n }\n return Result;\n }\n}" }, { "code": null, "e": 3002, "s": 3000, "text": "0" }, { "code": null, "e": 3020, "s": 3002, "text": "rmn51242 days ago" }, { "code": null, "e": 3808, "s": 3020, "text": "class Solution\n{\n public:\n //Function to convert binary tree into circular doubly linked list.\n void inorder(Node*root,Node* &head,Node* &prev,int& f){\n if(!root) return;\n inorder(root->left,head,prev,f);\n if(f==0){\n head=root;\n prev=head;\n f=1;\n }\n else{\n prev->right=root;\n prev->right->left=prev;\n prev=prev->right;\n \n }\n inorder(root->right,head,prev,f);\n // only diff is that connect last to head\n prev->right=head;\n head->left=prev;\n }\n \n Node *bTreeToCList(Node *root)\n {\n int f=0;\n Node*head=NULL;\n Node*prev=NULL;\n inorder(root,head,prev,f);\n return head;\n \n }\n};\n" }, { "code": null, "e": 3811, "s": 3808, "text": "+1" }, { "code": null, "e": 3831, "s": 3811, "text": "triloki351 week ago" }, { "code": null, "e": 4333, "s": 3831, "text": "Node *prev = NULL; Node *head = NULL; Node *bTreeToCList(Node *root) { if(root==NULL) return NULL; bTreeToCList(root->left); if(prev==NULL) { head = root; } else { prev->right = root; root->left = prev; head->left = root; } prev = root; Node* temp = bTreeToCList(root->right); if(temp==NULL) root->right = head; return head; }" }, { "code": null, "e": 4335, "s": 4333, "text": "0" }, { "code": null, "e": 4356, "s": 4335, "text": "subhamk472 weeks ago" }, { "code": null, "e": 4888, "s": 4356, "text": "class Solution{ Node prev = null, tail = null; Node bTreeToClist(Node root) { Node res = convert(root); tail.right=res; res.left=tail; return res; } Node convert(Node root){ if(root==null) { return root; } Node head = convert(root.left); if(prev == null) head = root; else{ prev.right = root; root.left = prev; } prev = root; convert(root.right); if (root.right==null) tail = root; return head; } }" }, { "code": null, "e": 4891, "s": 4888, "text": "-1" }, { "code": null, "e": 4910, "s": 4891, "text": "cs200152 weeks ago" }, { "code": null, "e": 5378, "s": 4910, "text": "class Solution{ public: //Function to convert binary tree into circular doubly linked list. Node *bTreeToCList(Node *root) { struct Node*head=NULL; struct Node*pre=NULL; if(!root) return NULL; bTreeToCList(root->left); if(!pre){ head=root; } else{ pre->right=root; root->left=pre; } pre=root; bTreeToCList(root->right); pre->right=head; head->left=pre; return head;}};" }, { "code": null, "e": 5386, "s": 5384, "text": "0" }, { "code": null, "e": 5405, "s": 5386, "text": "crawler1 month ago" }, { "code": null, "e": 6387, "s": 5405, "text": "\tvoid add(Node *&head, Node *&tail, int dat){\n if(!head || !tail){\n Node *newnode = new Node();\n newnode->data = dat;\n head = tail = newnode;\n tail->right = head;\n head->left = tail;\n return;\n }\n else{\n Node *newnode = new Node();\n newnode->data = dat;\n newnode->left = tail;\n tail->right=newnode;\n head->left = newnode;\n newnode->right = head;\n tail = newnode;\n }\n }\n void inorder(Node *root, Node *&head, Node *&tail){\n if(root){\n inorder(root->left, head, tail);\n add(head, tail, root->data);\n inorder(root->right, head, tail);\n }\n }\n Node *bTreeToCList(Node *root)\n {\n if(!root)\n return nullptr;\n Node *head = nullptr;\n Node *tail = nullptr;\n inorder(root, head, tail);\n \n return head;\n }" }, { "code": null, "e": 6390, "s": 6387, "text": "+1" }, { "code": null, "e": 6413, "s": 6390, "text": "shirurrohit1 month ago" }, { "code": null, "e": 6433, "s": 6413, "text": "PYTHON - EASY - DLL" }, { "code": null, "e": 7029, "s": 6435, "text": "class Solution:\n \n def __init__(self):\n self.prev = None\n self.head = None\n \n def helper(self, root):\n if root == None:\n return\n \n self.helper(root.left)\n \n if self.head == None:\n self.head = root\n else:\n self.prev.right = root\n root.left = self.prev\n self.prev = root\n \n self.helper(root.right)\n \n def bTreeToClist(self, root):\n self.helper(root)\n self.prev.right = self.head\n self.head.left = self.prev\n return self.head" }, { "code": null, "e": 7031, "s": 7029, "text": "0" }, { "code": null, "e": 7048, "s": 7031, "text": "psadv1 month ago" }, { "code": null, "e": 7242, "s": 7048, "text": "For this problem> we can reduce the complexity of CDLL to just DLL step1: just build DLL during inorder traversal step2: after inorder completion, set tail.right = head and head.left = tail" }, { "code": null, "e": 7244, "s": 7242, "text": "0" }, { "code": null, "e": 7270, "s": 7244, "text": "priyeshanand92 months ago" }, { "code": null, "e": 8017, "s": 7270, "text": "class Solution{ public: //Function to convert binary tree into circular doubly linked list. void convert(Node *&prev, Node *&head, Node *root) { if(root==NULL) return; convert(prev,head,root->left); if(prev==NULL){ head=root; prev=root; } else{ prev->right=root; prev->right->left=prev; prev=root; } convert(prev,head,root->right); } Node *bTreeToCList(Node *root) { Node *prev=NULL; Node *head=NULL; convert(prev,head,root); Node *p=head; prev->right=NULL; while(p){ if(p->right==NULL){ p->right=head; head->left=p; break; } p=p->right; } return head; }};" }, { "code": null, "e": 8163, "s": 8017, "text": "We strongly recommend solving this problem on your own before viewing its editorial. Do you still\n want to view the editorial?" }, { "code": null, "e": 8199, "s": 8163, "text": " Login to access your submissions. " }, { "code": null, "e": 8209, "s": 8199, "text": "\nProblem\n" }, { "code": null, "e": 8219, "s": 8209, "text": "\nContest\n" }, { "code": null, "e": 8282, "s": 8219, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 8430, "s": 8282, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 8638, "s": 8430, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8744, "s": 8638, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
TreeMap descendingKeySet() Method in Java with Examples - GeeksforGeeks
27 Aug, 2020 The descendingKeySet() method of TreeMap class returns a reverse order NavigableSet view of the keys contained within the map. The iterator of the set returns the keys in descending order. Note: The set is backed by the map, so changes to the map are reflected within the set, and vice-versa. Syntax: public NavigableSet<K> descendingKeySet() Parameters: The method does not take any parameters. Return Value: The method returns a navigable set view of the values contained in the map. Exception: The method does not throw any exceptions. Example 1: Java // Java Program to show the working// of descendingKeySet() Methodimport java.io.*;import java.util.*;public class GFG { public static void main(String[] args) { // creating tree map of Integer and String TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // populating tree map using put() treemap.put(3, "three"); treemap.put(1, "one"); treemap.put(2, "two"); treemap.put(0, "zero"); treemap.put(7, "seven"); treemap.put(6, "six"); // putting values in navigable set // use of descendingKeySet NavigableSet set1 = treemap.descendingKeySet(); System.out.println("Navigable set values are: " + set1); }} Output: Navigable set values are: [7, 6, 3, 2, 1, 0] Example 2: Java // Java Program to show the working// of descendingKeySet() Methodimport java.io.*;import java.util.*;public class GFG { public static void main(String[] args) { // creating tree map of Integer and String TreeMap<Integer, String> geeks = new TreeMap<Integer, String>(); // putting values in navigable set geeks.put(1, "Guru"); geeks.put(2, "Ayush"); geeks.put(3, "Devesh"); geeks.put(4, "Kashish"); System.out.println("TreeMap values :- " + geeks); // use of descendingKeySet NavigableSet nevigableSet = geeks.descendingKeySet(); System.out.println("Reverse key values:- " + nevigableSet); }} Output: TreeMap values :- {1=Guru, 2=Ayush, 3=Devesh, 4=Kashish} Reverse key values:- [4, 3, 2, 1] Java-Collections java-treeset java-treeset-functions Picked Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Functional Interfaces in Java Stream In Java Constructors in Java Different ways of Reading a text file in Java Exceptions in Java Generics in Java Comparator Interface in Java with Examples Strings in Java Difference between Abstract Class and Interface in Java How to remove an element from ArrayList in Java?
[ { "code": null, "e": 23557, "s": 23529, "text": "\n27 Aug, 2020" }, { "code": null, "e": 23747, "s": 23557, "text": "The descendingKeySet() method of TreeMap class returns a reverse order NavigableSet view of the keys contained within the map. The iterator of the set returns the keys in descending order. " }, { "code": null, "e": 23851, "s": 23747, "text": "Note: The set is backed by the map, so changes to the map are reflected within the set, and vice-versa." }, { "code": null, "e": 23859, "s": 23851, "text": "Syntax:" }, { "code": null, "e": 23902, "s": 23859, "text": "public NavigableSet<K> descendingKeySet()\n" }, { "code": null, "e": 23955, "s": 23902, "text": "Parameters: The method does not take any parameters." }, { "code": null, "e": 24045, "s": 23955, "text": "Return Value: The method returns a navigable set view of the values contained in the map." }, { "code": null, "e": 24098, "s": 24045, "text": "Exception: The method does not throw any exceptions." }, { "code": null, "e": 24111, "s": 24098, "text": "Example 1: " }, { "code": null, "e": 24116, "s": 24111, "text": "Java" }, { "code": "// Java Program to show the working// of descendingKeySet() Methodimport java.io.*;import java.util.*;public class GFG { public static void main(String[] args) { // creating tree map of Integer and String TreeMap<Integer, String> treemap = new TreeMap<Integer, String>(); // populating tree map using put() treemap.put(3, \"three\"); treemap.put(1, \"one\"); treemap.put(2, \"two\"); treemap.put(0, \"zero\"); treemap.put(7, \"seven\"); treemap.put(6, \"six\"); // putting values in navigable set // use of descendingKeySet NavigableSet set1 = treemap.descendingKeySet(); System.out.println(\"Navigable set values are: \" + set1); }}", "e": 24881, "s": 24116, "text": null }, { "code": null, "e": 24890, "s": 24881, "text": "Output: " }, { "code": null, "e": 24936, "s": 24890, "text": "Navigable set values are: [7, 6, 3, 2, 1, 0]\n" }, { "code": null, "e": 24949, "s": 24936, "text": "Example 2: " }, { "code": null, "e": 24954, "s": 24949, "text": "Java" }, { "code": "// Java Program to show the working// of descendingKeySet() Methodimport java.io.*;import java.util.*;public class GFG { public static void main(String[] args) { // creating tree map of Integer and String TreeMap<Integer, String> geeks = new TreeMap<Integer, String>(); // putting values in navigable set geeks.put(1, \"Guru\"); geeks.put(2, \"Ayush\"); geeks.put(3, \"Devesh\"); geeks.put(4, \"Kashish\"); System.out.println(\"TreeMap values :- \" + geeks); // use of descendingKeySet NavigableSet nevigableSet = geeks.descendingKeySet(); System.out.println(\"Reverse key values:- \" + nevigableSet); }}", "e": 25691, "s": 24954, "text": null }, { "code": null, "e": 25701, "s": 25691, "text": "Output: " }, { "code": null, "e": 25793, "s": 25701, "text": "TreeMap values :- {1=Guru, 2=Ayush, 3=Devesh, 4=Kashish}\nReverse key values:- [4, 3, 2, 1]\n" }, { "code": null, "e": 25812, "s": 25795, "text": "Java-Collections" }, { "code": null, "e": 25825, "s": 25812, "text": "java-treeset" }, { "code": null, "e": 25848, "s": 25825, "text": "java-treeset-functions" }, { "code": null, "e": 25855, "s": 25848, "text": "Picked" }, { "code": null, "e": 25860, "s": 25855, "text": "Java" }, { "code": null, "e": 25865, "s": 25860, "text": "Java" }, { "code": null, "e": 25882, "s": 25865, "text": "Java-Collections" }, { "code": null, "e": 25980, "s": 25882, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25989, "s": 25980, "text": "Comments" }, { "code": null, "e": 26002, "s": 25989, "text": "Old Comments" }, { "code": null, "e": 26032, "s": 26002, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26047, "s": 26032, "text": "Stream In Java" }, { "code": null, "e": 26068, "s": 26047, "text": "Constructors in Java" }, { "code": null, "e": 26114, "s": 26068, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26133, "s": 26114, "text": "Exceptions in Java" }, { "code": null, "e": 26150, "s": 26133, "text": "Generics in Java" }, { "code": null, "e": 26193, "s": 26150, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 26209, "s": 26193, "text": "Strings in Java" }, { "code": null, "e": 26265, "s": 26209, "text": "Difference between Abstract Class and Interface in Java" } ]
A single query to get the sum of count from different tables in MySQL?
To get the sum of count from different tables, use UNION ALL. Let us first create a table − mysql> create table DemoTable1 -> ( -> Id int, -> Name varchar(30) -> ); Query OK, 0 rows affected (1.55 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1 values(10,'Chris Brown'); Query OK, 1 row affected (0.83 sec) mysql> insert into DemoTable1 values(20,'David Miller'); Query OK, 1 row affected (0.50 sec) mysql> insert into DemoTable1 values(30,'John Adam'); Query OK, 1 row affected (0.83 sec) Display all records from the table using select statement − mysql> select *from DemoTable1; +------+--------------+ | Id | Name | +------+--------------+ | 10 | Chris Brown | | 20 | David Miller | | 30 | John Adam | +------+--------------+ 3 rows in set (0.00 sec) Following is the query to create second table − mysql> create table DemoTable2 -> ( -> Amount int -> ); Query OK, 0 rows affected (1.17 sec) Insert some records in the table using insert command − mysql> insert into DemoTable2 values(100); Query OK, 1 row affected (0.30 sec) mysql> insert into DemoTable2 values(200); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable2 values(300); Query OK, 1 row affected (0.54 sec) Display all records from the table using select statement − mysql> select *from DemoTable2; +--------+ | Amount | +--------+ | 100 | | 200 | | 300 | +--------+ 3 rows in set (0.00 sec) Here is how to get sum of count from different tables in a single query − mysql> select sum(AllCount) AS Total_Count -> from -> ( -> (select count(*) AS AllCount from DemoTable1) -> union all -> (select count(*) AS AllCount from DemoTable2) -> )t; +-------------+ | Total_Count | +-------------+ | 6 | +-------------+ 1 row in set (0.03 sec)
[ { "code": null, "e": 1154, "s": 1062, "text": "To get the sum of count from different tables, use UNION ALL. Let us first create a table −" }, { "code": null, "e": 1264, "s": 1154, "text": "mysql> create table DemoTable1\n-> (\n-> Id int,\n-> Name varchar(30)\n-> );\nQuery OK, 0 rows affected (1.55 sec)" }, { "code": null, "e": 1320, "s": 1264, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1595, "s": 1320, "text": "mysql> insert into DemoTable1 values(10,'Chris Brown');\nQuery OK, 1 row affected (0.83 sec)\nmysql> insert into DemoTable1 values(20,'David Miller');\nQuery OK, 1 row affected (0.50 sec)\nmysql> insert into DemoTable1 values(30,'John Adam');\nQuery OK, 1 row affected (0.83 sec)" }, { "code": null, "e": 1655, "s": 1595, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1687, "s": 1655, "text": "mysql> select *from DemoTable1;" }, { "code": null, "e": 1880, "s": 1687, "text": "+------+--------------+\n| Id | Name |\n+------+--------------+\n| 10 | Chris Brown |\n| 20 | David Miller |\n| 30 | John Adam |\n+------+--------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 1928, "s": 1880, "text": "Following is the query to create second table −" }, { "code": null, "e": 2021, "s": 1928, "text": "mysql> create table DemoTable2\n-> (\n-> Amount int\n-> );\nQuery OK, 0 rows affected (1.17 sec)" }, { "code": null, "e": 2077, "s": 2021, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 2314, "s": 2077, "text": "mysql> insert into DemoTable2 values(100);\nQuery OK, 1 row affected (0.30 sec)\nmysql> insert into DemoTable2 values(200);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable2 values(300);\nQuery OK, 1 row affected (0.54 sec)" }, { "code": null, "e": 2374, "s": 2314, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 2406, "s": 2374, "text": "mysql> select *from DemoTable2;" }, { "code": null, "e": 2508, "s": 2406, "text": "+--------+\n| Amount |\n+--------+\n| 100 |\n| 200 |\n| 300 |\n+--------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2582, "s": 2508, "text": "Here is how to get sum of count from different tables in a single query −" }, { "code": null, "e": 2756, "s": 2582, "text": "mysql> select sum(AllCount) AS Total_Count\n-> from\n-> (\n-> (select count(*) AS AllCount from DemoTable1)\n-> union all\n-> (select count(*) AS AllCount from DemoTable2)\n-> )t;" }, { "code": null, "e": 2860, "s": 2756, "text": "+-------------+\n| Total_Count |\n+-------------+\n| 6 |\n+-------------+\n1 row in set (0.03 sec)" } ]
Modify XML files with Python
18 Aug, 2021 Python|Modifying/Parsing XML Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.The design goals of XML focus on simplicity, generality, and usability across the Internet.It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services.XML is an inherently hierarchical data format, and the most natural way to represent it is with a tree.To perform any operations like parsing, searching, modifying an XML file we use a module xml.etree.ElementTree .It has two classes.ElementTree represents the whole XML document as a tree which helps while performing the operations. Element represents a single node in this tree.Reading and writing from the whole document are done on the ElementTree level.Interactions with a single XML element and its sub-elements are done on the Element level. Properties of Element: PARSING:We can parse XML data from a string or an XML document.Considering xml.etree.ElementTree as ET.1. ET.parse(‘Filename’).getroot() -ET.parse(‘fname’)-creates a tree and then we extract the root by .getroot().2. ET.fromstring(stringname) -To create a root from an XML data string.Example 1: XML document: XML <?xml version="1.0"?><!--COUNTRIES is the root element--><COUNTRIES> <country name="INDIA"> <neighbor name="Dubai" direction="W"/> </country> <country name="Singapore"> <neighbor name="Malaysia" direction="N"/> </country></COUNTRIES> Python Code: Python3 # importing the module.import xml.etree.ElementTree as ETXMLexample_stored_in_a_string ='''<?xml version ="1.0"?><COUNTRIES> <country name ="INDIA"> <neighbor name ="Dubai" direction ="W"/> </country> <country name ="Singapore"> <neighbor name ="Malaysia" direction ="N"/> </country></COUNTRIES>'''# parsing directly.tree = ET.parse('xmldocument.xml')root = tree.getroot()# parsing using the string.stringroot = ET.fromstring(XMLexample_stored_in_a_string)# printing the root.print(root)print(stringroot) Output: outputexample1 Element methods:1)Element.iter(‘tag’) -Iterates over all the child elements(Sub-tree elements) 2)Element.findall(‘tag’) -Finds only elements with a tag which are direct children of the current element. 3)Element.find(‘tag’) -Finds the first Child with the particular tag. 4)Element.get(‘tag’) -Accesses the elements attributes. 5)Element.text -Gives the text of the element. 6)Element.attrib-returns all the attributes present. 7)Element.tag-returns the element name.Example 2: Python3 import xml.etree.ElementTree as ETXMLexample_stored_in_a_string ='''<?xml version ="1.0"?><States> <state name ="TELANGANA"> <rank>1</rank> <neighbor name ="ANDHRA" language ="Telugu"/> <neighbor name ="KARNATAKA" language ="Kannada"/> </state> <state name ="GUJARAT"> <rank>2</rank> <neighbor name ="RAJASTHAN" direction ="N"/> <neighbor name ="MADHYA PRADESH" direction ="E"/> </state> <state name ="KERALA"> <rank>3</rank> <neighbor name ="TAMILNADU" direction ="S" language ="Tamil"/> </state></States>'''# parsing from the string.root = ET.fromstring(XMLexample_stored_in_a_string)# printing attributes of the root tags 'neighbor'.for neighbor in root.iter('neighbor'): print(neighbor.attrib)# finding the state tag and their child attributes.for state in root.findall('state'): rank = state.find('rank').text name = state.get('name') print(name, rank) Output: Element methods output. MODIFYING: Modifying the XML document can also be done through Element methods. Methods: 1)Element.set(‘attrname’, ‘value’) – Modifying element attributes. 2)Element.SubElement(parent, new_childtag) -creates a new child tag under the parent. 3)Element.write(‘filename.xml’)-creates the tree of xml into another file. 4)Element.pop() -delete a particular attribute. 5)Element.remove() -to delete a complete tag.Example 3: XML Document: xml <?xml version="1.0"?><breakfast_menu> <food> <name itemid="11">Belgian Waffles</name> <price>5.95</price> <description>Two of our famous Belgian Waffleswith plenty of real maple syrup</description> <calories>650</calories> </food> <food> <name itemid="21">Strawberry Belgian Waffles</name> <price>7.95</price> <description>Light Belgian waffles coveredwith strawberries and whipped cream</description> <calories>900</calories> </food> <food> <name itemid="31">Berry-Berry Belgian Waffles</name> <price>8.95</price> <description>Light Belgian waffles covered withan assortment of fresh berries and whipped cream</description> <calories>900</calories> </food> <food> <name itemid="41">French Toast</name> <price>4.50</price> <description>Thick slices made from ourhomemade sourdough bread</description> <calories>600</calories> </food></breakfast_menu> Python Code: Python3 import xml.etree.ElementTree as ET mytree = ET.parse('xmldocument.xml.txt')myroot = mytree.getroot() # iterating through the price values.for prices in myroot.iter('price'): # updates the price value prices.text = str(float(prices.text)+10) # creates a new attribute prices.set('newprices', 'yes') # creating a new tag under the parent.# myroot[0] here is the first food tag.ET.SubElement(myroot[0], 'tasty')for temp in myroot.iter('tasty'): # giving the value as Yes. temp.text = str('YES') # deleting attributes in the xml.# by using pop as attrib returns dictionary.# removes the itemid attribute in the name tag of# the second food tag.myroot[1][0].attrib.pop('itemid') # Removing the tag completely we use remove function.# completely removes the third food tag.myroot.remove(myroot[2]) mytree.write('output.xml') Output: simranarora5sos Picked Python-XML Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python 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 Convert integer to string in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Aug, 2021" }, { "code": null, "e": 1120, "s": 28, "text": "Python|Modifying/Parsing XML Extensible Markup Language (XML) is a markup language that defines a set of rules for encoding documents in a format that is both human-readable and machine-readable.The design goals of XML focus on simplicity, generality, and usability across the Internet.It is a textual data format with strong support via Unicode for different human languages. Although the design of XML focuses on documents, the language is widely used for the representation of arbitrary data structures such as those used in web services.XML is an inherently hierarchical data format, and the most natural way to represent it is with a tree.To perform any operations like parsing, searching, modifying an XML file we use a module xml.etree.ElementTree .It has two classes.ElementTree represents the whole XML document as a tree which helps while performing the operations. Element represents a single node in this tree.Reading and writing from the whole document are done on the ElementTree level.Interactions with a single XML element and its sub-elements are done on the Element level. " }, { "code": null, "e": 1144, "s": 1120, "text": "Properties of Element: " }, { "code": null, "e": 1455, "s": 1144, "text": "PARSING:We can parse XML data from a string or an XML document.Considering xml.etree.ElementTree as ET.1. ET.parse(‘Filename’).getroot() -ET.parse(‘fname’)-creates a tree and then we extract the root by .getroot().2. ET.fromstring(stringname) -To create a root from an XML data string.Example 1: XML document: " }, { "code": null, "e": 1459, "s": 1455, "text": "XML" }, { "code": "<?xml version=\"1.0\"?><!--COUNTRIES is the root element--><COUNTRIES> <country name=\"INDIA\"> <neighbor name=\"Dubai\" direction=\"W\"/> </country> <country name=\"Singapore\"> <neighbor name=\"Malaysia\" direction=\"N\"/> </country></COUNTRIES>", "e": 1719, "s": 1459, "text": null }, { "code": null, "e": 1734, "s": 1719, "text": "Python Code: " }, { "code": null, "e": 1742, "s": 1734, "text": "Python3" }, { "code": "# importing the module.import xml.etree.ElementTree as ETXMLexample_stored_in_a_string ='''<?xml version =\"1.0\"?><COUNTRIES> <country name =\"INDIA\"> <neighbor name =\"Dubai\" direction =\"W\"/> </country> <country name =\"Singapore\"> <neighbor name =\"Malaysia\" direction =\"N\"/> </country></COUNTRIES>'''# parsing directly.tree = ET.parse('xmldocument.xml')root = tree.getroot()# parsing using the string.stringroot = ET.fromstring(XMLexample_stored_in_a_string)# printing the root.print(root)print(stringroot)", "e": 2273, "s": 1742, "text": null }, { "code": null, "e": 2281, "s": 2273, "text": "Output:" }, { "code": null, "e": 2296, "s": 2281, "text": "outputexample1" }, { "code": null, "e": 2776, "s": 2296, "text": "Element methods:1)Element.iter(‘tag’) -Iterates over all the child elements(Sub-tree elements) 2)Element.findall(‘tag’) -Finds only elements with a tag which are direct children of the current element. 3)Element.find(‘tag’) -Finds the first Child with the particular tag. 4)Element.get(‘tag’) -Accesses the elements attributes. 5)Element.text -Gives the text of the element. 6)Element.attrib-returns all the attributes present. 7)Element.tag-returns the element name.Example 2: " }, { "code": null, "e": 2784, "s": 2776, "text": "Python3" }, { "code": "import xml.etree.ElementTree as ETXMLexample_stored_in_a_string ='''<?xml version =\"1.0\"?><States> <state name =\"TELANGANA\"> <rank>1</rank> <neighbor name =\"ANDHRA\" language =\"Telugu\"/> <neighbor name =\"KARNATAKA\" language =\"Kannada\"/> </state> <state name =\"GUJARAT\"> <rank>2</rank> <neighbor name =\"RAJASTHAN\" direction =\"N\"/> <neighbor name =\"MADHYA PRADESH\" direction =\"E\"/> </state> <state name =\"KERALA\"> <rank>3</rank> <neighbor name =\"TAMILNADU\" direction =\"S\" language =\"Tamil\"/> </state></States>'''# parsing from the string.root = ET.fromstring(XMLexample_stored_in_a_string)# printing attributes of the root tags 'neighbor'.for neighbor in root.iter('neighbor'): print(neighbor.attrib)# finding the state tag and their child attributes.for state in root.findall('state'): rank = state.find('rank').text name = state.get('name') print(name, rank)", "e": 3728, "s": 2784, "text": null }, { "code": null, "e": 3736, "s": 3728, "text": "Output:" }, { "code": null, "e": 3760, "s": 3736, "text": "Element methods output." }, { "code": null, "e": 4197, "s": 3760, "text": "MODIFYING: Modifying the XML document can also be done through Element methods. Methods: 1)Element.set(‘attrname’, ‘value’) – Modifying element attributes. 2)Element.SubElement(parent, new_childtag) -creates a new child tag under the parent. 3)Element.write(‘filename.xml’)-creates the tree of xml into another file. 4)Element.pop() -delete a particular attribute. 5)Element.remove() -to delete a complete tag.Example 3: XML Document: " }, { "code": null, "e": 4201, "s": 4197, "text": "xml" }, { "code": "<?xml version=\"1.0\"?><breakfast_menu> <food> <name itemid=\"11\">Belgian Waffles</name> <price>5.95</price> <description>Two of our famous Belgian Waffleswith plenty of real maple syrup</description> <calories>650</calories> </food> <food> <name itemid=\"21\">Strawberry Belgian Waffles</name> <price>7.95</price> <description>Light Belgian waffles coveredwith strawberries and whipped cream</description> <calories>900</calories> </food> <food> <name itemid=\"31\">Berry-Berry Belgian Waffles</name> <price>8.95</price> <description>Light Belgian waffles covered withan assortment of fresh berries and whipped cream</description> <calories>900</calories> </food> <food> <name itemid=\"41\">French Toast</name> <price>4.50</price> <description>Thick slices made from ourhomemade sourdough bread</description> <calories>600</calories> </food></breakfast_menu>", "e": 5188, "s": 4201, "text": null }, { "code": null, "e": 5203, "s": 5188, "text": "Python Code: " }, { "code": null, "e": 5211, "s": 5203, "text": "Python3" }, { "code": "import xml.etree.ElementTree as ET mytree = ET.parse('xmldocument.xml.txt')myroot = mytree.getroot() # iterating through the price values.for prices in myroot.iter('price'): # updates the price value prices.text = str(float(prices.text)+10) # creates a new attribute prices.set('newprices', 'yes') # creating a new tag under the parent.# myroot[0] here is the first food tag.ET.SubElement(myroot[0], 'tasty')for temp in myroot.iter('tasty'): # giving the value as Yes. temp.text = str('YES') # deleting attributes in the xml.# by using pop as attrib returns dictionary.# removes the itemid attribute in the name tag of# the second food tag.myroot[1][0].attrib.pop('itemid') # Removing the tag completely we use remove function.# completely removes the third food tag.myroot.remove(myroot[2]) mytree.write('output.xml')", "e": 6048, "s": 5211, "text": null }, { "code": null, "e": 6058, "s": 6048, "text": "Output: " }, { "code": null, "e": 6076, "s": 6060, "text": "simranarora5sos" }, { "code": null, "e": 6083, "s": 6076, "text": "Picked" }, { "code": null, "e": 6094, "s": 6083, "text": "Python-XML" }, { "code": null, "e": 6101, "s": 6094, "text": "Python" }, { "code": null, "e": 6199, "s": 6101, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6217, "s": 6199, "text": "Python Dictionary" }, { "code": null, "e": 6259, "s": 6217, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 6281, "s": 6259, "text": "Enumerate() in Python" }, { "code": null, "e": 6307, "s": 6281, "text": "Python String | replace()" }, { "code": null, "e": 6339, "s": 6307, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 6368, "s": 6339, "text": "*args and **kwargs in Python" }, { "code": null, "e": 6395, "s": 6368, "text": "Python Classes and Objects" }, { "code": null, "e": 6425, "s": 6395, "text": "Iterate over a list in Python" }, { "code": null, "e": 6446, "s": 6425, "text": "Python OOPs Concepts" } ]
K’th Largest Element in BST when modification to BST is not allowed
27 Jun, 2022 Given a Binary Search Tree (BST) and a positive integer k, find the k’th largest element in the Binary Search Tree. For example, in the following BST, if k = 3, then output should be 14, and if k = 5, then output should be 10. We have discussed two methods in this post. The method 1 requires O(n) time. The method 2 takes O(h) time where h is height of BST, but requires augmenting the BST (storing count of nodes in left subtree with every node). Can we find k’th largest element in better than O(n) time and no augmentation? Approach: The idea is to do reverse inorder traversal of BST. Keep a count of nodes visited.The reverse inorder traversal traverses all nodes in decreasing order, i.e, visit the right node then centre then left and continue traversing the nodes recursively.While doing the traversal, keep track of the count of nodes visited so far.When the count becomes equal to k, stop the traversal and print the key. The idea is to do reverse inorder traversal of BST. Keep a count of nodes visited. The reverse inorder traversal traverses all nodes in decreasing order, i.e, visit the right node then centre then left and continue traversing the nodes recursively. While doing the traversal, keep track of the count of nodes visited so far. When the count becomes equal to k, stop the traversal and print the key. Implementation: C++ Java Python3 C# Javascript // C++ program to find k'th largest element in BST#include<bits/stdc++.h>using namespace std; struct Node{ int key; Node *left, *right;}; // A utility function to create a new BST nodeNode *newNode(int item){ Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A function to find k'th largest element in a given tree.void kthLargestUtil(Node *root, int k, int &c){ // Base cases, the second condition is important to // avoid unnecessary recursive calls if (root == NULL || c >= k) return; // Follow reverse inorder traversal so that the // largest element is visited first kthLargestUtil(root->right, k, c); // Increment count of visited nodes c++; // If c becomes k now, then this is the k'th largest if (c == k) { cout << "K'th largest element is " << root->key << endl; return; } // Recur for left subtree kthLargestUtil(root->left, k, c);} // Function to find k'th largest elementvoid kthLargest(Node *root, int k){ // Initialize count of nodes visited as 0 int c = 0; // Note that c is passed by reference kthLargestUtil(root, k, c);} /* A utility function to insert a new node with given key in BST */Node* insert(Node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} // Driver Program to test above functionsint main(){ /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); int c = 0; for (int k=1; k<=7; k++) kthLargest(root, k); return 0;} // Java code to find k'th largest element in BST // 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; } // function to insert nodes public void insert(int data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given key in BST */ Node insertRec(Node node, int data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } if (data == node.data) { return node; } /* Otherwise, recur down the tree */ if (data < node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // class that stores the value of count public class count { int c = 0; } // utility function to find kth largest no in // a given tree void kthLargestUtil(Node node, int k, count C) { // Base cases, the second condition is important to // avoid unnecessary recursive calls if (node == null || C.c >= k) return; // Follow reverse inorder traversal so that the // largest element is visited first this.kthLargestUtil(node.right, k, C); // Increment count of visited nodes C.c++; // If c becomes k now, then this is the k'th largest if (C.c == k) { System.out.println(k + "th largest element is " + node.data); return; } // Recur for left subtree this.kthLargestUtil(node.left, k, C); } // Method to find the kth largest no in given BST void kthLargest(int k) { count c = new count(); // object of class count this.kthLargestUtil(this.root, k, c); } // Driver function public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); for (int i = 1; i <= 7; i++) { tree.kthLargest(i); } }} // This code is contributed by Kamal Rawal # Python3 program to find k'th largest# element in BST class Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # A function to find k'th largest# element in a given tree.def kthLargestUtil(root, k, c): # Base cases, the second condition # is important to avoid unnecessary # recursive calls if root == None or c[0] >= k: return # Follow reverse inorder traversal # so that the largest element is # visited first kthLargestUtil(root.right, k, c) # Increment count of visited nodes c[0] += 1 # If c becomes k now, then this is # the k'th largest if c[0] == k: print("K'th largest element is", root.key) return # Recur for left subtree kthLargestUtil(root.left, k, c) # Function to find k'th largest elementdef kthLargest(root, k): # Initialize count of nodes # visited as 0 c = [0] # Note that c is passed by reference kthLargestUtil(root, k, c) # A utility function to insert a new# node with given key in BST */def insert(node, key): # If the tree is empty, # return a new node if node == None: return Node(key) # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Driver Codeif __name__ == '__main__': # Let us create following BST # 50 # / \ # 30 70 # / \ / \ # 20 40 60 80 */ root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) for k in range(1,8): kthLargest(root, k) # This code is contributed by PranchalK using System; // C# code to find k'th largest element in BST // 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 public Node root; // Constructor public BinarySearchTree() { root = null; } // function to insert nodes public virtual void insert(int data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given key in BST */ public virtual Node insertRec(Node node, int data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } if (data == node.data) { return node; } /* Otherwise, recur down the tree */ if (data < node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // class that stores the value of count public class count { private readonly BinarySearchTree outerInstance; public count(BinarySearchTree outerInstance) { this.outerInstance = outerInstance; } internal int c = 0; } // utility function to find kth largest no in // a given tree public virtual void kthLargestUtil(Node node, int k, count C) { // Base cases, the second condition is important to // avoid unnecessary recursive calls if (node == null || C.c >= k) { return; } // Follow reverse inorder traversal so that the // largest element is visited first this.kthLargestUtil(node.right, k, C); // Increment count of visited nodes C.c++; // If c becomes k now, then this is the k'th largest if (C.c == k) { Console.WriteLine(k + "th largest element is " + node.data); return; } // Recur for left subtree this.kthLargestUtil(node.left, k, C); } // Method to find the kth largest no in given BST public virtual void kthLargest(int k) { count c = new count(this); // object of class count this.kthLargestUtil(this.root, k, c); } // Driver function public static void Main(string[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); for (int i = 1; i <= 7; i++) { tree.kthLargest(i); } }} // This code is contributed by Shrikant13 <script>// javascript code to find k'th largest element in BST // A binary tree nodeclass Node { constructor(d) { this.data = d; this.left = this.right = null; }} // Root of BST var root = null; // Constructor // function to insert nodes function insert(data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given key in BST */ function insertRec( node , data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } if (data == node.data) { return node; } /* Otherwise, recur down the tree */ if (data < node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // class that stores the value of count class count { constructor(){this.c = 0;} } // utility function to find kth largest no in // a given tree function kthLargestUtil( node , k, C) { // Base cases, the second condition is important to // avoid unnecessary recursive calls if (node == null || C.c >= k) return; // Follow reverse inorder traversal so that the // largest element is visited first this.kthLargestUtil(node.right, k, C); // Increment count of visited nodes C.c++; // If c becomes k now, then this is the k'th largest if (C.c == k) { document.write(k + "th largest element is " + node.data+"<br/>"); return; } // Recur for left subtree this.kthLargestUtil(node.left, k, C); } // Method to find the kth largest no in given BST function kthLargest(k) { c = new count(); // object of class count this.kthLargestUtil(this.root, k, c); } // Driver function /* Let us create following BST 50 / \ 30 70 / \ / \ 20 40 60 80 */ insert(50); insert(30); insert(20); insert(40); insert(70); insert(60); insert(80); for (i = 1; i <= 7; i++) { kthLargest(i); } // This code contributed by gauravrajput1</script> K'th largest element is 80 K'th largest element is 70 K'th largest element is 60 K'th largest element is 50 K'th largest element is 40 K'th largest element is 30 K'th largest element is 20 Complexity Analysis: Time Complexity: O(n). In worst case the code can traverse each and every node of the tree if the k given is equal to n (total number of nodes in the tree). Therefore overall time complexity is O(n).Auxiliary Space: O(h). Max recursion stack of height h at a given time. Time Complexity: O(n). In worst case the code can traverse each and every node of the tree if the k given is equal to n (total number of nodes in the tree). Therefore overall time complexity is O(n). Auxiliary Space: O(h). Max recursion stack of height h at a given time. K’th Largest Element in BST when modification to BST is not allowed | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersK’th Largest Element in BST when modification to BST is not allowed | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:39•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=QavTg43VDsU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Chirag Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above shrikanth13 PranchalKatiyar andrew1234 GauravRajput1 AryanRaja ravishekr7 polymatir3j hardikkoriintern Accolite Amazon Order-Statistics Samsung Binary Search Tree Tree Accolite Amazon Samsung Binary Search Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. A program to check if a binary tree is BST or not Find postorder traversal of BST from preorder traversal Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Sorted Array to Balanced BST Optimal Binary Search Tree | DP-24 Tree Traversals (Inorder, Preorder and Postorder) Binary Tree | Set 1 (Introduction) Level Order Binary Tree Traversal Introduction to Data Structures Introduction to Tree Data Structure
[ { "code": null, "e": 52, "s": 24, "text": "\n27 Jun, 2022" }, { "code": null, "e": 280, "s": 52, "text": "Given a Binary Search Tree (BST) and a positive integer k, find the k’th largest element in the Binary Search Tree. For example, in the following BST, if k = 3, then output should be 14, and if k = 5, then output should be 10. " }, { "code": null, "e": 581, "s": 280, "text": "We have discussed two methods in this post. The method 1 requires O(n) time. The method 2 takes O(h) time where h is height of BST, but requires augmenting the BST (storing count of nodes in left subtree with every node). Can we find k’th largest element in better than O(n) time and no augmentation?" }, { "code": null, "e": 592, "s": 581, "text": "Approach: " }, { "code": null, "e": 987, "s": 592, "text": "The idea is to do reverse inorder traversal of BST. Keep a count of nodes visited.The reverse inorder traversal traverses all nodes in decreasing order, i.e, visit the right node then centre then left and continue traversing the nodes recursively.While doing the traversal, keep track of the count of nodes visited so far.When the count becomes equal to k, stop the traversal and print the key." }, { "code": null, "e": 1070, "s": 987, "text": "The idea is to do reverse inorder traversal of BST. Keep a count of nodes visited." }, { "code": null, "e": 1236, "s": 1070, "text": "The reverse inorder traversal traverses all nodes in decreasing order, i.e, visit the right node then centre then left and continue traversing the nodes recursively." }, { "code": null, "e": 1312, "s": 1236, "text": "While doing the traversal, keep track of the count of nodes visited so far." }, { "code": null, "e": 1385, "s": 1312, "text": "When the count becomes equal to k, stop the traversal and print the key." }, { "code": null, "e": 1401, "s": 1385, "text": "Implementation:" }, { "code": null, "e": 1405, "s": 1401, "text": "C++" }, { "code": null, "e": 1410, "s": 1405, "text": "Java" }, { "code": null, "e": 1418, "s": 1410, "text": "Python3" }, { "code": null, "e": 1421, "s": 1418, "text": "C#" }, { "code": null, "e": 1432, "s": 1421, "text": "Javascript" }, { "code": "// C++ program to find k'th largest element in BST#include<bits/stdc++.h>using namespace std; struct Node{ int key; Node *left, *right;}; // A utility function to create a new BST nodeNode *newNode(int item){ Node *temp = new Node; temp->key = item; temp->left = temp->right = NULL; return temp;} // A function to find k'th largest element in a given tree.void kthLargestUtil(Node *root, int k, int &c){ // Base cases, the second condition is important to // avoid unnecessary recursive calls if (root == NULL || c >= k) return; // Follow reverse inorder traversal so that the // largest element is visited first kthLargestUtil(root->right, k, c); // Increment count of visited nodes c++; // If c becomes k now, then this is the k'th largest if (c == k) { cout << \"K'th largest element is \" << root->key << endl; return; } // Recur for left subtree kthLargestUtil(root->left, k, c);} // Function to find k'th largest elementvoid kthLargest(Node *root, int k){ // Initialize count of nodes visited as 0 int c = 0; // Note that c is passed by reference kthLargestUtil(root, k, c);} /* A utility function to insert a new node with given key in BST */Node* insert(Node* node, int key){ /* If the tree is empty, return a new node */ if (node == NULL) return newNode(key); /* Otherwise, recur down the tree */ if (key < node->key) node->left = insert(node->left, key); else if (key > node->key) node->right = insert(node->right, key); /* return the (unchanged) node pointer */ return node;} // Driver Program to test above functionsint main(){ /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ Node *root = NULL; root = insert(root, 50); insert(root, 30); insert(root, 20); insert(root, 40); insert(root, 70); insert(root, 60); insert(root, 80); int c = 0; for (int k=1; k<=7; k++) kthLargest(root, k); return 0;}", "e": 3515, "s": 1432, "text": null }, { "code": "// Java code to find k'th largest element in BST // 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; } // function to insert nodes public void insert(int data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given key in BST */ Node insertRec(Node node, int data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } if (data == node.data) { return node; } /* Otherwise, recur down the tree */ if (data < node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // class that stores the value of count public class count { int c = 0; } // utility function to find kth largest no in // a given tree void kthLargestUtil(Node node, int k, count C) { // Base cases, the second condition is important to // avoid unnecessary recursive calls if (node == null || C.c >= k) return; // Follow reverse inorder traversal so that the // largest element is visited first this.kthLargestUtil(node.right, k, C); // Increment count of visited nodes C.c++; // If c becomes k now, then this is the k'th largest if (C.c == k) { System.out.println(k + \"th largest element is \" + node.data); return; } // Recur for left subtree this.kthLargestUtil(node.left, k, C); } // Method to find the kth largest no in given BST void kthLargest(int k) { count c = new count(); // object of class count this.kthLargestUtil(this.root, k, c); } // Driver function public static void main(String[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); for (int i = 1; i <= 7; i++) { tree.kthLargest(i); } }} // This code is contributed by Kamal Rawal", "e": 6245, "s": 3515, "text": null }, { "code": "# Python3 program to find k'th largest# element in BST class Node: # Constructor to create a new node def __init__(self, data): self.key = data self.left = None self.right = None # A function to find k'th largest# element in a given tree.def kthLargestUtil(root, k, c): # Base cases, the second condition # is important to avoid unnecessary # recursive calls if root == None or c[0] >= k: return # Follow reverse inorder traversal # so that the largest element is # visited first kthLargestUtil(root.right, k, c) # Increment count of visited nodes c[0] += 1 # If c becomes k now, then this is # the k'th largest if c[0] == k: print(\"K'th largest element is\", root.key) return # Recur for left subtree kthLargestUtil(root.left, k, c) # Function to find k'th largest elementdef kthLargest(root, k): # Initialize count of nodes # visited as 0 c = [0] # Note that c is passed by reference kthLargestUtil(root, k, c) # A utility function to insert a new# node with given key in BST */def insert(node, key): # If the tree is empty, # return a new node if node == None: return Node(key) # Otherwise, recur down the tree if key < node.key: node.left = insert(node.left, key) elif key > node.key: node.right = insert(node.right, key) # return the (unchanged) node pointer return node # Driver Codeif __name__ == '__main__': # Let us create following BST # 50 # / \\ # 30 70 # / \\ / \\ # 20 40 60 80 */ root = None root = insert(root, 50) insert(root, 30) insert(root, 20) insert(root, 40) insert(root, 70) insert(root, 60) insert(root, 80) for k in range(1,8): kthLargest(root, k) # This code is contributed by PranchalK", "e": 8159, "s": 6245, "text": null }, { "code": "using System; // C# code to find k'th largest element in BST // 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 public Node root; // Constructor public BinarySearchTree() { root = null; } // function to insert nodes public virtual void insert(int data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given key in BST */ public virtual Node insertRec(Node node, int data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } if (data == node.data) { return node; } /* Otherwise, recur down the tree */ if (data < node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // class that stores the value of count public class count { private readonly BinarySearchTree outerInstance; public count(BinarySearchTree outerInstance) { this.outerInstance = outerInstance; } internal int c = 0; } // utility function to find kth largest no in // a given tree public virtual void kthLargestUtil(Node node, int k, count C) { // Base cases, the second condition is important to // avoid unnecessary recursive calls if (node == null || C.c >= k) { return; } // Follow reverse inorder traversal so that the // largest element is visited first this.kthLargestUtil(node.right, k, C); // Increment count of visited nodes C.c++; // If c becomes k now, then this is the k'th largest if (C.c == k) { Console.WriteLine(k + \"th largest element is \" + node.data); return; } // Recur for left subtree this.kthLargestUtil(node.left, k, C); } // Method to find the kth largest no in given BST public virtual void kthLargest(int k) { count c = new count(this); // object of class count this.kthLargestUtil(this.root, k, c); } // Driver function public static void Main(string[] args) { BinarySearchTree tree = new BinarySearchTree(); /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ tree.insert(50); tree.insert(30); tree.insert(20); tree.insert(40); tree.insert(70); tree.insert(60); tree.insert(80); for (int i = 1; i <= 7; i++) { tree.kthLargest(i); } }} // This code is contributed by Shrikant13", "e": 11156, "s": 8159, "text": null }, { "code": "<script>// javascript code to find k'th largest element in BST // A binary tree nodeclass Node { constructor(d) { this.data = d; this.left = this.right = null; }} // Root of BST var root = null; // Constructor // function to insert nodes function insert(data) { this.root = this.insertRec(this.root, data); } /* A utility function to insert a new node with given key in BST */ function insertRec( node , data) { /* If the tree is empty, return a new node */ if (node == null) { this.root = new Node(data); return this.root; } if (data == node.data) { return node; } /* Otherwise, recur down the tree */ if (data < node.data) { node.left = this.insertRec(node.left, data); } else { node.right = this.insertRec(node.right, data); } return node; } // class that stores the value of count class count { constructor(){this.c = 0;} } // utility function to find kth largest no in // a given tree function kthLargestUtil( node , k, C) { // Base cases, the second condition is important to // avoid unnecessary recursive calls if (node == null || C.c >= k) return; // Follow reverse inorder traversal so that the // largest element is visited first this.kthLargestUtil(node.right, k, C); // Increment count of visited nodes C.c++; // If c becomes k now, then this is the k'th largest if (C.c == k) { document.write(k + \"th largest element is \" + node.data+\"<br/>\"); return; } // Recur for left subtree this.kthLargestUtil(node.left, k, C); } // Method to find the kth largest no in given BST function kthLargest(k) { c = new count(); // object of class count this.kthLargestUtil(this.root, k, c); } // Driver function /* Let us create following BST 50 / \\ 30 70 / \\ / \\ 20 40 60 80 */ insert(50); insert(30); insert(20); insert(40); insert(70); insert(60); insert(80); for (i = 1; i <= 7; i++) { kthLargest(i); } // This code contributed by gauravrajput1</script>", "e": 13674, "s": 11156, "text": null }, { "code": null, "e": 13863, "s": 13674, "text": "K'th largest element is 80\nK'th largest element is 70\nK'th largest element is 60\nK'th largest element is 50\nK'th largest element is 40\nK'th largest element is 30\nK'th largest element is 20" }, { "code": null, "e": 13886, "s": 13863, "text": "Complexity Analysis: " }, { "code": null, "e": 14157, "s": 13886, "text": "Time Complexity: O(n). In worst case the code can traverse each and every node of the tree if the k given is equal to n (total number of nodes in the tree). Therefore overall time complexity is O(n).Auxiliary Space: O(h). Max recursion stack of height h at a given time." }, { "code": null, "e": 14357, "s": 14157, "text": "Time Complexity: O(n). In worst case the code can traverse each and every node of the tree if the k given is equal to n (total number of nodes in the tree). Therefore overall time complexity is O(n)." }, { "code": null, "e": 14429, "s": 14357, "text": "Auxiliary Space: O(h). Max recursion stack of height h at a given time." }, { "code": null, "e": 15381, "s": 14429, "text": "K’th Largest Element in BST when modification to BST is not allowed | GeeksforGeeks - YouTubeGeeksforGeeks529K subscribersK’th Largest Element in BST when modification to BST is not allowed | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 3:39•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=QavTg43VDsU\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 15551, "s": 15381, "text": "This article is contributed by Chirag Sharma. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 15563, "s": 15551, "text": "shrikanth13" }, { "code": null, "e": 15579, "s": 15563, "text": "PranchalKatiyar" }, { "code": null, "e": 15590, "s": 15579, "text": "andrew1234" }, { "code": null, "e": 15604, "s": 15590, "text": "GauravRajput1" }, { "code": null, "e": 15614, "s": 15604, "text": "AryanRaja" }, { "code": null, "e": 15625, "s": 15614, "text": "ravishekr7" }, { "code": null, "e": 15637, "s": 15625, "text": "polymatir3j" }, { "code": null, "e": 15654, "s": 15637, "text": "hardikkoriintern" }, { "code": null, "e": 15663, "s": 15654, "text": "Accolite" }, { "code": null, "e": 15670, "s": 15663, "text": "Amazon" }, { "code": null, "e": 15687, "s": 15670, "text": "Order-Statistics" }, { "code": null, "e": 15695, "s": 15687, "text": "Samsung" }, { "code": null, "e": 15714, "s": 15695, "text": "Binary Search Tree" }, { "code": null, "e": 15719, "s": 15714, "text": "Tree" }, { "code": null, "e": 15728, "s": 15719, "text": "Accolite" }, { "code": null, "e": 15735, "s": 15728, "text": "Amazon" }, { "code": null, "e": 15743, "s": 15735, "text": "Samsung" }, { "code": null, "e": 15762, "s": 15743, "text": "Binary Search Tree" }, { "code": null, "e": 15767, "s": 15762, "text": "Tree" }, { "code": null, "e": 15865, "s": 15767, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 15915, "s": 15865, "text": "A program to check if a binary tree is BST or not" }, { "code": null, "e": 15971, "s": 15915, "text": "Find postorder traversal of BST from preorder traversal" }, { "code": null, "e": 16041, "s": 15971, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" }, { "code": null, "e": 16070, "s": 16041, "text": "Sorted Array to Balanced BST" }, { "code": null, "e": 16105, "s": 16070, "text": "Optimal Binary Search Tree | DP-24" }, { "code": null, "e": 16155, "s": 16105, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 16190, "s": 16155, "text": "Binary Tree | Set 1 (Introduction)" }, { "code": null, "e": 16224, "s": 16190, "text": "Level Order Binary Tree Traversal" }, { "code": null, "e": 16256, "s": 16224, "text": "Introduction to Data Structures" } ]
Linked List Implementation in C#
24 Jun, 2022 A LinkedList is a linear data structure which stores element in the non-contiguous location. The elements in a linked list are linked with each other using pointers. Or in other words, LinkedList consists of nodes where each node contains a data field and a reference(link) to the next node in the list. In C#, LinkedList is the generic type of collection which is defined in System.Collections.Generic namespace. It is a doubly linked list, therefore, each node points forward to the Next node and backward to the Previous node. It is a dynamic collection which grows, according to the need of your program. It also provides fast inserting and removing elements. Important Points: The LinkedList class implements the ICollection<T>, IEnumerable<T>, IReadOnlyCollection<T>, ICollection, IEnumerable, IDeserializationCallback, and ISerializable interfaces. It also supports enumerators. You can remove nodes and reinsert them, either in the same list or in another list, which results in no additional objects allocated on the heap. Every node in a LinkedList<T> object is of the type LinkedListNode<T>. It does not support chaining, splitting, cycles, or other features that can leave the list in an inconsistent state. If the LinkedList is empty, the First and Last properties contain null. The capacity of a LinkedList is the number of elements the LinkedList can hold. In LinkedList, it is allowed to store duplicate elements but of the same type. A LinkedList class has 3 constructors which are used to create a LinkedList which are as follows: LinkedList(): This constructor is used to create an instance of the LinkedList class that is empty. LinkedList(IEnumerable): This constructor is used to create an instance of the LinkedList class that contains elements copied from the specified IEnumerable and has sufficient capacity to accommodate the number of elements copied. LinkedList(SerializationInfo, StreamingContext): This constructor is used to create an instance of the LinkedList class that is serializable with the specified SerializationInfo and StreamingContext. Let’s see how to create an LinkedList using LinkedList() constructor: Step 1: Include System.Collections.Generic namespace in your program with the help of using keyword: using System.Collections.Generic; Step 2: Create a LinkedList using LinkedList class as shown below: LinkedList <Type_of_linkedlist> linkedlist_name = new LinkedList <Type_of_linkedlist>(); Step 3: LinkedList provides 4 different methods to add nodes and these methods are: AddAfter: This method is used to add a new node or value after an existing node in the LinkedList. AddBefore: This method is used to add a new node or value before an existing node in the LinkedList. AddFirst: This method is used to add a new node or value at the start of the LinkedList. AddLast: This method is used to add a new node or value at the end of the LinkedList. Step 4: The elements of the LinkedList is accessed by using a foreach loop or by using for loop. As shown in the below example. Example: CSharp // C# program to illustrate how // to create a LinkedListusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating a linkedlist // Using LinkedList class LinkedList<String> my_list = new LinkedList<String>(); // Adding elements in the LinkedList // Using AddLast() method my_list.AddLast("Zoya"); my_list.AddLast("Shilpa"); my_list.AddLast("Rohit"); my_list.AddLast("Rohan"); my_list.AddLast("Juhi"); my_list.AddLast("Zoya"); Console.WriteLine("Best students of XYZ university:"); // Accessing the elements of // LinkedList Using foreach loop foreach(string str in my_list) { Console.WriteLine(str); } }} Best students of XYZ university: Zoya Shilpa Rohit Rohan Juhi Zoya In LinkedList, it is allowed to remove elements from the LinkedList. LinkedList<T> class provides 5 different methods to remove elements and the methods are: Clear(): This method is used to remove all nodes from the LinkedList. Remove(LinkedListNode): This method is used to remove the specified node from the LinkedList. Remove(T): This method is used to remove the first occurrence of the specified value from the LinkedList. RemoveFirst(): This method is used to remove the node at the start of the LinkedList. RemoveLast(): This method is used to remove the node at the end of the LinkedList. Example: CSharp // C# program to illustrate how to// remove elements from LinkedListusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating a linkedlist // Using LinkedList class LinkedList<String> my_list = new LinkedList<String>(); // Adding elements in the LinkedList // Using AddLast() method my_list.AddLast("Zoya"); my_list.AddLast("Shilpa"); my_list.AddLast("Rohit"); my_list.AddLast("Rohan"); my_list.AddLast("Juhi"); my_list.AddLast("Zoya"); // Initial number of elements Console.WriteLine("Best students of XYZ "+ "university initially:"); // Accessing the elements of // Linkedlist Using foreach loop foreach(string str in my_list) { Console.WriteLine(str); } // After using Remove(LinkedListNode) // method Console.WriteLine("Best students of XYZ"+ " university in 2000:"); my_list.Remove(my_list.First); foreach(string str in my_list) { Console.WriteLine(str); } // After using Remove(T) method Console.WriteLine("Best students of XYZ"+ " university in 2001:"); my_list.Remove("Rohit"); foreach(string str in my_list) { Console.WriteLine(str); } // After using RemoveFirst() method Console.WriteLine("Best students of XYZ"+ " university in 2002:"); my_list.RemoveFirst(); foreach(string str in my_list) { Console.WriteLine(str); } // After using RemoveLast() method Console.WriteLine("Best students of XYZ"+ " university in 2003:"); my_list.RemoveLast(); foreach(string str in my_list) { Console.WriteLine(str); } // After using Clear() method my_list.Clear(); Console.WriteLine("Number of students: {0}", my_list.Count); }} Best students of XYZ university initially: Zoya Shilpa Rohit Rohan Juhi Zoya Best students of XYZ university in 2000: Shilpa Rohit Rohan Juhi Zoya Best students of XYZ university in 2001: Shilpa Rohan Juhi Zoya Best students of XYZ university in 2002: Rohan Juhi Zoya Best students of XYZ university in 2003: Rohan Juhi Number of students: 0 In LinkedList, you can check whether the given value is present or not using the Contains(T) method. This method is used to determine whether a value is in the LinkedList. Example: CSharp // C# program to illustrate how // to check whether the given // element is present or not // in the LinkedListusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating a linkedlist // Using LinkedList class LinkedList<String> my_list = new LinkedList<String>(); // Adding elements in the Linkedlist // Using AddLast() method my_list.AddLast("Zoya"); my_list.AddLast("Shilpa"); my_list.AddLast("Rohit"); my_list.AddLast("Rohan"); my_list.AddLast("Juhi"); // Check if the given element // is available or not if (my_list.Contains("Shilpa") == true) { Console.WriteLine("Element Found...!!"); } else { Console.WriteLine("Element Not found...!!"); } }} Element Found...!! simranarora5sos CSharp-Generic-Namespace CSharp-LinkedList C# Linked List Linked List 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 String.Split() Method in C# with Examples C# | IsNullOrEmpty() Method Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Jun, 2022" }, { "code": null, "e": 736, "s": 53, "text": "A LinkedList is a linear data structure which stores element in the non-contiguous location. The elements in a linked list are linked with each other using pointers. Or in other words, LinkedList consists of nodes where each node contains a data field and a reference(link) to the next node in the list. In C#, LinkedList is the generic type of collection which is defined in System.Collections.Generic namespace. It is a doubly linked list, therefore, each node points forward to the Next node and backward to the Previous node. It is a dynamic collection which grows, according to the need of your program. It also provides fast inserting and removing elements. Important Points:" }, { "code": null, "e": 910, "s": 736, "text": "The LinkedList class implements the ICollection<T>, IEnumerable<T>, IReadOnlyCollection<T>, ICollection, IEnumerable, IDeserializationCallback, and ISerializable interfaces." }, { "code": null, "e": 940, "s": 910, "text": "It also supports enumerators." }, { "code": null, "e": 1086, "s": 940, "text": "You can remove nodes and reinsert them, either in the same list or in another list, which results in no additional objects allocated on the heap." }, { "code": null, "e": 1157, "s": 1086, "text": "Every node in a LinkedList<T> object is of the type LinkedListNode<T>." }, { "code": null, "e": 1274, "s": 1157, "text": "It does not support chaining, splitting, cycles, or other features that can leave the list in an inconsistent state." }, { "code": null, "e": 1346, "s": 1274, "text": "If the LinkedList is empty, the First and Last properties contain null." }, { "code": null, "e": 1426, "s": 1346, "text": "The capacity of a LinkedList is the number of elements the LinkedList can hold." }, { "code": null, "e": 1505, "s": 1426, "text": "In LinkedList, it is allowed to store duplicate elements but of the same type." }, { "code": null, "e": 1603, "s": 1505, "text": "A LinkedList class has 3 constructors which are used to create a LinkedList which are as follows:" }, { "code": null, "e": 1703, "s": 1603, "text": "LinkedList(): This constructor is used to create an instance of the LinkedList class that is empty." }, { "code": null, "e": 1934, "s": 1703, "text": "LinkedList(IEnumerable): This constructor is used to create an instance of the LinkedList class that contains elements copied from the specified IEnumerable and has sufficient capacity to accommodate the number of elements copied." }, { "code": null, "e": 2134, "s": 1934, "text": "LinkedList(SerializationInfo, StreamingContext): This constructor is used to create an instance of the LinkedList class that is serializable with the specified SerializationInfo and StreamingContext." }, { "code": null, "e": 2305, "s": 2134, "text": "Let’s see how to create an LinkedList using LinkedList() constructor: Step 1: Include System.Collections.Generic namespace in your program with the help of using keyword:" }, { "code": null, "e": 2339, "s": 2305, "text": "using System.Collections.Generic;" }, { "code": null, "e": 2406, "s": 2339, "text": "Step 2: Create a LinkedList using LinkedList class as shown below:" }, { "code": null, "e": 2495, "s": 2406, "text": "LinkedList <Type_of_linkedlist> linkedlist_name = new LinkedList <Type_of_linkedlist>();" }, { "code": null, "e": 2579, "s": 2495, "text": "Step 3: LinkedList provides 4 different methods to add nodes and these methods are:" }, { "code": null, "e": 2678, "s": 2579, "text": "AddAfter: This method is used to add a new node or value after an existing node in the LinkedList." }, { "code": null, "e": 2779, "s": 2678, "text": "AddBefore: This method is used to add a new node or value before an existing node in the LinkedList." }, { "code": null, "e": 2868, "s": 2779, "text": "AddFirst: This method is used to add a new node or value at the start of the LinkedList." }, { "code": null, "e": 2954, "s": 2868, "text": "AddLast: This method is used to add a new node or value at the end of the LinkedList." }, { "code": null, "e": 3092, "s": 2954, "text": "Step 4: The elements of the LinkedList is accessed by using a foreach loop or by using for loop. As shown in the below example. Example: " }, { "code": null, "e": 3099, "s": 3092, "text": "CSharp" }, { "code": "// C# program to illustrate how // to create a LinkedListusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating a linkedlist // Using LinkedList class LinkedList<String> my_list = new LinkedList<String>(); // Adding elements in the LinkedList // Using AddLast() method my_list.AddLast(\"Zoya\"); my_list.AddLast(\"Shilpa\"); my_list.AddLast(\"Rohit\"); my_list.AddLast(\"Rohan\"); my_list.AddLast(\"Juhi\"); my_list.AddLast(\"Zoya\"); Console.WriteLine(\"Best students of XYZ university:\"); // Accessing the elements of // LinkedList Using foreach loop foreach(string str in my_list) { Console.WriteLine(str); } }}", "e": 3914, "s": 3099, "text": null }, { "code": null, "e": 3981, "s": 3914, "text": "Best students of XYZ university:\nZoya\nShilpa\nRohit\nRohan\nJuhi\nZoya" }, { "code": null, "e": 4139, "s": 3981, "text": "In LinkedList, it is allowed to remove elements from the LinkedList. LinkedList<T> class provides 5 different methods to remove elements and the methods are:" }, { "code": null, "e": 4209, "s": 4139, "text": "Clear(): This method is used to remove all nodes from the LinkedList." }, { "code": null, "e": 4303, "s": 4209, "text": "Remove(LinkedListNode): This method is used to remove the specified node from the LinkedList." }, { "code": null, "e": 4409, "s": 4303, "text": "Remove(T): This method is used to remove the first occurrence of the specified value from the LinkedList." }, { "code": null, "e": 4495, "s": 4409, "text": "RemoveFirst(): This method is used to remove the node at the start of the LinkedList." }, { "code": null, "e": 4578, "s": 4495, "text": "RemoveLast(): This method is used to remove the node at the end of the LinkedList." }, { "code": null, "e": 4588, "s": 4578, "text": "Example: " }, { "code": null, "e": 4595, "s": 4588, "text": "CSharp" }, { "code": "// C# program to illustrate how to// remove elements from LinkedListusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating a linkedlist // Using LinkedList class LinkedList<String> my_list = new LinkedList<String>(); // Adding elements in the LinkedList // Using AddLast() method my_list.AddLast(\"Zoya\"); my_list.AddLast(\"Shilpa\"); my_list.AddLast(\"Rohit\"); my_list.AddLast(\"Rohan\"); my_list.AddLast(\"Juhi\"); my_list.AddLast(\"Zoya\"); // Initial number of elements Console.WriteLine(\"Best students of XYZ \"+ \"university initially:\"); // Accessing the elements of // Linkedlist Using foreach loop foreach(string str in my_list) { Console.WriteLine(str); } // After using Remove(LinkedListNode) // method Console.WriteLine(\"Best students of XYZ\"+ \" university in 2000:\"); my_list.Remove(my_list.First); foreach(string str in my_list) { Console.WriteLine(str); } // After using Remove(T) method Console.WriteLine(\"Best students of XYZ\"+ \" university in 2001:\"); my_list.Remove(\"Rohit\"); foreach(string str in my_list) { Console.WriteLine(str); } // After using RemoveFirst() method Console.WriteLine(\"Best students of XYZ\"+ \" university in 2002:\"); my_list.RemoveFirst(); foreach(string str in my_list) { Console.WriteLine(str); } // After using RemoveLast() method Console.WriteLine(\"Best students of XYZ\"+ \" university in 2003:\"); my_list.RemoveLast(); foreach(string str in my_list) { Console.WriteLine(str); } // After using Clear() method my_list.Clear(); Console.WriteLine(\"Number of students: {0}\", my_list.Count); }}", "e": 6758, "s": 4595, "text": null }, { "code": null, "e": 7100, "s": 6758, "text": "Best students of XYZ university initially:\nZoya\nShilpa\nRohit\nRohan\nJuhi\nZoya\nBest students of XYZ university in 2000:\nShilpa\nRohit\nRohan\nJuhi\nZoya\nBest students of XYZ university in 2001:\nShilpa\nRohan\nJuhi\nZoya\nBest students of XYZ university in 2002:\nRohan\nJuhi\nZoya\nBest students of XYZ university in 2003:\nRohan\nJuhi\nNumber of students: 0" }, { "code": null, "e": 7282, "s": 7100, "text": "In LinkedList, you can check whether the given value is present or not using the Contains(T) method. This method is used to determine whether a value is in the LinkedList. Example: " }, { "code": null, "e": 7289, "s": 7282, "text": "CSharp" }, { "code": "// C# program to illustrate how // to check whether the given // element is present or not // in the LinkedListusing System;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Creating a linkedlist // Using LinkedList class LinkedList<String> my_list = new LinkedList<String>(); // Adding elements in the Linkedlist // Using AddLast() method my_list.AddLast(\"Zoya\"); my_list.AddLast(\"Shilpa\"); my_list.AddLast(\"Rohit\"); my_list.AddLast(\"Rohan\"); my_list.AddLast(\"Juhi\"); // Check if the given element // is available or not if (my_list.Contains(\"Shilpa\") == true) { Console.WriteLine(\"Element Found...!!\"); } else { Console.WriteLine(\"Element Not found...!!\"); } }}", "e": 8166, "s": 7289, "text": null }, { "code": null, "e": 8185, "s": 8166, "text": "Element Found...!!" }, { "code": null, "e": 8201, "s": 8185, "text": "simranarora5sos" }, { "code": null, "e": 8226, "s": 8201, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 8244, "s": 8226, "text": "CSharp-LinkedList" }, { "code": null, "e": 8247, "s": 8244, "text": "C#" }, { "code": null, "e": 8259, "s": 8247, "text": "Linked List" }, { "code": null, "e": 8271, "s": 8259, "text": "Linked List" }, { "code": null, "e": 8369, "s": 8271, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8423, "s": 8369, "text": "Difference between Abstract Class and Interface in C#" }, { "code": null, "e": 8485, "s": 8423, "text": "C# | How to check whether a List contains a specified element" }, { "code": null, "e": 8508, "s": 8485, "text": "C# | Arrays of Strings" }, { "code": null, "e": 8550, "s": 8508, "text": "String.Split() Method in C# with Examples" }, { "code": null, "e": 8578, "s": 8550, "text": "C# | IsNullOrEmpty() Method" }, { "code": null, "e": 8613, "s": 8578, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 8652, "s": 8613, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 8674, "s": 8652, "text": "Reverse a linked list" }, { "code": null, "e": 8722, "s": 8674, "text": "Stack Data Structure (Introduction and Program)" } ]
How to create table with 100% width, with vertical scroll inside table body in HTML ?
12 Mar, 2019 The approach of this article is to create table with 100% width using width property and create vertical scroll inside table body using overflow-y property. Overflow property is used to create scrollbar in table. Use display: block; property to display the block level element. Since changing the display property of tbody, we should change the property for thead element as well to prevent from breaking the table layout. Example: <!DOCTYPE html><html> <head> <title> Display table with vertical scrollbar </title> <style> table.scrolldown { width: 100%; /* border-collapse: collapse; */ border-spacing: 0; border: 2px solid black; } /* To display the block as level element */ table.scrolldown tbody, table.scrolldown thead { display: block; } thead tr th { height: 40px; line-height: 40px; } table.scrolldown tbody { /* Set the height of table body */ height: 50px; /* Set vertical scroll */ overflow-y: auto; /* Hide the horizontal scroll */ overflow-x: hidden; } tbody { border-top: 2px solid black; } tbody td, thead th { width : 200px; border-right: 2px solid black; } td { text-align:center; } </style></head> <body> <table class="scrolldown"> <!-- Table head content --> <thead> <tr> <th>Heading 1</th> <th>Heading 2</th> <th>Heading 3</th> <th>Heading 4</th> <th>Heading 5</th> </tr> </thead> <!-- Table body content --> <tbody> <tr> <td>Content</td> <td>Content</td> <td>Content</td> <td>Content</td> <td>Content</td> </tr> <tr> <td>Content</td> <td>Content</td> <td>Content</td> <td>Content</td> <td>Content</td> </tr> <tr> <td>Content</td> <td>Content</td> <td>Content</td> <td>Content</td> <td>Content</td> </tr> </tbody> </table><body> </html> Output: HTML-Misc Picked HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTTP headers | Content-Type Design a Tribute Page using HTML & CSS How to Insert Form Data into Database using PHP ? How to position a div at the bottom of its container using CSS? Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Mar, 2019" }, { "code": null, "e": 451, "s": 28, "text": "The approach of this article is to create table with 100% width using width property and create vertical scroll inside table body using overflow-y property. Overflow property is used to create scrollbar in table. Use display: block; property to display the block level element. Since changing the display property of tbody, we should change the property for thead element as well to prevent from breaking the table layout." }, { "code": null, "e": 460, "s": 451, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Display table with vertical scrollbar </title> <style> table.scrolldown { width: 100%; /* border-collapse: collapse; */ border-spacing: 0; border: 2px solid black; } /* To display the block as level element */ table.scrolldown tbody, table.scrolldown thead { display: block; } thead tr th { height: 40px; line-height: 40px; } table.scrolldown tbody { /* Set the height of table body */ height: 50px; /* Set vertical scroll */ overflow-y: auto; /* Hide the horizontal scroll */ overflow-x: hidden; } tbody { border-top: 2px solid black; } tbody td, thead th { width : 200px; border-right: 2px solid black; } td { text-align:center; } </style></head> <body> <table class=\"scrolldown\"> <!-- Table head content --> <thead> <tr> <th>Heading 1</th> <th>Heading 2</th> <th>Heading 3</th> <th>Heading 4</th> <th>Heading 5</th> </tr> </thead> <!-- Table body content --> <tbody> <tr> <td>Content</td> <td>Content</td> <td>Content</td> <td>Content</td> <td>Content</td> </tr> <tr> <td>Content</td> <td>Content</td> <td>Content</td> <td>Content</td> <td>Content</td> </tr> <tr> <td>Content</td> <td>Content</td> <td>Content</td> <td>Content</td> <td>Content</td> </tr> </tbody> </table><body> </html> ", "e": 2608, "s": 460, "text": null }, { "code": null, "e": 2616, "s": 2608, "text": "Output:" }, { "code": null, "e": 2626, "s": 2616, "text": "HTML-Misc" }, { "code": null, "e": 2633, "s": 2626, "text": "Picked" }, { "code": null, "e": 2638, "s": 2633, "text": "HTML" }, { "code": null, "e": 2655, "s": 2638, "text": "Web Technologies" }, { "code": null, "e": 2682, "s": 2655, "text": "Web technologies Questions" }, { "code": null, "e": 2687, "s": 2682, "text": "HTML" }, { "code": null, "e": 2785, "s": 2687, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2809, "s": 2785, "text": "REST API (Introduction)" }, { "code": null, "e": 2837, "s": 2809, "text": "HTTP headers | Content-Type" }, { "code": null, "e": 2876, "s": 2837, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2926, "s": 2876, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 2990, "s": 2926, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 3023, "s": 2990, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3084, "s": 3023, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3127, "s": 3084, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 3199, "s": 3127, "text": "Differences between Functional Components and Class Components in React" } ]
Animated Splash Screen in Android Using Jetpack Compose
08 Sep, 2021 Jetpack Compose is Android’s advanced toolkit for creating materialistic UI in a very simpler form. It does not require any kind of XML files in Android Studio also it helps to create native applications as well. It is recently launched in the Android Studio Arctic Fox version. Jetpack Compose Functions are declared as: @Composable fun MessageCard(name: String) { Text(text = "Hello $name!") } Preview Compose Functions: @Preview @Composable fun PreviewMessageCard() { MessageCard("Android") } Splash Screen is usually the first screen that represents your application through the logo or name of the application. It stays for few seconds and then automatically leads you to your main screen. You can use your logo or any kind of informative text that signifies your application. Animated Splash Screen looks pretty attractive to users as the logo or any kind of text can be animated to make it more interesting. Jetpack Compose provides a variety of APIs to decide which Animations to be performed. In this project, we are going to use Animatable API to implement our splash screen. You can customize your animation effect as well as the delay time according to your preference. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Jetpack Compose. Requirements: Android Studio Arctic Fox Version Kotlin Image (.png) Step 1: Create a New Project Create a new project in Android Studio using Empty Compose Activity and select the language as Kotlin. Click Finish. Step 2: Add Dependency Adding Navigation dependency into build.gradle(:app) file located in Gradle Scripts folder. implementation “androidx.navigation:navigation-compose:2.4.0-alpha06” Step 3: Add Image to Drawable Folder Add an image/logo (.png) into drawable folder. The naming convention of an image should be in lowercase without any symbols or numbers or space. Step 4: Working with the MainActivity.kt file Create a Composable Function for Navigation Kotlin @Composablefun Navigation() { val navController = rememberNavController() NavHost(navController = navController, startDestination = "splash_screen") { composable("splash_screen") { SplashScreen(navController = navController) } // Main Screen composable("main_screen") { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text(text = "Main Screen", color = Color.Black, fontSize = 24.sp) } } }} Create a Composable Function for Splash Screen Kotlin @Composablefun SplashScreen(navController: NavController) { val scale = remember { androidx.compose.animation.core.Animatable(0f) } // AnimationEffect LaunchedEffect(key1 = true) { scale.animateTo( targetValue = 0.7f, animationSpec = tween( durationMillis = 800, easing = { OvershootInterpolator(4f).getInterpolation(it) }) ) delay(3000L) navController.navigate("main_screen") } // Image Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) { Image(painter = painterResource(id = R.drawable.gfglogo), contentDescription = "Logo", modifier = Modifier.scale(scale.value)) }} Go to the MainActivity.kt file and refer to the following code. Below is the complete code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail. Kotlin package com.example.splashscreenjc import android.os.Bundleimport android.view.animation.OvershootInterpolatorimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.animation.core.tweenimport androidx.compose.foundation.Imageimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.material.Surfaceimport androidx.compose.material.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.rememberimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.scaleimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.unit.spimport androidx.navigation.NavControllerimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport kotlinx.coroutines.delay class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Surface(color = Color.White, modifier = Modifier.fillMaxSize()) { com.example.splashscreenjc.Navigation() } } }}@Composablefun Navigation() { val navController = rememberNavController() NavHost(navController = navController, startDestination = "splash_screen") { composable("splash_screen") { SplashScreen(navController = navController) } // Main Screen composable("main_screen") { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text(text = "Main Screen", color = Color.Black, fontSize = 24.sp) } } }}@Composablefun SplashScreen(navController: NavController) { val scale = remember { androidx.compose.animation.core.Animatable(0f) } // Animation LaunchedEffect(key1 = true) { scale.animateTo( targetValue = 0.7f, // tween Animation animationSpec = tween( durationMillis = 800, easing = { OvershootInterpolator(4f).getInterpolation(it) })) // Customize the delay time delay(3000L) navController.navigate("main_screen") } // Image Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) { // Change the logo Image(painter = painterResource(id = R.drawable.gfglogo), contentDescription = "Logo", modifier = Modifier.scale(scale.value)) }} Output: Android-Jetpack Blogathon-2021 Android Blogathon Kotlin Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Sep, 2021" }, { "code": null, "e": 374, "s": 52, "text": "Jetpack Compose is Android’s advanced toolkit for creating materialistic UI in a very simpler form. It does not require any kind of XML files in Android Studio also it helps to create native applications as well. It is recently launched in the Android Studio Arctic Fox version. Jetpack Compose Functions are declared as:" }, { "code": null, "e": 452, "s": 374, "text": "@Composable\nfun MessageCard(name: String) {\n Text(text = \"Hello $name!\")\n}" }, { "code": null, "e": 479, "s": 452, "text": "Preview Compose Functions:" }, { "code": null, "e": 556, "s": 479, "text": "@Preview\n@Composable\nfun PreviewMessageCard() {\n MessageCard(\"Android\")\n}" }, { "code": null, "e": 842, "s": 556, "text": "Splash Screen is usually the first screen that represents your application through the logo or name of the application. It stays for few seconds and then automatically leads you to your main screen. You can use your logo or any kind of informative text that signifies your application." }, { "code": null, "e": 1242, "s": 842, "text": "Animated Splash Screen looks pretty attractive to users as the logo or any kind of text can be animated to make it more interesting. Jetpack Compose provides a variety of APIs to decide which Animations to be performed. In this project, we are going to use Animatable API to implement our splash screen. You can customize your animation effect as well as the delay time according to your preference." }, { "code": null, "e": 1410, "s": 1242, "text": "A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Jetpack Compose." }, { "code": null, "e": 1424, "s": 1410, "text": "Requirements:" }, { "code": null, "e": 1458, "s": 1424, "text": "Android Studio Arctic Fox Version" }, { "code": null, "e": 1465, "s": 1458, "text": "Kotlin" }, { "code": null, "e": 1478, "s": 1465, "text": "Image (.png)" }, { "code": null, "e": 1507, "s": 1478, "text": "Step 1: Create a New Project" }, { "code": null, "e": 1624, "s": 1507, "text": "Create a new project in Android Studio using Empty Compose Activity and select the language as Kotlin. Click Finish." }, { "code": null, "e": 1647, "s": 1624, "text": "Step 2: Add Dependency" }, { "code": null, "e": 1739, "s": 1647, "text": "Adding Navigation dependency into build.gradle(:app) file located in Gradle Scripts folder." }, { "code": null, "e": 1809, "s": 1739, "text": "implementation “androidx.navigation:navigation-compose:2.4.0-alpha06”" }, { "code": null, "e": 1846, "s": 1809, "text": "Step 3: Add Image to Drawable Folder" }, { "code": null, "e": 1991, "s": 1846, "text": "Add an image/logo (.png) into drawable folder. The naming convention of an image should be in lowercase without any symbols or numbers or space." }, { "code": null, "e": 2037, "s": 1991, "text": "Step 4: Working with the MainActivity.kt file" }, { "code": null, "e": 2081, "s": 2037, "text": "Create a Composable Function for Navigation" }, { "code": null, "e": 2088, "s": 2081, "text": "Kotlin" }, { "code": "@Composablefun Navigation() { val navController = rememberNavController() NavHost(navController = navController, startDestination = \"splash_screen\") { composable(\"splash_screen\") { SplashScreen(navController = navController) } // Main Screen composable(\"main_screen\") { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text(text = \"Main Screen\", color = Color.Black, fontSize = 24.sp) } } }}", "e": 2608, "s": 2088, "text": null }, { "code": null, "e": 2655, "s": 2608, "text": "Create a Composable Function for Splash Screen" }, { "code": null, "e": 2662, "s": 2655, "text": "Kotlin" }, { "code": "@Composablefun SplashScreen(navController: NavController) { val scale = remember { androidx.compose.animation.core.Animatable(0f) } // AnimationEffect LaunchedEffect(key1 = true) { scale.animateTo( targetValue = 0.7f, animationSpec = tween( durationMillis = 800, easing = { OvershootInterpolator(4f).getInterpolation(it) }) ) delay(3000L) navController.navigate(\"main_screen\") } // Image Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) { Image(painter = painterResource(id = R.drawable.gfglogo), contentDescription = \"Logo\", modifier = Modifier.scale(scale.value)) }}", "e": 3465, "s": 2662, "text": null }, { "code": null, "e": 3660, "s": 3465, "text": "Go to the MainActivity.kt file and refer to the following code. Below is the complete code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 3667, "s": 3660, "text": "Kotlin" }, { "code": "package com.example.splashscreenjc import android.os.Bundleimport android.view.animation.OvershootInterpolatorimport androidx.activity.ComponentActivityimport androidx.activity.compose.setContentimport androidx.compose.animation.core.tweenimport androidx.compose.foundation.Imageimport androidx.compose.foundation.layout.Boximport androidx.compose.foundation.layout.fillMaxSizeimport androidx.compose.material.Surfaceimport androidx.compose.material.Textimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.rememberimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.draw.scaleimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.res.painterResourceimport androidx.compose.ui.unit.spimport androidx.navigation.NavControllerimport androidx.navigation.compose.NavHostimport androidx.navigation.compose.composableimport androidx.navigation.compose.rememberNavControllerimport kotlinx.coroutines.delay class MainActivity : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { Surface(color = Color.White, modifier = Modifier.fillMaxSize()) { com.example.splashscreenjc.Navigation() } } }}@Composablefun Navigation() { val navController = rememberNavController() NavHost(navController = navController, startDestination = \"splash_screen\") { composable(\"splash_screen\") { SplashScreen(navController = navController) } // Main Screen composable(\"main_screen\") { Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) { Text(text = \"Main Screen\", color = Color.Black, fontSize = 24.sp) } } }}@Composablefun SplashScreen(navController: NavController) { val scale = remember { androidx.compose.animation.core.Animatable(0f) } // Animation LaunchedEffect(key1 = true) { scale.animateTo( targetValue = 0.7f, // tween Animation animationSpec = tween( durationMillis = 800, easing = { OvershootInterpolator(4f).getInterpolation(it) })) // Customize the delay time delay(3000L) navController.navigate(\"main_screen\") } // Image Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) { // Change the logo Image(painter = painterResource(id = R.drawable.gfglogo), contentDescription = \"Logo\", modifier = Modifier.scale(scale.value)) }}", "e": 6442, "s": 3667, "text": null }, { "code": null, "e": 6450, "s": 6442, "text": "Output:" }, { "code": null, "e": 6466, "s": 6450, "text": "Android-Jetpack" }, { "code": null, "e": 6481, "s": 6466, "text": "Blogathon-2021" }, { "code": null, "e": 6489, "s": 6481, "text": "Android" }, { "code": null, "e": 6499, "s": 6489, "text": "Blogathon" }, { "code": null, "e": 6506, "s": 6499, "text": "Kotlin" }, { "code": null, "e": 6514, "s": 6506, "text": "Android" } ]
C library function - memmove()
The C library function void *memmove(void *str1, const void *str2, size_t n) copies n characters from str2 to str1, but for overlapping memory blocks, memmove() is a safer approach than memcpy(). Following is the declaration for memmove() function. void *memmove(void *str1, const void *str2, size_t n) str1 − This is a pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*. str1 − This is a pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*. str2 − This is a pointer to the source of data to be copied, type-casted to a pointer of type void*. str2 − This is a pointer to the source of data to be copied, type-casted to a pointer of type void*. n − This is the number of bytes to be copied. n − This is the number of bytes to be copied. This function returns a pointer to the destination, which is str1. The following example shows the usage of memmove() function. #include <stdio.h> #include <string.h> int main () { char dest[] = "oldstring"; const char src[] = "newstring"; printf("Before memmove dest = %s, src = %s\n", dest, src); memmove(dest, src, 9); printf("After memmove dest = %s, src = %s\n", dest, src); return(0); } Let us compile and run the above program that will produce the following result − Before memmove dest = oldstring, src = newstring After memmove dest = newstring, src = newstring
[ { "code": null, "e": 2337, "s": 2141, "text": "The C library function void *memmove(void *str1, const void *str2, size_t n) copies n characters from str2 to str1, but for overlapping memory blocks, memmove() is a safer approach than memcpy()." }, { "code": null, "e": 2390, "s": 2337, "text": "Following is the declaration for memmove() function." }, { "code": null, "e": 2444, "s": 2390, "text": "void *memmove(void *str1, const void *str2, size_t n)" }, { "code": null, "e": 2569, "s": 2444, "text": "str1 − This is a pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*." }, { "code": null, "e": 2694, "s": 2569, "text": "str1 − This is a pointer to the destination array where the content is to be copied, type-casted to a pointer of type void*." }, { "code": null, "e": 2795, "s": 2694, "text": "str2 − This is a pointer to the source of data to be copied, type-casted to a pointer of type void*." }, { "code": null, "e": 2896, "s": 2795, "text": "str2 − This is a pointer to the source of data to be copied, type-casted to a pointer of type void*." }, { "code": null, "e": 2942, "s": 2896, "text": "n − This is the number of bytes to be copied." }, { "code": null, "e": 2988, "s": 2942, "text": "n − This is the number of bytes to be copied." }, { "code": null, "e": 3055, "s": 2988, "text": "This function returns a pointer to the destination, which is str1." }, { "code": null, "e": 3116, "s": 3055, "text": "The following example shows the usage of memmove() function." }, { "code": null, "e": 3403, "s": 3116, "text": "#include <stdio.h>\n#include <string.h>\n\nint main () {\n char dest[] = \"oldstring\";\n const char src[] = \"newstring\";\n\n printf(\"Before memmove dest = %s, src = %s\\n\", dest, src);\n memmove(dest, src, 9);\n printf(\"After memmove dest = %s, src = %s\\n\", dest, src);\n\n return(0);\n}" }, { "code": null, "e": 3485, "s": 3403, "text": "Let us compile and run the above program that will produce the following result −" } ]
HTML5 - Interview Questions
Dear readers, these HTML5 Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of HTML5. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer: HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web. HTML5 introduces a number of new elements and attributes that helps in building a modern websites. Following are great features introduced in HTML5 − New Semantic Elements − These are like <header>, <footer>, and <section>. New Semantic Elements − These are like <header>, <footer>, and <section>. Forms 2.0 − Improvements to HTML web forms where new attributes have been introduced for <input> tag. Forms 2.0 − Improvements to HTML web forms where new attributes have been introduced for <input> tag. Persistent Local Storage − To achieve without resorting to third-party plugins. Persistent Local Storage − To achieve without resorting to third-party plugins. WebSocket − A a next-generation bidirectional communication technology for web applications. WebSocket − A a next-generation bidirectional communication technology for web applications. Server-Sent Events − HTML5 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE). Server-Sent Events − HTML5 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE). Canvas − This supports a two-dimensional drawing surface that you can program with JavaScript. Canvas − This supports a two-dimensional drawing surface that you can program with JavaScript. Audio & Video − You can embed audio or video on your web pages without resorting to third-party plugins. Audio & Video − You can embed audio or video on your web pages without resorting to third-party plugins. Geolocation − Now visitors can choose to share their physical location with your web application. Geolocation − Now visitors can choose to share their physical location with your web application. Microdata − This lets you create your own vocabularies beyond HTML5 and extend your web pages with custom semantics. Microdata − This lets you create your own vocabularies beyond HTML5 and extend your web pages with custom semantics. Drag and drop − Drag and drop the items from one location to another location on a the same webpage. Drag and drop − Drag and drop the items from one location to another location on a the same webpage. The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality. The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have excellent support for HTML5. Yes! HTML5 is designed, as much as possible, to be backward compatible with existing web browsers. New features build on existing features and allow you to provide fallback content for older browsers. It is suggested to detect support for individual HTML5 features using a few lines of JavaScript. No! This tag represents a generic document or application section. It can be used together with h1-h6 to indicate the document structure. This tag represents an independent piece of content of a document, such as a blog entry or newspaper article. This tag represents a piece of content that is only slightly related to the rest of the page. This tag represents the header of a section. This tag represents a footer for a section and can contain information about the author, copyright information, et cetera. This tag represents a section of the document intended for navigation. This tag can be used to mark up a conversation. This tag can be used to associate a caption together with some embedded content, such as a graphic or video. A custom data attribute starts with data- and would be named based on your requirement. Following is the simple example− <div class="example" data-subject="physics" data-level="complex"> ... </div> The above will be perfectly valid HTML5 with two custom attributes called data-subject and data-level. You would be able to get the values of these attributes using JavaScript APIs or CSS in similar way as you get for standard attributes. Web Forms 2.0 is an extension to the forms features found in HTML4. Form elements and attributes in HTML5 provide a greater degree of semantic mark-up than HTML4 and remove a great deal of the need for tedious scripting and styling that was required in HTML4. It represents a date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC. It represents a date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with no time zone information. It represents a date (year, month, day) encoded according to ISO 8601. It represents a date consisting of a year and a month encoded according to ISO 8601. It represents a date consisting of a year and a week number encoded according to ISO 8601. It represents a time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601. This control accepts only numerical value. The step attribute specifies the precision, defaulting to 1. The range type is used for input fields that should contain a value from a range of numbers. This accepts only email value. This type is used for input fields that should contain an e-mail address. If you try to submit a simple text, it forces to enter only email address in [email protected] format. This accepts only URL value. This type is used for input fields that should contain a URL address. If you try to submit a simple text, it forces to enter only URL address either in http://www.example.com format or in http://example.com format. HTML5 introduced a new element <output> which is used to represent the result of different types of output, such as output written by a script. HTML5 introduced a new attribute called placeholder. This attribute on <input> and <textarea> elements provides a hint to the user of what can be entered in the field. The placeholder text must not contain carriage returns or line-feeds. This is a simple one-step pattern, easily programmed in JavaScript at the time of document load, automatically focus one particular form field. HTML5 introduced a new attribute called required which would insist to have a value in an input control. Yes! HTML5 allows embeding SVG directly using <svg>...</svg> tag. Yes! The HTML syntax of HTML5 allows for MathML elements to be used inside a document using <math>...</math> tags. Cookies have following drawbacks− Cookies are included with every HTTP request, thereby slowing down your web application by transmitting the same data. Cookies are included with every HTTP request, thereby slowing down your web application by transmitting the same data. Cookies are included with every HTTP request, thereby sending data unencrypted over the internet. Cookies are included with every HTTP request, thereby sending data unencrypted over the internet. Cookies are limited to about 4 KB of data . Not enough to store required data. Cookies are limited to about 4 KB of data . Not enough to store required data. HTML5 introduces the sessionStorage attribute which would be used by the sites to add data to the session storage, and it will be accessible to any page from the same site opened in that window i.e. session and as soon as you close the window, session would be lost. HTML5 introduces the localStorage attribute which would be used to access a page's local storage area without no time limit and this local storage will be available whenever you would use that page. The Session Storage Data would be deleted by the browsers immediately after the session gets terminated. local storage data has no time limit. To clear a local storage setting you would need to call localStorage.remove('key'); where 'key' is the key of the value you want to remove. If you want to clear all settings, you need to call localStorage.clear() method. Along with HTML5, WHATWG Web Applications 1.0 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE). Using SSE you can push DOM events continously from your web server to the visitor's browser. The event streaming approach opens a persistent connection to the server, sending data to the client when new information is available, eliminating the need for continuous polling. Server-sent events standardizes how we stream data from the server to the client. To use Server-Sent Events in a web application, you would need to add an <eventsource> element to the document. The src attribute of <eventsource> element should point to an URL which should provide a persistent HTTP connection that sends a data stream containing the events. The URL would point to a PHP, PERL or any Python script which would take care of sending event data consistently. server side script should send Content-type header specifying the type text/event-stream as follows− print "Content-Type: text/event-stream\n\n"; After setting Content-Type, server side script would send an Event − tag followed by event name. Following example would send Server-Time as event name terminated by a new line character. print "Event: server-time\n"; Final step is to send event data using Data − tag which would be followed by integer of string value terminated by a new line character as follows− $time = localtime(); print "Data: $time\n"; Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers. Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler. Following is the API which creates a new WebSocket object. Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful. The readonly attribute readyState represents the state of the connection. It can have the following values: A value of 0 indicates that the connection has not yet been established. A value of 0 indicates that the connection has not yet been established. A value of 1 indicates that the connection is established and communication is possible. A value of 1 indicates that the connection is established and communication is possible. A value of 2 indicates that the connection is going through the closing handshake. A value of 2 indicates that the connection is going through the closing handshake. A value of 3 indicates that the connection has been closed or could not be opened. A value of 3 indicates that the connection has been closed or could not be opened. The readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using send() method. HTML5 element <canvas> gives you an easy and powerful way to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions or do simple (and not so simple) animations. HTML5 supports <audio> tag which is used to embed sound content in an HTML or XHTML document. The current HTML5 draft specification does not specify which audio formats browsers should support in the audio tag. But most commonly used audio formats are ogg, mp3 and wav. You can use <source> tag to specify media along with media type and many other attributes. An audio element allows multiple source elements and browser will use the first recognized format. HTML5 supports <video> tag which is used to embed a video file in an HTML or XHTML document.The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. But most commonly used video formats are− Ogg − Ogg files with Thedora video codec and Vorbis audio codec. Ogg − Ogg files with Thedora video codec and Vorbis audio codec. mpeg4 − MPEG4 files with H.264 video codec and AAC audio codec. mpeg4 − MPEG4 files with H.264 video codec and AAC audio codec. You can use <source> tag to specify media along with media type and many other attributes. An audio element allows multiple source elements and browser will use the first recognized format. HTML5 Geolocation API lets you share your location with your favorite web sites. A Javascript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map. Today most of the browsers and mobile devices support Geolocation API. The geolocation APIs work with a new property of the global navigator object ie. Geolocation object which can be created as follows: The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device. This method retrieves the current geographic location of the user. This method retrieves periodic updates about the current geographic location of the device. This method cancels an ongoing watchPosition call. Web Workers do all the computationally expensive tasks without interrupting the user interface and typically run on separate threads. Web Workers allow for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive. Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong. Second it really doesn't matter much if you could not answer few questions but it matters that whatever you answered, you must have answered with confidence. So just feel confident during your interview. We at tutorialspoint wish you best luck to have a good interviewer and all the very best for your future endeavor. Cheers :-)
[ { "code": null, "e": 3176, "s": 2742, "text": "Dear readers, these HTML5 Interview Questions have been designed specially to get you acquainted with the nature of questions you may encounter during your interview for the subject of HTML5. As per my experience good interviewers hardly plan to ask any particular question during your interview, normally questions start with some basic concept of the subject and later they continue based on further discussion and what you answer:" }, { "code": null, "e": 3361, "s": 3176, "text": "HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web." }, { "code": null, "e": 3511, "s": 3361, "text": "HTML5 introduces a number of new elements and attributes that helps in building a modern websites. Following are great features introduced in HTML5 −" }, { "code": null, "e": 3585, "s": 3511, "text": "New Semantic Elements − These are like <header>, <footer>, and <section>." }, { "code": null, "e": 3659, "s": 3585, "text": "New Semantic Elements − These are like <header>, <footer>, and <section>." }, { "code": null, "e": 3761, "s": 3659, "text": "Forms 2.0 − Improvements to HTML web forms where new attributes have been introduced for <input> tag." }, { "code": null, "e": 3863, "s": 3761, "text": "Forms 2.0 − Improvements to HTML web forms where new attributes have been introduced for <input> tag." }, { "code": null, "e": 3943, "s": 3863, "text": "Persistent Local Storage − To achieve without resorting to third-party plugins." }, { "code": null, "e": 4023, "s": 3943, "text": "Persistent Local Storage − To achieve without resorting to third-party plugins." }, { "code": null, "e": 4116, "s": 4023, "text": "WebSocket − A a next-generation bidirectional communication technology for web applications." }, { "code": null, "e": 4209, "s": 4116, "text": "WebSocket − A a next-generation bidirectional communication technology for web applications." }, { "code": null, "e": 4347, "s": 4209, "text": "Server-Sent Events − HTML5 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE)." }, { "code": null, "e": 4485, "s": 4347, "text": "Server-Sent Events − HTML5 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE)." }, { "code": null, "e": 4580, "s": 4485, "text": "Canvas − This supports a two-dimensional drawing surface that you can program with JavaScript." }, { "code": null, "e": 4675, "s": 4580, "text": "Canvas − This supports a two-dimensional drawing surface that you can program with JavaScript." }, { "code": null, "e": 4780, "s": 4675, "text": "Audio & Video − You can embed audio or video on your web pages without resorting to third-party plugins." }, { "code": null, "e": 4885, "s": 4780, "text": "Audio & Video − You can embed audio or video on your web pages without resorting to third-party plugins." }, { "code": null, "e": 4983, "s": 4885, "text": "Geolocation − Now visitors can choose to share their physical location with your web application." }, { "code": null, "e": 5081, "s": 4983, "text": "Geolocation − Now visitors can choose to share their physical location with your web application." }, { "code": null, "e": 5198, "s": 5081, "text": "Microdata − This lets you create your own vocabularies beyond HTML5 and extend your web pages with custom semantics." }, { "code": null, "e": 5315, "s": 5198, "text": "Microdata − This lets you create your own vocabularies beyond HTML5 and extend your web pages with custom semantics." }, { "code": null, "e": 5416, "s": 5315, "text": "Drag and drop − Drag and drop the items from one location to another location on a the same webpage." }, { "code": null, "e": 5517, "s": 5416, "text": "Drag and drop − Drag and drop the items from one location to another location on a the same webpage." }, { "code": null, "e": 5707, "s": 5517, "text": "The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality." }, { "code": null, "e": 5831, "s": 5707, "text": "The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have excellent support for HTML5." }, { "code": null, "e": 6032, "s": 5831, "text": "Yes! HTML5 is designed, as much as possible, to be backward compatible with existing web browsers. New features build on existing features and allow you to provide fallback content for older browsers." }, { "code": null, "e": 6129, "s": 6032, "text": "It is suggested to detect support for individual HTML5 features using a few lines of JavaScript." }, { "code": null, "e": 6133, "s": 6129, "text": "No!" }, { "code": null, "e": 6267, "s": 6133, "text": "This tag represents a generic document or application section. It can be used together with h1-h6 to indicate the document structure." }, { "code": null, "e": 6377, "s": 6267, "text": "This tag represents an independent piece of content of a document, such as a blog entry or newspaper article." }, { "code": null, "e": 6471, "s": 6377, "text": "This tag represents a piece of content that is only slightly related to the rest of the page." }, { "code": null, "e": 6516, "s": 6471, "text": "This tag represents the header of a section." }, { "code": null, "e": 6639, "s": 6516, "text": "This tag represents a footer for a section and can contain information about the author, copyright information, et cetera." }, { "code": null, "e": 6710, "s": 6639, "text": "This tag represents a section of the document intended for navigation." }, { "code": null, "e": 6758, "s": 6710, "text": "This tag can be used to mark up a conversation." }, { "code": null, "e": 6867, "s": 6758, "text": "This tag can be used to associate a caption together with some embedded content, such as a graphic or video." }, { "code": null, "e": 6988, "s": 6867, "text": "A custom data attribute starts with data- and would be named based on your requirement. Following is the simple example−" }, { "code": null, "e": 7068, "s": 6988, "text": "<div class=\"example\" data-subject=\"physics\" data-level=\"complex\">\n ...\n</div>" }, { "code": null, "e": 7307, "s": 7068, "text": "The above will be perfectly valid HTML5 with two custom attributes called data-subject and data-level. You would be able to get the values of these attributes using JavaScript APIs or CSS in similar way as you get for standard attributes." }, { "code": null, "e": 7567, "s": 7307, "text": "Web Forms 2.0 is an extension to the forms features found in HTML4. Form elements and attributes in HTML5 provide a greater degree of semantic mark-up than HTML4 and remove a great deal of the need for tedious scripting and styling that was required in HTML4." }, { "code": null, "e": 7722, "s": 7567, "text": "It represents a date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC." }, { "code": null, "e": 7877, "s": 7722, "text": "It represents a date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with no time zone information." }, { "code": null, "e": 7948, "s": 7877, "text": "It represents a date (year, month, day) encoded according to ISO 8601." }, { "code": null, "e": 8033, "s": 7948, "text": "It represents a date consisting of a year and a month encoded according to ISO 8601." }, { "code": null, "e": 8124, "s": 8033, "text": "It represents a date consisting of a year and a week number encoded according to ISO 8601." }, { "code": null, "e": 8220, "s": 8124, "text": "It represents a time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601." }, { "code": null, "e": 8324, "s": 8220, "text": "This control accepts only numerical value. The step attribute specifies the precision, defaulting to 1." }, { "code": null, "e": 8417, "s": 8324, "text": "The range type is used for input fields that should contain a value from a range of numbers." }, { "code": null, "e": 8625, "s": 8417, "text": "This accepts only email value. This type is used for input fields that should contain an e-mail address. If you try to submit a simple text, it forces to enter only email address in [email protected] format." }, { "code": null, "e": 8869, "s": 8625, "text": "This accepts only URL value. This type is used for input fields that should contain a URL address. If you try to submit a simple text, it forces to enter only URL address either in http://www.example.com format or in http://example.com format." }, { "code": null, "e": 9013, "s": 8869, "text": "HTML5 introduced a new element <output> which is used to represent the result of different types of output, such as output written by a script." }, { "code": null, "e": 9251, "s": 9013, "text": "HTML5 introduced a new attribute called placeholder. This attribute on <input> and <textarea> elements provides a hint to the user of what can be entered in the field. The placeholder text must not contain carriage returns or line-feeds." }, { "code": null, "e": 9395, "s": 9251, "text": "This is a simple one-step pattern, easily programmed in JavaScript at the time of document load, automatically focus one particular form field." }, { "code": null, "e": 9500, "s": 9395, "text": "HTML5 introduced a new attribute called required which would insist to have a value in an input control." }, { "code": null, "e": 9566, "s": 9500, "text": "Yes! HTML5 allows embeding SVG directly using <svg>...</svg> tag." }, { "code": null, "e": 9681, "s": 9566, "text": "Yes! The HTML syntax of HTML5 allows for MathML elements to be used inside a document using <math>...</math> tags." }, { "code": null, "e": 9715, "s": 9681, "text": "Cookies have following drawbacks−" }, { "code": null, "e": 9834, "s": 9715, "text": "Cookies are included with every HTTP request, thereby slowing down your web application by transmitting the same data." }, { "code": null, "e": 9953, "s": 9834, "text": "Cookies are included with every HTTP request, thereby slowing down your web application by transmitting the same data." }, { "code": null, "e": 10051, "s": 9953, "text": "Cookies are included with every HTTP request, thereby sending data unencrypted over the internet." }, { "code": null, "e": 10149, "s": 10051, "text": "Cookies are included with every HTTP request, thereby sending data unencrypted over the internet." }, { "code": null, "e": 10228, "s": 10149, "text": "Cookies are limited to about 4 KB of data . Not enough to store required data." }, { "code": null, "e": 10307, "s": 10228, "text": "Cookies are limited to about 4 KB of data . Not enough to store required data." }, { "code": null, "e": 10574, "s": 10307, "text": "HTML5 introduces the sessionStorage attribute which would be used by the sites to add data to the session storage, and it will be accessible to any page from the same site opened in that window i.e. session and as soon as you close the window, session would be lost." }, { "code": null, "e": 10773, "s": 10574, "text": "HTML5 introduces the localStorage attribute which would be used to access a page's local storage area without no time limit and this local storage will be available whenever you would use that page." }, { "code": null, "e": 10878, "s": 10773, "text": "The Session Storage Data would be deleted by the browsers immediately after the session gets terminated." }, { "code": null, "e": 11137, "s": 10878, "text": "local storage data has no time limit. To clear a local storage setting you would need to call localStorage.remove('key'); where 'key' is the key of the value you want to remove. If you want to clear all settings, you need to call localStorage.clear() method." }, { "code": null, "e": 11387, "s": 11137, "text": "Along with HTML5, WHATWG Web Applications 1.0 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE). Using SSE you can push DOM events continously from your web server to the visitor's browser." }, { "code": null, "e": 11568, "s": 11387, "text": "The event streaming approach opens a persistent connection to the server, sending data to the client when new information is available, eliminating the need for continuous polling." }, { "code": null, "e": 11650, "s": 11568, "text": "Server-sent events standardizes how we stream data from the server to the client." }, { "code": null, "e": 11762, "s": 11650, "text": "To use Server-Sent Events in a web application, you would need to add an <eventsource> element to the document." }, { "code": null, "e": 11926, "s": 11762, "text": "The src attribute of <eventsource> element should point to an URL which should provide a persistent HTTP connection that sends a data stream containing the events." }, { "code": null, "e": 12040, "s": 11926, "text": "The URL would point to a PHP, PERL or any Python script which would take care of sending event data consistently." }, { "code": null, "e": 12142, "s": 12040, "text": " server side script should send Content-type header specifying the type text/event-stream as follows−" }, { "code": null, "e": 12187, "s": 12142, "text": "print \"Content-Type: text/event-stream\\n\\n\";" }, { "code": null, "e": 12375, "s": 12187, "text": "After setting Content-Type, server side script would send an Event − tag followed by event name. Following example would send Server-Time as event name terminated by a new line character." }, { "code": null, "e": 12405, "s": 12375, "text": "print \"Event: server-time\\n\";" }, { "code": null, "e": 12553, "s": 12405, "text": "Final step is to send event data using Data − tag which would be followed by integer of string value terminated by a new line character as follows−" }, { "code": null, "e": 12597, "s": 12553, "text": "$time = localtime();\nprint \"Data: $time\\n\";" }, { "code": null, "e": 12798, "s": 12597, "text": "Web Sockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers." }, { "code": null, "e": 12996, "s": 12798, "text": "Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler." }, { "code": null, "e": 13055, "s": 12996, "text": "Following is the API which creates a new WebSocket object." }, { "code": null, "e": 13271, "s": 13055, "text": "Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful." }, { "code": null, "e": 13379, "s": 13271, "text": "The readonly attribute readyState represents the state of the connection. It can have the following values:" }, { "code": null, "e": 13452, "s": 13379, "text": "A value of 0 indicates that the connection has not yet been established." }, { "code": null, "e": 13525, "s": 13452, "text": "A value of 0 indicates that the connection has not yet been established." }, { "code": null, "e": 13614, "s": 13525, "text": "A value of 1 indicates that the connection is established and communication is possible." }, { "code": null, "e": 13703, "s": 13614, "text": "A value of 1 indicates that the connection is established and communication is possible." }, { "code": null, "e": 13786, "s": 13703, "text": "A value of 2 indicates that the connection is going through the closing handshake." }, { "code": null, "e": 13869, "s": 13786, "text": "A value of 2 indicates that the connection is going through the closing handshake." }, { "code": null, "e": 13952, "s": 13869, "text": "A value of 3 indicates that the connection has been closed or could not be opened." }, { "code": null, "e": 14035, "s": 13952, "text": "A value of 3 indicates that the connection has been closed or could not be opened." }, { "code": null, "e": 14161, "s": 14035, "text": "The readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using send() method." }, { "code": null, "e": 14354, "s": 14161, "text": "HTML5 element <canvas> gives you an easy and powerful way to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions or do simple (and not so simple) animations." }, { "code": null, "e": 14624, "s": 14354, "text": "HTML5 supports <audio> tag which is used to embed sound content in an HTML or XHTML document. The current HTML5 draft specification does not specify which audio formats browsers should support in the audio tag. But most commonly used audio formats are ogg, mp3 and wav." }, { "code": null, "e": 14814, "s": 14624, "text": "You can use <source> tag to specify media along with media type and many other attributes. An audio element allows multiple source elements and browser will use the first recognized format." }, { "code": null, "e": 15065, "s": 14814, "text": "HTML5 supports <video> tag which is used to embed a video file in an HTML or XHTML document.The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. But most commonly used video formats are−" }, { "code": null, "e": 15130, "s": 15065, "text": "Ogg − Ogg files with Thedora video codec and Vorbis audio codec." }, { "code": null, "e": 15195, "s": 15130, "text": "Ogg − Ogg files with Thedora video codec and Vorbis audio codec." }, { "code": null, "e": 15259, "s": 15195, "text": "mpeg4 − MPEG4 files with H.264 video codec and AAC audio codec." }, { "code": null, "e": 15323, "s": 15259, "text": "mpeg4 − MPEG4 files with H.264 video codec and AAC audio codec." }, { "code": null, "e": 15513, "s": 15323, "text": "You can use <source> tag to specify media along with media type and many other attributes. An audio element allows multiple source elements and browser will use the first recognized format." }, { "code": null, "e": 15785, "s": 15513, "text": "HTML5 Geolocation API lets you share your location with your favorite web sites. A Javascript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map." }, { "code": null, "e": 15989, "s": 15785, "text": "Today most of the browsers and mobile devices support Geolocation API. The geolocation APIs work with a new property of the global navigator object ie. Geolocation object which can be created as follows:" }, { "code": null, "e": 16121, "s": 15989, "text": "The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device." }, { "code": null, "e": 16188, "s": 16121, "text": "This method retrieves the current geographic location of the user." }, { "code": null, "e": 16280, "s": 16188, "text": "This method retrieves periodic updates about the current geographic location of the device." }, { "code": null, "e": 16331, "s": 16280, "text": "This method cancels an ongoing watchPosition call." }, { "code": null, "e": 16465, "s": 16331, "text": "Web Workers do all the computationally expensive tasks without interrupting the user interface and typically run on separate threads." }, { "code": null, "e": 16678, "s": 16465, "text": "Web Workers allow for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive." }, { "code": null, "e": 16965, "s": 16678, "text": "Further you can go through your past assignments you have done with the subject and make sure you are able to speak confidently on them. If you are fresher then interviewer does not expect you will answer very complex questions, rather you have to make your basics concepts very strong." } ]
TCS Coding Practice Question | Swap two Numbers
07 Jul, 2022 Given two numbers, the task is to swap the two numbers using Command Line Arguments. Examples: Input: n1 = 10, n2 = 20 Output: 20 10 Input: n1 = 100, n2 = 101 Output: 101 100 Approach: Since the numbers are entered as Command line Arguments, there is no need for a dedicated input line Extract the input numbers from the command line argument This extracted numbers will be in string type. Convert these numbers into integer type and store it in variables, say num1 and num2 Get the sum in one of the two given numbers. The numbers can then be swapped using the sum and subtraction from the sum. Program: C Java // C program to swap the two numbers// using command line arguments #include <stdio.h>#include <stdlib.h> /* atoi */ // Function to swap the two numbersvoid swap(int x, int y){ // Code to swap ‘x’ and ‘y’ // x now becomes x+y x = x + y; // y becomes x y = x - y; // x becomes y x = x - y; printf("%d %d\n", x, y);} // Driver codeint main(int argc, char* argv[]){ int num1, num2; // Check if the length of args array is 1 if (argc == 1) printf("No command line arguments found.\n"); else { // Get the command line argument and // Convert it from string type to integer type // using function "atoi( argument)" num1 = atoi(argv[1]); num2 = atoi(argv[2]); // Swap the numbers and print it swap(num1, num2); } return 0;} // Java program to swap the two numbers// using command line arguments class GFG { // Function to swap the two numbers static void swap(int x, int y) { // Code to swap ‘x’ and ‘y’ // x now becomes x+y x = x + y; // y becomes x y = x - y; // x becomes y x = x - y; System.out.println(x + " " + y); } // Driver code public static void main(String[] args) { // Check if length of args array is // greater than 0 if (args.length > 0) { // Get the command line argument and // Convert it from string type to integer type int num1 = Integer.parseInt(args[0]); int num2 = Integer.parseInt(args[1]); // Swap the numbers swap(num1, num2); } else System.out.println("No command line " + "arguments found."); }} Output: In C: In Java: Time Complexity: O(1)Auxiliary Space: O(1) jayanth_mkv TCS TCS-coding-questions C++ Programs Java Programs Placements TCS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n07 Jul, 2022" }, { "code": null, "e": 149, "s": 53, "text": "Given two numbers, the task is to swap the two numbers using Command Line Arguments. Examples:" }, { "code": null, "e": 230, "s": 149, "text": "Input: n1 = 10, n2 = 20\nOutput: 20 10\n\nInput: n1 = 100, n2 = 101\nOutput: 101 100" }, { "code": null, "e": 240, "s": 230, "text": "Approach:" }, { "code": null, "e": 341, "s": 240, "text": "Since the numbers are entered as Command line Arguments, there is no need for a dedicated input line" }, { "code": null, "e": 398, "s": 341, "text": "Extract the input numbers from the command line argument" }, { "code": null, "e": 445, "s": 398, "text": "This extracted numbers will be in string type." }, { "code": null, "e": 530, "s": 445, "text": "Convert these numbers into integer type and store it in variables, say num1 and num2" }, { "code": null, "e": 575, "s": 530, "text": "Get the sum in one of the two given numbers." }, { "code": null, "e": 651, "s": 575, "text": "The numbers can then be swapped using the sum and subtraction from the sum." }, { "code": null, "e": 661, "s": 651, "text": "Program: " }, { "code": null, "e": 663, "s": 661, "text": "C" }, { "code": null, "e": 668, "s": 663, "text": "Java" }, { "code": "// C program to swap the two numbers// using command line arguments #include <stdio.h>#include <stdlib.h> /* atoi */ // Function to swap the two numbersvoid swap(int x, int y){ // Code to swap ‘x’ and ‘y’ // x now becomes x+y x = x + y; // y becomes x y = x - y; // x becomes y x = x - y; printf(\"%d %d\\n\", x, y);} // Driver codeint main(int argc, char* argv[]){ int num1, num2; // Check if the length of args array is 1 if (argc == 1) printf(\"No command line arguments found.\\n\"); else { // Get the command line argument and // Convert it from string type to integer type // using function \"atoi( argument)\" num1 = atoi(argv[1]); num2 = atoi(argv[2]); // Swap the numbers and print it swap(num1, num2); } return 0;}", "e": 1492, "s": 668, "text": null }, { "code": "// Java program to swap the two numbers// using command line arguments class GFG { // Function to swap the two numbers static void swap(int x, int y) { // Code to swap ‘x’ and ‘y’ // x now becomes x+y x = x + y; // y becomes x y = x - y; // x becomes y x = x - y; System.out.println(x + \" \" + y); } // Driver code public static void main(String[] args) { // Check if length of args array is // greater than 0 if (args.length > 0) { // Get the command line argument and // Convert it from string type to integer type int num1 = Integer.parseInt(args[0]); int num2 = Integer.parseInt(args[1]); // Swap the numbers swap(num1, num2); } else System.out.println(\"No command line \" + \"arguments found.\"); }}", "e": 2424, "s": 1492, "text": null }, { "code": null, "e": 2432, "s": 2424, "text": "Output:" }, { "code": null, "e": 2439, "s": 2432, "text": "In C: " }, { "code": null, "e": 2449, "s": 2439, "text": "In Java: " }, { "code": null, "e": 2492, "s": 2449, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 2504, "s": 2492, "text": "jayanth_mkv" }, { "code": null, "e": 2508, "s": 2504, "text": "TCS" }, { "code": null, "e": 2529, "s": 2508, "text": "TCS-coding-questions" }, { "code": null, "e": 2542, "s": 2529, "text": "C++ Programs" }, { "code": null, "e": 2556, "s": 2542, "text": "Java Programs" }, { "code": null, "e": 2567, "s": 2556, "text": "Placements" }, { "code": null, "e": 2571, "s": 2567, "text": "TCS" } ]
Divide each dataframe row by vector in R
17 May, 2021 In this article, we will discuss how to divide each dataframe row by vector in R Programming Language. The mapply() method can be used to apply a FUN to the dataframe or a matrix, to modify the data. The function specified as the first argument may be any boolean operator, arithmetic, or logical. The operator is then applied taking the dataframe row as one operand and the vector as the other. The result has to be stored in another variable. The time incurred in this operation is equivalent to the number of rows in the dataframe. Syntax: mapply(FUN, df , vec) Example: R # declaring dataframedata_frame <- data.frame(col1 = c(2,4,6), col2 = c(4,6,8), col3 = c(8,10,12), col4 = c(20,16,14)) print ("Original Dataframe")print (data_frame) # declaring vectorvec <- c(1:4) # dividing each row by vectordiv <- mapply('/', data_frame, vec) print ("Result of division")print (div) Output [1] "Original Dataframe" col1 col2 col3 col4 1 2 4 8 20 2 4 6 10 16 3 6 8 12 14 [1] "Result of division" col1 col2 col3 col4 [1,] 2 2 2.666667 5.0 [2,] 4 3 3.333333 4.0 [3,] 6 4 4.000000 3.5 This method in R programming language returns an array obtained from an input array by sweeping out a summary statistic. The method is used to compute arithmetic operations on the dataframe over the chosen axis. For, row-wise operation the chosen axis is 2 and the operand becomes the row of the dataframe. The result has to be stored in another variable. The time incurred in this operation is equivalent to the number of rows in the dataframe. The data type of the resultant column is the largest compatible data type. Syntax: sweep (df , axis, vec, op) Parameter : df – DataFrame axis – To compute it row-wise, use axis = 1 and for column-wise, use axis = 2 vec – The vector to apply on the dataframe op – The operator to apply Example: R # declaring dataframedata_frame <- data.frame(col1 = c(2,4,6), col2 = c(4,6,8), col3 = c(8,10,12), col4 = c(20,16,14)) print ("Original Dataframe")print (data_frame) # declaring vectorvec <- c(1:4) # dividing each row by vectordiv <- sweep(data_frame,2,vec,'/') print ("Result of division")print (div) Output [1] "Original Dataframe" col1 col2 col3 col4 1 2 4 8 20 2 4 6 10 16 3 6 8 12 14 [1] "Result of division" col1 col2 col3 col4 1 2 2 2.666667 5.0 2 4 3 3.333333 4.0 3 6 4 4.000000 3.5 Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n17 May, 2021" }, { "code": null, "e": 131, "s": 28, "text": "In this article, we will discuss how to divide each dataframe row by vector in R Programming Language." }, { "code": null, "e": 564, "s": 131, "text": "The mapply() method can be used to apply a FUN to the dataframe or a matrix, to modify the data. The function specified as the first argument may be any boolean operator, arithmetic, or logical. The operator is then applied taking the dataframe row as one operand and the vector as the other. The result has to be stored in another variable. The time incurred in this operation is equivalent to the number of rows in the dataframe. " }, { "code": null, "e": 594, "s": 564, "text": "Syntax: mapply(FUN, df , vec)" }, { "code": null, "e": 603, "s": 594, "text": "Example:" }, { "code": null, "e": 605, "s": 603, "text": "R" }, { "code": "# declaring dataframedata_frame <- data.frame(col1 = c(2,4,6), col2 = c(4,6,8), col3 = c(8,10,12), col4 = c(20,16,14)) print (\"Original Dataframe\")print (data_frame) # declaring vectorvec <- c(1:4) # dividing each row by vectordiv <- mapply('/', data_frame, vec) print (\"Result of division\")print (div)", "e": 938, "s": 605, "text": null }, { "code": null, "e": 945, "s": 938, "text": "Output" }, { "code": null, "e": 1197, "s": 945, "text": "[1] \"Original Dataframe\"\n col1 col2 col3 col4\n1 2 4 8 20\n2 4 6 10 16\n3 6 8 12 14\n[1] \"Result of division\"\n col1 col2 col3 col4\n[1,] 2 2 2.666667 5.0\n[2,] 4 3 3.333333 4.0\n[3,] 6 4 4.000000 3.5" }, { "code": null, "e": 1719, "s": 1197, "text": "This method in R programming language returns an array obtained from an input array by sweeping out a summary statistic. The method is used to compute arithmetic operations on the dataframe over the chosen axis. For, row-wise operation the chosen axis is 2 and the operand becomes the row of the dataframe. The result has to be stored in another variable. The time incurred in this operation is equivalent to the number of rows in the dataframe. The data type of the resultant column is the largest compatible data type. " }, { "code": null, "e": 1754, "s": 1719, "text": "Syntax: sweep (df , axis, vec, op)" }, { "code": null, "e": 1766, "s": 1754, "text": "Parameter :" }, { "code": null, "e": 1781, "s": 1766, "text": "df – DataFrame" }, { "code": null, "e": 1860, "s": 1781, "text": "axis – To compute it row-wise, use axis = 1 and for column-wise, use axis = 2 " }, { "code": null, "e": 1903, "s": 1860, "text": "vec – The vector to apply on the dataframe" }, { "code": null, "e": 1930, "s": 1903, "text": "op – The operator to apply" }, { "code": null, "e": 1939, "s": 1930, "text": "Example:" }, { "code": null, "e": 1941, "s": 1939, "text": "R" }, { "code": "# declaring dataframedata_frame <- data.frame(col1 = c(2,4,6), col2 = c(4,6,8), col3 = c(8,10,12), col4 = c(20,16,14)) print (\"Original Dataframe\")print (data_frame) # declaring vectorvec <- c(1:4) # dividing each row by vectordiv <- sweep(data_frame,2,vec,'/') print (\"Result of division\")print (div)", "e": 2273, "s": 1941, "text": null }, { "code": null, "e": 2280, "s": 2273, "text": "Output" }, { "code": null, "e": 2521, "s": 2280, "text": "[1] \"Original Dataframe\"\n col1 col2 col3 col4\n1 2 4 8 20\n2 4 6 10 16\n3 6 8 12 14\n[1] \"Result of division\"\n col1 col2 col3 col4\n1 2 2 2.666667 5.0\n2 4 3 3.333333 4.0\n3 6 4 4.000000 3.5 " }, { "code": null, "e": 2528, "s": 2521, "text": "Picked" }, { "code": null, "e": 2549, "s": 2528, "text": "R DataFrame-Programs" }, { "code": null, "e": 2561, "s": 2549, "text": "R-DataFrame" }, { "code": null, "e": 2572, "s": 2561, "text": "R Language" }, { "code": null, "e": 2583, "s": 2572, "text": "R Programs" } ]
Determining file format using Python
02 Sep, 2020 The general way of recognizing the type of file is by looking at its extension. But this isn’t generally the case. This type of standard for recognizing file by associating an extension with a file type is enforced by some operating system families (predominantly Windows). Other OS’s such as Linux (and its variants) use the magic number for recognizing file types. A Magic Number is a constant value, used for the identification of a file. This method provides more flexibility in naming a file and does not mandate the presence of an extension. Magic numbers are good for recognizing files, as sometimes a file may not have the correct file extension (or may not have one at all). In this article we will learn how to recognize files by their extension, using python. We would be using the Python Magic library to provide such capabilities to our program. To install the library, execute the following command in your operating system’s command interpreter:- pip install python-magic For demonstration purpose, we would be using a file name apple.jpg with the following contents:- Apparent from the contents, the file is an HTML file. But since it is saved with a .jpg extension, the operating system won’t be able to recognize its actual file type. So this file would be befitting for our program. Python3 import magic # printing the human readable type of the fileprint(magic.from_file('apple.jpg')) # printing the mime type of the fileprint(magic.from_file('apple.jpg', mime = True)) Output: HTML document, ASCII text, with CRLF line terminators text/html Explanation: Firstly we import the magic library. Then we use magic.from_file() method to attain the human-readable file type. After which we use the mime=True attribute to attain the mime type of the file. Things to consider while using the above code: The code works on Linux and Mac OS. But there exists an inbuilt terminal command named file on those operating systems, which provide the same functionality as this program, without installing any other library. File type recognition using extensions also exists in the newer versions of the library. Since the file type recognition generally happens by fingerprint lookup of the header of the file, it is not mandatory for one to load the whole file for type recognition. Small sections of the files could also be provided as an argument using magic.from_buffer() and passing the initial bytes of the file using open(‘file.ext’, ‘rb’).read(n) (Only recommended if aware of the header format of the file type). python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 713, "s": 28, "text": "The general way of recognizing the type of file is by looking at its extension. But this isn’t generally the case. This type of standard for recognizing file by associating an extension with a file type is enforced by some operating system families (predominantly Windows). Other OS’s such as Linux (and its variants) use the magic number for recognizing file types. A Magic Number is a constant value, used for the identification of a file. This method provides more flexibility in naming a file and does not mandate the presence of an extension. Magic numbers are good for recognizing files, as sometimes a file may not have the correct file extension (or may not have one at all)." }, { "code": null, "e": 991, "s": 713, "text": "In this article we will learn how to recognize files by their extension, using python. We would be using the Python Magic library to provide such capabilities to our program. To install the library, execute the following command in your operating system’s command interpreter:-" }, { "code": null, "e": 1017, "s": 991, "text": "pip install python-magic\n" }, { "code": null, "e": 1114, "s": 1017, "text": "For demonstration purpose, we would be using a file name apple.jpg with the following contents:-" }, { "code": null, "e": 1333, "s": 1114, "text": "Apparent from the contents, the file is an HTML file. But since it is saved with a .jpg extension, the operating system won’t be able to recognize its actual file type. So this file would be befitting for our program. " }, { "code": null, "e": 1341, "s": 1333, "text": "Python3" }, { "code": "import magic # printing the human readable type of the fileprint(magic.from_file('apple.jpg')) # printing the mime type of the fileprint(magic.from_file('apple.jpg', mime = True))", "e": 1523, "s": 1341, "text": null }, { "code": null, "e": 1531, "s": 1523, "text": "Output:" }, { "code": null, "e": 1596, "s": 1531, "text": "HTML document, ASCII text, with CRLF line terminators\ntext/html\n" }, { "code": null, "e": 1609, "s": 1596, "text": "Explanation:" }, { "code": null, "e": 1805, "s": 1609, "text": "Firstly we import the magic library. Then we use magic.from_file() method to attain the human-readable file type. After which we use the mime=True attribute to attain the mime type of the file. " }, { "code": null, "e": 1852, "s": 1805, "text": "Things to consider while using the above code:" }, { "code": null, "e": 2064, "s": 1852, "text": "The code works on Linux and Mac OS. But there exists an inbuilt terminal command named file on those operating systems, which provide the same functionality as this program, without installing any other library." }, { "code": null, "e": 2153, "s": 2064, "text": "File type recognition using extensions also exists in the newer versions of the library." }, { "code": null, "e": 2563, "s": 2153, "text": "Since the file type recognition generally happens by fingerprint lookup of the header of the file, it is not mandatory for one to load the whole file for type recognition. Small sections of the files could also be provided as an argument using magic.from_buffer() and passing the initial bytes of the file using open(‘file.ext’, ‘rb’).read(n) (Only recommended if aware of the header format of the file type)." }, { "code": null, "e": 2578, "s": 2563, "text": "python-utility" }, { "code": null, "e": 2585, "s": 2578, "text": "Python" } ]
How to set font color in HTML?
To set the font color in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property color. HTML5 do not support the <font> tag, so the CSS style is used to add font color. The <font> tag deprecated in HTML5. Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet. You can try to run the following code to set font color in HTML − Live Demo <!DOCTYPE html> <html> <head> <title>HTML Font color</title> </head> <body> <h1>Products</h1> <p style="color:blue">This is demo content.</p> </body> </html>
[ { "code": null, "e": 1371, "s": 1062, "text": "To set the font color in HTML, use the style attribute. The style attribute specifies an inline style for an element. The attribute is used with the HTML <p> tag, with the CSS property color. HTML5 do not support the <font> tag, so the CSS style is used to add font color. The <font> tag deprecated in HTML5." }, { "code": null, "e": 1533, "s": 1371, "text": "Just keep in mind, the usage of style attribute overrides any style set globally. It will override any style set in the HTML <style> tag or external style sheet." }, { "code": null, "e": 1599, "s": 1533, "text": "You can try to run the following code to set font color in HTML −" }, { "code": null, "e": 1609, "s": 1599, "text": "Live Demo" }, { "code": null, "e": 1797, "s": 1609, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Font color</title>\n </head>\n <body>\n <h1>Products</h1>\n <p style=\"color:blue\">This is demo content.</p>\n </body>\n</html>" } ]
Angular PrimeNG PanelMenu Component - GeeksforGeeks
08 Sep, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the PanelMenu component in Angular PrimeNG. We will also learn about the properties, styling along with their syntaxes that will be used in the code. PanelMenu component: It is used to make a menu in the form of a panel. It can be considered as a combination of accordion and tree components Properties: model: It is an array of menu items. It accepts the array data type as input & the default value is null. style: It is used to set an inline style of the component. It is of the string data type & the default value is null. styleClass: It is used to set the style class of the component. It is of the string data type & the default value is null. multiple: It is used to specify whether multiple tabs can be activated at the same time or not. It is of the boolean data type & the default value is true. transitionOptions: It is used to set the transition options of the animation. It is of the string data type & the default value is 400ms cubic-bezier(0.86, 0, 0.07, 1). Styling: p-panelmenu: It is a container element. p-panelmenu-header: It is an accordion header of the root submenu. p-panelmenu-content: It is an accordion content of the root submenu. p-menu-list: It is an element list. p-menuitem: It is an element menuitem. p-menuitem-text: It is the label of a menuitem. p-menuitem-icon: It is an icon of a menuitem. p-panelmenu-icon: It is the arrow icon of an accordion header. Creating Angular application & module installation: Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: After complete installation, it will look like the following: Example 1: This is the basic example that illustrates how to use the PanelMenu component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG PanelMenu Component</h5><p-panelMenu [model]="gfg"></p-panelMenu> app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { PanelMenuModule } from 'primeng/panelmenu'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, PanelMenuModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} app.component.ts import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }} Output: Example 2: In this example, we will know how to use multiple property in the panelmenu component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG PanelMenu Component</h5><p-panelMenu [multiple]='false' [model]="gfg"></p-panelMenu> app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { PanelMenuModule } from 'primeng/panelmenu'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, PanelMenuModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} app.component.ts import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }} Output: Reference: https://primefaces.org/primeng/showcase/#/panelmenu Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular PrimeNG Messages Component Angular 10 (blur) Event How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26464, "s": 26436, "text": "\n08 Sep, 2021" }, { "code": null, "e": 26856, "s": 26464, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the PanelMenu component in Angular PrimeNG. We will also learn about the properties, styling along with their syntaxes that will be used in the code. " }, { "code": null, "e": 26998, "s": 26856, "text": "PanelMenu component: It is used to make a menu in the form of a panel. It can be considered as a combination of accordion and tree components" }, { "code": null, "e": 27010, "s": 26998, "text": "Properties:" }, { "code": null, "e": 27116, "s": 27010, "text": "model: It is an array of menu items. It accepts the array data type as input & the default value is null." }, { "code": null, "e": 27234, "s": 27116, "text": "style: It is used to set an inline style of the component. It is of the string data type & the default value is null." }, { "code": null, "e": 27357, "s": 27234, "text": "styleClass: It is used to set the style class of the component. It is of the string data type & the default value is null." }, { "code": null, "e": 27513, "s": 27357, "text": "multiple: It is used to specify whether multiple tabs can be activated at the same time or not. It is of the boolean data type & the default value is true." }, { "code": null, "e": 27682, "s": 27513, "text": "transitionOptions: It is used to set the transition options of the animation. It is of the string data type & the default value is 400ms cubic-bezier(0.86, 0, 0.07, 1)." }, { "code": null, "e": 27691, "s": 27682, "text": "Styling:" }, { "code": null, "e": 27731, "s": 27691, "text": "p-panelmenu: It is a container element." }, { "code": null, "e": 27798, "s": 27731, "text": "p-panelmenu-header: It is an accordion header of the root submenu." }, { "code": null, "e": 27867, "s": 27798, "text": "p-panelmenu-content: It is an accordion content of the root submenu." }, { "code": null, "e": 27903, "s": 27867, "text": "p-menu-list: It is an element list." }, { "code": null, "e": 27942, "s": 27903, "text": "p-menuitem: It is an element menuitem." }, { "code": null, "e": 27990, "s": 27942, "text": "p-menuitem-text: It is the label of a menuitem." }, { "code": null, "e": 28036, "s": 27990, "text": "p-menuitem-icon: It is an icon of a menuitem." }, { "code": null, "e": 28099, "s": 28036, "text": "p-panelmenu-icon: It is the arrow icon of an accordion header." }, { "code": null, "e": 28153, "s": 28101, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 28220, "s": 28153, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 28235, "s": 28220, "text": "ng new appname" }, { "code": null, "e": 28332, "s": 28235, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 28343, "s": 28332, "text": "cd appname" }, { "code": null, "e": 28392, "s": 28343, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 28449, "s": 28392, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 28530, "s": 28449, "text": "Project Structure: After complete installation, it will look like the following:" }, { "code": null, "e": 28620, "s": 28530, "text": "Example 1: This is the basic example that illustrates how to use the PanelMenu component." }, { "code": null, "e": 28639, "s": 28620, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG PanelMenu Component</h5><p-panelMenu [model]=\"gfg\"></p-panelMenu>", "e": 28739, "s": 28639, "text": null }, { "code": null, "e": 28753, "s": 28739, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { PanelMenuModule } from 'primeng/panelmenu'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, PanelMenuModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 29230, "s": 28753, "text": null }, { "code": null, "e": 29247, "s": 29230, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }}", "e": 29822, "s": 29247, "text": null }, { "code": null, "e": 29832, "s": 29824, "text": "Output:" }, { "code": null, "e": 29930, "s": 29832, "text": "Example 2: In this example, we will know how to use multiple property in the panelmenu component." }, { "code": null, "e": 29949, "s": 29930, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG PanelMenu Component</h5><p-panelMenu [multiple]='false' [model]=\"gfg\"></p-panelMenu>", "e": 30068, "s": 29949, "text": null }, { "code": null, "e": 30082, "s": 30068, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component';import { PanelMenuModule } from 'primeng/panelmenu'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, PanelMenuModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 30559, "s": 30082, "text": null }, { "code": null, "e": 30576, "s": 30559, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';import { MenuItem } from 'primeng/api'; @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: MenuItem[]; ngOnInit() { this.gfg = [ { label: 'HTML', items: [ { label: 'HTML 1' }, { label: 'HTML 2' } ] }, { label: 'Angular', items: [ { label: 'Angular 1' }, { label: 'Angular 2' } ] } ]; }}", "e": 31151, "s": 30576, "text": null }, { "code": null, "e": 31159, "s": 31151, "text": "Output:" }, { "code": null, "e": 31222, "s": 31159, "text": "Reference: https://primefaces.org/primeng/showcase/#/panelmenu" }, { "code": null, "e": 31238, "s": 31222, "text": "Angular-PrimeNG" }, { "code": null, "e": 31248, "s": 31238, "text": "AngularJS" }, { "code": null, "e": 31265, "s": 31248, "text": "Web Technologies" }, { "code": null, "e": 31363, "s": 31265, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31398, "s": 31363, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 31433, "s": 31398, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 31468, "s": 31433, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 31492, "s": 31468, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 31545, "s": 31492, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 31585, "s": 31545, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31618, "s": 31585, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 31663, "s": 31618, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31706, "s": 31663, "text": "How to fetch data from an API in ReactJS ?" } ]
automake command in Linux with Examples - GeeksforGeeks
08 Apr, 2019 automake is a tool used for automatically generating Makefile.in files compliant with the set GNU Coding Standards. autoconf is required for the use of automake. automake manual can either be read on-line or downloaded in the PDF format. More formats are also offered for download or on-line reading. It will generate the Makefile.in for configuration from the Makefile.am file. Syntax: automake [OPTION]....[Makefile] Operation Modes: –help : Prints help and then exits. –version : Prints the version information and then it exits. -v or –verbose : Prints the verbosely list of processes. –no-force : It will only update Makefile.in which are out of date. -W or –warnings=Category : Reports the warnings falling in that specific category.The different warnings category’s are: The different warnings category’s are: Dependency Tracking Options: -i or –ignore-deps : Disables the dependency tracking code. –include-deps : Enables the dependency tracking code. Flavors: –foreign : It sets the strictness to foreign. –gnits : It sets the strictness to gnits. –gnu : It sets the strictness to gnu. The library files: -a or –add-missing : Adds the standard missing files to the package. –libdir = DIRECTORY : Sets the directory storing library files. -c or –copy : With -a, copies the missing files. -f or –force-missing : Forces the update of standard files. linux-command Linux-misc-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. TCP Server-Client implementation in C tar command in Linux with examples curl command in Linux with Examples Conditional Statements | Shell Script Tail command in Linux with examples UDP Server-Client implementation in C Cat command in Linux with examples touch command in Linux with Examples scp command in Linux with Examples echo command in Linux with Examples
[ { "code": null, "e": 25455, "s": 25427, "text": "\n08 Apr, 2019" }, { "code": null, "e": 25834, "s": 25455, "text": "automake is a tool used for automatically generating Makefile.in files compliant with the set GNU Coding Standards. autoconf is required for the use of automake. automake manual can either be read on-line or downloaded in the PDF format. More formats are also offered for download or on-line reading. It will generate the Makefile.in for configuration from the Makefile.am file." }, { "code": null, "e": 25842, "s": 25834, "text": "Syntax:" }, { "code": null, "e": 25874, "s": 25842, "text": "automake [OPTION]....[Makefile]" }, { "code": null, "e": 25891, "s": 25874, "text": "Operation Modes:" }, { "code": null, "e": 25927, "s": 25891, "text": "–help : Prints help and then exits." }, { "code": null, "e": 25988, "s": 25927, "text": "–version : Prints the version information and then it exits." }, { "code": null, "e": 26045, "s": 25988, "text": "-v or –verbose : Prints the verbosely list of processes." }, { "code": null, "e": 26112, "s": 26045, "text": "–no-force : It will only update Makefile.in which are out of date." }, { "code": null, "e": 26233, "s": 26112, "text": "-W or –warnings=Category : Reports the warnings falling in that specific category.The different warnings category’s are:" }, { "code": null, "e": 26272, "s": 26233, "text": "The different warnings category’s are:" }, { "code": null, "e": 26301, "s": 26272, "text": "Dependency Tracking Options:" }, { "code": null, "e": 26361, "s": 26301, "text": "-i or –ignore-deps : Disables the dependency tracking code." }, { "code": null, "e": 26415, "s": 26361, "text": "–include-deps : Enables the dependency tracking code." }, { "code": null, "e": 26424, "s": 26415, "text": "Flavors:" }, { "code": null, "e": 26470, "s": 26424, "text": "–foreign : It sets the strictness to foreign." }, { "code": null, "e": 26512, "s": 26470, "text": "–gnits : It sets the strictness to gnits." }, { "code": null, "e": 26550, "s": 26512, "text": "–gnu : It sets the strictness to gnu." }, { "code": null, "e": 26569, "s": 26550, "text": "The library files:" }, { "code": null, "e": 26638, "s": 26569, "text": "-a or –add-missing : Adds the standard missing files to the package." }, { "code": null, "e": 26702, "s": 26638, "text": "–libdir = DIRECTORY : Sets the directory storing library files." }, { "code": null, "e": 26751, "s": 26702, "text": "-c or –copy : With -a, copies the missing files." }, { "code": null, "e": 26811, "s": 26751, "text": "-f or –force-missing : Forces the update of standard files." }, { "code": null, "e": 26825, "s": 26811, "text": "linux-command" }, { "code": null, "e": 26845, "s": 26825, "text": "Linux-misc-commands" }, { "code": null, "e": 26852, "s": 26845, "text": "Picked" }, { "code": null, "e": 26863, "s": 26852, "text": "Linux-Unix" }, { "code": null, "e": 26961, "s": 26863, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26999, "s": 26961, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 27034, "s": 26999, "text": "tar command in Linux with examples" }, { "code": null, "e": 27070, "s": 27034, "text": "curl command in Linux with Examples" }, { "code": null, "e": 27108, "s": 27070, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 27144, "s": 27108, "text": "Tail command in Linux with examples" }, { "code": null, "e": 27182, "s": 27144, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 27217, "s": 27182, "text": "Cat command in Linux with examples" }, { "code": null, "e": 27254, "s": 27217, "text": "touch command in Linux with Examples" }, { "code": null, "e": 27289, "s": 27254, "text": "scp command in Linux with Examples" } ]