title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Financial NLP: The Internet’s Financial Membrane | by Posey | Towards Data Science
Disclaimer: No investment advice. There is no guarantee of any data herein being accurate or correct; all data is purely educational. Please consult a licensed investment professional before making investing decisions. Note: API taken down a few weeks ago as it’s being embedded in https://www.spawner.ai. If you want direct access to the API feel free to email luke [at] spawner [dot] ai I’ve written a lot about Natural Language Processing. It’s been possibly the source of the most innovation in AI/ML for decades, with many of the most interesting use-cases. Recently, companies like Hugging Face have brought together teams of NLP researchers and engineers to build and open-source incredible tooling. Like many others, I’m especially fond of huggingface/transformers. This sort of open-sourced innovation has enabled a whole new class of applications across all sorts of different domains. It’s making Applied AI, especially in web apps and internet startups, incredibly accessible. At Spawner, we decided to use our massive store of Financial Big Data in tandem with NLP from projects like Hugging Face, spaCy, and others to build something cool around Natural Language Processing for Finance and trading. We’ve made this part of the Spawner API free, covering select data for stocks from the S&P 500. You can use our Python library to access this endpoint directly. “Answer” is your natural language plug into financial data. The end goal is to be able to ask any question about financial instruments and get back natural language answers. For now, you can ask all sorts of questions about income statements, balance sheets, and cash flows. We’re working on adding major economic indicators and news next! You’ll get back the raw data from the latest reported quarter’s earnings. Optionally, ask directly and you can get over a decade of quarterly reports. This is a very early version of our Python library. While the core API is stable, the Python library has a long way to go. Expect answers and data to sometimes be unavailable or inaccurate. We give 0 guarantee of accuracy or liveness of data for our free parts of the API. The data fueling the free version of the API is sourced from open datasets and corporate earnings/releases. It goes through significant ETL before being ready for the training and understanding portions of our NLP. pip install spawner from spawner.nlp import answer You’ll get back a Pandas DataFrame containing an answer in natural language, all in order of what our model believes is the highest probability to answer your question... answer('what is the p/e ratio of apple?') The p/e ratio of Apple is 20.45answer('how about the revenue of GE?') The total revenue (Q4) of General Electric Company (GE) is 23,360,000,000answer('where is the S&P 500 at now?') Here is the quote for SPY (S&P 500 ETF): 281.5 For now, you can ask and explore all things income statements, balance sheets, and basic things like price and financial statistics. We’re constantly adding to our data and improving our algorithms. We’re imagining all sorts of web apps and plugins that can be built by plugging into the heart of finance with Natural Language Processing. And we’re partnering with developers who want to build cool stuff. You can join our Discord and help us build the financial membrane of the internet! And if you get a chance, check out Spawner — the future of finance is automated. I started a newsletter where we share datasets and analysis every Monday Wednesday and Friday.
[ { "code": null, "e": 391, "s": 172, "text": "Disclaimer: No investment advice. There is no guarantee of any data herein being accurate or correct; all data is purely educational. Please consult a licensed investment professional before making investing decisions." }, { "code": null, "e": 561, "s": 391, "text": "Note: API taken down a few weeks ago as it’s being embedded in https://www.spawner.ai. If you want direct access to the API feel free to email luke [at] spawner [dot] ai" }, { "code": null, "e": 946, "s": 561, "text": "I’ve written a lot about Natural Language Processing. It’s been possibly the source of the most innovation in AI/ML for decades, with many of the most interesting use-cases. Recently, companies like Hugging Face have brought together teams of NLP researchers and engineers to build and open-source incredible tooling. Like many others, I’m especially fond of huggingface/transformers." }, { "code": null, "e": 1385, "s": 946, "text": "This sort of open-sourced innovation has enabled a whole new class of applications across all sorts of different domains. It’s making Applied AI, especially in web apps and internet startups, incredibly accessible. At Spawner, we decided to use our massive store of Financial Big Data in tandem with NLP from projects like Hugging Face, spaCy, and others to build something cool around Natural Language Processing for Finance and trading." }, { "code": null, "e": 1546, "s": 1385, "text": "We’ve made this part of the Spawner API free, covering select data for stocks from the S&P 500. You can use our Python library to access this endpoint directly." }, { "code": null, "e": 2037, "s": 1546, "text": "“Answer” is your natural language plug into financial data. The end goal is to be able to ask any question about financial instruments and get back natural language answers. For now, you can ask all sorts of questions about income statements, balance sheets, and cash flows. We’re working on adding major economic indicators and news next! You’ll get back the raw data from the latest reported quarter’s earnings. Optionally, ask directly and you can get over a decade of quarterly reports." }, { "code": null, "e": 2310, "s": 2037, "text": "This is a very early version of our Python library. While the core API is stable, the Python library has a long way to go. Expect answers and data to sometimes be unavailable or inaccurate. We give 0 guarantee of accuracy or liveness of data for our free parts of the API." }, { "code": null, "e": 2525, "s": 2310, "text": "The data fueling the free version of the API is sourced from open datasets and corporate earnings/releases. It goes through significant ETL before being ready for the training and understanding portions of our NLP." }, { "code": null, "e": 2545, "s": 2525, "text": "pip install spawner" }, { "code": null, "e": 2576, "s": 2545, "text": "from spawner.nlp import answer" }, { "code": null, "e": 2747, "s": 2576, "text": "You’ll get back a Pandas DataFrame containing an answer in natural language, all in order of what our model believes is the highest probability to answer your question..." }, { "code": null, "e": 3018, "s": 2747, "text": "answer('what is the p/e ratio of apple?') The p/e ratio of Apple is 20.45answer('how about the revenue of GE?') The total revenue (Q4) of General Electric Company (GE) is 23,360,000,000answer('where is the S&P 500 at now?') Here is the quote for SPY (S&P 500 ETF): 281.5" }, { "code": null, "e": 3588, "s": 3018, "text": "For now, you can ask and explore all things income statements, balance sheets, and basic things like price and financial statistics. We’re constantly adding to our data and improving our algorithms. We’re imagining all sorts of web apps and plugins that can be built by plugging into the heart of finance with Natural Language Processing. And we’re partnering with developers who want to build cool stuff. You can join our Discord and help us build the financial membrane of the internet! And if you get a chance, check out Spawner — the future of finance is automated." } ]
Explain JSON format in PowerShell.
Javascript Object Notation (JSON) is the light-weight structure which is easy to read by human and simple to parse and understand by machine. Although the name contains the Javascript, both Javascript and JSON are different and they have syntax and structure is different as well. You can get more information about JSON https://www.json.org/json-en.html Its basic structure is Key-Value pair but both are separated by a colon ‘:’. It has an almost similar structure as a hashtable, PSCustomObjecct. For example, { "Name": "Albert Don" } If you have multiple Key-Value pairs, you can separate them with a comma. For example, { "Name": "Albert Don", "City": "New York", "SSID": 17728839 } Save the above file with the extension .json. We will first use the ConvertFrom-Json command to get the output in the table format. There is another command to convert the file/output into JSON using ConvertTo-Json command. PS E:\scripts\Powershell> Get-Content .\test.json | ConvertFrom-Json Name City SSID ---- ---- ---- Albert Don New York 17728839 If you have more than one set of Key-Value pairs then you need to declare them inside array Syntax - [] and need to separate each set with the comma (,). [ { "Name": "Albert Don", "City": "New York", "SSID": 17728839 }, { "Name":"John Carter", "City":"Ohio", "SSID":224544 }, { "Name":"Milly Lucas", "City":"Netherlands", "SSID":44903 } ] PS E:\scripts\Powershell> Get-Content .\test.json | ConvertFrom-Json Name City SSID ---- ---- ---- Albert Don New York 17728839 John Carter Ohio 224544 Milly Lucas Netherlands 44903 You can convert the output table to the Json format using Convertto-Json cmdlet. See the example below. Get-Service | Select Name, DisplayName, Status,StartType | Select –First 3 | ConvertTo-Json PS E:\scripts\Powershell> Get- Service | Select Name, DisplayName, Status,StartType | Select - First 3 | ConvertTo-Json [ { "Name": "AarSvc_69f5c", "DisplayName": "Agent Activation Runtime_69f5c", "Status": 1, "StartType": 3 }, { "Name": "AdobeARMservice", "DisplayName": "Adobe Acrobat Update Service", "Status": 4, "StartType": 2 }, { "Name": "AdobeFlashPlayerUpdateSvc", "DisplayName": "Adobe Flash Player Update Service", "Status": 1, "StartType": 3 } ] In the above example, individual services are split into a set of arrays.
[ { "code": null, "e": 1343, "s": 1062, "text": "Javascript Object Notation (JSON) is the light-weight structure which is easy to read by human and simple to parse and understand by machine. Although the name contains the Javascript, both Javascript and JSON are different and they have syntax and structure is different as well." }, { "code": null, "e": 1383, "s": 1343, "text": "You can get more information about JSON" }, { "code": null, "e": 1417, "s": 1383, "text": "https://www.json.org/json-en.html" }, { "code": null, "e": 1575, "s": 1417, "text": "Its basic structure is Key-Value pair but both are separated by a colon ‘:’. It has an almost similar structure as a hashtable, PSCustomObjecct. For example," }, { "code": null, "e": 1603, "s": 1575, "text": "{\n \"Name\": \"Albert Don\"\n}" }, { "code": null, "e": 1690, "s": 1603, "text": "If you have multiple Key-Value pairs, you can separate them with a comma. For example," }, { "code": null, "e": 1762, "s": 1690, "text": "{\n \"Name\": \"Albert Don\",\n \"City\": \"New York\",\n \"SSID\": 17728839\n}" }, { "code": null, "e": 1986, "s": 1762, "text": "Save the above file with the extension .json. We will first use the ConvertFrom-Json command to get the output in the table format. There is another command to convert the file/output into JSON using ConvertTo-Json command." }, { "code": null, "e": 2147, "s": 1986, "text": "PS E:\\scripts\\Powershell> Get-Content .\\test.json | ConvertFrom-Json\nName City SSID\n---- ---- ----\nAlbert Don New York 17728839" }, { "code": null, "e": 2301, "s": 2147, "text": "If you have more than one set of Key-Value pairs then you need to declare them inside array Syntax - [] and need to separate each set with the comma (,)." }, { "code": null, "e": 2558, "s": 2301, "text": "[\n {\n \"Name\": \"Albert Don\",\n \"City\": \"New York\",\n \"SSID\": 17728839\n },\n {\n \"Name\":\"John Carter\",\n \"City\":\"Ohio\",\n \"SSID\":224544\n },\n {\n \"Name\":\"Milly Lucas\",\n \"City\":\"Netherlands\",\n \"SSID\":44903\n }\n]" }, { "code": null, "e": 2764, "s": 2558, "text": "PS E:\\scripts\\Powershell> Get-Content .\\test.json | ConvertFrom-Json\nName City SSID\n---- ---- ----\nAlbert Don New York 17728839\nJohn Carter Ohio 224544\nMilly Lucas Netherlands 44903" }, { "code": null, "e": 2868, "s": 2764, "text": "You can convert the output table to the Json format using Convertto-Json cmdlet. See the example below." }, { "code": null, "e": 2960, "s": 2868, "text": "Get-Service | Select Name, DisplayName, Status,StartType | Select –First 3\n| ConvertTo-Json" }, { "code": null, "e": 3508, "s": 2960, "text": "PS E:\\scripts\\Powershell> Get-\nService | Select Name, DisplayName, Status,StartType | Select -\nFirst 3 | ConvertTo-Json\n[\n {\n \"Name\": \"AarSvc_69f5c\",\n \"DisplayName\": \"Agent Activation Runtime_69f5c\",\n \"Status\": 1,\n \"StartType\": 3\n },\n {\n \"Name\": \"AdobeARMservice\",\n \"DisplayName\": \"Adobe Acrobat Update Service\",\n \"Status\": 4,\n \"StartType\": 2\n },\n {\n \"Name\": \"AdobeFlashPlayerUpdateSvc\",\n \"DisplayName\": \"Adobe Flash Player Update Service\",\n \"Status\": 1,\n \"StartType\": 3\n }\n]" }, { "code": null, "e": 3582, "s": 3508, "text": "In the above example, individual services are split into a set of arrays." } ]
Java Program to replace one specific character with another
Use the replace() method to replace a specific character with another. Let’s say the following is our string and here we are replacing a whitespace with a $ character. String str1 = "Orange is the new Black!"; Now, use the replace() method to replace a character with $ str1.replace(' ', '$'); Live Demo public class Demo { public static void main(String[] args) { String str1 = "Orange is the new Black!"; System.out.println("String: "+str1); String str2 = str1.replace(' ', '$'); System.out.println("Updated string: "+str2); } } String: Orange is the new Black! Updated string: Orange$is$the$new$Black!
[ { "code": null, "e": 1230, "s": 1062, "text": "Use the replace() method to replace a specific character with another. Let’s say the following is our string and here we are replacing a whitespace with a $ character." }, { "code": null, "e": 1272, "s": 1230, "text": "String str1 = \"Orange is the new Black!\";" }, { "code": null, "e": 1332, "s": 1272, "text": "Now, use the replace() method to replace a character with $" }, { "code": null, "e": 1356, "s": 1332, "text": "str1.replace(' ', '$');" }, { "code": null, "e": 1367, "s": 1356, "text": " Live Demo" }, { "code": null, "e": 1624, "s": 1367, "text": "public class Demo {\n public static void main(String[] args) {\n String str1 = \"Orange is the new Black!\";\n System.out.println(\"String: \"+str1);\n String str2 = str1.replace(' ', '$');\n System.out.println(\"Updated string: \"+str2);\n }\n}" }, { "code": null, "e": 1698, "s": 1624, "text": "String: Orange is the new Black!\nUpdated string: Orange$is$the$new$Black!" } ]
ReactJS Components
15 Nov, 2021 A Component is one of the core building blocks of React. In other words, we can say that every application you will develop in React will be made up of pieces called components. Components make the task of building UIs much easier. You can see a UI broken down into multiple individual pieces called components and work on them independently and merge them all in a parent component which will be your final UI. You can see in the below image we have broken down the UI of GeeksforGeeks’s homepage into individual components. Chapters descriptions off, selected captions settings, opens captions settings dialog captions off, selected English This is a modal window. Beginning of dialog window. Escape will cancel and close the window. End of dialog window. Google’s custom search at the top can be seen as an individual component, the navigation bar can be seen as an individual component, the sidebar is an individual component, the list of articles or post is also an individual component and finally, we can merge all of these individual components to make a parent component which will be the final UI for the homepage.Components in React basically return a piece of JSX code that tells what should be rendered on the screen. In React, we mainly have two types of components: Functional Components: Functional components are simply javascript functions. We can create a functional component in React by writing a javascript function. These functions may or may not receive data as parameters, we will discuss this later in the tutorial. Below example shows a valid functional component in React: const Democomponent=()=> { return <h1>Welcome Message!</h1>; }Class Components: The class components are a little more complex than the functional components. The functional components are not aware of the other components in your program whereas the class components can work with each other. We can pass data from one class component to other class components. We can use JavaScript ES6 classes to create class-based components in React. Below example shows a valid class-based component in React: Functional Components: Functional components are simply javascript functions. We can create a functional component in React by writing a javascript function. These functions may or may not receive data as parameters, we will discuss this later in the tutorial. Below example shows a valid functional component in React: const Democomponent=()=> { return <h1>Welcome Message!</h1>; } Class Components: The class components are a little more complex than the functional components. The functional components are not aware of the other components in your program whereas the class components can work with each other. We can pass data from one class component to other class components. We can use JavaScript ES6 classes to create class-based components in React. Below example shows a valid class-based component in React: class Democomponent extends React.Component { render(){ return <h1>Welcome Message!</h1>; } } The components we created in the above two examples are equivalent, and we also have stated the basic difference between a functional component and class component. We will learn about more properties of class-based components in further tutorials. For now, keep in mind that we will use functional component only when we are sure that our component does not require interacting or work with any other component. That is, these components do not require data from other components however we can compose multiple functional components under a single functional component. We can also use class-based components for this purpose but it is not recommended as using class-based components without need will make your application in-efficient. In this post, we will mainly write functional components to make things easier to understand. We will discuss class-based components in detail later in the tutorial. Rendering Components In our previous post on rendering elements in React we have seen how elements initialized with DOM tags are rendered using ReactDOM.render() method. React is also capable of rendering user-defined components. To render a component in React we can initialize an element with a user-defined component and pass this element as the first parameter to ReactDOM.render() or directly pass the component as the first argument to the ReactDOM.render() method. Below syntax shows how to initialize a component to an element: const elementName = <ComponentName />; In the above syntax, the ComponentName is the name of the user-defined component. Note: The name of a component should always start with a capital letter. This is done to differentiate a component tag with html tags.Below example renders a component named Welcome to the screen: Open your index.js file from your project directory, and make the given below changes: src index.js: javascript import React from 'react'; import ReactDOM from 'react-dom'; // This is a functional component const Welcome=()=>{ return <h1>Hello World!</h1> } ReactDOM.render( <Welcome />, document.getElementById("root") ); Output: Let us see step-wise what is happening in the above example: We call the ReactDOM.render() as the first parameter.React then calls the component Welcome, which returns <h1>Hello World!</h1>; as the result.Then the ReactDOM efficiently updates the DOM to match with the returned element and renders that element to the DOM element with id as “root”. We call the ReactDOM.render() as the first parameter. React then calls the component Welcome, which returns <h1>Hello World!</h1>; as the result. Then the ReactDOM efficiently updates the DOM to match with the returned element and renders that element to the DOM element with id as “root”. For more information on component open component set 2Reference: https://reactjs.org/docs/components-and-props.html Akanksha_Rai shubhamyadav4 react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n15 Nov, 2021" }, { "code": null, "e": 580, "s": 52, "text": "A Component is one of the core building blocks of React. In other words, we can say that every application you will develop in React will be made up of pieces called components. Components make the task of building UIs much easier. You can see a UI broken down into multiple individual pieces called components and work on them independently and merge them all in a parent component which will be your final UI. You can see in the below image we have broken down the UI of GeeksforGeeks’s homepage into individual components. " }, { "code": null, "e": 589, "s": 580, "text": "Chapters" }, { "code": null, "e": 616, "s": 589, "text": "descriptions off, selected" }, { "code": null, "e": 666, "s": 616, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 689, "s": 666, "text": "captions off, selected" }, { "code": null, "e": 697, "s": 689, "text": "English" }, { "code": null, "e": 721, "s": 697, "text": "This is a modal window." }, { "code": null, "e": 790, "s": 721, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 812, "s": 790, "text": "End of dialog window." }, { "code": null, "e": 1337, "s": 812, "text": "Google’s custom search at the top can be seen as an individual component, the navigation bar can be seen as an individual component, the sidebar is an individual component, the list of articles or post is also an individual component and finally, we can merge all of these individual components to make a parent component which will be the final UI for the homepage.Components in React basically return a piece of JSX code that tells what should be rendered on the screen. In React, we mainly have two types of components: " }, { "code": null, "e": 2164, "s": 1337, "text": "Functional Components: Functional components are simply javascript functions. We can create a functional component in React by writing a javascript function. These functions may or may not receive data as parameters, we will discuss this later in the tutorial. Below example shows a valid functional component in React: const Democomponent=()=>\n{\n return <h1>Welcome Message!</h1>;\n}Class Components: The class components are a little more complex than the functional components. The functional components are not aware of the other components in your program whereas the class components can work with each other. We can pass data from one class component to other class components. We can use JavaScript ES6 classes to create class-based components in React. Below example shows a valid class-based component in React: " }, { "code": null, "e": 2486, "s": 2164, "text": "Functional Components: Functional components are simply javascript functions. We can create a functional component in React by writing a javascript function. These functions may or may not receive data as parameters, we will discuss this later in the tutorial. Below example shows a valid functional component in React: " }, { "code": null, "e": 2553, "s": 2486, "text": "const Democomponent=()=>\n{\n return <h1>Welcome Message!</h1>;\n}" }, { "code": null, "e": 2993, "s": 2553, "text": "Class Components: The class components are a little more complex than the functional components. The functional components are not aware of the other components in your program whereas the class components can work with each other. We can pass data from one class component to other class components. We can use JavaScript ES6 classes to create class-based components in React. Below example shows a valid class-based component in React: " }, { "code": null, "e": 3105, "s": 2993, "text": "class Democomponent extends React.Component\n{\n render(){\n return <h1>Welcome Message!</h1>;\n }\n}" }, { "code": null, "e": 4013, "s": 3105, "text": "The components we created in the above two examples are equivalent, and we also have stated the basic difference between a functional component and class component. We will learn about more properties of class-based components in further tutorials. For now, keep in mind that we will use functional component only when we are sure that our component does not require interacting or work with any other component. That is, these components do not require data from other components however we can compose multiple functional components under a single functional component. We can also use class-based components for this purpose but it is not recommended as using class-based components without need will make your application in-efficient. In this post, we will mainly write functional components to make things easier to understand. We will discuss class-based components in detail later in the tutorial. " }, { "code": null, "e": 4034, "s": 4013, "text": "Rendering Components" }, { "code": null, "e": 4551, "s": 4034, "text": "In our previous post on rendering elements in React we have seen how elements initialized with DOM tags are rendered using ReactDOM.render() method. React is also capable of rendering user-defined components. To render a component in React we can initialize an element with a user-defined component and pass this element as the first parameter to ReactDOM.render() or directly pass the component as the first argument to the ReactDOM.render() method. Below syntax shows how to initialize a component to an element: " }, { "code": null, "e": 4590, "s": 4551, "text": "const elementName = <ComponentName />;" }, { "code": null, "e": 4870, "s": 4590, "text": "In the above syntax, the ComponentName is the name of the user-defined component. Note: The name of a component should always start with a capital letter. This is done to differentiate a component tag with html tags.Below example renders a component named Welcome to the screen: " }, { "code": null, "e": 4957, "s": 4870, "text": "Open your index.js file from your project directory, and make the given below changes:" }, { "code": null, "e": 4971, "s": 4957, "text": "src index.js:" }, { "code": null, "e": 4982, "s": 4971, "text": "javascript" }, { "code": "import React from 'react'; import ReactDOM from 'react-dom'; // This is a functional component const Welcome=()=>{ return <h1>Hello World!</h1> } ReactDOM.render( <Welcome />, document.getElementById(\"root\") ); ", "e": 5214, "s": 4982, "text": null }, { "code": null, "e": 5224, "s": 5214, "text": "Output: " }, { "code": null, "e": 5286, "s": 5224, "text": "Let us see step-wise what is happening in the above example: " }, { "code": null, "e": 5574, "s": 5286, "text": "We call the ReactDOM.render() as the first parameter.React then calls the component Welcome, which returns <h1>Hello World!</h1>; as the result.Then the ReactDOM efficiently updates the DOM to match with the returned element and renders that element to the DOM element with id as “root”." }, { "code": null, "e": 5628, "s": 5574, "text": "We call the ReactDOM.render() as the first parameter." }, { "code": null, "e": 5720, "s": 5628, "text": "React then calls the component Welcome, which returns <h1>Hello World!</h1>; as the result." }, { "code": null, "e": 5864, "s": 5720, "text": "Then the ReactDOM efficiently updates the DOM to match with the returned element and renders that element to the DOM element with id as “root”." }, { "code": null, "e": 5981, "s": 5864, "text": "For more information on component open component set 2Reference: https://reactjs.org/docs/components-and-props.html " }, { "code": null, "e": 5994, "s": 5981, "text": "Akanksha_Rai" }, { "code": null, "e": 6008, "s": 5994, "text": "shubhamyadav4" }, { "code": null, "e": 6017, "s": 6008, "text": "react-js" }, { "code": null, "e": 6034, "s": 6017, "text": "Web Technologies" } ]
Data Structures | Binary Trees | Question 10
28 Jun, 2021 A complete n-ary tree is a tree in which each node has n children or no children. Let I be the number of internal nodes and L be the number of leaves in a complete n-ary tree. If L = 41, and I = 10, what is the value of n?(A) 6(B) 3(C) 4(D) 5Answer: (D)Explanation: For an n-ary tree where each node has n children or no children, following relation holds L = (n-1)*I + 1 Where L is the number of leaf nodes and I is the number of internal nodes. Let us find out the value of n for the given data. L = 41 , I = 10 41 = 10*(n-1) + 1 (n-1) = 4 n = 5 Quiz of this Question Binary Trees Quiz Data Structures Data Structures-Binary Trees Data Structures Data Structures Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Data Structures | Array | Question 2 Data Structures | Queue | Question 2 Amazon Interview Experience for SDE-II Data Structures | Hash | Question 5 Data Structures | Misc | Question 9 Data Structures | Linked List | Question 4 Data Structures | Linked List | Question 16 Bit manipulation | Swap Endianness of a number FIFO vs LIFO approach in Programming UGC-NET | UGC NET CS 2018 July - II | Question 70
[ { "code": null, "e": 53, "s": 25, "text": "\n28 Jun, 2021" }, { "code": null, "e": 409, "s": 53, "text": "A complete n-ary tree is a tree in which each node has n children or no children. Let I be the number of internal nodes and L be the number of leaves in a complete n-ary tree. If L = 41, and I = 10, what is the value of n?(A) 6(B) 3(C) 4(D) 5Answer: (D)Explanation: For an n-ary tree where each node has n children or no children, following relation holds" }, { "code": null, "e": 429, "s": 409, "text": " L = (n-1)*I + 1" }, { "code": null, "e": 504, "s": 429, "text": "Where L is the number of leaf nodes and I is the number of internal nodes." }, { "code": null, "e": 555, "s": 504, "text": "Let us find out the value of n for the given data." }, { "code": null, "e": 613, "s": 555, "text": " L = 41 , I = 10\n 41 = 10*(n-1) + 1\n (n-1) = 4\n n = 5" }, { "code": null, "e": 635, "s": 613, "text": "Quiz of this Question" }, { "code": null, "e": 653, "s": 635, "text": "Binary Trees Quiz" }, { "code": null, "e": 669, "s": 653, "text": "Data Structures" }, { "code": null, "e": 698, "s": 669, "text": "Data Structures-Binary Trees" }, { "code": null, "e": 714, "s": 698, "text": "Data Structures" }, { "code": null, "e": 730, "s": 714, "text": "Data Structures" }, { "code": null, "e": 828, "s": 730, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 865, "s": 828, "text": "Data Structures | Array | Question 2" }, { "code": null, "e": 902, "s": 865, "text": "Data Structures | Queue | Question 2" }, { "code": null, "e": 941, "s": 902, "text": "Amazon Interview Experience for SDE-II" }, { "code": null, "e": 977, "s": 941, "text": "Data Structures | Hash | Question 5" }, { "code": null, "e": 1013, "s": 977, "text": "Data Structures | Misc | Question 9" }, { "code": null, "e": 1056, "s": 1013, "text": "Data Structures | Linked List | Question 4" }, { "code": null, "e": 1100, "s": 1056, "text": "Data Structures | Linked List | Question 16" }, { "code": null, "e": 1147, "s": 1100, "text": "Bit manipulation | Swap Endianness of a number" }, { "code": null, "e": 1184, "s": 1147, "text": "FIFO vs LIFO approach in Programming" } ]
LongAdder increment() method in Java with Examples
28 Jan, 2019 LongAdder class in Java creates a new adder with an initial sum of zero. The Java.LongAdder.increment() is an inbuilt method in java that increases the value by 1. Syntax: public void increment() Parameters: The function does not accepts any parameter. Return value: The method do not returns any value. Below programs demonstrate the above function: Program 1: // Java program to demonstrate// the LongAdder.increment() method import java.lang.*;import java.util.concurrent.atomic.LongAdder; public class GFG { public static void main(String args[]) { // Initialized with 0 LongAdder num = new LongAdder(); // Print the initial value System.out.println("Initial value is: " + num); // Add 6 to it num.add(6); // Print the new value System.out.println("After addition" + " of 6, value is: " + num); // Increment operation on num num.increment(); // Print after increment System.out.println("After increment, " + " value is: " + num); }} Initial value is: 0 After addition of 6, value is: 6 After increment, value is: 7 Program 2: // Java program to demonstrate// the LongAdder.increment() method import java.lang.*;import java.util.concurrent.atomic.LongAdder; public class GFG { public static void main(String args[]) { // Initialized with 0 LongAdder num = new LongAdder(); // Print the initial value System.out.println("Initial value is: " + num); // Add 10 to it num.add(10); // Print the new value System.out.println("After addition" + " of 10, value is: " + num); // Increment operation on num num.increment(); // Print after increment System.out.println("After increment, " + " value is: " + num); }} Initial value is: 0 After addition of 10, value is: 10 After increment, value is: 11 Java - util package Java-Functions Java-LongAdder Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Multidimensional Arrays in Java Collections in Java Set in Java Stream In Java Initializing a List in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jan, 2019" }, { "code": null, "e": 192, "s": 28, "text": "LongAdder class in Java creates a new adder with an initial sum of zero. The Java.LongAdder.increment() is an inbuilt method in java that increases the value by 1." }, { "code": null, "e": 200, "s": 192, "text": "Syntax:" }, { "code": null, "e": 225, "s": 200, "text": "public void increment()\n" }, { "code": null, "e": 282, "s": 225, "text": "Parameters: The function does not accepts any parameter." }, { "code": null, "e": 333, "s": 282, "text": "Return value: The method do not returns any value." }, { "code": null, "e": 380, "s": 333, "text": "Below programs demonstrate the above function:" }, { "code": null, "e": 391, "s": 380, "text": "Program 1:" }, { "code": "// Java program to demonstrate// the LongAdder.increment() method import java.lang.*;import java.util.concurrent.atomic.LongAdder; public class GFG { public static void main(String args[]) { // Initialized with 0 LongAdder num = new LongAdder(); // Print the initial value System.out.println(\"Initial value is: \" + num); // Add 6 to it num.add(6); // Print the new value System.out.println(\"After addition\" + \" of 6, value is: \" + num); // Increment operation on num num.increment(); // Print after increment System.out.println(\"After increment, \" + \" value is: \" + num); }}", "e": 1203, "s": 391, "text": null }, { "code": null, "e": 1287, "s": 1203, "text": "Initial value is: 0\nAfter addition of 6, value is: 6\nAfter increment, value is: 7\n" }, { "code": null, "e": 1298, "s": 1287, "text": "Program 2:" }, { "code": "// Java program to demonstrate// the LongAdder.increment() method import java.lang.*;import java.util.concurrent.atomic.LongAdder; public class GFG { public static void main(String args[]) { // Initialized with 0 LongAdder num = new LongAdder(); // Print the initial value System.out.println(\"Initial value is: \" + num); // Add 10 to it num.add(10); // Print the new value System.out.println(\"After addition\" + \" of 10, value is: \" + num); // Increment operation on num num.increment(); // Print after increment System.out.println(\"After increment, \" + \" value is: \" + num); }}", "e": 2113, "s": 1298, "text": null }, { "code": null, "e": 2200, "s": 2113, "text": "Initial value is: 0\nAfter addition of 10, value is: 10\nAfter increment, value is: 11\n" }, { "code": null, "e": 2220, "s": 2200, "text": "Java - util package" }, { "code": null, "e": 2235, "s": 2220, "text": "Java-Functions" }, { "code": null, "e": 2250, "s": 2235, "text": "Java-LongAdder" }, { "code": null, "e": 2255, "s": 2250, "text": "Java" }, { "code": null, "e": 2260, "s": 2255, "text": "Java" }, { "code": null, "e": 2358, "s": 2260, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2409, "s": 2358, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 2440, "s": 2409, "text": "How to iterate any Map in Java" }, { "code": null, "e": 2459, "s": 2440, "text": "Interfaces in Java" }, { "code": null, "e": 2489, "s": 2459, "text": "HashMap in Java with Examples" }, { "code": null, "e": 2507, "s": 2489, "text": "ArrayList in Java" }, { "code": null, "e": 2539, "s": 2507, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2559, "s": 2539, "text": "Collections in Java" }, { "code": null, "e": 2571, "s": 2559, "text": "Set in Java" }, { "code": null, "e": 2586, "s": 2571, "text": "Stream In Java" } ]
VLOOKUP Function in Excel With Examples
15 May, 2021 Excel is widely used for data handling and almost everyone nowadays uses excel heavily. And at the same time, it is very user-friendly. Excel has several functions and formulas to make tedious jobs very easy. Like SUMIF() function VLOOKUP() is another very useful function widely used to ‘look up’ any data from a long table or a range by row. It supports approximate or exact matches based on one of its arguments being ‘True’ or ‘False’. This function also supports wildcards( ‘*’ and ‘?’) for partial matching. Generally, VLOOKUP() function is used to find data from a table or a list or range. It has basically two features – Approximate match and Exact match. Note: User must set the LOOKUP -value in the first column of the selected table as VLOOKUP() always searches in the right of the value and returns the desired output. Syntax: =VLOOKUP (lookup_value, table_array, col_index_num, [range_lookup]) Arguments: lookup_value(Required): This is the lookup value that should be provided by the user and must be in the first column of the selected table. table_array(Required): This is the table where the lookup_value and our desired output both exist(Not necessarily the output exits all the time. In that case, it returns N/A error.). VLOOKUP() function uses this table_array argument to find the result. col_index_num(Required): This is the column number of the table_array where VLOOKUP() will search for its output. If it gets the result, it then returns the specific value. [range_lookup](optional): This argument is completely optional. The user may or may not provide this according to his need. This argument value may be True or False. If this is ‘True’, it means approximate match and if it’s ‘False’, it searches for an exact match. If nothing is specified by the user, by default this value is set to be ‘True’ and it searches for an approximate match. Return Value: This function searches the corresponding value of the given argument and returns the desired matched value from the table or range provided as an argument. Examples: Exact Match: Here, we will see an example of the exact match of the VLOOKUP() function. Example 1 Approximate Match: In this case, when an exact match is not found VLOOKUP() function will return the value of the next greater element. The following is the example. Example 2 Here, the 1018 roll number does not exist. So it returns the student name of roll number 1017(i.e the next greater element in the list). Example of First Match, Case Insensitive & N/A error: This function always returns the first matched element. It is at the same time case-insensitive. And if we are looking for an element’s exact match while the element being absent in the table this function will show #N/A. Note: This function always searches rightwards to the lookup_value. Example 3 Picked Excel Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Delete Blank Columns in Excel? How to Normalize Data in Excel? How to Get Length of Array in Excel VBA? How to Find the Last Used Row and Column in Excel VBA? How to Use Solver in Excel? Macros in Excel How to Show Percentages in Stacked Column Chart in Excel? How to make a 3 Axis Graph using Excel? How to Extract the Last Word From a Cell in Excel? Introduction to Excel Spreadsheet
[ { "code": null, "e": 52, "s": 24, "text": "\n15 May, 2021" }, { "code": null, "e": 566, "s": 52, "text": "Excel is widely used for data handling and almost everyone nowadays uses excel heavily. And at the same time, it is very user-friendly. Excel has several functions and formulas to make tedious jobs very easy. Like SUMIF() function VLOOKUP() is another very useful function widely used to ‘look up’ any data from a long table or a range by row. It supports approximate or exact matches based on one of its arguments being ‘True’ or ‘False’. This function also supports wildcards( ‘*’ and ‘?’) for partial matching." }, { "code": null, "e": 718, "s": 566, "text": "Generally, VLOOKUP() function is used to find data from a table or a list or range. It has basically two features – Approximate match and Exact match. " }, { "code": null, "e": 885, "s": 718, "text": "Note: User must set the LOOKUP -value in the first column of the selected table as VLOOKUP() always searches in the right of the value and returns the desired output." }, { "code": null, "e": 961, "s": 885, "text": "Syntax:\n=VLOOKUP (lookup_value, table_array, col_index_num, [range_lookup])" }, { "code": null, "e": 972, "s": 961, "text": "Arguments:" }, { "code": null, "e": 1112, "s": 972, "text": "lookup_value(Required): This is the lookup value that should be provided by the user and must be in the first column of the selected table." }, { "code": null, "e": 1365, "s": 1112, "text": "table_array(Required): This is the table where the lookup_value and our desired output both exist(Not necessarily the output exits all the time. In that case, it returns N/A error.). VLOOKUP() function uses this table_array argument to find the result." }, { "code": null, "e": 1538, "s": 1365, "text": "col_index_num(Required): This is the column number of the table_array where VLOOKUP() will search for its output. If it gets the result, it then returns the specific value." }, { "code": null, "e": 1924, "s": 1538, "text": "[range_lookup](optional): This argument is completely optional. The user may or may not provide this according to his need. This argument value may be True or False. If this is ‘True’, it means approximate match and if it’s ‘False’, it searches for an exact match. If nothing is specified by the user, by default this value is set to be ‘True’ and it searches for an approximate match." }, { "code": null, "e": 1938, "s": 1924, "text": "Return Value:" }, { "code": null, "e": 2094, "s": 1938, "text": "This function searches the corresponding value of the given argument and returns the desired matched value from the table or range provided as an argument." }, { "code": null, "e": 2104, "s": 2094, "text": "Examples:" }, { "code": null, "e": 2117, "s": 2104, "text": "Exact Match:" }, { "code": null, "e": 2192, "s": 2117, "text": "Here, we will see an example of the exact match of the VLOOKUP() function." }, { "code": null, "e": 2202, "s": 2192, "text": "Example 1" }, { "code": null, "e": 2221, "s": 2202, "text": "Approximate Match:" }, { "code": null, "e": 2368, "s": 2221, "text": "In this case, when an exact match is not found VLOOKUP() function will return the value of the next greater element. The following is the example." }, { "code": null, "e": 2378, "s": 2368, "text": "Example 2" }, { "code": null, "e": 2515, "s": 2378, "text": "Here, the 1018 roll number does not exist. So it returns the student name of roll number 1017(i.e the next greater element in the list)." }, { "code": null, "e": 2569, "s": 2515, "text": "Example of First Match, Case Insensitive & N/A error:" }, { "code": null, "e": 2792, "s": 2569, "text": "This function always returns the first matched element. It is at the same time case-insensitive. And if we are looking for an element’s exact match while the element being absent in the table this function will show #N/A. " }, { "code": null, "e": 2860, "s": 2792, "text": "Note: This function always searches rightwards to the lookup_value." }, { "code": null, "e": 2870, "s": 2860, "text": "Example 3" }, { "code": null, "e": 2877, "s": 2870, "text": "Picked" }, { "code": null, "e": 2883, "s": 2877, "text": "Excel" }, { "code": null, "e": 2981, "s": 2883, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3019, "s": 2981, "text": "How to Delete Blank Columns in Excel?" }, { "code": null, "e": 3051, "s": 3019, "text": "How to Normalize Data in Excel?" }, { "code": null, "e": 3092, "s": 3051, "text": "How to Get Length of Array in Excel VBA?" }, { "code": null, "e": 3147, "s": 3092, "text": "How to Find the Last Used Row and Column in Excel VBA?" }, { "code": null, "e": 3175, "s": 3147, "text": "How to Use Solver in Excel?" }, { "code": null, "e": 3191, "s": 3175, "text": "Macros in Excel" }, { "code": null, "e": 3249, "s": 3191, "text": "How to Show Percentages in Stacked Column Chart in Excel?" }, { "code": null, "e": 3289, "s": 3249, "text": "How to make a 3 Axis Graph using Excel?" }, { "code": null, "e": 3340, "s": 3289, "text": "How to Extract the Last Word From a Cell in Excel?" } ]
How to Use Enumeration to Display Elements of Hashtable in Java?
18 Nov, 2021 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. Now here we can get the keys and values of a Hashtable as an Enumeration object using keys() and elements() method. We can obtain all keys and values respectively as an Enumeration object using Enumeration methods like hasMoreElements() and nextElement() we can read all keys and values corresponding to a Hashtable. Example 1: Java // Java Program to Demonstrate Getting Values// as an Enumeration of Hashtable class import java.io.*;import java.util.Enumeration;import java.util.Hashtable; // Main class// EnumerationOnKeyspublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty hashtable Hashtable<Integer, String> ht = new Hashtable<Integer, String>(); // Inserting key-value pairs into hash table // using put() method ht.put(1, "Geeks"); ht.put(2, "for"); ht.put(3, "Geeks"); // Now creating an Enumeration object // to read elements Enumeration e = ht.elements(); // Condition holds true till there is // single key remaining // Printing elements of hashtable // using enumeration while (e.hasMoreElements()) { // Printing the current element System.out.println(e.nextElement()); } }} Geeks for Geeks Example 2: Java // Java Program to Demonstrate Getting Keys// as an Enumeration of Hashtable class // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty hashtable Hashtable<String, String> ht = new Hashtable<String, String>(); // Inserting key-value pairs into hash table // using put() method ht.put("Name", "Rohan"); ht.put("Age", "23"); ht.put("Address", "India"); ht.put("Article", "GeeksforGeeks"); // Now creating an Enumeration object // to store keys Enumeration<String> e = ht.keys(); // Condition holds true till there is // single key remaining while (e.hasMoreElements()) { // Getting key String key = e.nextElement(); // Printing key and value corresponding to // that key System.out.println(key + ":" + ht.get(key)); } }} Name:Rohan Article:GeeksforGeeks Age:23 Address:India solankimayank Java-HashTable Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Nov, 2021" }, { "code": null, "e": 298, "s": 28, "text": "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": 615, "s": 298, "text": "Now here we can get the keys and values of a Hashtable as an Enumeration object using keys() and elements() method. We can obtain all keys and values respectively as an Enumeration object using Enumeration methods like hasMoreElements() and nextElement() we can read all keys and values corresponding to a Hashtable." }, { "code": null, "e": 626, "s": 615, "text": "Example 1:" }, { "code": null, "e": 631, "s": 626, "text": "Java" }, { "code": "// Java Program to Demonstrate Getting Values// as an Enumeration of Hashtable class import java.io.*;import java.util.Enumeration;import java.util.Hashtable; // Main class// EnumerationOnKeyspublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty hashtable Hashtable<Integer, String> ht = new Hashtable<Integer, String>(); // Inserting key-value pairs into hash table // using put() method ht.put(1, \"Geeks\"); ht.put(2, \"for\"); ht.put(3, \"Geeks\"); // Now creating an Enumeration object // to read elements Enumeration e = ht.elements(); // Condition holds true till there is // single key remaining // Printing elements of hashtable // using enumeration while (e.hasMoreElements()) { // Printing the current element System.out.println(e.nextElement()); } }}", "e": 1609, "s": 631, "text": null }, { "code": null, "e": 1625, "s": 1609, "text": "Geeks\nfor\nGeeks" }, { "code": null, "e": 1637, "s": 1625, "text": " Example 2:" }, { "code": null, "e": 1642, "s": 1637, "text": "Java" }, { "code": "// Java Program to Demonstrate Getting Keys// as an Enumeration of Hashtable class // Importing required classesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty hashtable Hashtable<String, String> ht = new Hashtable<String, String>(); // Inserting key-value pairs into hash table // using put() method ht.put(\"Name\", \"Rohan\"); ht.put(\"Age\", \"23\"); ht.put(\"Address\", \"India\"); ht.put(\"Article\", \"GeeksforGeeks\"); // Now creating an Enumeration object // to store keys Enumeration<String> e = ht.keys(); // Condition holds true till there is // single key remaining while (e.hasMoreElements()) { // Getting key String key = e.nextElement(); // Printing key and value corresponding to // that key System.out.println(key + \":\" + ht.get(key)); } }}", "e": 2680, "s": 1642, "text": null }, { "code": null, "e": 2734, "s": 2680, "text": "Name:Rohan\nArticle:GeeksforGeeks\nAge:23\nAddress:India" }, { "code": null, "e": 2748, "s": 2734, "text": "solankimayank" }, { "code": null, "e": 2763, "s": 2748, "text": "Java-HashTable" }, { "code": null, "e": 2768, "s": 2763, "text": "Java" }, { "code": null, "e": 2782, "s": 2768, "text": "Java Programs" }, { "code": null, "e": 2787, "s": 2782, "text": "Java" } ]
ViewPager Using Fragments in Android with Example
13 Feb, 2022 ViewPager is a layout manager that allows the user to flip left and right through pages of data. It is mostly found in apps like Youtube, Snapchat where the user shifts right – left to switch to a screen. Instead of using activities fragments are used. It is also used to guide the user through the app when the user launches the app for the first time. Steps for implementing viewpager: Adding the ViewPager widget to the XML layout (usually the main_layout).Creating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class. Adding the ViewPager widget to the XML layout (usually the main_layout). Creating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class. An adapter populates the pages inside the Viewpager. PagerAdapter is the base class which is extended by FragmentPagerAdapter and FragmentStatePagerAdapter. Let’s see a quick difference between the two classes. Difference between FragmentPagerAdapter and FragmentStatePagerAdapter: FragmentStatePagerAdapter: Keeps in memory only the current fragment displayed on the screen. This is memory efficient and should be used in applications with dynamic fragments. (where the number of fragments is not fixed.). FragmentPagerAdapter: This adapter should be used when the number of fragments is fixed. An application that has 3 tabs which won’t change during the runtime of the application. This tutorial will be using FragmentPagerAdapter. Following is the structure of the ViewPagerAdapter Class: Java import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment;import androidx.fragment.app.FragmentManager;import androidx.fragment.app.FragmentPagerAdapter;import java.util.ArrayList;import java.util.List; public class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> fragments = new ArrayList<>(); private final List<String> fragmentTitle = new ArrayList<>(); public ViewPagerAdapter(@NonNull FragmentManager fm) { super(fm); } public void add(Fragment fragment, String title) { fragments.add(fragment); fragmentTitle.add(title); } @NonNull @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } @Nullable @Override public CharSequence getPageTitle(int position) { return fragmentTitle.get(position); }} Method Description: getCount(): This method returns the number of fragments to display. (Required to Override) getItem(int pos): Returns the fragment at the pos index. (Required to override) ViewPagerAdapter(@NonNull FragmentManager FM): (required) The ViewPager Adapter needs to have a parameterized constructor that accepts the FragmentManager instance. Which is responsible for managing the fragments. A FragmentManager manages Fragments in Android, specifically, it handles transactions between fragments. A transaction is a way to add, replace, or remove fragments. getPageTitle(int pos): (optional) Similar to getItem() this methods returns the title of the page at index pos. add(Fragment fragment, String title): This method is responsible for populating the fragments and fragmentTitle lists. which hold the fragments and titles respectively. A sample GIF 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 Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Initially, the project directory should look like this. Step 2: Working with the activity_main.xml file The three widgets AppBarLayout used to host the TabLayout which is responsible for displaying the page titles. ViewPager layout which will house the different fragments. The below Image explains the important parameters to set to get the app working as intended. In the TabLayout we need to add the tabmode = “fixed” parameter which tells the android system that will have a fixed number of tabs in our application. Add the following code to the “activity_main.xml” file. XML <?xml version="1.0" encoding="utf-8"?><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <com.google.android.material.appbar.AppBarLayout android:id="@+id/appbar" android:layout_width="match_parent" android:layout_height="wrap_content"> <com.google.android.material.tabs.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="match_parent" app:tabGravity="fill" app:tabMode="fixed" /> </com.google.android.material.appbar.AppBarLayout> <androidx.viewpager.widget.ViewPager android:id="@+id/viewpager" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_behavior="@string/appbar_scrolling_view_behavior" /> </androidx.coordinatorlayout.widget.CoordinatorLayout> Step 3: Create Fragments Now we need to design out pages that are fragmented. For this tutorial, we will be using three Pages (fragments). Add three blank fragments to the project. The project Structure should look like this. Below is the code for the Page1.java, Page2.java, and Page3.java file respectively. Java Java Java import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment; public class Page1 extends Fragment { public Page1() { // required empty public constructor. } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_page1, container, false); }} import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment; public class Page2 extends Fragment { public Page2() { // required empty public constructor. } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_page2, container, false); }} import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment; public class Page3 extends Fragment { public Page3() { // required empty public constructor. } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_page3, container, false); }} Method Description: Page1(): Default Constructure. onCreateView( onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState): This method is responsible for inflating (parsing) the respective XML file and return the view which is added to the ViewPager adapter. onCreate(Bundle SaveInstanceState): This methods is similar to activities OnCreate() method. Designing the Page XML Files. All the fragments XML layouts have the same designs. We have a TextView at the center displaying the name of the respective page, the root container used here is FrameLayout whose background is set to #0F9D58 Below is the code for the fragment_page1.xml file: Code: XML <?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#0F9D58" tools:context=".Page1"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="Page 1" android:textColor="@color/white" android:textSize="60sp" android:textStyle="bold" /></FrameLayout> Below is the code for the fragment_page2.xml file: Code: XML <?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#0F9D58" tools:context=".Page2"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="Page 2" android:textColor="@color/white" android:textSize="60sp" android:textStyle="bold" /></FrameLayout> Below is the code for the fragment_page3.xml file: Code: XML <?xml version="1.0" encoding="utf-8"?><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#0F9D58" tools:context=".Page3"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center" android:text="Page 3" android:textColor="@color/white" android:textSize="60sp" android:textStyle="bold" /></FrameLayout> Step 4: Creating the ViewPager Adapter Add a java class named ViewPagerAdapter to the project structure. The project structure would look like this. Below is the code for the ViewPagerAdapter.java file: Java import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment;import androidx.fragment.app.FragmentManager;import androidx.fragment.app.FragmentPagerAdapter;import java.util.ArrayList;import java.util.List; public class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> fragments = new ArrayList<>(); private final List<String> fragmentTitle = new ArrayList<>(); public ViewPagerAdapter(@NonNull FragmentManager fm) { super(fm); } public void add(Fragment fragment, String title) { fragments.add(fragment); fragmentTitle.add(title); } @NonNull @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } @Nullable @Override public CharSequence getPageTitle(int position) { return fragmentTitle.get(position); }} Step 5: Working with the MainActivity.java file In the MainActivity, we need to perform the following steps. Initialize the ViewPager, TabLayout, and the Adapter.Add the Pages (fragments ) along with the titlesLink the TabLayout to the Viewpager using the setupWithiewPager method. Initialize the ViewPager, TabLayout, and the Adapter. Add the Pages (fragments ) along with the titles Link the TabLayout to the Viewpager using the setupWithiewPager method. Syntax:TabLayout.setupWithiewPager(ViewPager pager). Description: The tablayout with the viewpager. The titles of each pager now appears on the tablayout. The user can also navigate through the fragments by clicking on the tabs. Parameter: Viewpager: Used to display the fragments. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail. Java import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import androidx.viewpager.widget.ViewPager;import com.google.android.material.tabs.TabLayout; public class MainActivity extends AppCompatActivity { private ViewPagerAdapter viewPagerAdapter; private ViewPager viewPager; private TabLayout tabLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewPager = findViewById(R.id.viewpager); // setting up the adapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); // add the fragments viewPagerAdapter.add(new Page1(), "Page 1"); viewPagerAdapter.add(new Page2(), "Page 2"); viewPagerAdapter.add(new Page3(), "Page 3"); // Set the adapter viewPager.setAdapter(viewPagerAdapter); // The Page (fragment) titles will be displayed in the // tabLayout hence we need to set the page viewer // we use the setupWithViewPager(). tabLayout = findViewById(R.id.tab_layout); tabLayout.setupWithViewPager(viewPager); }} Output: Find the code in the following GitHub repo: https://github.com/evilc3/ViewPager singghakshay gabaa406 kk773572498 android Picked Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Android SDK and it's Components Android RecyclerView in Kotlin Android Project folder Structure Broadcast Receiver in Android With Example Flutter - Custom Bottom Navigation Bar Split() String method in Java with examples Arrays.sort() in Java with examples Object Oriented Programming (OOPs) Concept in Java Reverse a string in Java How to iterate any Map in Java
[ { "code": null, "e": 54, "s": 26, "text": "\n13 Feb, 2022" }, { "code": null, "e": 409, "s": 54, "text": "ViewPager is a layout manager that allows the user to flip left and right through pages of data. It is mostly found in apps like Youtube, Snapchat where the user shifts right – left to switch to a screen. Instead of using activities fragments are used. It is also used to guide the user through the app when the user launches the app for the first time. " }, { "code": null, "e": 444, "s": 409, "text": "Steps for implementing viewpager: " }, { "code": null, "e": 610, "s": 444, "text": "Adding the ViewPager widget to the XML layout (usually the main_layout).Creating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class." }, { "code": null, "e": 683, "s": 610, "text": "Adding the ViewPager widget to the XML layout (usually the main_layout)." }, { "code": null, "e": 777, "s": 683, "text": "Creating an Adapter by extending the FragmentPagerAdapter or FragmentStatePagerAdapter class." }, { "code": null, "e": 988, "s": 777, "text": "An adapter populates the pages inside the Viewpager. PagerAdapter is the base class which is extended by FragmentPagerAdapter and FragmentStatePagerAdapter. Let’s see a quick difference between the two classes." }, { "code": null, "e": 1060, "s": 988, "text": "Difference between FragmentPagerAdapter and FragmentStatePagerAdapter:" }, { "code": null, "e": 1285, "s": 1060, "text": "FragmentStatePagerAdapter: Keeps in memory only the current fragment displayed on the screen. This is memory efficient and should be used in applications with dynamic fragments. (where the number of fragments is not fixed.)." }, { "code": null, "e": 1513, "s": 1285, "text": "FragmentPagerAdapter: This adapter should be used when the number of fragments is fixed. An application that has 3 tabs which won’t change during the runtime of the application. This tutorial will be using FragmentPagerAdapter." }, { "code": null, "e": 1571, "s": 1513, "text": "Following is the structure of the ViewPagerAdapter Class:" }, { "code": null, "e": 1576, "s": 1571, "text": "Java" }, { "code": "import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment;import androidx.fragment.app.FragmentManager;import androidx.fragment.app.FragmentPagerAdapter;import java.util.ArrayList;import java.util.List; public class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> fragments = new ArrayList<>(); private final List<String> fragmentTitle = new ArrayList<>(); public ViewPagerAdapter(@NonNull FragmentManager fm) { super(fm); } public void add(Fragment fragment, String title) { fragments.add(fragment); fragmentTitle.add(title); } @NonNull @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } @Nullable @Override public CharSequence getPageTitle(int position) { return fragmentTitle.get(position); }}", "e": 2552, "s": 1576, "text": null }, { "code": null, "e": 2574, "s": 2552, "text": " Method Description: " }, { "code": null, "e": 2666, "s": 2574, "text": "getCount(): This method returns the number of fragments to display. (Required to Override)" }, { "code": null, "e": 2747, "s": 2666, "text": "getItem(int pos): Returns the fragment at the pos index. (Required to override)" }, { "code": null, "e": 3127, "s": 2747, "text": "ViewPagerAdapter(@NonNull FragmentManager FM): (required) The ViewPager Adapter needs to have a parameterized constructor that accepts the FragmentManager instance. Which is responsible for managing the fragments. A FragmentManager manages Fragments in Android, specifically, it handles transactions between fragments. A transaction is a way to add, replace, or remove fragments." }, { "code": null, "e": 3239, "s": 3127, "text": "getPageTitle(int pos): (optional) Similar to getItem() this methods returns the title of the page at index pos." }, { "code": null, "e": 3408, "s": 3239, "text": "add(Fragment fragment, String title): This method is responsible for populating the fragments and fragmentTitle lists. which hold the fragments and titles respectively." }, { "code": null, "e": 3574, "s": 3408, "text": "A sample GIF 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 Java language. " }, { "code": null, "e": 3603, "s": 3574, "text": "Step 1: Create a New Project" }, { "code": null, "e": 3822, "s": 3603, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Initially, the project directory should look like this. " }, { "code": null, "e": 3871, "s": 3822, "text": "Step 2: Working with the activity_main.xml file " }, { "code": null, "e": 4135, "s": 3871, "text": "The three widgets AppBarLayout used to host the TabLayout which is responsible for displaying the page titles. ViewPager layout which will house the different fragments. The below Image explains the important parameters to set to get the app working as intended. " }, { "code": null, "e": 4346, "s": 4135, "text": "In the TabLayout we need to add the tabmode = “fixed” parameter which tells the android system that will have a fixed number of tabs in our application. Add the following code to the “activity_main.xml” file. " }, { "code": null, "e": 4350, "s": 4346, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <com.google.android.material.appbar.AppBarLayout android:id=\"@+id/appbar\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\"> <com.google.android.material.tabs.TabLayout android:id=\"@+id/tab_layout\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" app:tabGravity=\"fill\" app:tabMode=\"fixed\" /> </com.google.android.material.appbar.AppBarLayout> <androidx.viewpager.widget.ViewPager android:id=\"@+id/viewpager\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" app:layout_behavior=\"@string/appbar_scrolling_view_behavior\" /> </androidx.coordinatorlayout.widget.CoordinatorLayout>", "e": 5409, "s": 4350, "text": null }, { "code": null, "e": 5434, "s": 5409, "text": "Step 3: Create Fragments" }, { "code": null, "e": 5637, "s": 5434, "text": "Now we need to design out pages that are fragmented. For this tutorial, we will be using three Pages (fragments). Add three blank fragments to the project. The project Structure should look like this. " }, { "code": null, "e": 5722, "s": 5637, "text": "Below is the code for the Page1.java, Page2.java, and Page3.java file respectively. " }, { "code": null, "e": 5727, "s": 5722, "text": "Java" }, { "code": null, "e": 5732, "s": 5727, "text": "Java" }, { "code": null, "e": 5737, "s": 5732, "text": "Java" }, { "code": "import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment; public class Page1 extends Fragment { public Page1() { // required empty public constructor. } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_page1, container, false); }}", "e": 6436, "s": 5737, "text": null }, { "code": "import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment; public class Page2 extends Fragment { public Page2() { // required empty public constructor. } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_page2, container, false); }}", "e": 7135, "s": 6436, "text": null }, { "code": "import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment; public class Page3 extends Fragment { public Page3() { // required empty public constructor. } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { return inflater.inflate(R.layout.fragment_page3, container, false); }}", "e": 7838, "s": 7135, "text": null }, { "code": null, "e": 7860, "s": 7838, "text": "Method Description: " }, { "code": null, "e": 7891, "s": 7860, "text": "Page1(): Default Constructure." }, { "code": null, "e": 8128, "s": 7891, "text": "onCreateView( onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState): This method is responsible for inflating (parsing) the respective XML file and return the view which is added to the ViewPager adapter." }, { "code": null, "e": 8221, "s": 8128, "text": "onCreate(Bundle SaveInstanceState): This methods is similar to activities OnCreate() method." }, { "code": null, "e": 8461, "s": 8221, "text": "Designing the Page XML Files. All the fragments XML layouts have the same designs. We have a TextView at the center displaying the name of the respective page, the root container used here is FrameLayout whose background is set to #0F9D58" }, { "code": null, "e": 8513, "s": 8461, "text": "Below is the code for the fragment_page1.xml file: " }, { "code": null, "e": 8520, "s": 8513, "text": "Code: " }, { "code": null, "e": 8524, "s": 8520, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#0F9D58\" tools:context=\".Page1\"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:text=\"Page 1\" android:textColor=\"@color/white\" android:textSize=\"60sp\" android:textStyle=\"bold\" /></FrameLayout>", "e": 9158, "s": 8524, "text": null }, { "code": null, "e": 9211, "s": 9158, "text": " Below is the code for the fragment_page2.xml file: " }, { "code": null, "e": 9219, "s": 9211, "text": "Code: " }, { "code": null, "e": 9223, "s": 9219, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#0F9D58\" tools:context=\".Page2\"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:text=\"Page 2\" android:textColor=\"@color/white\" android:textSize=\"60sp\" android:textStyle=\"bold\" /></FrameLayout>", "e": 9857, "s": 9223, "text": null }, { "code": null, "e": 9909, "s": 9857, "text": "Below is the code for the fragment_page3.xml file: " }, { "code": null, "e": 9916, "s": 9909, "text": "Code: " }, { "code": null, "e": 9920, "s": 9916, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><FrameLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:background=\"#0F9D58\" tools:context=\".Page3\"> <!-- TODO: Update blank fragment layout --> <TextView android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:gravity=\"center\" android:text=\"Page 3\" android:textColor=\"@color/white\" android:textSize=\"60sp\" android:textStyle=\"bold\" /></FrameLayout>", "e": 10554, "s": 9920, "text": null }, { "code": null, "e": 10594, "s": 10554, "text": "Step 4: Creating the ViewPager Adapter " }, { "code": null, "e": 10705, "s": 10594, "text": "Add a java class named ViewPagerAdapter to the project structure. The project structure would look like this. " }, { "code": null, "e": 10761, "s": 10705, "text": "Below is the code for the ViewPagerAdapter.java file: " }, { "code": null, "e": 10766, "s": 10761, "text": "Java" }, { "code": "import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.Fragment;import androidx.fragment.app.FragmentManager;import androidx.fragment.app.FragmentPagerAdapter;import java.util.ArrayList;import java.util.List; public class ViewPagerAdapter extends FragmentPagerAdapter { private final List<Fragment> fragments = new ArrayList<>(); private final List<String> fragmentTitle = new ArrayList<>(); public ViewPagerAdapter(@NonNull FragmentManager fm) { super(fm); } public void add(Fragment fragment, String title) { fragments.add(fragment); fragmentTitle.add(title); } @NonNull @Override public Fragment getItem(int position) { return fragments.get(position); } @Override public int getCount() { return fragments.size(); } @Nullable @Override public CharSequence getPageTitle(int position) { return fragmentTitle.get(position); }}", "e": 11748, "s": 10766, "text": null }, { "code": null, "e": 11796, "s": 11748, "text": "Step 5: Working with the MainActivity.java file" }, { "code": null, "e": 11859, "s": 11796, "text": "In the MainActivity, we need to perform the following steps. " }, { "code": null, "e": 12032, "s": 11859, "text": "Initialize the ViewPager, TabLayout, and the Adapter.Add the Pages (fragments ) along with the titlesLink the TabLayout to the Viewpager using the setupWithiewPager method." }, { "code": null, "e": 12086, "s": 12032, "text": "Initialize the ViewPager, TabLayout, and the Adapter." }, { "code": null, "e": 12135, "s": 12086, "text": "Add the Pages (fragments ) along with the titles" }, { "code": null, "e": 12207, "s": 12135, "text": "Link the TabLayout to the Viewpager using the setupWithiewPager method." }, { "code": null, "e": 12260, "s": 12207, "text": "Syntax:TabLayout.setupWithiewPager(ViewPager pager)." }, { "code": null, "e": 12436, "s": 12260, "text": "Description: The tablayout with the viewpager. The titles of each pager now appears on the tablayout. The user can also navigate through the fragments by clicking on the tabs." }, { "code": null, "e": 12447, "s": 12436, "text": "Parameter:" }, { "code": null, "e": 12489, "s": 12447, "text": "Viewpager: Used to display the fragments." }, { "code": null, "e": 12613, "s": 12489, "text": "Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail." }, { "code": null, "e": 12618, "s": 12613, "text": "Java" }, { "code": "import android.os.Bundle;import androidx.appcompat.app.AppCompatActivity;import androidx.viewpager.widget.ViewPager;import com.google.android.material.tabs.TabLayout; public class MainActivity extends AppCompatActivity { private ViewPagerAdapter viewPagerAdapter; private ViewPager viewPager; private TabLayout tabLayout; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); viewPager = findViewById(R.id.viewpager); // setting up the adapter viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager()); // add the fragments viewPagerAdapter.add(new Page1(), \"Page 1\"); viewPagerAdapter.add(new Page2(), \"Page 2\"); viewPagerAdapter.add(new Page3(), \"Page 3\"); // Set the adapter viewPager.setAdapter(viewPagerAdapter); // The Page (fragment) titles will be displayed in the // tabLayout hence we need to set the page viewer // we use the setupWithViewPager(). tabLayout = findViewById(R.id.tab_layout); tabLayout.setupWithViewPager(viewPager); }}", "e": 13806, "s": 12618, "text": null }, { "code": null, "e": 13816, "s": 13806, "text": "Output: " }, { "code": null, "e": 13897, "s": 13816, "text": " Find the code in the following GitHub repo: https://github.com/evilc3/ViewPager" }, { "code": null, "e": 13912, "s": 13899, "text": "singghakshay" }, { "code": null, "e": 13921, "s": 13912, "text": "gabaa406" }, { "code": null, "e": 13933, "s": 13921, "text": "kk773572498" }, { "code": null, "e": 13941, "s": 13933, "text": "android" }, { "code": null, "e": 13948, "s": 13941, "text": "Picked" }, { "code": null, "e": 13956, "s": 13948, "text": "Android" }, { "code": null, "e": 13961, "s": 13956, "text": "Java" }, { "code": null, "e": 13966, "s": 13961, "text": "Java" }, { "code": null, "e": 13974, "s": 13966, "text": "Android" }, { "code": null, "e": 14072, "s": 13974, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14104, "s": 14072, "text": "Android SDK and it's Components" }, { "code": null, "e": 14135, "s": 14104, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 14168, "s": 14135, "text": "Android Project folder Structure" }, { "code": null, "e": 14211, "s": 14168, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 14250, "s": 14211, "text": "Flutter - Custom Bottom Navigation Bar" }, { "code": null, "e": 14294, "s": 14250, "text": "Split() String method in Java with examples" }, { "code": null, "e": 14330, "s": 14294, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 14381, "s": 14330, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 14406, "s": 14381, "text": "Reverse a string in Java" } ]
Python program to print odd numbers in a List
22 Apr, 2020 Given a list of numbers, write a Python program to print all odd numbers in given list. Example: Input: list1 = [2, 7, 5, 64, 14] Output: [7, 5] Input: list2 = [12, 14, 95, 3, 73] Output: [95, 3, 73] Using for loop : Iterate each element in the list using for loop and check if num % 2 != 0. If the condition satisfies, then only print the number.# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] # iterating each number in listfor num in list1: # checking condition if num % 2 != 0: print(num, end = " ")Output:21 45 93 Using while loop :# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93]i = 0 # using while loop while(i < len(list1)): # checking condition if list1[i] % 2 != 0: print(list1[i], end = " ") # increment i i += 1 Output:21 45 93 Using list comprehension :# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] only_odd = [num for num in list1 if num % 2 == 1] print(only_odd)Output:21 45 93 Using lambda expressions :# Python program to print odd numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93, 11] # we can also print odd no's using lambda exp. odd_nos = list(filter(lambda x: (x % 2 != 0), list1)) print("Odd numbers in the list: ", odd_nos) Output:Odd numbers in the list: [21, 45, 93, 11] Using for loop : Iterate each element in the list using for loop and check if num % 2 != 0. If the condition satisfies, then only print the number.# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] # iterating each number in listfor num in list1: # checking condition if num % 2 != 0: print(num, end = " ")Output:21 45 93 # Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] # iterating each number in listfor num in list1: # checking condition if num % 2 != 0: print(num, end = " ") Output: 21 45 93 Using while loop :# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93]i = 0 # using while loop while(i < len(list1)): # checking condition if list1[i] % 2 != 0: print(list1[i], end = " ") # increment i i += 1 Output:21 45 93 # Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93]i = 0 # using while loop while(i < len(list1)): # checking condition if list1[i] % 2 != 0: print(list1[i], end = " ") # increment i i += 1 Output: 21 45 93 Using list comprehension :# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] only_odd = [num for num in list1 if num % 2 == 1] print(only_odd)Output:21 45 93 # Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] only_odd = [num for num in list1 if num % 2 == 1] print(only_odd) Output: 21 45 93 Using lambda expressions :# Python program to print odd numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93, 11] # we can also print odd no's using lambda exp. odd_nos = list(filter(lambda x: (x % 2 != 0), list1)) print("Odd numbers in the list: ", odd_nos) Output:Odd numbers in the list: [21, 45, 93, 11] # Python program to print odd numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93, 11] # we can also print odd no's using lambda exp. odd_nos = list(filter(lambda x: (x % 2 != 0), list1)) print("Odd numbers in the list: ", odd_nos) Output: Odd numbers in the list: [21, 45, 93, 11] princeeross Python list-programs python-list Python Python Programs School Programming python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n22 Apr, 2020" }, { "code": null, "e": 140, "s": 52, "text": "Given a list of numbers, write a Python program to print all odd numbers in given list." }, { "code": null, "e": 149, "s": 140, "text": "Example:" }, { "code": null, "e": 253, "s": 149, "text": "Input: list1 = [2, 7, 5, 64, 14]\nOutput: [7, 5]\n\nInput: list2 = [12, 14, 95, 3, 73]\nOutput: [95, 3, 73]" }, { "code": null, "e": 1492, "s": 253, "text": "Using for loop : Iterate each element in the list using for loop and check if num % 2 != 0. If the condition satisfies, then only print the number.# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] # iterating each number in listfor num in list1: # checking condition if num % 2 != 0: print(num, end = \" \")Output:21 45 93 Using while loop :# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93]i = 0 # using while loop while(i < len(list1)): # checking condition if list1[i] % 2 != 0: print(list1[i], end = \" \") # increment i i += 1 Output:21 45 93 Using list comprehension :# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] only_odd = [num for num in list1 if num % 2 == 1] print(only_odd)Output:21 45 93 Using lambda expressions :# Python program to print odd numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93, 11] # we can also print odd no's using lambda exp. odd_nos = list(filter(lambda x: (x % 2 != 0), list1)) print(\"Odd numbers in the list: \", odd_nos) Output:Odd numbers in the list: [21, 45, 93, 11]" }, { "code": null, "e": 1881, "s": 1492, "text": "Using for loop : Iterate each element in the list using for loop and check if num % 2 != 0. If the condition satisfies, then only print the number.# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] # iterating each number in listfor num in list1: # checking condition if num % 2 != 0: print(num, end = \" \")Output:21 45 93 " }, { "code": "# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] # iterating each number in listfor num in list1: # checking condition if num % 2 != 0: print(num, end = \" \")", "e": 2107, "s": 1881, "text": null }, { "code": null, "e": 2115, "s": 2107, "text": "Output:" }, { "code": null, "e": 2125, "s": 2115, "text": "21 45 93 " }, { "code": null, "e": 2441, "s": 2125, "text": "Using while loop :# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93]i = 0 # using while loop while(i < len(list1)): # checking condition if list1[i] % 2 != 0: print(list1[i], end = \" \") # increment i i += 1 Output:21 45 93 " }, { "code": "# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93]i = 0 # using while loop while(i < len(list1)): # checking condition if list1[i] % 2 != 0: print(list1[i], end = \" \") # increment i i += 1 ", "e": 2723, "s": 2441, "text": null }, { "code": null, "e": 2731, "s": 2723, "text": "Output:" }, { "code": null, "e": 2741, "s": 2731, "text": "21 45 93 " }, { "code": null, "e": 2949, "s": 2741, "text": "Using list comprehension :# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] only_odd = [num for num in list1 if num % 2 == 1] print(only_odd)Output:21 45 93 " }, { "code": "# Python program to print odd Numbers in a List # list of numberslist1 = [10, 21, 4, 45, 66, 93] only_odd = [num for num in list1 if num % 2 == 1] print(only_odd)", "e": 3115, "s": 2949, "text": null }, { "code": null, "e": 3123, "s": 3115, "text": "Output:" }, { "code": null, "e": 3133, "s": 3123, "text": "21 45 93 " }, { "code": null, "e": 3462, "s": 3133, "text": "Using lambda expressions :# Python program to print odd numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93, 11] # we can also print odd no's using lambda exp. odd_nos = list(filter(lambda x: (x % 2 != 0), list1)) print(\"Odd numbers in the list: \", odd_nos) Output:Odd numbers in the list: [21, 45, 93, 11]" }, { "code": "# Python program to print odd numbers in a List # list of numbers list1 = [10, 21, 4, 45, 66, 93, 11] # we can also print odd no's using lambda exp. odd_nos = list(filter(lambda x: (x % 2 != 0), list1)) print(\"Odd numbers in the list: \", odd_nos) ", "e": 3716, "s": 3462, "text": null }, { "code": null, "e": 3724, "s": 3716, "text": "Output:" }, { "code": null, "e": 3767, "s": 3724, "text": "Odd numbers in the list: [21, 45, 93, 11]" }, { "code": null, "e": 3779, "s": 3767, "text": "princeeross" }, { "code": null, "e": 3800, "s": 3779, "text": "Python list-programs" }, { "code": null, "e": 3812, "s": 3800, "text": "python-list" }, { "code": null, "e": 3819, "s": 3812, "text": "Python" }, { "code": null, "e": 3835, "s": 3819, "text": "Python Programs" }, { "code": null, "e": 3854, "s": 3835, "text": "School Programming" }, { "code": null, "e": 3866, "s": 3854, "text": "python-list" } ]
Python | Word Similarity using spaCy
19 Jul, 2019 Word similarity is a number between 0 to 1 which tells us how close two words are, semantically. This is done by finding similarity between word vectors in the vector space. spaCy, one of the fastest NLP libraries widely used today, provides a simple method for this task. spaCy’s Model –spaCy supports two methods to find word similarity: using context-sensitive tensors, and using word vectors. Below is the code to download these models. # Downloading the small model containing tensors. python -m spacy download en_core_web_sm # Downloading over 1 million word vectors. python -m spacy download en_core_web_lg Below is the code to find word similarity, which can be extended to sentences and documents. import spacy nlp = spacy.load('en_core_web_md') print("Enter two space-separated words")words = input() tokens = nlp(words) for token in tokens: # Printing the following attributes of each token. # text: the word string, has_vector: if it contains # a vector representation in the model, # vector_norm: the algebraic norm of the vector, # is_oov: if the word is out of vocabulary. print(token.text, token.has_vector, token.vector_norm, token.is_oov) token1, token2 = tokens[0], tokens[1] print("Similarity:", token1.similarity(token2)) Output: cat True 6.6808186 False dog True 7.0336733 False Similarity: 0.80168545 The ‘en_core_web_md’ model yields vectors of dimension 300*1 for ‘dog’ and ‘cat’. One may also use the larger model, ‘en_vectors_web_lg’ which yields vectors of larger dimension for the same two words. Using Custom Language Models –By simply switching the language model, we can find a similarity between Latin, French or German documents. spaCy supports a total of 49 languages at present. spaCy also allows one to fix word vectors for words as per user need. Below is an example. import spacyimport numpy as npfrom spacy.vocab import Vocab nlp = spacy.load('en_core_web_md')new_word = 'bucrest' print('Before custom setting')print(vocab.get_vector('bucrest')) custom_vector = np.random.uniform(-1, 1, (300, )) vocab.set_vector(new_word, custom_vector) print('After custom setting')print(vocab.get_vector('bucrest')) Output: Before custom setting array([0., 0., 0., 0., 0., 0., 0., 0., --- ]) After custom setting array([ 0.68106073, 0.6037007, 0.9526876, -0.25600302, -0.24049562, --- ]) Natural-language-processing Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jul, 2019" }, { "code": null, "e": 301, "s": 28, "text": "Word similarity is a number between 0 to 1 which tells us how close two words are, semantically. This is done by finding similarity between word vectors in the vector space. spaCy, one of the fastest NLP libraries widely used today, provides a simple method for this task." }, { "code": null, "e": 469, "s": 301, "text": "spaCy’s Model –spaCy supports two methods to find word similarity: using context-sensitive tensors, and using word vectors. Below is the code to download these models." }, { "code": null, "e": 644, "s": 469, "text": "# Downloading the small model containing tensors.\npython -m spacy download en_core_web_sm\n\n# Downloading over 1 million word vectors.\npython -m spacy download en_core_web_lg\n" }, { "code": null, "e": 737, "s": 644, "text": "Below is the code to find word similarity, which can be extended to sentences and documents." }, { "code": "import spacy nlp = spacy.load('en_core_web_md') print(\"Enter two space-separated words\")words = input() tokens = nlp(words) for token in tokens: # Printing the following attributes of each token. # text: the word string, has_vector: if it contains # a vector representation in the model, # vector_norm: the algebraic norm of the vector, # is_oov: if the word is out of vocabulary. print(token.text, token.has_vector, token.vector_norm, token.is_oov) token1, token2 = tokens[0], tokens[1] print(\"Similarity:\", token1.similarity(token2))", "e": 1298, "s": 737, "text": null }, { "code": null, "e": 1306, "s": 1298, "text": "Output:" }, { "code": null, "e": 1380, "s": 1306, "text": "cat True 6.6808186 False\ndog True 7.0336733 False\nSimilarity: 0.80168545\n" }, { "code": null, "e": 1582, "s": 1380, "text": "The ‘en_core_web_md’ model yields vectors of dimension 300*1 for ‘dog’ and ‘cat’. One may also use the larger model, ‘en_vectors_web_lg’ which yields vectors of larger dimension for the same two words." }, { "code": null, "e": 1862, "s": 1582, "text": "Using Custom Language Models –By simply switching the language model, we can find a similarity between Latin, French or German documents. spaCy supports a total of 49 languages at present. spaCy also allows one to fix word vectors for words as per user need. Below is an example." }, { "code": "import spacyimport numpy as npfrom spacy.vocab import Vocab nlp = spacy.load('en_core_web_md')new_word = 'bucrest' print('Before custom setting')print(vocab.get_vector('bucrest')) custom_vector = np.random.uniform(-1, 1, (300, )) vocab.set_vector(new_word, custom_vector) print('After custom setting')print(vocab.get_vector('bucrest'))", "e": 2203, "s": 1862, "text": null }, { "code": null, "e": 2211, "s": 2203, "text": "Output:" }, { "code": null, "e": 2379, "s": 2211, "text": "Before custom setting\narray([0., 0., 0., 0., 0., 0., 0., 0., --- ])\n\nAfter custom setting\narray([ 0.68106073, 0.6037007, 0.9526876, -0.25600302, -0.24049562, --- ])\n" }, { "code": null, "e": 2407, "s": 2379, "text": "Natural-language-processing" }, { "code": null, "e": 2414, "s": 2407, "text": "Python" } ]
Check if a Binary Tree contains duplicate subtrees of size 2 or more
28 Jun, 2021 Given a Binary Tree, check whether the Binary tree contains a duplicate sub-tree of size 2 or more. Note : Two same leaf nodes are not considered as subtree size of a leaf node is one. Input : Binary Tree A / \ B C / \ \ D E B / \ D E Output : Yes Asked in : Google Interview Tree with duplicate Sub-Tree [ highlight by blue color ellipse ] [ Method 1] A simple solution is that, we pick every node of tree and try to find is any sub-tree of given tree is present in tree which is identical with that sub-tree. Here we can use below post to find if a subtree is present anywhere else in tree. Check if a binary tree is subtree of another binary tree [Method 2 ]( Efficient solution ) An Efficient solution based on tree serialization and hashing. The idea is to serialize subtrees as strings and store the strings in hash table. Once we find a serialized tree (which is not a leaf) already existing in hash-table, we return true. Below The implementation of above idea. C++ Java Python3 C# Javascript // C++ program to find if there is a duplicate// sub-tree of size 2 or more.#include<bits/stdc++.h>using namespace std; // Separator nodeconst char MARKER = '$'; // Structure for a binary tree nodestruct Node{ char key; Node *left, *right;}; // A utility function to create a new nodeNode* newNode(char key){ Node* node = new Node; node->key = key; node->left = node->right = NULL; return node;} unordered_set<string> subtrees; // This function returns empty string if tree// contains a duplicate subtree of size 2 or more.string dupSubUtil(Node *root){ string s = ""; // If current node is NULL, return marker if (root == NULL) return s + MARKER; // If left subtree has a duplicate subtree. string lStr = dupSubUtil(root->left); if (lStr.compare(s) == 0) return s; // Do same for right subtree string rStr = dupSubUtil(root->right); if (rStr.compare(s) == 0) return s; // Serialize current subtree s = s + root->key + lStr + rStr; // If current subtree already exists in hash // table. [Note that size of a serialized tree // with single node is 3 as it has two marker // nodes. if (s.length() > 3 && subtrees.find(s) != subtrees.end()) return ""; subtrees.insert(s); return s;} // Driver program to test above functionsint main(){ Node *root = newNode('A'); root->left = newNode('B'); root->right = newNode('C'); root->left->left = newNode('D'); root->left->right = newNode('E'); root->right->right = newNode('B'); root->right->right->right = newNode('E'); root->right->right->left= newNode('D'); string str = dupSubUtil(root); (str.compare("") == 0) ? cout << " Yes ": cout << " No " ; return 0;} // Java program to find if there is a duplicate// sub-tree of size 2 or more.import java.util.HashSet;public class Main { static char MARKER = '$'; // This function returns empty string if tree // contains a duplicate subtree of size 2 or more. public static String dupSubUtil(Node root, HashSet<String> subtrees) { String s = ""; // If current node is NULL, return marker if (root == null) return s + MARKER; // If left subtree has a duplicate subtree. String lStr = dupSubUtil(root.left,subtrees); if (lStr.equals(s)) return s; // Do same for right subtree String rStr = dupSubUtil(root.right,subtrees); if (rStr.equals(s)) return s; // Serialize current subtree s = s + root.data + lStr + rStr; // If current subtree already exists in hash // table. [Note that size of a serialized tree // with single node is 3 as it has two marker // nodes. if (s.length() > 3 && subtrees.contains(s)) return ""; subtrees.add(s); return s; } //Function to find if the Binary Tree contains duplicate //subtrees of size 2 or more public static String dupSub(Node root) { HashSet<String> subtrees=new HashSet<>(); return dupSubUtil(root,subtrees); } public static void main(String args[]) { Node root = new Node('A'); root.left = new Node('B'); root.right = new Node('C'); root.left.left = new Node('D'); root.left.right = new Node('E'); root.right.right = new Node('B'); root.right.right.right = new Node('E'); root.right.right.left= new Node('D'); String str = dupSub(root); if(str.equals("")) System.out.print(" Yes "); else System.out.print(" No "); }} // A binary tree Node has data,// pointer to left child// and a pointer to right childclass Node { int data; Node left,right; Node(int data) { this.data=data; }};//This code is contributed by Gaurav Tiwari # Python3 program to find if there is# a duplicate sub-tree of size 2 or more # Separator nodeMARKER = '$' # Structure for a binary tree nodeclass Node: def __init__(self, x): self.key = x self.left = None self.right = None subtrees = {} # This function returns empty if tree# contains a duplicate subtree of size# 2 or more.def dupSubUtil(root): global subtrees s = "" # If current node is None, return marker if (root == None): return s + MARKER # If left subtree has a duplicate subtree. lStr = dupSubUtil(root.left) if (s in lStr): return s # Do same for right subtree rStr = dupSubUtil(root.right) if (s in rStr): return s # Serialize current subtree s = s + root.key + lStr + rStr # If current subtree already exists in hash # table. [Note that size of a serialized tree # with single node is 3 as it has two marker # nodes. if (len(s) > 3 and s in subtrees): return "" subtrees[s] = 1 return s # Driver codeif __name__ == '__main__': root = Node('A') root.left = Node('B') root.right = Node('C') root.left.left = Node('D') root.left.right = Node('E') root.right.right = Node('B') root.right.right.right = Node('E') root.right.right.left= Node('D') str = dupSubUtil(root) if "" in str: print(" Yes ") else: print(" No ") # This code is contributed by mohit kumar 29 // C# program to find if there is a duplicate// sub-tree of size 2 or more.using System;using System.Collections.Generic; class GFG{ static char MARKER = '$'; // This function returns empty string if tree // contains a duplicate subtree of size 2 or more. public static String dupSubUtil(Node root, HashSet<String> subtrees) { String s = ""; // If current node is NULL, return marker if (root == null) return s + MARKER; // If left subtree has a duplicate subtree. String lStr = dupSubUtil(root.left,subtrees); if (lStr.Equals(s)) return s; // Do same for right subtree String rStr = dupSubUtil(root.right,subtrees); if (rStr.Equals(s)) return s; // Serialize current subtree s = s + root.data + lStr + rStr; // If current subtree already exists in hash // table. [Note that size of a serialized tree // with single node is 3 as it has two marker // nodes. if (s.Length > 3 && subtrees.Contains(s)) return ""; subtrees.Add(s); return s; } // Function to find if the Binary Tree contains // duplicate subtrees of size 2 or more public static String dupSub(Node root) { HashSet<String> subtrees = new HashSet<String>(); return dupSubUtil(root,subtrees); } // Driver code public static void Main(String []args) { Node root = new Node('A'); root.left = new Node('B'); root.right = new Node('C'); root.left.left = new Node('D'); root.left.right = new Node('E'); root.right.right = new Node('B'); root.right.right.right = new Node('E'); root.right.right.left= new Node('D'); String str = dupSub(root); if(str.Equals("")) Console.Write(" Yes "); else Console.Write(" No "); }} // A binary tree Node has data,// pointer to left child// and a pointer to right childpublic class Node{ public int data; public Node left,right; public Node(int data) { this.data = data; }}; // This code is contributed by 29AjayKumar <script>// Javascript program to find if there is a duplicate// sub-tree of size 2 or more. let MARKER = '$'; // A binary tree Node has data,// pointer to left child// and a pointer to right child class Node { constructor(data) { this.data=data; } } // This function returns empty string if tree // contains a duplicate subtree of size 2 or more. function dupSubUtil(root,subtrees) { let s = ""; // If current node is NULL, return marker if (root == null) return s + MARKER; // If left subtree has a duplicate subtree. let lStr = dupSubUtil(root.left,subtrees); if (lStr==(s)) return s; // Do same for right subtree let rStr = dupSubUtil(root.right,subtrees); if (rStr==(s)) return s; // Serialize current subtree s = s + root.data + lStr + rStr; // If current subtree already exists in hash // table. [Note that size of a serialized tree // with single node is 3 as it has two marker // nodes. if (s.length > 3 && subtrees.has(s)) return ""; subtrees.add(s); return s; } //Function to find if the Binary Tree contains duplicate //subtrees of size 2 or more function dupSub(root) { let subtrees=new Set(); return dupSubUtil(root,subtrees); } let root = new Node('A'); root.left = new Node('B'); root.right = new Node('C'); root.left.left = new Node('D'); root.left.right = new Node('E'); root.right.right = new Node('B'); root.right.right.right = new Node('E'); root.right.right.left= new Node('D'); let str = dupSub(root); if(str==("")) document.write(" Yes "); else document.write(" No "); // This code is contributed by unknown2108</script> Output: Yes This article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. _Gaurav_Tiwari 29AjayKumar mohit kumar 29 unknown2108 Google Tree Google Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 237, "s": 52, "text": "Given a Binary Tree, check whether the Binary tree contains a duplicate sub-tree of size 2 or more. Note : Two same leaf nodes are not considered as subtree size of a leaf node is one." }, { "code": null, "e": 445, "s": 237, "text": "Input : Binary Tree \n A\n / \\ \n B C\n / \\ \\ \n D E B \n / \\ \n D E\nOutput : Yes" }, { "code": null, "e": 474, "s": 445, "text": "Asked in : Google Interview " }, { "code": null, "e": 541, "s": 476, "text": "Tree with duplicate Sub-Tree [ highlight by blue color ellipse ]" }, { "code": null, "e": 851, "s": 541, "text": "[ Method 1] A simple solution is that, we pick every node of tree and try to find is any sub-tree of given tree is present in tree which is identical with that sub-tree. Here we can use below post to find if a subtree is present anywhere else in tree. Check if a binary tree is subtree of another binary tree " }, { "code": null, "e": 1132, "s": 851, "text": "[Method 2 ]( Efficient solution ) An Efficient solution based on tree serialization and hashing. The idea is to serialize subtrees as strings and store the strings in hash table. Once we find a serialized tree (which is not a leaf) already existing in hash-table, we return true. " }, { "code": null, "e": 1173, "s": 1132, "text": "Below The implementation of above idea. " }, { "code": null, "e": 1177, "s": 1173, "text": "C++" }, { "code": null, "e": 1182, "s": 1177, "text": "Java" }, { "code": null, "e": 1190, "s": 1182, "text": "Python3" }, { "code": null, "e": 1193, "s": 1190, "text": "C#" }, { "code": null, "e": 1204, "s": 1193, "text": "Javascript" }, { "code": "// C++ program to find if there is a duplicate// sub-tree of size 2 or more.#include<bits/stdc++.h>using namespace std; // Separator nodeconst char MARKER = '$'; // Structure for a binary tree nodestruct Node{ char key; Node *left, *right;}; // A utility function to create a new nodeNode* newNode(char key){ Node* node = new Node; node->key = key; node->left = node->right = NULL; return node;} unordered_set<string> subtrees; // This function returns empty string if tree// contains a duplicate subtree of size 2 or more.string dupSubUtil(Node *root){ string s = \"\"; // If current node is NULL, return marker if (root == NULL) return s + MARKER; // If left subtree has a duplicate subtree. string lStr = dupSubUtil(root->left); if (lStr.compare(s) == 0) return s; // Do same for right subtree string rStr = dupSubUtil(root->right); if (rStr.compare(s) == 0) return s; // Serialize current subtree s = s + root->key + lStr + rStr; // If current subtree already exists in hash // table. [Note that size of a serialized tree // with single node is 3 as it has two marker // nodes. if (s.length() > 3 && subtrees.find(s) != subtrees.end()) return \"\"; subtrees.insert(s); return s;} // Driver program to test above functionsint main(){ Node *root = newNode('A'); root->left = newNode('B'); root->right = newNode('C'); root->left->left = newNode('D'); root->left->right = newNode('E'); root->right->right = newNode('B'); root->right->right->right = newNode('E'); root->right->right->left= newNode('D'); string str = dupSubUtil(root); (str.compare(\"\") == 0) ? cout << \" Yes \": cout << \" No \" ; return 0;}", "e": 2968, "s": 1204, "text": null }, { "code": "// Java program to find if there is a duplicate// sub-tree of size 2 or more.import java.util.HashSet;public class Main { static char MARKER = '$'; // This function returns empty string if tree // contains a duplicate subtree of size 2 or more. public static String dupSubUtil(Node root, HashSet<String> subtrees) { String s = \"\"; // If current node is NULL, return marker if (root == null) return s + MARKER; // If left subtree has a duplicate subtree. String lStr = dupSubUtil(root.left,subtrees); if (lStr.equals(s)) return s; // Do same for right subtree String rStr = dupSubUtil(root.right,subtrees); if (rStr.equals(s)) return s; // Serialize current subtree s = s + root.data + lStr + rStr; // If current subtree already exists in hash // table. [Note that size of a serialized tree // with single node is 3 as it has two marker // nodes. if (s.length() > 3 && subtrees.contains(s)) return \"\"; subtrees.add(s); return s; } //Function to find if the Binary Tree contains duplicate //subtrees of size 2 or more public static String dupSub(Node root) { HashSet<String> subtrees=new HashSet<>(); return dupSubUtil(root,subtrees); } public static void main(String args[]) { Node root = new Node('A'); root.left = new Node('B'); root.right = new Node('C'); root.left.left = new Node('D'); root.left.right = new Node('E'); root.right.right = new Node('B'); root.right.right.right = new Node('E'); root.right.right.left= new Node('D'); String str = dupSub(root); if(str.equals(\"\")) System.out.print(\" Yes \"); else System.out.print(\" No \"); }} // A binary tree Node has data,// pointer to left child// and a pointer to right childclass Node { int data; Node left,right; Node(int data) { this.data=data; }};//This code is contributed by Gaurav Tiwari", "e": 5100, "s": 2968, "text": null }, { "code": "# Python3 program to find if there is# a duplicate sub-tree of size 2 or more # Separator nodeMARKER = '$' # Structure for a binary tree nodeclass Node: def __init__(self, x): self.key = x self.left = None self.right = None subtrees = {} # This function returns empty if tree# contains a duplicate subtree of size# 2 or more.def dupSubUtil(root): global subtrees s = \"\" # If current node is None, return marker if (root == None): return s + MARKER # If left subtree has a duplicate subtree. lStr = dupSubUtil(root.left) if (s in lStr): return s # Do same for right subtree rStr = dupSubUtil(root.right) if (s in rStr): return s # Serialize current subtree s = s + root.key + lStr + rStr # If current subtree already exists in hash # table. [Note that size of a serialized tree # with single node is 3 as it has two marker # nodes. if (len(s) > 3 and s in subtrees): return \"\" subtrees[s] = 1 return s # Driver codeif __name__ == '__main__': root = Node('A') root.left = Node('B') root.right = Node('C') root.left.left = Node('D') root.left.right = Node('E') root.right.right = Node('B') root.right.right.right = Node('E') root.right.right.left= Node('D') str = dupSubUtil(root) if \"\" in str: print(\" Yes \") else: print(\" No \") # This code is contributed by mohit kumar 29", "e": 6569, "s": 5100, "text": null }, { "code": "// C# program to find if there is a duplicate// sub-tree of size 2 or more.using System;using System.Collections.Generic; class GFG{ static char MARKER = '$'; // This function returns empty string if tree // contains a duplicate subtree of size 2 or more. public static String dupSubUtil(Node root, HashSet<String> subtrees) { String s = \"\"; // If current node is NULL, return marker if (root == null) return s + MARKER; // If left subtree has a duplicate subtree. String lStr = dupSubUtil(root.left,subtrees); if (lStr.Equals(s)) return s; // Do same for right subtree String rStr = dupSubUtil(root.right,subtrees); if (rStr.Equals(s)) return s; // Serialize current subtree s = s + root.data + lStr + rStr; // If current subtree already exists in hash // table. [Note that size of a serialized tree // with single node is 3 as it has two marker // nodes. if (s.Length > 3 && subtrees.Contains(s)) return \"\"; subtrees.Add(s); return s; } // Function to find if the Binary Tree contains // duplicate subtrees of size 2 or more public static String dupSub(Node root) { HashSet<String> subtrees = new HashSet<String>(); return dupSubUtil(root,subtrees); } // Driver code public static void Main(String []args) { Node root = new Node('A'); root.left = new Node('B'); root.right = new Node('C'); root.left.left = new Node('D'); root.left.right = new Node('E'); root.right.right = new Node('B'); root.right.right.right = new Node('E'); root.right.right.left= new Node('D'); String str = dupSub(root); if(str.Equals(\"\")) Console.Write(\" Yes \"); else Console.Write(\" No \"); }} // A binary tree Node has data,// pointer to left child// and a pointer to right childpublic class Node{ public int data; public Node left,right; public Node(int data) { this.data = data; }}; // This code is contributed by 29AjayKumar", "e": 8777, "s": 6569, "text": null }, { "code": "<script>// Javascript program to find if there is a duplicate// sub-tree of size 2 or more. let MARKER = '$'; // A binary tree Node has data,// pointer to left child// and a pointer to right child class Node { constructor(data) { this.data=data; } } // This function returns empty string if tree // contains a duplicate subtree of size 2 or more. function dupSubUtil(root,subtrees) { let s = \"\"; // If current node is NULL, return marker if (root == null) return s + MARKER; // If left subtree has a duplicate subtree. let lStr = dupSubUtil(root.left,subtrees); if (lStr==(s)) return s; // Do same for right subtree let rStr = dupSubUtil(root.right,subtrees); if (rStr==(s)) return s; // Serialize current subtree s = s + root.data + lStr + rStr; // If current subtree already exists in hash // table. [Note that size of a serialized tree // with single node is 3 as it has two marker // nodes. if (s.length > 3 && subtrees.has(s)) return \"\"; subtrees.add(s); return s; } //Function to find if the Binary Tree contains duplicate //subtrees of size 2 or more function dupSub(root) { let subtrees=new Set(); return dupSubUtil(root,subtrees); } let root = new Node('A'); root.left = new Node('B'); root.right = new Node('C'); root.left.left = new Node('D'); root.left.right = new Node('E'); root.right.right = new Node('B'); root.right.right.right = new Node('E'); root.right.right.left= new Node('D'); let str = dupSub(root); if(str==(\"\")) document.write(\" Yes \"); else document.write(\" No \"); // This code is contributed by unknown2108</script>", "e": 10716, "s": 8777, "text": null }, { "code": null, "e": 10725, "s": 10716, "text": "Output: " }, { "code": null, "e": 10729, "s": 10725, "text": "Yes" }, { "code": null, "e": 11151, "s": 10729, "text": "This article is contributed by Nishant Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 11166, "s": 11151, "text": "_Gaurav_Tiwari" }, { "code": null, "e": 11178, "s": 11166, "text": "29AjayKumar" }, { "code": null, "e": 11193, "s": 11178, "text": "mohit kumar 29" }, { "code": null, "e": 11205, "s": 11193, "text": "unknown2108" }, { "code": null, "e": 11212, "s": 11205, "text": "Google" }, { "code": null, "e": 11217, "s": 11212, "text": "Tree" }, { "code": null, "e": 11224, "s": 11217, "text": "Google" }, { "code": null, "e": 11229, "s": 11224, "text": "Tree" } ]
Print array after it is right rotated K times
11 Jun, 2022 Given an Array of size N and a values K, around which we need to right rotate the array. How to quickly print the right rotated array?Examples : Input: Array[] = {1, 3, 5, 7, 9}, K = 2. Output: 7 9 1 3 5 Explanation: After 1st rotation - {9, 1, 3, 5, 7} After 2nd rotation - {7, 9, 1, 3, 5} Input: Array[] = {1, 2, 3, 4, 5}, K = 4. Output: 2 3 4 5 1 Approach: We will first take mod of K by N (K = K % N) because after every N rotation array will become the same as the initial array. Now, we will iterate the array from i = 0 to i = N-1 and check, If i < K, Print rightmost Kth element (a[N + i -K]). Otherwise, Print array after ‘K’ elements (a[i – K]). We will first take mod of K by N (K = K % N) because after every N rotation array will become the same as the initial array. Now, we will iterate the array from i = 0 to i = N-1 and check, If i < K, Print rightmost Kth element (a[N + i -K]). Otherwise, Print array after ‘K’ elements (a[i – K]). If i < K, Print rightmost Kth element (a[N + i -K]). Otherwise, Print array after ‘K’ elements (a[i – K]). Below is the implementation of the above approach. C++ Java Python3 C# Javascript // C++ implementation of right rotation// of an array K number of times#include<bits/stdc++.h>using namespace std; // Function to rightRotate arrayvoid RightRotate(int a[], int n, int k){ // If rotation is greater // than size of array k = k % n; for(int i = 0; i < n; i++) { if(i < k) { // Printing rightmost // kth elements cout << a[n + i - k] << " "; } else { // Prints array after // 'k' elements cout << (a[i - k]) << " "; } } cout << "\n";} // Driver codeint main(){ int Array[] = { 1, 2, 3, 4, 5 }; int N = sizeof(Array) / sizeof(Array[0]); int K = 2; RightRotate(Array, N, K);} // This code is contributed by Surendra_Gangwar // Java Implementation of Right Rotation// of an Array K number of timesimport java.util.*;import java.lang.*;import java.io.*; class Array_Rotation{ // Function to rightRotate arraystatic void RightRotate(int a[], int n, int k){ // If rotation is greater // than size of array k=k%n; for(int i = 0; i < n; i++) { if(i<k) { // Printing rightmost // kth elements System.out.print(a[n + i - k] + " "); } else { // Prints array after // 'k' elements System.out.print(a[i - k] + " "); } } System.out.println();} // Driver programpublic static void main(String args[]){ int Array[] = {1, 2, 3, 4, 5}; int N = Array.length; int K = 2; RightRotate(Array, N, K); }}// This code is contributed by M Vamshi Krishna # Python3 implementation of right rotation# of an array K number of times # Function to rightRotate arraydef RightRotate(a, n, k): # If rotation is greater # than size of array k = k % n; for i in range(0, n): if(i < k): # Printing rightmost # kth elements print(a[n + i - k], end = " "); else: # Prints array after # 'k' elements print(a[i - k], end = " "); print("\n"); # Driver codeArray = [ 1, 2, 3, 4, 5 ];N = len(Array);K = 2; RightRotate(Array, N, K); # This code is contributed by Code_Mech // C# implementation of right rotation// of an array K number of timesusing System;class GFG{ // Function to rightRotate arraystatic void RightRotate(int []a, int n, int k){ // If rotation is greater // than size of array k = k % n; for(int i = 0; i < n; i++) { if(i < k) { // Printing rightmost // kth elements Console.Write(a[n + i - k] + " "); } else { // Prints array after // 'k' elements Console.Write(a[i - k] + " "); } } Console.WriteLine();} // Driver codepublic static void Main(String []args){ int []Array = { 1, 2, 3, 4, 5 }; int N = Array.Length; int K = 2; RightRotate(Array, N, K);}} // This code is contributed by Rohit_ranjan // Javascript implementation of right rotation// of an array K number of times // Function to rightRotate arrayfunction RightRotate(a, n, k){ // If rotation is greater // than size of array k = k % n; for (let i = 0; i < n; i++) { if (i < k) { // Printing rightmost // kth elements document.write(a[n + i - k] + " "); } else { // Prints array after // 'k' elements document.write((a[i - k]) + " "); } } document.write("<br>");} // Driver codelet Array = [1, 2, 3, 4, 5];let N = Array.length;let K = 2; RightRotate(Array, N, K); // This code is contributed by gfgking. 4 5 1 2 3 Time complexity : O(n) Auxiliary Space : O(1) Method 2: Reversing the array Approach: The approach is simple yet optimized. The idea is to reverse the array three times. For the first time we reverse only the last k elements. Second time we will reverse first n-k(n=size of array) elements. Finally we will get our rotated array by reversing the entire array. Code: C++ C Java // C++ program to rotate right an array by K times#include <iostream>using namespace std;int main(){ int arr[] = { 1, 3, 5, 7, 9, 11 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; //No. of rotations k = k % n; int i, j; // Reverse last k numbers for (i = n - k, j = n - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Reverse the first n-k terms for (i = 0, j = n - k - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Reverse the entire array for (i = 0, j = n - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Print the rotated array for (int i = 0; i < n; i++) { cout << arr[i] << " "; } return 0;} // C program to rotate right an array by K times#include <stdio.h>// using namespace std;int main(){ int arr[] = { 1, 3, 5, 7, 9, 11 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; //No. of rotations k = k % n; int i, j; // Reverse last k numbers for (i = n - k, j = n - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Reverse the first n-k terms for (i = 0, j = n - k - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Reverse the entire array for (i = 0, j = n - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Print the rotated array for (int i = 0; i < n; i++) { printf("%d ", arr[i]); } return 0;} // JAVA program to rotate right an array by K timesimport java.io.*;class GFG { public static void main(String[] args) { int arr[] = new int[] { 1, 3, 5, 7, 9, 11 }; int n = arr.length; int k = 3; // No. of rotations k = k % n; int i, j; // Reverse last k numbers for (i = n - k, j = n - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Reverse the first n-k terms for (i = 0, j = n - k - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Reverse the entire array for (i = 0, j = n - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Print the rotated array for (int t = 0; t < n; t++) { System.out.print(arr[t] + " "); } }} // This code is contributed by Taranpreet 7 9 11 1 3 5 Complexity Analysis: Time Complexity: O(N). Auxiliary Space: O(1). Please see following posts for other methods of array rotation: https://www.geeksforgeeks.org/print-array-after-it-is-right-rotated-k-times-set-2/ ipg2016107 Rohit_ranjan Code_Mech gfgking hguru001 shreyasnaphad singhh3010 rotation Arrays Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Jun, 2022" }, { "code": null, "e": 199, "s": 52, "text": "Given an Array of size N and a values K, around which we need to right rotate the array. How to quickly print the right rotated array?Examples : " }, { "code": null, "e": 411, "s": 199, "text": "Input: Array[] = {1, 3, 5, 7, 9}, K = 2.\nOutput: 7 9 1 3 5\nExplanation:\nAfter 1st rotation - {9, 1, 3, 5, 7}\nAfter 2nd rotation - {7, 9, 1, 3, 5}\n\nInput: Array[] = {1, 2, 3, 4, 5}, K = 4.\nOutput: 2 3 4 5 1 " }, { "code": null, "e": 424, "s": 413, "text": "Approach: " }, { "code": null, "e": 724, "s": 424, "text": "We will first take mod of K by N (K = K % N) because after every N rotation array will become the same as the initial array. Now, we will iterate the array from i = 0 to i = N-1 and check, If i < K, Print rightmost Kth element (a[N + i -K]). Otherwise, Print array after ‘K’ elements (a[i – K]). " }, { "code": null, "e": 851, "s": 724, "text": "We will first take mod of K by N (K = K % N) because after every N rotation array will become the same as the initial array. " }, { "code": null, "e": 1025, "s": 851, "text": "Now, we will iterate the array from i = 0 to i = N-1 and check, If i < K, Print rightmost Kth element (a[N + i -K]). Otherwise, Print array after ‘K’ elements (a[i – K]). " }, { "code": null, "e": 1091, "s": 1025, "text": "If i < K, Print rightmost Kth element (a[N + i -K]). Otherwise, " }, { "code": null, "e": 1136, "s": 1091, "text": "Print array after ‘K’ elements (a[i – K]). " }, { "code": null, "e": 1189, "s": 1136, "text": "Below is the implementation of the above approach. " }, { "code": null, "e": 1193, "s": 1189, "text": "C++" }, { "code": null, "e": 1198, "s": 1193, "text": "Java" }, { "code": null, "e": 1206, "s": 1198, "text": "Python3" }, { "code": null, "e": 1209, "s": 1206, "text": "C#" }, { "code": null, "e": 1220, "s": 1209, "text": "Javascript" }, { "code": "// C++ implementation of right rotation// of an array K number of times#include<bits/stdc++.h>using namespace std; // Function to rightRotate arrayvoid RightRotate(int a[], int n, int k){ // If rotation is greater // than size of array k = k % n; for(int i = 0; i < n; i++) { if(i < k) { // Printing rightmost // kth elements cout << a[n + i - k] << \" \"; } else { // Prints array after // 'k' elements cout << (a[i - k]) << \" \"; } } cout << \"\\n\";} // Driver codeint main(){ int Array[] = { 1, 2, 3, 4, 5 }; int N = sizeof(Array) / sizeof(Array[0]); int K = 2; RightRotate(Array, N, K);} // This code is contributed by Surendra_Gangwar", "e": 2023, "s": 1220, "text": null }, { "code": "// Java Implementation of Right Rotation// of an Array K number of timesimport java.util.*;import java.lang.*;import java.io.*; class Array_Rotation{ // Function to rightRotate arraystatic void RightRotate(int a[], int n, int k){ // If rotation is greater // than size of array k=k%n; for(int i = 0; i < n; i++) { if(i<k) { // Printing rightmost // kth elements System.out.print(a[n + i - k] + \" \"); } else { // Prints array after // 'k' elements System.out.print(a[i - k] + \" \"); } } System.out.println();} // Driver programpublic static void main(String args[]){ int Array[] = {1, 2, 3, 4, 5}; int N = Array.length; int K = 2; RightRotate(Array, N, K); }}// This code is contributed by M Vamshi Krishna", "e": 2959, "s": 2023, "text": null }, { "code": "# Python3 implementation of right rotation# of an array K number of times # Function to rightRotate arraydef RightRotate(a, n, k): # If rotation is greater # than size of array k = k % n; for i in range(0, n): if(i < k): # Printing rightmost # kth elements print(a[n + i - k], end = \" \"); else: # Prints array after # 'k' elements print(a[i - k], end = \" \"); print(\"\\n\"); # Driver codeArray = [ 1, 2, 3, 4, 5 ];N = len(Array);K = 2; RightRotate(Array, N, K); # This code is contributed by Code_Mech", "e": 3564, "s": 2959, "text": null }, { "code": "// C# implementation of right rotation// of an array K number of timesusing System;class GFG{ // Function to rightRotate arraystatic void RightRotate(int []a, int n, int k){ // If rotation is greater // than size of array k = k % n; for(int i = 0; i < n; i++) { if(i < k) { // Printing rightmost // kth elements Console.Write(a[n + i - k] + \" \"); } else { // Prints array after // 'k' elements Console.Write(a[i - k] + \" \"); } } Console.WriteLine();} // Driver codepublic static void Main(String []args){ int []Array = { 1, 2, 3, 4, 5 }; int N = Array.Length; int K = 2; RightRotate(Array, N, K);}} // This code is contributed by Rohit_ranjan", "e": 4394, "s": 3564, "text": null }, { "code": "// Javascript implementation of right rotation// of an array K number of times // Function to rightRotate arrayfunction RightRotate(a, n, k){ // If rotation is greater // than size of array k = k % n; for (let i = 0; i < n; i++) { if (i < k) { // Printing rightmost // kth elements document.write(a[n + i - k] + \" \"); } else { // Prints array after // 'k' elements document.write((a[i - k]) + \" \"); } } document.write(\"<br>\");} // Driver codelet Array = [1, 2, 3, 4, 5];let N = Array.length;let K = 2; RightRotate(Array, N, K); // This code is contributed by gfgking.", "e": 5078, "s": 4394, "text": null }, { "code": null, "e": 5089, "s": 5078, "text": "4 5 1 2 3 " }, { "code": null, "e": 5136, "s": 5089, "text": "Time complexity : O(n) Auxiliary Space : O(1) " }, { "code": null, "e": 5167, "s": 5136, "text": "Method 2: Reversing the array " }, { "code": null, "e": 5451, "s": 5167, "text": "Approach: The approach is simple yet optimized. The idea is to reverse the array three times. For the first time we reverse only the last k elements. Second time we will reverse first n-k(n=size of array) elements. Finally we will get our rotated array by reversing the entire array." }, { "code": null, "e": 5457, "s": 5451, "text": "Code:" }, { "code": null, "e": 5461, "s": 5457, "text": "C++" }, { "code": null, "e": 5463, "s": 5461, "text": "C" }, { "code": null, "e": 5468, "s": 5463, "text": "Java" }, { "code": "// C++ program to rotate right an array by K times#include <iostream>using namespace std;int main(){ int arr[] = { 1, 3, 5, 7, 9, 11 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; //No. of rotations k = k % n; int i, j; // Reverse last k numbers for (i = n - k, j = n - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Reverse the first n-k terms for (i = 0, j = n - k - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Reverse the entire array for (i = 0, j = n - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Print the rotated array for (int i = 0; i < n; i++) { cout << arr[i] << \" \"; } return 0;}", "e": 6291, "s": 5468, "text": null }, { "code": "// C program to rotate right an array by K times#include <stdio.h>// using namespace std;int main(){ int arr[] = { 1, 3, 5, 7, 9, 11 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; //No. of rotations k = k % n; int i, j; // Reverse last k numbers for (i = n - k, j = n - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Reverse the first n-k terms for (i = 0, j = n - k - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Reverse the entire array for (i = 0, j = n - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Print the rotated array for (int i = 0; i < n; i++) { printf(\"%d \", arr[i]); } return 0;}", "e": 7114, "s": 6291, "text": null }, { "code": "// JAVA program to rotate right an array by K timesimport java.io.*;class GFG { public static void main(String[] args) { int arr[] = new int[] { 1, 3, 5, 7, 9, 11 }; int n = arr.length; int k = 3; // No. of rotations k = k % n; int i, j; // Reverse last k numbers for (i = n - k, j = n - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Reverse the first n-k terms for (i = 0, j = n - k - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Reverse the entire array for (i = 0, j = n - 1; i < j; i++, j--) { int temp = arr[i]; arr[i] = arr[j]; arr[j] = temp; } // Print the rotated array for (int t = 0; t < n; t++) { System.out.print(arr[t] + \" \"); } }} // This code is contributed by Taranpreet", "e": 8106, "s": 7114, "text": null }, { "code": null, "e": 8120, "s": 8106, "text": "7 9 11 1 3 5 " }, { "code": null, "e": 8141, "s": 8120, "text": "Complexity Analysis:" }, { "code": null, "e": 8164, "s": 8141, "text": "Time Complexity: O(N)." }, { "code": null, "e": 8187, "s": 8164, "text": "Auxiliary Space: O(1)." }, { "code": null, "e": 8252, "s": 8187, "text": "Please see following posts for other methods of array rotation: " }, { "code": null, "e": 8335, "s": 8252, "text": "https://www.geeksforgeeks.org/print-array-after-it-is-right-rotated-k-times-set-2/" }, { "code": null, "e": 8346, "s": 8335, "text": "ipg2016107" }, { "code": null, "e": 8359, "s": 8346, "text": "Rohit_ranjan" }, { "code": null, "e": 8369, "s": 8359, "text": "Code_Mech" }, { "code": null, "e": 8377, "s": 8369, "text": "gfgking" }, { "code": null, "e": 8386, "s": 8377, "text": "hguru001" }, { "code": null, "e": 8400, "s": 8386, "text": "shreyasnaphad" }, { "code": null, "e": 8411, "s": 8400, "text": "singhh3010" }, { "code": null, "e": 8420, "s": 8411, "text": "rotation" }, { "code": null, "e": 8427, "s": 8420, "text": "Arrays" }, { "code": null, "e": 8434, "s": 8427, "text": "Arrays" } ]
Difference between input() and raw_input() functions in Python - GeeksforGeeks
12 Dec, 2019 Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard. input ( prompt ) raw_input ( prompt ) Python input() function is used to take the values from the user. This function is called to tell the program to stop and wait for the user to input the values. It is a built-in function. The input() function is used in both the version of Python 2.x and Python 3.x. In Python 3.x, the input function explicitly converts the input you give to type string. But Python 2.x input function takes the value and type of the input you enter as it is without modifying the type. Example program in Python3 # Python program to demonstrate# input() function in Python3.x val1 = input("Enter the name: ") # print the type of input valueprint(type(val1))print(val1) val2 = input("Enter the number: ")print(type(val2)) val2 = int(val2)print(type(val2))print(val2) Input and Output Here, the value “python3” take from the user and store it in the val1 variable. The type of the value stored is always string for input function only for Python 3.x. The value “1997” take from the user and store it in the variable val2. Now, the type of variable val2 is a string and we have to convert the type to an integer using int() function. The val2 variable stores the value “1997” as an integer type. Example program in Python2 # Python program to demonstrate# input() function in Python2.x val1 = input("Enter the name: ")print(type(val1))print(val1) val2 = input("Enter the number: ")print(type(val2))print(val2) Input and Output Here, the value “python3” take from the user and store it in the val1 variable. The function takes the value and type of the input you enter as it is without modifying the type. The type of value in val1 is string type. The value “1997” takes from the user and store it in the variable val2. Now, the type of variable val2 is integer type. We don’t need to explicitly change the variable type. Python raw_input function is used to get the values from the user. We call this function to tell the program to stop and wait for the user to input the values. It is a built-in function. The input function is used only in Python 2.x version. The Python 2.x has two functions to take the value from the user. The first one is input function and another one is raw_input() function. The raw_input() function is similar to input() function in Python 3.x. Developers are recommended to use raw_input function in Python 2.x. Because there is a vulnerability in input function in Python 2.x version. Example program in Python2 # Python program to demonstrate# input() function in Python2.x val1 = raw_input("Enter the name: ")print(type(val1))print(val1) val2 = raw_input("Enter the number: ")print(type(val2))val2 = int(val2)print(type(val2))print(val2) Input and Output Here, the value “python3” take from the user and store it in the val1 variable. The type of the value stored is always string for raw_input function. The value “1997” take from the user and store it in the variable val2. Now, the type of variable val2 is a string and we have to convert the type to an integer using int() function. The val2 variable stores the value “1997” as an integer type. python-input-output Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python program to convert a list to string Python String | replace() Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24369, "s": 24341, "text": "\n12 Dec, 2019" }, { "code": null, "e": 24661, "s": 24369, "text": "Developers often have a need to interact with users, either to get data or to provide some sort of result. Most programs today use a dialog box as a way of asking the user to provide some type of input. While Python provides us with two inbuilt functions to read the input from the keyboard." }, { "code": null, "e": 24678, "s": 24661, "text": "input ( prompt )" }, { "code": null, "e": 24699, "s": 24678, "text": "raw_input ( prompt )" }, { "code": null, "e": 25170, "s": 24699, "text": "Python input() function is used to take the values from the user. This function is called to tell the program to stop and wait for the user to input the values. It is a built-in function. The input() function is used in both the version of Python 2.x and Python 3.x. In Python 3.x, the input function explicitly converts the input you give to type string. But Python 2.x input function takes the value and type of the input you enter as it is without modifying the type." }, { "code": null, "e": 25197, "s": 25170, "text": "Example program in Python3" }, { "code": "# Python program to demonstrate# input() function in Python3.x val1 = input(\"Enter the name: \") # print the type of input valueprint(type(val1))print(val1) val2 = input(\"Enter the number: \")print(type(val2)) val2 = int(val2)print(type(val2))print(val2)", "e": 25458, "s": 25197, "text": null }, { "code": null, "e": 25475, "s": 25458, "text": "Input and Output" }, { "code": null, "e": 25885, "s": 25475, "text": "Here, the value “python3” take from the user and store it in the val1 variable. The type of the value stored is always string for input function only for Python 3.x. The value “1997” take from the user and store it in the variable val2. Now, the type of variable val2 is a string and we have to convert the type to an integer using int() function. The val2 variable stores the value “1997” as an integer type." }, { "code": null, "e": 25912, "s": 25885, "text": "Example program in Python2" }, { "code": "# Python program to demonstrate# input() function in Python2.x val1 = input(\"Enter the name: \")print(type(val1))print(val1) val2 = input(\"Enter the number: \")print(type(val2))print(val2)", "e": 26103, "s": 25912, "text": null }, { "code": null, "e": 26120, "s": 26103, "text": "Input and Output" }, { "code": null, "e": 26514, "s": 26120, "text": "Here, the value “python3” take from the user and store it in the val1 variable. The function takes the value and type of the input you enter as it is without modifying the type. The type of value in val1 is string type. The value “1997” takes from the user and store it in the variable val2. Now, the type of variable val2 is integer type. We don’t need to explicitly change the variable type." }, { "code": null, "e": 27108, "s": 26514, "text": "Python raw_input function is used to get the values from the user. We call this function to tell the program to stop and wait for the user to input the values. It is a built-in function. The input function is used only in Python 2.x version. The Python 2.x has two functions to take the value from the user. The first one is input function and another one is raw_input() function. The raw_input() function is similar to input() function in Python 3.x. Developers are recommended to use raw_input function in Python 2.x. Because there is a vulnerability in input function in Python 2.x version." }, { "code": null, "e": 27135, "s": 27108, "text": "Example program in Python2" }, { "code": "# Python program to demonstrate# input() function in Python2.x val1 = raw_input(\"Enter the name: \")print(type(val1))print(val1) val2 = raw_input(\"Enter the number: \")print(type(val2))val2 = int(val2)print(type(val2))print(val2)", "e": 27367, "s": 27135, "text": null }, { "code": null, "e": 27384, "s": 27367, "text": "Input and Output" }, { "code": null, "e": 27778, "s": 27384, "text": "Here, the value “python3” take from the user and store it in the val1 variable. The type of the value stored is always string for raw_input function. The value “1997” take from the user and store it in the variable val2. Now, the type of variable val2 is a string and we have to convert the type to an integer using int() function. The val2 variable stores the value “1997” as an integer type." }, { "code": null, "e": 27798, "s": 27778, "text": "python-input-output" }, { "code": null, "e": 27805, "s": 27798, "text": "Python" }, { "code": null, "e": 27824, "s": 27805, "text": "Technical Scripter" }, { "code": null, "e": 27922, "s": 27824, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27931, "s": 27922, "text": "Comments" }, { "code": null, "e": 27944, "s": 27931, "text": "Old Comments" }, { "code": null, "e": 27962, "s": 27944, "text": "Python Dictionary" }, { "code": null, "e": 27997, "s": 27962, "text": "Read a file line by line in Python" }, { "code": null, "e": 28019, "s": 27997, "text": "Enumerate() in Python" }, { "code": null, "e": 28051, "s": 28019, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28081, "s": 28051, "text": "Iterate over a list in Python" }, { "code": null, "e": 28123, "s": 28081, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28166, "s": 28123, "text": "Python program to convert a list to string" }, { "code": null, "e": 28192, "s": 28166, "text": "Python String | replace()" }, { "code": null, "e": 28236, "s": 28192, "text": "Reading and Writing to text files in Python" } ]
How can I show and hide div on mouse click using jQuery?
To show and hide div on mouse click using jQuery, use the toggle() method. On mouse click, the div is visible and on again clicking the div, it hides. 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(){ $('#show').click(function() { $('.menu').toggle("slide"); }); }); </script> </head> <body> <div id="show">Click to Show/ Hide div</div> <div class="menu" style="display: none;"> <ol> <li>India</li> <li>US</li> <li>UK</li> <li>Australia</li> </ol> </div> </body> </html>
[ { "code": null, "e": 1213, "s": 1062, "text": "To show and hide div on mouse click using jQuery, use the toggle() method. On mouse click, the div is visible and on again clicking the div, it hides." }, { "code": null, "e": 1223, "s": 1213, "text": "Live Demo" }, { "code": null, "e": 1700, "s": 1223, "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 $('#show').click(function() {\n $('.menu').toggle(\"slide\");\n });\n});\n</script>\n</head>\n<body>\n\n<div id=\"show\">Click to Show/ Hide div</div>\n <div class=\"menu\" style=\"display: none;\">\n <ol>\n <li>India</li>\n <li>US</li>\n <li>UK</li>\n <li>Australia</li>\n </ol>\n </div>\n</body>\n</html>" } ]
How to use seek() method to reset a file read/write position in Python?
You can use the seek(offset[, whence]) method. It sets the file's current position, like stdio's fseek(). The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end). For example, if you already have a file open and want to go back to starting position, you can use: f = open('my_file.txt', 'r') f.seek(0) f.close() This will seek the pointer to beginning of the file. You can also provide the second argument as 2 and get the pointer to end of file.
[ { "code": null, "e": 1347, "s": 1062, "text": "You can use the seek(offset[, whence]) method. It sets the file's current position, like stdio's fseek(). The whence argument is optional and defaults to 0 (absolute file positioning); other values are 1 (seek relative to the current position) and 2 (seek relative to the file's end)." }, { "code": null, "e": 1447, "s": 1347, "text": "For example, if you already have a file open and want to go back to starting position, you can use:" }, { "code": null, "e": 1496, "s": 1447, "text": "f = open('my_file.txt', 'r')\nf.seek(0)\nf.close()" }, { "code": null, "e": 1632, "s": 1496, "text": "This will seek the pointer to beginning of the file. You can also provide the second argument as 2 and get the pointer to end of file. " } ]
C++ List Library - pop_back() Function
The C++ function std::list::pop_back() removes the last element from list and reduces size of the list by one. Following is the declaration for std::list::pop_back() function form std::list header. void pop_back(); None None This member function never throws exception. Calling this function on empty list causes undefined behavior. Constant i.e. O(1) The following example shows the usage of std::list::pop_back() function. #include <iostream> #include <list> using namespace std; int main(void) { list<int> l = {1, 2, 3, 4, 5}; cout << "List contains following elements before pop_back operation" << endl; for (auto it = l.begin(); it != l.end(); ++it) cout << *it << endl; l.pop_back(); cout << "List contains following elements after pop_back operation" << endl; for (auto it = l.begin(); it != l.end(); ++it) cout << *it << endl; return 0; } Let us compile and run the above program, this will produce the following result − List contains following elements before pop_back operation 1 2 3 4 5 List contains following elements after pop_back operation 1 2 3 4 Print Add Notes Bookmark this page
[ { "code": null, "e": 2714, "s": 2603, "text": "The C++ function std::list::pop_back() removes the last element from list and reduces size of the list by one." }, { "code": null, "e": 2801, "s": 2714, "text": "Following is the declaration for std::list::pop_back() function form std::list header." }, { "code": null, "e": 2819, "s": 2801, "text": "void pop_back();\n" }, { "code": null, "e": 2824, "s": 2819, "text": "None" }, { "code": null, "e": 2829, "s": 2824, "text": "None" }, { "code": null, "e": 2937, "s": 2829, "text": "This member function never throws exception. Calling this function on empty list causes undefined behavior." }, { "code": null, "e": 2956, "s": 2937, "text": "Constant i.e. O(1)" }, { "code": null, "e": 3029, "s": 2956, "text": "The following example shows the usage of std::list::pop_back() function." }, { "code": null, "e": 3492, "s": 3029, "text": "#include <iostream>\n#include <list>\n\nusing namespace std;\n\nint main(void) {\n list<int> l = {1, 2, 3, 4, 5};\n\n cout << \"List contains following elements before pop_back operation\" << endl;\n\n for (auto it = l.begin(); it != l.end(); ++it)\n cout << *it << endl;\n\n l.pop_back();\n\n cout << \"List contains following elements after pop_back operation\" << endl;\n\n for (auto it = l.begin(); it != l.end(); ++it)\n cout << *it << endl;\n\n return 0;\n}" }, { "code": null, "e": 3575, "s": 3492, "text": "Let us compile and run the above program, this will produce the following result −" }, { "code": null, "e": 3711, "s": 3575, "text": "List contains following elements before pop_back operation\n1\n2\n3\n4\n5\nList contains following elements after pop_back operation\n1\n2\n3\n4\n" }, { "code": null, "e": 3718, "s": 3711, "text": " Print" }, { "code": null, "e": 3729, "s": 3718, "text": " Add Notes" } ]
How to use pattern attribute in HTML?
The pattern attribute in HTML is used to set a regular expression in the following input types: text, url, tel, search, date, email, and password. For passwords, with the pattern attribute, you can set the minimum required values. For example, password should have at least 8 characters. You can try to run the following code to learn how to use pattern attribute in HTML. Here, we have set the pattern for 8 or more characters in the password. If a user will add less than that, then by clicking Submit button, an error will raise i.e. “Please match the requested format: Eight or more characters”. <!DOCTYPE html> <html> <body> <h2>Register</h2> <form action="/new.php"> Student UserName<br><input type = "text" name = "name"/><br> Password<br><input type = "password" name = "password" pattern = ".{8,}" title="Eight or more characters"><br><br> <input type = "submit" value = "Submit"> </form> </body> </html>
[ { "code": null, "e": 1350, "s": 1062, "text": "The pattern attribute in HTML is used to set a regular expression in the following input types: text, url, tel, search, date, email, and password. For passwords, with the pattern attribute, you can set the minimum required values. For example, password should have at least 8 characters." }, { "code": null, "e": 1662, "s": 1350, "text": "You can try to run the following code to learn how to use pattern attribute in HTML. Here, we have set the pattern for 8 or more characters in the password. If a user will add less than that, then by clicking Submit button, an error will raise i.e. “Please match the requested format: Eight or more characters”." }, { "code": null, "e": 2036, "s": 1662, "text": "<!DOCTYPE html>\n<html>\n <body>\n <h2>Register</h2>\n <form action=\"/new.php\">\n Student UserName<br><input type = \"text\" name = \"name\"/><br>\n Password<br><input type = \"password\" name = \"password\" pattern = \".{8,}\"\n title=\"Eight or more characters\"><br><br>\n <input type = \"submit\" value = \"Submit\">\n </form>\n </body>\n</html>" } ]
Hide popover using Bootstrap .popover("hide") method
To hide the displayed popover, use the popover(“hide”) method. Use the method to hide the popover like this − $(".btn-primary").click(function(){ $("[data-toggle='popover']").popover('hide'); }); You can try to run the following code to implement the popover(“hide”) method − Live Demo <!DOCTYPE html> <html lang="en"> <head> <title>Bootstrap Example</title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body> <div class="container"> <h3>Example</h3> <a href="#" data-toggle="popover" title="Demo Header" data-content="This is demo text!">Info</a> <div> <p>The following is a demo button:</p> <button type="button" class="btn btn-default">Display</button> <button type="button" class="btn btn-primary">Hide</button> </div> </div> <script> $(document).ready(function(){ $(".btn-default").click(function(){ $("[data-toggle='popover']").popover('show'); }); $(".btn-primary").click(function(){ $("[data-toggle='popover']").popover('hide'); }); }); </script> </body> </html>
[ { "code": null, "e": 1125, "s": 1062, "text": "To hide the displayed popover, use the popover(“hide”) method." }, { "code": null, "e": 1172, "s": 1125, "text": "Use the method to hide the popover like this −" }, { "code": null, "e": 1260, "s": 1172, "text": "$(\".btn-primary\").click(function(){\n $(\"[data-toggle='popover']\").popover('hide');\n});" }, { "code": null, "e": 1340, "s": 1260, "text": "You can try to run the following code to implement the popover(“hide”) method −" }, { "code": null, "e": 1350, "s": 1340, "text": "Live Demo" }, { "code": null, "e": 2477, "s": 1350, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <title>Bootstrap Example</title>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n <link rel=\"stylesheet\" href=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css\">\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js\"></script>\n </head>\n\n<body>\n\n <div class=\"container\">\n <h3>Example</h3>\n <a href=\"#\" data-toggle=\"popover\" title=\"Demo Header\" data-content=\"This is demo text!\">Info</a>\n <div>\n <p>The following is a demo button:</p>\n <button type=\"button\" class=\"btn btn-default\">Display</button>\n <button type=\"button\" class=\"btn btn-primary\">Hide</button>\n </div> \n </div>\n\n<script>\n $(document).ready(function(){\n $(\".btn-default\").click(function(){\n $(\"[data-toggle='popover']\").popover('show');\n });\n $(\".btn-primary\").click(function(){\n $(\"[data-toggle='popover']\").popover('hide');\n });\n });\n</script>\n\n</body>\n</html>" } ]
Difference Between Primary key and Foreign key in DBMS
In this post, we will understand the difference between Primary key and Foreign key in DBMS It is used to ensure that the data in the specific column is unique. It is used to ensure that the data in the specific column is unique. It helps uniquely identify a record in a relational database. It helps uniquely identify a record in a relational database. One primary key only is allowed in a table. One primary key only is allowed in a table. It is a combination of the ‘UNIQUE’ and ‘Not Null’ constraints. It is a combination of the ‘UNIQUE’ and ‘Not Null’ constraints. This means it can’t be a NULL value. This means it can’t be a NULL value. Its value can’t be deleted from parent table. Its value can’t be deleted from parent table. The constraint can be implicitly defined for the temporary tables. The constraint can be implicitly defined for the temporary tables. CREATE TABLE table_name ( col_name int NOT NULL PRIMARY KEY, .... ); It is a column or a group of columns in a relational database table. It is a column or a group of columns in a relational database table. It gives a link between the data in both the tables. It gives a link between the data in both the tables. It is the field in a table which is analogous to primary key of other table. It is the field in a table which is analogous to primary key of other table. More than one foreign key is allowed in a table. More than one foreign key is allowed in a table. It can contain duplicate values in a relational database. It can contain duplicate values in a relational database. It can contain NULL values. It can contain NULL values. Its value can be deleted from the child table. Its value can be deleted from the child table. The constraint can’t be defined on local or global temporary tables. The constraint can’t be defined on local or global temporary tables. CREATE TABLE table_name ( col_name int NOT NULL PRIMARY KEY, col_name int FOREIGN KEY REFERENCES Persons(col_name) );
[ { "code": null, "e": 1154, "s": 1062, "text": "In this post, we will understand the difference between Primary key and Foreign key in DBMS" }, { "code": null, "e": 1223, "s": 1154, "text": "It is used to ensure that the data in the specific column is unique." }, { "code": null, "e": 1292, "s": 1223, "text": "It is used to ensure that the data in the specific column is unique." }, { "code": null, "e": 1354, "s": 1292, "text": "It helps uniquely identify a record in a relational database." }, { "code": null, "e": 1416, "s": 1354, "text": "It helps uniquely identify a record in a relational database." }, { "code": null, "e": 1460, "s": 1416, "text": "One primary key only is allowed in a table." }, { "code": null, "e": 1504, "s": 1460, "text": "One primary key only is allowed in a table." }, { "code": null, "e": 1568, "s": 1504, "text": "It is a combination of the ‘UNIQUE’ and ‘Not Null’ constraints." }, { "code": null, "e": 1632, "s": 1568, "text": "It is a combination of the ‘UNIQUE’ and ‘Not Null’ constraints." }, { "code": null, "e": 1669, "s": 1632, "text": "This means it can’t be a NULL value." }, { "code": null, "e": 1706, "s": 1669, "text": "This means it can’t be a NULL value." }, { "code": null, "e": 1752, "s": 1706, "text": "Its value can’t be deleted from parent table." }, { "code": null, "e": 1798, "s": 1752, "text": "Its value can’t be deleted from parent table." }, { "code": null, "e": 1865, "s": 1798, "text": "The constraint can be implicitly defined for the temporary tables." }, { "code": null, "e": 1932, "s": 1865, "text": "The constraint can be implicitly defined for the temporary tables." }, { "code": null, "e": 2001, "s": 1932, "text": "CREATE TABLE table_name (\ncol_name int NOT NULL PRIMARY KEY,\n....\n);" }, { "code": null, "e": 2070, "s": 2001, "text": "It is a column or a group of columns in a relational database table." }, { "code": null, "e": 2139, "s": 2070, "text": "It is a column or a group of columns in a relational database table." }, { "code": null, "e": 2192, "s": 2139, "text": "It gives a link between the data in both the tables." }, { "code": null, "e": 2245, "s": 2192, "text": "It gives a link between the data in both the tables." }, { "code": null, "e": 2322, "s": 2245, "text": "It is the field in a table which is analogous to primary key of other table." }, { "code": null, "e": 2399, "s": 2322, "text": "It is the field in a table which is analogous to primary key of other table." }, { "code": null, "e": 2448, "s": 2399, "text": "More than one foreign key is allowed in a table." }, { "code": null, "e": 2497, "s": 2448, "text": "More than one foreign key is allowed in a table." }, { "code": null, "e": 2555, "s": 2497, "text": "It can contain duplicate values in a relational database." }, { "code": null, "e": 2613, "s": 2555, "text": "It can contain duplicate values in a relational database." }, { "code": null, "e": 2641, "s": 2613, "text": "It can contain NULL values." }, { "code": null, "e": 2669, "s": 2641, "text": "It can contain NULL values." }, { "code": null, "e": 2716, "s": 2669, "text": "Its value can be deleted from the child table." }, { "code": null, "e": 2763, "s": 2716, "text": "Its value can be deleted from the child table." }, { "code": null, "e": 2832, "s": 2763, "text": "The constraint can’t be defined on local or global temporary tables." }, { "code": null, "e": 2901, "s": 2832, "text": "The constraint can’t be defined on local or global temporary tables." }, { "code": null, "e": 3025, "s": 2901, "text": "CREATE TABLE table_name (\n col_name int NOT NULL PRIMARY KEY,\n col_name int FOREIGN KEY REFERENCES Persons(col_name)\n);" } ]
Add a temporary column in MySQL where the values depend on another column?
You can use CASE statement for this and set conditions to get result in the temporary column. Let us first create a table − mysql> create table DemoTable ( EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY, EmployeeName varchar(20), EmployeeSalary int, EmployeeExperience int ); Query OK, 0 rows affected (0.64 sec) Following is the query to insert some records in the table using insert command − mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Larry',4500,5); Query OK, 1 row affected (0.20 sec) mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Mike',130000,8); Query OK, 1 row affected (0.21 sec) mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Sam',11000,5); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Carol',140000,8) ; Query OK, 1 row affected (0.18 sec) Following is the query to display records from the table using select command − mysql> select *from DemoTable; This will produce the following output − +------------+--------------+----------------+--------------------+ | EmployeeId | EmployeeName | EmployeeSalary | EmployeeExperience | +------------+--------------+----------------+--------------------+ | 1 | Larry | 4500 | 5 | | 2 | Mike | 130000 | 8 | | 3 | Sam | 11000 | 5 | | 4 | Carol | 140000 | 8 | +------------+--------------+----------------+--------------------+ 4 rows in set (0.00 sec) Following is the query to add a temporary column in MySQL where the values depend on another column. Here the temporary column is NewSalary − mysql> select EmployeeId,EmployeeName,EmployeeSalary,EmployeeExperience, case when EmployeeExperience=5 then EmployeeSalary+10000 when EmployeeExperience=8 then EmployeeSalary+20000 else null end as NewSalary from DemoTable; This will produce the following output − +------------+--------------+----------------+--------------------+-----------+ | EmployeeId | EmployeeName | EmployeeSalary | EmployeeExperience | NewSalary | +------------+--------------+----------------+--------------------+-----------+ | 1 | Larry | 4500 | 5 | 14500 | | 2 | Mike | 130000 | 8 | 150000 | | 3 | Sam | 11000 | 5 | 21000 | | 4 | Carol | 140000 | 8 | 160000 | +------------+--------------+----------------+--------------------+-----------+ 4 rows in set (0.00 sec)
[ { "code": null, "e": 1156, "s": 1062, "text": "You can use CASE statement for this and set conditions to get result in the temporary column." }, { "code": null, "e": 1186, "s": 1156, "text": "Let us first create a table −" }, { "code": null, "e": 1397, "s": 1186, "text": "mysql> create table DemoTable\n (\n EmployeeId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n EmployeeName varchar(20),\n EmployeeSalary int,\n EmployeeExperience int\n );\nQuery OK, 0 rows affected (0.64 sec)" }, { "code": null, "e": 1479, "s": 1397, "text": "Following is the query to insert some records in the table using insert command −" }, { "code": null, "e": 2030, "s": 1479, "text": "mysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Larry',4500,5);\nQuery OK, 1 row affected (0.20 sec)\nmysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Mike',130000,8);\nQuery OK, 1 row affected (0.21 sec)\nmysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Sam',11000,5);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable(EmployeeName,EmployeeSalary,EmployeeExperience) values('Carol',140000,8) ;\nQuery OK, 1 row affected (0.18 sec)" }, { "code": null, "e": 2110, "s": 2030, "text": "Following is the query to display records from the table using select command −" }, { "code": null, "e": 2141, "s": 2110, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2182, "s": 2141, "text": "This will produce the following output −" }, { "code": null, "e": 2751, "s": 2182, "text": "+------------+--------------+----------------+--------------------+\n| EmployeeId | EmployeeName | EmployeeSalary | EmployeeExperience |\n+------------+--------------+----------------+--------------------+\n| 1 | Larry | 4500 | 5 |\n| 2 | Mike | 130000 | 8 |\n| 3 | Sam | 11000 | 5 |\n| 4 | Carol | 140000 | 8 |\n+------------+--------------+----------------+--------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2893, "s": 2751, "text": "Following is the query to add a temporary column in MySQL where the values depend on another column. Here the temporary column is NewSalary −" }, { "code": null, "e": 3127, "s": 2893, "text": "mysql> select EmployeeId,EmployeeName,EmployeeSalary,EmployeeExperience,\ncase when\n EmployeeExperience=5 then EmployeeSalary+10000\n when EmployeeExperience=8 then EmployeeSalary+20000\nelse null\n end as NewSalary\nfrom DemoTable;" }, { "code": null, "e": 3168, "s": 3127, "text": "This will produce the following output −" }, { "code": null, "e": 3833, "s": 3168, "text": "+------------+--------------+----------------+--------------------+-----------+\n| EmployeeId | EmployeeName | EmployeeSalary | EmployeeExperience | NewSalary |\n+------------+--------------+----------------+--------------------+-----------+\n| 1 | Larry | 4500 | 5 | 14500 |\n| 2 | Mike | 130000 | 8 | 150000 |\n| 3 | Sam | 11000 | 5 | 21000 |\n| 4 | Carol | 140000 | 8 | 160000 |\n+------------+--------------+----------------+--------------------+-----------+\n4 rows in set (0.00 sec)" } ]
API as a product. How to sell your work when all you know is a back-end | by Artem | Towards Data Science
In this post, I will go through my experience of developing, deploying and selling my API via an API marketplace. I did not have to set up a website or think about how to integrate payment processing solutions. I just wrote my code and deployed it. Building a startup requires a team. A team of a few jacks of all trades: coders, marketing, sales. And, it is a long and exhausting path, therefore, low chances to succeed. You do not have to launch a startup to begin your own thing. I believe there is a way to make products while doing only the back-end job. Over the past year, I have come up with a plan of how I could release my own product without having to deal with managing users and/or dealing with payment processing. It is a 3 steps procedure: Make an API that solves a problemDeploy it with a serverless architectureDistribute through an API Marketplace Make an API that solves a problem Deploy it with a serverless architecture Distribute through an API Marketplace About 6 months ago I had to implement a “procedure” that extracts information from news articles published online. A script that takes article URL as an input and returns structured records such as title, published date, authors, media links, etc. It took me a few minutes to find out that there is a Python library that does all that. Few more minutes of coding, and I had a working prototype. Once you have a code that does something, it is not that difficult to wrap it up as an API. What might be difficult is to deploy and host it. I had to process hundreds of articles a few times per hour. All at the same moment. A spike of 200–800 news URLs that have to be analyzed, then nothing for an undefined amount of time. We were already building our solution on AWS, so I figured out that AWS Lambda should be the best option for this case. AWS Lambda is a serverless Function-as-a-service tool that runs your code in response to an event. You do not have to maintain servers. You pay only for the time that function is executed. I deployed a Lambda function. It worked just as it supposed to: it handled hundreds of simultaneous calls by making concurrent invocations. And, you pay only for the time when it is executed. That was the moment where I thought: “Well, it was quite easy. Does any company sells an API that does that?” Yes, they exist. It seems like they are doing exactly the same thing as I did for my side-project. It is good news because: There is a market for such a thingI have a few examples to compare There is a market for such a thing I have a few examples to compare Now we have to transform our serverless function to a serverless API. I used Zappa python package that does all the heavy lifting for me. I wrote an API with Flask, then deployed it with AWS Lambda and API Gateway through Zappa. The full API code is open-sourced on my GitHub page. Another great package to deploy your serverless code that works with many programming languages and many cloud providers is Serverless. On average, my AWS bill for 50,000 calls of my API would be around 0.6 to 0.8$. Excluding Free Tier! 50,000 API calls for a similar solution are in a 30–250$ range. So, the question is what are the other costs that I should imply to distribute, promote and, more importantly, charge for my API. Most likely, it will not be enough to make me rich but can be enough to cover my subscription bills for Netflix, Spotify, Leetcode, and others. According to RapidAPI: An API marketplace works in the same way as these other online marketplaces, allowing providers to list APIs and developers to consume them. Like other types of marketplaces, a typical API marketplace has several components including a developer portal and an API provider portal. Disclaimer: I am not affiliated/paid/getting any special discounts by RapidAPI at the time I write it. I chose this platform as I believe it is the best one for me. To release my API on RapidAPI Marketplace, I followed the next procedures: I deployed an API on AWS with API Gateway and LambdaCreated an x-api-key on API Gateway to restrict the accessConnected my API to RapidAPI marketplaceShared the x-api-key with RapidAPI I deployed an API on AWS with API Gateway and Lambda Created an x-api-key on API Gateway to restrict the access Connected my API to RapidAPI marketplace Shared the x-api-key with RapidAPI When the end-user makes a call to RapidAPI endpoint (from my API page), it takes care of discounting the token from the user’s plan. Then, RapidAPI makes a call to my API with the x-api-key that I provided. No matter how many different users are using my API through RapidAPI. For my back-end, it is always identical calls with the same x-api-key. So, I do not have to manage users in any way: payment collections, usage plans, usage dashboard— all of this is not my burden anymore. The price for that is 20% of any transaction. No transaction — no pay. For example, if I sell a plan of 100,000 calls/month for 50$ → I get 80% of it (40$). I do not have to pay to RapidAPI if no one buys any plans. Feel free to go to the page of my API where you can test it for free. Get the full code of the API on my GitHub repository. The description of how to set it up is included. I am on ProductHunt today (20 April, 2020), so there is a great chance to see if such a product can get attention from the community. Probably, you have the function itself already. It might be a simple thing that combines a few Python libraries (like mine). It does not matter if you think that any developer who you know can reproduce your code. There are still thousands of people who might be willing to buy it. It will be almost always cheaper for them to pay you instead of writing the code, deploying and maintaining it. A list of API that are in-demand and many developers can do: Text summarization API Text paraphrase API Text categorization API Image classification API API to extract and normalize locations from text/web page API to scrape emails from any URL You use open-source libraries to handle the core functionality. Combine them and obtain unique code. Moreover, if you have already developed such a code and have used it then you know your audience which is great for product development. The best way is to make your resume stand out is by demonstrating that you are capable to make something final. Searching for your first job as a software engineer/data scientist/data engineer/back-end engineer might be extremely difficult, but having your own fully released and maintained API should bring you to the top 1%. Many recruiters will be more willing to open your product page rather than your GitHub repository. APIs that I find on API marketplaces are mostly produced by companies, not individuals. Software products produced by companies are much less prone to errors. However, the price is high. Indie hackers working on the bootstrapped projects would prefer to take a look at something less sophisticated but cheap. The global economy is entering the time of recession. Companies’ budgets will shrink. Those who can propose cheap substitutes to existing solutions should see the rise in demand. So, maybe now is the time. About meMy name is Artem, I build newscatcherapi.com - ultra-fast API to find news articles by any topic, country, language, website, or keyword.I write about Python, cloud architecture, elasticsearch, data engineering, and entrepreneurship.
[ { "code": null, "e": 421, "s": 172, "text": "In this post, I will go through my experience of developing, deploying and selling my API via an API marketplace. I did not have to set up a website or think about how to integrate payment processing solutions. I just wrote my code and deployed it." }, { "code": null, "e": 594, "s": 421, "text": "Building a startup requires a team. A team of a few jacks of all trades: coders, marketing, sales. And, it is a long and exhausting path, therefore, low chances to succeed." }, { "code": null, "e": 732, "s": 594, "text": "You do not have to launch a startup to begin your own thing. I believe there is a way to make products while doing only the back-end job." }, { "code": null, "e": 900, "s": 732, "text": "Over the past year, I have come up with a plan of how I could release my own product without having to deal with managing users and/or dealing with payment processing." }, { "code": null, "e": 927, "s": 900, "text": "It is a 3 steps procedure:" }, { "code": null, "e": 1038, "s": 927, "text": "Make an API that solves a problemDeploy it with a serverless architectureDistribute through an API Marketplace" }, { "code": null, "e": 1072, "s": 1038, "text": "Make an API that solves a problem" }, { "code": null, "e": 1113, "s": 1072, "text": "Deploy it with a serverless architecture" }, { "code": null, "e": 1151, "s": 1113, "text": "Distribute through an API Marketplace" }, { "code": null, "e": 1399, "s": 1151, "text": "About 6 months ago I had to implement a “procedure” that extracts information from news articles published online. A script that takes article URL as an input and returns structured records such as title, published date, authors, media links, etc." }, { "code": null, "e": 1546, "s": 1399, "text": "It took me a few minutes to find out that there is a Python library that does all that. Few more minutes of coding, and I had a working prototype." }, { "code": null, "e": 1688, "s": 1546, "text": "Once you have a code that does something, it is not that difficult to wrap it up as an API. What might be difficult is to deploy and host it." }, { "code": null, "e": 1873, "s": 1688, "text": "I had to process hundreds of articles a few times per hour. All at the same moment. A spike of 200–800 news URLs that have to be analyzed, then nothing for an undefined amount of time." }, { "code": null, "e": 1993, "s": 1873, "text": "We were already building our solution on AWS, so I figured out that AWS Lambda should be the best option for this case." }, { "code": null, "e": 2182, "s": 1993, "text": "AWS Lambda is a serverless Function-as-a-service tool that runs your code in response to an event. You do not have to maintain servers. You pay only for the time that function is executed." }, { "code": null, "e": 2374, "s": 2182, "text": "I deployed a Lambda function. It worked just as it supposed to: it handled hundreds of simultaneous calls by making concurrent invocations. And, you pay only for the time when it is executed." }, { "code": null, "e": 2484, "s": 2374, "text": "That was the moment where I thought: “Well, it was quite easy. Does any company sells an API that does that?”" }, { "code": null, "e": 2583, "s": 2484, "text": "Yes, they exist. It seems like they are doing exactly the same thing as I did for my side-project." }, { "code": null, "e": 2608, "s": 2583, "text": "It is good news because:" }, { "code": null, "e": 2675, "s": 2608, "text": "There is a market for such a thingI have a few examples to compare" }, { "code": null, "e": 2710, "s": 2675, "text": "There is a market for such a thing" }, { "code": null, "e": 2743, "s": 2710, "text": "I have a few examples to compare" }, { "code": null, "e": 2813, "s": 2743, "text": "Now we have to transform our serverless function to a serverless API." }, { "code": null, "e": 2881, "s": 2813, "text": "I used Zappa python package that does all the heavy lifting for me." }, { "code": null, "e": 3025, "s": 2881, "text": "I wrote an API with Flask, then deployed it with AWS Lambda and API Gateway through Zappa. The full API code is open-sourced on my GitHub page." }, { "code": null, "e": 3161, "s": 3025, "text": "Another great package to deploy your serverless code that works with many programming languages and many cloud providers is Serverless." }, { "code": null, "e": 3262, "s": 3161, "text": "On average, my AWS bill for 50,000 calls of my API would be around 0.6 to 0.8$. Excluding Free Tier!" }, { "code": null, "e": 3326, "s": 3262, "text": "50,000 API calls for a similar solution are in a 30–250$ range." }, { "code": null, "e": 3456, "s": 3326, "text": "So, the question is what are the other costs that I should imply to distribute, promote and, more importantly, charge for my API." }, { "code": null, "e": 3600, "s": 3456, "text": "Most likely, it will not be enough to make me rich but can be enough to cover my subscription bills for Netflix, Spotify, Leetcode, and others." }, { "code": null, "e": 3623, "s": 3600, "text": "According to RapidAPI:" }, { "code": null, "e": 3904, "s": 3623, "text": "An API marketplace works in the same way as these other online marketplaces, allowing providers to list APIs and developers to consume them. Like other types of marketplaces, a typical API marketplace has several components including a developer portal and an API provider portal." }, { "code": null, "e": 4069, "s": 3904, "text": "Disclaimer: I am not affiliated/paid/getting any special discounts by RapidAPI at the time I write it. I chose this platform as I believe it is the best one for me." }, { "code": null, "e": 4144, "s": 4069, "text": "To release my API on RapidAPI Marketplace, I followed the next procedures:" }, { "code": null, "e": 4329, "s": 4144, "text": "I deployed an API on AWS with API Gateway and LambdaCreated an x-api-key on API Gateway to restrict the accessConnected my API to RapidAPI marketplaceShared the x-api-key with RapidAPI" }, { "code": null, "e": 4382, "s": 4329, "text": "I deployed an API on AWS with API Gateway and Lambda" }, { "code": null, "e": 4441, "s": 4382, "text": "Created an x-api-key on API Gateway to restrict the access" }, { "code": null, "e": 4482, "s": 4441, "text": "Connected my API to RapidAPI marketplace" }, { "code": null, "e": 4517, "s": 4482, "text": "Shared the x-api-key with RapidAPI" }, { "code": null, "e": 4724, "s": 4517, "text": "When the end-user makes a call to RapidAPI endpoint (from my API page), it takes care of discounting the token from the user’s plan. Then, RapidAPI makes a call to my API with the x-api-key that I provided." }, { "code": null, "e": 4865, "s": 4724, "text": "No matter how many different users are using my API through RapidAPI. For my back-end, it is always identical calls with the same x-api-key." }, { "code": null, "e": 5000, "s": 4865, "text": "So, I do not have to manage users in any way: payment collections, usage plans, usage dashboard— all of this is not my burden anymore." }, { "code": null, "e": 5157, "s": 5000, "text": "The price for that is 20% of any transaction. No transaction — no pay. For example, if I sell a plan of 100,000 calls/month for 50$ → I get 80% of it (40$)." }, { "code": null, "e": 5216, "s": 5157, "text": "I do not have to pay to RapidAPI if no one buys any plans." }, { "code": null, "e": 5286, "s": 5216, "text": "Feel free to go to the page of my API where you can test it for free." }, { "code": null, "e": 5389, "s": 5286, "text": "Get the full code of the API on my GitHub repository. The description of how to set it up is included." }, { "code": null, "e": 5523, "s": 5389, "text": "I am on ProductHunt today (20 April, 2020), so there is a great chance to see if such a product can get attention from the community." }, { "code": null, "e": 5917, "s": 5523, "text": "Probably, you have the function itself already. It might be a simple thing that combines a few Python libraries (like mine). It does not matter if you think that any developer who you know can reproduce your code. There are still thousands of people who might be willing to buy it. It will be almost always cheaper for them to pay you instead of writing the code, deploying and maintaining it." }, { "code": null, "e": 5978, "s": 5917, "text": "A list of API that are in-demand and many developers can do:" }, { "code": null, "e": 6001, "s": 5978, "text": "Text summarization API" }, { "code": null, "e": 6021, "s": 6001, "text": "Text paraphrase API" }, { "code": null, "e": 6045, "s": 6021, "text": "Text categorization API" }, { "code": null, "e": 6070, "s": 6045, "text": "Image classification API" }, { "code": null, "e": 6128, "s": 6070, "text": "API to extract and normalize locations from text/web page" }, { "code": null, "e": 6162, "s": 6128, "text": "API to scrape emails from any URL" }, { "code": null, "e": 6263, "s": 6162, "text": "You use open-source libraries to handle the core functionality. Combine them and obtain unique code." }, { "code": null, "e": 6400, "s": 6263, "text": "Moreover, if you have already developed such a code and have used it then you know your audience which is great for product development." }, { "code": null, "e": 6727, "s": 6400, "text": "The best way is to make your resume stand out is by demonstrating that you are capable to make something final. Searching for your first job as a software engineer/data scientist/data engineer/back-end engineer might be extremely difficult, but having your own fully released and maintained API should bring you to the top 1%." }, { "code": null, "e": 6826, "s": 6727, "text": "Many recruiters will be more willing to open your product page rather than your GitHub repository." }, { "code": null, "e": 7135, "s": 6826, "text": "APIs that I find on API marketplaces are mostly produced by companies, not individuals. Software products produced by companies are much less prone to errors. However, the price is high. Indie hackers working on the bootstrapped projects would prefer to take a look at something less sophisticated but cheap." }, { "code": null, "e": 7341, "s": 7135, "text": "The global economy is entering the time of recession. Companies’ budgets will shrink. Those who can propose cheap substitutes to existing solutions should see the rise in demand. So, maybe now is the time." } ]
Trailing zeroes in factorial | Practice | GeeksforGeeks
For an integer N find the number of trailing zeroes in N!. Example 1: Input: N = 5 Output: 1 Explanation: 5! = 120 so the number of trailing zero is 1. Example 2: Input: N = 4 Output: 0 Explanation: 4! = 24 so the number of trailing zero is 0. Your Task: You don't need to read input or print anything. Your task is to complete the function trailingZeroes() which take an integer N as an input parameter and returns the count of trailing zeroes in the N!. Expected Time Complexity: O(logN) Expected Auxiliary Space: O(1) Constraints: 1 <= N <= 109 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": 297, "s": 238, "text": "For an integer N find the number of trailing zeroes in N!." }, { "code": null, "e": 308, "s": 297, "text": "Example 1:" }, { "code": null, "e": 390, "s": 308, "text": "Input:\nN = 5\nOutput:\n1\nExplanation:\n5! = 120 so the number of trailing zero is 1." }, { "code": null, "e": 401, "s": 390, "text": "Example 2:" }, { "code": null, "e": 482, "s": 401, "text": "Input:\nN = 4\nOutput:\n0\nExplanation:\n4! = 24 so the number of trailing zero is 0." }, { "code": null, "e": 696, "s": 482, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function trailingZeroes() which take an integer N as an input parameter and returns the count of trailing zeroes in the N!." }, { "code": null, "e": 761, "s": 696, "text": "Expected Time Complexity: O(logN)\nExpected Auxiliary Space: O(1)" }, { "code": null, "e": 788, "s": 761, "text": "Constraints:\n1 <= N <= 109" }, { "code": null, "e": 934, "s": 788, "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": 970, "s": 934, "text": " Login to access your submissions. " }, { "code": null, "e": 980, "s": 970, "text": "\nProblem\n" }, { "code": null, "e": 990, "s": 980, "text": "\nContest\n" }, { "code": null, "e": 1053, "s": 990, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 1201, "s": 1053, "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": 1409, "s": 1201, "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": 1515, "s": 1409, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Find the size of largest subset of anagram words - GeeksforGeeks
12 Apr, 2022 Given an array of n string containing lowercase letters. Find the size of largest subset of string which are anagram of each others. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. Input: ant magenta magnate tan gnamate Output: 3 Explanation Anagram strings(1) - ant, tan Anagram strings(2) - magenta, magnate, gnamate Thus, only second subset have largest size i.e., 3 Input: cars bikes arcs steer Output: 2 Naive approach is to generate all possible subset and iterate from largest size of subset containing all string having same size and anagram of each others. Time complexity of this approach is O() where n and m are the size of array and length of string respectively.Efficient approach is to use hashing and sorting. Sort all characters of string and store the hash value(sorted string) in map(unordered_map in C++ and HashMap in java). At last check which one is the frequency sorted word with the highest number of occurrence. C++ Java Python3 C# Javascript // C++ Program to find the size of// largest subset of anagram#include <bits/stdc++.h>using namespace std; // Utility function to find size of// largest subset of anagramint largestAnagramSet(string arr[], int n){ int maxSize = 0; unordered_map<string, int> count; for (int i = 0; i < n; ++i) { // sort the string sort(arr[i].begin(), arr[i].end()); // Increment the count of string count[arr[i]] += 1; // Compute the maximum size of string maxSize = max(maxSize, count[arr[i]]); } return maxSize;} // Driver codeint main(){ string arr[] = { "ant", "magenta", "magnate", "tan", "gnamate" }; int n = sizeof(arr) / sizeof(arr[0]); cout << largestAnagramSet(arr, n) << "\n"; string arr1[] = { "cars", "bikes", "arcs", "steer" }; n = sizeof(arr1) / sizeof(arr[0]); cout << largestAnagramSet(arr1, n); return 0;} // Java Program to find the size of// largest subset of anagramimport java.util.*; class GFG{ // Utility function to find size of// largest subset of anagramstatic int largestAnagramSet(String arr[], int n){ int maxSize = 0; HashMap<String, Integer> count = new HashMap<>(); for (int i = 0; i < n; ++i) { // sort the String char temp[] = arr[i].toCharArray(); Arrays.sort(temp); arr[i] = new String(temp); // Increment the count of String if(count.containsKey(arr[i])) { count.put(arr[i], count.get(arr[i]) + 1); } else { count.put(arr[i], 1); } // Compute the maximum size of String maxSize = Math.max(maxSize, count.get(arr[i])); } return maxSize;} // Driver codepublic static void main(String[] args){ String arr[] = { "ant", "magenta", "magnate", "tan", "gnamate" }; int n = arr.length; System.out.println(largestAnagramSet(arr, n)); String arr1[] = { "cars", "bikes", "arcs", "steer" }; n = arr1.length; System.out.println(largestAnagramSet(arr1, n));}} // This code is contributed by 29AjayKumar # Python3 Program to find the size of# largest subset of anagram # Utility function to find size of# largest subset of anagramdef largestAnagramSet(arr, n) : maxSize = 0 count = {} for i in range(n) : # sort the string arr[i] = ''.join(sorted(arr[i])) # Increment the count of string if arr[i] in count : count[arr[i]] += 1 else : count[arr[i]] = 1 # Compute the maximum size of string maxSize = max(maxSize, count[arr[i]]) return maxSize # Driver codearr = [ "ant", "magenta", "magnate", "tan", "gnamate" ]n = len(arr)print(largestAnagramSet(arr, n)) arr1 = [ "cars", "bikes", "arcs", "steer" ]n = len(arr1)print(largestAnagramSet(arr1, n)) # This code is contributed by divyeshrabadiya072019 // C# Program to find the size of// largest subset of anagramusing System;using System.Collections.Generic; class GFG{ // Utility function to find size of// largest subset of anagramstatic int largestAnagramSet(String []arr, int n){ int maxSize = 0; Dictionary<String, int> count = new Dictionary<String, int>(); for (int i = 0; i < n; ++i) { // sort the String char []temp = arr[i].ToCharArray(); Array.Sort(temp); arr[i] = new String(temp); // Increment the count of String if(count.ContainsKey(arr[i])) { count[arr[i]] = count[arr[i]] + 1; } else { count.Add(arr[i], 1); } // Compute the maximum size of String maxSize = Math.Max(maxSize, count[arr[i]]); } return maxSize;} // Driver codepublic static void Main(String[] args){ String []arr = {"ant", "magenta", "magnate", "tan", "gnamate"}; int n = arr.Length; Console.WriteLine(largestAnagramSet(arr, n)); String []arr1 = {"cars", "bikes", "arcs", "steer"}; n = arr1.Length; Console.WriteLine(largestAnagramSet(arr1, n));}} // This code is contributed by Rajput-Ji <script> // JavaScript Program to find the size of// largest subset of anagram // Utility function to find size of// largest subset of anagramfunction largestAnagramSet(arr, n){ var maxSize = 0; var count = new Map(); for(var i = 0; i < n; ++i) { // sort the String var temp = arr[i].split(''); temp.sort(); arr[i] = temp.join(''); // Increment the count of String if(count.has(arr[i])) { count.set(arr[i], count.get(arr[i])+1); } else { count.set(arr[i], 1); } // Compute the maximum size of String maxSize = Math.max(maxSize, count.get(arr[i])); } return maxSize;} // Driver codevar arr = ["ant", "magenta", "magnate", "tan", "gnamate"];var n = arr.length;document.write(largestAnagramSet(arr, n) + "<br>");var arr1 = ["cars", "bikes", "arcs", "steer"];n = arr1.length;document.write(largestAnagramSet(arr1, n)); </script> Output: 3 2 Time complexity: O() where m is maximum size among all of the strings Auxiliary space: O(n + m)Best approach is to store the frequency array of each word. In this, we just need to iterate over the characters of the words and increment the frequency of current letter. At last, increment the count of only identical frequency array[] and take the maximum among them. This approach is best only when length of strings are maximum in comparison to the array size. cpp Python3 Javascript // C++ Program to find the size of// largest subset of anagram#include <bits/stdc++.h>using namespace std; // Utility function to find size of// largest subset of anagramint largestAnagramSet(string arr[], int n){ int maxSize = 0; // Initialize map<> of vector array map<vector<int>, int> count; for (int i = 0; i < n; ++i) { // Vector array to store // frequency of element vector<int> freq(26); for (char ch : arr[i]) freq[ch - 'a'] += 1; // Increment the count of // frequency array in map<> count[freq] += 1; // Compute the maximum size maxSize = max(maxSize, count[freq]); } return maxSize;} // Driver codeint main(){ string arr[] = { "ant", "magenta", "magnate", "tan", "gnamate" }; int n = sizeof(arr) / sizeof(arr[0]); cout << largestAnagramSet(arr, n) << "\n"; string arr1[] = { "cars", "bikes", "arcs", "steer" }; n = sizeof(arr1) / sizeof(arr[0]); cout << largestAnagramSet(arr1, n); return 0;} # Python Program to find the size of# largest subset of anagram # Utility function to find size of# largest subset of anagramdef largestAnagramSet(arr, n): maxSize = 0 # Initialize dictionary of array count = {} for i in range(n): # list to store # frequency of element freq=[0 for i in range(26)] for ch in arr[i]: freq[ord(ch) - ord('a')] += 1 # Increment the count of # frequency array in dictionary temp = "".join(str(i) for i in freq) if temp not in count: count[temp] = 1 else: count[temp] += 1 # Compute the maximum size maxSize = max(maxSize, count[temp]) return maxSize # Driver codearr = ["ant", "magenta", "magnate","tan", "gnamate"]n = len(arr)print(largestAnagramSet(arr, n)) arr1 = ["cars", "bikes", "arcs", "steer"]n = len(arr1)print(largestAnagramSet(arr1, n)) # This code is contributed by rag2127 <script> // JavaScript Program to find the size of// largest subset of anagram // Utility function to find size of// largest subset of anagramfunction largestAnagramSet(arr, n){ let maxSize = 0 // Initialize dictionary of array let count = new Map() for(let i = 0; i < n; i++){ // list to store // frequency of element let freq=new Array(26).fill(0) for(let ch of arr[i]) freq[ch.charCodeAt(0) - 'a'.charCodeAt(0)] += 1 // Increment the count of // frequency array in dictionary let temp = freq.join('') if(count.has(temp) == false) count.set(temp,1) else count.set(temp, count.get(temp)+ 1) // Compute the maximum size maxSize = Math.max(maxSize, count.get(temp)) } return maxSize} // Driver codelet arr = ["ant", "magenta", "magnate","tan", "gnamate"]let n = arr.lengthdocument.write(largestAnagramSet(arr, n),"</br>") let arr1 = ["cars", "bikes", "arcs", "steer"]n = arr1.lengthdocument.write(largestAnagramSet(arr1, n),"</br>") // This code is contributed by shinjanpatra </script> Output 3 2 Time complexity: O() where m is maximum size among all of the strings Auxiliary space: O(n + m) ManasChhabra2 29AjayKumar Rajput-Ji divyeshrabadiya07 rag2127 noob2000 shinjanpatra anagram cpp-unordered_map cpp-vector Strings Strings anagram Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Top 50 String Coding Problems for Interviews Naive algorithm for Pattern Searching Vigenère Cipher Hill Cipher Count words in a given string How to Append a Character to a String in C Convert character array to string in C++ sprintf() in C Program to count occurrence of a given character in a string Converting Roman Numerals to Decimal lying between 1 to 3999
[ { "code": null, "e": 24852, "s": 24824, "text": "\n12 Apr, 2022" }, { "code": null, "e": 25164, "s": 24852, "text": "Given an array of n string containing lowercase letters. Find the size of largest subset of string which are anagram of each others. An anagram of a string is another string that contains same characters, only the order of characters can be different. For example, “abcd” and “dabc” are anagram of each other. " }, { "code": null, "e": 25417, "s": 25164, "text": "Input: \nant magenta magnate tan gnamate\nOutput: 3\nExplanation\nAnagram strings(1) - ant, tan\nAnagram strings(2) - magenta, magnate,\n gnamate\nThus, only second subset have largest\nsize i.e., 3\n\nInput: \ncars bikes arcs steer \nOutput: 2" }, { "code": null, "e": 25950, "s": 25419, "text": "Naive approach is to generate all possible subset and iterate from largest size of subset containing all string having same size and anagram of each others. Time complexity of this approach is O() where n and m are the size of array and length of string respectively.Efficient approach is to use hashing and sorting. Sort all characters of string and store the hash value(sorted string) in map(unordered_map in C++ and HashMap in java). At last check which one is the frequency sorted word with the highest number of occurrence. " }, { "code": null, "e": 25954, "s": 25950, "text": "C++" }, { "code": null, "e": 25959, "s": 25954, "text": "Java" }, { "code": null, "e": 25967, "s": 25959, "text": "Python3" }, { "code": null, "e": 25970, "s": 25967, "text": "C#" }, { "code": null, "e": 25981, "s": 25970, "text": "Javascript" }, { "code": "// C++ Program to find the size of// largest subset of anagram#include <bits/stdc++.h>using namespace std; // Utility function to find size of// largest subset of anagramint largestAnagramSet(string arr[], int n){ int maxSize = 0; unordered_map<string, int> count; for (int i = 0; i < n; ++i) { // sort the string sort(arr[i].begin(), arr[i].end()); // Increment the count of string count[arr[i]] += 1; // Compute the maximum size of string maxSize = max(maxSize, count[arr[i]]); } return maxSize;} // Driver codeint main(){ string arr[] = { \"ant\", \"magenta\", \"magnate\", \"tan\", \"gnamate\" }; int n = sizeof(arr) / sizeof(arr[0]); cout << largestAnagramSet(arr, n) << \"\\n\"; string arr1[] = { \"cars\", \"bikes\", \"arcs\", \"steer\" }; n = sizeof(arr1) / sizeof(arr[0]); cout << largestAnagramSet(arr1, n); return 0;}", "e": 26924, "s": 25981, "text": null }, { "code": "// Java Program to find the size of// largest subset of anagramimport java.util.*; class GFG{ // Utility function to find size of// largest subset of anagramstatic int largestAnagramSet(String arr[], int n){ int maxSize = 0; HashMap<String, Integer> count = new HashMap<>(); for (int i = 0; i < n; ++i) { // sort the String char temp[] = arr[i].toCharArray(); Arrays.sort(temp); arr[i] = new String(temp); // Increment the count of String if(count.containsKey(arr[i])) { count.put(arr[i], count.get(arr[i]) + 1); } else { count.put(arr[i], 1); } // Compute the maximum size of String maxSize = Math.max(maxSize, count.get(arr[i])); } return maxSize;} // Driver codepublic static void main(String[] args){ String arr[] = { \"ant\", \"magenta\", \"magnate\", \"tan\", \"gnamate\" }; int n = arr.length; System.out.println(largestAnagramSet(arr, n)); String arr1[] = { \"cars\", \"bikes\", \"arcs\", \"steer\" }; n = arr1.length; System.out.println(largestAnagramSet(arr1, n));}} // This code is contributed by 29AjayKumar", "e": 28129, "s": 26924, "text": null }, { "code": "# Python3 Program to find the size of# largest subset of anagram # Utility function to find size of# largest subset of anagramdef largestAnagramSet(arr, n) : maxSize = 0 count = {} for i in range(n) : # sort the string arr[i] = ''.join(sorted(arr[i])) # Increment the count of string if arr[i] in count : count[arr[i]] += 1 else : count[arr[i]] = 1 # Compute the maximum size of string maxSize = max(maxSize, count[arr[i]]) return maxSize # Driver codearr = [ \"ant\", \"magenta\", \"magnate\", \"tan\", \"gnamate\" ]n = len(arr)print(largestAnagramSet(arr, n)) arr1 = [ \"cars\", \"bikes\", \"arcs\", \"steer\" ]n = len(arr1)print(largestAnagramSet(arr1, n)) # This code is contributed by divyeshrabadiya072019", "e": 28912, "s": 28129, "text": null }, { "code": "// C# Program to find the size of// largest subset of anagramusing System;using System.Collections.Generic; class GFG{ // Utility function to find size of// largest subset of anagramstatic int largestAnagramSet(String []arr, int n){ int maxSize = 0; Dictionary<String, int> count = new Dictionary<String, int>(); for (int i = 0; i < n; ++i) { // sort the String char []temp = arr[i].ToCharArray(); Array.Sort(temp); arr[i] = new String(temp); // Increment the count of String if(count.ContainsKey(arr[i])) { count[arr[i]] = count[arr[i]] + 1; } else { count.Add(arr[i], 1); } // Compute the maximum size of String maxSize = Math.Max(maxSize, count[arr[i]]); } return maxSize;} // Driver codepublic static void Main(String[] args){ String []arr = {\"ant\", \"magenta\", \"magnate\", \"tan\", \"gnamate\"}; int n = arr.Length; Console.WriteLine(largestAnagramSet(arr, n)); String []arr1 = {\"cars\", \"bikes\", \"arcs\", \"steer\"}; n = arr1.Length; Console.WriteLine(largestAnagramSet(arr1, n));}} // This code is contributed by Rajput-Ji", "e": 30189, "s": 28912, "text": null }, { "code": "<script> // JavaScript Program to find the size of// largest subset of anagram // Utility function to find size of// largest subset of anagramfunction largestAnagramSet(arr, n){ var maxSize = 0; var count = new Map(); for(var i = 0; i < n; ++i) { // sort the String var temp = arr[i].split(''); temp.sort(); arr[i] = temp.join(''); // Increment the count of String if(count.has(arr[i])) { count.set(arr[i], count.get(arr[i])+1); } else { count.set(arr[i], 1); } // Compute the maximum size of String maxSize = Math.max(maxSize, count.get(arr[i])); } return maxSize;} // Driver codevar arr = [\"ant\", \"magenta\", \"magnate\", \"tan\", \"gnamate\"];var n = arr.length;document.write(largestAnagramSet(arr, n) + \"<br>\");var arr1 = [\"cars\", \"bikes\", \"arcs\", \"steer\"];n = arr1.length;document.write(largestAnagramSet(arr1, n)); </script>", "e": 31191, "s": 30189, "text": null }, { "code": null, "e": 31201, "s": 31191, "text": "Output: " }, { "code": null, "e": 31205, "s": 31201, "text": "3\n2" }, { "code": null, "e": 31667, "s": 31205, "text": "Time complexity: O() where m is maximum size among all of the strings Auxiliary space: O(n + m)Best approach is to store the frequency array of each word. In this, we just need to iterate over the characters of the words and increment the frequency of current letter. At last, increment the count of only identical frequency array[] and take the maximum among them. This approach is best only when length of strings are maximum in comparison to the array size. " }, { "code": null, "e": 31671, "s": 31667, "text": "cpp" }, { "code": null, "e": 31679, "s": 31671, "text": "Python3" }, { "code": null, "e": 31690, "s": 31679, "text": "Javascript" }, { "code": "// C++ Program to find the size of// largest subset of anagram#include <bits/stdc++.h>using namespace std; // Utility function to find size of// largest subset of anagramint largestAnagramSet(string arr[], int n){ int maxSize = 0; // Initialize map<> of vector array map<vector<int>, int> count; for (int i = 0; i < n; ++i) { // Vector array to store // frequency of element vector<int> freq(26); for (char ch : arr[i]) freq[ch - 'a'] += 1; // Increment the count of // frequency array in map<> count[freq] += 1; // Compute the maximum size maxSize = max(maxSize, count[freq]); } return maxSize;} // Driver codeint main(){ string arr[] = { \"ant\", \"magenta\", \"magnate\", \"tan\", \"gnamate\" }; int n = sizeof(arr) / sizeof(arr[0]); cout << largestAnagramSet(arr, n) << \"\\n\"; string arr1[] = { \"cars\", \"bikes\", \"arcs\", \"steer\" }; n = sizeof(arr1) / sizeof(arr[0]); cout << largestAnagramSet(arr1, n); return 0;}", "e": 32781, "s": 31690, "text": null }, { "code": "# Python Program to find the size of# largest subset of anagram # Utility function to find size of# largest subset of anagramdef largestAnagramSet(arr, n): maxSize = 0 # Initialize dictionary of array count = {} for i in range(n): # list to store # frequency of element freq=[0 for i in range(26)] for ch in arr[i]: freq[ord(ch) - ord('a')] += 1 # Increment the count of # frequency array in dictionary temp = \"\".join(str(i) for i in freq) if temp not in count: count[temp] = 1 else: count[temp] += 1 # Compute the maximum size maxSize = max(maxSize, count[temp]) return maxSize # Driver codearr = [\"ant\", \"magenta\", \"magnate\",\"tan\", \"gnamate\"]n = len(arr)print(largestAnagramSet(arr, n)) arr1 = [\"cars\", \"bikes\", \"arcs\", \"steer\"]n = len(arr1)print(largestAnagramSet(arr1, n)) # This code is contributed by rag2127", "e": 33732, "s": 32781, "text": null }, { "code": "<script> // JavaScript Program to find the size of// largest subset of anagram // Utility function to find size of// largest subset of anagramfunction largestAnagramSet(arr, n){ let maxSize = 0 // Initialize dictionary of array let count = new Map() for(let i = 0; i < n; i++){ // list to store // frequency of element let freq=new Array(26).fill(0) for(let ch of arr[i]) freq[ch.charCodeAt(0) - 'a'.charCodeAt(0)] += 1 // Increment the count of // frequency array in dictionary let temp = freq.join('') if(count.has(temp) == false) count.set(temp,1) else count.set(temp, count.get(temp)+ 1) // Compute the maximum size maxSize = Math.max(maxSize, count.get(temp)) } return maxSize} // Driver codelet arr = [\"ant\", \"magenta\", \"magnate\",\"tan\", \"gnamate\"]let n = arr.lengthdocument.write(largestAnagramSet(arr, n),\"</br>\") let arr1 = [\"cars\", \"bikes\", \"arcs\", \"steer\"]n = arr1.lengthdocument.write(largestAnagramSet(arr1, n),\"</br>\") // This code is contributed by shinjanpatra </script>", "e": 34855, "s": 33732, "text": null }, { "code": null, "e": 34866, "s": 34855, "text": "Output\n3\n2" }, { "code": null, "e": 34963, "s": 34866, "text": "Time complexity: O() where m is maximum size among all of the strings Auxiliary space: O(n + m) " }, { "code": null, "e": 34977, "s": 34963, "text": "ManasChhabra2" }, { "code": null, "e": 34989, "s": 34977, "text": "29AjayKumar" }, { "code": null, "e": 34999, "s": 34989, "text": "Rajput-Ji" }, { "code": null, "e": 35017, "s": 34999, "text": "divyeshrabadiya07" }, { "code": null, "e": 35025, "s": 35017, "text": "rag2127" }, { "code": null, "e": 35034, "s": 35025, "text": "noob2000" }, { "code": null, "e": 35047, "s": 35034, "text": "shinjanpatra" }, { "code": null, "e": 35055, "s": 35047, "text": "anagram" }, { "code": null, "e": 35073, "s": 35055, "text": "cpp-unordered_map" }, { "code": null, "e": 35084, "s": 35073, "text": "cpp-vector" }, { "code": null, "e": 35092, "s": 35084, "text": "Strings" }, { "code": null, "e": 35100, "s": 35092, "text": "Strings" }, { "code": null, "e": 35108, "s": 35100, "text": "anagram" }, { "code": null, "e": 35206, "s": 35108, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35251, "s": 35206, "text": "Top 50 String Coding Problems for Interviews" }, { "code": null, "e": 35289, "s": 35251, "text": "Naive algorithm for Pattern Searching" }, { "code": null, "e": 35306, "s": 35289, "text": "Vigenère Cipher" }, { "code": null, "e": 35318, "s": 35306, "text": "Hill Cipher" }, { "code": null, "e": 35348, "s": 35318, "text": "Count words in a given string" }, { "code": null, "e": 35391, "s": 35348, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 35432, "s": 35391, "text": "Convert character array to string in C++" }, { "code": null, "e": 35447, "s": 35432, "text": "sprintf() in C" }, { "code": null, "e": 35508, "s": 35447, "text": "Program to count occurrence of a given character in a string" } ]
How to get innerHTML of a div tag using jQuery?
To get the innerHTML of a div tag in jQuery, use the class with innerHTML. You can try to run the following code to learn how to get innerHTML of a div tag 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(){ $("#button1").click(function(){ var one = $('.a').innerHTML; alert(one); }); }); </script> </head> <body> <div class="a">Value one</div> <button id="button1">Get</button> </body> </html>
[ { "code": null, "e": 1233, "s": 1062, "text": "To get the innerHTML of a div tag in jQuery, use the class with innerHTML. You can try to run the following code to learn how to get innerHTML of a div tag using jQuery −" }, { "code": null, "e": 1243, "s": 1233, "text": "Live Demo" }, { "code": null, "e": 1614, "s": 1243, "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 $(\"#button1\").click(function(){\n var one = $('.a').innerHTML;\n alert(one);\n });\n });\n</script>\n</head>\n\n<body>\n <div class=\"a\">Value one</div>\n <button id=\"button1\">Get</button>\n</body>\n\n</html>" } ]
Bootstrap .btn-lg class
To make a large button, use the .btn-lg class in Bootstrap. You can try to run the following code to implement the btn-lg class Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <meta name = "viewport" content = "width=device-width, initial-scale = 1"> <link rel = "stylesheet" href = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <button type = "button" class = "btn btn-default btn-lg"> Large button </button> </body> </html>
[ { "code": null, "e": 1122, "s": 1062, "text": "To make a large button, use the .btn-lg class in Bootstrap." }, { "code": null, "e": 1190, "s": 1122, "text": "You can try to run the following code to implement the btn-lg class" }, { "code": null, "e": 1200, "s": 1190, "text": "Live Demo" }, { "code": null, "e": 1809, "s": 1200, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <meta name = \"viewport\" content = \"width=device-width, initial-scale = 1\">\n <link rel = \"stylesheet\" href = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <button type = \"button\" class = \"btn btn-default btn-lg\">\n Large button\n </button>\n </body>\n</html>" } ]
How to print the Python Exception/Error Hierarchy? - GeeksforGeeks
20 Aug, 2020 Before Printing the Error Hierarchy let’s understand what an Exception really is? Exceptions occur even if our code is syntactically correct, however, while executing they throw an error. They are not unconditionally fatal, errors which we get while executing are called Exceptions. There are many Built-in Exceptions in Python let’s try to print them out in a hierarchy. For printing the tree hierarchy we will use inspect module in Python. The inspect module provides useful functions to get information about objects such as modules, classes, methods, functions, and code objects. For example, it can help you examine the contents of a class, extract and format the argument list for a function. For building a tree hierarchy we will use inspect.getclasstree(). Syntax: inspect.getclasstree(classes, unique=False) inspect.getclasstree() arranges the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list. If the unique argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times. Let’s write a code for printing tree hierarchy for built-in exceptions: Python3 # import inspect moduleimport inspect # our treeClass functiondef treeClass(cls, ind = 0): # print name of the class print ('-' * ind, cls.__name__) # iterating through subclasses for i in cls.__subclasses__(): treeClass(i, ind + 3) print("Hierarchy for Built-in exceptions is : ") # inspect.getmro() Return a tuple # of class cls’s base classes. # building a tree hierarchy inspect.getclasstree(inspect.getmro(BaseException)) # function calltreeClass(BaseException) Output: Hierarchy for Built-in exceptions is : BaseException --- Exception ------ TypeError ------ StopAsyncIteration ------ StopIteration ------ ImportError --------- ModuleNotFoundError --------- ZipImportError ------ OSError --------- ConnectionError ------------ BrokenPipeError ------------ ConnectionAbortedError ------------ ConnectionRefusedError ------------ ConnectionResetError --------- BlockingIOError --------- ChildProcessError --------- FileExistsError --------- FileNotFoundError --------- IsADirectoryError --------- NotADirectoryError --------- InterruptedError --------- PermissionError --------- ProcessLookupError --------- TimeoutError --------- UnsupportedOperation ------ EOFError ------ RuntimeError --------- RecursionError --------- NotImplementedError --------- _DeadlockError ------ NameError --------- UnboundLocalError ------ AttributeError ------ SyntaxError --------- IndentationError ------------ TabError ------ LookupError --------- IndexError --------- KeyError --------- CodecRegistryError ------ ValueError --------- UnicodeError ------------ UnicodeEncodeError ------------ UnicodeDecodeError ------------ UnicodeTranslateError --------- UnsupportedOperation ------ AssertionError ------ ArithmeticError --------- FloatingPointError --------- OverflowError --------- ZeroDivisionError ------ SystemError --------- CodecRegistryError ------ ReferenceError ------ MemoryError ------ BufferError ------ Warning --------- UserWarning --------- DeprecationWarning --------- PendingDeprecationWarning --------- SyntaxWarning --------- RuntimeWarning --------- FutureWarning --------- ImportWarning --------- UnicodeWarning --------- BytesWarning --------- ResourceWarning ------ _OptionError ------ error ------ Verbose ------ Error ------ TokenError ------ StopTokenizing ------ EndOfBlock --- GeneratorExit --- SystemExit --- KeyboardInterrupt Python-exceptions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Selecting rows in pandas DataFrame based on conditions Python | Pandas dataframe.groupby() Create a directory in Python
[ { "code": null, "e": 24292, "s": 24264, "text": "\n20 Aug, 2020" }, { "code": null, "e": 24664, "s": 24292, "text": "Before Printing the Error Hierarchy let’s understand what an Exception really is? Exceptions occur even if our code is syntactically correct, however, while executing they throw an error. They are not unconditionally fatal, errors which we get while executing are called Exceptions. There are many Built-in Exceptions in Python let’s try to print them out in a hierarchy." }, { "code": null, "e": 24992, "s": 24664, "text": "For printing the tree hierarchy we will use inspect module in Python. The inspect module provides useful functions to get information about objects such as modules, classes, methods, functions, and code objects. For example, it can help you examine the contents of a class, extract and format the argument list for a function." }, { "code": null, "e": 25058, "s": 24992, "text": "For building a tree hierarchy we will use inspect.getclasstree()." }, { "code": null, "e": 25110, "s": 25058, "text": "Syntax: inspect.getclasstree(classes, unique=False)" }, { "code": null, "e": 25317, "s": 25110, "text": "inspect.getclasstree() arranges the given list of classes into a hierarchy of nested lists. Where a nested list appears, it contains classes derived from the class whose entry immediately precedes the list." }, { "code": null, "e": 25531, "s": 25317, "text": "If the unique argument is true, exactly one entry appears in the returned structure for each class in the given list. Otherwise, classes using multiple inheritance and their descendants will appear multiple times." }, { "code": null, "e": 25603, "s": 25531, "text": "Let’s write a code for printing tree hierarchy for built-in exceptions:" }, { "code": null, "e": 25611, "s": 25603, "text": "Python3" }, { "code": "# import inspect moduleimport inspect # our treeClass functiondef treeClass(cls, ind = 0): # print name of the class print ('-' * ind, cls.__name__) # iterating through subclasses for i in cls.__subclasses__(): treeClass(i, ind + 3) print(\"Hierarchy for Built-in exceptions is : \") # inspect.getmro() Return a tuple # of class cls’s base classes. # building a tree hierarchy inspect.getclasstree(inspect.getmro(BaseException)) # function calltreeClass(BaseException)", "e": 26115, "s": 25611, "text": null }, { "code": null, "e": 26123, "s": 26115, "text": "Output:" }, { "code": null, "e": 27999, "s": 26123, "text": "Hierarchy for Built-in exceptions is : \n BaseException\n--- Exception\n------ TypeError\n------ StopAsyncIteration\n------ StopIteration\n------ ImportError\n--------- ModuleNotFoundError\n--------- ZipImportError\n------ OSError\n--------- ConnectionError\n------------ BrokenPipeError\n------------ ConnectionAbortedError\n------------ ConnectionRefusedError\n------------ ConnectionResetError\n--------- BlockingIOError\n--------- ChildProcessError\n--------- FileExistsError\n--------- FileNotFoundError\n--------- IsADirectoryError\n--------- NotADirectoryError\n--------- InterruptedError\n--------- PermissionError\n--------- ProcessLookupError\n--------- TimeoutError\n--------- UnsupportedOperation\n------ EOFError\n------ RuntimeError\n--------- RecursionError\n--------- NotImplementedError\n--------- _DeadlockError\n------ NameError\n--------- UnboundLocalError\n------ AttributeError\n------ SyntaxError\n--------- IndentationError\n------------ TabError\n------ LookupError\n--------- IndexError\n--------- KeyError\n--------- CodecRegistryError\n------ ValueError\n--------- UnicodeError\n------------ UnicodeEncodeError\n------------ UnicodeDecodeError\n------------ UnicodeTranslateError\n--------- UnsupportedOperation\n------ AssertionError\n------ ArithmeticError\n--------- FloatingPointError\n--------- OverflowError\n--------- ZeroDivisionError\n------ SystemError\n--------- CodecRegistryError\n------ ReferenceError\n------ MemoryError\n------ BufferError\n------ Warning\n--------- UserWarning\n--------- DeprecationWarning\n--------- PendingDeprecationWarning\n--------- SyntaxWarning\n--------- RuntimeWarning\n--------- FutureWarning\n--------- ImportWarning\n--------- UnicodeWarning\n--------- BytesWarning\n--------- ResourceWarning\n------ _OptionError\n------ error\n------ Verbose\n------ Error\n------ TokenError\n------ StopTokenizing\n------ EndOfBlock\n--- GeneratorExit\n--- SystemExit\n--- KeyboardInterrupt\n" }, { "code": null, "e": 28017, "s": 27999, "text": "Python-exceptions" }, { "code": null, "e": 28024, "s": 28017, "text": "Python" }, { "code": null, "e": 28122, "s": 28024, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28154, "s": 28122, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28210, "s": 28154, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28252, "s": 28210, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28294, "s": 28252, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28316, "s": 28294, "text": "Defaultdict in Python" }, { "code": null, "e": 28355, "s": 28316, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28386, "s": 28355, "text": "Python | os.path.join() method" }, { "code": null, "e": 28441, "s": 28386, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28477, "s": 28441, "text": "Python | Pandas dataframe.groupby()" } ]
Tryit Editor v3.7
Tryit: Using pixels
[]
Tryit Editor v3.7
Tryit: HTML table border style
[]
Body-parser middleware in Node.js - GeeksforGeeks
25 Jun, 2021 Body-parser is the Node.js body parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it.Installation of body-parser module: You can visit the link to Install body-parser module. You can install this package by using this command. You can visit the link to Install body-parser module. You can install this package by using this command. npm install body-parser After installing body-parser you can check your body-parser version in command prompt using the command. After installing body-parser you can check your body-parser version in command prompt using the command. npm --version body-parser 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. 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 Filename: SampleForm.ejs html <!DOCTYPE html><html> <head> <title>Body-Parser Module Demo</title></head> <body> <h1>Demo Form</h1> <form action="saveData" method="POST"> <pre> Enter your Email : <input type="text" name="email"> <br> <input type="submit" value="Submit Form"> </pre> </form></body> </html> Filename: index.js javascript const bodyparser = require('body-parser')const express = require("express")const path = require('path')const app = express() var PORT = process.env.port || 3000 // View Engine Setupapp.set("views", path.join(__dirname))app.set("view engine", "ejs") // Body-parser middlewareapp.use(bodyparser.urlencoded({extended:false}))app.use(bodyparser.json()) app.get("/", function(req, res){ res.render("SampleForm")}); app.post('/saveData', (req, res) => { console.log("Using Body-parser: ", req.body.email)}) app.listen(PORT, function(error){ if (error) throw error console.log("Server created Successfully on PORT", PORT)}) Steps to run the program: The project structure will look like this: The project structure will look like this: Make sure you have installed ‘view engine’ like I have used “ejs” and also installed express and body-parser module using following commands: Make sure you have installed ‘view engine’ like I have used “ejs” and also installed express and body-parser module using following commands: npm install express npm install ejs npm install body-parser Run index.js file using below command: Run index.js file using below command: node index.js Now Open browser and type the below URL and you will see the Demo Form as shown below: Now Open browser and type the below URL and you will see the Demo Form as shown below: http://localhost:3000/ Now submit the form and then you will see the following output: Now submit the form and then you will see the following output: But if we do not use this body-parser middle, then while parsing, error will occur as show below: But if we do not use this body-parser middle, then while parsing, error will occur as show below: So this is how you can use body-parser module for parsing incoming request bodies in a middleware before you handle it. jpd20 Node.js-Misc Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.readFile() Method Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Express.js res.render() Function Roadmap to Become a Web Developer in 2022 Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 23988, "s": 23960, "text": "\n25 Jun, 2021" }, { "code": null, "e": 24173, "s": 23988, "text": "Body-parser is the Node.js body parsing middleware. It is responsible for parsing the incoming request bodies in a middleware before you handle it.Installation of body-parser module: " }, { "code": null, "e": 24281, "s": 24173, "text": "You can visit the link to Install body-parser module. You can install this package by using this command. " }, { "code": null, "e": 24389, "s": 24281, "text": "You can visit the link to Install body-parser module. You can install this package by using this command. " }, { "code": null, "e": 24413, "s": 24389, "text": "npm install body-parser" }, { "code": null, "e": 24520, "s": 24413, "text": "After installing body-parser you can check your body-parser version in command prompt using the command. " }, { "code": null, "e": 24627, "s": 24520, "text": "After installing body-parser you can check your body-parser version in command prompt using the command. " }, { "code": null, "e": 24653, "s": 24627, "text": "npm --version body-parser" }, { "code": null, "e": 24791, "s": 24653, "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. " }, { "code": null, "e": 24929, "s": 24791, "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. " }, { "code": null, "e": 24943, "s": 24929, "text": "node index.js" }, { "code": null, "e": 24970, "s": 24943, "text": "Filename: SampleForm.ejs " }, { "code": null, "e": 24975, "s": 24970, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Body-Parser Module Demo</title></head> <body> <h1>Demo Form</h1> <form action=\"saveData\" method=\"POST\"> <pre> Enter your Email : <input type=\"text\" name=\"email\"> <br> <input type=\"submit\" value=\"Submit Form\"> </pre> </form></body> </html>", "e": 25366, "s": 24975, "text": null }, { "code": null, "e": 25387, "s": 25366, "text": "Filename: index.js " }, { "code": null, "e": 25398, "s": 25387, "text": "javascript" }, { "code": "const bodyparser = require('body-parser')const express = require(\"express\")const path = require('path')const app = express() var PORT = process.env.port || 3000 // View Engine Setupapp.set(\"views\", path.join(__dirname))app.set(\"view engine\", \"ejs\") // Body-parser middlewareapp.use(bodyparser.urlencoded({extended:false}))app.use(bodyparser.json()) app.get(\"/\", function(req, res){ res.render(\"SampleForm\")}); app.post('/saveData', (req, res) => { console.log(\"Using Body-parser: \", req.body.email)}) app.listen(PORT, function(error){ if (error) throw error console.log(\"Server created Successfully on PORT\", PORT)})", "e": 26031, "s": 25398, "text": null }, { "code": null, "e": 26059, "s": 26031, "text": "Steps to run the program: " }, { "code": null, "e": 26104, "s": 26059, "text": "The project structure will look like this: " }, { "code": null, "e": 26149, "s": 26104, "text": "The project structure will look like this: " }, { "code": null, "e": 26293, "s": 26149, "text": "Make sure you have installed ‘view engine’ like I have used “ejs” and also installed express and body-parser module using following commands: " }, { "code": null, "e": 26437, "s": 26293, "text": "Make sure you have installed ‘view engine’ like I have used “ejs” and also installed express and body-parser module using following commands: " }, { "code": null, "e": 26497, "s": 26437, "text": "npm install express\nnpm install ejs\nnpm install body-parser" }, { "code": null, "e": 26538, "s": 26497, "text": "Run index.js file using below command: " }, { "code": null, "e": 26579, "s": 26538, "text": "Run index.js file using below command: " }, { "code": null, "e": 26593, "s": 26579, "text": "node index.js" }, { "code": null, "e": 26682, "s": 26593, "text": "Now Open browser and type the below URL and you will see the Demo Form as shown below: " }, { "code": null, "e": 26771, "s": 26682, "text": "Now Open browser and type the below URL and you will see the Demo Form as shown below: " }, { "code": null, "e": 26794, "s": 26771, "text": "http://localhost:3000/" }, { "code": null, "e": 26864, "s": 26798, "text": "Now submit the form and then you will see the following output: " }, { "code": null, "e": 26930, "s": 26864, "text": "Now submit the form and then you will see the following output: " }, { "code": null, "e": 27030, "s": 26930, "text": "But if we do not use this body-parser middle, then while parsing, error will occur as show below: " }, { "code": null, "e": 27130, "s": 27030, "text": "But if we do not use this body-parser middle, then while parsing, error will occur as show below: " }, { "code": null, "e": 27251, "s": 27130, "text": "So this is how you can use body-parser module for parsing incoming request bodies in a middleware before you handle it. " }, { "code": null, "e": 27257, "s": 27251, "text": "jpd20" }, { "code": null, "e": 27270, "s": 27257, "text": "Node.js-Misc" }, { "code": null, "e": 27278, "s": 27270, "text": "Node.js" }, { "code": null, "e": 27295, "s": 27278, "text": "Web Technologies" }, { "code": null, "e": 27393, "s": 27295, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27422, "s": 27393, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 27452, "s": 27422, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 27509, "s": 27452, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 27563, "s": 27509, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 27596, "s": 27563, "text": "Express.js res.render() Function" }, { "code": null, "e": 27638, "s": 27596, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 27700, "s": 27638, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 27743, "s": 27700, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27788, "s": 27743, "text": "Convert a string to an integer in JavaScript" } ]
How to Identify Unusual Observations on Your Regression Model with R? | by Michaelino Mervisiano | Towards Data Science
In this article, I will discuss a few methods on how to detect unusual observations in regression analysis. As an analyst, you might to consider screening for unusual observations, it will help you to get a comprehensive regression model. The unusual observations require further investigation, either because they are different compared to other observations, or because they bring a disproportionate amount of influence to the outcomes of the model. There are three types of unusual observations that I will review: · Outliers · High-leverage observations · Influential observations For illustration, I will use R sample data (state.x77). This data set give us information such as population size, average income, illiteracy rate, temperature, and murder rate for 50 states in USA. Using code below, I would like to build a regression model that can predict the murder rate in certain states based on their population, income, illiteracy rate, and temperature. Also, we will apply car package for our data wrangling. # How to Identify Unusual Observations in Regression?# Created by Michaelino Mervisianoinstall.packages(“car”)library(“car”)states <- as.data.frame(state.x77[,c(“Murder”, “Population”,”Illiteracy”, “Income”, “Frost”)])View(states) fit <- lm(Murder ~ Population + Illiteracy + Income + Frost, data=states)summary(fit) From summary function, we find that our model is indeed significant with p-value of F-statistic <0.05. From t-test, we also spot that both illiteracy rate and population size are the significant on predict murder rate in a state. Next, we will investigate if we have unusual observations in our model > summary(fit)Call:lm(formula = Murder ~ Population + Illiteracy + Income + Frost, data = states)Residuals: Min 1Q Median 3Q Max -4.7960 -1.6495 -0.0811 1.4815 7.6210Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 1.235e+00 3.866e+00 0.319 0.7510 Population 2.237e-04 9.052e-05 2.471 0.0173 * Illiteracy 4.143e+00 8.744e-01 4.738 2.19e-05 ***Income 6.442e-05 6.837e-04 0.094 0.9253 Frost 5.813e-04 1.005e-02 0.058 0.9541 — -Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 2.535 on 45 degrees of freedomMultiple R-squared: 0.567, Adjusted R-squared: 0.5285 F-statistic: 14.73 on 4 and 45 DF, p-value: 9.133e-08 Outliers Outliers observations aren’t predicted well by regression model. They either have extremely large positive or negative residuals. If the model is underestimating the response value, then it will be indicated by positive residual. On the other hand, if the model is overestimating the response value, then it will be indicated by negative residual. From our regression model example, we can start investigating outliers observation by using Q-Q plot. Code below helps you to plot and find potential outliers. Nevada (28th observation) and Rhode Island (39th observation) are states that detected as potential outliers. > qqPlot(fit,labels=row.names(states), id.method=”identify”, simulate=TRUE, main=”Q-Q Plot”) Nevada Rhode Island 28 39 Applying outlierTest function is helping us to confirm if potential outliers are indeed outliers. The statistical test is showing that Nevada undeniably detected as an outlier with p-value = 0.048. > outlierTest(fit) rstudent unadjusted p-value Bonferroni pNevada 3.542929 0.00095088 0.047544 Q-Q plot also confirms that Nevada has a large positive residual. It means our model underestimates the murder rate in this state. You can spot that the murder rate in Nevada is 11.5% while the model only predicts at 3.9%. We clearly understand that Nevada is indeed different compared to other states. > states[“Nevada”,] Murder Population Illiteracy Income FrostNevada 11.5 590 0.5 5149 188> fitted(fit)[“Nevada”] Nevada 3.878958 Therefore, you can remove this observation and re-run the test to see if other outliers are present. As an analyst, you might want to know why Nevada has a high murder rate. Perhaps you can ask post this question to Quora and let me know if you have the answer 😉 High-leverage points Observations will be considered as high-leverage points if they resemble outliers when we compared it to other predictors. Strictly speaking, they have uncommon combination of predictor values while the response value has minor impact on determining leverage. You can compute the high leverage observation by looking at the ratio of number of parameters estimated in model and sample size. If an observation has a ratio greater than 2 -3 times the average ratio, then the observation considers as high-leverage points. I personally like to use this simple function to identify high-leverage observations. highleverage <- function(fit) { p <- length(coefficients(fit)) n <- length(fitted(fit)) ratio <-p/n plot(hatvalues(fit), main=”Index Plot of Ratio”) abline(h=c(2,3)*ratio, col=”red”, lty=2) identify(1:n, hatvalues(fit), names(hatvalues(fit)))}highleverage(fit) The graph above indicates that Alaska and California have the highest ratio. It means these two states are quite unusual if we compared their predictor values compared to other states. Here is why: · For Alaska, this state has a much higher income compared to other states, while having smaller population and lower temperature. · For California, this state has much a bigger population than other states, while having higher income and higher temperature. Both of these states are indeed quite particular compared to the other 48 states. One thing to remember that not all high-leverage observations are influential observations. It will depend if they are outliers or not. Influential Observations Observations with a disproportionate impact on the values of the model parameters can be considered as Influential observations. For instance, if you drop a single observation, then it change your model dramatically. That single observation must be influential observation. Thus, it is important for us to inspect if our data contains influential points or not. In my experience, there are two effective methods to identify influential observations: 1. Cook’s distance Code below provide a way to calculate the cut-off and plot Cook’s distance for each of our observation. The plot shows Alaska, Hawaii, and Nevada as influential observations. Removing these 3 states will have a significant impact on the values of the intercept and slope in our regression model. cutoff <- 4/(nrow(states)-length(fit$coefficients)-2)plot(fit, which=4, cook.levels=cutoff)abline(h=cutoff, lty=2, col=”red”) I need to highlight that the plot above is indeed helpful to identify influential observations, but it doesn’t give extra information about how these observations affect the model. That’s why Added Variable plots can be an option for us to dig more information. 2. Added Variable plots Added variable plots works by plotting each predictor variable against the response variable and other predictors. It can be easily created using the avPlots() function in car package. library(car) avPlots(fit, ask=FALSE, id.method=”identify”) From the graph below, the straight line in each plot is the actual regression coefficient for that predictor variable. We might view the impact of influential observations by imagining how the line would alter if the point representing that observation was removed. Now, we will incorporate all information from outlier, high-leverage, and influential observations into a single informative plot. I personally find influencePlot() is a very handy function to represent these unusual observation issues. library(car) influencePlot(fit, id.method=”identify”, main=”Influence Plot”, sub=”Circle size is proportional to Cook’s distance”) The graph above summarises our final verdict conveniently. Here it is: · Nevada and Rhode island are Outliers. · California, Washington, New York, and Hawaii are High-Leverage Observations · Alaska is the Influential Observation I hope you find this article is useful and kindly share it with others
[ { "code": null, "e": 623, "s": 171, "text": "In this article, I will discuss a few methods on how to detect unusual observations in regression analysis. As an analyst, you might to consider screening for unusual observations, it will help you to get a comprehensive regression model. The unusual observations require further investigation, either because they are different compared to other observations, or because they bring a disproportionate amount of influence to the outcomes of the model." }, { "code": null, "e": 689, "s": 623, "text": "There are three types of unusual observations that I will review:" }, { "code": null, "e": 700, "s": 689, "text": "· Outliers" }, { "code": null, "e": 729, "s": 700, "text": "· High-leverage observations" }, { "code": null, "e": 756, "s": 729, "text": "· Influential observations" }, { "code": null, "e": 955, "s": 756, "text": "For illustration, I will use R sample data (state.x77). This data set give us information such as population size, average income, illiteracy rate, temperature, and murder rate for 50 states in USA." }, { "code": null, "e": 1190, "s": 955, "text": "Using code below, I would like to build a regression model that can predict the murder rate in certain states based on their population, income, illiteracy rate, and temperature. Also, we will apply car package for our data wrangling." }, { "code": null, "e": 1507, "s": 1190, "text": "# How to Identify Unusual Observations in Regression?# Created by Michaelino Mervisianoinstall.packages(“car”)library(“car”)states <- as.data.frame(state.x77[,c(“Murder”, “Population”,”Illiteracy”, “Income”, “Frost”)])View(states) fit <- lm(Murder ~ Population + Illiteracy + Income + Frost, data=states)summary(fit)" }, { "code": null, "e": 1808, "s": 1507, "text": "From summary function, we find that our model is indeed significant with p-value of F-statistic <0.05. From t-test, we also spot that both illiteracy rate and population size are the significant on predict murder rate in a state. Next, we will investigate if we have unusual observations in our model" }, { "code": null, "e": 2473, "s": 1808, "text": "> summary(fit)Call:lm(formula = Murder ~ Population + Illiteracy + Income + Frost, data = states)Residuals: Min 1Q Median 3Q Max -4.7960 -1.6495 -0.0811 1.4815 7.6210Coefficients: Estimate Std. Error t value Pr(>|t|) (Intercept) 1.235e+00 3.866e+00 0.319 0.7510 Population 2.237e-04 9.052e-05 2.471 0.0173 * Illiteracy 4.143e+00 8.744e-01 4.738 2.19e-05 ***Income 6.442e-05 6.837e-04 0.094 0.9253 Frost 5.813e-04 1.005e-02 0.058 0.9541 — -Signif. codes: 0 ‘***’ 0.001 ‘**’ 0.01 ‘*’ 0.05 ‘.’ 0.1 ‘ ’ 1Residual standard error: 2.535 on 45 degrees of freedomMultiple R-squared: 0.567, Adjusted R-squared: 0.5285 F-statistic: 14.73 on 4 and 45 DF, p-value: 9.133e-08" }, { "code": null, "e": 2482, "s": 2473, "text": "Outliers" }, { "code": null, "e": 2830, "s": 2482, "text": "Outliers observations aren’t predicted well by regression model. They either have extremely large positive or negative residuals. If the model is underestimating the response value, then it will be indicated by positive residual. On the other hand, if the model is overestimating the response value, then it will be indicated by negative residual." }, { "code": null, "e": 3100, "s": 2830, "text": "From our regression model example, we can start investigating outliers observation by using Q-Q plot. Code below helps you to plot and find potential outliers. Nevada (28th observation) and Rhode Island (39th observation) are states that detected as potential outliers." }, { "code": null, "e": 3237, "s": 3100, "text": "> qqPlot(fit,labels=row.names(states), id.method=”identify”, simulate=TRUE, main=”Q-Q Plot”) Nevada Rhode Island 28 39" }, { "code": null, "e": 3435, "s": 3237, "text": "Applying outlierTest function is helping us to confirm if potential outliers are indeed outliers. The statistical test is showing that Nevada undeniably detected as an outlier with p-value = 0.048." }, { "code": null, "e": 3548, "s": 3435, "text": "> outlierTest(fit) rstudent unadjusted p-value Bonferroni pNevada 3.542929 0.00095088 0.047544" }, { "code": null, "e": 3851, "s": 3548, "text": "Q-Q plot also confirms that Nevada has a large positive residual. It means our model underestimates the murder rate in this state. You can spot that the murder rate in Nevada is 11.5% while the model only predicts at 3.9%. We clearly understand that Nevada is indeed different compared to other states." }, { "code": null, "e": 4007, "s": 3851, "text": "> states[“Nevada”,] Murder Population Illiteracy Income FrostNevada 11.5 590 0.5 5149 188> fitted(fit)[“Nevada”] Nevada 3.878958" }, { "code": null, "e": 4270, "s": 4007, "text": "Therefore, you can remove this observation and re-run the test to see if other outliers are present. As an analyst, you might want to know why Nevada has a high murder rate. Perhaps you can ask post this question to Quora and let me know if you have the answer 😉" }, { "code": null, "e": 4291, "s": 4270, "text": "High-leverage points" }, { "code": null, "e": 4551, "s": 4291, "text": "Observations will be considered as high-leverage points if they resemble outliers when we compared it to other predictors. Strictly speaking, they have uncommon combination of predictor values while the response value has minor impact on determining leverage." }, { "code": null, "e": 4896, "s": 4551, "text": "You can compute the high leverage observation by looking at the ratio of number of parameters estimated in model and sample size. If an observation has a ratio greater than 2 -3 times the average ratio, then the observation considers as high-leverage points. I personally like to use this simple function to identify high-leverage observations." }, { "code": null, "e": 5157, "s": 4896, "text": "highleverage <- function(fit) { p <- length(coefficients(fit)) n <- length(fitted(fit)) ratio <-p/n plot(hatvalues(fit), main=”Index Plot of Ratio”) abline(h=c(2,3)*ratio, col=”red”, lty=2) identify(1:n, hatvalues(fit), names(hatvalues(fit)))}highleverage(fit)" }, { "code": null, "e": 5355, "s": 5157, "text": "The graph above indicates that Alaska and California have the highest ratio. It means these two states are quite unusual if we compared their predictor values compared to other states. Here is why:" }, { "code": null, "e": 5486, "s": 5355, "text": "· For Alaska, this state has a much higher income compared to other states, while having smaller population and lower temperature." }, { "code": null, "e": 5614, "s": 5486, "text": "· For California, this state has much a bigger population than other states, while having higher income and higher temperature." }, { "code": null, "e": 5832, "s": 5614, "text": "Both of these states are indeed quite particular compared to the other 48 states. One thing to remember that not all high-leverage observations are influential observations. It will depend if they are outliers or not." }, { "code": null, "e": 5857, "s": 5832, "text": "Influential Observations" }, { "code": null, "e": 6219, "s": 5857, "text": "Observations with a disproportionate impact on the values of the model parameters can be considered as Influential observations. For instance, if you drop a single observation, then it change your model dramatically. That single observation must be influential observation. Thus, it is important for us to inspect if our data contains influential points or not." }, { "code": null, "e": 6307, "s": 6219, "text": "In my experience, there are two effective methods to identify influential observations:" }, { "code": null, "e": 6326, "s": 6307, "text": "1. Cook’s distance" }, { "code": null, "e": 6622, "s": 6326, "text": "Code below provide a way to calculate the cut-off and plot Cook’s distance for each of our observation. The plot shows Alaska, Hawaii, and Nevada as influential observations. Removing these 3 states will have a significant impact on the values of the intercept and slope in our regression model." }, { "code": null, "e": 6748, "s": 6622, "text": "cutoff <- 4/(nrow(states)-length(fit$coefficients)-2)plot(fit, which=4, cook.levels=cutoff)abline(h=cutoff, lty=2, col=”red”)" }, { "code": null, "e": 7010, "s": 6748, "text": "I need to highlight that the plot above is indeed helpful to identify influential observations, but it doesn’t give extra information about how these observations affect the model. That’s why Added Variable plots can be an option for us to dig more information." }, { "code": null, "e": 7034, "s": 7010, "text": "2. Added Variable plots" }, { "code": null, "e": 7219, "s": 7034, "text": "Added variable plots works by plotting each predictor variable against the response variable and other predictors. It can be easily created using the avPlots() function in car package." }, { "code": null, "e": 7278, "s": 7219, "text": "library(car) avPlots(fit, ask=FALSE, id.method=”identify”)" }, { "code": null, "e": 7544, "s": 7278, "text": "From the graph below, the straight line in each plot is the actual regression coefficient for that predictor variable. We might view the impact of influential observations by imagining how the line would alter if the point representing that observation was removed." }, { "code": null, "e": 7781, "s": 7544, "text": "Now, we will incorporate all information from outlier, high-leverage, and influential observations into a single informative plot. I personally find influencePlot() is a very handy function to represent these unusual observation issues." }, { "code": null, "e": 7912, "s": 7781, "text": "library(car) influencePlot(fit, id.method=”identify”, main=”Influence Plot”, sub=”Circle size is proportional to Cook’s distance”)" }, { "code": null, "e": 7983, "s": 7912, "text": "The graph above summarises our final verdict conveniently. Here it is:" }, { "code": null, "e": 8023, "s": 7983, "text": "· Nevada and Rhode island are Outliers." }, { "code": null, "e": 8101, "s": 8023, "text": "· California, Washington, New York, and Hawaii are High-Leverage Observations" }, { "code": null, "e": 8141, "s": 8101, "text": "· Alaska is the Influential Observation" } ]
What are the properties of Regular expressions in TOC?
A regular expression is basically a shorthand way of showing how a regular language is built from the base set of regular languages. The symbols are identical which are used to construct the languages, and any given expression that has a language closely associated with it. For each regular expression E, there is a regular language L(E). There are some general equalities for the regular expressions. Properties All the properties held for any regular expressions R, E, F and can be verified by using properties of languages and sets. Additive (+) properties The additive properties of regular expressions are as follows − R + E = E + R R + ∅ = ∅ + R = R R + R = R (R + E) + F = R + (E + F) Product (·) properties The product properties of regular expressions are as follows − R∅ = ∅R = ∅ R∧ = ∧R = R (RE)F = R(EF) Distributive properties The distributive properties of regular expressions are as follows − R(E + F) = RE + RF (R + E)F = RF + EF Closure properties The closure properties of regular expressions are as follows − ∅* = ∧ * = ∧ R* = R*R* = (R*)* = R + R* R* = ∧ + RR* = (∧ + R)R* RR* = R*R R(ER)* = (RE)*R (R + E)* = (R*E*)* = (R* + E*)* = R*(ER*)* All the properties can be verified by using the properties of languages and sets. Example 1 Show that (∅ + a + b)* = a*(ba*)* Using the properties above: (∅ + a + b)* = (a + b)* (+ property) = a*(ba*)* (closure property). Example 2 Show that ∧ + ab + abab(ab)* = (ab)* Using the properties above: ∧ + ab + abab(ab)* = ∧ + ab(∧ + ab(ab)*) = ∧ + ab((ab)*) (using R* = ∧ + RR*) = ∧ + ab(ab)*= (ab)* (using R* = ∧ + RR* again)
[ { "code": null, "e": 1195, "s": 1062, "text": "A regular expression is basically a shorthand way of showing how a regular language is built from the base set of regular languages." }, { "code": null, "e": 1337, "s": 1195, "text": "The symbols are identical which are used to construct the languages, and any given expression that has a language closely associated with it." }, { "code": null, "e": 1402, "s": 1337, "text": "For each regular expression E, there is a regular language L(E)." }, { "code": null, "e": 1465, "s": 1402, "text": "There are some general equalities for the regular expressions." }, { "code": null, "e": 1476, "s": 1465, "text": "Properties" }, { "code": null, "e": 1599, "s": 1476, "text": "All the properties held for any regular expressions R, E, F and can be verified by using properties of languages and sets." }, { "code": null, "e": 1623, "s": 1599, "text": "Additive (+) properties" }, { "code": null, "e": 1687, "s": 1623, "text": "The additive properties of regular expressions are as follows −" }, { "code": null, "e": 1755, "s": 1687, "text": "R + E = E + R\nR + ∅ = ∅ + R = R\nR + R = R\n(R + E) + F = R + (E + F)" }, { "code": null, "e": 1778, "s": 1755, "text": "Product (·) properties" }, { "code": null, "e": 1841, "s": 1778, "text": "The product properties of regular expressions are as follows −" }, { "code": null, "e": 1879, "s": 1841, "text": "R∅ = ∅R = ∅\nR∧ = ∧R = R\n(RE)F = R(EF)" }, { "code": null, "e": 1903, "s": 1879, "text": "Distributive properties" }, { "code": null, "e": 1971, "s": 1903, "text": "The distributive properties of regular expressions are as follows −" }, { "code": null, "e": 2009, "s": 1971, "text": "R(E + F) = RE + RF\n(R + E)F = RF + EF" }, { "code": null, "e": 2028, "s": 2009, "text": "Closure properties" }, { "code": null, "e": 2091, "s": 2028, "text": "The closure properties of regular expressions are as follows −" }, { "code": null, "e": 2225, "s": 2091, "text": "∅* = ∧ * = ∧\nR* = R*R* = (R*)* = R + R*\nR* = ∧ + RR* = (∧ + R)R*\nRR* = R*R\nR(ER)* = (RE)*R\n(R + E)* = (R*E*)* = (R* + E*)* = R*(ER*)*" }, { "code": null, "e": 2307, "s": 2225, "text": "All the properties can be verified by using the properties of languages and sets." }, { "code": null, "e": 2317, "s": 2307, "text": "Example 1" }, { "code": null, "e": 2327, "s": 2317, "text": "Show that" }, { "code": null, "e": 2351, "s": 2327, "text": "(∅ + a + b)* = a*(ba*)*" }, { "code": null, "e": 2447, "s": 2351, "text": "Using the properties above:\n(∅ + a + b)* = (a + b)* (+ property)\n= a*(ba*)* (closure property)." }, { "code": null, "e": 2457, "s": 2447, "text": "Example 2" }, { "code": null, "e": 2467, "s": 2457, "text": "Show that" }, { "code": null, "e": 2494, "s": 2467, "text": "∧ + ab + abab(ab)* = (ab)*" }, { "code": null, "e": 2666, "s": 2494, "text": "Using the properties above:\n∧ + ab + abab(ab)* = ∧ + ab(∧ + ab(ab)*)\n = ∧ + ab((ab)*) (using R* = ∧ + RR*)\n= ∧ + ab(ab)*= (ab)* (using R* = ∧ + RR* again)" } ]
C# | Copy StringCollection at the specified index of array - GeeksforGeeks
01 Feb, 2019 StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace. StringCollection.CopyTo(String[], Int32) method is used to copy the entire StringCollection values to a one-dimensional array of strings which starts at the specified index of the target array. Syntax: public void CopyTo (string[] array, int index); Parameters: array : It is the one-dimensional array of strings that is the destination of the elements copied from StringCollection. The Array must have zero-based indexing. index : It is the zero-based index in array at which copying begins. Exceptions: ArgumentNullException : If the array is null. ArgumentOutOfRangeException : If the index is less than zero. InvalidCastException : If the type of the source StringCollection cannot be cast automatically to the type of the destination array. ArgumentException : If the array is multidimensional or the number of elements in the source StringCollection is greater than the available space from index to the end of the destination array. Note: The specified array must be of a compatible type. This method is an O(n) operation, where n is Count. Below given are some examples to understand the implementation in a better way: Example 1: // C# code to copy StringCollection to array,// starting at the specified index of// the target arrayusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr1 String[] myArr1 = new String[] { "A", "B", "C", "D", "E" }; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr1); // creating a String array named myArr2 String[] myArr2 = new String[myCol.Count]; // Copying StringCollection to array myArr2 // starting from index 0 myCol.CopyTo(myArr2, 0); // Displaying elements in array myArr2 for (int i = 0; i < myArr2.Length; i++) { Console.WriteLine(myArr2[i]); } }} Output: A B C D E Example 2: // C# code to copy StringCollection to array,// starting at the specified index of// the target arrayusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr1 String[] myArr1 = new String[] {"1", "2", "3", "4", "5", "6"}; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr1); // creating a String array named myArr2 String[] myArr2 = new String[myCol.Count]; // Copying StringCollection to array myArr2 // starting from index -1 // This should raise exception "ArgumentOutOfRangeException" // as index is less than 0 myCol.CopyTo(myArr2, -1); // Displaying elements in array myArr2 for (int i = 0; i < myArr2.Length; i++) { Console.WriteLine(myArr2[i]); } }} Output: Unhandled Exception:System.ArgumentOutOfRangeException: Value has to be >= 0.Parameter name: destinationIndex Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringcollection.copyto?view=netframework-4.7.2 CSharp-Collections-Namespace CSharp-method CSharp-Specialized-Namespace CSharp-Specialized-StringCollection 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": 24112, "s": 23911, "text": "StringCollection class is a new addition to the .NET Framework class library that represents a collection of strings. StringCollection class is defined in the System.Collections.Specialized namespace." }, { "code": null, "e": 24306, "s": 24112, "text": "StringCollection.CopyTo(String[], Int32) method is used to copy the entire StringCollection values to a one-dimensional array of strings which starts at the specified index of the target array." }, { "code": null, "e": 24314, "s": 24306, "text": "Syntax:" }, { "code": null, "e": 24363, "s": 24314, "text": "public void CopyTo (string[] array, int index);\n" }, { "code": null, "e": 24375, "s": 24363, "text": "Parameters:" }, { "code": null, "e": 24537, "s": 24375, "text": "array : It is the one-dimensional array of strings that is the destination of the elements copied from StringCollection. The Array must have zero-based indexing." }, { "code": null, "e": 24606, "s": 24537, "text": "index : It is the zero-based index in array at which copying begins." }, { "code": null, "e": 24618, "s": 24606, "text": "Exceptions:" }, { "code": null, "e": 24664, "s": 24618, "text": "ArgumentNullException : If the array is null." }, { "code": null, "e": 24726, "s": 24664, "text": "ArgumentOutOfRangeException : If the index is less than zero." }, { "code": null, "e": 24859, "s": 24726, "text": "InvalidCastException : If the type of the source StringCollection cannot be cast automatically to the type of the destination array." }, { "code": null, "e": 25053, "s": 24859, "text": "ArgumentException : If the array is multidimensional or the number of elements in the source StringCollection is greater than the available space from index to the end of the destination array." }, { "code": null, "e": 25059, "s": 25053, "text": "Note:" }, { "code": null, "e": 25109, "s": 25059, "text": "The specified array must be of a compatible type." }, { "code": null, "e": 25161, "s": 25109, "text": "This method is an O(n) operation, where n is Count." }, { "code": null, "e": 25241, "s": 25161, "text": "Below given are some examples to understand the implementation in a better way:" }, { "code": null, "e": 25252, "s": 25241, "text": "Example 1:" }, { "code": "// C# code to copy StringCollection to array,// starting at the specified index of// the target arrayusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr1 String[] myArr1 = new String[] { \"A\", \"B\", \"C\", \"D\", \"E\" }; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr1); // creating a String array named myArr2 String[] myArr2 = new String[myCol.Count]; // Copying StringCollection to array myArr2 // starting from index 0 myCol.CopyTo(myArr2, 0); // Displaying elements in array myArr2 for (int i = 0; i < myArr2.Length; i++) { Console.WriteLine(myArr2[i]); } }}", "e": 26217, "s": 25252, "text": null }, { "code": null, "e": 26225, "s": 26217, "text": "Output:" }, { "code": null, "e": 26236, "s": 26225, "text": "A\nB\nC\nD\nE\n" }, { "code": null, "e": 26247, "s": 26236, "text": "Example 2:" }, { "code": "// C# code to copy StringCollection to array,// starting at the specified index of// the target arrayusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // creating a StringCollection named myCol StringCollection myCol = new StringCollection(); // creating a string array named myArr1 String[] myArr1 = new String[] {\"1\", \"2\", \"3\", \"4\", \"5\", \"6\"}; // Copying the elements of a string // array to the end of the StringCollection. myCol.AddRange(myArr1); // creating a String array named myArr2 String[] myArr2 = new String[myCol.Count]; // Copying StringCollection to array myArr2 // starting from index -1 // This should raise exception \"ArgumentOutOfRangeException\" // as index is less than 0 myCol.CopyTo(myArr2, -1); // Displaying elements in array myArr2 for (int i = 0; i < myArr2.Length; i++) { Console.WriteLine(myArr2[i]); } }}", "e": 27357, "s": 26247, "text": null }, { "code": null, "e": 27365, "s": 27357, "text": "Output:" }, { "code": null, "e": 27475, "s": 27365, "text": "Unhandled Exception:System.ArgumentOutOfRangeException: Value has to be >= 0.Parameter name: destinationIndex" }, { "code": null, "e": 27486, "s": 27475, "text": "Reference:" }, { "code": null, "e": 27609, "s": 27486, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.stringcollection.copyto?view=netframework-4.7.2" }, { "code": null, "e": 27638, "s": 27609, "text": "CSharp-Collections-Namespace" }, { "code": null, "e": 27652, "s": 27638, "text": "CSharp-method" }, { "code": null, "e": 27681, "s": 27652, "text": "CSharp-Specialized-Namespace" }, { "code": null, "e": 27717, "s": 27681, "text": "CSharp-Specialized-StringCollection" }, { "code": null, "e": 27720, "s": 27717, "text": "C#" }, { "code": null, "e": 27818, "s": 27720, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27827, "s": 27818, "text": "Comments" }, { "code": null, "e": 27840, "s": 27827, "text": "Old Comments" }, { "code": null, "e": 27880, "s": 27840, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 27903, "s": 27880, "text": "Extension Method in C#" }, { "code": null, "e": 27931, "s": 27903, "text": "HashSet in C# with Examples" }, { "code": null, "e": 27953, "s": 27931, "text": "Partial Classes in C#" }, { "code": null, "e": 27970, "s": 27953, "text": "C# | Inheritance" }, { "code": null, "e": 28010, "s": 27970, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 28043, "s": 28010, "text": "Linked List Implementation in C#" }, { "code": null, "e": 28086, "s": 28043, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 28102, "s": 28086, "text": "C# | List Class" } ]
Convert Character value to ASCII value in R Programming - charToRaw() Function - GeeksforGeeks
02 Mar, 2021 charToRaw() function in R Language is used to convert the given character to their corresponding ASCII value or “raw” objects. Syntax: charToRaw(x)Parameters: x: Given characters to be converted Example 1: Python3 # R program to illustrate# charToRaw function # Calling charToRaw() function over# some alphabetsx <- charToRaw("a")y <- charToRaw("A")z <- charToRaw("ab") # Getting the corresponding ASCII valuexyz Output : [1] 61 [1] 41 [1] 61 62 Example 2: Python3 # R program to illustrate# charToRaw function # Initializing some stringsa <- "Geeks"b <- "GFG is a CS Portal" # Calling charToRaw() function# over above stringsc <- charToRaw(a)d <- charToRaw(b) # Getting the ASCII values of the above# specified stringscd Output: [1] 47 65 65 6b 73 [1] 47 46 47 20 69 73 20 61 20 43 53 20 50 6f 72 74 61 6c arorakashish0911 R String-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? How to change Row Names of DataFrame in R ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R Printing Output of an R Program How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? K-Means Clustering in R Programming
[ { "code": null, "e": 24455, "s": 24427, "text": "\n02 Mar, 2021" }, { "code": null, "e": 24583, "s": 24455, "text": "charToRaw() function in R Language is used to convert the given character to their corresponding ASCII value or “raw” objects. " }, { "code": null, "e": 24653, "s": 24583, "text": "Syntax: charToRaw(x)Parameters: x: Given characters to be converted " }, { "code": null, "e": 24666, "s": 24653, "text": "Example 1: " }, { "code": null, "e": 24674, "s": 24666, "text": "Python3" }, { "code": "# R program to illustrate# charToRaw function # Calling charToRaw() function over# some alphabetsx <- charToRaw(\"a\")y <- charToRaw(\"A\")z <- charToRaw(\"ab\") # Getting the corresponding ASCII valuexyz", "e": 24873, "s": 24674, "text": null }, { "code": null, "e": 24884, "s": 24873, "text": "Output : " }, { "code": null, "e": 24908, "s": 24884, "text": "[1] 61\n[1] 41\n[1] 61 62" }, { "code": null, "e": 24921, "s": 24908, "text": "Example 2: " }, { "code": null, "e": 24929, "s": 24921, "text": "Python3" }, { "code": "# R program to illustrate# charToRaw function # Initializing some stringsa <- \"Geeks\"b <- \"GFG is a CS Portal\" # Calling charToRaw() function# over above stringsc <- charToRaw(a)d <- charToRaw(b) # Getting the ASCII values of the above# specified stringscd", "e": 25186, "s": 24929, "text": null }, { "code": null, "e": 25196, "s": 25186, "text": "Output: " }, { "code": null, "e": 25273, "s": 25196, "text": "[1] 47 65 65 6b 73\n[1] 47 46 47 20 69 73 20 61 20 43 53 20 50 6f 72 74 61 6c" }, { "code": null, "e": 25292, "s": 25275, "text": "arorakashish0911" }, { "code": null, "e": 25311, "s": 25292, "text": "R String-Functions" }, { "code": null, "e": 25322, "s": 25311, "text": "R Language" }, { "code": null, "e": 25420, "s": 25322, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25429, "s": 25420, "text": "Comments" }, { "code": null, "e": 25442, "s": 25429, "text": "Old Comments" }, { "code": null, "e": 25500, "s": 25442, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 25544, "s": 25500, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 25596, "s": 25544, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 25628, "s": 25596, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 25680, "s": 25628, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25712, "s": 25680, "text": "Printing Output of an R Program" }, { "code": null, "e": 25750, "s": 25712, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25785, "s": 25750, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 25843, "s": 25785, "text": "How to Split Column Into Multiple Columns in R DataFrame?" } ]
How to show/hide div element depending multiple values using Bootstrap and jQuery ? - GeeksforGeeks
03 Aug, 2021 Bootstrap and jQuery have been used together to develop interactive web applications. Both Bootstrap and jQuery are free and open source which makes it popular among developers. This article deals with showing and hiding division depending on user input with the help of Bootstrap and jQuery. Below shown are two approaches to establish the same. First Approach: In the first method, only one division is visible at a time depending on the input from the user. This method comprises a drop down list with three options. The user can select one option at a time and depending on the value of the option the corresponding division is displayed. The method used in the code snippet are as follows: $(document).ready(function): The ready event is triggered when the document is loaded and the function passed as parameter is executed. $(selector).change(function): The change event is triggered when the selected element (input, textarea or select) has been changed and the function passed as a parameter is executed. Here the function passed as parameter is invoked when the user selects an option from the drop down menu. $(selector).find(filter): This method returns all the descendant elements of the selected element. Here <option> is the descendant of <select>. Also, the method requires a filter to return the required element. Here the selected option is the filter ie the option selected by the user is returned. $(selector).each(function): This method executed the function passed as parameter for each matched element. Here the function passed as parameter executes for each element returned by the find() method. $(selector).attr(attribute): This method set or return attributes and values of the selected elements respectively. Here the value of the selected option is extracted into the optionValue variable. $(selector).not(criteria): This method returns elements that do not match the specified criteria. Here the not method returns the options that are not selected by the users. $(selector).hide(): This method hides the selected element. $(selector).show(): This method shows the selected element. Explanation: The page displays a drop down menu from which the user selects an option. As soon as a change occurs in the <select> element, the change() method is triggered which in turn invokes the find function and it returns the selected option. The attr() method extracts the value of the option into the optionValue variable. The optionValue variable is appended with ‘.’ (which turns it into one among the defined division classes) in the not() method. The not() method hides all the classes that do not match the class mentioned in the criteria. The show() method finally displays the division as selected by the user. If no option is selected by the user then all the divisions are hidden. html <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title>Show Hide Elements Using Dropdown</title> <!--CSS stylesheet--> <style> .box { color: #fff; padding: 20px; display: none; margin-top: 20px; } .red { background: red; } .green { background: green; } .blue { background: blue; } </style> <!--importing jquery cdn--> <script src="https://code.jquery.com/jquery-1.12.4.min.js"> </script> <script> // jQuery functions to hide and show the div $(document).ready(function () { $("select").change(function () { $(this).find("option:selected") .each(function () { var optionValue = $(this).attr("value"); if (optionValue) { $(".box").not("." + optionValue).hide(); $("." + optionValue).show(); } else { $(".box").hide(); } }); }).change(); }); </script></head> <body> <div> <!--dropdown list options--> <select> <option>Choose Color</option> <option value="red">Red</option> <option value="green">Green</option> <option value="blue">Blue</option> </select> </div> <!--divs that hide and show--> <div class="red box">Red Selected</div> <div class="green box">Green Selected</div> <div class="blue box">Blue Selected</div></body> </html> Output: Second Approach: This approach demonstrates how one or more divisions can be displayed simultaneously. This method makes use of checkboxes for taking user input. As check boxes are capable of taking more than one value at a time hence it is an ideal choice to serve our purpose. The following methods are used in the code: $(document).ready(function): The ready event is triggered when the document is loaded and the function passed as parameter is executed. $(selector).click(function): This method triggers the click event or executes a function when a click event occurs. Here as the user checks the checkbox the click event is triggered and the function passed as parameter is executed. $(selector).attr(attribute): This method returns the values of the selected elements. Here the value of the selected option is extracted into the inputValue variable. $(selector).toggle(): This method toggles between hide() method and show() method for the selected elements. If the box is checked the division is shown. If the box is unchecked the division is hidden. Explanation: The webpage comprises certain checkboxes. The user may select one or more than one check boxes at a time. The divisions corresponding to the checkboxes are shown if they were hidden initially. If the checkboxes are unchecked then the corresponding division is hidden. html <!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"> <title>Show Hide Elements Using Checkboxes</title> <!--CSS stylesheet--> <style> .box { color: #fff; padding: 20px; display: none; margin-top: 20px; } .red { background: red; } .green { background: green; } .blue { background: blue; } label { margin-right: 15px; } </style> <!--import jQuery cdn--> <script src= "https://code.jquery.com/jquery-1.12.4.min.js"> </script> <script> // jQuery functions to show and hide divisions $(document).ready(function () { $('input[type="checkbox"]').click(function () { var inputValue = $(this).attr("value"); $("." + inputValue).toggle(); }); }); </script></head> <body> <div> <!--checkboxes--> <label><input type="checkbox" name="colorCheckbox" value="red"> red </label> <label><input type="checkbox" name="colorCheckbox" value="green"> green </label> <label><input type="checkbox" name="colorCheckbox" value="blue"> blue </label> </div> <!--Divisions to be shown and hidden--> <div class="red box">Red Selected</div> <div class="green box">Green Selected</div> <div class="blue box">Blue Selected</div></body> </html> Output jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. Bootstrap-Misc HTML-Misc jQuery-Misc Picked Bootstrap HTML JavaScript JQuery Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? Tailwind CSS vs Bootstrap How to keep gap between columns using Bootstrap? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to set the default value for an HTML <select> element ? How to update Node.js and NPM to next version ? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 25290, "s": 25262, "text": "\n03 Aug, 2021" }, { "code": null, "e": 25638, "s": 25290, "text": "Bootstrap and jQuery have been used together to develop interactive web applications. Both Bootstrap and jQuery are free and open source which makes it popular among developers. This article deals with showing and hiding division depending on user input with the help of Bootstrap and jQuery. Below shown are two approaches to establish the same. " }, { "code": null, "e": 25987, "s": 25638, "text": "First Approach: In the first method, only one division is visible at a time depending on the input from the user. This method comprises a drop down list with three options. The user can select one option at a time and depending on the value of the option the corresponding division is displayed. The method used in the code snippet are as follows: " }, { "code": null, "e": 26123, "s": 25987, "text": "$(document).ready(function): The ready event is triggered when the document is loaded and the function passed as parameter is executed." }, { "code": null, "e": 26412, "s": 26123, "text": "$(selector).change(function): The change event is triggered when the selected element (input, textarea or select) has been changed and the function passed as a parameter is executed. Here the function passed as parameter is invoked when the user selects an option from the drop down menu." }, { "code": null, "e": 26710, "s": 26412, "text": "$(selector).find(filter): This method returns all the descendant elements of the selected element. Here <option> is the descendant of <select>. Also, the method requires a filter to return the required element. Here the selected option is the filter ie the option selected by the user is returned." }, { "code": null, "e": 26913, "s": 26710, "text": "$(selector).each(function): This method executed the function passed as parameter for each matched element. Here the function passed as parameter executes for each element returned by the find() method." }, { "code": null, "e": 27111, "s": 26913, "text": "$(selector).attr(attribute): This method set or return attributes and values of the selected elements respectively. Here the value of the selected option is extracted into the optionValue variable." }, { "code": null, "e": 27285, "s": 27111, "text": "$(selector).not(criteria): This method returns elements that do not match the specified criteria. Here the not method returns the options that are not selected by the users." }, { "code": null, "e": 27345, "s": 27285, "text": "$(selector).hide(): This method hides the selected element." }, { "code": null, "e": 27405, "s": 27345, "text": "$(selector).show(): This method shows the selected element." }, { "code": null, "e": 28104, "s": 27405, "text": "Explanation: The page displays a drop down menu from which the user selects an option. As soon as a change occurs in the <select> element, the change() method is triggered which in turn invokes the find function and it returns the selected option. The attr() method extracts the value of the option into the optionValue variable. The optionValue variable is appended with ‘.’ (which turns it into one among the defined division classes) in the not() method. The not() method hides all the classes that do not match the class mentioned in the criteria. The show() method finally displays the division as selected by the user. If no option is selected by the user then all the divisions are hidden. " }, { "code": null, "e": 28109, "s": 28104, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <title>Show Hide Elements Using Dropdown</title> <!--CSS stylesheet--> <style> .box { color: #fff; padding: 20px; display: none; margin-top: 20px; } .red { background: red; } .green { background: green; } .blue { background: blue; } </style> <!--importing jquery cdn--> <script src=\"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <script> // jQuery functions to hide and show the div $(document).ready(function () { $(\"select\").change(function () { $(this).find(\"option:selected\") .each(function () { var optionValue = $(this).attr(\"value\"); if (optionValue) { $(\".box\").not(\".\" + optionValue).hide(); $(\".\" + optionValue).show(); } else { $(\".box\").hide(); } }); }).change(); }); </script></head> <body> <div> <!--dropdown list options--> <select> <option>Choose Color</option> <option value=\"red\">Red</option> <option value=\"green\">Green</option> <option value=\"blue\">Blue</option> </select> </div> <!--divs that hide and show--> <div class=\"red box\">Red Selected</div> <div class=\"green box\">Green Selected</div> <div class=\"blue box\">Blue Selected</div></body> </html>", "e": 29753, "s": 28109, "text": null }, { "code": null, "e": 29762, "s": 29753, "text": "Output: " }, { "code": null, "e": 30088, "s": 29764, "text": "Second Approach: This approach demonstrates how one or more divisions can be displayed simultaneously. This method makes use of checkboxes for taking user input. As check boxes are capable of taking more than one value at a time hence it is an ideal choice to serve our purpose. The following methods are used in the code: " }, { "code": null, "e": 30224, "s": 30088, "text": "$(document).ready(function): The ready event is triggered when the document is loaded and the function passed as parameter is executed." }, { "code": null, "e": 30456, "s": 30224, "text": "$(selector).click(function): This method triggers the click event or executes a function when a click event occurs. Here as the user checks the checkbox the click event is triggered and the function passed as parameter is executed." }, { "code": null, "e": 30623, "s": 30456, "text": "$(selector).attr(attribute): This method returns the values of the selected elements. Here the value of the selected option is extracted into the inputValue variable." }, { "code": null, "e": 30825, "s": 30623, "text": "$(selector).toggle(): This method toggles between hide() method and show() method for the selected elements. If the box is checked the division is shown. If the box is unchecked the division is hidden." }, { "code": null, "e": 31108, "s": 30825, "text": "Explanation: The webpage comprises certain checkboxes. The user may select one or more than one check boxes at a time. The divisions corresponding to the checkboxes are shown if they were hidden initially. If the checkboxes are unchecked then the corresponding division is hidden. " }, { "code": null, "e": 31113, "s": 31108, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <title>Show Hide Elements Using Checkboxes</title> <!--CSS stylesheet--> <style> .box { color: #fff; padding: 20px; display: none; margin-top: 20px; } .red { background: red; } .green { background: green; } .blue { background: blue; } label { margin-right: 15px; } </style> <!--import jQuery cdn--> <script src= \"https://code.jquery.com/jquery-1.12.4.min.js\"> </script> <script> // jQuery functions to show and hide divisions $(document).ready(function () { $('input[type=\"checkbox\"]').click(function () { var inputValue = $(this).attr(\"value\"); $(\".\" + inputValue).toggle(); }); }); </script></head> <body> <div> <!--checkboxes--> <label><input type=\"checkbox\" name=\"colorCheckbox\" value=\"red\"> red </label> <label><input type=\"checkbox\" name=\"colorCheckbox\" value=\"green\"> green </label> <label><input type=\"checkbox\" name=\"colorCheckbox\" value=\"blue\"> blue </label> </div> <!--Divisions to be shown and hidden--> <div class=\"red box\">Red Selected</div> <div class=\"green box\">Green Selected</div> <div class=\"blue box\">Blue Selected</div></body> </html>", "e": 32665, "s": 31113, "text": null }, { "code": null, "e": 32673, "s": 32665, "text": "Output " }, { "code": null, "e": 32945, "s": 32677, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 32960, "s": 32945, "text": "Bootstrap-Misc" }, { "code": null, "e": 32970, "s": 32960, "text": "HTML-Misc" }, { "code": null, "e": 32982, "s": 32970, "text": "jQuery-Misc" }, { "code": null, "e": 32989, "s": 32982, "text": "Picked" }, { "code": null, "e": 32999, "s": 32989, "text": "Bootstrap" }, { "code": null, "e": 33004, "s": 32999, "text": "HTML" }, { "code": null, "e": 33015, "s": 33004, "text": "JavaScript" }, { "code": null, "e": 33022, "s": 33015, "text": "JQuery" }, { "code": null, "e": 33039, "s": 33022, "text": "Web Technologies" }, { "code": null, "e": 33066, "s": 33039, "text": "Web technologies Questions" }, { "code": null, "e": 33071, "s": 33066, "text": "HTML" }, { "code": null, "e": 33169, "s": 33071, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33178, "s": 33169, "text": "Comments" }, { "code": null, "e": 33191, "s": 33178, "text": "Old Comments" }, { "code": null, "e": 33232, "s": 33191, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 33295, "s": 33232, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 33328, "s": 33295, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 33354, "s": 33328, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 33403, "s": 33354, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 33465, "s": 33403, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 33515, "s": 33465, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33575, "s": 33515, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 33623, "s": 33575, "text": "How to update Node.js and NPM to next version ?" } ]
JSF - Validator Tags
JSF provides inbuilt validators to validate its UI components. These tags can validate the length of the field, the type of input which can be a custom object. For these tags you need to use the following namespaces of URI in html node. <html xmlns = "http://www.w3.org/1999/xhtml" xmlns:f = "http://java.sun.com/jsf/core"> Following are important Validator Tags in JSF 2.0− Validates the length of a string Validates the range of a numeric value Validates the range of a float value Validates JSF component with a given regular expression Creates a custom validator 37 Lectures 3.5 hours Chaand Sheikh Print Add Notes Bookmark this page
[ { "code": null, "e": 2112, "s": 1952, "text": "JSF provides inbuilt validators to validate its UI components. These tags can validate the length of the field, the type of input which can be a custom object." }, { "code": null, "e": 2189, "s": 2112, "text": "For these tags you need to use the following namespaces of URI in html node." }, { "code": null, "e": 2285, "s": 2189, "text": "<html \n xmlns = \"http://www.w3.org/1999/xhtml\" \n xmlns:f = \"http://java.sun.com/jsf/core\">\n" }, { "code": null, "e": 2336, "s": 2285, "text": "Following are important Validator Tags in JSF 2.0−" }, { "code": null, "e": 2369, "s": 2336, "text": "Validates the length of a string" }, { "code": null, "e": 2408, "s": 2369, "text": "Validates the range of a numeric value" }, { "code": null, "e": 2445, "s": 2408, "text": "Validates the range of a float value" }, { "code": null, "e": 2501, "s": 2445, "text": "Validates JSF component with a given regular expression" }, { "code": null, "e": 2528, "s": 2501, "text": "Creates a custom validator" }, { "code": null, "e": 2563, "s": 2528, "text": "\n 37 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2578, "s": 2563, "text": " Chaand Sheikh" }, { "code": null, "e": 2585, "s": 2578, "text": " Print" }, { "code": null, "e": 2596, "s": 2585, "text": " Add Notes" } ]
Using Tables in HANA DB
SAP HANA is an in-memory database that supports all the features of a conventional database. You can perform all DDL, DML, and DCL statements on database objects. Users can create new tables, views, functions, triggers, and all other database functions using HANA Studio front-end. Tables in HANA database can be accessed from HANA Studio in Catalogue tab under Schemas. New tables can be created using the following two methods − Using SQL editor Using GUI option All the database objects - tables, views, and other objects can be used to design a Universe - Data Foundation layer and later to publish Business Layer to BO repository for BI reporting. In SAP HANA Studio, open SQL editor by selecting the Schema name and click the circled option in the following screenshot. You can run all SQL queries in SQL editor, which are required to perform conventional database functions. You can create new tables, views by writing the CREATE command in the editor window or right-click the Schema name and write the following Create script. Following is the Create table SQL command that can be used to create a column table in HANA database. Create column Table Sample1 ( Cust_ID INTEGER, Cust_NAME VARCHAR(10), PRIMARY KEY (Cust_ID) ); To insert the data, run the Insert statement in SQL editor. "Sample" is the table name. Insert into Sample Values (101,'Jon'); Insert into Sample Values (201,'Tina'); Insert into Sample Values (301,'Jacob'); When the data is entered, you can see the data in this row-based table by going to Data Preview option. To see the data, right-click the table name → Open Data Preview. All the database objects in SAP HANA system are maintained in CATALOG folder in HANA Studio. Following are the key capabilities of SAP HANA database system − You can use high performance in-memory database for processing complex transactions and analytics. You can manage large database volumes in multitenant database containers. You can use high performance in-memory database for processing complex transactions and analytics. You can manage large database volumes in multitenant database containers. SAP HANA system combines OLAP and OLTP processing into a single in-memory database. It removes the disk bottlenecks, offering groundbreaking performance. SAP HANA system combines OLAP and OLTP processing into a single in-memory database. It removes the disk bottlenecks, offering groundbreaking performance. Using SAP HANA in-memory database component, you can run advanced analytical queries, which are complex in nature with high-speed transactions to get the correct, up-to-date responses in a fraction of a second. Using SAP HANA in-memory database component, you can run advanced analytical queries, which are complex in nature with high-speed transactions to get the correct, up-to-date responses in a fraction of a second. All the 2-dimensional objects exist in schemas in HANA database. Schemas are shown under the Catalog folder in HANA Studio. When you expand any of the schema, you can see different Relational objects - functions, indexes, views, and synonyms inside it. If you open SAP HANA cockpit using the following link, you can see different database functions in HANA system: https://best:4303/sap/hana/admin/cockpit To create a view in one table, write the following SQL statement. create view view_name as select ARTICLE_ID,ARTICLE_LABEL,CATEGORY,SALE_PRICE from "AA_HANA11"."ARTICLE_LOOKUP"; You can drop a view using the Drop command, like we drop a table. Drop view "AA_HANA11"."DEMO_TEST"; 25 Lectures 6 hours Sanjo Thomas 26 Lectures 2 hours Neha Gupta 30 Lectures 2.5 hours Sumit Agarwal 30 Lectures 4 hours Sumit Agarwal 14 Lectures 1.5 hours Neha Malik 13 Lectures 1.5 hours Neha Malik Print Add Notes Bookmark this page
[ { "code": null, "e": 2593, "s": 2311, "text": "SAP HANA is an in-memory database that supports all the features of a conventional database. You can perform all DDL, DML, and DCL statements on database objects. Users can create new tables, views, functions, triggers, and all other database functions using HANA Studio front-end." }, { "code": null, "e": 2742, "s": 2593, "text": "Tables in HANA database can be accessed from HANA Studio in Catalogue tab under Schemas. New tables can be created using the following two methods −" }, { "code": null, "e": 2759, "s": 2742, "text": "Using SQL editor" }, { "code": null, "e": 2776, "s": 2759, "text": "Using GUI option" }, { "code": null, "e": 2964, "s": 2776, "text": "All the database objects - tables, views, and other objects can be used to design a Universe - Data Foundation layer and later to publish Business Layer to BO repository for BI reporting." }, { "code": null, "e": 3347, "s": 2964, "text": "In SAP HANA Studio, open SQL editor by selecting the Schema name and click the circled option in the following screenshot. You can run all SQL queries in SQL editor, which are required to perform conventional database functions. You can create new tables, views by writing the CREATE command in the editor window or right-click the Schema name and write the following Create script." }, { "code": null, "e": 3449, "s": 3347, "text": "Following is the Create table SQL command that can be used to create a column table in HANA database." }, { "code": null, "e": 3553, "s": 3449, "text": "Create column Table Sample1 (\n Cust_ID INTEGER,\n Cust_NAME VARCHAR(10),\n PRIMARY KEY (Cust_ID)\n);" }, { "code": null, "e": 3641, "s": 3553, "text": "To insert the data, run the Insert statement in SQL editor. \"Sample\" is the table name." }, { "code": null, "e": 3761, "s": 3641, "text": "Insert into Sample Values (101,'Jon');\nInsert into Sample Values (201,'Tina');\nInsert into Sample Values (301,'Jacob');" }, { "code": null, "e": 3930, "s": 3761, "text": "When the data is entered, you can see the data in this row-based table by going to Data Preview option. To see the data, right-click the table name → Open Data Preview." }, { "code": null, "e": 4088, "s": 3930, "text": "All the database objects in SAP HANA system are maintained in CATALOG folder in HANA Studio. Following are the key capabilities of SAP HANA database system −" }, { "code": null, "e": 4261, "s": 4088, "text": "You can use high performance in-memory database for processing complex transactions and analytics. You can manage large database volumes in multitenant database containers." }, { "code": null, "e": 4434, "s": 4261, "text": "You can use high performance in-memory database for processing complex transactions and analytics. You can manage large database volumes in multitenant database containers." }, { "code": null, "e": 4588, "s": 4434, "text": "SAP HANA system combines OLAP and OLTP processing into a single in-memory database. It removes the disk bottlenecks, offering groundbreaking performance." }, { "code": null, "e": 4742, "s": 4588, "text": "SAP HANA system combines OLAP and OLTP processing into a single in-memory database. It removes the disk bottlenecks, offering groundbreaking performance." }, { "code": null, "e": 4953, "s": 4742, "text": "Using SAP HANA in-memory database component, you can run advanced analytical queries, which are complex in nature with high-speed transactions to get the correct, up-to-date responses in a fraction of a second." }, { "code": null, "e": 5164, "s": 4953, "text": "Using SAP HANA in-memory database component, you can run advanced analytical queries, which are complex in nature with high-speed transactions to get the correct, up-to-date responses in a fraction of a second." }, { "code": null, "e": 5417, "s": 5164, "text": "All the 2-dimensional objects exist in schemas in HANA database. Schemas are shown under the Catalog folder in HANA Studio. When you expand any of the schema, you can see different Relational objects - functions, indexes, views, and synonyms inside it." }, { "code": null, "e": 5570, "s": 5417, "text": "If you open SAP HANA cockpit using the following link, you can see different database functions in HANA system: https://best:4303/sap/hana/admin/cockpit" }, { "code": null, "e": 5636, "s": 5570, "text": "To create a view in one table, write the following SQL statement." }, { "code": null, "e": 5661, "s": 5636, "text": "create view view_name as" }, { "code": null, "e": 5748, "s": 5661, "text": "select ARTICLE_ID,ARTICLE_LABEL,CATEGORY,SALE_PRICE\nfrom \"AA_HANA11\".\"ARTICLE_LOOKUP\";" }, { "code": null, "e": 5814, "s": 5748, "text": "You can drop a view using the Drop command, like we drop a table." }, { "code": null, "e": 5849, "s": 5814, "text": "Drop view \"AA_HANA11\".\"DEMO_TEST\";" }, { "code": null, "e": 5882, "s": 5849, "text": "\n 25 Lectures \n 6 hours \n" }, { "code": null, "e": 5896, "s": 5882, "text": " Sanjo Thomas" }, { "code": null, "e": 5929, "s": 5896, "text": "\n 26 Lectures \n 2 hours \n" }, { "code": null, "e": 5941, "s": 5929, "text": " Neha Gupta" }, { "code": null, "e": 5976, "s": 5941, "text": "\n 30 Lectures \n 2.5 hours \n" }, { "code": null, "e": 5991, "s": 5976, "text": " Sumit Agarwal" }, { "code": null, "e": 6024, "s": 5991, "text": "\n 30 Lectures \n 4 hours \n" }, { "code": null, "e": 6039, "s": 6024, "text": " Sumit Agarwal" }, { "code": null, "e": 6074, "s": 6039, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6086, "s": 6074, "text": " Neha Malik" }, { "code": null, "e": 6121, "s": 6086, "text": "\n 13 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6133, "s": 6121, "text": " Neha Malik" }, { "code": null, "e": 6140, "s": 6133, "text": " Print" }, { "code": null, "e": 6151, "s": 6140, "text": " Add Notes" } ]
Writing advanced SQL queries in pandas | by Zolzaya Luvsandorj | Towards Data Science
Being able to skillfully manipulate data with both SQL and pandas, a data analysis library in Python, is a valuable skill to have for data analysts, data scientists and anyone working with data. In this post, we will look at selected few advanced SQL queries and their counterparts in pandas. If you are still new to pandas, you may want to check out 10 minutes to pandas or my previous post where I covered side-by-side comparison of basic queries and their equivalents in pandas. This post assumes that the reader is comfortable with querying in SQL. We will create a small dataset to use. Let’s assume we have two imaginary people’s trip data from the past 2 years: df = pd.DataFrame({'name': ['Ann', 'Ann', 'Ann', 'Bob', 'Bob'], 'destination': ['Japan', 'Korea', 'Switzerland', 'USA', 'Switzerland'], 'dep_date': ['2019-02-02', '2019-01-01', '2020-01-11', '2019-05-05', '2020-01-11'], 'duration': [7, 21, 14, 10, 14]})df Let’s define dep_date as the departure date to the destination and assume that duration shows trip length in days. We will start with the basic versions of LEAD() and LAG(). For each trip, let’s pull the departure date of the next trip: lead1, the second next trip: lead2, the previous trip: lag1 and the third previous trip: lag3. SELECT name , destination , dep_date , duration , LEAD(dep_date) OVER(ORDER BY dep_date, name) AS lead1 , LEAD(dep_date, 2) OVER(ORDER BY dep_date, name) AS lead2 , LAG(dep_date) OVER(ORDER BY dep_date, name) AS lag1 , LAG(dep_date, 3) OVER(ORDER BY dep_date, name) AS lag3FROM df To get the same output in pandas, we use shift(): df.sort_values(['dep_date', 'name'], inplace=True)df.assign(lead1 = df['dep_date'].shift(-1), lead2 = df['dep_date'].shift(-2), lag1 = df['dep_date'].shift(), lag3 = df['dep_date'].shift(3)) In the first line, we sorted the data with sort_values() once in place since we are using the same logic for all shifting operations. Doing it this way is more efficient than sorting the data every time we create a new column like below: df.assign(lead1 = df.sort_values(['dep_date', 'name'])['dep_date'] .shift(-1), lead2 = df.sort_values(['dep_date', 'name'])['dep_date'] .shift(-2), lag1 = df.sort_values(['dep_date', 'name'])['dep_date'] .shift(), lag3 = df.sort_values(['dep_date', 'name'])['dep_date'] .shift(3)) Output from this inefficient approach will contain the right values but the order of the rows will be same as the original data and will not be sorted. Now let’s look at the remaining 4 lines of the code. In pandas, we can create multiple columns with assign(). However, the new columns haven’t been added to the DataFrame. If we wanted to add the new columns to df , we will need to assign like this: df.sort_values(['dep_date', 'name'], inplace=True)df = df.assign(lead1 = df['dep_date'].shift(-1), lead2 = df['dep_date'].shift(-2), lag1 = df['dep_date'].shift(), lag3 = df['dep_date'].shift(3)) We will look at another example for LEAD() with PARTITION BY() in the last section. Now, let’s look at how to manipulate date/datetime columns. In this section, we will extract day name of the week from departure date: day, name of the month from departure date: month, number of days elapsed since previous trip: diff and arrival date: arr_date. SELECT name , destination , dep_date , duration , DATENAME(WEEKDAY, dep_date) AS day , DATENAME(MONTH, dep_date) AS month , DATEDIFF(DAY, LAG(dep_date) OVER(ORDER BY dep_date, name), dep_date) AS diff , DATEADD(DAY, day, dep_date) AS arr_dateFROM df Firstly, we must ensure the column data types are the right ones: # Convert to proper dtypedf['dep_date'] = pd.to_datetime(df['dep_date'])df['duration'] = pd.to_timedelta(df['duration'], 'D') Converting dep_date to datetime will allow us to access many date parts with the .dt accessor. For instance: df[‘dep_date’].dt.year will give us the year (equivalent to DATEPART(YEAR, dep_date) in SQL). Converting duration to timedelta allows us to add it to a datetime column to get another datetime column. Having done the data type conversion, let’s see the comparison: df.sort_values(['dep_date', 'name'], inplace=True)df.assign(day = df['dep_date'].dt.day_name(), month = df['dep_date'].dt.month_name(), diff = df['dep_date'] - df['dep_date'].shift(), arr_date = df['dep_date'] + df['duration']) As you can see, the manipulation is simple once the data types are correctly set. Of note, we can check the data types of columns with the dtypes attribute of a DataFrame. Here’s an example: df.sort_values(['dep_date', 'name'], inplace=True)df.assign(day = df['dep_date'].dt.day_name(), month = df['dep_date'].dt.month_name(), diff = df['dep_date'] - df['dep_date'].shift(), arr_date = df['dep_date'] + df['duration']).dtypes In pandas, when finding the difference between two dates, it returns a timedelta column. Therefore, we can see that column diff is actually a timedelta. You may have used at least one of these functions before in SQL. The key difference between these three is their treatment in ranking ties and ranks thereafter. Let’s create three columns that rank each record based on duration using each of these method: row_number_d, rank_d and dense_rank_d. When using ROW_NUMBER(), ties are given a different rank unlike the other two. To control how ties are treated with ROW_NUMBER(), we used name to breaks ties. SELECT name , destination , dep_date , duration , ROW_NUMBER() OVER(ORDER BY duration, name) AS row_number_d , RANK() OVER(ORDER BY duration) AS rank_d , DENSE_RANK() OVER(ORDER BY duration) AS dense_rank_dFROM df The equivalent of the query in pandas is possible with rank(): df.sort_values(['duration', 'name']).assign( row_number_d = df['duration'].rank(method='first').astype(int), rank_d = df['duration'].rank(method='min').astype(int), dense_rank_d = df['duration'].rank(method='dense').astype(int)) We specify the relevant method inside rank() as illustrated above. Of note, there are other variations we haven’t covered here. If you are interested to find out, have a look at the documentation. We did something slightly different with this example. Unlike examples in previous two sections, we didn’t sort the data in place. Instead, we chained methods and haven’t modified the data at all. You may have also noticed that we have included astype(int). This is to convert the ranks in floats to integers. If you prefer to see floats, then that portion of the code could be removed: df.sort_values(['duration', 'name']).assign( row_number_d = df['duration'].rank(method='first'), rank_d = df['duration'].rank(method='min'), dense_rank_d = df['duration'].rank(method='dense')) In this section, we will create column for the longest trip duration: max_dur, total duration for all trips: sum_dur, average duration of trip per person: avg_dur_name and cumulative sum of trip length for each person: cum_sum_dur_name. SELECT name , destination , dep_date , duration , MAX(duration) OVER() AS max_dur , SUM(duration) OVER() AS sum_dur , AVG(duration) OVER(PARTITION BY name) AS avg_dur_name , SUM(duration) OVER(PARTITION BY name ORDER BY dep_date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cum_sum_dur_nameFROM df This can be done like this in pandas: df.assign(max_dur=df['duration'].max(), sum_dur=df['duration'].sum(), avg_dur_name=df.groupby('name')['duration'] .transform('mean'), cum_sum_dur_name=df.sort_values('dep_date') .groupby('name')['duration'] .transform('cumsum')) Appending aggregate statistics such as max_dur and sum_dur is simple in pandas because of broadcasting. Essentially, if we try to assign a scalar value to a new column in pandas, the value is broadcasted across all rows. PARTITION BY is achieved with combination of groupby() and transform(). In this output, the data is in the same order as before (i.e. unsorted) whereas it will be sorted by dep_date for each person in SQL. We have only sorted the data when creating cum_sum_dur_name. If we desire the output to be sorted, the code changes to: df.sort_values(['name', 'dep_date'], inplace=True)df.assign(max_dur=df['duration'].max(), sum_dur=df['duration'].sum(), avg_dur_name=df.groupby('name')['duration'] .transform('mean'), cum_sum_dur_name=df.groupby('name')['duration'] .transform('cumsum')) This will be identical to the SQL output. Lastly, let’s write one query that covers pieces of the four different areas we just visited. Here’s our last example: SELECT ROW_NUMBER() OVER(PARTITION BY name ORDER BY dep_date) AS number , name , destination , DATENAME(MONTH, dep_date) AS dep_month , dep_date , DATEADD(DAY, duration, dep_date) AS arr_date , LEAD(dep_date) OVER(PARTITION BY NAME ORDER BY dep_date) AS next_dep_date , DATEDIFF(DAY, dep_date, LEAD(dep_date) OVER(PARTITION BY NAME ORDER BY dep_date)) AS gap , duration , AVG(1.0 * duration) OVER() AS avg_dur , AVG(1.0 * duration) OVER(PARTITION BY name) AS avg_dur_name , SUM(duration) OVER(PARTITION BY name ORDER BY dep_date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cum_sum_dur_name FROM dfORDER BY name, dep_date I believe we learn more when we practice ourselves. I encourage you to try translating this SQL query to pandas on your own before seeing the comparison that we are about to look at. 👀 Here is the comparison: # Convert to proper typedf['dep_date'] = pd.to_datetime(df['dep_date'])df['duration'] = pd.to_timedelta(df['duration'], 'D')# Sort datadf.sort_values(['name', 'dep_date'], inplace=True)# Append new columns to datadf = df.assign(number=df.groupby('name')['dep_date'] .rank('min') .astype(int), dep_month = df['dep_date'].dt.month_name(), arr_date = df['dep_date'] + df['duration'], next_dep_date = df.groupby('name')['dep_date'] .transform(lambda x: x.shift(-1)), gap = df.groupby('name')['dep_date'] .transform(lambda x: x.shift(-1))- df['dep_date'], avg_dur = df['duration'].mean(), avg_dur_name = df.groupby('name')['duration'] .transform(lambda x: x.mean()), cum_sum_dur_name = df.groupby('name')['duration'] .transform(lambda x: x.cumsum()))# Reorder columnscolumns = ['number', 'name', 'destination', 'dep_month', 'dep_date', 'arr_date', 'next_dep_date', 'gap', 'duration', 'avg_dur', 'avg_dur_name', 'cum_sum_dur_name']df[columns] We have converted data types, sorted the data in place and modified it with new columns. To view the data with columns ordered in the same way as SQL query, we used a list which outlines the order of the columns. If you only run df, the columns would be ordered differently. You may have noticed that avg_dur is expressed in combination of days, hours and minutes: ‘13 days 04:48:00’. This is equivalent to 13 + (4*60+48) / (24*60) = 13.2 days. If we wanted to see just 13.2, then we could replace df[‘duration’].mean() with this snippet which converts duration to numeric type before finding mean: pd.to_numeric(df[‘duration’].dt.days).mean(). When creating avg_dur_name and cum_sum_dur_name, we used lambda function instead of using a syntax like this: avg_dur_name = df.groupby('name')['duration'].transform('mean'),cum_sum_dur_name = df.groupby('name')['duration'] .transform('cumsum') That’s because if we try to do that we will come across an issue described here. Therefore, we used one of the work-arounds instead. Voila❕ This remarks the end of our comparisons. Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me. Thank you for reading my post. Hope you find this post useful ✂️ and learned a bit more about pandas. If you are interested to learn more about pandas, here are links to some of my posts: ◼️️ 5 tips for data aggregation in pandas◼️️ Writing 5 common SQL queries in pandas◼️️ 5 tips for pandas users◼️️ How to transform variables in a pandas DataFrame Bye for now 🏃💨
[ { "code": null, "e": 465, "s": 172, "text": "Being able to skillfully manipulate data with both SQL and pandas, a data analysis library in Python, is a valuable skill to have for data analysts, data scientists and anyone working with data. In this post, we will look at selected few advanced SQL queries and their counterparts in pandas." }, { "code": null, "e": 725, "s": 465, "text": "If you are still new to pandas, you may want to check out 10 minutes to pandas or my previous post where I covered side-by-side comparison of basic queries and their equivalents in pandas. This post assumes that the reader is comfortable with querying in SQL." }, { "code": null, "e": 841, "s": 725, "text": "We will create a small dataset to use. Let’s assume we have two imaginary people’s trip data from the past 2 years:" }, { "code": null, "e": 1253, "s": 841, "text": "df = pd.DataFrame({'name': ['Ann', 'Ann', 'Ann', 'Bob', 'Bob'], 'destination': ['Japan', 'Korea', 'Switzerland', 'USA', 'Switzerland'], 'dep_date': ['2019-02-02', '2019-01-01', '2020-01-11', '2019-05-05', '2020-01-11'], 'duration': [7, 21, 14, 10, 14]})df" }, { "code": null, "e": 1368, "s": 1253, "text": "Let’s define dep_date as the departure date to the destination and assume that duration shows trip length in days." }, { "code": null, "e": 1585, "s": 1368, "text": "We will start with the basic versions of LEAD() and LAG(). For each trip, let’s pull the departure date of the next trip: lead1, the second next trip: lead2, the previous trip: lag1 and the third previous trip: lag3." }, { "code": null, "e": 1908, "s": 1585, "text": "SELECT name , destination , dep_date , duration , LEAD(dep_date) OVER(ORDER BY dep_date, name) AS lead1 , LEAD(dep_date, 2) OVER(ORDER BY dep_date, name) AS lead2 , LAG(dep_date) OVER(ORDER BY dep_date, name) AS lag1 , LAG(dep_date, 3) OVER(ORDER BY dep_date, name) AS lag3FROM df" }, { "code": null, "e": 1958, "s": 1908, "text": "To get the same output in pandas, we use shift():" }, { "code": null, "e": 2176, "s": 1958, "text": "df.sort_values(['dep_date', 'name'], inplace=True)df.assign(lead1 = df['dep_date'].shift(-1), lead2 = df['dep_date'].shift(-2), lag1 = df['dep_date'].shift(), lag3 = df['dep_date'].shift(3))" }, { "code": null, "e": 2414, "s": 2176, "text": "In the first line, we sorted the data with sort_values() once in place since we are using the same logic for all shifting operations. Doing it this way is more efficient than sorting the data every time we create a new column like below:" }, { "code": null, "e": 2796, "s": 2414, "text": "df.assign(lead1 = df.sort_values(['dep_date', 'name'])['dep_date'] .shift(-1), lead2 = df.sort_values(['dep_date', 'name'])['dep_date'] .shift(-2), lag1 = df.sort_values(['dep_date', 'name'])['dep_date'] .shift(), lag3 = df.sort_values(['dep_date', 'name'])['dep_date'] .shift(3))" }, { "code": null, "e": 2948, "s": 2796, "text": "Output from this inefficient approach will contain the right values but the order of the rows will be same as the original data and will not be sorted." }, { "code": null, "e": 3198, "s": 2948, "text": "Now let’s look at the remaining 4 lines of the code. In pandas, we can create multiple columns with assign(). However, the new columns haven’t been added to the DataFrame. If we wanted to add the new columns to df , we will need to assign like this:" }, { "code": null, "e": 3436, "s": 3198, "text": "df.sort_values(['dep_date', 'name'], inplace=True)df = df.assign(lead1 = df['dep_date'].shift(-1), lead2 = df['dep_date'].shift(-2), lag1 = df['dep_date'].shift(), lag3 = df['dep_date'].shift(3))" }, { "code": null, "e": 3580, "s": 3436, "text": "We will look at another example for LEAD() with PARTITION BY() in the last section. Now, let’s look at how to manipulate date/datetime columns." }, { "code": null, "e": 3783, "s": 3580, "text": "In this section, we will extract day name of the week from departure date: day, name of the month from departure date: month, number of days elapsed since previous trip: diff and arrival date: arr_date." }, { "code": null, "e": 4112, "s": 3783, "text": "SELECT name , destination , dep_date , duration , DATENAME(WEEKDAY, dep_date) AS day , DATENAME(MONTH, dep_date) AS month , DATEDIFF(DAY, LAG(dep_date) OVER(ORDER BY dep_date, name), dep_date) AS diff , DATEADD(DAY, day, dep_date) AS arr_dateFROM df" }, { "code": null, "e": 4178, "s": 4112, "text": "Firstly, we must ensure the column data types are the right ones:" }, { "code": null, "e": 4304, "s": 4178, "text": "# Convert to proper dtypedf['dep_date'] = pd.to_datetime(df['dep_date'])df['duration'] = pd.to_timedelta(df['duration'], 'D')" }, { "code": null, "e": 4507, "s": 4304, "text": "Converting dep_date to datetime will allow us to access many date parts with the .dt accessor. For instance: df[‘dep_date’].dt.year will give us the year (equivalent to DATEPART(YEAR, dep_date) in SQL)." }, { "code": null, "e": 4613, "s": 4507, "text": "Converting duration to timedelta allows us to add it to a datetime column to get another datetime column." }, { "code": null, "e": 4677, "s": 4613, "text": "Having done the data type conversion, let’s see the comparison:" }, { "code": null, "e": 4932, "s": 4677, "text": "df.sort_values(['dep_date', 'name'], inplace=True)df.assign(day = df['dep_date'].dt.day_name(), month = df['dep_date'].dt.month_name(), diff = df['dep_date'] - df['dep_date'].shift(), arr_date = df['dep_date'] + df['duration'])" }, { "code": null, "e": 5123, "s": 4932, "text": "As you can see, the manipulation is simple once the data types are correctly set. Of note, we can check the data types of columns with the dtypes attribute of a DataFrame. Here’s an example:" }, { "code": null, "e": 5385, "s": 5123, "text": "df.sort_values(['dep_date', 'name'], inplace=True)df.assign(day = df['dep_date'].dt.day_name(), month = df['dep_date'].dt.month_name(), diff = df['dep_date'] - df['dep_date'].shift(), arr_date = df['dep_date'] + df['duration']).dtypes" }, { "code": null, "e": 5538, "s": 5385, "text": "In pandas, when finding the difference between two dates, it returns a timedelta column. Therefore, we can see that column diff is actually a timedelta." }, { "code": null, "e": 5833, "s": 5538, "text": "You may have used at least one of these functions before in SQL. The key difference between these three is their treatment in ranking ties and ranks thereafter. Let’s create three columns that rank each record based on duration using each of these method: row_number_d, rank_d and dense_rank_d." }, { "code": null, "e": 5992, "s": 5833, "text": "When using ROW_NUMBER(), ties are given a different rank unlike the other two. To control how ties are treated with ROW_NUMBER(), we used name to breaks ties." }, { "code": null, "e": 6242, "s": 5992, "text": "SELECT name , destination , dep_date , duration , ROW_NUMBER() OVER(ORDER BY duration, name) AS row_number_d , RANK() OVER(ORDER BY duration) AS rank_d , DENSE_RANK() OVER(ORDER BY duration) AS dense_rank_dFROM df" }, { "code": null, "e": 6305, "s": 6242, "text": "The equivalent of the query in pandas is possible with rank():" }, { "code": null, "e": 6543, "s": 6305, "text": "df.sort_values(['duration', 'name']).assign( row_number_d = df['duration'].rank(method='first').astype(int), rank_d = df['duration'].rank(method='min').astype(int), dense_rank_d = df['duration'].rank(method='dense').astype(int))" }, { "code": null, "e": 6740, "s": 6543, "text": "We specify the relevant method inside rank() as illustrated above. Of note, there are other variations we haven’t covered here. If you are interested to find out, have a look at the documentation." }, { "code": null, "e": 6937, "s": 6740, "text": "We did something slightly different with this example. Unlike examples in previous two sections, we didn’t sort the data in place. Instead, we chained methods and haven’t modified the data at all." }, { "code": null, "e": 7127, "s": 6937, "text": "You may have also noticed that we have included astype(int). This is to convert the ranks in floats to integers. If you prefer to see floats, then that portion of the code could be removed:" }, { "code": null, "e": 7329, "s": 7127, "text": "df.sort_values(['duration', 'name']).assign( row_number_d = df['duration'].rank(method='first'), rank_d = df['duration'].rank(method='min'), dense_rank_d = df['duration'].rank(method='dense'))" }, { "code": null, "e": 7566, "s": 7329, "text": "In this section, we will create column for the longest trip duration: max_dur, total duration for all trips: sum_dur, average duration of trip per person: avg_dur_name and cumulative sum of trip length for each person: cum_sum_dur_name." }, { "code": null, "e": 7970, "s": 7566, "text": "SELECT name , destination , dep_date , duration , MAX(duration) OVER() AS max_dur , SUM(duration) OVER() AS sum_dur , AVG(duration) OVER(PARTITION BY name) AS avg_dur_name , SUM(duration) OVER(PARTITION BY name ORDER BY dep_date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cum_sum_dur_nameFROM df" }, { "code": null, "e": 8008, "s": 7970, "text": "This can be done like this in pandas:" }, { "code": null, "e": 8344, "s": 8008, "text": "df.assign(max_dur=df['duration'].max(), sum_dur=df['duration'].sum(), avg_dur_name=df.groupby('name')['duration'] .transform('mean'), cum_sum_dur_name=df.sort_values('dep_date') .groupby('name')['duration'] .transform('cumsum'))" }, { "code": null, "e": 8637, "s": 8344, "text": "Appending aggregate statistics such as max_dur and sum_dur is simple in pandas because of broadcasting. Essentially, if we try to assign a scalar value to a new column in pandas, the value is broadcasted across all rows. PARTITION BY is achieved with combination of groupby() and transform()." }, { "code": null, "e": 8891, "s": 8637, "text": "In this output, the data is in the same order as before (i.e. unsorted) whereas it will be sorted by dep_date for each person in SQL. We have only sorted the data when creating cum_sum_dur_name. If we desire the output to be sorted, the code changes to:" }, { "code": null, "e": 9224, "s": 8891, "text": "df.sort_values(['name', 'dep_date'], inplace=True)df.assign(max_dur=df['duration'].max(), sum_dur=df['duration'].sum(), avg_dur_name=df.groupby('name')['duration'] .transform('mean'), cum_sum_dur_name=df.groupby('name')['duration'] .transform('cumsum'))" }, { "code": null, "e": 9266, "s": 9224, "text": "This will be identical to the SQL output." }, { "code": null, "e": 9385, "s": 9266, "text": "Lastly, let’s write one query that covers pieces of the four different areas we just visited. Here’s our last example:" }, { "code": null, "e": 10267, "s": 9385, "text": "SELECT ROW_NUMBER() OVER(PARTITION BY name ORDER BY dep_date) AS number , name , destination , DATENAME(MONTH, dep_date) AS dep_month , dep_date , DATEADD(DAY, duration, dep_date) AS arr_date , LEAD(dep_date) OVER(PARTITION BY NAME ORDER BY dep_date) AS next_dep_date , DATEDIFF(DAY, dep_date, LEAD(dep_date) OVER(PARTITION BY NAME ORDER BY dep_date)) AS gap , duration , AVG(1.0 * duration) OVER() AS avg_dur , AVG(1.0 * duration) OVER(PARTITION BY name) AS avg_dur_name , SUM(duration) OVER(PARTITION BY name ORDER BY dep_date RANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) AS cum_sum_dur_name FROM dfORDER BY name, dep_date" }, { "code": null, "e": 10452, "s": 10267, "text": "I believe we learn more when we practice ourselves. I encourage you to try translating this SQL query to pandas on your own before seeing the comparison that we are about to look at. 👀" }, { "code": null, "e": 10476, "s": 10452, "text": "Here is the comparison:" }, { "code": null, "e": 11752, "s": 10476, "text": "# Convert to proper typedf['dep_date'] = pd.to_datetime(df['dep_date'])df['duration'] = pd.to_timedelta(df['duration'], 'D')# Sort datadf.sort_values(['name', 'dep_date'], inplace=True)# Append new columns to datadf = df.assign(number=df.groupby('name')['dep_date'] .rank('min') .astype(int), dep_month = df['dep_date'].dt.month_name(), arr_date = df['dep_date'] + df['duration'], next_dep_date = df.groupby('name')['dep_date'] .transform(lambda x: x.shift(-1)), gap = df.groupby('name')['dep_date'] .transform(lambda x: x.shift(-1))- df['dep_date'], avg_dur = df['duration'].mean(), avg_dur_name = df.groupby('name')['duration'] .transform(lambda x: x.mean()), cum_sum_dur_name = df.groupby('name')['duration'] .transform(lambda x: x.cumsum()))# Reorder columnscolumns = ['number', 'name', 'destination', 'dep_month', 'dep_date', 'arr_date', 'next_dep_date', 'gap', 'duration', 'avg_dur', 'avg_dur_name', 'cum_sum_dur_name']df[columns]" }, { "code": null, "e": 12027, "s": 11752, "text": "We have converted data types, sorted the data in place and modified it with new columns. To view the data with columns ordered in the same way as SQL query, we used a list which outlines the order of the columns. If you only run df, the columns would be ordered differently." }, { "code": null, "e": 12397, "s": 12027, "text": "You may have noticed that avg_dur is expressed in combination of days, hours and minutes: ‘13 days 04:48:00’. This is equivalent to 13 + (4*60+48) / (24*60) = 13.2 days. If we wanted to see just 13.2, then we could replace df[‘duration’].mean() with this snippet which converts duration to numeric type before finding mean: pd.to_numeric(df[‘duration’].dt.days).mean()." }, { "code": null, "e": 12507, "s": 12397, "text": "When creating avg_dur_name and cum_sum_dur_name, we used lambda function instead of using a syntax like this:" }, { "code": null, "e": 12662, "s": 12507, "text": "avg_dur_name = df.groupby('name')['duration'].transform('mean'),cum_sum_dur_name = df.groupby('name')['duration'] .transform('cumsum')" }, { "code": null, "e": 12795, "s": 12662, "text": "That’s because if we try to do that we will come across an issue described here. Therefore, we used one of the work-arounds instead." }, { "code": null, "e": 12843, "s": 12795, "text": "Voila❕ This remarks the end of our comparisons." }, { "code": null, "e": 13067, "s": 12843, "text": "Would you like to access more content like this? Medium members get unlimited access to any articles on Medium. If you become a member using my referral link, a portion of your membership fee will directly go to support me." }, { "code": null, "e": 13255, "s": 13067, "text": "Thank you for reading my post. Hope you find this post useful ✂️ and learned a bit more about pandas. If you are interested to learn more about pandas, here are links to some of my posts:" }, { "code": null, "e": 13418, "s": 13255, "text": "◼️️ 5 tips for data aggregation in pandas◼️️ Writing 5 common SQL queries in pandas◼️️ 5 tips for pandas users◼️️ How to transform variables in a pandas DataFrame" } ]
N-th Tribonacci Number in C++
Suppose we have a value n, we have to generate n-th Tribonacci number. The Tribonacci numbers are similar to the Fibonacci numbers, but here we are generating a term by adding three previous terms. Suppose we want to generate T(n), then the formula will be like below − T(n) = T(n - 1) + T(n - 2) + T(n - 3) The first few numbers to start, are {0, 1, 1} We can solve them by following this algorithm − • first := 0, second := 1, third := 1 • for i in range n – 3, do o next := first + second + third o first := second, second := third, third := next • return third Live Demo #include<iostream> using namespace std; long tribonacci_gen(int n){ //function to generate n tetranacci numbers int first = 0, second = 1, third = 1; for(int i = 0; i < n - 3; i++){ int next = first + second + third; first = second; second = third; third = next; } return third; } main(){ cout << "15th Tribonacci Term: " << tribonacci_gen(15); } 15 15th Tribonacci Term: 1705
[ { "code": null, "e": 1332, "s": 1062, "text": "Suppose we have a value n, we have to generate n-th Tribonacci number. The Tribonacci numbers are similar to the Fibonacci numbers, but here we are generating a term by adding three previous terms. Suppose we want to generate T(n), then the formula will be like below −" }, { "code": null, "e": 1370, "s": 1332, "text": "T(n) = T(n - 1) + T(n - 2) + T(n - 3)" }, { "code": null, "e": 1416, "s": 1370, "text": "The first few numbers to start, are {0, 1, 1}" }, { "code": null, "e": 1464, "s": 1416, "text": "We can solve them by following this algorithm −" }, { "code": null, "e": 1633, "s": 1464, "text": "• first := 0, second := 1, third := 1\n• for i in range n – 3, do\n o next := first + second + third\n o first := second, second := third, third := next\n• return third" }, { "code": null, "e": 1644, "s": 1633, "text": " Live Demo" }, { "code": null, "e": 2033, "s": 1644, "text": "#include<iostream>\nusing namespace std;\nlong tribonacci_gen(int n){\n //function to generate n tetranacci numbers\n int first = 0, second = 1, third = 1;\n for(int i = 0; i < n - 3; i++){\n int next = first + second + third;\n first = second;\n second = third;\n third = next;\n }\n return third;\n}\nmain(){\n cout << \"15th Tribonacci Term: \" << tribonacci_gen(15);\n}" }, { "code": null, "e": 2036, "s": 2033, "text": "15" }, { "code": null, "e": 2063, "s": 2036, "text": "15th Tribonacci Term: 1705" } ]
Normal Probability Plot - GeeksforGeeks
22 Jan, 2021 The probability plot is a way of visually comparing the data coming from different distributions. These data can be of empirical dataset or theoretical dataset. The probability plot can be of two types: P-P plot: The (Probability-to-Probability) p-p plot is the way to visualize the comparing of cumulative distribution function (CDFs) of the two distributions (empirical and theoretical) against each other. Q-Q plot: The q-q (Quantile-to-Quantile) plot is used to compare the quantiles of two distributions. The quantiles can be defined as continuous intervals with equal probabilities or dividing the samples between a similar way The distributions may be theoretical or sample distributions from a process, etc. The normal probability plot is a case of the q-q plot. Normal Probability plot: The normal probability plot is a way of knowing whether the dataset is normally distributed or not. In this plot, data is plotted against the theoretical normal distribution plot in a way such that if a given dataset is normally distributed it should form an approximate straight line. The normal probability plot is a case of the probability plot (more specifically Q-Q plot). This plot is commonly used in the industry for finding the deviation from the normal process. The normal probability plot has the following axis. Horizontal Axis: Normal-order statistic medians. Vertical Axis: Order response values The order response variable can be calculated as: Where Ui is the uniform order median statistics and G is the percent point function of normal distribution. It is the inverse of the cumulative distribution function. i.e given probability distribution, we want the cumulative distribution function. The uniform order statistics medians can be approximated by: The underlying assumptions for a measurement process that the data should have following Random numbers. From fixed distributions. With fixed location With a fixed scale. The normal probability plot is used to answer the following questions: Is Data normally distributed? If not, what is the nature of distribution In this implementation, we will be using statsmodels python library and seaborn library for visualizing different plots. These libraries are pre-installed in colab, but for local environment using pip install. Python3 # imports import numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport scipy.stats as scimport statsmodels.graphics.gofplots as sm # define distributionssample_size = 10000 standard_norm = np.random.normal(size=sample_size)heavy_tailed_norm = np.random.normal(loc=0, scale=2, size=sample_size)skewed_norm = sc.skewnorm.rvs(a=5, size=sample_size)skew_left_norm = sc.skewnorm.rvs(a=-5, size=sample_size) # plots for standard distributionfig, ax = plt.subplots(1, 2, figsize=(12, 7))sns.histplot(standard_norm,kde=True, color ='blue',ax=ax[0])sm.ProbPlot(standard_norm).qqplot(line='s', ax=ax[1]) # plot for right-tailed distributionfig, ax = plt.subplots(1, 2, figsize=(12, 7))sm.ProbPlot(skewed_norm).qqplot(line='s', ax=ax[1]);sns.histplot(skewed_norm,kde=True, color ='blue',ax=ax[0]) # plot for left-tailed distributionfig, ax = plt.subplots(1, 2, figsize=(12, 7))sm.ProbPlot(skew_left_norm).qqplot(line='s',color='red', ax=ax[1]);sns.histplot(skew_left_norm,kde=True, color ='red',ax=ax[0]) # plot for heavy tailed distributionfig, ax = plt.subplots(1, 2, figsize=(12, 7))sm.ProbPlot(heavy_tailed_norm).qqplot(line='s',color ='green', ax=ax[1]);sns.histplot(heavy_tailed_norm,kde=True, color ='green',ax=ax[0])sns.histplot(standard_norm,kde=True, color ='red',ax=ax[0]) Standard Normal Right Skewed Left-Skewed Heavy-tailed (see axis values) NIST handbook Data Visualization ML-EDA ML-plots Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between Informed and Uninformed Search in AI Deploy Machine Learning Model using Flask Support Vector Machine Algorithm Types of Environments in AI k-nearest neighbor algorithm in Python 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": 23953, "s": 23925, "text": "\n22 Jan, 2021" }, { "code": null, "e": 24156, "s": 23953, "text": "The probability plot is a way of visually comparing the data coming from different distributions. These data can be of empirical dataset or theoretical dataset. The probability plot can be of two types:" }, { "code": null, "e": 24362, "s": 24156, "text": "P-P plot: The (Probability-to-Probability) p-p plot is the way to visualize the comparing of cumulative distribution function (CDFs) of the two distributions (empirical and theoretical) against each other." }, { "code": null, "e": 24724, "s": 24362, "text": "Q-Q plot: The q-q (Quantile-to-Quantile) plot is used to compare the quantiles of two distributions. The quantiles can be defined as continuous intervals with equal probabilities or dividing the samples between a similar way The distributions may be theoretical or sample distributions from a process, etc. The normal probability plot is a case of the q-q plot." }, { "code": null, "e": 25222, "s": 24724, "text": "Normal Probability plot: The normal probability plot is a way of knowing whether the dataset is normally distributed or not. In this plot, data is plotted against the theoretical normal distribution plot in a way such that if a given dataset is normally distributed it should form an approximate straight line. The normal probability plot is a case of the probability plot (more specifically Q-Q plot). This plot is commonly used in the industry for finding the deviation from the normal process. " }, { "code": null, "e": 25274, "s": 25222, "text": "The normal probability plot has the following axis." }, { "code": null, "e": 25323, "s": 25274, "text": "Horizontal Axis: Normal-order statistic medians." }, { "code": null, "e": 25360, "s": 25323, "text": "Vertical Axis: Order response values" }, { "code": null, "e": 25410, "s": 25360, "text": "The order response variable can be calculated as:" }, { "code": null, "e": 25659, "s": 25410, "text": "Where Ui is the uniform order median statistics and G is the percent point function of normal distribution. It is the inverse of the cumulative distribution function. i.e given probability distribution, we want the cumulative distribution function." }, { "code": null, "e": 25720, "s": 25659, "text": "The uniform order statistics medians can be approximated by:" }, { "code": null, "e": 25810, "s": 25720, "text": "The underlying assumptions for a measurement process that the data should have following " }, { "code": null, "e": 25826, "s": 25810, "text": "Random numbers." }, { "code": null, "e": 25852, "s": 25826, "text": "From fixed distributions." }, { "code": null, "e": 25872, "s": 25852, "text": "With fixed location" }, { "code": null, "e": 25892, "s": 25872, "text": "With a fixed scale." }, { "code": null, "e": 25963, "s": 25892, "text": "The normal probability plot is used to answer the following questions:" }, { "code": null, "e": 25993, "s": 25963, "text": "Is Data normally distributed?" }, { "code": null, "e": 26036, "s": 25993, "text": "If not, what is the nature of distribution" }, { "code": null, "e": 26247, "s": 26036, "text": "In this implementation, we will be using statsmodels python library and seaborn library for visualizing different plots. These libraries are pre-installed in colab, but for local environment using pip install. " }, { "code": null, "e": 26255, "s": 26247, "text": "Python3" }, { "code": "# imports import numpy as npimport matplotlib.pyplot as pltimport seaborn as snsimport scipy.stats as scimport statsmodels.graphics.gofplots as sm # define distributionssample_size = 10000 standard_norm = np.random.normal(size=sample_size)heavy_tailed_norm = np.random.normal(loc=0, scale=2, size=sample_size)skewed_norm = sc.skewnorm.rvs(a=5, size=sample_size)skew_left_norm = sc.skewnorm.rvs(a=-5, size=sample_size) # plots for standard distributionfig, ax = plt.subplots(1, 2, figsize=(12, 7))sns.histplot(standard_norm,kde=True, color ='blue',ax=ax[0])sm.ProbPlot(standard_norm).qqplot(line='s', ax=ax[1]) # plot for right-tailed distributionfig, ax = plt.subplots(1, 2, figsize=(12, 7))sm.ProbPlot(skewed_norm).qqplot(line='s', ax=ax[1]);sns.histplot(skewed_norm,kde=True, color ='blue',ax=ax[0]) # plot for left-tailed distributionfig, ax = plt.subplots(1, 2, figsize=(12, 7))sm.ProbPlot(skew_left_norm).qqplot(line='s',color='red', ax=ax[1]);sns.histplot(skew_left_norm,kde=True, color ='red',ax=ax[0]) # plot for heavy tailed distributionfig, ax = plt.subplots(1, 2, figsize=(12, 7))sm.ProbPlot(heavy_tailed_norm).qqplot(line='s',color ='green', ax=ax[1]);sns.histplot(heavy_tailed_norm,kde=True, color ='green',ax=ax[0])sns.histplot(standard_norm,kde=True, color ='red',ax=ax[0])", "e": 27551, "s": 26255, "text": null }, { "code": null, "e": 27567, "s": 27551, "text": "Standard Normal" }, { "code": null, "e": 27580, "s": 27567, "text": "Right Skewed" }, { "code": null, "e": 27592, "s": 27580, "text": "Left-Skewed" }, { "code": null, "e": 27623, "s": 27592, "text": "Heavy-tailed (see axis values)" }, { "code": null, "e": 27637, "s": 27623, "text": "NIST handbook" }, { "code": null, "e": 27656, "s": 27637, "text": "Data Visualization" }, { "code": null, "e": 27663, "s": 27656, "text": "ML-EDA" }, { "code": null, "e": 27672, "s": 27663, "text": "ML-plots" }, { "code": null, "e": 27689, "s": 27672, "text": "Machine Learning" }, { "code": null, "e": 27696, "s": 27689, "text": "Python" }, { "code": null, "e": 27713, "s": 27696, "text": "Machine Learning" }, { "code": null, "e": 27811, "s": 27713, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27820, "s": 27811, "text": "Comments" }, { "code": null, "e": 27833, "s": 27820, "text": "Old Comments" }, { "code": null, "e": 27889, "s": 27833, "text": "Difference between Informed and Uninformed Search in AI" }, { "code": null, "e": 27931, "s": 27889, "text": "Deploy Machine Learning Model using Flask" }, { "code": null, "e": 27964, "s": 27931, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 27992, "s": 27964, "text": "Types of Environments in AI" }, { "code": null, "e": 28031, "s": 27992, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 28059, "s": 28031, "text": "Read JSON file using Python" }, { "code": null, "e": 28109, "s": 28059, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28131, "s": 28109, "text": "Python map() function" } ]
How to center a popup window on screen using JavaScript?
To center a popup window on the screen, you can try to run the following code Live Demo <!DOCTYPE html> <html> <body> <script> function myPopup(myURL, title, myWidth, myHeight) { var left = (screen.width - myWidth) / 2; var top = (screen.height - myHeight) / 4; var myWindow = window.open(myURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + myWidth + ', height=' + myHeight + ', top=' + top + ', left=' + left); } </script> <button onclick=" myPopup ('http://www.qries.com', 'web', 1050, 550);">Open Qries.com</button> </body> </html>
[ { "code": null, "e": 1140, "s": 1062, "text": "To center a popup window on the screen, you can try to run the following code" }, { "code": null, "e": 1150, "s": 1140, "text": "Live Demo" }, { "code": null, "e": 1757, "s": 1150, "text": "<!DOCTYPE html>\n<html>\n <body>\n <script>\n function myPopup(myURL, title, myWidth, myHeight) {\n var left = (screen.width - myWidth) / 2;\n var top = (screen.height - myHeight) / 4;\n var myWindow = window.open(myURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + myWidth + ', height=' + myHeight + ', top=' + top + ', left=' + left);\n }\n </script>\n <button onclick=\" myPopup ('http://www.qries.com', 'web', 1050, 550);\">Open Qries.com</button>\n </body>\n</html>" } ]
Count of sub-arrays with odd product - GeeksforGeeks
26 Apr, 2021 Given an integer array arr[] of size N, the task is to count the number of sub-arrays that have an odd product.Examples: Input : arr[] = {5, 1, 2, 3, 4} Output : 4 Explanation: The sub-arrays with odd product are- {5}, {1}, {3}, {5, 1}. Hence the count is 4.Input : arr[] = {12, 15, 7, 3, 25, 6, 2, 1, 1, 7} Output : 16 Naive Approach: A simple solution is to calculate the product of every sub-array and check whether it is odd or not and calculate the count accordingly. Time Complexity: O(N2)Efficient Approach: An odd product is possible only by the product of odd numbers. Thus, for every K continuous odd numbers in the array, the count of sub-arrays with the odd product increases by K*(K+1)/2. One way of counting continuous odd numbers is to calculate the difference between the indexes of every two consecutive even numbers and subtract it by 1. For the calculation, -1 and N are considered as indexes of even numbers. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to find the count of// sub-arrays with odd product#include <bits/stdc++.h>using namespace std; // Function that returns the count of// sub-arrays with odd productint countSubArrayWithOddProduct(int* A, int N){ // Initialize the count variable int count = 0; // Initialize variable to store the // last index with even number int last = -1; // Initialize variable to store // count of continuous odd numbers int K = 0; // Loop through the array for (int i = 0; i < N; i++) { // Check if the number // is even or not if (A[i] % 2 == 0) { // Calculate count of continuous // odd numbers K = (i - last - 1); // Increase the count of sub-arrays // with odd product count += (K * (K + 1) / 2); // Store the index of last // even number last = i; } } // N considered as index of // even number K = (N - last - 1); count += (K * (K + 1) / 2); return count;} // Driver Codeint main(){ int arr[] = { 12, 15, 7, 3, 25, 6, 2, 1, 1, 7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << countSubArrayWithOddProduct(arr, n); return 0;} // Java program to find the count of// sub-arrays with odd productclass GFG { // Function that returns the count of// sub-arrays with odd productstatic int countSubArrayWithOddProduct(int A[], int N){ // Initialize the count variable int count = 0; // Initialize variable to store the // last index with even number int last = -1; // Initialize variable to store // count of continuous odd numbers int K = 0; // Loop through the array for(int i = 0; i < N; i++) { // Check if the number // is even or not if (A[i] % 2 == 0) { // Calculate count of continuous // odd numbers K = (i - last - 1); // Increase the count of sub-arrays // with odd product count += (K * (K + 1) / 2); // Store the index of last // even number last = i; } } // N considered as index of // even number K = (N - last - 1); count += (K * (K + 1) / 2); return count;} // Driver Codepublic static void main(String args[]){ int arr[] = { 12, 15, 7, 3, 25, 6, 2, 1, 1, 7 }; int n = arr.length; // Function call System.out.println(countSubArrayWithOddProduct(arr, n));}} // This code is contributed by rutvik_56 # Python3 program to find the count of# sub-arrays with odd product # Function that returns the count of# sub-arrays with odd productdef countSubArrayWithOddProduct(A, N): # Initialize the count variable count = 0 # Initialize variable to store the # last index with even number last = -1 # Initialize variable to store # count of continuous odd numbers K = 0 # Loop through the array for i in range(N): # Check if the number # is even or not if (A[i] % 2 == 0): # Calculate count of continuous # odd numbers K = (i - last - 1) # Increase the count of sub-arrays # with odd product count += (K * (K + 1) / 2) # Store the index of last # even number last = i # N considered as index of # even number K = (N - last - 1) count += (K * (K + 1) / 2) return count # Driver Codeif __name__ == '__main__': arr = [ 12, 15, 7, 3, 25, 6, 2, 1, 1, 7 ] n = len(arr) # Function call print(int(countSubArrayWithOddProduct(arr, n))) # This code is contributed by Bhupendra_Singh // C# program to find the count of// sub-arrays with odd productusing System;class GFG{ // Function that returns the count of// sub-arrays with odd product static int countSubArrayWithOddProduct(int[] A, int N){ // Initialize the count variable int count = 0; // Initialize variable to store the // last index with even number int last = -1; // Initialize variable to store // count of continuous odd numbers int K = 0; // Loop through the array for(int i = 0; i < N; i++) { // Check if the number // is even or not if (A[i] % 2 == 0) { // Calculate count of continuous // odd numbers K = (i - last - 1); // Increase the count of sub-arrays // with odd product count += (K * (K + 1) / 2); // Store the index of last // even number last = i; } } // N considered as index of // even number K = (N - last - 1); count += (K * (K + 1) / 2); return count;} // Driver codestatic void Main(){ int[] arr = { 12, 15, 7, 3, 25, 6, 2, 1, 1, 7 }; int n = arr.Length; // Function call Console.WriteLine(countSubArrayWithOddProduct(arr, n));}} // This code is contributed by divyeshrabadiya07 <script>// Javascript program to find the count of// sub-arrays with odd product // Function that returns the count of// sub-arrays with odd productfunction countSubArrayWithOddProduct(A, N){ // Initialize the count variable var count = 0; // Initialize variable to store the // last index with even number var last = -1; // Initialize variable to store // count of continuous odd numbers var K = 0; // Loop through the array for (var i = 0; i < N; i++) { // Check if the number // is even or not if (A[i] % 2 == 0) { // Calculate count of continuous // odd numbers K = (i - last - 1); // Increase the count of sub-arrays // with odd product count += (K * (K + 1) / 2); // Store the index of last // even number last = i; } } // N considered as index of // even number K = (N - last - 1); count += (K * (K + 1) / 2); return count;} // Driver Codevar arr = [ 12, 15, 7, 3, 25, 6, 2, 1, 1, 7 ];var n = arr.length; // Function calldocument.write( countSubArrayWithOddProduct(arr, n)); // This code is contributed by rrrtnx.</script> 16 Time Complexity: O(N) Auxiliary Space: O(1) bgangwar59 rutvik_56 divyeshrabadiya07 rrrtnx Maths subarray Arrays Competitive Programming Mathematical Arrays Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stack Data Structure (Introduction and Program) Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Introduction to Arrays Linear Search Practice for cracking any coding interview Competitive Programming - A Complete Guide Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Top 10 Algorithms and Data Structures for Competitive Programming
[ { "code": null, "e": 25162, "s": 25134, "text": "\n26 Apr, 2021" }, { "code": null, "e": 25285, "s": 25162, "text": "Given an integer array arr[] of size N, the task is to count the number of sub-arrays that have an odd product.Examples: " }, { "code": null, "e": 25486, "s": 25285, "text": "Input : arr[] = {5, 1, 2, 3, 4} Output : 4 Explanation: The sub-arrays with odd product are- {5}, {1}, {3}, {5, 1}. Hence the count is 4.Input : arr[] = {12, 15, 7, 3, 25, 6, 2, 1, 1, 7} Output : 16 " }, { "code": null, "e": 26149, "s": 25488, "text": "Naive Approach: A simple solution is to calculate the product of every sub-array and check whether it is odd or not and calculate the count accordingly. Time Complexity: O(N2)Efficient Approach: An odd product is possible only by the product of odd numbers. Thus, for every K continuous odd numbers in the array, the count of sub-arrays with the odd product increases by K*(K+1)/2. One way of counting continuous odd numbers is to calculate the difference between the indexes of every two consecutive even numbers and subtract it by 1. For the calculation, -1 and N are considered as indexes of even numbers. Below is the implementation of the above approach: " }, { "code": null, "e": 26153, "s": 26149, "text": "C++" }, { "code": null, "e": 26158, "s": 26153, "text": "Java" }, { "code": null, "e": 26166, "s": 26158, "text": "Python3" }, { "code": null, "e": 26169, "s": 26166, "text": "C#" }, { "code": null, "e": 26180, "s": 26169, "text": "Javascript" }, { "code": "// C++ program to find the count of// sub-arrays with odd product#include <bits/stdc++.h>using namespace std; // Function that returns the count of// sub-arrays with odd productint countSubArrayWithOddProduct(int* A, int N){ // Initialize the count variable int count = 0; // Initialize variable to store the // last index with even number int last = -1; // Initialize variable to store // count of continuous odd numbers int K = 0; // Loop through the array for (int i = 0; i < N; i++) { // Check if the number // is even or not if (A[i] % 2 == 0) { // Calculate count of continuous // odd numbers K = (i - last - 1); // Increase the count of sub-arrays // with odd product count += (K * (K + 1) / 2); // Store the index of last // even number last = i; } } // N considered as index of // even number K = (N - last - 1); count += (K * (K + 1) / 2); return count;} // Driver Codeint main(){ int arr[] = { 12, 15, 7, 3, 25, 6, 2, 1, 1, 7 }; int n = sizeof(arr) / sizeof(arr[0]); // Function call cout << countSubArrayWithOddProduct(arr, n); return 0;}", "e": 27449, "s": 26180, "text": null }, { "code": "// Java program to find the count of// sub-arrays with odd productclass GFG { // Function that returns the count of// sub-arrays with odd productstatic int countSubArrayWithOddProduct(int A[], int N){ // Initialize the count variable int count = 0; // Initialize variable to store the // last index with even number int last = -1; // Initialize variable to store // count of continuous odd numbers int K = 0; // Loop through the array for(int i = 0; i < N; i++) { // Check if the number // is even or not if (A[i] % 2 == 0) { // Calculate count of continuous // odd numbers K = (i - last - 1); // Increase the count of sub-arrays // with odd product count += (K * (K + 1) / 2); // Store the index of last // even number last = i; } } // N considered as index of // even number K = (N - last - 1); count += (K * (K + 1) / 2); return count;} // Driver Codepublic static void main(String args[]){ int arr[] = { 12, 15, 7, 3, 25, 6, 2, 1, 1, 7 }; int n = arr.length; // Function call System.out.println(countSubArrayWithOddProduct(arr, n));}} // This code is contributed by rutvik_56", "e": 28791, "s": 27449, "text": null }, { "code": "# Python3 program to find the count of# sub-arrays with odd product # Function that returns the count of# sub-arrays with odd productdef countSubArrayWithOddProduct(A, N): # Initialize the count variable count = 0 # Initialize variable to store the # last index with even number last = -1 # Initialize variable to store # count of continuous odd numbers K = 0 # Loop through the array for i in range(N): # Check if the number # is even or not if (A[i] % 2 == 0): # Calculate count of continuous # odd numbers K = (i - last - 1) # Increase the count of sub-arrays # with odd product count += (K * (K + 1) / 2) # Store the index of last # even number last = i # N considered as index of # even number K = (N - last - 1) count += (K * (K + 1) / 2) return count # Driver Codeif __name__ == '__main__': arr = [ 12, 15, 7, 3, 25, 6, 2, 1, 1, 7 ] n = len(arr) # Function call print(int(countSubArrayWithOddProduct(arr, n))) # This code is contributed by Bhupendra_Singh", "e": 29971, "s": 28791, "text": null }, { "code": "// C# program to find the count of// sub-arrays with odd productusing System;class GFG{ // Function that returns the count of// sub-arrays with odd product static int countSubArrayWithOddProduct(int[] A, int N){ // Initialize the count variable int count = 0; // Initialize variable to store the // last index with even number int last = -1; // Initialize variable to store // count of continuous odd numbers int K = 0; // Loop through the array for(int i = 0; i < N; i++) { // Check if the number // is even or not if (A[i] % 2 == 0) { // Calculate count of continuous // odd numbers K = (i - last - 1); // Increase the count of sub-arrays // with odd product count += (K * (K + 1) / 2); // Store the index of last // even number last = i; } } // N considered as index of // even number K = (N - last - 1); count += (K * (K + 1) / 2); return count;} // Driver codestatic void Main(){ int[] arr = { 12, 15, 7, 3, 25, 6, 2, 1, 1, 7 }; int n = arr.Length; // Function call Console.WriteLine(countSubArrayWithOddProduct(arr, n));}} // This code is contributed by divyeshrabadiya07", "e": 31373, "s": 29971, "text": null }, { "code": "<script>// Javascript program to find the count of// sub-arrays with odd product // Function that returns the count of// sub-arrays with odd productfunction countSubArrayWithOddProduct(A, N){ // Initialize the count variable var count = 0; // Initialize variable to store the // last index with even number var last = -1; // Initialize variable to store // count of continuous odd numbers var K = 0; // Loop through the array for (var i = 0; i < N; i++) { // Check if the number // is even or not if (A[i] % 2 == 0) { // Calculate count of continuous // odd numbers K = (i - last - 1); // Increase the count of sub-arrays // with odd product count += (K * (K + 1) / 2); // Store the index of last // even number last = i; } } // N considered as index of // even number K = (N - last - 1); count += (K * (K + 1) / 2); return count;} // Driver Codevar arr = [ 12, 15, 7, 3, 25, 6, 2, 1, 1, 7 ];var n = arr.length; // Function calldocument.write( countSubArrayWithOddProduct(arr, n)); // This code is contributed by rrrtnx.</script>", "e": 32622, "s": 31373, "text": null }, { "code": null, "e": 32625, "s": 32622, "text": "16" }, { "code": null, "e": 32672, "s": 32627, "text": "Time Complexity: O(N) Auxiliary Space: O(1) " }, { "code": null, "e": 32683, "s": 32672, "text": "bgangwar59" }, { "code": null, "e": 32693, "s": 32683, "text": "rutvik_56" }, { "code": null, "e": 32711, "s": 32693, "text": "divyeshrabadiya07" }, { "code": null, "e": 32718, "s": 32711, "text": "rrrtnx" }, { "code": null, "e": 32724, "s": 32718, "text": "Maths" }, { "code": null, "e": 32733, "s": 32724, "text": "subarray" }, { "code": null, "e": 32740, "s": 32733, "text": "Arrays" }, { "code": null, "e": 32764, "s": 32740, "text": "Competitive Programming" }, { "code": null, "e": 32777, "s": 32764, "text": "Mathematical" }, { "code": null, "e": 32784, "s": 32777, "text": "Arrays" }, { "code": null, "e": 32797, "s": 32784, "text": "Mathematical" }, { "code": null, "e": 32895, "s": 32797, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32943, "s": 32895, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 32987, "s": 32943, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 33019, "s": 32987, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 33042, "s": 33019, "text": "Introduction to Arrays" }, { "code": null, "e": 33056, "s": 33042, "text": "Linear Search" }, { "code": null, "e": 33099, "s": 33056, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 33142, "s": 33099, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 33183, "s": 33142, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 33210, "s": 33183, "text": "Modulo 10^9+7 (1000000007)" } ]
How to display progress bar while loading a url to webView in Android?
This example demonstrates how do I display progress bar while loading a url to webview in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <ProgressBar android:id="@+id/progressBar" android:max="3" android:progress="100" style="?android:attr/progressBarStyleLarge" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerInParent="true" /> <WebView android:id="@+id/webView" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/progressBar" android:layout_centerHorizontal="true" /> </RelativeLayout> Step 3 − Add the following code to src/MainActivity.java import android.graphics.Bitmap; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.webkit.WebView; import android.widget.ProgressBar; public class MainActivity extends AppCompatActivity { WebView webview; ProgressBar progressBar; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); webview = findViewById(R.id.webView); progressBar = findViewById(R.id.progressBar); webview.setWebViewClient(new WebViewClient()); webview.loadUrl("https://www.google.com"); } public class WebViewClient extends android.webkit.WebViewClient { @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { super.onPageStarted(view, url, favicon); } @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { view.loadUrl(url); return true; } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); progressBar.setVisibility(View.GONE); } } } 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.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 – Click here to download the project code.
[ { "code": null, "e": 1161, "s": 1062, "text": "This example demonstrates how do I display progress bar while loading a url to webview in android." }, { "code": null, "e": 1290, "s": 1161, "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": 1355, "s": 1290, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2200, "s": 1355, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <ProgressBar\n android:id=\"@+id/progressBar\"\n android:max=\"3\"\n android:progress=\"100\"\n style=\"?android:attr/progressBarStyleLarge\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerInParent=\"true\" />\n <WebView\n android:id=\"@+id/webView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_below=\"@+id/progressBar\"\n android:layout_centerHorizontal=\"true\" />\n</RelativeLayout>" }, { "code": null, "e": 2257, "s": 2200, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3466, "s": 2257, "text": "import android.graphics.Bitmap;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.webkit.WebView;\nimport android.widget.ProgressBar;\npublic class MainActivity extends AppCompatActivity {\n WebView webview;\n ProgressBar progressBar;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n webview = findViewById(R.id.webView);\n progressBar = findViewById(R.id.progressBar);\n webview.setWebViewClient(new WebViewClient());\n webview.loadUrl(\"https://www.google.com\");\n }\n public class WebViewClient extends android.webkit.WebViewClient {\n @Override\n public void onPageStarted(WebView view, String url, Bitmap favicon) {\n super.onPageStarted(view, url, favicon);\n }\n @Override\n public boolean shouldOverrideUrlLoading(WebView view, String url) {\n view.loadUrl(url);\n return true;\n }\n @Override\n public void onPageFinished(WebView view, String url) {\n super.onPageFinished(view, url);\n progressBar.setVisibility(View.GONE);\n }\n }\n}" }, { "code": null, "e": 3521, "s": 3466, "text": "Step 4 - Add the following code to androidManifest.xml" }, { "code": null, "e": 4259, "s": 3521, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <uses-permission 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 android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 4606, "s": 4259, "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 –" }, { "code": null, "e": 4647, "s": 4606, "text": "Click here to download the project code." } ]
Android - Time Picker
Android Time Picker allows you to select the time of day in either 24 hour or AM/PM mode. The time consists of hours, minutes and clock format. Android provides this functionality through TimePicker class. In order to use TimePicker class, you have to first define the TimePicker component in your activity.xml. It is define as below − <TimePicker android:id="@+id/timePicker1" android:layout_width="wrap_content" android:layout_height="wrap_content" /> After that you have to create an object of TimePicker class and get a reference of the above defined xml component. Its syntax is given below. import android.widget.TimePicker; private TimePicker timePicker1; timePicker1 = (TimePicker) findViewById(R.id.timePicker1); In order to get the time selected by the user on the screen, you will use getCurrentHour() and getCurrentMinute() method of the TimePicker Class. Their syntax is given below. int hour = timePicker1.getCurrentHour(); int min = timePicker1.getCurrentMinute(); Apart form these methods, there are other methods in the API that gives more control over TimePicker Component. They are listed below. is24HourView() This method returns true if this is in 24 hour view else false isEnabled() This method returns the enabled status for this view setCurrentHour(Integer currentHour) This method sets the current hour setCurrentMinute(Integer currentMinute) This method sets the current minute setEnabled(boolean enabled) This method set the enabled state of this view setIs24HourView(Boolean is24HourView) This method set whether in 24 hour or AM/PM mode setOnTimeChangedListener(TimePicker.OnTimeChangedListener onTimeChangedListener) This method Set the callback that indicates the time has been adjusted by the user Here is an example demonstrating the use of TimePicker class. It creates a basic Time Picker application that allows you to set the time using TimePicker Widget To experiment with this example , you can run this on an actual device or in an emulator. Following is the content of the modified main activity file src/com.example.timepicker/MainActivity.java. package com.example.timepicker; import java.util.Calendar; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.widget.TextView; import android.widget.TimePicker; public class MainActivity extends Activity { private TimePicker timePicker1; private TextView time; private Calendar calendar; private String format = ""; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); timePicker1 = (TimePicker) findViewById(R.id.timePicker1); time = (TextView) findViewById(R.id.textView1); calendar = Calendar.getInstance(); int hour = calendar.get(Calendar.HOUR_OF_DAY); int min = calendar.get(Calendar.MINUTE); showTime(hour, min); } public void setTime(View view) { int hour = timePicker1.getCurrentHour(); int min = timePicker1.getCurrentMinute(); showTime(hour, min); } public void showTime(int hour, int min) { if (hour == 0) { hour += 12; format = "AM"; } else if (hour == 12) { format = "PM"; } else if (hour > 12) { hour -= 12; format = "PM"; } else { format = "AM"; } time.setText(new StringBuilder().append(hour).append(" : ").append(min) .append(" ").append(format)); } } Following is the modified content of the xml res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TextView android:id="@+id/textView2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:text="@string/time_pick" android:textAppearance="?android:attr/textAppearanceMedium" /> <Button android:id="@+id/set_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:layout_centerHorizontal="true" android:layout_marginBottom="180dp" android:onClick="setTime" android:text="@string/time_save" /> <TimePicker android:id="@+id/timePicker1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_above="@+id/set_button" android:layout_centerHorizontal="true" android:layout_marginBottom="24dp" /> <TextView android:id="@+id/textView3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/timePicker1" android:layout_alignTop="@+id/set_button" android:layout_marginTop="67dp" android:text="@string/time_current" android:textAppearance="?android:attr/textAppearanceMedium" /> <TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView3" android:layout_centerHorizontal="true" android:layout_marginTop="50dp" android:text="@string/time_selected" android:textAppearance="?android:attr/textAppearanceMedium" /> </RelativeLayout> Following is the content of the res/values/string.xml. <?xml version="1.0" encoding="utf-8"?> <resources> <string name="app_name">TimePicker</string> <string name="action_settings">Settings</string> <string name="time_picker_example">Time Picker Example</string> <string name="time_pick">Pick the time and press save button</string> <string name="time_save">Save</string> <string name="time_selected"></string> <string name="time_current">The Time is:</string> </resources> Let's try to run our TimePicker application we just modified. I assume you had created your AVD while doing environment setup. To run the app from Android studio, open one of your project's activity files and click Run icon from the toolbar. Android Studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
[ { "code": null, "e": 3947, "s": 3741, "text": "Android Time Picker allows you to select the time of day in either 24 hour or AM/PM mode. The time consists of hours, minutes and clock format. Android provides this functionality through TimePicker class." }, { "code": null, "e": 4077, "s": 3947, "text": "In order to use TimePicker class, you have to first define the TimePicker component in your activity.xml. It is define as below −" }, { "code": null, "e": 4204, "s": 4077, "text": "<TimePicker\n android:id=\"@+id/timePicker1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />" }, { "code": null, "e": 4347, "s": 4204, "text": "After that you have to create an object of TimePicker class and get a reference of the above defined xml component. Its syntax is given below." }, { "code": null, "e": 4473, "s": 4347, "text": "import android.widget.TimePicker;\nprivate TimePicker timePicker1;\ntimePicker1 = (TimePicker) findViewById(R.id.timePicker1);\t" }, { "code": null, "e": 4648, "s": 4473, "text": "In order to get the time selected by the user on the screen, you will use getCurrentHour() and getCurrentMinute() method of the TimePicker Class. Their syntax is given below." }, { "code": null, "e": 4731, "s": 4648, "text": "int hour = timePicker1.getCurrentHour();\nint min = timePicker1.getCurrentMinute();" }, { "code": null, "e": 4866, "s": 4731, "text": "Apart form these methods, there are other methods in the API that gives more control over TimePicker Component. They are listed below." }, { "code": null, "e": 4881, "s": 4866, "text": "is24HourView()" }, { "code": null, "e": 4944, "s": 4881, "text": "This method returns true if this is in 24 hour view else false" }, { "code": null, "e": 4956, "s": 4944, "text": "isEnabled()" }, { "code": null, "e": 5009, "s": 4956, "text": "This method returns the enabled status for this view" }, { "code": null, "e": 5045, "s": 5009, "text": "setCurrentHour(Integer currentHour)" }, { "code": null, "e": 5079, "s": 5045, "text": "This method sets the current hour" }, { "code": null, "e": 5119, "s": 5079, "text": "setCurrentMinute(Integer currentMinute)" }, { "code": null, "e": 5155, "s": 5119, "text": "This method sets the current minute" }, { "code": null, "e": 5183, "s": 5155, "text": "setEnabled(boolean enabled)" }, { "code": null, "e": 5230, "s": 5183, "text": "This method set the enabled state of this view" }, { "code": null, "e": 5268, "s": 5230, "text": "setIs24HourView(Boolean is24HourView)" }, { "code": null, "e": 5317, "s": 5268, "text": "This method set whether in 24 hour or AM/PM mode" }, { "code": null, "e": 5398, "s": 5317, "text": "setOnTimeChangedListener(TimePicker.OnTimeChangedListener onTimeChangedListener)" }, { "code": null, "e": 5481, "s": 5398, "text": "This method Set the callback that indicates the time has been adjusted by the user" }, { "code": null, "e": 5642, "s": 5481, "text": "Here is an example demonstrating the use of TimePicker class. It creates a basic Time Picker application that allows you to set the time using TimePicker Widget" }, { "code": null, "e": 5732, "s": 5642, "text": "To experiment with this example , you can run this on an actual device or in an emulator." }, { "code": null, "e": 5838, "s": 5732, "text": "Following is the content of the modified main activity file src/com.example.timepicker/MainActivity.java." }, { "code": null, "e": 7285, "s": 5838, "text": "package com.example.timepicker;\n\nimport java.util.Calendar;\n\nimport android.app.Activity;\nimport android.os.Bundle;\nimport android.view.Menu;\nimport android.view.View;\nimport android.widget.TextView;\nimport android.widget.TimePicker;\n\npublic class MainActivity extends Activity {\n private TimePicker timePicker1;\n private TextView time;\n private Calendar calendar;\n private String format = \"\";\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n \n timePicker1 = (TimePicker) findViewById(R.id.timePicker1);\n time = (TextView) findViewById(R.id.textView1);\n calendar = Calendar.getInstance();\n \n int hour = calendar.get(Calendar.HOUR_OF_DAY);\n int min = calendar.get(Calendar.MINUTE);\n showTime(hour, min);\n }\n\n public void setTime(View view) {\n int hour = timePicker1.getCurrentHour();\n int min = timePicker1.getCurrentMinute();\n showTime(hour, min);\n }\n\n public void showTime(int hour, int min) {\n if (hour == 0) {\n hour += 12;\n format = \"AM\";\n } else if (hour == 12) {\n format = \"PM\";\n } else if (hour > 12) {\n hour -= 12;\n format = \"PM\";\n } else {\n format = \"AM\";\n }\n\t\t\n time.setText(new StringBuilder().append(hour).append(\" : \").append(min)\n .append(\" \").append(format));\n }\n\n\n}" }, { "code": null, "e": 7360, "s": 7285, "text": "Following is the modified content of the xml res/layout/activity_main.xml." }, { "code": null, "e": 9609, "s": 7360, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\"\n android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n tools:context=\".MainActivity\" >\n \n <TextView\n android:id=\"@+id/textView2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:text=\"@string/time_pick\"\n android:textAppearance=\"?android:attr/textAppearanceMedium\" />\n \n <Button\n android:id=\"@+id/set_button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginBottom=\"180dp\"\n android:onClick=\"setTime\"\n android:text=\"@string/time_save\" />\n \n <TimePicker\n android:id=\"@+id/timePicker1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_above=\"@+id/set_button\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginBottom=\"24dp\" />\n \n <TextView\n android:id=\"@+id/textView3\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignLeft=\"@+id/timePicker1\"\n android:layout_alignTop=\"@+id/set_button\"\n android:layout_marginTop=\"67dp\"\n android:text=\"@string/time_current\"\n android:textAppearance=\"?android:attr/textAppearanceMedium\" />\n \n <TextView\n android:id=\"@+id/textView1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@+id/textView3\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"50dp\"\n android:text=\"@string/time_selected\"\n android:textAppearance=\"?android:attr/textAppearanceMedium\" />\n\n</RelativeLayout>" }, { "code": null, "e": 9664, "s": 9609, "text": "Following is the content of the res/values/string.xml." }, { "code": null, "e": 10101, "s": 9664, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n<string name=\"app_name\">TimePicker</string>\n <string name=\"action_settings\">Settings</string>\n <string name=\"time_picker_example\">Time Picker Example</string>\n <string name=\"time_pick\">Pick the time and press save button</string>\n <string name=\"time_save\">Save</string>\n <string name=\"time_selected\"></string>\n <string name=\"time_current\">The Time is:</string>\n</resources>" } ]
NLP | How tokenizing text, sentence, words works
05 Nov, 2021 Natural Language Processing (NLP) is a subfield of computer science, artificial intelligence, information engineering, and human-computer interaction. This field focuses on how to program computers to process and analyze large amounts of natural language data. It is difficult to perform as the process of reading and understanding languages is far more complex than it seems at first glance. Tokenization is the process of tokenizing or splitting a string, text into a list of tokens. One can think of token as parts like a word is a token in a sentence, and a sentence is a token in a paragraph. Key points of the article – Text into sentences tokenization Sentences into words tokenization Sentences using regular expressions tokenization Code #1: Sentence Tokenization – Splitting sentences in the paragraph from nltk.tokenize import sent_tokenize text = "Hello everyone. Welcome to GeeksforGeeks. You are studying NLP article"sent_tokenize(text) Output : ['Hello everyone.', 'Welcome to GeeksforGeeks.', 'You are studying NLP article'] How sent_tokenize works ?The sent_tokenize function uses an instance of PunktSentenceTokenizer from the nltk.tokenize.punkt module, which is already been trained and thus very well knows to mark the end and beginning of sentence at what characters and punctuation. Code #2: PunktSentenceTokenizer – When we have huge chunks of data then it is efficient to use it. import nltk.data # Loading PunktSentenceTokenizer using English pickle filetokenizer = nltk.data.load('tokenizers/punkt/PY3/english.pickle') tokenizer.tokenize(text) Output : ['Hello everyone.', 'Welcome to GeeksforGeeks.', 'You are studying NLP article'] Code #3: Tokenize sentence of different language – One can also tokenize sentence from different languages using different pickle file other than English. import nltk.data spanish_tokenizer = nltk.data.load('tokenizers/punkt/PY3/spanish.pickle') text = 'Hola amigo. Estoy bien.'spanish_tokenizer.tokenize(text) Output : ['Hola amigo.', 'Estoy bien.'] Code #4: Word Tokenization – Splitting words in a sentence. from nltk.tokenize import word_tokenize text = "Hello everyone. Welcome to GeeksforGeeks."word_tokenize(text) Output : ['Hello', 'everyone', '.', 'Welcome', 'to', 'GeeksforGeeks', '.'] How word_tokenize works?word_tokenize() function is a wrapper function that calls tokenize() on an instance of the TreebankWordTokenizer class. Code #5: Using TreebankWordTokenizer from nltk.tokenize import TreebankWordTokenizer tokenizer = TreebankWordTokenizer()tokenizer.tokenize(text) Output : ['Hello', 'everyone.', 'Welcome', 'to', 'GeeksforGeeks', '.'] These tokenizers work by separating the words using punctuation and spaces. And as mentioned in the code outputs above, it doesn’t discard the punctuation, allowing a user to decide what to do with the punctuations at the time of pre-processing. Code #6: PunktWordTokenizer – It doen’t separates the punctuation from the words. from nltk.tokenize import PunktWordTokenizer tokenizer = PunktWordTokenizer()tokenizer.tokenize("Let's see how it's working.") Output : ['Let', "'s", 'see', 'how', 'it', "'s", 'working', '.'] Code #6: WordPunctTokenizer – It separates the punctuation from the words. from nltk.tokenize import WordPunctTokenizer tokenizer = WordPunctTokenizer()tokenizer.tokenize("Let's see how it's working.") Output : ['Let', "'", 's', 'see', 'how', 'it', "'", 's', 'working', '.'] Code #7: Using Regular Expression from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer("[\w']+")text = "Let's see how it's working."tokenizer.tokenize(text) Output : ["Let's", 'see', 'how', "it's", 'working'] Code #7: Using Regular Expression from nltk.tokenize import regexp_tokenize text = "Let's see how it's working."regexp_tokenize(text, "[\w']+") Output : ["Let's", 'see', 'how', "it's", 'working'] Akanksha_Rai marcosarcticseal Natural-language-processing Python-nltk Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Getting started with Machine Learning Introduction to Recurrent Neural Network Support Vector Machine Algorithm Random Forest Regression in Python Running Python script on GPU. Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n05 Nov, 2021" }, { "code": null, "e": 447, "s": 54, "text": "Natural Language Processing (NLP) is a subfield of computer science, artificial intelligence, information engineering, and human-computer interaction. This field focuses on how to program computers to process and analyze large amounts of natural language data. It is difficult to perform as the process of reading and understanding languages is far more complex than it seems at first glance." }, { "code": null, "e": 652, "s": 447, "text": "Tokenization is the process of tokenizing or splitting a string, text into a list of tokens. One can think of token as parts like a word is a token in a sentence, and a sentence is a token in a paragraph." }, { "code": null, "e": 680, "s": 652, "text": "Key points of the article –" }, { "code": null, "e": 713, "s": 680, "text": "Text into sentences tokenization" }, { "code": null, "e": 747, "s": 713, "text": "Sentences into words tokenization" }, { "code": null, "e": 796, "s": 747, "text": "Sentences using regular expressions tokenization" }, { "code": null, "e": 866, "s": 796, "text": "Code #1: Sentence Tokenization – Splitting sentences in the paragraph" }, { "code": "from nltk.tokenize import sent_tokenize text = \"Hello everyone. Welcome to GeeksforGeeks. You are studying NLP article\"sent_tokenize(text)", "e": 1006, "s": 866, "text": null }, { "code": null, "e": 1015, "s": 1006, "text": "Output :" }, { "code": null, "e": 1099, "s": 1015, "text": "['Hello everyone.',\n 'Welcome to GeeksforGeeks.',\n 'You are studying NLP article']\n" }, { "code": null, "e": 1463, "s": 1099, "text": "How sent_tokenize works ?The sent_tokenize function uses an instance of PunktSentenceTokenizer from the nltk.tokenize.punkt module, which is already been trained and thus very well knows to mark the end and beginning of sentence at what characters and punctuation. Code #2: PunktSentenceTokenizer – When we have huge chunks of data then it is efficient to use it." }, { "code": "import nltk.data # Loading PunktSentenceTokenizer using English pickle filetokenizer = nltk.data.load('tokenizers/punkt/PY3/english.pickle') tokenizer.tokenize(text)", "e": 1631, "s": 1463, "text": null }, { "code": null, "e": 1640, "s": 1631, "text": "Output :" }, { "code": null, "e": 1724, "s": 1640, "text": "['Hello everyone.',\n 'Welcome to GeeksforGeeks.',\n 'You are studying NLP article']\n" }, { "code": null, "e": 1880, "s": 1724, "text": " Code #3: Tokenize sentence of different language – One can also tokenize sentence from different languages using different pickle file other than English." }, { "code": "import nltk.data spanish_tokenizer = nltk.data.load('tokenizers/punkt/PY3/spanish.pickle') text = 'Hola amigo. Estoy bien.'spanish_tokenizer.tokenize(text)", "e": 2038, "s": 1880, "text": null }, { "code": null, "e": 2047, "s": 2038, "text": "Output :" }, { "code": null, "e": 2081, "s": 2047, "text": "['Hola amigo.', \n 'Estoy bien.']\n" }, { "code": null, "e": 2142, "s": 2081, "text": " Code #4: Word Tokenization – Splitting words in a sentence." }, { "code": "from nltk.tokenize import word_tokenize text = \"Hello everyone. Welcome to GeeksforGeeks.\"word_tokenize(text)", "e": 2253, "s": 2142, "text": null }, { "code": null, "e": 2262, "s": 2253, "text": "Output :" }, { "code": null, "e": 2329, "s": 2262, "text": "['Hello', 'everyone', '.', 'Welcome', 'to', 'GeeksforGeeks', '.']\n" }, { "code": null, "e": 2510, "s": 2329, "text": "How word_tokenize works?word_tokenize() function is a wrapper function that calls tokenize() on an instance of the TreebankWordTokenizer class. Code #5: Using TreebankWordTokenizer" }, { "code": "from nltk.tokenize import TreebankWordTokenizer tokenizer = TreebankWordTokenizer()tokenizer.tokenize(text)", "e": 2619, "s": 2510, "text": null }, { "code": null, "e": 2628, "s": 2619, "text": "Output :" }, { "code": null, "e": 2691, "s": 2628, "text": "['Hello', 'everyone.', 'Welcome', 'to', 'GeeksforGeeks', '.']\n" }, { "code": null, "e": 3019, "s": 2691, "text": "These tokenizers work by separating the words using punctuation and spaces. And as mentioned in the code outputs above, it doesn’t discard the punctuation, allowing a user to decide what to do with the punctuations at the time of pre-processing. Code #6: PunktWordTokenizer – It doen’t separates the punctuation from the words." }, { "code": "from nltk.tokenize import PunktWordTokenizer tokenizer = PunktWordTokenizer()tokenizer.tokenize(\"Let's see how it's working.\")", "e": 3147, "s": 3019, "text": null }, { "code": null, "e": 3156, "s": 3147, "text": "Output :" }, { "code": null, "e": 3213, "s": 3156, "text": "['Let', \"'s\", 'see', 'how', 'it', \"'s\", 'working', '.']\n" }, { "code": null, "e": 3289, "s": 3213, "text": " Code #6: WordPunctTokenizer – It separates the punctuation from the words." }, { "code": "from nltk.tokenize import WordPunctTokenizer tokenizer = WordPunctTokenizer()tokenizer.tokenize(\"Let's see how it's working.\")", "e": 3417, "s": 3289, "text": null }, { "code": null, "e": 3426, "s": 3417, "text": "Output :" }, { "code": null, "e": 3491, "s": 3426, "text": "['Let', \"'\", 's', 'see', 'how', 'it', \"'\", 's', 'working', '.']\n" }, { "code": null, "e": 3526, "s": 3491, "text": " Code #7: Using Regular Expression" }, { "code": "from nltk.tokenize import RegexpTokenizer tokenizer = RegexpTokenizer(\"[\\w']+\")text = \"Let's see how it's working.\"tokenizer.tokenize(text)", "e": 3667, "s": 3526, "text": null }, { "code": null, "e": 3676, "s": 3667, "text": "Output :" }, { "code": null, "e": 3720, "s": 3676, "text": "[\"Let's\", 'see', 'how', \"it's\", 'working']\n" }, { "code": null, "e": 3755, "s": 3720, "text": " Code #7: Using Regular Expression" }, { "code": "from nltk.tokenize import regexp_tokenize text = \"Let's see how it's working.\"regexp_tokenize(text, \"[\\w']+\")", "e": 3866, "s": 3755, "text": null }, { "code": null, "e": 3875, "s": 3866, "text": "Output :" }, { "code": null, "e": 3919, "s": 3875, "text": "[\"Let's\", 'see', 'how', \"it's\", 'working']\n" }, { "code": null, "e": 3932, "s": 3919, "text": "Akanksha_Rai" }, { "code": null, "e": 3949, "s": 3932, "text": "marcosarcticseal" }, { "code": null, "e": 3977, "s": 3949, "text": "Natural-language-processing" }, { "code": null, "e": 3989, "s": 3977, "text": "Python-nltk" }, { "code": null, "e": 4006, "s": 3989, "text": "Machine Learning" }, { "code": null, "e": 4013, "s": 4006, "text": "Python" }, { "code": null, "e": 4030, "s": 4013, "text": "Machine Learning" }, { "code": null, "e": 4128, "s": 4030, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4166, "s": 4128, "text": "Getting started with Machine Learning" }, { "code": null, "e": 4207, "s": 4166, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 4240, "s": 4207, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 4275, "s": 4240, "text": "Random Forest Regression in Python" }, { "code": null, "e": 4305, "s": 4275, "text": "Running Python script on GPU." }, { "code": null, "e": 4333, "s": 4305, "text": "Read JSON file using Python" }, { "code": null, "e": 4355, "s": 4333, "text": "Python map() function" }, { "code": null, "e": 4405, "s": 4355, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4423, "s": 4405, "text": "Python Dictionary" } ]
GATE | GATE-CS-2007 | Question 76
28 Jun, 2021 Suppose the letters a, b, c, d, e, f have probabilities 1/2, 1/4, 1/8, 1/16, 1/32, 1/32 respectively. Which of the following is the Huffman code for the letter a, b, c, d, e, f?(A) 0, 10, 110, 1110, 11110, 11111(B) 11, 10, 011, 010, 001, 000(C) 11, 10, 01, 001, 0001, 0000(D) 110, 100, 010, 000, 001, 111Answer: (A)Explanation: We get the following Huffman Tree after applying Huffman Coding Algorithm. The idea is to keep the least probable characters as low as possible by picking them first. The letters a, b, c, d, e, f have probabilities 1/2, 1/4, 1/8, 1/16, 1/32, 1/32 respectively. 1 / \ / \ 1/2 a(1/2) / \ / \ 1/4 b(1/4) / \ / \ 1/8 c(1/8) / \ / \ 1/16 d(1/16) / \ e f Quiz of this Question GATE-CS-2007 GATE-GATE-CS-2007 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jun, 2021" }, { "code": null, "e": 523, "s": 28, "text": "Suppose the letters a, b, c, d, e, f have probabilities 1/2, 1/4, 1/8, 1/16, 1/32, 1/32 respectively. Which of the following is the Huffman code for the letter a, b, c, d, e, f?(A) 0, 10, 110, 1110, 11110, 11111(B) 11, 10, 011, 010, 001, 000(C) 11, 10, 01, 001, 0001, 0000(D) 110, 100, 010, 000, 001, 111Answer: (A)Explanation: We get the following Huffman Tree after applying Huffman Coding Algorithm. The idea is to keep the least probable characters as low as possible by picking them first." }, { "code": null, "e": 874, "s": 523, "text": "The letters a, b, c, d, e, f have probabilities \n1/2, 1/4, 1/8, 1/16, 1/32, 1/32 respectively. \n\n 1\n / \\\n / \\\n 1/2 a(1/2)\n / \\\n / \\\n 1/4 b(1/4) \n / \\\n / \\\n 1/8 c(1/8) \n / \\\n / \\\n 1/16 d(1/16)\n / \\\n e f" }, { "code": null, "e": 896, "s": 874, "text": "Quiz of this Question" }, { "code": null, "e": 909, "s": 896, "text": "GATE-CS-2007" }, { "code": null, "e": 927, "s": 909, "text": "GATE-GATE-CS-2007" }, { "code": null, "e": 932, "s": 927, "text": "GATE" } ]
PyQt5 – How to create semi transparent window ?
26 Mar, 2020 When we design an application in PyQt5, the main window is used to appear by default the window is opaque, but we can make it transparent as well. we can do this by using setWindowOpacity() method which belongs to the QWidget class. Syntax : setWindowOpacity(0.5) Argument : It takes float value as argument : 0 for completely transparent and 1 for opaque. Action performed : Makes the window transparent. Code : # importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle("Python") self.setWindowOpacity(0.5) # setting the geometry of window self.setGeometry(60, 60, 600, 400) # creating a label widget self.label_1 = QLabel("transparent ", self) # moving position self.label_1.move(100, 100) self.label_1.adjustSize() # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec()) Output : Python-gui Python-PyQt Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n26 Mar, 2020" }, { "code": null, "e": 261, "s": 28, "text": "When we design an application in PyQt5, the main window is used to appear by default the window is opaque, but we can make it transparent as well. we can do this by using setWindowOpacity() method which belongs to the QWidget class." }, { "code": null, "e": 292, "s": 261, "text": "Syntax : setWindowOpacity(0.5)" }, { "code": null, "e": 385, "s": 292, "text": "Argument : It takes float value as argument : 0 for completely transparent and 1 for opaque." }, { "code": null, "e": 434, "s": 385, "text": "Action performed : Makes the window transparent." }, { "code": null, "e": 441, "s": 434, "text": "Code :" }, { "code": "# importing the required libraries from PyQt5.QtCore import * from PyQt5.QtGui import * from PyQt5.QtWidgets import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # set the title self.setWindowTitle(\"Python\") self.setWindowOpacity(0.5) # setting the geometry of window self.setGeometry(60, 60, 600, 400) # creating a label widget self.label_1 = QLabel(\"transparent \", self) # moving position self.label_1.move(100, 100) self.label_1.adjustSize() # show all the widgets self.show() # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())", "e": 1214, "s": 441, "text": null }, { "code": null, "e": 1223, "s": 1214, "text": "Output :" }, { "code": null, "e": 1234, "s": 1223, "text": "Python-gui" }, { "code": null, "e": 1246, "s": 1234, "text": "Python-PyQt" }, { "code": null, "e": 1253, "s": 1246, "text": "Python" } ]
Neon Number
16 Mar, 2022 A neon number is a number where the sum of digits of square of the number is equal to the number. The task is to check and print neon numbers in a range. Examples: Input : 9 Output : Neon Number Explanation: square is 9*9 = 81 and sum of the digits of the square is 9. Input :12 Output : Not a Neon Number Explanation: square is 12*12 = 144 and sum of the digits of the square is 9 (1 + 4 + 4) which is not equal to 12. The implementation is simple, we first compute square of given number, the find sum of digits in the square. C++ Java Python C# PHP Javascript // C/C++ program to check and print// Neon Numbers upto 10000#include <iostream>using namespace std;#include <math.h> int checkNeon(int x){ // storing the square of x int sq = x * x; // calculating the sum of digits // of sq int sum_digits = 0; while (sq != 0) { sum_digits = sum_digits + sq % 10; sq = sq / 10; } return (sum_digits == x);} // Driver Codeint main(void){ // Printing Neon Numbers upto 10000 for (int i = 1; i <= 10000; i++) if (checkNeon(i)) cout << i << " "; } // Java program to check and print// Neon Numbers upto 10000import java.io.*; class GFG { // function to check Neon Number static boolean checkNeon(int x) { // storing the square of x int sq = x * x; // calculating the sum of digits // of sq int sum_digits = 0; while (sq != 0) { sum_digits = sum_digits + sq % 10; sq = sq / 10; } return (sum_digits == x); } // Driver Code public static void main(String args[]) throws IOException { // Printing Neon Numbers upto 10000 for (int i = 1; i <= 10000; i++) if (checkNeon(i)) System.out.print(i + " "); }}// This code is contributed by Nikita Tiwari. # Python program to check and print# Neon Numbers upto 10000 # function to check Neon Numberdef checkNeon (x) : # storing the square of x sq = x * x # calculating the sum of digits # of sq sum_digits = 0 while (sq != 0) : sum_digits = sum_digits + sq % 10 sq = sq / 10 return (sum_digits == x) # Driver Code i = 1# Printing Neon Numbers upto 10000while i <= 10000 : if (checkNeon(i)) : print i, i = i + 1 # This code is contributed by Nikita Tiwari. // C# program to check and print// Neon Numbers upto 10000using System; class GFG{ // function to check Neon Number static bool checkNeon(int x) { // storing the square of x int sq = x * x; // calculating the sum of digits // of sq int sum_digits = 0; while (sq != 0) { sum_digits = sum_digits + sq % 10; sq = sq / 10; } return (sum_digits == x); } // Driver Code public static void Main() { // Printing Neon Numbers upto 10000 for (int i = 1; i <= 10000; i++) if (checkNeon(i)) Console.Write(i + " "); }} // This code is contributed by vt_m. <?php// PHP program to check and print// Neon Numbers upto 10000 function checkNeon($x){ // storing the square of x $sq = $x * $x; // calculating the // sum of digits of sq $sum_digits = 0; while ($sq != 0) { $sum_digits = $sum_digits + $sq % 10; $sq = $sq / 10; } return ($sum_digits == $x);} // Driver Code // Printing Neon Numbers // upto 10000 for ($i = 1; $i <= 10000; $i++) if (checkNeon($i)) echo $i . " "; // This code is contributed by Sam007?> <script> // Javascript program to check and print// Neon Numbers upto 10000 // function to check Neon Number function checkNeon(x) { // storing the square of x let sq = x * x; // calculating the sum of digits // of sq let sum_digits = 0; while (sq != 0) { sum_digits = sum_digits + sq % 10; sq = Math.floor(sq / 10); } return (sum_digits == x); } // driver program // Printing Neon Numbers upto 10000 for (let i = 1; i <= 10000; i++) if (checkNeon(i)) document.write(i + " "); </script> Output: 1 9 Neon Number | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersNeon Number | 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 / 3:18•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=g2Kp_2xPVHY" 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 Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Sam007 sanjoy_62 arorakashish0911 simmytarika5 series Mathematical Mathematical series Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Algorithm to solve Rubik's Cube Merge two sorted arrays with O(1) extra space Program to print prime numbers from 1 to N. Find next greater number with same set of digits Segment Tree | Set 1 (Sum of given range) Check if a number is Palindrome Count ways to reach the n'th stair Count all possible paths from top left to bottom right of a mXn matrix Fizz Buzz Implementation Product of Array except itself
[ { "code": null, "e": 53, "s": 25, "text": "\n16 Mar, 2022" }, { "code": null, "e": 207, "s": 53, "text": "A neon number is a number where the sum of digits of square of the number is equal to the number. The task is to check and print neon numbers in a range." }, { "code": null, "e": 218, "s": 207, "text": "Examples: " }, { "code": null, "e": 478, "s": 218, "text": "Input : 9\nOutput : Neon Number\nExplanation: square is 9*9 = 81 and \nsum of the digits of the square is 9.\n\nInput :12\nOutput : Not a Neon Number\nExplanation: square is 12*12 = 144 and \nsum of the digits of the square is 9 (1 \n+ 4 + 4) which is not equal to 12." }, { "code": null, "e": 587, "s": 478, "text": "The implementation is simple, we first compute square of given number, the find sum of digits in the square." }, { "code": null, "e": 591, "s": 587, "text": "C++" }, { "code": null, "e": 596, "s": 591, "text": "Java" }, { "code": null, "e": 603, "s": 596, "text": "Python" }, { "code": null, "e": 606, "s": 603, "text": "C#" }, { "code": null, "e": 610, "s": 606, "text": "PHP" }, { "code": null, "e": 621, "s": 610, "text": "Javascript" }, { "code": "// C/C++ program to check and print// Neon Numbers upto 10000#include <iostream>using namespace std;#include <math.h> int checkNeon(int x){ // storing the square of x int sq = x * x; // calculating the sum of digits // of sq int sum_digits = 0; while (sq != 0) { sum_digits = sum_digits + sq % 10; sq = sq / 10; } return (sum_digits == x);} // Driver Codeint main(void){ // Printing Neon Numbers upto 10000 for (int i = 1; i <= 10000; i++) if (checkNeon(i)) cout << i << \" \"; }", "e": 1164, "s": 621, "text": null }, { "code": "// Java program to check and print// Neon Numbers upto 10000import java.io.*; class GFG { // function to check Neon Number static boolean checkNeon(int x) { // storing the square of x int sq = x * x; // calculating the sum of digits // of sq int sum_digits = 0; while (sq != 0) { sum_digits = sum_digits + sq % 10; sq = sq / 10; } return (sum_digits == x); } // Driver Code public static void main(String args[]) throws IOException { // Printing Neon Numbers upto 10000 for (int i = 1; i <= 10000; i++) if (checkNeon(i)) System.out.print(i + \" \"); }}// This code is contributed by Nikita Tiwari.", "e": 1934, "s": 1164, "text": null }, { "code": "# Python program to check and print# Neon Numbers upto 10000 # function to check Neon Numberdef checkNeon (x) : # storing the square of x sq = x * x # calculating the sum of digits # of sq sum_digits = 0 while (sq != 0) : sum_digits = sum_digits + sq % 10 sq = sq / 10 return (sum_digits == x) # Driver Code i = 1# Printing Neon Numbers upto 10000while i <= 10000 : if (checkNeon(i)) : print i, i = i + 1 # This code is contributed by Nikita Tiwari.", "e": 2442, "s": 1934, "text": null }, { "code": "// C# program to check and print// Neon Numbers upto 10000using System; class GFG{ // function to check Neon Number static bool checkNeon(int x) { // storing the square of x int sq = x * x; // calculating the sum of digits // of sq int sum_digits = 0; while (sq != 0) { sum_digits = sum_digits + sq % 10; sq = sq / 10; } return (sum_digits == x); } // Driver Code public static void Main() { // Printing Neon Numbers upto 10000 for (int i = 1; i <= 10000; i++) if (checkNeon(i)) Console.Write(i + \" \"); }} // This code is contributed by vt_m.", "e": 3161, "s": 2442, "text": null }, { "code": "<?php// PHP program to check and print// Neon Numbers upto 10000 function checkNeon($x){ // storing the square of x $sq = $x * $x; // calculating the // sum of digits of sq $sum_digits = 0; while ($sq != 0) { $sum_digits = $sum_digits + $sq % 10; $sq = $sq / 10; } return ($sum_digits == $x);} // Driver Code // Printing Neon Numbers // upto 10000 for ($i = 1; $i <= 10000; $i++) if (checkNeon($i)) echo $i . \" \"; // This code is contributed by Sam007?>", "e": 3730, "s": 3161, "text": null }, { "code": "<script> // Javascript program to check and print// Neon Numbers upto 10000 // function to check Neon Number function checkNeon(x) { // storing the square of x let sq = x * x; // calculating the sum of digits // of sq let sum_digits = 0; while (sq != 0) { sum_digits = sum_digits + sq % 10; sq = Math.floor(sq / 10); } return (sum_digits == x); } // driver program // Printing Neon Numbers upto 10000 for (let i = 1; i <= 10000; i++) if (checkNeon(i)) document.write(i + \" \"); </script>", "e": 4357, "s": 3730, "text": null }, { "code": null, "e": 4367, "s": 4357, "text": "Output: " }, { "code": null, "e": 4373, "s": 4367, "text": "1 9\n " }, { "code": null, "e": 5213, "s": 4373, "text": "Neon Number | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersNeon Number | 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 / 3:18•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=g2Kp_2xPVHY\" 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": 5635, "s": 5213, "text": "This article is contributed by Nikita Tiwari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 5642, "s": 5635, "text": "Sam007" }, { "code": null, "e": 5652, "s": 5642, "text": "sanjoy_62" }, { "code": null, "e": 5669, "s": 5652, "text": "arorakashish0911" }, { "code": null, "e": 5682, "s": 5669, "text": "simmytarika5" }, { "code": null, "e": 5689, "s": 5682, "text": "series" }, { "code": null, "e": 5702, "s": 5689, "text": "Mathematical" }, { "code": null, "e": 5715, "s": 5702, "text": "Mathematical" }, { "code": null, "e": 5722, "s": 5715, "text": "series" }, { "code": null, "e": 5820, "s": 5722, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5852, "s": 5820, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 5898, "s": 5852, "text": "Merge two sorted arrays with O(1) extra space" }, { "code": null, "e": 5942, "s": 5898, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 5991, "s": 5942, "text": "Find next greater number with same set of digits" }, { "code": null, "e": 6033, "s": 5991, "text": "Segment Tree | Set 1 (Sum of given range)" }, { "code": null, "e": 6065, "s": 6033, "text": "Check if a number is Palindrome" }, { "code": null, "e": 6100, "s": 6065, "text": "Count ways to reach the n'th stair" }, { "code": null, "e": 6171, "s": 6100, "text": "Count all possible paths from top left to bottom right of a mXn matrix" }, { "code": null, "e": 6196, "s": 6171, "text": "Fizz Buzz Implementation" } ]
CSS Grid and place-items together
22 Jun, 2021 In this article, we will see how can we use the CSS grid and place-items property together to arrange elements in the web page. place-items is not specifically for the CSS grid it can be used with other properties too. Steps: Create three div with class container Each div will contain three more div with class box. Add class initial to the first div, middle to the second div, and end to the third div. Example: HTML html <!DOCTYPE html><html> <body> <h1>Place-items in start</h1> <!-- Container to be placed from starting --> <div class="container initial"> <div class="box">Item 1</div> <div class="box">Item 2</div> <div class="box">Item 3</div> </div> <h1>Place-items in middle</h1> <!-- Container to be placed in middle --> <div class="container middle"> <div class="box">Item 1</div> <div class="box">Item 2</div> <div class="box">Item 3</div> </div> <h1>Place-items in end</h1> <!-- Container to be placed in end --> <div class="container end"> <div class="box">Item 1</div> <div class="box">Item 2</div> <div class="box">Item 3</div> </div> </body></html> Arrange items in each container in three columns using the CSS grid. Add property place-items:start to div with class initial, similarly add place-items:center and place-items:end to div with class middle and end respectively. Example: CSS html <style> h1 { text-align: center; margin-top: 10px; } /* arrange boxes of container in three column form*/ .container { display: grid; grid-template-columns: 1fr 1fr 1fr; } /* starting position for first container*/ .initial { place-items: start; } /* middle position for second container*/ .middle { place-items: center; } /* ending position for first container*/ .end { place-items: end; } .box { width: 150px; height: 150px; display: flex; align-items: center; justify-content: center; background-color: #829099; }</style> Complete Code: html <!DOCTYPE html><html> <head> <style> h1 { text-align: center; margin-top: 10px; } /* arrange boxes of container in three column form*/ .container { display: grid; grid-template-columns: 1fr 1fr 1fr; } /* starting position for first container*/ .initial { place-items: start; } /* middle position for second container*/ .middle { place-items: center; } /* ending position for first container*/ .end { place-items: end; } .box { width: 150px; height: 150px; display: flex; align-items: center; justify-content: center; background-color: #829099; } </style> </head> <body> <h1>Place-items in start</h1> <!-- Container to be placed from starting --> <div class="container initial"> <div class="box">Item 1</div> <div class="box">Item 2</div> <div class="box">Item 3</div> </div> <h1>Place-items in middle</h1> <!-- Container to be placed in middle --> <div class="container middle"> <div class="box">Item 1</div> <div class="box">Item 2</div> <div class="box">Item 3</div> </div> <h1>Place-items in end</h1> <!-- Container to be placed in end --> <div class="container end"> <div class="box">Item 1</div> <div class="box">Item 2</div> <div class="box">Item 3</div> </div> </body></html> Output: anikakapoor CSS-Misc CSS-Properties CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Design a web page using HTML and CSS Form validation using jQuery REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2021" }, { "code": null, "e": 156, "s": 28, "text": "In this article, we will see how can we use the CSS grid and place-items property together to arrange elements in the web page." }, { "code": null, "e": 248, "s": 156, "text": "place-items is not specifically for the CSS grid it can be used with other properties too. " }, { "code": null, "e": 255, "s": 248, "text": "Steps:" }, { "code": null, "e": 293, "s": 255, "text": "Create three div with class container" }, { "code": null, "e": 346, "s": 293, "text": "Each div will contain three more div with class box." }, { "code": null, "e": 434, "s": 346, "text": "Add class initial to the first div, middle to the second div, and end to the third div." }, { "code": null, "e": 450, "s": 434, "text": "Example: HTML " }, { "code": null, "e": 455, "s": 450, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <h1>Place-items in start</h1> <!-- Container to be placed from starting --> <div class=\"container initial\"> <div class=\"box\">Item 1</div> <div class=\"box\">Item 2</div> <div class=\"box\">Item 3</div> </div> <h1>Place-items in middle</h1> <!-- Container to be placed in middle --> <div class=\"container middle\"> <div class=\"box\">Item 1</div> <div class=\"box\">Item 2</div> <div class=\"box\">Item 3</div> </div> <h1>Place-items in end</h1> <!-- Container to be placed in end --> <div class=\"container end\"> <div class=\"box\">Item 1</div> <div class=\"box\">Item 2</div> <div class=\"box\">Item 3</div> </div> </body></html>", "e": 1286, "s": 455, "text": null }, { "code": null, "e": 1355, "s": 1286, "text": "Arrange items in each container in three columns using the CSS grid." }, { "code": null, "e": 1513, "s": 1355, "text": "Add property place-items:start to div with class initial, similarly add place-items:center and place-items:end to div with class middle and end respectively." }, { "code": null, "e": 1528, "s": 1513, "text": "Example: CSS " }, { "code": null, "e": 1533, "s": 1528, "text": "html" }, { "code": "<style> h1 { text-align: center; margin-top: 10px; } /* arrange boxes of container in three column form*/ .container { display: grid; grid-template-columns: 1fr 1fr 1fr; } /* starting position for first container*/ .initial { place-items: start; } /* middle position for second container*/ .middle { place-items: center; } /* ending position for first container*/ .end { place-items: end; } .box { width: 150px; height: 150px; display: flex; align-items: center; justify-content: center; background-color: #829099; }</style>", "e": 2197, "s": 1533, "text": null }, { "code": null, "e": 2214, "s": 2197, "text": "Complete Code: " }, { "code": null, "e": 2219, "s": 2214, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <style> h1 { text-align: center; margin-top: 10px; } /* arrange boxes of container in three column form*/ .container { display: grid; grid-template-columns: 1fr 1fr 1fr; } /* starting position for first container*/ .initial { place-items: start; } /* middle position for second container*/ .middle { place-items: center; } /* ending position for first container*/ .end { place-items: end; } .box { width: 150px; height: 150px; display: flex; align-items: center; justify-content: center; background-color: #829099; } </style> </head> <body> <h1>Place-items in start</h1> <!-- Container to be placed from starting --> <div class=\"container initial\"> <div class=\"box\">Item 1</div> <div class=\"box\">Item 2</div> <div class=\"box\">Item 3</div> </div> <h1>Place-items in middle</h1> <!-- Container to be placed in middle --> <div class=\"container middle\"> <div class=\"box\">Item 1</div> <div class=\"box\">Item 2</div> <div class=\"box\">Item 3</div> </div> <h1>Place-items in end</h1> <!-- Container to be placed in end --> <div class=\"container end\"> <div class=\"box\">Item 1</div> <div class=\"box\">Item 2</div> <div class=\"box\">Item 3</div> </div> </body></html>", "e": 3991, "s": 2219, "text": null }, { "code": null, "e": 3999, "s": 3991, "text": "Output:" }, { "code": null, "e": 4011, "s": 3999, "text": "anikakapoor" }, { "code": null, "e": 4020, "s": 4011, "text": "CSS-Misc" }, { "code": null, "e": 4035, "s": 4020, "text": "CSS-Properties" }, { "code": null, "e": 4039, "s": 4035, "text": "CSS" }, { "code": null, "e": 4044, "s": 4039, "text": "HTML" }, { "code": null, "e": 4061, "s": 4044, "text": "Web Technologies" }, { "code": null, "e": 4066, "s": 4061, "text": "HTML" }, { "code": null, "e": 4164, "s": 4066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4203, "s": 4164, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 4242, "s": 4203, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 4281, "s": 4242, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 4318, "s": 4281, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 4347, "s": 4318, "text": "Form validation using jQuery" }, { "code": null, "e": 4371, "s": 4347, "text": "REST API (Introduction)" }, { "code": null, "e": 4424, "s": 4371, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4484, "s": 4424, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 4545, "s": 4484, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
jQuery getJSON() Method
24 Nov, 2021 In this article, we will learn about the getJSON() method in jQuery, along with understanding their implementation through the example. jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for its philosophy of “Write less, do more”. The getJSON() method in jQuery fetches JSON-encoded data from the server using a GET HTTP request. Syntax: $(selector).getJSON(url,data,success(data,status,xhr)) Parameters: This method accepts three parameters as mentioned above and described below: url: It is a required parameter. It is used to specify the URL in the form of a string to which the request is sent data: It is an optional parameter that specifies data that will be sent to the server. callback: It is also an optional parameter that runs when the request succeeds. Return Value: It returns XMLHttpRequest object. Please refer to the jQuery Tutorial and jQuery Examples articles for further details. Example: The below example illustrates the getJSON() method in jQuery. employee.json file: { “name”: “Tony Stark”, “age” : “53”, “role”: “Techincal content writer”, “company”:”Geeks for Geeks” } Here, we get the JSON file and displays its content. HTML <!DOCTYPE html><html> <head> <title>jQuery getJSON() Method</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <!-- Script to get JSON file and display its content --> <script type="text/javascript" language="javascript"> $(document).ready(function() { $("#fetch").click(function(event) { $.getJSON('employee.json', function(emp) { $('#display').html('<p> Name: ' + emp.name + '</p>'); $('#display').append('<p>Age : ' + emp.age + '</p>'); $('#display').append('<p> Role: ' + emp.role + '</p>'); $('#display').append('<p> Company: ' + emp.company + '</p>'); }); }); }); </script></head> <body> <p> Click on the button to fetch employee data </p> <div id="display" style="background-color:#39B54A;"></div> <input type="button" id="fetch" value="Fetch Employee Data" /> </body> </html> Output: getJSON() Method bhaskargeeksforgeeks jQuery-AJAX jQuery-Questions Picked JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n24 Nov, 2021" }, { "code": null, "e": 362, "s": 53, "text": "In this article, we will learn about the getJSON() method in jQuery, along with understanding their implementation through the example. jQuery is an open-source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous for its philosophy of “Write less, do more”. " }, { "code": null, "e": 461, "s": 362, "text": "The getJSON() method in jQuery fetches JSON-encoded data from the server using a GET HTTP request." }, { "code": null, "e": 469, "s": 461, "text": "Syntax:" }, { "code": null, "e": 524, "s": 469, "text": "$(selector).getJSON(url,data,success(data,status,xhr))" }, { "code": null, "e": 613, "s": 524, "text": "Parameters: This method accepts three parameters as mentioned above and described below:" }, { "code": null, "e": 729, "s": 613, "text": "url: It is a required parameter. It is used to specify the URL in the form of a string to which the request is sent" }, { "code": null, "e": 816, "s": 729, "text": "data: It is an optional parameter that specifies data that will be sent to the server." }, { "code": null, "e": 896, "s": 816, "text": "callback: It is also an optional parameter that runs when the request succeeds." }, { "code": null, "e": 944, "s": 896, "text": "Return Value: It returns XMLHttpRequest object." }, { "code": null, "e": 1030, "s": 944, "text": "Please refer to the jQuery Tutorial and jQuery Examples articles for further details." }, { "code": null, "e": 1101, "s": 1030, "text": "Example: The below example illustrates the getJSON() method in jQuery." }, { "code": null, "e": 1121, "s": 1101, "text": "employee.json file:" }, { "code": null, "e": 1225, "s": 1121, "text": "{ “name”: “Tony Stark”, “age” : “53”, “role”: “Techincal content writer”, “company”:”Geeks for Geeks” }" }, { "code": null, "e": 1278, "s": 1225, "text": "Here, we get the JSON file and displays its content." }, { "code": null, "e": 1283, "s": 1278, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>jQuery getJSON() Method</title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <!-- Script to get JSON file and display its content --> <script type=\"text/javascript\" language=\"javascript\"> $(document).ready(function() { $(\"#fetch\").click(function(event) { $.getJSON('employee.json', function(emp) { $('#display').html('<p> Name: ' + emp.name + '</p>'); $('#display').append('<p>Age : ' + emp.age + '</p>'); $('#display').append('<p> Role: ' + emp.role + '</p>'); $('#display').append('<p> Company: ' + emp.company + '</p>'); }); }); }); </script></head> <body> <p> Click on the button to fetch employee data </p> <div id=\"display\" style=\"background-color:#39B54A;\"></div> <input type=\"button\" id=\"fetch\" value=\"Fetch Employee Data\" /> </body> </html>", "e": 2287, "s": 1283, "text": null }, { "code": null, "e": 2295, "s": 2287, "text": "Output:" }, { "code": null, "e": 2313, "s": 2295, "text": " getJSON() Method" }, { "code": null, "e": 2334, "s": 2313, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 2346, "s": 2334, "text": "jQuery-AJAX" }, { "code": null, "e": 2363, "s": 2346, "text": "jQuery-Questions" }, { "code": null, "e": 2370, "s": 2363, "text": "Picked" }, { "code": null, "e": 2377, "s": 2370, "text": "JQuery" }, { "code": null, "e": 2394, "s": 2377, "text": "Web Technologies" } ]
Find roots or zeros of a Polynomial in R Programming – polyroot() Function
12 Jun, 2020 polyroot() function in R Language is used to calculate roots of a polynomial equation.A polynomial equation is represented as, p(x) = (z1) + (z2 * x) + (z3 * x2) +...+ (z[n] * xn-1) Syntax: polyroot(z) Parameters:z: Vector of polynomial coefficients in Increasing order Example 1: # R program to find zeros of a polynomial # Creating vectors of coefficientsx1 <- c(1, 2, 3)x2 <- c(-8, 4, -2)x3 <- c(12, -2, 3) # Calling polyroot() functionpolyroot(x1)polyroot(x2)polyroot(x3) Output: [1] -0.3333333+0.4714045i -0.3333333-0.4714045i [1] 1+1.732051i 1-1.732051i [1] 0.333333+1.972027i 0.333333-1.972027i Example 2: # R program to find zeros of a polynomial # Calling polyroot() function # For equation 2x - 3 = 0polyroot(c(-3, 2)) # For equation 3x ^ 2 - 4x + 5 = 0polyroot(c(5, -4, 3)) # For equation 2x ^ 4 - 3x -12 = 0polyroot(c(-12, -3, 0, 2)) Output: [1] 1.5+0i [1] 0.666667+1.105542i 0.666667-1.105542i [1] 2.090489+0.000000i -1.045244+1.333269i -1.045244-1.333269i R Math-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Filter data by multiple conditions in R using Dplyr How to Replace specific values in column in R DataFrame ? Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Loops in R (for, while, repeat) Group by function in R using Dplyr How to change Row Names of DataFrame in R ? How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? R - if statement
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Jun, 2020" }, { "code": null, "e": 155, "s": 28, "text": "polyroot() function in R Language is used to calculate roots of a polynomial equation.A polynomial equation is represented as," }, { "code": null, "e": 210, "s": 155, "text": "p(x) = (z1) + (z2 * x) + (z3 * x2) +...+ (z[n] * xn-1)" }, { "code": null, "e": 230, "s": 210, "text": "Syntax: polyroot(z)" }, { "code": null, "e": 298, "s": 230, "text": "Parameters:z: Vector of polynomial coefficients in Increasing order" }, { "code": null, "e": 309, "s": 298, "text": "Example 1:" }, { "code": "# R program to find zeros of a polynomial # Creating vectors of coefficientsx1 <- c(1, 2, 3)x2 <- c(-8, 4, -2)x3 <- c(12, -2, 3) # Calling polyroot() functionpolyroot(x1)polyroot(x2)polyroot(x3)", "e": 506, "s": 309, "text": null }, { "code": null, "e": 514, "s": 506, "text": "Output:" }, { "code": null, "e": 633, "s": 514, "text": "[1] -0.3333333+0.4714045i -0.3333333-0.4714045i\n[1] 1+1.732051i 1-1.732051i\n[1] 0.333333+1.972027i 0.333333-1.972027i\n" }, { "code": null, "e": 644, "s": 633, "text": "Example 2:" }, { "code": "# R program to find zeros of a polynomial # Calling polyroot() function # For equation 2x - 3 = 0polyroot(c(-3, 2)) # For equation 3x ^ 2 - 4x + 5 = 0polyroot(c(5, -4, 3)) # For equation 2x ^ 4 - 3x -12 = 0polyroot(c(-12, -3, 0, 2))", "e": 881, "s": 644, "text": null }, { "code": null, "e": 889, "s": 881, "text": "Output:" }, { "code": null, "e": 1007, "s": 889, "text": "[1] 1.5+0i\n[1] 0.666667+1.105542i 0.666667-1.105542i\n[1] 2.090489+0.000000i -1.045244+1.333269i -1.045244-1.333269i\n" }, { "code": null, "e": 1023, "s": 1007, "text": "R Math-Function" }, { "code": null, "e": 1034, "s": 1023, "text": "R Language" }, { "code": null, "e": 1132, "s": 1034, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1184, "s": 1132, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 1242, "s": 1184, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 1294, "s": 1242, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 1352, "s": 1294, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 1384, "s": 1352, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 1419, "s": 1384, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 1463, "s": 1419, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 1501, "s": 1463, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 1550, "s": 1501, "text": "How to filter R DataFrame by values in a column?" } ]
Predicting Air Quality Index using Python
01 Jun, 2021 Let us see how to predict the air quality index using Python. AQI is calculated based on chemical pollutant quantity. By using machine learning, we can predict the AQI. AQI: The air quality index is an index for reporting air quality on a daily basis. In other words, it is a measure of how air pollution affects one’s health within a short time period. The AQI is calculated based on the average concentration of a particular pollutant measured over a standard time interval. Generally, the time interval is 24 hours for most pollutants, 8 hours for carbon monoxide and ozone. We can see how air pollution is by looking at the AQI Let’s find the AQI based on Chemical pollutants using Machine Learning Concept. Note: To download the Data set click here. It contains 8 attributes, of which 7 are chemical pollution quantities and one is Air Quality Index. PM2.5-AVG, PM10-AVG, NO2-AVG, NH3-AVG, SO2-AG, OZONE-AVG are independent attributes. air_quality_index is a dependent attribute. Since air_quality_index is calculated based on the 7 attributes. As the data is numeric and there are no missing values in the data, so no preprocessing is required. Our goal is to predict the AQI, so this task is either Classification or regression. So as our class label is continuous, regression technique is required. Regression is supervised learning technique that fits the data in a given range. Example Regression techniques in Python: Random Forest Regressor Ada Boost Regressor Bagging Regressor Linear Regression etc. Python3 # importing pandas module for data frameimport pandas as pd # loading dataset and storing in train variabletrain=pd.read_csv('AQI.csv') # display top 5 datatrain.head() Output: Python3 # importing Randomforestfrom sklearn.ensemble import AdaBoostRegressorfrom sklearn.ensemble import RandomForestRegressor # creating modelm1 = RandomForestRegressor() # separating class label and other attributestrain1 = train.drop(['air_quality_index'], axis=1)target = train['air_quality_index'] # Fitting the modelm1.fit(train1, target)'''RandomForestRegressor(bootstrap=True, ccp_alpha=0.0, criterion='mse', max_depth=None, max_features='auto', max_leaf_nodes=None, max_samples=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False)''' # calculating the score and the score is 97.96360799890066%m1.score(train1, target) * 100 # predicting the model with other values (testing the data)# so AQI is 123.71m1.predict([[123, 45, 67, 34, 5, 0, 23]]) # Adaboost model# importing module # defining modelm2 = AdaBoostRegressor() # Fitting the modelm2.fit(train1, target) '''AdaBoostRegressor(base_estimator=None, learning_rate=1.0, loss='linear', n_estimators=50, random_state=None)''' # calculating the score and the score is 96.15377360010211%m2.score(train1, target)*100 # predicting the model with other values (testing the data)# so AQI is 94.42105263m2.predict([[123, 45, 67, 34, 5, 0, 23]]) Output: By this, we can say that by given test data we got 123 and 95 so the AQI is Unhealthy. saurabh1990aror Python-pandas python-utility Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Support Vector Machine Algorithm Introduction to Recurrent Neural Network ML | Monte Carlo Tree Search (MCTS) Markov Decision Process DBSCAN Clustering in ML | Density based clustering Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Jun, 2021" }, { "code": null, "e": 223, "s": 54, "text": "Let us see how to predict the air quality index using Python. AQI is calculated based on chemical pollutant quantity. By using machine learning, we can predict the AQI." }, { "code": null, "e": 633, "s": 223, "text": "AQI: The air quality index is an index for reporting air quality on a daily basis. In other words, it is a measure of how air pollution affects one’s health within a short time period. The AQI is calculated based on the average concentration of a particular pollutant measured over a standard time interval. Generally, the time interval is 24 hours for most pollutants, 8 hours for carbon monoxide and ozone." }, { "code": null, "e": 687, "s": 633, "text": "We can see how air pollution is by looking at the AQI" }, { "code": null, "e": 768, "s": 687, "text": "Let’s find the AQI based on Chemical pollutants using Machine Learning Concept. " }, { "code": null, "e": 811, "s": 768, "text": "Note: To download the Data set click here." }, { "code": null, "e": 1106, "s": 811, "text": "It contains 8 attributes, of which 7 are chemical pollution quantities and one is Air Quality Index. PM2.5-AVG, PM10-AVG, NO2-AVG, NH3-AVG, SO2-AG, OZONE-AVG are independent attributes. air_quality_index is a dependent attribute. Since air_quality_index is calculated based on the 7 attributes." }, { "code": null, "e": 1363, "s": 1106, "text": "As the data is numeric and there are no missing values in the data, so no preprocessing is required. Our goal is to predict the AQI, so this task is either Classification or regression. So as our class label is continuous, regression technique is required." }, { "code": null, "e": 1485, "s": 1363, "text": "Regression is supervised learning technique that fits the data in a given range. Example Regression techniques in Python:" }, { "code": null, "e": 1509, "s": 1485, "text": "Random Forest Regressor" }, { "code": null, "e": 1529, "s": 1509, "text": "Ada Boost Regressor" }, { "code": null, "e": 1547, "s": 1529, "text": "Bagging Regressor" }, { "code": null, "e": 1570, "s": 1547, "text": "Linear Regression etc." }, { "code": null, "e": 1578, "s": 1570, "text": "Python3" }, { "code": "# importing pandas module for data frameimport pandas as pd # loading dataset and storing in train variabletrain=pd.read_csv('AQI.csv') # display top 5 datatrain.head()", "e": 1747, "s": 1578, "text": null }, { "code": null, "e": 1759, "s": 1751, "text": "Output:" }, { "code": null, "e": 1771, "s": 1763, "text": "Python3" }, { "code": "# importing Randomforestfrom sklearn.ensemble import AdaBoostRegressorfrom sklearn.ensemble import RandomForestRegressor # creating modelm1 = RandomForestRegressor() # separating class label and other attributestrain1 = train.drop(['air_quality_index'], axis=1)target = train['air_quality_index'] # Fitting the modelm1.fit(train1, target)'''RandomForestRegressor(bootstrap=True, ccp_alpha=0.0, criterion='mse', max_depth=None, max_features='auto', max_leaf_nodes=None, max_samples=None, min_impurity_decrease=0.0, min_impurity_split=None, min_samples_leaf=1, min_samples_split=2, min_weight_fraction_leaf=0.0, n_estimators=100, n_jobs=None, oob_score=False, random_state=None, verbose=0, warm_start=False)''' # calculating the score and the score is 97.96360799890066%m1.score(train1, target) * 100 # predicting the model with other values (testing the data)# so AQI is 123.71m1.predict([[123, 45, 67, 34, 5, 0, 23]]) # Adaboost model# importing module # defining modelm2 = AdaBoostRegressor() # Fitting the modelm2.fit(train1, target) '''AdaBoostRegressor(base_estimator=None, learning_rate=1.0, loss='linear', n_estimators=50, random_state=None)''' # calculating the score and the score is 96.15377360010211%m2.score(train1, target)*100 # predicting the model with other values (testing the data)# so AQI is 94.42105263m2.predict([[123, 45, 67, 34, 5, 0, 23]])", "e": 3279, "s": 1771, "text": null }, { "code": null, "e": 3294, "s": 3286, "text": "Output:" }, { "code": null, "e": 3385, "s": 3298, "text": "By this, we can say that by given test data we got 123 and 95 so the AQI is Unhealthy." }, { "code": null, "e": 3403, "s": 3387, "text": "saurabh1990aror" }, { "code": null, "e": 3417, "s": 3403, "text": "Python-pandas" }, { "code": null, "e": 3432, "s": 3417, "text": "python-utility" }, { "code": null, "e": 3449, "s": 3432, "text": "Machine Learning" }, { "code": null, "e": 3456, "s": 3449, "text": "Python" }, { "code": null, "e": 3473, "s": 3456, "text": "Machine Learning" }, { "code": null, "e": 3571, "s": 3473, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3604, "s": 3571, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 3645, "s": 3604, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 3681, "s": 3645, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 3705, "s": 3681, "text": "Markov Decision Process" }, { "code": null, "e": 3756, "s": 3705, "text": "DBSCAN Clustering in ML | Density based clustering" }, { "code": null, "e": 3784, "s": 3756, "text": "Read JSON file using Python" }, { "code": null, "e": 3806, "s": 3784, "text": "Python map() function" }, { "code": null, "e": 3856, "s": 3806, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 3874, "s": 3856, "text": "Python Dictionary" } ]
Pattern to print X in a rectangular box
21 May, 2021 Given the value of length, print the X pattern in a box using # and ” “Examples: Input : 10 Output : ########## ## ## # # # # # # # # # ## # # ## # # # # # # # # # ## ## ########## Input : 7 Output : ####### ## ## # # # # # # # # # # # ## ## ####### Below is the implementation to print X in a rectangular box pattern : C++ Java Python 3 C# PHP Javascript // CPP code to print the above// specified pattern#include <bits/stdc++.h>using namespace std; // Function to print patternvoid pattern(int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 || i == n - 1 || j == 0 || j == n - 1 || i == j || i == n - 1 - j) cout << "#"; else cout << " "; } cout << endl; }} // Driver programint main(){ int n = 9; pattern(n); return 0;} // Java code to print the above// specified patternclass GFG { // Function to print pattern static void pattern(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 || i == n - 1 || j == 0 || j == n - 1 || i == j || i == n - 1 - j) System.out.print("#"); else System.out.print(" "); } System.out.println(); } } // Driver Code public static void main(String args[]) { int n = 9; pattern(n);; }} // This code is contributed by Sam007 # Python3 code to print the above# specified pattern # Function to print patterndef pattern(n): for i in range(0, n): for j in range(0, n): if (i == 0 or i == n - 1 or j == 0 or j == n - 1 or i == j or i == n - 1 - j): print( "#", end="") else: print( " ",end="") print("") # Driver programn = 9pattern(n) # This code is contributed by Smitha. // C# code to print the above// specified patternusing System; public class GFG { // Function to print pattern static void pattern(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 || i == n - 1 || j == 0 || j == n - 1 || i == j || i == n - 1 - j) Console.Write("#"); else Console.Write(" "); } Console.WriteLine(); } } // Driver code public static void Main() { int n = 9; pattern(n); }} // This code is contributed by Sam007. <?php// PHP code to print the above// specified pattern // Function to print patternfunction pattern($n){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { if ($i == 0 || $i == $n - 1 || $j == 0 || $j == $n - 1 || $i == $j || $i == $n - 1 - $j) echo "#"; else echo " "; } echo "\n"; }} // Driver Code $n = 9; pattern($n); // This code is contributed by nitin mittal?> <script> // JavaScript code to print the above // specified pattern // Function to print pattern function pattern(n) { for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { if ( i === 0 || i === n - 1 || j === 0 || j === n - 1 || i === j || i === n - 1 - j ) document.write("#"); else document.write(" "); } document.write("<br>"); } } // Driver code var n = 9; pattern(n); </script> ######### ## ## # # # # # # # # # # # # # # # # # # # ## ## ######### Sam007 Smitha Dinesh Semwal nitin mittal rdtank pattern-printing School Programming pattern-printing Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Constructors in Java Exceptions in Java Python Exception Handling Python Try Except Ternary Operator in Python How JVM Works - JVM Architecture? Python program to add two numbers Variables in Java Data types in Java Difference between Abstract Class and Interface in Java
[ { "code": null, "e": 53, "s": 25, "text": "\n21 May, 2021" }, { "code": null, "e": 136, "s": 53, "text": "Given the value of length, print the X pattern in a box using # and ” “Examples: " }, { "code": null, "e": 371, "s": 136, "text": "Input : 10 \nOutput : ##########\n ## ##\n # # # #\n # # # #\n # ## #\n # ## #\n # # # #\n # # # #\n ## ##\n ##########" }, { "code": null, "e": 522, "s": 373, "text": "Input : 7 \nOutput : #######\n ## ##\n # # # # \n # # #\n # # # #\n ## ##\n #######" }, { "code": null, "e": 593, "s": 522, "text": "Below is the implementation to print X in a rectangular box pattern : " }, { "code": null, "e": 597, "s": 593, "text": "C++" }, { "code": null, "e": 602, "s": 597, "text": "Java" }, { "code": null, "e": 611, "s": 602, "text": "Python 3" }, { "code": null, "e": 614, "s": 611, "text": "C#" }, { "code": null, "e": 618, "s": 614, "text": "PHP" }, { "code": null, "e": 629, "s": 618, "text": "Javascript" }, { "code": "// CPP code to print the above// specified pattern#include <bits/stdc++.h>using namespace std; // Function to print patternvoid pattern(int n){ for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 || i == n - 1 || j == 0 || j == n - 1 || i == j || i == n - 1 - j) cout << \"#\"; else cout << \" \"; } cout << endl; }} // Driver programint main(){ int n = 9; pattern(n); return 0;}", "e": 1180, "s": 629, "text": null }, { "code": "// Java code to print the above// specified patternclass GFG { // Function to print pattern static void pattern(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 || i == n - 1 || j == 0 || j == n - 1 || i == j || i == n - 1 - j) System.out.print(\"#\"); else System.out.print(\" \"); } System.out.println(); } } // Driver Code public static void main(String args[]) { int n = 9; pattern(n);; }} // This code is contributed by Sam007", "e": 1914, "s": 1180, "text": null }, { "code": "# Python3 code to print the above# specified pattern # Function to print patterndef pattern(n): for i in range(0, n): for j in range(0, n): if (i == 0 or i == n - 1 or j == 0 or j == n - 1 or i == j or i == n - 1 - j): print( \"#\", end=\"\") else: print( \" \",end=\"\") print(\"\") # Driver programn = 9pattern(n) # This code is contributed by Smitha.", "e": 2375, "s": 1914, "text": null }, { "code": "// C# code to print the above// specified patternusing System; public class GFG { // Function to print pattern static void pattern(int n) { for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (i == 0 || i == n - 1 || j == 0 || j == n - 1 || i == j || i == n - 1 - j) Console.Write(\"#\"); else Console.Write(\" \"); } Console.WriteLine(); } } // Driver code public static void Main() { int n = 9; pattern(n); }} // This code is contributed by Sam007.", "e": 3077, "s": 2375, "text": null }, { "code": "<?php// PHP code to print the above// specified pattern // Function to print patternfunction pattern($n){ for ($i = 0; $i < $n; $i++) { for ($j = 0; $j < $n; $j++) { if ($i == 0 || $i == $n - 1 || $j == 0 || $j == $n - 1 || $i == $j || $i == $n - 1 - $j) echo \"#\"; else echo \" \"; } echo \"\\n\"; }} // Driver Code $n = 9; pattern($n); // This code is contributed by nitin mittal?>", "e": 3600, "s": 3077, "text": null }, { "code": "<script> // JavaScript code to print the above // specified pattern // Function to print pattern function pattern(n) { for (var i = 0; i < n; i++) { for (var j = 0; j < n; j++) { if ( i === 0 || i === n - 1 || j === 0 || j === n - 1 || i === j || i === n - 1 - j ) document.write(\"#\"); else document.write(\" \"); } document.write(\"<br>\"); } } // Driver code var n = 9; pattern(n); </script>", "e": 4201, "s": 3600, "text": null }, { "code": null, "e": 4291, "s": 4201, "text": "#########\n## ##\n# # # #\n# # # #\n# # #\n# # # #\n# # # #\n## ##\n#########" }, { "code": null, "e": 4300, "s": 4293, "text": "Sam007" }, { "code": null, "e": 4321, "s": 4300, "text": "Smitha Dinesh Semwal" }, { "code": null, "e": 4334, "s": 4321, "text": "nitin mittal" }, { "code": null, "e": 4341, "s": 4334, "text": "rdtank" }, { "code": null, "e": 4358, "s": 4341, "text": "pattern-printing" }, { "code": null, "e": 4377, "s": 4358, "text": "School Programming" }, { "code": null, "e": 4394, "s": 4377, "text": "pattern-printing" }, { "code": null, "e": 4492, "s": 4394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4513, "s": 4492, "text": "Constructors in Java" }, { "code": null, "e": 4532, "s": 4513, "text": "Exceptions in Java" }, { "code": null, "e": 4558, "s": 4532, "text": "Python Exception Handling" }, { "code": null, "e": 4576, "s": 4558, "text": "Python Try Except" }, { "code": null, "e": 4603, "s": 4576, "text": "Ternary Operator in Python" }, { "code": null, "e": 4637, "s": 4603, "text": "How JVM Works - JVM Architecture?" }, { "code": null, "e": 4671, "s": 4637, "text": "Python program to add two numbers" }, { "code": null, "e": 4689, "s": 4671, "text": "Variables in Java" }, { "code": null, "e": 4708, "s": 4689, "text": "Data types in Java" } ]
Levels of Memory in Operating System
02 Apr, 2020 Memory hierarchy of a computer system it handles differences in speed. “Hierarchy” is a great way to say “order of thinks” like top to bottom, fast to slow, most important to least important. If you look at the memory hierarchy inside the computer, according to the fastest to the slowest: 1. CPU Registers 2. Caches memory 3. Main or Primary Memory 4. Secondary Memory These are explained as following below. CPU Register:These high speed registers in CPU serve as working memory for instruction and temporary storage of data. Typically, they create a general purpose register file to store data as it is processed. The capacity of 32 data words is typical of a register file, and each register can be read or written from within a single clock cycle.Caches Memory:Now a days, most computers contain another level of IC memory- sometimes several such levels- Known as cache memory, that is positioned logically between the CPU registers and main memory. storage capacity of a cache is less than of main memory, but with an access time of one to three cycles, the cache is much faster than main memory because some or all of it can reside on the same IC as the CPU.For high performance computers, caches are essential components. Unlike the other three types of memory, the cache is usually transparent to programmers. Simultaneously, a computes cache and main memory implement directly mapped external memory by the instructions of the CPU.Main or Primary Memory:It is large, fairly fast external memory, which stores programs and data in active use. in main memory, storage locations are addressed directly by the load and store instruction of the CPU. While an IC Technology similar to that of a CPU register file is used, access is slower is due to large capacity of main memory and the fact that it is physically separated from the CPU. Access time of five or more clock cycles are usual.Secondary Memory:Secondary memory is very large in capacity but much slower than memory. Secondary memory store system programs, large data files, and the like are not consistently required by the CPU. When the capacity of the main memory. in secondary storage, information is considered on line, but is accessed indirectly through I/O programs that transfer information between main and secondary memory.The most and common examples of secondary memory are magnetic hard disks and CD-ROMs (compact discs only read memories), both of which have relatively slow electrical access mechanisms. Storage capacity of several gigabytes is typical, while access time is measured in milliseconds. CPU Register:These high speed registers in CPU serve as working memory for instruction and temporary storage of data. Typically, they create a general purpose register file to store data as it is processed. The capacity of 32 data words is typical of a register file, and each register can be read or written from within a single clock cycle. Caches Memory:Now a days, most computers contain another level of IC memory- sometimes several such levels- Known as cache memory, that is positioned logically between the CPU registers and main memory. storage capacity of a cache is less than of main memory, but with an access time of one to three cycles, the cache is much faster than main memory because some or all of it can reside on the same IC as the CPU.For high performance computers, caches are essential components. Unlike the other three types of memory, the cache is usually transparent to programmers. Simultaneously, a computes cache and main memory implement directly mapped external memory by the instructions of the CPU. Main or Primary Memory:It is large, fairly fast external memory, which stores programs and data in active use. in main memory, storage locations are addressed directly by the load and store instruction of the CPU. While an IC Technology similar to that of a CPU register file is used, access is slower is due to large capacity of main memory and the fact that it is physically separated from the CPU. Access time of five or more clock cycles are usual. Secondary Memory:Secondary memory is very large in capacity but much slower than memory. Secondary memory store system programs, large data files, and the like are not consistently required by the CPU. When the capacity of the main memory. in secondary storage, information is considered on line, but is accessed indirectly through I/O programs that transfer information between main and secondary memory.The most and common examples of secondary memory are magnetic hard disks and CD-ROMs (compact discs only read memories), both of which have relatively slow electrical access mechanisms. Storage capacity of several gigabytes is typical, while access time is measured in milliseconds. Computer Organization & Architecture GATE CS Operating Systems Write From Home Operating Systems Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Direct Access Media (DMA) Controller in Computer Architecture Control Characters Architecture of 8085 microprocessor Pin diagram of 8086 microprocessor I2C Communication Protocol Layers of OSI Model ACID Properties in DBMS TCP/IP Model Types of Operating Systems Normal Forms in DBMS
[ { "code": null, "e": 52, "s": 24, "text": "\n02 Apr, 2020" }, { "code": null, "e": 244, "s": 52, "text": "Memory hierarchy of a computer system it handles differences in speed. “Hierarchy” is a great way to say “order of thinks” like top to bottom, fast to slow, most important to least important." }, { "code": null, "e": 342, "s": 244, "text": "If you look at the memory hierarchy inside the computer, according to the fastest to the slowest:" }, { "code": null, "e": 423, "s": 342, "text": "1. CPU Registers\n2. Caches memory\n3. Main or Primary Memory\n4. Secondary Memory " }, { "code": null, "e": 463, "s": 423, "text": "These are explained as following below." }, { "code": null, "e": 2634, "s": 463, "text": "CPU Register:These high speed registers in CPU serve as working memory for instruction and temporary storage of data. Typically, they create a general purpose register file to store data as it is processed. The capacity of 32 data words is typical of a register file, and each register can be read or written from within a single clock cycle.Caches Memory:Now a days, most computers contain another level of IC memory- sometimes several such levels- Known as cache memory, that is positioned logically between the CPU registers and main memory. storage capacity of a cache is less than of main memory, but with an access time of one to three cycles, the cache is much faster than main memory because some or all of it can reside on the same IC as the CPU.For high performance computers, caches are essential components. Unlike the other three types of memory, the cache is usually transparent to programmers. Simultaneously, a computes cache and main memory implement directly mapped external memory by the instructions of the CPU.Main or Primary Memory:It is large, fairly fast external memory, which stores programs and data in active use. in main memory, storage locations are addressed directly by the load and store instruction of the CPU. While an IC Technology similar to that of a CPU register file is used, access is slower is due to large capacity of main memory and the fact that it is physically separated from the CPU. Access time of five or more clock cycles are usual.Secondary Memory:Secondary memory is very large in capacity but much slower than memory. Secondary memory store system programs, large data files, and the like are not consistently required by the CPU. When the capacity of the main memory. in secondary storage, information is considered on line, but is accessed indirectly through I/O programs that transfer information between main and secondary memory.The most and common examples of secondary memory are magnetic hard disks and CD-ROMs (compact discs only read memories), both of which have relatively slow electrical access mechanisms. Storage capacity of several gigabytes is typical, while access time is measured in milliseconds." }, { "code": null, "e": 2977, "s": 2634, "text": "CPU Register:These high speed registers in CPU serve as working memory for instruction and temporary storage of data. Typically, they create a general purpose register file to store data as it is processed. The capacity of 32 data words is typical of a register file, and each register can be read or written from within a single clock cycle." }, { "code": null, "e": 3667, "s": 2977, "text": "Caches Memory:Now a days, most computers contain another level of IC memory- sometimes several such levels- Known as cache memory, that is positioned logically between the CPU registers and main memory. storage capacity of a cache is less than of main memory, but with an access time of one to three cycles, the cache is much faster than main memory because some or all of it can reside on the same IC as the CPU.For high performance computers, caches are essential components. Unlike the other three types of memory, the cache is usually transparent to programmers. Simultaneously, a computes cache and main memory implement directly mapped external memory by the instructions of the CPU." }, { "code": null, "e": 4120, "s": 3667, "text": "Main or Primary Memory:It is large, fairly fast external memory, which stores programs and data in active use. in main memory, storage locations are addressed directly by the load and store instruction of the CPU. While an IC Technology similar to that of a CPU register file is used, access is slower is due to large capacity of main memory and the fact that it is physically separated from the CPU. Access time of five or more clock cycles are usual." }, { "code": null, "e": 4808, "s": 4120, "text": "Secondary Memory:Secondary memory is very large in capacity but much slower than memory. Secondary memory store system programs, large data files, and the like are not consistently required by the CPU. When the capacity of the main memory. in secondary storage, information is considered on line, but is accessed indirectly through I/O programs that transfer information between main and secondary memory.The most and common examples of secondary memory are magnetic hard disks and CD-ROMs (compact discs only read memories), both of which have relatively slow electrical access mechanisms. Storage capacity of several gigabytes is typical, while access time is measured in milliseconds." }, { "code": null, "e": 4845, "s": 4808, "text": "Computer Organization & Architecture" }, { "code": null, "e": 4853, "s": 4845, "text": "GATE CS" }, { "code": null, "e": 4871, "s": 4853, "text": "Operating Systems" }, { "code": null, "e": 4887, "s": 4871, "text": "Write From Home" }, { "code": null, "e": 4905, "s": 4887, "text": "Operating Systems" }, { "code": null, "e": 5003, "s": 4905, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5065, "s": 5003, "text": "Direct Access Media (DMA) Controller in Computer Architecture" }, { "code": null, "e": 5084, "s": 5065, "text": "Control Characters" }, { "code": null, "e": 5120, "s": 5084, "text": "Architecture of 8085 microprocessor" }, { "code": null, "e": 5155, "s": 5120, "text": "Pin diagram of 8086 microprocessor" }, { "code": null, "e": 5182, "s": 5155, "text": "I2C Communication Protocol" }, { "code": null, "e": 5202, "s": 5182, "text": "Layers of OSI Model" }, { "code": null, "e": 5226, "s": 5202, "text": "ACID Properties in DBMS" }, { "code": null, "e": 5239, "s": 5226, "text": "TCP/IP Model" }, { "code": null, "e": 5266, "s": 5239, "text": "Types of Operating Systems" } ]
What is Algorithm | Introduction to Algorithms
23 Jun, 2022 The word Algorithm means ” A set of rules to be followed in calculations or other problem-solving operations ” Or ” A procedure for solving a mathematical problem in a finite number of steps that frequently by recursive operations “. Therefore Algorithm refers to a sequence of finite steps to solve a particular problem. Algorithms can be simple and complex depending on what you want to achieve. It can be understood by taking the example of cooking a new recipe. To cook a new recipe, one reads the instructions and steps and executes them one by one, in the given sequence. The result thus obtained is the new dish cooked perfectly. Every time you use your phone, computer, laptop, or calculator you are using Algorithms. Similarly, algorithms help to do a task in programming to get the expected output. The Algorithm designed are language-independent, i.e. they are just plain instructions that can be implemented in any language, and yet the output will be the same, as expected. As one would not follow any written instructions to cook the recipe, but only the standard one. Similarly, not all written instructions for programming is an algorithms. In order for some instructions to be an algorithm, it must have the following characteristics: Clear and Unambiguous: The algorithm should be clear and unambiguous. Each of its steps should be clear in all aspects and must lead to only one meaning. Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs. Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it should be well-defined as well. Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time. Feasible: The algorithm must be simple, generic, and practical, such that it can be executed with the available resources. It must not contain some future technology or anything. Language Independent: The Algorithm designed must be language-independent, i.e. it must be just plain instructions that can be implemented in any language, and yet the output will be the same, as expected. It should terminate after a finite time. It should produce at least one output. It should take zero or more input. It should be deterministic means giving the same output for the same input case. Every step in the algorithm must be effective i.e. every step should do some work. There are several types of algorithms available. Some important algorithms are: 1. Brute Force Algorithm: It is the simplest approach for a problem. A brute force algorithm is the first approach that comes to finding when we see a problem. 2. Recursive Algorithm: A recursive algorithm is based on recursion. In this case, a problem is broken into several sub-parts and called the same function again and again. 3. Backtracking Algorithm: The backtracking algorithm basically builds the solution by searching among all possible solutions. Using this algorithm, we keep on building the solution following criteria. Whenever a solution fails we trace back to the failure point and build on the next solution and continue this process till we find the solution or all possible solutions are looked after. 4. Searching Algorithm: Searching algorithms are the ones that are used for searching elements or groups of elements from a particular data structure. They can be of different types based on their approach or the data structure in which the element should be found. 5. Sorting Algorithm: Sorting is arranging a group of data in a particular manner according to the requirement. The algorithms which help in performing this function are called sorting algorithms. Generally sorting algorithms are used to sort groups of data in an increasing or decreasing manner. 6. Hashing Algorithm: Hashing algorithms work similarly to the searching algorithm. But they contain an index with a key ID. In hashing, a key is assigned to specific data. 7. Divide and Conquer Algorithm: This algorithm breaks a problem into sub-problems, solves a single sub-problem and merges the solutions together to get the final solution. It consists of the following three steps: Divide Solve Combine 8. Greedy Algorithm: In this type of algorithm the solution is built part by part. The solution of the next part is built based on the immediate benefit of the next part. The one solution giving the most benefit will be chosen as the solution for the next part. 9. Dynamic Programming Algorithm: This algorithm uses the concept of using the already found solution to avoid repetitive calculation of the same part of the problem. It divides the problem into smaller overlapping subproblems and solves them. 10. Randomized Algorithm: In the randomized algorithm we use a random number so it gives immediate benefit. The random number helps in deciding the expected outcome. To learn more about the types of algorithms refer to the article about “Types of Algorithms“. It is easy to understand. An algorithm is a step-wise representation of a solution to a given problem. In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the programmer to convert it into an actual program. Writing an algorithm takes a long time so it is time-consuming. Understanding complex logic through algorithms can be very difficult. Branching and Looping statements are difficult to show in Algorithms(imp). In order to write an algorithm, the following things are needed as a pre-requisite: The problem that is to be solved by this algorithm i.e. clear problem definition.The constraints of the problem must be considered while solving the problem.The input to be taken to solve the problem.The output to be expected when the problem is solved.The solution to this problem, is within the given constraints. The problem that is to be solved by this algorithm i.e. clear problem definition. The constraints of the problem must be considered while solving the problem. The input to be taken to solve the problem. The output to be expected when the problem is solved. The solution to this problem, is within the given constraints. Then the algorithm is written with the help of the above parameters such that it solves the problem.Example: Consider the example to add three numbers and print the sum. Step 1: Fulfilling the pre-requisites As discussed above, in order to write an algorithm, its pre-requisites must be fulfilled. The problem that is to be solved by this algorithm: Add 3 numbers and print their sum.The constraints of the problem that must be considered while solving the problem: The numbers must contain only digits and no other characters.The input to be taken to solve the problem: The three numbers to be added.The output to be expected when the problem is solved: The sum of the three numbers taken as the input i.e. a single integer value.The solution to this problem, in the given constraints: The solution consists of adding the 3 numbers. It can be done with the help of ‘+’ operator, or bit-wise, or any other method. The problem that is to be solved by this algorithm: Add 3 numbers and print their sum.The constraints of the problem that must be considered while solving the problem: The numbers must contain only digits and no other characters.The input to be taken to solve the problem: The three numbers to be added.The output to be expected when the problem is solved: The sum of the three numbers taken as the input i.e. a single integer value.The solution to this problem, in the given constraints: The solution consists of adding the 3 numbers. It can be done with the help of ‘+’ operator, or bit-wise, or any other method. The problem that is to be solved by this algorithm: Add 3 numbers and print their sum. The constraints of the problem that must be considered while solving the problem: The numbers must contain only digits and no other characters. The input to be taken to solve the problem: The three numbers to be added. The output to be expected when the problem is solved: The sum of the three numbers taken as the input i.e. a single integer value. The solution to this problem, in the given constraints: The solution consists of adding the 3 numbers. It can be done with the help of ‘+’ operator, or bit-wise, or any other method. Step 2: Designing the algorithmNow let’s design the algorithm with the help of the above pre-requisites:Algorithm to add 3 numbers and print their sum: STARTDeclare 3 integer variables num1, num2 and num3.Take the three numbers, to be added, as inputs in variables num1, num2, and num3 respectively.Declare an integer variable sum to store the resultant sum of the 3 numbers.Add the 3 numbers and store the result in the variable sum.Print the value of the variable sumEND STARTDeclare 3 integer variables num1, num2 and num3.Take the three numbers, to be added, as inputs in variables num1, num2, and num3 respectively.Declare an integer variable sum to store the resultant sum of the 3 numbers.Add the 3 numbers and store the result in the variable sum.Print the value of the variable sumEND START Declare 3 integer variables num1, num2 and num3. Take the three numbers, to be added, as inputs in variables num1, num2, and num3 respectively. Declare an integer variable sum to store the resultant sum of the 3 numbers. Add the 3 numbers and store the result in the variable sum. Print the value of the variable sum END Step 3: Testing the algorithm by implementing it.In order to test the algorithm, let’s implement it in C language. Program: C++ C Java Python3 // C++ program to add three numbers// with the help of above designed// algorithm#include <bits/stdc++.h>using namespace std; int main(){ // Variables to take the input of // the 3 numbers int num1, num2, num3; // Variable to store the resultant sum int sum; // Take the 3 numbers as input cout << "Enter the 1st number: "; cin >> num1; cout << " " << num1 << endl; cout << "Enter the 2nd number: "; cin >> num2; cout << " " << num2 << endl; cout << "Enter the 3rd number: "; cin >> num3; cout << " " << num3; // Calculate the sum using + operator // and store it in variable sum sum = num1 + num2 + num3; // Print the sum cout << "\nSum of the 3 numbers is: " << sum; return 0;} // This code is contributed by shivanisinghss2110 // C program to add three numbers// with the help of above designed algorithm #include <stdio.h> int main(){ // Variables to take the input of the 3 numbers int num1, num2, num3; // Variable to store the resultant sum int sum; // Take the 3 numbers as input printf("Enter the 1st number: "); scanf("%d", &num1); printf("%d\n", num1); printf("Enter the 2nd number: "); scanf("%d", &num2); printf("%d\n", num2); printf("Enter the 3rd number: "); scanf("%d", &num3); printf("%d\n", num3); // Calculate the sum using + operator // and store it in variable sum sum = num1 + num2 + num3; // Print the sum printf("\nSum of the 3 numbers is: %d", sum); return 0;} // Java program to add the three numbers// with the help of above designed// algorithmimport java.util.*; class GFG { public static void main(String[] args) { // Variable to store the resultant sum int sum = 0; // Declare the object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in); // Scanner definition // Variables to take the input of // the 3 numbers System.out.println("Enter the 1st number: "); int num1 = sc.nextInt(); // input is an Integer // read by nextInt() function System.out.println(" " + num1); System.out.println("Enter the 2nd number: "); int num2 = sc.nextInt(); System.out.println(" " + num2); System.out.println("Enter the 3rd number: "); int num3 = sc.nextInt(); System.out.println(" " + num3); // Calculate the sum using + operator // and store it in variable sum sum = num1 + num2 + num3; System.out.println("Sum of the 3 numbers is = " + sum); }} /*This code is contributed by Rishab Dugar*/ # Python3 program to add three numbers# with the help of above designed# algorithm if __name__ == "__main__": # Variables to take the input of # the 3 numbers num1 = num2 = num3 = 0 # Variable to store the resultant sum sum = 0 # Take the 3 numbers as input num1 = int(input("Enter the 1st number: ")) num2 = int(input("Enter the 2nd number: ")) num3 = int(input("Enter the 3rd number: ")) # Calculate the sum using + operator # and store it in variable sum sum = num1 + num2 + num3 # Print the sum print("\nSum of the 3 numbers is:", sum) Enter the 1st number: 0 Enter the 2nd number: 0 Enter the 3rd number: -1577141152 Sum of the 3 numbers is: -1577141152 One problem, many solutions: The solution to an algorithm can be or cannot be more than one. It means that while implementing the algorithm, there can be more than one method to implement it. For example, in the above problem to add 3 numbers, the sum can be calculated in many ways like: + operator Bit-wise operators . . etc For a standard algorithm to be good, it must be efficient. Hence the efficiency of an algorithm must be checked and maintained. It can be in two stages: Priori Analysis: “Priori” means “before”. Hence Priori analysis means checking the algorithm before its implementation. In this, the algorithm is checked when it is written in the form of theoretical steps. This Efficiency of an algorithm is measured by assuming that all other factors, for example, processor speed, are constant and have no effect on the implementation. This is done usually by the algorithm designer. This analysis is independent of the type of hardware and language of the compiler. It gives the approximate answers for the complexity of the program.Posterior Analysis: “Posterior” means “after”. Hence Posterior analysis means checking the algorithm after its implementation. In this, the algorithm is checked by implementing it in any programming language and executing it. This analysis helps to get the actual and real analysis report about correctness, space required, time consumed etc. That is, it is dependent on the language of the compiler and the type of hardware used. Priori Analysis: “Priori” means “before”. Hence Priori analysis means checking the algorithm before its implementation. In this, the algorithm is checked when it is written in the form of theoretical steps. This Efficiency of an algorithm is measured by assuming that all other factors, for example, processor speed, are constant and have no effect on the implementation. This is done usually by the algorithm designer. This analysis is independent of the type of hardware and language of the compiler. It gives the approximate answers for the complexity of the program. Posterior Analysis: “Posterior” means “after”. Hence Posterior analysis means checking the algorithm after its implementation. In this, the algorithm is checked by implementing it in any programming language and executing it. This analysis helps to get the actual and real analysis report about correctness, space required, time consumed etc. That is, it is dependent on the language of the compiler and the type of hardware used. An algorithm is defined as complex based on the amount of Space and Time it consumes. Hence the Complexity of an algorithm refers to the measure of the Time that it will need to execute and get the expected output, and the Space it will need to store all the data (input, temporary data and output). Hence these two factors define the efficiency of an algorithm. The two factors of Algorithm Complexity are: Time Factor: Time is measured by counting the number of key operations such as comparisons in the sorting algorithm. Space Factor: Space is measured by counting the maximum memory space required by the algorithm. Therefore the complexity of an algorithm can be divided into two types: 1. Space Complexity: The space complexity of an algorithm refers to the amount of memory used by the algorithm to store the variables and get the result. This can be for inputs, temporary operations, or outputs. How to calculate Space Complexity?The space complexity of an algorithm is calculated by determining the following 2 components: Fixed Part: This refers to the space that is definitely required by the algorithm. For example, input variables, output variables, program size, etc. Variable Part: This refers to the space that can be different based on the implementation of the algorithm. For example, temporary variables, dynamic memory allocation, recursion stack space, etc.Therefore Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I) is the variable part of the algorithm, which depends on instance characteristic I. Example: Consider the below algorithm for Linear Search Step 1: STARTStep 2: Get the array in arr and the number to be searched in xStep 3: Start from the leftmost element of arr[] and one by one compare x with each element of arr[]Step 4: If x matches with an element, Print True.Step 5: If x doesn’t match with any of the elements, Print False.Step 6: ENDHere, There are 2 variables arr[], and x, where the arr[] is the variable part and x is the fixed part. Hence S(P) = 1+1. Now, space depends on data types of given variables and constant types and it will be multiplied accordingly. 2. Time Complexity: The time complexity of an algorithm refers to the amount of time that is required by the algorithm to execute and get the result. This can be for normal operations, conditional if-else statements, loop statements, etc. How to calculate Time Complexity?The time complexity of an algorithm is also calculated by determining the following 2 components: Constant time part: Any instruction that is executed just once comes in this part. For example, input, output, if-else, switch, etc. Variable Time Part: Any instruction that is executed more than once, say n times, comes in this part. For example, loops, recursion, etc.Therefore Time complexity of any algorithm P is T(P) = C + TP(I), where C is the constant time part and TP(I) is the variable part of the algorithm, which depends on the instance characteristic I. Example: In the algorithm of Linear Search above, the time complexity is calculated as follows: Step 1: –Constant TimeStep 2: –Constant TimeStep 3: –Variable Time (Till the length of the Array, say n, or the index of the found element)Step 4: –Constant TimeStep 5: –Constant TimeStep 6: –Constant TimeHence, T(P) = 5 + n, which can be said as T(n). AnubhavMittal itskawal2000 shivanisinghss2110 amartyaghoshgfg piyushsri20146 ece20becd76 shraddhajain3131 kingrishabdugar animeshdey Algorithms-Analysis of Algorithms Algorithms Computer Subject Data Structures Data Structures Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews Difference between BFS and DFS Recursion SDE SHEET - A Complete Guide for SDE Preparation Software Engineering | Coupling and Cohesion Type Checking in Compiler Design Difference between NP hard and NP complete problem Aptitude for Placements
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Jun, 2022" }, { "code": null, "e": 288, "s": 52, "text": "The word Algorithm means ” A set of rules to be followed in calculations or other problem-solving operations ” Or ” A procedure for solving a mathematical problem in a finite number of steps that frequently by recursive operations “. " }, { "code": null, "e": 376, "s": 288, "text": "Therefore Algorithm refers to a sequence of finite steps to solve a particular problem." }, { "code": null, "e": 452, "s": 376, "text": "Algorithms can be simple and complex depending on what you want to achieve." }, { "code": null, "e": 863, "s": 452, "text": "It can be understood by taking the example of cooking a new recipe. To cook a new recipe, one reads the instructions and steps and executes them one by one, in the given sequence. The result thus obtained is the new dish cooked perfectly. Every time you use your phone, computer, laptop, or calculator you are using Algorithms. Similarly, algorithms help to do a task in programming to get the expected output." }, { "code": null, "e": 1041, "s": 863, "text": "The Algorithm designed are language-independent, i.e. they are just plain instructions that can be implemented in any language, and yet the output will be the same, as expected." }, { "code": null, "e": 1306, "s": 1041, "text": "As one would not follow any written instructions to cook the recipe, but only the standard one. Similarly, not all written instructions for programming is an algorithms. In order for some instructions to be an algorithm, it must have the following characteristics:" }, { "code": null, "e": 1460, "s": 1306, "text": "Clear and Unambiguous: The algorithm should be clear and unambiguous. Each of its steps should be clear in all aspects and must lead to only one meaning." }, { "code": null, "e": 1553, "s": 1460, "text": "Well-Defined Inputs: If an algorithm says to take inputs, it should be well-defined inputs. " }, { "code": null, "e": 1677, "s": 1553, "text": "Well-Defined Outputs: The algorithm must clearly define what output will be yielded and it should be well-defined as well. " }, { "code": null, "e": 1766, "s": 1677, "text": "Finite-ness: The algorithm must be finite, i.e. it should terminate after a finite time." }, { "code": null, "e": 1945, "s": 1766, "text": "Feasible: The algorithm must be simple, generic, and practical, such that it can be executed with the available resources. It must not contain some future technology or anything." }, { "code": null, "e": 2151, "s": 1945, "text": "Language Independent: The Algorithm designed must be language-independent, i.e. it must be just plain instructions that can be implemented in any language, and yet the output will be the same, as expected." }, { "code": null, "e": 2192, "s": 2151, "text": "It should terminate after a finite time." }, { "code": null, "e": 2231, "s": 2192, "text": "It should produce at least one output." }, { "code": null, "e": 2266, "s": 2231, "text": "It should take zero or more input." }, { "code": null, "e": 2347, "s": 2266, "text": "It should be deterministic means giving the same output for the same input case." }, { "code": null, "e": 2430, "s": 2347, "text": "Every step in the algorithm must be effective i.e. every step should do some work." }, { "code": null, "e": 2510, "s": 2430, "text": "There are several types of algorithms available. Some important algorithms are:" }, { "code": null, "e": 2670, "s": 2510, "text": "1. Brute Force Algorithm: It is the simplest approach for a problem. A brute force algorithm is the first approach that comes to finding when we see a problem." }, { "code": null, "e": 2842, "s": 2670, "text": "2. Recursive Algorithm: A recursive algorithm is based on recursion. In this case, a problem is broken into several sub-parts and called the same function again and again." }, { "code": null, "e": 3232, "s": 2842, "text": "3. Backtracking Algorithm: The backtracking algorithm basically builds the solution by searching among all possible solutions. Using this algorithm, we keep on building the solution following criteria. Whenever a solution fails we trace back to the failure point and build on the next solution and continue this process till we find the solution or all possible solutions are looked after." }, { "code": null, "e": 3498, "s": 3232, "text": "4. Searching Algorithm: Searching algorithms are the ones that are used for searching elements or groups of elements from a particular data structure. They can be of different types based on their approach or the data structure in which the element should be found." }, { "code": null, "e": 3795, "s": 3498, "text": "5. Sorting Algorithm: Sorting is arranging a group of data in a particular manner according to the requirement. The algorithms which help in performing this function are called sorting algorithms. Generally sorting algorithms are used to sort groups of data in an increasing or decreasing manner." }, { "code": null, "e": 3968, "s": 3795, "text": "6. Hashing Algorithm: Hashing algorithms work similarly to the searching algorithm. But they contain an index with a key ID. In hashing, a key is assigned to specific data." }, { "code": null, "e": 4183, "s": 3968, "text": "7. Divide and Conquer Algorithm: This algorithm breaks a problem into sub-problems, solves a single sub-problem and merges the solutions together to get the final solution. It consists of the following three steps:" }, { "code": null, "e": 4190, "s": 4183, "text": "Divide" }, { "code": null, "e": 4196, "s": 4190, "text": "Solve" }, { "code": null, "e": 4204, "s": 4196, "text": "Combine" }, { "code": null, "e": 4466, "s": 4204, "text": "8. Greedy Algorithm: In this type of algorithm the solution is built part by part. The solution of the next part is built based on the immediate benefit of the next part. The one solution giving the most benefit will be chosen as the solution for the next part." }, { "code": null, "e": 4710, "s": 4466, "text": "9. Dynamic Programming Algorithm: This algorithm uses the concept of using the already found solution to avoid repetitive calculation of the same part of the problem. It divides the problem into smaller overlapping subproblems and solves them." }, { "code": null, "e": 4876, "s": 4710, "text": "10. Randomized Algorithm: In the randomized algorithm we use a random number so it gives immediate benefit. The random number helps in deciding the expected outcome." }, { "code": null, "e": 4970, "s": 4876, "text": "To learn more about the types of algorithms refer to the article about “Types of Algorithms“." }, { "code": null, "e": 4996, "s": 4970, "text": "It is easy to understand." }, { "code": null, "e": 5073, "s": 4996, "text": "An algorithm is a step-wise representation of a solution to a given problem." }, { "code": null, "e": 5219, "s": 5073, "text": "In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for the programmer to convert it into an actual program." }, { "code": null, "e": 5283, "s": 5219, "text": "Writing an algorithm takes a long time so it is time-consuming." }, { "code": null, "e": 5353, "s": 5283, "text": "Understanding complex logic through algorithms can be very difficult." }, { "code": null, "e": 5428, "s": 5353, "text": "Branching and Looping statements are difficult to show in Algorithms(imp)." }, { "code": null, "e": 5514, "s": 5428, "text": "In order to write an algorithm, the following things are needed as a pre-requisite: " }, { "code": null, "e": 5830, "s": 5514, "text": "The problem that is to be solved by this algorithm i.e. clear problem definition.The constraints of the problem must be considered while solving the problem.The input to be taken to solve the problem.The output to be expected when the problem is solved.The solution to this problem, is within the given constraints." }, { "code": null, "e": 5912, "s": 5830, "text": "The problem that is to be solved by this algorithm i.e. clear problem definition." }, { "code": null, "e": 5989, "s": 5912, "text": "The constraints of the problem must be considered while solving the problem." }, { "code": null, "e": 6033, "s": 5989, "text": "The input to be taken to solve the problem." }, { "code": null, "e": 6087, "s": 6033, "text": "The output to be expected when the problem is solved." }, { "code": null, "e": 6150, "s": 6087, "text": "The solution to this problem, is within the given constraints." }, { "code": null, "e": 6321, "s": 6150, "text": "Then the algorithm is written with the help of the above parameters such that it solves the problem.Example: Consider the example to add three numbers and print the sum. " }, { "code": null, "e": 7065, "s": 6321, "text": "Step 1: Fulfilling the pre-requisites As discussed above, in order to write an algorithm, its pre-requisites must be fulfilled. The problem that is to be solved by this algorithm: Add 3 numbers and print their sum.The constraints of the problem that must be considered while solving the problem: The numbers must contain only digits and no other characters.The input to be taken to solve the problem: The three numbers to be added.The output to be expected when the problem is solved: The sum of the three numbers taken as the input i.e. a single integer value.The solution to this problem, in the given constraints: The solution consists of adding the 3 numbers. It can be done with the help of ‘+’ operator, or bit-wise, or any other method." }, { "code": null, "e": 7681, "s": 7065, "text": "The problem that is to be solved by this algorithm: Add 3 numbers and print their sum.The constraints of the problem that must be considered while solving the problem: The numbers must contain only digits and no other characters.The input to be taken to solve the problem: The three numbers to be added.The output to be expected when the problem is solved: The sum of the three numbers taken as the input i.e. a single integer value.The solution to this problem, in the given constraints: The solution consists of adding the 3 numbers. It can be done with the help of ‘+’ operator, or bit-wise, or any other method." }, { "code": null, "e": 7768, "s": 7681, "text": "The problem that is to be solved by this algorithm: Add 3 numbers and print their sum." }, { "code": null, "e": 7912, "s": 7768, "text": "The constraints of the problem that must be considered while solving the problem: The numbers must contain only digits and no other characters." }, { "code": null, "e": 7987, "s": 7912, "text": "The input to be taken to solve the problem: The three numbers to be added." }, { "code": null, "e": 8118, "s": 7987, "text": "The output to be expected when the problem is solved: The sum of the three numbers taken as the input i.e. a single integer value." }, { "code": null, "e": 8301, "s": 8118, "text": "The solution to this problem, in the given constraints: The solution consists of adding the 3 numbers. It can be done with the help of ‘+’ operator, or bit-wise, or any other method." }, { "code": null, "e": 8774, "s": 8301, "text": "Step 2: Designing the algorithmNow let’s design the algorithm with the help of the above pre-requisites:Algorithm to add 3 numbers and print their sum: STARTDeclare 3 integer variables num1, num2 and num3.Take the three numbers, to be added, as inputs in variables num1, num2, and num3 respectively.Declare an integer variable sum to store the resultant sum of the 3 numbers.Add the 3 numbers and store the result in the variable sum.Print the value of the variable sumEND" }, { "code": null, "e": 9095, "s": 8774, "text": "STARTDeclare 3 integer variables num1, num2 and num3.Take the three numbers, to be added, as inputs in variables num1, num2, and num3 respectively.Declare an integer variable sum to store the resultant sum of the 3 numbers.Add the 3 numbers and store the result in the variable sum.Print the value of the variable sumEND" }, { "code": null, "e": 9101, "s": 9095, "text": "START" }, { "code": null, "e": 9150, "s": 9101, "text": "Declare 3 integer variables num1, num2 and num3." }, { "code": null, "e": 9245, "s": 9150, "text": "Take the three numbers, to be added, as inputs in variables num1, num2, and num3 respectively." }, { "code": null, "e": 9322, "s": 9245, "text": "Declare an integer variable sum to store the resultant sum of the 3 numbers." }, { "code": null, "e": 9382, "s": 9322, "text": "Add the 3 numbers and store the result in the variable sum." }, { "code": null, "e": 9418, "s": 9382, "text": "Print the value of the variable sum" }, { "code": null, "e": 9422, "s": 9418, "text": "END" }, { "code": null, "e": 9537, "s": 9422, "text": "Step 3: Testing the algorithm by implementing it.In order to test the algorithm, let’s implement it in C language." }, { "code": null, "e": 9546, "s": 9537, "text": "Program:" }, { "code": null, "e": 9550, "s": 9546, "text": "C++" }, { "code": null, "e": 9552, "s": 9550, "text": "C" }, { "code": null, "e": 9557, "s": 9552, "text": "Java" }, { "code": null, "e": 9565, "s": 9557, "text": "Python3" }, { "code": "// C++ program to add three numbers// with the help of above designed// algorithm#include <bits/stdc++.h>using namespace std; int main(){ // Variables to take the input of // the 3 numbers int num1, num2, num3; // Variable to store the resultant sum int sum; // Take the 3 numbers as input cout << \"Enter the 1st number: \"; cin >> num1; cout << \" \" << num1 << endl; cout << \"Enter the 2nd number: \"; cin >> num2; cout << \" \" << num2 << endl; cout << \"Enter the 3rd number: \"; cin >> num3; cout << \" \" << num3; // Calculate the sum using + operator // and store it in variable sum sum = num1 + num2 + num3; // Print the sum cout << \"\\nSum of the 3 numbers is: \" << sum; return 0;} // This code is contributed by shivanisinghss2110", "e": 10386, "s": 9565, "text": null }, { "code": "// C program to add three numbers// with the help of above designed algorithm #include <stdio.h> int main(){ // Variables to take the input of the 3 numbers int num1, num2, num3; // Variable to store the resultant sum int sum; // Take the 3 numbers as input printf(\"Enter the 1st number: \"); scanf(\"%d\", &num1); printf(\"%d\\n\", num1); printf(\"Enter the 2nd number: \"); scanf(\"%d\", &num2); printf(\"%d\\n\", num2); printf(\"Enter the 3rd number: \"); scanf(\"%d\", &num3); printf(\"%d\\n\", num3); // Calculate the sum using + operator // and store it in variable sum sum = num1 + num2 + num3; // Print the sum printf(\"\\nSum of the 3 numbers is: %d\", sum); return 0;}", "e": 11110, "s": 10386, "text": null }, { "code": "// Java program to add the three numbers// with the help of above designed// algorithmimport java.util.*; class GFG { public static void main(String[] args) { // Variable to store the resultant sum int sum = 0; // Declare the object and initialize with // predefined standard input object Scanner sc = new Scanner(System.in); // Scanner definition // Variables to take the input of // the 3 numbers System.out.println(\"Enter the 1st number: \"); int num1 = sc.nextInt(); // input is an Integer // read by nextInt() function System.out.println(\" \" + num1); System.out.println(\"Enter the 2nd number: \"); int num2 = sc.nextInt(); System.out.println(\" \" + num2); System.out.println(\"Enter the 3rd number: \"); int num3 = sc.nextInt(); System.out.println(\" \" + num3); // Calculate the sum using + operator // and store it in variable sum sum = num1 + num2 + num3; System.out.println(\"Sum of the 3 numbers is = \" + sum); }} /*This code is contributed by Rishab Dugar*/", "e": 12304, "s": 11110, "text": null }, { "code": "# Python3 program to add three numbers# with the help of above designed# algorithm if __name__ == \"__main__\": # Variables to take the input of # the 3 numbers num1 = num2 = num3 = 0 # Variable to store the resultant sum sum = 0 # Take the 3 numbers as input num1 = int(input(\"Enter the 1st number: \")) num2 = int(input(\"Enter the 2nd number: \")) num3 = int(input(\"Enter the 3rd number: \")) # Calculate the sum using + operator # and store it in variable sum sum = num1 + num2 + num3 # Print the sum print(\"\\nSum of the 3 numbers is:\", sum)", "e": 12894, "s": 12304, "text": null }, { "code": null, "e": 13014, "s": 12894, "text": "Enter the 1st number: 0\nEnter the 2nd number: 0\nEnter the 3rd number: -1577141152\n\nSum of the 3 numbers is: -1577141152" }, { "code": null, "e": 13303, "s": 13014, "text": "One problem, many solutions: The solution to an algorithm can be or cannot be more than one. It means that while implementing the algorithm, there can be more than one method to implement it. For example, in the above problem to add 3 numbers, the sum can be calculated in many ways like:" }, { "code": null, "e": 13314, "s": 13303, "text": "+ operator" }, { "code": null, "e": 13333, "s": 13314, "text": "Bit-wise operators" }, { "code": null, "e": 13341, "s": 13333, "text": ". . etc" }, { "code": null, "e": 13494, "s": 13341, "text": "For a standard algorithm to be good, it must be efficient. Hence the efficiency of an algorithm must be checked and maintained. It can be in two stages:" }, { "code": null, "e": 14495, "s": 13494, "text": "Priori Analysis: “Priori” means “before”. Hence Priori analysis means checking the algorithm before its implementation. In this, the algorithm is checked when it is written in the form of theoretical steps. This Efficiency of an algorithm is measured by assuming that all other factors, for example, processor speed, are constant and have no effect on the implementation. This is done usually by the algorithm designer. This analysis is independent of the type of hardware and language of the compiler. It gives the approximate answers for the complexity of the program.Posterior Analysis: “Posterior” means “after”. Hence Posterior analysis means checking the algorithm after its implementation. In this, the algorithm is checked by implementing it in any programming language and executing it. This analysis helps to get the actual and real analysis report about correctness, space required, time consumed etc. That is, it is dependent on the language of the compiler and the type of hardware used." }, { "code": null, "e": 15066, "s": 14495, "text": "Priori Analysis: “Priori” means “before”. Hence Priori analysis means checking the algorithm before its implementation. In this, the algorithm is checked when it is written in the form of theoretical steps. This Efficiency of an algorithm is measured by assuming that all other factors, for example, processor speed, are constant and have no effect on the implementation. This is done usually by the algorithm designer. This analysis is independent of the type of hardware and language of the compiler. It gives the approximate answers for the complexity of the program." }, { "code": null, "e": 15497, "s": 15066, "text": "Posterior Analysis: “Posterior” means “after”. Hence Posterior analysis means checking the algorithm after its implementation. In this, the algorithm is checked by implementing it in any programming language and executing it. This analysis helps to get the actual and real analysis report about correctness, space required, time consumed etc. That is, it is dependent on the language of the compiler and the type of hardware used." }, { "code": null, "e": 15905, "s": 15497, "text": "An algorithm is defined as complex based on the amount of Space and Time it consumes. Hence the Complexity of an algorithm refers to the measure of the Time that it will need to execute and get the expected output, and the Space it will need to store all the data (input, temporary data and output). Hence these two factors define the efficiency of an algorithm. The two factors of Algorithm Complexity are:" }, { "code": null, "e": 16022, "s": 15905, "text": "Time Factor: Time is measured by counting the number of key operations such as comparisons in the sorting algorithm." }, { "code": null, "e": 16118, "s": 16022, "text": "Space Factor: Space is measured by counting the maximum memory space required by the algorithm." }, { "code": null, "e": 16190, "s": 16118, "text": "Therefore the complexity of an algorithm can be divided into two types:" }, { "code": null, "e": 16403, "s": 16190, "text": "1. Space Complexity: The space complexity of an algorithm refers to the amount of memory used by the algorithm to store the variables and get the result. This can be for inputs, temporary operations, or outputs. " }, { "code": null, "e": 16533, "s": 16403, "text": "How to calculate Space Complexity?The space complexity of an algorithm is calculated by determining the following 2 components: " }, { "code": null, "e": 16683, "s": 16533, "text": "Fixed Part: This refers to the space that is definitely required by the algorithm. For example, input variables, output variables, program size, etc." }, { "code": null, "e": 17069, "s": 16683, "text": "Variable Part: This refers to the space that can be different based on the implementation of the algorithm. For example, temporary variables, dynamic memory allocation, recursion stack space, etc.Therefore Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I) is the variable part of the algorithm, which depends on instance characteristic I." }, { "code": null, "e": 17125, "s": 17069, "text": "Example: Consider the below algorithm for Linear Search" }, { "code": null, "e": 17658, "s": 17125, "text": "Step 1: STARTStep 2: Get the array in arr and the number to be searched in xStep 3: Start from the leftmost element of arr[] and one by one compare x with each element of arr[]Step 4: If x matches with an element, Print True.Step 5: If x doesn’t match with any of the elements, Print False.Step 6: ENDHere, There are 2 variables arr[], and x, where the arr[] is the variable part and x is the fixed part. Hence S(P) = 1+1. Now, space depends on data types of given variables and constant types and it will be multiplied accordingly." }, { "code": null, "e": 17897, "s": 17658, "text": "2. Time Complexity: The time complexity of an algorithm refers to the amount of time that is required by the algorithm to execute and get the result. This can be for normal operations, conditional if-else statements, loop statements, etc." }, { "code": null, "e": 18029, "s": 17897, "text": "How to calculate Time Complexity?The time complexity of an algorithm is also calculated by determining the following 2 components: " }, { "code": null, "e": 18162, "s": 18029, "text": "Constant time part: Any instruction that is executed just once comes in this part. For example, input, output, if-else, switch, etc." }, { "code": null, "e": 18496, "s": 18162, "text": "Variable Time Part: Any instruction that is executed more than once, say n times, comes in this part. For example, loops, recursion, etc.Therefore Time complexity of any algorithm P is T(P) = C + TP(I), where C is the constant time part and TP(I) is the variable part of the algorithm, which depends on the instance characteristic I." }, { "code": null, "e": 18592, "s": 18496, "text": "Example: In the algorithm of Linear Search above, the time complexity is calculated as follows:" }, { "code": null, "e": 18845, "s": 18592, "text": "Step 1: –Constant TimeStep 2: –Constant TimeStep 3: –Variable Time (Till the length of the Array, say n, or the index of the found element)Step 4: –Constant TimeStep 5: –Constant TimeStep 6: –Constant TimeHence, T(P) = 5 + n, which can be said as T(n)." }, { "code": null, "e": 18859, "s": 18845, "text": "AnubhavMittal" }, { "code": null, "e": 18872, "s": 18859, "text": "itskawal2000" }, { "code": null, "e": 18891, "s": 18872, "text": "shivanisinghss2110" }, { "code": null, "e": 18907, "s": 18891, "text": "amartyaghoshgfg" }, { "code": null, "e": 18922, "s": 18907, "text": "piyushsri20146" }, { "code": null, "e": 18934, "s": 18922, "text": "ece20becd76" }, { "code": null, "e": 18951, "s": 18934, "text": "shraddhajain3131" }, { "code": null, "e": 18967, "s": 18951, "text": "kingrishabdugar" }, { "code": null, "e": 18978, "s": 18967, "text": "animeshdey" }, { "code": null, "e": 19012, "s": 18978, "text": "Algorithms-Analysis of Algorithms" }, { "code": null, "e": 19023, "s": 19012, "text": "Algorithms" }, { "code": null, "e": 19040, "s": 19023, "text": "Computer Subject" }, { "code": null, "e": 19056, "s": 19040, "text": "Data Structures" }, { "code": null, "e": 19072, "s": 19056, "text": "Data Structures" }, { "code": null, "e": 19083, "s": 19072, "text": "Algorithms" }, { "code": null, "e": 19181, "s": 19083, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 19206, "s": 19181, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 19255, "s": 19206, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 19299, "s": 19255, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 19330, "s": 19299, "text": "Difference between BFS and DFS" }, { "code": null, "e": 19340, "s": 19330, "text": "Recursion" }, { "code": null, "e": 19389, "s": 19340, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 19434, "s": 19389, "text": "Software Engineering | Coupling and Cohesion" }, { "code": null, "e": 19467, "s": 19434, "text": "Type Checking in Compiler Design" }, { "code": null, "e": 19518, "s": 19467, "text": "Difference between NP hard and NP complete problem" } ]
Trinomial Triangle
02 Jun, 2022 The trinomial triangle is a variation of Pascal’s triangle. The difference between the two is that an entry in the trinomial triangle is the sum of the three (rather than the two in Pascal’s triangle) entries above it : The k-th entry of the n-th row is denoted by : Rows are counted starting from 0. The entries of the n-th row are indexed starting with -n from the left, and the middle entry has index 0. The symmetry of the entries of a row about the middle entry is expressed by the relationship Properties : The n-th row corresponds to the coefficients in the polynomial expansion of the expansion of the trinomial (1 + x + x2) raised to the n-th power. or Symmetricallyhence the alternative name trinomial coefficients because of their relationship to the multinomial coefficients : The diagonals have intersecting properties, such as their relationship to the triangular numbers. The sum of the elements of n-th row is 3n. Recursion formula The trinomial coefficients can be generated using the following recursion formula : where, , for k nApplications : The triangle corresponds to the number of possible paths that can be taken by the king in a game of chess. The entry in a cell represents the number of different paths (using minimum number of moves) the king can take to reach the cell. The coefficient of xk in the polynomial (1 + x + x2)n specifies the number of different ways of randomly drawing k cards from two sets of n identical playing cards. For example, in such a card game with two sets of the three cards A, B, C , the choices look like this : Given a positive number n. The task is to print Trinomial Triangle of height n. Examples: Input : n = 4 Output : 1 1 1 1 1 2 3 2 1 1 3 6 7 6 3 1 Input : n = 5 Output : 1 1 1 1 1 2 3 2 1 1 3 6 7 6 3 1 1 4 10 16 19 16 10 4 1 Below is the implementation of printing trinomial triangle of height n : C++ Java Python3 C# PHP Javascript // CPP Program to print trinomial triangle.#include<bits/stdc++.h>using namespace std; // Function to find the trinomial triangle value.int TrinomialValue(int n, int k){ // base case if (n == 0 && k == 0) return 1; // base case if(k < -n || k > n) return 0; // recursive step. return TrinomialValue (n - 1, k - 1) + TrinomialValue (n - 1, k) + TrinomialValue (n - 1, k + 1);} // Function to print Trinomial Triangle of height n.void printTrinomial(int n){ // printing n rows. for (int i = 0; i < n; i++) { // printing first half of triangle for (int j = -i; j <= 0; j++) cout << TrinomialValue(i, j) << " "; // printing second half of triangle. for (int j = 1; j <= i; j++) cout << TrinomialValue(i, j) << " "; cout << endl; }} // Driven Programint main(){ int n = 4; printTrinomial(n); return 0;} // Java Program to print trinomial triangle.import java.util.*;import java.lang.*; public class GfG { // Function to find the trinomial // triangle value. public static int TrinomialValue(int n, int k) { // base case if (n == 0 && k == 0) return 1; // base case if (k < -n || k > n) return 0; // recursive step. return TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1); } // Function to print Trinomial // Triangle of height n. public static void printTrinomial(int n) { // printing n rows. for (int i = 0; i < n; i++) { // printing first half of triangle for (int j = -i; j <= 0; j++) System.out.print(TrinomialValue(i, j) + " "); // printing second half of triangle. for (int j = 1; j <= i; j++) System.out.print(TrinomialValue(i, j) + " "); System.out.println(); } } // driver function public static void main(String argc[]) { int n = 4; printTrinomial(n); } } /* This code is contributed by Sagar Shukla */ # Python3 code to print trinomial triangle. # Function to find the trinomial triangle value.def TrinomialValue(n, k): # base case if n == 0 and k == 0: return 1 # base case if k < -n or k > n: return 0 # recursive step. return (TrinomialValue (n - 1, k - 1)+ TrinomialValue (n - 1, k)+ TrinomialValue (n - 1, k + 1)) # Function to print Trinomial Triangle of height n.def printTrinomial( n ): # printing n rows. for i in range(n): # printing first half of triangle for j in range(-i, 1): print(TrinomialValue(i, j),end=" ") # printing second half of triangle. for j in range(1, i+1): print( TrinomialValue(i, j),end=" ") print("\n",end='') # Driven Coden = 4printTrinomial(n) # This code is contributed by "Sharad_Bhardwaj". // C# Program to print trinomial triangle.using System; public class GfG { // Function to find the trinomial // triangle value. public static int TrinomialValue(int n, int k) { // base case if (n == 0 && k == 0) return 1; // base case if (k < -n || k > n) return 0; // recursive step. return TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1); } // Function to print Trinomial // Triangle of height n. public static void printTrinomial(int n) { // printing n rows. for (int i = 0; i < n; i++) { // printing first half of triangle for (int j = -i; j <= 0; j++) Console.Write(TrinomialValue(i, j) + " "); // printing second half of triangle. for (int j = 1; j <= i; j++) Console.Write(TrinomialValue(i, j) + " "); Console.WriteLine(); } } // Driver function public static void Main() { int n = 4; printTrinomial(n); } } /* This code is contributed by Vt_m */ <?php// PHP Program to print// trinomial triangle. // Function to find the// trinomial triangle value.function TrinomialValue($n, $k){ // base case if ($n == 0 && $k == 0) return 1; // base case if($k < -$n || $k > $n) return 0; // recursive step. return TrinomialValue ($n - 1, $k - 1) + TrinomialValue ($n - 1, $k) + TrinomialValue ($n - 1, $k + 1);} // Function to print Trinomial// Triangle of height n.function printTrinomial($n){ // printing n rows. for ($i = 0; $i < $n; $i++) { // printing first // half of triangle for ($j = -$i; $j <= 0; $j++) echo TrinomialValue($i, $j), " "; // printing second // half of triangle. for ($j = 1; $j <= $i; $j++) echo TrinomialValue($i, $j) , " "; echo "\n"; }} // Driver Code$n = 4; printTrinomial($n); // This code is contributed// by ajit?> <script> // JavaScript Program to print trinomial triangle. // Function to find the trinomial // triangle value. function TrinomialValue(n, k) { // base case if (n == 0 && k == 0) return 1; // base case if (k < -n || k > n) return 0; // recursive step. return TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1); } // Function to print Trinomial // Triangle of height n. function printTrinomial(n) { // printing n rows. for (let i = 0; i < n; i++) { // printing first half of triangle for (let j = -i; j <= 0; j++) document.write(TrinomialValue(i, j) + " "); // printing second half of triangle. for (let j = 1; j <= i; j++) document.write(TrinomialValue(i, j) + " "); document.write("<br/>"); } } // Driver code let n = 4; printTrinomial(n); // This code is contributed by code_hunt.</script> Output: 1 1 1 1 1 2 3 2 1 1 3 6 7 6 3 1 Below is the implementation of printing Trinomial Triangle using Dynamic Programming and property of trinomial triangle i.e C++ C Java Python3 C# PHP Javascript // C++ Program to print trinomial triangle.#include <bits/stdc++.h>#define MAX 10using namespace std; // Function to find the trinomial triangle value.int TrinomialValue(int dp[MAX][MAX], int n, int k){ // Using property of trinomial triangle. if (k < 0) k = -k; // If value already calculated, return that. if (dp[n][k] != 0) return dp[n][k]; // base case if (n == 0 && k == 0) return 1; // base case if (k < -n || k > n) return 0; // recursive step and storing the value. return (dp[n][k] = TrinomialValue(dp, n - 1, k - 1) + TrinomialValue(dp, n - 1, k) + TrinomialValue(dp, n - 1, k + 1));} // Function to print Trinomial Triangle of height n.void printTrinomial(int n){ int dp[MAX][MAX] = { 0 }; // printing n rows. for (int i = 0; i < n; i++) { // printing first half of triangle for (int j = -i; j <= 0; j++) cout << TrinomialValue(dp, i, j) << " "; // printing second half of triangle. for (int j = 1; j <= i; j++) cout << TrinomialValue(dp, i, j) << " "; cout << endl; }} // Driven Programint main(){ int n = 4; printTrinomial(n); return 0;} // The code is contributed by Gautam goel (gautamgoel962) // CPP Program to print trinomial triangle.#include<bits/stdc++.h>#define MAX 10using namespace std; // Function to find the trinomial triangle value.int TrinomialValue(int dp[MAX][MAX], int n, int k){ // Using property of trinomial triangle. if (k < 0) k = -k; // If value already calculated, return that. if (dp[n][k] != 0) return dp[n][k]; // base case if (n == 0 && k == 0) return 1; // base case if(k < -n || k > n) return 0; // recursive step and storing the value. return (dp[n][k] = TrinomialValue(dp, n - 1, k - 1) + TrinomialValue(dp, n - 1, k) + TrinomialValue(dp, n - 1, k + 1));} // Function to print Trinomial Triangle of height n.void printTrinomial(int n){ int dp[MAX][MAX] = { 0 }; // printing n rows. for (int i = 0; i < n; i++) { // printing first half of triangle for (int j = -i; j <= 0; j++) cout << TrinomialValue(dp, i, j) << " "; // printing second half of triangle. for (int j = 1; j <= i; j++) cout << TrinomialValue(dp, i, j) << " "; cout << endl; }} // Driven Programint main(){ int n = 4; printTrinomial(n); return 0;} // Java Program to print trinomial triangle.import java.util.*;import java.lang.*; public class GfG { private static final int MAX = 10; // Function to find the trinomial triangle value. public static int TrinomialValue(int dp[][], int n, int k) { // Using property of trinomial triangle. if (k < 0) k = -k; // If value already calculated, return that. if (dp[n][k] != 0) return dp[n][k]; // base case if (n == 0 && k == 0) return 1; // base case if (k < -n || k > n) return 0; // recursive step and storing the value. return (dp[n][k] = TrinomialValue(dp, n - 1, k - 1) + TrinomialValue(dp, n - 1, k) + TrinomialValue(dp, n - 1, k + 1)); } // Function to print Trinomial Triangle of height n. public static void printTrinomial(int n) { int[][] dp = new int[MAX][MAX]; // printing n rows. for (int i = 0; i < n; i++) { // printing first half of triangle for (int j = -i; j <= 0; j++) System.out.print(TrinomialValue(dp, i, j) + " "); // printing second half of triangle. for (int j = 1; j <= i; j++) System.out.print(TrinomialValue(dp, i, j) + " "); System.out.println(); } } // driver function public static void main(String argc[]) { int n = 4; printTrinomial(n); } }/* This code is contributed by Sagar Shukla */ # Python3 code to print trinomial triangle. # Function to find the trinomial triangle value.def TrinomialValue(dp , n , k): # Using property of trinomial triangle. if k < 0: k = -k # If value already calculated, return that. if dp[n][k] != 0: return dp[n][k] # base case if n == 0 and k == 0: return 1 # base case if k < -n or k > n: return 0 # recursive step and storing the value. return (TrinomialValue(dp, n - 1, k - 1) + TrinomialValue(dp, n - 1, k)+ TrinomialValue(dp, n - 1, k + 1)) # Function to print Trinomial Triangle of height n.def printTrinomial(n): dp = [[0]*10]*10 # printing n rows. for i in range(n): # printing first half of triangle for j in range(-i,1): print(TrinomialValue(dp, i, j),end=" ") # printing second half of triangle. for j in range(1,i+1): print(TrinomialValue(dp, i, j),end=" ") print("\n",end='') # Driven Programn = 4printTrinomial(n) # This code is contributed by "Sharad_Bhardwaj". // C# Program to print// trinomial triangle.using System; class GFG{ private static int MAX = 10; // Function to find the // trinomial triangle value. public static int TrinomialValue(int [,]dp, int n, int k) { // Using property of // trinomial triangle. if (k < 0) k = -k; // If value already // calculated, return that. if (dp[n, k] != 0) return dp[n, k]; // base case if (n == 0 && k == 0) return 1; // base case if (k < -n || k > n) return 0; // recursive step and storing the value. return (dp[n, k] = TrinomialValue(dp, n - 1, k - 1) + TrinomialValue(dp, n - 1, k) + TrinomialValue(dp, n - 1, k + 1)); } // Function to print Trinomial // Triangle of height n. public static void printTrinomial(int n) { int[,] dp = new int[MAX, MAX]; // printing n rows. for (int i = 0; i < n; i++) { // printing first // half of triangle for (int j = -i; j <= 0; j++) Console.Write(TrinomialValue(dp, i, j) + " "); // printing second half // of triangle. for (int j = 1; j <= i; j++) Console.Write(TrinomialValue(dp, i, j) + " "); Console.WriteLine(); } } // Driver Code static public void Main () { int n = 4; printTrinomial(n); }} // This code is contributed by ajit <?php// PHP Program to print// trinomial triangle. $MAX = 10; // Function to find the// trinomial triangle value.function TrinomialValue($dp, $n, $k){ // Using property of // trinomial triangle. if ($k < 0) $k = -$k; // If value already // calculated, return that. if ($dp[$n][$k] != 0) return $dp[$n][$k]; // base case if ($n == 0 && $k == 0) return 1; // base case if($k < -$n || $k > $n) return 0; // recursive step and // storing the value. return ($dp[$n][$k] = TrinomialValue($dp, $n - 1, $k - 1) + TrinomialValue($dp, $n - 1, $k) + TrinomialValue($dp, $n - 1, $k + 1));} // Function to print Trinomial// Triangle of height n.function printTrinomial($n){ global $MAX; $dp; for ($i = 0; $i < $MAX; $i++) for ($j = 0; $j < $MAX; $j++) $dp[$i][$j] = 0; // printing n rows. for ($i = 0; $i < $n; $i++) { // printing first // half of triangle for ($j = -$i; $j <= 0; $j++) echo TrinomialValue($dp, $i, $j)." "; // printing second // half of triangle. for ($j = 1; $j <= $i; $j++) echo TrinomialValue($dp, $i, $j)." "; echo "\n"; }} // Driven Code$n = 4;printTrinomial($n); // This code is contributed by mits?> <script> // Javascript Program to print trinomial triangle.var MAX = 10 // Function to find the trinomial triangle value.function TrinomialValue(dp, n, k){ // Using property of trinomial triangle. if (k < 0) k = -k; // If value already calculated, return that. if (dp[n][k] != 0) return dp[n][k]; // base case if (n == 0 && k == 0) return 1; // base case if(k < -n || k > n) return 0; // recursive step and storing the value. return (dp[n][k] = TrinomialValue(dp, n - 1, k - 1) + TrinomialValue(dp, n - 1, k) + TrinomialValue(dp, n - 1, k + 1));} // Function to print Trinomial Triangle of height n.function printTrinomial(n){ var dp = Array.from(Array(MAX), ()=> Array(MAX).fill(0)); // printing n rows. for (var i = 0; i < n; i++) { // printing first half of triangle for (var j = -i; j <= 0; j++) document.write( TrinomialValue(dp, i, j) + " "); // printing second half of triangle. for (var j = 1; j <= i; j++) document.write( TrinomialValue(dp, i, j) + " "); document.write("<br>"); }} // Driven Programvar n = 4;printTrinomial(n); </script> Output: 1 1 1 1 1 2 3 2 1 1 3 6 7 6 3 1 jit_t Mithun Kumar code_hunt rutvik_56 surinderdawra388 simmytarika5 gautamgoel962 Combinatorial Mathematical Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Write a program to print all permutations of a given string Permutation and Combination in Python Factorial of a large number Count of subsets with sum equal to X itertools.combinations() module in Python to print all possible combinations 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": "\n02 Jun, 2022" }, { "code": null, "e": 274, "s": 52, "text": "The trinomial triangle is a variation of Pascal’s triangle. The difference between the two is that an entry in the trinomial triangle is the sum of the three (rather than the two in Pascal’s triangle) entries above it : " }, { "code": null, "e": 569, "s": 274, "text": "The k-th entry of the n-th row is denoted by : Rows are counted starting from 0. The entries of the n-th row are indexed starting with -n from the left, and the middle entry has index 0. The symmetry of the entries of a row about the middle entry is expressed by the relationship Properties : " }, { "code": null, "e": 847, "s": 569, "text": "The n-th row corresponds to the coefficients in the polynomial expansion of the expansion of the trinomial (1 + x + x2) raised to the n-th power. or Symmetricallyhence the alternative name trinomial coefficients because of their relationship to the multinomial coefficients : " }, { "code": null, "e": 947, "s": 847, "text": "The diagonals have intersecting properties, such as their relationship to the triangular numbers. " }, { "code": null, "e": 990, "s": 947, "text": "The sum of the elements of n-th row is 3n." }, { "code": null, "e": 1125, "s": 990, "text": "Recursion formula The trinomial coefficients can be generated using the following recursion formula : where, , for k nApplications : " }, { "code": null, "e": 1364, "s": 1125, "text": "The triangle corresponds to the number of possible paths that can be taken by the king in a game of chess. The entry in a cell represents the number of different paths (using minimum number of moves) the king can take to reach the cell. " }, { "code": null, "e": 1638, "s": 1366, "text": "The coefficient of xk in the polynomial (1 + x + x2)n specifies the number of different ways of randomly drawing k cards from two sets of n identical playing cards. For example, in such a card game with two sets of the three cards A, B, C , the choices look like this : " }, { "code": null, "e": 1730, "s": 1638, "text": "Given a positive number n. The task is to print Trinomial Triangle of height n. Examples: " }, { "code": null, "e": 1865, "s": 1730, "text": "Input : n = 4\nOutput :\n1\n1 1 1\n1 2 3 2 1\n1 3 6 7 6 3 1\n\nInput : n = 5\nOutput :\n1\n1 1 1 \n1 2 3 2 1\n1 3 6 7 6 3 1\n1 4 10 16 19 16 10 4 1" }, { "code": null, "e": 1940, "s": 1865, "text": "Below is the implementation of printing trinomial triangle of height n : " }, { "code": null, "e": 1944, "s": 1940, "text": "C++" }, { "code": null, "e": 1949, "s": 1944, "text": "Java" }, { "code": null, "e": 1957, "s": 1949, "text": "Python3" }, { "code": null, "e": 1960, "s": 1957, "text": "C#" }, { "code": null, "e": 1964, "s": 1960, "text": "PHP" }, { "code": null, "e": 1975, "s": 1964, "text": "Javascript" }, { "code": "// CPP Program to print trinomial triangle.#include<bits/stdc++.h>using namespace std; // Function to find the trinomial triangle value.int TrinomialValue(int n, int k){ // base case if (n == 0 && k == 0) return 1; // base case if(k < -n || k > n) return 0; // recursive step. return TrinomialValue (n - 1, k - 1) + TrinomialValue (n - 1, k) + TrinomialValue (n - 1, k + 1);} // Function to print Trinomial Triangle of height n.void printTrinomial(int n){ // printing n rows. for (int i = 0; i < n; i++) { // printing first half of triangle for (int j = -i; j <= 0; j++) cout << TrinomialValue(i, j) << \" \"; // printing second half of triangle. for (int j = 1; j <= i; j++) cout << TrinomialValue(i, j) << \" \"; cout << endl; }} // Driven Programint main(){ int n = 4; printTrinomial(n); return 0;}", "e": 2944, "s": 1975, "text": null }, { "code": "// Java Program to print trinomial triangle.import java.util.*;import java.lang.*; public class GfG { // Function to find the trinomial // triangle value. public static int TrinomialValue(int n, int k) { // base case if (n == 0 && k == 0) return 1; // base case if (k < -n || k > n) return 0; // recursive step. return TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1); } // Function to print Trinomial // Triangle of height n. public static void printTrinomial(int n) { // printing n rows. for (int i = 0; i < n; i++) { // printing first half of triangle for (int j = -i; j <= 0; j++) System.out.print(TrinomialValue(i, j) + \" \"); // printing second half of triangle. for (int j = 1; j <= i; j++) System.out.print(TrinomialValue(i, j) + \" \"); System.out.println(); } } // driver function public static void main(String argc[]) { int n = 4; printTrinomial(n); } } /* This code is contributed by Sagar Shukla */", "e": 4269, "s": 2944, "text": null }, { "code": "# Python3 code to print trinomial triangle. # Function to find the trinomial triangle value.def TrinomialValue(n, k): # base case if n == 0 and k == 0: return 1 # base case if k < -n or k > n: return 0 # recursive step. return (TrinomialValue (n - 1, k - 1)+ TrinomialValue (n - 1, k)+ TrinomialValue (n - 1, k + 1)) # Function to print Trinomial Triangle of height n.def printTrinomial( n ): # printing n rows. for i in range(n): # printing first half of triangle for j in range(-i, 1): print(TrinomialValue(i, j),end=\" \") # printing second half of triangle. for j in range(1, i+1): print( TrinomialValue(i, j),end=\" \") print(\"\\n\",end='') # Driven Coden = 4printTrinomial(n) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 5169, "s": 4269, "text": null }, { "code": "// C# Program to print trinomial triangle.using System; public class GfG { // Function to find the trinomial // triangle value. public static int TrinomialValue(int n, int k) { // base case if (n == 0 && k == 0) return 1; // base case if (k < -n || k > n) return 0; // recursive step. return TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1); } // Function to print Trinomial // Triangle of height n. public static void printTrinomial(int n) { // printing n rows. for (int i = 0; i < n; i++) { // printing first half of triangle for (int j = -i; j <= 0; j++) Console.Write(TrinomialValue(i, j) + \" \"); // printing second half of triangle. for (int j = 1; j <= i; j++) Console.Write(TrinomialValue(i, j) + \" \"); Console.WriteLine(); } } // Driver function public static void Main() { int n = 4; printTrinomial(n); } } /* This code is contributed by Vt_m */", "e": 6426, "s": 5169, "text": null }, { "code": "<?php// PHP Program to print// trinomial triangle. // Function to find the// trinomial triangle value.function TrinomialValue($n, $k){ // base case if ($n == 0 && $k == 0) return 1; // base case if($k < -$n || $k > $n) return 0; // recursive step. return TrinomialValue ($n - 1, $k - 1) + TrinomialValue ($n - 1, $k) + TrinomialValue ($n - 1, $k + 1);} // Function to print Trinomial// Triangle of height n.function printTrinomial($n){ // printing n rows. for ($i = 0; $i < $n; $i++) { // printing first // half of triangle for ($j = -$i; $j <= 0; $j++) echo TrinomialValue($i, $j), \" \"; // printing second // half of triangle. for ($j = 1; $j <= $i; $j++) echo TrinomialValue($i, $j) , \" \"; echo \"\\n\"; }} // Driver Code$n = 4; printTrinomial($n); // This code is contributed// by ajit?>", "e": 7393, "s": 6426, "text": null }, { "code": "<script> // JavaScript Program to print trinomial triangle. // Function to find the trinomial // triangle value. function TrinomialValue(n, k) { // base case if (n == 0 && k == 0) return 1; // base case if (k < -n || k > n) return 0; // recursive step. return TrinomialValue(n - 1, k - 1) + TrinomialValue(n - 1, k) + TrinomialValue(n - 1, k + 1); } // Function to print Trinomial // Triangle of height n. function printTrinomial(n) { // printing n rows. for (let i = 0; i < n; i++) { // printing first half of triangle for (let j = -i; j <= 0; j++) document.write(TrinomialValue(i, j) + \" \"); // printing second half of triangle. for (let j = 1; j <= i; j++) document.write(TrinomialValue(i, j) + \" \"); document.write(\"<br/>\"); } } // Driver code let n = 4; printTrinomial(n); // This code is contributed by code_hunt.</script>", "e": 8573, "s": 7393, "text": null }, { "code": null, "e": 8583, "s": 8573, "text": "Output: " }, { "code": null, "e": 8619, "s": 8583, "text": "1 \n1 1 1 \n1 2 3 2 1 \n1 3 6 7 6 3 1 " }, { "code": null, "e": 8745, "s": 8619, "text": "Below is the implementation of printing Trinomial Triangle using Dynamic Programming and property of trinomial triangle i.e " }, { "code": null, "e": 8749, "s": 8745, "text": "C++" }, { "code": null, "e": 8751, "s": 8749, "text": "C" }, { "code": null, "e": 8756, "s": 8751, "text": "Java" }, { "code": null, "e": 8764, "s": 8756, "text": "Python3" }, { "code": null, "e": 8767, "s": 8764, "text": "C#" }, { "code": null, "e": 8771, "s": 8767, "text": "PHP" }, { "code": null, "e": 8782, "s": 8771, "text": "Javascript" }, { "code": "// C++ Program to print trinomial triangle.#include <bits/stdc++.h>#define MAX 10using namespace std; // Function to find the trinomial triangle value.int TrinomialValue(int dp[MAX][MAX], int n, int k){ // Using property of trinomial triangle. if (k < 0) k = -k; // If value already calculated, return that. if (dp[n][k] != 0) return dp[n][k]; // base case if (n == 0 && k == 0) return 1; // base case if (k < -n || k > n) return 0; // recursive step and storing the value. return (dp[n][k] = TrinomialValue(dp, n - 1, k - 1) + TrinomialValue(dp, n - 1, k) + TrinomialValue(dp, n - 1, k + 1));} // Function to print Trinomial Triangle of height n.void printTrinomial(int n){ int dp[MAX][MAX] = { 0 }; // printing n rows. for (int i = 0; i < n; i++) { // printing first half of triangle for (int j = -i; j <= 0; j++) cout << TrinomialValue(dp, i, j) << \" \"; // printing second half of triangle. for (int j = 1; j <= i; j++) cout << TrinomialValue(dp, i, j) << \" \"; cout << endl; }} // Driven Programint main(){ int n = 4; printTrinomial(n); return 0;} // The code is contributed by Gautam goel (gautamgoel962)", "e": 10078, "s": 8782, "text": null }, { "code": "// CPP Program to print trinomial triangle.#include<bits/stdc++.h>#define MAX 10using namespace std; // Function to find the trinomial triangle value.int TrinomialValue(int dp[MAX][MAX], int n, int k){ // Using property of trinomial triangle. if (k < 0) k = -k; // If value already calculated, return that. if (dp[n][k] != 0) return dp[n][k]; // base case if (n == 0 && k == 0) return 1; // base case if(k < -n || k > n) return 0; // recursive step and storing the value. return (dp[n][k] = TrinomialValue(dp, n - 1, k - 1) + TrinomialValue(dp, n - 1, k) + TrinomialValue(dp, n - 1, k + 1));} // Function to print Trinomial Triangle of height n.void printTrinomial(int n){ int dp[MAX][MAX] = { 0 }; // printing n rows. for (int i = 0; i < n; i++) { // printing first half of triangle for (int j = -i; j <= 0; j++) cout << TrinomialValue(dp, i, j) << \" \"; // printing second half of triangle. for (int j = 1; j <= i; j++) cout << TrinomialValue(dp, i, j) << \" \"; cout << endl; }} // Driven Programint main(){ int n = 4; printTrinomial(n); return 0;}", "e": 11354, "s": 10078, "text": null }, { "code": "// Java Program to print trinomial triangle.import java.util.*;import java.lang.*; public class GfG { private static final int MAX = 10; // Function to find the trinomial triangle value. public static int TrinomialValue(int dp[][], int n, int k) { // Using property of trinomial triangle. if (k < 0) k = -k; // If value already calculated, return that. if (dp[n][k] != 0) return dp[n][k]; // base case if (n == 0 && k == 0) return 1; // base case if (k < -n || k > n) return 0; // recursive step and storing the value. return (dp[n][k] = TrinomialValue(dp, n - 1, k - 1) + TrinomialValue(dp, n - 1, k) + TrinomialValue(dp, n - 1, k + 1)); } // Function to print Trinomial Triangle of height n. public static void printTrinomial(int n) { int[][] dp = new int[MAX][MAX]; // printing n rows. for (int i = 0; i < n; i++) { // printing first half of triangle for (int j = -i; j <= 0; j++) System.out.print(TrinomialValue(dp, i, j) + \" \"); // printing second half of triangle. for (int j = 1; j <= i; j++) System.out.print(TrinomialValue(dp, i, j) + \" \"); System.out.println(); } } // driver function public static void main(String argc[]) { int n = 4; printTrinomial(n); } }/* This code is contributed by Sagar Shukla */", "e": 12926, "s": 11354, "text": null }, { "code": "# Python3 code to print trinomial triangle. # Function to find the trinomial triangle value.def TrinomialValue(dp , n , k): # Using property of trinomial triangle. if k < 0: k = -k # If value already calculated, return that. if dp[n][k] != 0: return dp[n][k] # base case if n == 0 and k == 0: return 1 # base case if k < -n or k > n: return 0 # recursive step and storing the value. return (TrinomialValue(dp, n - 1, k - 1) + TrinomialValue(dp, n - 1, k)+ TrinomialValue(dp, n - 1, k + 1)) # Function to print Trinomial Triangle of height n.def printTrinomial(n): dp = [[0]*10]*10 # printing n rows. for i in range(n): # printing first half of triangle for j in range(-i,1): print(TrinomialValue(dp, i, j),end=\" \") # printing second half of triangle. for j in range(1,i+1): print(TrinomialValue(dp, i, j),end=\" \") print(\"\\n\",end='') # Driven Programn = 4printTrinomial(n) # This code is contributed by \"Sharad_Bhardwaj\".", "e": 14046, "s": 12926, "text": null }, { "code": "// C# Program to print// trinomial triangle.using System; class GFG{ private static int MAX = 10; // Function to find the // trinomial triangle value. public static int TrinomialValue(int [,]dp, int n, int k) { // Using property of // trinomial triangle. if (k < 0) k = -k; // If value already // calculated, return that. if (dp[n, k] != 0) return dp[n, k]; // base case if (n == 0 && k == 0) return 1; // base case if (k < -n || k > n) return 0; // recursive step and storing the value. return (dp[n, k] = TrinomialValue(dp, n - 1, k - 1) + TrinomialValue(dp, n - 1, k) + TrinomialValue(dp, n - 1, k + 1)); } // Function to print Trinomial // Triangle of height n. public static void printTrinomial(int n) { int[,] dp = new int[MAX, MAX]; // printing n rows. for (int i = 0; i < n; i++) { // printing first // half of triangle for (int j = -i; j <= 0; j++) Console.Write(TrinomialValue(dp, i, j) + \" \"); // printing second half // of triangle. for (int j = 1; j <= i; j++) Console.Write(TrinomialValue(dp, i, j) + \" \"); Console.WriteLine(); } } // Driver Code static public void Main () { int n = 4; printTrinomial(n); }} // This code is contributed by ajit", "e": 15856, "s": 14046, "text": null }, { "code": "<?php// PHP Program to print// trinomial triangle. $MAX = 10; // Function to find the// trinomial triangle value.function TrinomialValue($dp, $n, $k){ // Using property of // trinomial triangle. if ($k < 0) $k = -$k; // If value already // calculated, return that. if ($dp[$n][$k] != 0) return $dp[$n][$k]; // base case if ($n == 0 && $k == 0) return 1; // base case if($k < -$n || $k > $n) return 0; // recursive step and // storing the value. return ($dp[$n][$k] = TrinomialValue($dp, $n - 1, $k - 1) + TrinomialValue($dp, $n - 1, $k) + TrinomialValue($dp, $n - 1, $k + 1));} // Function to print Trinomial// Triangle of height n.function printTrinomial($n){ global $MAX; $dp; for ($i = 0; $i < $MAX; $i++) for ($j = 0; $j < $MAX; $j++) $dp[$i][$j] = 0; // printing n rows. for ($i = 0; $i < $n; $i++) { // printing first // half of triangle for ($j = -$i; $j <= 0; $j++) echo TrinomialValue($dp, $i, $j).\" \"; // printing second // half of triangle. for ($j = 1; $j <= $i; $j++) echo TrinomialValue($dp, $i, $j).\" \"; echo \"\\n\"; }} // Driven Code$n = 4;printTrinomial($n); // This code is contributed by mits?>", "e": 17254, "s": 15856, "text": null }, { "code": "<script> // Javascript Program to print trinomial triangle.var MAX = 10 // Function to find the trinomial triangle value.function TrinomialValue(dp, n, k){ // Using property of trinomial triangle. if (k < 0) k = -k; // If value already calculated, return that. if (dp[n][k] != 0) return dp[n][k]; // base case if (n == 0 && k == 0) return 1; // base case if(k < -n || k > n) return 0; // recursive step and storing the value. return (dp[n][k] = TrinomialValue(dp, n - 1, k - 1) + TrinomialValue(dp, n - 1, k) + TrinomialValue(dp, n - 1, k + 1));} // Function to print Trinomial Triangle of height n.function printTrinomial(n){ var dp = Array.from(Array(MAX), ()=> Array(MAX).fill(0)); // printing n rows. for (var i = 0; i < n; i++) { // printing first half of triangle for (var j = -i; j <= 0; j++) document.write( TrinomialValue(dp, i, j) + \" \"); // printing second half of triangle. for (var j = 1; j <= i; j++) document.write( TrinomialValue(dp, i, j) + \" \"); document.write(\"<br>\"); }} // Driven Programvar n = 4;printTrinomial(n); </script>", "e": 18519, "s": 17254, "text": null }, { "code": null, "e": 18528, "s": 18519, "text": "Output: " }, { "code": null, "e": 18564, "s": 18528, "text": "1 \n1 1 1 \n1 2 3 2 1 \n1 3 6 7 6 3 1 " }, { "code": null, "e": 18570, "s": 18564, "text": "jit_t" }, { "code": null, "e": 18583, "s": 18570, "text": "Mithun Kumar" }, { "code": null, "e": 18593, "s": 18583, "text": "code_hunt" }, { "code": null, "e": 18603, "s": 18593, "text": "rutvik_56" }, { "code": null, "e": 18620, "s": 18603, "text": "surinderdawra388" }, { "code": null, "e": 18633, "s": 18620, "text": "simmytarika5" }, { "code": null, "e": 18647, "s": 18633, "text": "gautamgoel962" }, { "code": null, "e": 18661, "s": 18647, "text": "Combinatorial" }, { "code": null, "e": 18674, "s": 18661, "text": "Mathematical" }, { "code": null, "e": 18687, "s": 18674, "text": "Mathematical" }, { "code": null, "e": 18701, "s": 18687, "text": "Combinatorial" }, { "code": null, "e": 18799, "s": 18701, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 18859, "s": 18799, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 18897, "s": 18859, "text": "Permutation and Combination in Python" }, { "code": null, "e": 18925, "s": 18897, "text": "Factorial of a large number" }, { "code": null, "e": 18962, "s": 18925, "text": "Count of subsets with sum equal to X" }, { "code": null, "e": 19039, "s": 18962, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 19069, "s": 19039, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 19112, "s": 19069, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 19172, "s": 19112, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 19187, "s": 19172, "text": "C++ Data Types" } ]
HTML <blockquote> Tag
17 Mar, 2022 The <blockquote> tag in HTML is used to display the long quotations (a section that is quoted from another source). It changes the alignment to make it unique from others. It contains both opening and closing tags. In blockquote tag, we can use elements like heading, list, paragraph, etc. Note: The <blockquote> tag in HTML4.1 defines the long quotation i.e. quotations that span multiple lines. But in HTML5, the <blockquote> tag specify the section that is quoted from other source. Syntax: <blockquote> Contents... </blockquote> Attribute: It contains a single attribute cite which is used to specify the source of the quotation. The below examples illustrate the blockquote tag: Example 1: HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2><blockquote> Tag</h2> <!--blockquote Tag starts here --> <blockquote cite="https://www.geeksforgeeks.org/html-tutorials/"> <p> HTML stands for HyperText Markup Language. It is used to design web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within tag which defines the structure of web pages. </p> </blockquote> <!--blockquote Tag ends here --> </body></html> Output: Example 2: HTML <!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2><blockquote> Tag</h2> <p>This is blockquote Tag text with attribute cite</p> <!--blockquote Tag starts here --> <blockquote cite="www.geeksforgeeks.org"> GeeksforGeeks:A computer science portal for geeks </blockquote> <!--blockquote Tag ends here --></body> </html> Output: Supported Browsers: Google Chrome Internet Explorer Firefox Safari Opera shubhamyadav4 HTML-Tags HTML HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? CSS to put icon inside an input element in a form Types of CSS (Cascading Style Sheet) HTTP headers | Content-Type
[ { "code": null, "e": 54, "s": 26, "text": "\n17 Mar, 2022" }, { "code": null, "e": 344, "s": 54, "text": "The <blockquote> tag in HTML is used to display the long quotations (a section that is quoted from another source). It changes the alignment to make it unique from others. It contains both opening and closing tags. In blockquote tag, we can use elements like heading, list, paragraph, etc." }, { "code": null, "e": 541, "s": 344, "text": "Note: The <blockquote> tag in HTML4.1 defines the long quotation i.e. quotations that span multiple lines. But in HTML5, the <blockquote> tag specify the section that is quoted from other source. " }, { "code": null, "e": 550, "s": 541, "text": "Syntax: " }, { "code": null, "e": 589, "s": 550, "text": "<blockquote> Contents... </blockquote>" }, { "code": null, "e": 691, "s": 589, "text": "Attribute: It contains a single attribute cite which is used to specify the source of the quotation. " }, { "code": null, "e": 752, "s": 691, "text": "The below examples illustrate the blockquote tag: Example 1:" }, { "code": null, "e": 757, "s": 752, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2><blockquote> Tag</h2> <!--blockquote Tag starts here --> <blockquote cite=\"https://www.geeksforgeeks.org/html-tutorials/\"> <p> HTML stands for HyperText Markup Language. It is used to design web pages using a markup language. HTML is the combination of Hypertext and Markup language. Hypertext defines the link between the web pages. A markup language is used to define the text document within tag which defines the structure of web pages. </p> </blockquote> <!--blockquote Tag ends here --> </body></html>", "e": 1399, "s": 757, "text": null }, { "code": null, "e": 1408, "s": 1399, "text": "Output: " }, { "code": null, "e": 1420, "s": 1408, "text": "Example 2: " }, { "code": null, "e": 1425, "s": 1420, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <h1>GeeksforGeeks</h1> <h2><blockquote> Tag</h2> <p>This is blockquote Tag text with attribute cite</p> <!--blockquote Tag starts here --> <blockquote cite=\"www.geeksforgeeks.org\"> GeeksforGeeks:A computer science portal for geeks </blockquote> <!--blockquote Tag ends here --></body> </html>", "e": 1781, "s": 1425, "text": null }, { "code": null, "e": 1790, "s": 1781, "text": "Output: " }, { "code": null, "e": 1811, "s": 1790, "text": "Supported Browsers: " }, { "code": null, "e": 1825, "s": 1811, "text": "Google Chrome" }, { "code": null, "e": 1843, "s": 1825, "text": "Internet Explorer" }, { "code": null, "e": 1851, "s": 1843, "text": "Firefox" }, { "code": null, "e": 1858, "s": 1851, "text": "Safari" }, { "code": null, "e": 1864, "s": 1858, "text": "Opera" }, { "code": null, "e": 1878, "s": 1864, "text": "shubhamyadav4" }, { "code": null, "e": 1888, "s": 1878, "text": "HTML-Tags" }, { "code": null, "e": 1893, "s": 1888, "text": "HTML" }, { "code": null, "e": 1898, "s": 1893, "text": "HTML" }, { "code": null, "e": 1996, "s": 1898, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2044, "s": 1996, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2106, "s": 2044, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2156, "s": 2106, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2180, "s": 2156, "text": "REST API (Introduction)" }, { "code": null, "e": 2233, "s": 2180, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2293, "s": 2233, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2354, "s": 2293, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 2404, "s": 2354, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 2441, "s": 2404, "text": "Types of CSS (Cascading Style Sheet)" } ]
Python - Summation of float string list - GeeksforGeeks
11 Dec, 2019 Sometimes, while working with Python list, we can have a problem in which we need to find summation in list. But sometimes, we don’t have a natural number but a floating-point number in string format. This problem can occur while working with data, both in web development and Data Science domain. Let’s discuss the ways in which this problem can be solved. Method #1 : Using sum() + float() + generatorThis problem can be solved using the sum function in which we first convert the strings into float and then pass this logic in functions in respective sum function. # Python3 code to demonstrate working of# Summation of float string list# using sum() + float() + generator # initialize liststest_list = ['4.5', '7.8', '9.8', '10.3'] # printing original listprint("The original list is : " + str(test_list)) # Summation of float string list# using sum() + float() + generatorres_sum = sum(float(sub) for sub in test_list) # printing resultprint("The summation of float string list : " + str(res_sum)) The original list is : ['4.5', '7.8', '9.8', '10.3'] The summation of float string list : 32.400000000000006 Method #2 : Using loopThis is a brute force method to perform this task. In this, we iterate for the list and convert and sum the list float elements during iteration. # Python3 code to demonstrate working of# Summation of float string list# Using loop # initialize liststest_list = ['4.5', '7.8', '9.8', '10.3'] # printing original listprint("The original list is : " + str(test_list)) # Summation of float string list# Using loopres_sum = 0 for ele in test_list: res_sum += float(ele) # printing resultprint("The summation of float string list : " + str(res_sum)) The original list is : ['4.5', '7.8', '9.8', '10.3'] The summation of float string list : 32.400000000000006 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 25537, "s": 25509, "text": "\n11 Dec, 2019" }, { "code": null, "e": 25895, "s": 25537, "text": "Sometimes, while working with Python list, we can have a problem in which we need to find summation in list. But sometimes, we don’t have a natural number but a floating-point number in string format. This problem can occur while working with data, both in web development and Data Science domain. Let’s discuss the ways in which this problem can be solved." }, { "code": null, "e": 26105, "s": 25895, "text": "Method #1 : Using sum() + float() + generatorThis problem can be solved using the sum function in which we first convert the strings into float and then pass this logic in functions in respective sum function." }, { "code": "# Python3 code to demonstrate working of# Summation of float string list# using sum() + float() + generator # initialize liststest_list = ['4.5', '7.8', '9.8', '10.3'] # printing original listprint(\"The original list is : \" + str(test_list)) # Summation of float string list# using sum() + float() + generatorres_sum = sum(float(sub) for sub in test_list) # printing resultprint(\"The summation of float string list : \" + str(res_sum))", "e": 26544, "s": 26105, "text": null }, { "code": null, "e": 26654, "s": 26544, "text": "The original list is : ['4.5', '7.8', '9.8', '10.3']\nThe summation of float string list : 32.400000000000006\n" }, { "code": null, "e": 26824, "s": 26656, "text": "Method #2 : Using loopThis is a brute force method to perform this task. In this, we iterate for the list and convert and sum the list float elements during iteration." }, { "code": "# Python3 code to demonstrate working of# Summation of float string list# Using loop # initialize liststest_list = ['4.5', '7.8', '9.8', '10.3'] # printing original listprint(\"The original list is : \" + str(test_list)) # Summation of float string list# Using loopres_sum = 0 for ele in test_list: res_sum += float(ele) # printing resultprint(\"The summation of float string list : \" + str(res_sum))", "e": 27234, "s": 26824, "text": null }, { "code": null, "e": 27344, "s": 27234, "text": "The original list is : ['4.5', '7.8', '9.8', '10.3']\nThe summation of float string list : 32.400000000000006\n" }, { "code": null, "e": 27365, "s": 27344, "text": "Python list-programs" }, { "code": null, "e": 27372, "s": 27365, "text": "Python" }, { "code": null, "e": 27388, "s": 27372, "text": "Python Programs" }, { "code": null, "e": 27486, "s": 27388, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27518, "s": 27486, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27560, "s": 27518, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27602, "s": 27560, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27629, "s": 27602, "text": "Python Classes and Objects" }, { "code": null, "e": 27685, "s": 27629, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27707, "s": 27685, "text": "Defaultdict in Python" }, { "code": null, "e": 27746, "s": 27707, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27792, "s": 27746, "text": "Python | Split string into list of characters" }, { "code": null, "e": 27830, "s": 27792, "text": "Python | Convert a list to dictionary" } ]
os.walk() in Python - GeeksforGeeks
23 Nov, 2020 How to traverse file system in Python ? Suppose we have given below file structure in our system and we want to traverse all it’s branches completely from top to bottom ? OS.walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). root : Prints out directories only from what you specified. dirs : Prints out sub-directories from root. files : Prints out all files from root and directories. # Driver functionimport osif __name__ == "__main__": for (root,dirs,files) in os.walk('Test', topdown=true): print (root) print (dirs) print (files) print ('--------------------------------') Output: This article is contributed by Shashank Mishra (Gullu). 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. Python-Library python-modules python-os-module Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? *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? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Graph Plotting in Python | Set 1 Python | Get unique values from a list
[ { "code": null, "e": 25609, "s": 25581, "text": "\n23 Nov, 2020" }, { "code": null, "e": 25780, "s": 25609, "text": "How to traverse file system in Python ? Suppose we have given below file structure in our system and we want to traverse all it’s branches completely from top to bottom ?" }, { "code": null, "e": 26015, "s": 25780, "text": "OS.walk() generate the file names in a directory tree by walking the tree either top-down or bottom-up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames)." }, { "code": null, "e": 26075, "s": 26015, "text": "root : Prints out directories only from what you specified." }, { "code": null, "e": 26120, "s": 26075, "text": "dirs : Prints out sub-directories from root." }, { "code": null, "e": 26176, "s": 26120, "text": "files : Prints out all files from root and directories." }, { "code": "# Driver functionimport osif __name__ == \"__main__\": for (root,dirs,files) in os.walk('Test', topdown=true): print (root) print (dirs) print (files) print ('--------------------------------')", "e": 26399, "s": 26176, "text": null }, { "code": null, "e": 26407, "s": 26399, "text": "Output:" }, { "code": null, "e": 26720, "s": 26409, "text": "This article is contributed by Shashank Mishra (Gullu). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 26845, "s": 26720, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 26860, "s": 26845, "text": "Python-Library" }, { "code": null, "e": 26875, "s": 26860, "text": "python-modules" }, { "code": null, "e": 26892, "s": 26875, "text": "python-os-module" }, { "code": null, "e": 26899, "s": 26892, "text": "Python" }, { "code": null, "e": 26997, "s": 26899, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27029, "s": 26997, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27058, "s": 27029, "text": "*args and **kwargs in Python" }, { "code": null, "e": 27095, "s": 27058, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 27131, "s": 27095, "text": "Convert integer to string in Python" }, { "code": null, "e": 27173, "s": 27131, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27215, "s": 27173, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27242, "s": 27215, "text": "Python Classes and Objects" }, { "code": null, "e": 27298, "s": 27242, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27331, "s": 27298, "text": "Graph Plotting in Python | Set 1" } ]
How to make horizontal line with words in the middle using CSS? - GeeksforGeeks
22 Apr, 2019 CSS provides the feature of making a horizontal line including words or image in the middle of the webpage to make it attractive. This can be achieved by using simple CSS properties. Syntax: h4:before, h4:after { content: ""; flex: 1 1; border-bottom: 2px solid #000; margin: auto; } Example-1: To make a horizontal line with words in middle <html> <head> <style> h4 { display: flex; flex-direction: row; } h4:before, h4:after { content: ""; flex: 1 1; border-bottom: 2px solid #000; margin: auto; } img { height: 100px; width: 100px; border-radius: 50%; } </style></head> <body> <h4>GeeksforGeeks</h4></body> </html> Output : Example-2: To make a horizontal line with the image in middle <html> <head> <style> h1 { display: flex; flex-direction: row; } h1:before, h1:after { content: ""; flex: 1 1; border-bottom: 2px solid #000; margin: auto; } img { height: 100px; width: 100px; border-radius: 50%; } </style></head> <body> <h1><img src="https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200.png"> </h1></body> </html> Output: CSS-Misc CSS-Selectors Picked CSS Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to apply style to parent if it has child with CSS? How to set space between the flexbox ? Design a web page using HTML and CSS Create a Responsive Navbar using ReactJS Making a div vertically scrollable using CSS 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 25627, "s": 25599, "text": "\n22 Apr, 2019" }, { "code": null, "e": 25810, "s": 25627, "text": "CSS provides the feature of making a horizontal line including words or image in the middle of the webpage to make it attractive. This can be achieved by using simple CSS properties." }, { "code": null, "e": 25818, "s": 25810, "text": "Syntax:" }, { "code": null, "e": 25932, "s": 25818, "text": "h4:before, h4:after {\n content: \"\";\n flex: 1 1;\n border-bottom: 2px solid #000;\n margin: auto;\n}\n" }, { "code": null, "e": 25990, "s": 25932, "text": "Example-1: To make a horizontal line with words in middle" }, { "code": "<html> <head> <style> h4 { display: flex; flex-direction: row; } h4:before, h4:after { content: \"\"; flex: 1 1; border-bottom: 2px solid #000; margin: auto; } img { height: 100px; width: 100px; border-radius: 50%; } </style></head> <body> <h4>GeeksforGeeks</h4></body> </html>", "e": 26446, "s": 25990, "text": null }, { "code": null, "e": 26455, "s": 26446, "text": "Output :" }, { "code": null, "e": 26517, "s": 26455, "text": "Example-2: To make a horizontal line with the image in middle" }, { "code": "<html> <head> <style> h1 { display: flex; flex-direction: row; } h1:before, h1:after { content: \"\"; flex: 1 1; border-bottom: 2px solid #000; margin: auto; } img { height: 100px; width: 100px; border-radius: 50%; } </style></head> <body> <h1><img src=\"https://www.geeksforgeeks.org/wp-content/uploads/gfg_200X200.png\"> </h1></body> </html>", "e": 27038, "s": 26517, "text": null }, { "code": null, "e": 27046, "s": 27038, "text": "Output:" }, { "code": null, "e": 27055, "s": 27046, "text": "CSS-Misc" }, { "code": null, "e": 27069, "s": 27055, "text": "CSS-Selectors" }, { "code": null, "e": 27076, "s": 27069, "text": "Picked" }, { "code": null, "e": 27080, "s": 27076, "text": "CSS" }, { "code": null, "e": 27097, "s": 27080, "text": "Web Technologies" }, { "code": null, "e": 27124, "s": 27097, "text": "Web technologies Questions" }, { "code": null, "e": 27222, "s": 27124, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27277, "s": 27222, "text": "How to apply style to parent if it has child with CSS?" }, { "code": null, "e": 27316, "s": 27277, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 27353, "s": 27316, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27394, "s": 27353, "text": "Create a Responsive Navbar using ReactJS" }, { "code": null, "e": 27439, "s": 27394, "text": "Making a div vertically scrollable using CSS" }, { "code": null, "e": 27479, "s": 27439, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27512, "s": 27479, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27557, "s": 27512, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27600, "s": 27557, "text": "How to fetch data from an API in ReactJS ?" } ]
HTML | Marquee stop Method - GeeksforGeeks
20 Jan, 2022 The Marquee stop method in HTML is used to stop the scrolling. To start the scrolling use start() method. Syntax: Object.stop() Return value: This method has no return value. Example: <!DOCTYPE html><html> <head> <title>Marquee stop Method</title> <style> .main { text-align: center; } </style></head> <body> <h1 style="color:green; text-align:center;"> GeeksforGeeks </h1> <div class="main"> <marquee id="marID" bgcolor="Green" direction="left" loop=""> Scrolling </marquee> <br /> <input type="button" onclick="marID.start()" value="start"> <input type="button" onclick="marID.stop()" value="Stop"> </div></body> </html> Output: Supported Browsers: The browsers supported by HTML Marquee stop Method are listed below: Google Chrome Internet Explorer Firefox Apple Safari Opera Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. ManasChhabra2 HTML-Methods HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. REST API (Introduction) HTML Cheat Sheet - A Basic Guide to HTML Design a web page using HTML and CSS Form validation using jQuery Angular File Upload 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 ? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26139, "s": 26111, "text": "\n20 Jan, 2022" }, { "code": null, "e": 26245, "s": 26139, "text": "The Marquee stop method in HTML is used to stop the scrolling. To start the scrolling use start() method." }, { "code": null, "e": 26253, "s": 26245, "text": "Syntax:" }, { "code": null, "e": 26267, "s": 26253, "text": "Object.stop()" }, { "code": null, "e": 26314, "s": 26267, "text": "Return value: This method has no return value." }, { "code": null, "e": 26323, "s": 26314, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>Marquee stop Method</title> <style> .main { text-align: center; } </style></head> <body> <h1 style=\"color:green; text-align:center;\"> GeeksforGeeks </h1> <div class=\"main\"> <marquee id=\"marID\" bgcolor=\"Green\" direction=\"left\" loop=\"\"> Scrolling </marquee> <br /> <input type=\"button\" onclick=\"marID.start()\" value=\"start\"> <input type=\"button\" onclick=\"marID.stop()\" value=\"Stop\"> </div></body> </html>", "e": 26975, "s": 26323, "text": null }, { "code": null, "e": 26983, "s": 26975, "text": "Output:" }, { "code": null, "e": 27072, "s": 26983, "text": "Supported Browsers: The browsers supported by HTML Marquee stop Method are listed below:" }, { "code": null, "e": 27086, "s": 27072, "text": "Google Chrome" }, { "code": null, "e": 27104, "s": 27086, "text": "Internet Explorer" }, { "code": null, "e": 27112, "s": 27104, "text": "Firefox" }, { "code": null, "e": 27125, "s": 27112, "text": "Apple Safari" }, { "code": null, "e": 27131, "s": 27125, "text": "Opera" }, { "code": null, "e": 27268, "s": 27131, "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": 27282, "s": 27268, "text": "ManasChhabra2" }, { "code": null, "e": 27295, "s": 27282, "text": "HTML-Methods" }, { "code": null, "e": 27300, "s": 27295, "text": "HTML" }, { "code": null, "e": 27317, "s": 27300, "text": "Web Technologies" }, { "code": null, "e": 27322, "s": 27317, "text": "HTML" }, { "code": null, "e": 27420, "s": 27322, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27444, "s": 27420, "text": "REST API (Introduction)" }, { "code": null, "e": 27485, "s": 27444, "text": "HTML Cheat Sheet - A Basic Guide to HTML" }, { "code": null, "e": 27522, "s": 27485, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 27551, "s": 27522, "text": "Form validation using jQuery" }, { "code": null, "e": 27571, "s": 27551, "text": "Angular File Upload" }, { "code": null, "e": 27611, "s": 27571, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 27644, "s": 27611, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 27689, "s": 27644, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 27732, "s": 27689, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | Check if a variable is string - GeeksforGeeks
22 May, 2019 While working with different datatypes, we might come across a time, where we need to test the datatype for its nature. This article gives ways to test a variable against the data type it is. Let’s discuss certain ways in which this task can be done. Method #1 : Using isinstance(x, str) This method can be used to test whether any variable is a particular datatype. By giving the second argument as “str”, we can check if the variable we pass is a string or not. # Python3 code to demonstrate# Check if variable is string # using isinstance() # initializing string test_string = "GFG" # printing original string print("The original string : " + str(test_string)) # using isinstance()# Check if variable is string res = isinstance(test_string, str) # print resultprint("Is variable a string ? : " + str(res)) The original string : GFG Is variable a string ? : True Method #2 : Using type() This task can also be achieved using the type function in which we just need to pass the variable and equate with a particular type. # Python3 code to demonstrate# Check if variable is string # using type() # initializing string test_string = "GFG" # printing original string print("The original string : " + str(test_string)) # using type()# Check if variable is string res = type(test_string) == str # print resultprint("Is variable a string ? : " + str(res)) The original string : GFG Is variable a string ? : True Python string-programs Python Python Programs 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 Python String | replace() Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 26074, "s": 26046, "text": "\n22 May, 2019" }, { "code": null, "e": 26325, "s": 26074, "text": "While working with different datatypes, we might come across a time, where we need to test the datatype for its nature. This article gives ways to test a variable against the data type it is. Let’s discuss certain ways in which this task can be done." }, { "code": null, "e": 26362, "s": 26325, "text": "Method #1 : Using isinstance(x, str)" }, { "code": null, "e": 26538, "s": 26362, "text": "This method can be used to test whether any variable is a particular datatype. By giving the second argument as “str”, we can check if the variable we pass is a string or not." }, { "code": "# Python3 code to demonstrate# Check if variable is string # using isinstance() # initializing string test_string = \"GFG\" # printing original string print(\"The original string : \" + str(test_string)) # using isinstance()# Check if variable is string res = isinstance(test_string, str) # print resultprint(\"Is variable a string ? : \" + str(res))", "e": 26887, "s": 26538, "text": null }, { "code": null, "e": 26944, "s": 26887, "text": "The original string : GFG\nIs variable a string ? : True\n" }, { "code": null, "e": 26971, "s": 26946, "text": "Method #2 : Using type()" }, { "code": null, "e": 27104, "s": 26971, "text": "This task can also be achieved using the type function in which we just need to pass the variable and equate with a particular type." }, { "code": "# Python3 code to demonstrate# Check if variable is string # using type() # initializing string test_string = \"GFG\" # printing original string print(\"The original string : \" + str(test_string)) # using type()# Check if variable is string res = type(test_string) == str # print resultprint(\"Is variable a string ? : \" + str(res))", "e": 27437, "s": 27104, "text": null }, { "code": null, "e": 27494, "s": 27437, "text": "The original string : GFG\nIs variable a string ? : True\n" }, { "code": null, "e": 27517, "s": 27494, "text": "Python string-programs" }, { "code": null, "e": 27524, "s": 27517, "text": "Python" }, { "code": null, "e": 27540, "s": 27524, "text": "Python Programs" }, { "code": null, "e": 27638, "s": 27540, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27656, "s": 27638, "text": "Python Dictionary" }, { "code": null, "e": 27688, "s": 27656, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27710, "s": 27688, "text": "Enumerate() in Python" }, { "code": null, "e": 27752, "s": 27710, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27778, "s": 27752, "text": "Python String | replace()" }, { "code": null, "e": 27821, "s": 27778, "text": "Python program to convert a list to string" }, { "code": null, "e": 27843, "s": 27821, "text": "Defaultdict in Python" }, { "code": null, "e": 27882, "s": 27843, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27928, "s": 27882, "text": "Python | Split string into list of characters" } ]
Program to compute division upto n decimal places - GeeksforGeeks
20 Apr, 2021 Given 3 numbers x, y and n compute the division (x/y) upto n decimal places.Examples : Input : x = 22, y = 7, n = 10 Output : 3.1428571428 Explanation : Since n = 10, division (x / y) is taken till 10 decimal places. Input : x = 22, y = 7, n = 20 Output : 3.14285714285714285714 Approach : Get the remainder and get it subtracted by the dividend, multiply it by ten and go to the next iteration.If we reach the complete result, we may not need to continue until the pre-defined number of iterations are reached. Get the remainder and get it subtracted by the dividend, multiply it by ten and go to the next iteration. If we reach the complete result, we may not need to continue until the pre-defined number of iterations are reached. C++ Java C# PHP Python3 Javascript // CPP program to compute division upto n// decimal places.#include <bits/stdc++.h>using namespace std; void precisionCompute(int x, int y, int n){ // Base cases if (y == 0) { cout << "Infinite" << endl; return; } if (x == 0) { cout << 0 << endl; return; } if (n <= 0) { // Since n <= 0, don't compute after // the decimal cout << x / y << endl; return; } // Handling negative numbers if (((x > 0) && (y < 0)) || ((x < 0) && (y > 0))) { cout << "-"; x = x > 0 ? x : -x; y = y > 0 ? y : -y; } // Integral division int d = x / y; // Now one by print digits after dot // using school division method. for (int i = 0; i <= n; i++) { cout << d; x = x - (y * d); if (x == 0) break; x = x * 10; d = x / y; if (i == 0) cout << "."; }} // Driver Programint main(){ int x = 22, y = 7, n = 15; precisionCompute(x, y, n); return 0;} // Java program to compute division upto n// decimal places.import java.util.*; class Eulerian { public static void precisionCompute(int x, int y, int n) { // Base cases if (y == 0) { System.out.print("Infinite"); return; } if (x == 0) { System.out.print("0"); return; } if (n <= 0) { // Since n <= 0, don't compute after // the decimal System.out.print(x / y); return; } // Handling negative numbers if (((x > 0) && (y < 0)) || ((x < 0) && (y > 0))) { System.out.print("-"); x = x > 0 ? x : -x; y = y > 0 ? y : -y; } // Integral division int d = x / y; // Now one by print digits after dot // using school division method. for (int i = 0; i <= n; i++) { System.out.print(d); x = x - (y * d); if (x == 0) break; x = x * 10; d = x / y; if (i == 0) System.out.print("."); } } public static void main(String[] args) { int x = 22, y = 7, n = 15; precisionCompute(x, y, n); }} // This code is contributed by rishabh_jain // C# program to compute division// upto n decimal places.using System; class Eulerian { public static void precisionCompute(int x, int y, int n) { // Base cases if (y == 0) { Console.WriteLine("Infinite"); return; } if (x == 0) { Console.WriteLine("0"); return; } if (n <= 0) { // Since n <= 0, don't compute after // the decimal Console.WriteLine(x / y); return; } // Handling negative numbers if (((x > 0) && (y < 0)) || ((x < 0) && (y > 0))) { Console.WriteLine("-"); x = x > 0 ? x : -x; y = y > 0 ? y : -y; } // Integral division int d = x / y; // Now one by print digits after dot // using school division method. for (int i = 0; i <= n; i++) { Console.Write(d); x = x - (y * d); if (x == 0) break; x = x * 10; d = x / y; if (i == 0) Console.Write("."); } } // Driver code public static void Main() { int x = 22, y = 7, n = 15; precisionCompute(x, y, n); }} // This code is contributed by vt_m <?php// PHP program to compute// division upto n decimal// places. function precisionCompute($x, $y, $n){ // Base cases if ($y == 0) { echo "Infinite", "\n"; return; } if ($x == 0) { echo 0, "\n"; return; } if ($n <= 0) { // Since n <= 0, don't // compute after the decimal echo $x / $y, "\n"; return; } // Handling negative numbers if ((($x > 0) && ($y < 0)) || (($x < 0) && ($y > 0))) { echo "-"; $x = $x > 0 ? $x : -$x; $y = $y > 0 ? $y : -$y; } // Integral division $d = $x / $y; // Now one by print digits after dot // using school division method. for ($i = 0; $i <= $n; $i++) { echo $d; $x = $x - ($y * $d); if ($x == 0) break; $x = $x * 10; $d = $x / $y; if ($i == 0) echo "."; }} // Driver Code$x = 22; $y = 7; $n = 15; precisionCompute($x, $y, $n); // This code is contributed by aj_36?> # Python3 program to compute# division upto n decimal places. def precisionCompute(x, y, n): # Base cases if y == 0: print("Infinite"); return; if x == 0: print(0); return; if n <= 0: # Since n <= 0, don't # compute after the decimal print(x / y); return; # Handling negative numbers if (((x > 0) and (y < 0)) or ((x < 0) and (y > 0))): print("-", end = ""); if x < 0: x = -x; if y < 0: y = -y; # Integral division d = x / y; # Now one by print digits # after dot using school # division method. for i in range(0, n + 1): print(d); x = x - (y * d); if x == 0: break; x = x * 10; d = x / y; if (i == 0): print(".", end = ""); # Driver Codex = 22;y = 7;n = 15;precisionCompute(x, y, n); # This code is contributed by mits <script> // JavaScript program to compute division upto n// decimal places. function precisionCompute(x, y, n) { // Base cases if (y == 0) { document.write("Infinite"); return; } if (x == 0) { document.write("0"); return; } if (n <= 0) { // Since n <= 0, don't compute after // the decimal document.write(x / y); return; } // Handling negative numbers if (((x > 0) && (y < 0)) || ((x < 0) && (y > 0))) { document.write("-"); x = x > 0 ? x : -x; y = y > 0 ? y : -y; } // Integral division let d = x / y; // Now one by print digits after dot // using school division method. for (let i = 0; i <= n; i++) { document.write(d); x = x - (y * d); if (x == 0) break; x = x * 10; d = x / y; if (i == 0) document.write("."); } } // Driver code let x = 22, y = 7, n = 15; precisionCompute(x, y, n); </script> Output : 3.142857142857142 jit_t Mithun Kumar sanjoy_62 divisibility Mathematical School Programming Technical Scripter Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Program to print prime numbers from 1 to N. Modular multiplicative inverse Fizz Buzz Implementation Check if a number is Palindrome Generate all permutation of a set in Python Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 25962, "s": 25934, "text": "\n20 Apr, 2021" }, { "code": null, "e": 26051, "s": 25962, "text": "Given 3 numbers x, y and n compute the division (x/y) upto n decimal places.Examples : " }, { "code": null, "e": 26246, "s": 26051, "text": "Input : x = 22, y = 7, n = 10\nOutput : 3.1428571428\nExplanation :\nSince n = 10, division (x / y) is taken till\n10 decimal places.\n\nInput : x = 22, y = 7, n = 20\nOutput : 3.14285714285714285714" }, { "code": null, "e": 26261, "s": 26248, "text": "Approach : " }, { "code": null, "e": 26483, "s": 26261, "text": "Get the remainder and get it subtracted by the dividend, multiply it by ten and go to the next iteration.If we reach the complete result, we may not need to continue until the pre-defined number of iterations are reached." }, { "code": null, "e": 26589, "s": 26483, "text": "Get the remainder and get it subtracted by the dividend, multiply it by ten and go to the next iteration." }, { "code": null, "e": 26706, "s": 26589, "text": "If we reach the complete result, we may not need to continue until the pre-defined number of iterations are reached." }, { "code": null, "e": 26712, "s": 26708, "text": "C++" }, { "code": null, "e": 26717, "s": 26712, "text": "Java" }, { "code": null, "e": 26720, "s": 26717, "text": "C#" }, { "code": null, "e": 26724, "s": 26720, "text": "PHP" }, { "code": null, "e": 26732, "s": 26724, "text": "Python3" }, { "code": null, "e": 26743, "s": 26732, "text": "Javascript" }, { "code": "// CPP program to compute division upto n// decimal places.#include <bits/stdc++.h>using namespace std; void precisionCompute(int x, int y, int n){ // Base cases if (y == 0) { cout << \"Infinite\" << endl; return; } if (x == 0) { cout << 0 << endl; return; } if (n <= 0) { // Since n <= 0, don't compute after // the decimal cout << x / y << endl; return; } // Handling negative numbers if (((x > 0) && (y < 0)) || ((x < 0) && (y > 0))) { cout << \"-\"; x = x > 0 ? x : -x; y = y > 0 ? y : -y; } // Integral division int d = x / y; // Now one by print digits after dot // using school division method. for (int i = 0; i <= n; i++) { cout << d; x = x - (y * d); if (x == 0) break; x = x * 10; d = x / y; if (i == 0) cout << \".\"; }} // Driver Programint main(){ int x = 22, y = 7, n = 15; precisionCompute(x, y, n); return 0;}", "e": 27765, "s": 26743, "text": null }, { "code": "// Java program to compute division upto n// decimal places.import java.util.*; class Eulerian { public static void precisionCompute(int x, int y, int n) { // Base cases if (y == 0) { System.out.print(\"Infinite\"); return; } if (x == 0) { System.out.print(\"0\"); return; } if (n <= 0) { // Since n <= 0, don't compute after // the decimal System.out.print(x / y); return; } // Handling negative numbers if (((x > 0) && (y < 0)) || ((x < 0) && (y > 0))) { System.out.print(\"-\"); x = x > 0 ? x : -x; y = y > 0 ? y : -y; } // Integral division int d = x / y; // Now one by print digits after dot // using school division method. for (int i = 0; i <= n; i++) { System.out.print(d); x = x - (y * d); if (x == 0) break; x = x * 10; d = x / y; if (i == 0) System.out.print(\".\"); } } public static void main(String[] args) { int x = 22, y = 7, n = 15; precisionCompute(x, y, n); }} // This code is contributed by rishabh_jain", "e": 29046, "s": 27765, "text": null }, { "code": "// C# program to compute division// upto n decimal places.using System; class Eulerian { public static void precisionCompute(int x, int y, int n) { // Base cases if (y == 0) { Console.WriteLine(\"Infinite\"); return; } if (x == 0) { Console.WriteLine(\"0\"); return; } if (n <= 0) { // Since n <= 0, don't compute after // the decimal Console.WriteLine(x / y); return; } // Handling negative numbers if (((x > 0) && (y < 0)) || ((x < 0) && (y > 0))) { Console.WriteLine(\"-\"); x = x > 0 ? x : -x; y = y > 0 ? y : -y; } // Integral division int d = x / y; // Now one by print digits after dot // using school division method. for (int i = 0; i <= n; i++) { Console.Write(d); x = x - (y * d); if (x == 0) break; x = x * 10; d = x / y; if (i == 0) Console.Write(\".\"); } } // Driver code public static void Main() { int x = 22, y = 7, n = 15; precisionCompute(x, y, n); }} // This code is contributed by vt_m", "e": 30355, "s": 29046, "text": null }, { "code": "<?php// PHP program to compute// division upto n decimal// places. function precisionCompute($x, $y, $n){ // Base cases if ($y == 0) { echo \"Infinite\", \"\\n\"; return; } if ($x == 0) { echo 0, \"\\n\"; return; } if ($n <= 0) { // Since n <= 0, don't // compute after the decimal echo $x / $y, \"\\n\"; return; } // Handling negative numbers if ((($x > 0) && ($y < 0)) || (($x < 0) && ($y > 0))) { echo \"-\"; $x = $x > 0 ? $x : -$x; $y = $y > 0 ? $y : -$y; } // Integral division $d = $x / $y; // Now one by print digits after dot // using school division method. for ($i = 0; $i <= $n; $i++) { echo $d; $x = $x - ($y * $d); if ($x == 0) break; $x = $x * 10; $d = $x / $y; if ($i == 0) echo \".\"; }} // Driver Code$x = 22; $y = 7; $n = 15; precisionCompute($x, $y, $n); // This code is contributed by aj_36?>", "e": 31368, "s": 30355, "text": null }, { "code": "# Python3 program to compute# division upto n decimal places. def precisionCompute(x, y, n): # Base cases if y == 0: print(\"Infinite\"); return; if x == 0: print(0); return; if n <= 0: # Since n <= 0, don't # compute after the decimal print(x / y); return; # Handling negative numbers if (((x > 0) and (y < 0)) or ((x < 0) and (y > 0))): print(\"-\", end = \"\"); if x < 0: x = -x; if y < 0: y = -y; # Integral division d = x / y; # Now one by print digits # after dot using school # division method. for i in range(0, n + 1): print(d); x = x - (y * d); if x == 0: break; x = x * 10; d = x / y; if (i == 0): print(\".\", end = \"\"); # Driver Codex = 22;y = 7;n = 15;precisionCompute(x, y, n); # This code is contributed by mits", "e": 32335, "s": 31368, "text": null }, { "code": "<script> // JavaScript program to compute division upto n// decimal places. function precisionCompute(x, y, n) { // Base cases if (y == 0) { document.write(\"Infinite\"); return; } if (x == 0) { document.write(\"0\"); return; } if (n <= 0) { // Since n <= 0, don't compute after // the decimal document.write(x / y); return; } // Handling negative numbers if (((x > 0) && (y < 0)) || ((x < 0) && (y > 0))) { document.write(\"-\"); x = x > 0 ? x : -x; y = y > 0 ? y : -y; } // Integral division let d = x / y; // Now one by print digits after dot // using school division method. for (let i = 0; i <= n; i++) { document.write(d); x = x - (y * d); if (x == 0) break; x = x * 10; d = x / y; if (i == 0) document.write(\".\"); } } // Driver code let x = 22, y = 7, n = 15; precisionCompute(x, y, n); </script>", "e": 33522, "s": 32335, "text": null }, { "code": null, "e": 33532, "s": 33522, "text": "Output : " }, { "code": null, "e": 33550, "s": 33532, "text": "3.142857142857142" }, { "code": null, "e": 33558, "s": 33552, "text": "jit_t" }, { "code": null, "e": 33571, "s": 33558, "text": "Mithun Kumar" }, { "code": null, "e": 33581, "s": 33571, "text": "sanjoy_62" }, { "code": null, "e": 33594, "s": 33581, "text": "divisibility" }, { "code": null, "e": 33607, "s": 33594, "text": "Mathematical" }, { "code": null, "e": 33626, "s": 33607, "text": "School Programming" }, { "code": null, "e": 33645, "s": 33626, "text": "Technical Scripter" }, { "code": null, "e": 33658, "s": 33645, "text": "Mathematical" }, { "code": null, "e": 33756, "s": 33658, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33800, "s": 33756, "text": "Program to print prime numbers from 1 to N." }, { "code": null, "e": 33831, "s": 33800, "text": "Modular multiplicative inverse" }, { "code": null, "e": 33856, "s": 33831, "text": "Fizz Buzz Implementation" }, { "code": null, "e": 33888, "s": 33856, "text": "Check if a number is Palindrome" }, { "code": null, "e": 33932, "s": 33888, "text": "Generate all permutation of a set in Python" }, { "code": null, "e": 33950, "s": 33932, "text": "Python Dictionary" }, { "code": null, "e": 33966, "s": 33950, "text": "Arrays in C/C++" }, { "code": null, "e": 33985, "s": 33966, "text": "Inheritance in C++" }, { "code": null, "e": 34010, "s": 33985, "text": "Reverse a string in Java" } ]
p5.js | noiseSeed() Function - GeeksforGeeks
29 Jan, 2020 The noiseSeed() function is used to set a seed value for the noise() function. The noise() function, by default returns a number that is semi-random, meaning that the noise value would be the same for a coordinate only until the program is running. Running the program for the next time would yield a different value. These noise values can be made constant by setting a non-changing seed value in the program so that it returns the same values every time when the program is run. Syntax: noiseSeed( seed ) Parameters: This function accepts a single parameter as mentioned above and described below: seed: This parameter holds a number which represents the seed value. Return Value: This function does not return any value. Below example illustrates the noiseSeed() function in p5.js: Example: let x_coordinate = 0.0;let plot_y = 0.0; function setup() { createCanvas(400, 200);} function draw() { // Specifying a noise seed value noiseSeed(100); if (x_coordinate < 10) { // Get noise with x coordinate x_noise = noise(x_coordinate); // Output the noise along with // its corresponding coordinate coord_text = "Noise for x coordinate " + x_coordinate + " is " + x_noise; text(coord_text, 10, plot_y); // Increment the x coordinate x_coordinate++; // Increase the y coordinate // for plotting plot_y = plot_y + 15; }} Output: The values are constant every time the program is run. Running the program for the first time: Running the program for the second time: Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/ Reference: https://p5js.org/reference/#/p5/noiseSeed JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React How to calculate the number of days between two dates in javascript? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills
[ { "code": null, "e": 44937, "s": 44909, "text": "\n29 Jan, 2020" }, { "code": null, "e": 45255, "s": 44937, "text": "The noiseSeed() function is used to set a seed value for the noise() function. The noise() function, by default returns a number that is semi-random, meaning that the noise value would be the same for a coordinate only until the program is running. Running the program for the next time would yield a different value." }, { "code": null, "e": 45418, "s": 45255, "text": "These noise values can be made constant by setting a non-changing seed value in the program so that it returns the same values every time when the program is run." }, { "code": null, "e": 45426, "s": 45418, "text": "Syntax:" }, { "code": null, "e": 45444, "s": 45426, "text": "noiseSeed( seed )" }, { "code": null, "e": 45537, "s": 45444, "text": "Parameters: This function accepts a single parameter as mentioned above and described below:" }, { "code": null, "e": 45606, "s": 45537, "text": "seed: This parameter holds a number which represents the seed value." }, { "code": null, "e": 45661, "s": 45606, "text": "Return Value: This function does not return any value." }, { "code": null, "e": 45722, "s": 45661, "text": "Below example illustrates the noiseSeed() function in p5.js:" }, { "code": null, "e": 45731, "s": 45722, "text": "Example:" }, { "code": "let x_coordinate = 0.0;let plot_y = 0.0; function setup() { createCanvas(400, 200);} function draw() { // Specifying a noise seed value noiseSeed(100); if (x_coordinate < 10) { // Get noise with x coordinate x_noise = noise(x_coordinate); // Output the noise along with // its corresponding coordinate coord_text = \"Noise for x coordinate \" + x_coordinate + \" is \" + x_noise; text(coord_text, 10, plot_y); // Increment the x coordinate x_coordinate++; // Increase the y coordinate // for plotting plot_y = plot_y + 15; }}", "e": 46397, "s": 45731, "text": null }, { "code": null, "e": 46460, "s": 46397, "text": "Output: The values are constant every time the program is run." }, { "code": null, "e": 46500, "s": 46460, "text": "Running the program for the first time:" }, { "code": null, "e": 46541, "s": 46500, "text": "Running the program for the second time:" }, { "code": null, "e": 46678, "s": 46541, "text": "Online editor: https://editor.p5js.org/Environment Setup: https://www.geeksforgeeks.org/p5-js-soundfile-object-installation-and-methods/" }, { "code": null, "e": 46731, "s": 46678, "text": "Reference: https://p5js.org/reference/#/p5/noiseSeed" }, { "code": null, "e": 46748, "s": 46731, "text": "JavaScript-p5.js" }, { "code": null, "e": 46759, "s": 46748, "text": "JavaScript" }, { "code": null, "e": 46776, "s": 46759, "text": "Web Technologies" }, { "code": null, "e": 46874, "s": 46776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 46914, "s": 46874, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 46959, "s": 46914, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 47020, "s": 46959, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 47092, "s": 47020, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 47161, "s": 47092, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 47201, "s": 47161, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 47234, "s": 47201, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 47279, "s": 47234, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 47322, "s": 47279, "text": "How to fetch data from an API in ReactJS ?" } ]
Python | Pandas dataframe.set_value() - GeeksforGeeks
24 Nov, 2018 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.set_value() function put a single value at passed column and index. It takes the axis labels as input and a scalar value to be placed at the specified index in the dataframe. Alternative to this function is .at[] or .iat[]. Syntax:DataFrame.set_value(index, col, value, takeable=False)Parameters :index : row labelcol : column labelvalue : scalar valuetakeable : interpret the index/col as indexers, default False Return : frame : DataFrame If label pair is contained, will be reference to calling DataFrame, otherwise a new object Example #1: Use set_value() function to set the value in the dataframe at a particular index. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}) # Print the dataframedf Lets use the dataframe.set_value() function to set value of a particular index. # set value of a cell which has index label "2" and column label "B"df.set_value(2, 'B', 100) Output : Example #2: Use set_value() function to set value of a non-existent index and column in the dataframe. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({"A":[1, 5, 3, 4, 2], "B":[3, 2, 4, 3, 4], "C":[2, 2, 7, 3, 4], "D":[4, 3, 6, 12, 7]}) # Print the dataframedf Lets use the dataframe.set_value() function to set value of a particular index. # set value of a cell which has index label "8" and column label "8"df.set_value(8, 8, 1000) Output : Notice, for the non-existent row and column in the dataframe, a new row and column has been inserted. Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe *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": 26117, "s": 26089, "text": "\n24 Nov, 2018" }, { "code": null, "e": 26331, "s": 26117, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 26572, "s": 26331, "text": "Pandas dataframe.set_value() function put a single value at passed column and index. It takes the axis labels as input and a scalar value to be placed at the specified index in the dataframe. Alternative to this function is .at[] or .iat[]." }, { "code": null, "e": 26762, "s": 26572, "text": "Syntax:DataFrame.set_value(index, col, value, takeable=False)Parameters :index : row labelcol : column labelvalue : scalar valuetakeable : interpret the index/col as indexers, default False" }, { "code": null, "e": 26880, "s": 26762, "text": "Return : frame : DataFrame If label pair is contained, will be reference to calling DataFrame, otherwise a new object" }, { "code": null, "e": 26974, "s": 26880, "text": "Example #1: Use set_value() function to set the value in the dataframe at a particular index." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}) # Print the dataframedf", "e": 27229, "s": 26974, "text": null }, { "code": null, "e": 27309, "s": 27229, "text": "Lets use the dataframe.set_value() function to set value of a particular index." }, { "code": "# set value of a cell which has index label \"2\" and column label \"B\"df.set_value(2, 'B', 100)", "e": 27403, "s": 27309, "text": null }, { "code": null, "e": 27515, "s": 27403, "text": "Output : Example #2: Use set_value() function to set value of a non-existent index and column in the dataframe." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.DataFrame({\"A\":[1, 5, 3, 4, 2], \"B\":[3, 2, 4, 3, 4], \"C\":[2, 2, 7, 3, 4], \"D\":[4, 3, 6, 12, 7]}) # Print the dataframedf", "e": 27771, "s": 27515, "text": null }, { "code": null, "e": 27851, "s": 27771, "text": "Lets use the dataframe.set_value() function to set value of a particular index." }, { "code": "# set value of a cell which has index label \"8\" and column label \"8\"df.set_value(8, 8, 1000)", "e": 27944, "s": 27851, "text": null }, { "code": null, "e": 27953, "s": 27944, "text": "Output :" }, { "code": null, "e": 28055, "s": 27953, "text": "Notice, for the non-existent row and column in the dataframe, a new row and column has been inserted." }, { "code": null, "e": 28079, "s": 28055, "text": "Python pandas-dataFrame" }, { "code": null, "e": 28111, "s": 28079, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 28125, "s": 28111, "text": "Python-pandas" }, { "code": null, "e": 28132, "s": 28125, "text": "Python" }, { "code": null, "e": 28230, "s": 28132, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28248, "s": 28230, "text": "Python Dictionary" }, { "code": null, "e": 28280, "s": 28248, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28302, "s": 28280, "text": "Enumerate() in Python" }, { "code": null, "e": 28344, "s": 28302, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28373, "s": 28344, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28410, "s": 28373, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28446, "s": 28410, "text": "Convert integer to string in Python" }, { "code": null, "e": 28488, "s": 28446, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28530, "s": 28488, "text": "How To Convert Python Dictionary To JSON?" } ]
Dependency Injection with Dagger 2 in Android - GeeksforGeeks
24 Nov, 2020 If there are two classes, class A and class B and class A depends on class B then class B is called dependent for class A. So, Every time we want to access class B in class A we need to create an instance of class B in Class A or use static factory methods to access class A. But this will make our code tight coupled, difficult to manage, and test. In order to remove these problems, we use dependency injection. Dependency Injection is a design pattern that removes the dependency from the programming code and makes the application easy to manage and test. It also makes programming code loosely coupled. Let us assume, we want to store some data in SharedPreferences. In order to save or retrieve shared preferences data, we need the instance of shared preference in our Activity’s boilerplate code. And it may lead to problems in testing, managing, etc. if our codebase is large. This is where Android Dependency Injection helps. Here, SharedPreferences acts as a dependency for our Activity so, we don’t create its instance in our activity rather we inject it from some other class. Below is an illustration of the situation. Dagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are: @Module This annotation is used over the class which is used to construct objects and provide the dependencies.@Provides This is used over the method in the module class that will return the object.@Inject This is used over the fields, constructor, or method and indicate that dependencies are requested.@Component This is used over a component interface which acts as a bridge between @Module and @Inject. (Module class doesn’t provide dependency directly to requesting class, it uses component interface)@Singleton This is used to indicate only a single instance of dependency object is created. @Module This annotation is used over the class which is used to construct objects and provide the dependencies. @Provides This is used over the method in the module class that will return the object. @Inject This is used over the fields, constructor, or method and indicate that dependencies are requested. @Component This is used over a component interface which acts as a bridge between @Module and @Inject. (Module class doesn’t provide dependency directly to requesting class, it uses component interface) @Singleton This is used to indicate only a single instance of dependency object is created. In this example, we will add some data to shared preferences and then retrieve it from there using the dagger 2 library. Below is the picture of what we are going to do in this example. Note that we are going to implement this project using the Java language. Step 1: Create a New Project To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language. Step 2: Adding Dependencies In order to use dependency injection with the help of dagger 2 libraries, we need to add it’s dependency. Go to Gradle Scripts > build.gradle(Module: app) and add the following dependencies. After adding these dependencies you need to click on Sync Now. dependencies { implementation “com.google.dagger:hilt-core:2.29-alpha” annotationProcessor “com.google.dagger:hilt-compiler:2.29-alpha” } Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. XML <resources> <color name="colorPrimary">#0F9D58</color> <color name="colorPrimaryDark">#16E37F</color> <color name="colorAccent">#03DAC5</color> </resources> Step 3: Working with the activity_main.xml file In this step, we will create a layout file for the application. We have used EditText for taking the input from the user and a TextView for presenting the output and save and show buttons respectively. Below is the code snippet for the activity_main.xml file. XML <?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/saveBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/inputField" android:layout_centerInParent="true" android:layout_margin="8dp" android:background="@color/colorPrimary" android:text="Save" android:textColor="#ffffff" /> <Button android:id="@+id/getBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/outputField" android:layout_centerInParent="true" android:layout_margin="8dp" android:background="@color/colorPrimary" android:text="Show" android:textColor="#ffffff" /> <!--For input we have used EditText--> <EditText android:id="@+id/inputField" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="8dp" android:hint="Input Data" android:textAlignment="center" /> <!--For output we have used TextView--> <TextView android:id="@+id/outputField" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@+id/saveBtn" android:layout_margin="8dp" android:hint="Output Data" android:textAlignment="center" /> </RelativeLayout> Step 4: Creating Module Class Now, we will create a Module class which is used to construct the object and provide the dependencies. @Module annotations are used over the module class. This class contains a constructor that will initialize the context and a method that will return the dependent object for which @Provides annotation is used. Here, provideSharedPreferences() method will return the dependent object. In general, the method that returns the dependent object will be followed by the word provide. Go to the app > java > package > right-click and create a new java class and name it as SharedPreferenceModule. Below is the code snippet for the SharedPreferenceModule.java file. Java import android.content.Context;import android.content.SharedPreferences;import android.preference.PreferenceManager;import javax.inject.Singleton;import dagger.Module;import dagger.Provides; // @Module annotation is used over the class that // creates construct object and provides dependencies@Modulepublic class SharedPreferenceModule { private Context context; // Context gets initialize from the constructor itself public SharedPreferenceModule(Context context) { this.context = context; } @Singleton @Provides public Context provideContext() { return context; } // @Singleton indicates that only single instance // of dependency object is created // @Provide annotations used over the methods that // will provides the object of module class // This method will return the dependent object @Singleton @Provides public SharedPreferences provideSharedPreferences(Context context) { return PreferenceManager.getDefaultSharedPreferences(context); }} Step 5: Creating a Component Interface In this step, we will create an Interface. Go to the app > java > package > right-click and create an interface and name it as SharedPreferenceComponent. We use @Component annotation in order to mention all the modules. @Component(modules={SharedPreferenceModule}) The Activities, Fragments, or Services that may request the dependencies declared by modules must be declared in this interface with the individual inject() method. Below is the code snippet for the SharedPreferenceComponent.java Interface. Java import javax.inject.Singleton;import dagger.Component; // All the modules are mentioned under // the @Component annotation@Singleton@Component(modules = {SharedPreferenceModule.class})public interface SharedPreferenceComponent { void inject(MainActivity mainActivity);} Step 6: Working With the MainActivity.java File In this step, we will first initialize our Views and then bind Dagger to our application. For which component-interface is followed by the Dagger keyword. sharedPreferenceComponent = DaggerSharedPreferenceComponent.builder().sharedPreferenceModule(new SharedPreferenceModule(this)).build(); sharedPreferenceComponent.inject(this); Below is the code snippet for the MainActivity.java file. Note: When you will use Dagger as a prefix with Component(here, SharedPreferenceComponent) sometimes you may get an error or warning this is because DaggerSharedPreferenceComponent is generated after compilation. Java import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import javax.inject.Inject; public class MainActivity extends AppCompatActivity implements View.OnClickListener { EditText editText; TextView textView; Button saveBtn, getBtn; private SharedPreferenceComponent sharedPreferenceComponent; // @Inject is used to tell which activity, // fragment or service is allowed to request // dependencies declared in Module class @Inject SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Referencing the EditText, TextView and Buttons editText = (EditText) findViewById(R.id.inputField); textView = (TextView) findViewById(R.id.outputField); saveBtn = (Button) findViewById(R.id.saveBtn); getBtn = (Button) findViewById(R.id.getBtn); // Setting onClickListener behavior on button to reference // to the current activity(this MainActivity) saveBtn.setOnClickListener(this); getBtn.setOnClickListener(this); // Here we are binding dagger to our application // Dagger keyword will be prefix to the component name sharedPreferenceComponent = DaggerSharedPreferenceComponent.builder().sharedPreferenceModule( new SharedPreferenceModule(this)).build(); // we are injecting the shared preference dependent object sharedPreferenceComponent.inject(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.saveBtn: // Saving data to shared preference // inputField acts as key and editText data as value to that key SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString("inputField", editText.getText().toString().trim()); editor.apply(); break; case R.id.getBtn: // getting shared preferences data and set it to textview // s1: is the default string, You can write any thing there or leave it textView.setText(sharedPreferences.getString("inputField", "")); break; } }} android Technical Scripter 2020 Android Java Technical Scripter Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Resource Raw Folder in Android Studio Broadcast Receiver in Android With Example Services in Android with Example Android RecyclerView in Kotlin Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples
[ { "code": null, "e": 25925, "s": 25897, "text": "\n24 Nov, 2020" }, { "code": null, "e": 26048, "s": 25925, "text": "If there are two classes, class A and class B and class A depends on class B then class B is called dependent for class A." }, { "code": null, "e": 26533, "s": 26048, "text": "So, Every time we want to access class B in class A we need to create an instance of class B in Class A or use static factory methods to access class A. But this will make our code tight coupled, difficult to manage, and test. In order to remove these problems, we use dependency injection. Dependency Injection is a design pattern that removes the dependency from the programming code and makes the application easy to manage and test. It also makes programming code loosely coupled." }, { "code": null, "e": 27057, "s": 26533, "text": "Let us assume, we want to store some data in SharedPreferences. In order to save or retrieve shared preferences data, we need the instance of shared preference in our Activity’s boilerplate code. And it may lead to problems in testing, managing, etc. if our codebase is large. This is where Android Dependency Injection helps. Here, SharedPreferences acts as a dependency for our Activity so, we don’t create its instance in our activity rather we inject it from some other class. Below is an illustration of the situation." }, { "code": null, "e": 27243, "s": 27057, "text": "Dagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are:" }, { "code": null, "e": 27841, "s": 27243, "text": "@Module This annotation is used over the class which is used to construct objects and provide the dependencies.@Provides This is used over the method in the module class that will return the object.@Inject This is used over the fields, constructor, or method and indicate that dependencies are requested.@Component This is used over a component interface which acts as a bridge between @Module and @Inject. (Module class doesn’t provide dependency directly to requesting class, it uses component interface)@Singleton This is used to indicate only a single instance of dependency object is created." }, { "code": null, "e": 27953, "s": 27841, "text": "@Module This annotation is used over the class which is used to construct objects and provide the dependencies." }, { "code": null, "e": 28041, "s": 27953, "text": "@Provides This is used over the method in the module class that will return the object." }, { "code": null, "e": 28148, "s": 28041, "text": "@Inject This is used over the fields, constructor, or method and indicate that dependencies are requested." }, { "code": null, "e": 28351, "s": 28148, "text": "@Component This is used over a component interface which acts as a bridge between @Module and @Inject. (Module class doesn’t provide dependency directly to requesting class, it uses component interface)" }, { "code": null, "e": 28443, "s": 28351, "text": "@Singleton This is used to indicate only a single instance of dependency object is created." }, { "code": null, "e": 28704, "s": 28443, "text": "In this example, we will add some data to shared preferences and then retrieve it from there using the dagger 2 library. Below is the picture of what we are going to do in this example. Note that we are going to implement this project using the Java language. " }, { "code": null, "e": 28733, "s": 28704, "text": "Step 1: Create a New Project" }, { "code": null, "e": 28895, "s": 28733, "text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language." }, { "code": null, "e": 28923, "s": 28895, "text": "Step 2: Adding Dependencies" }, { "code": null, "e": 29177, "s": 28923, "text": "In order to use dependency injection with the help of dagger 2 libraries, we need to add it’s dependency. Go to Gradle Scripts > build.gradle(Module: app) and add the following dependencies. After adding these dependencies you need to click on Sync Now." }, { "code": null, "e": 29192, "s": 29177, "text": "dependencies {" }, { "code": null, "e": 29250, "s": 29192, "text": " implementation “com.google.dagger:hilt-core:2.29-alpha”" }, { "code": null, "e": 29317, "s": 29250, "text": " annotationProcessor “com.google.dagger:hilt-compiler:2.29-alpha”" }, { "code": null, "e": 29319, "s": 29317, "text": "}" }, { "code": null, "e": 29486, "s": 29319, "text": "Before moving further let’s add some color attributes in order to enhance the app bar. Go to app > res > values > colors.xml and add the following color attributes. " }, { "code": null, "e": 29490, "s": 29486, "text": "XML" }, { "code": "<resources> <color name=\"colorPrimary\">#0F9D58</color> <color name=\"colorPrimaryDark\">#16E37F</color> <color name=\"colorAccent\">#03DAC5</color> </resources> ", "e": 29660, "s": 29490, "text": null }, { "code": null, "e": 29708, "s": 29660, "text": "Step 3: Working with the activity_main.xml file" }, { "code": null, "e": 29968, "s": 29708, "text": "In this step, we will create a layout file for the application. We have used EditText for taking the input from the user and a TextView for presenting the output and save and show buttons respectively. Below is the code snippet for the activity_main.xml file." }, { "code": null, "e": 29972, "s": 29968, "text": "XML" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <Button android:id=\"@+id/saveBtn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/inputField\" android:layout_centerInParent=\"true\" android:layout_margin=\"8dp\" android:background=\"@color/colorPrimary\" android:text=\"Save\" android:textColor=\"#ffffff\" /> <Button android:id=\"@+id/getBtn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/outputField\" android:layout_centerInParent=\"true\" android:layout_margin=\"8dp\" android:background=\"@color/colorPrimary\" android:text=\"Show\" android:textColor=\"#ffffff\" /> <!--For input we have used EditText--> <EditText android:id=\"@+id/inputField\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"8dp\" android:hint=\"Input Data\" android:textAlignment=\"center\" /> <!--For output we have used TextView--> <TextView android:id=\"@+id/outputField\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@+id/saveBtn\" android:layout_margin=\"8dp\" android:hint=\"Output Data\" android:textAlignment=\"center\" /> </RelativeLayout>", "e": 31637, "s": 29972, "text": null }, { "code": null, "e": 31667, "s": 31637, "text": "Step 4: Creating Module Class" }, { "code": null, "e": 32329, "s": 31667, "text": "Now, we will create a Module class which is used to construct the object and provide the dependencies. @Module annotations are used over the module class. This class contains a constructor that will initialize the context and a method that will return the dependent object for which @Provides annotation is used. Here, provideSharedPreferences() method will return the dependent object. In general, the method that returns the dependent object will be followed by the word provide. Go to the app > java > package > right-click and create a new java class and name it as SharedPreferenceModule. Below is the code snippet for the SharedPreferenceModule.java file." }, { "code": null, "e": 32334, "s": 32329, "text": "Java" }, { "code": "import android.content.Context;import android.content.SharedPreferences;import android.preference.PreferenceManager;import javax.inject.Singleton;import dagger.Module;import dagger.Provides; // @Module annotation is used over the class that // creates construct object and provides dependencies@Modulepublic class SharedPreferenceModule { private Context context; // Context gets initialize from the constructor itself public SharedPreferenceModule(Context context) { this.context = context; } @Singleton @Provides public Context provideContext() { return context; } // @Singleton indicates that only single instance // of dependency object is created // @Provide annotations used over the methods that // will provides the object of module class // This method will return the dependent object @Singleton @Provides public SharedPreferences provideSharedPreferences(Context context) { return PreferenceManager.getDefaultSharedPreferences(context); }}", "e": 33365, "s": 32334, "text": null }, { "code": null, "e": 33404, "s": 33365, "text": "Step 5: Creating a Component Interface" }, { "code": null, "e": 33625, "s": 33404, "text": "In this step, we will create an Interface. Go to the app > java > package > right-click and create an interface and name it as SharedPreferenceComponent. We use @Component annotation in order to mention all the modules. " }, { "code": null, "e": 33671, "s": 33625, "text": "@Component(modules={SharedPreferenceModule}) " }, { "code": null, "e": 33912, "s": 33671, "text": "The Activities, Fragments, or Services that may request the dependencies declared by modules must be declared in this interface with the individual inject() method. Below is the code snippet for the SharedPreferenceComponent.java Interface." }, { "code": null, "e": 33917, "s": 33912, "text": "Java" }, { "code": "import javax.inject.Singleton;import dagger.Component; // All the modules are mentioned under // the @Component annotation@Singleton@Component(modules = {SharedPreferenceModule.class})public interface SharedPreferenceComponent { void inject(MainActivity mainActivity);}", "e": 34191, "s": 33917, "text": null }, { "code": null, "e": 34239, "s": 34191, "text": "Step 6: Working With the MainActivity.java File" }, { "code": null, "e": 34394, "s": 34239, "text": "In this step, we will first initialize our Views and then bind Dagger to our application. For which component-interface is followed by the Dagger keyword." }, { "code": null, "e": 34530, "s": 34394, "text": "sharedPreferenceComponent = DaggerSharedPreferenceComponent.builder().sharedPreferenceModule(new SharedPreferenceModule(this)).build();" }, { "code": null, "e": 34570, "s": 34530, "text": "sharedPreferenceComponent.inject(this);" }, { "code": null, "e": 34628, "s": 34570, "text": "Below is the code snippet for the MainActivity.java file." }, { "code": null, "e": 34841, "s": 34628, "text": "Note: When you will use Dagger as a prefix with Component(here, SharedPreferenceComponent) sometimes you may get an error or warning this is because DaggerSharedPreferenceComponent is generated after compilation." }, { "code": null, "e": 34846, "s": 34841, "text": "Java" }, { "code": "import android.content.SharedPreferences;import android.os.Bundle;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.TextView;import androidx.appcompat.app.AppCompatActivity;import javax.inject.Inject; public class MainActivity extends AppCompatActivity implements View.OnClickListener { EditText editText; TextView textView; Button saveBtn, getBtn; private SharedPreferenceComponent sharedPreferenceComponent; // @Inject is used to tell which activity, // fragment or service is allowed to request // dependencies declared in Module class @Inject SharedPreferences sharedPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Referencing the EditText, TextView and Buttons editText = (EditText) findViewById(R.id.inputField); textView = (TextView) findViewById(R.id.outputField); saveBtn = (Button) findViewById(R.id.saveBtn); getBtn = (Button) findViewById(R.id.getBtn); // Setting onClickListener behavior on button to reference // to the current activity(this MainActivity) saveBtn.setOnClickListener(this); getBtn.setOnClickListener(this); // Here we are binding dagger to our application // Dagger keyword will be prefix to the component name sharedPreferenceComponent = DaggerSharedPreferenceComponent.builder().sharedPreferenceModule( new SharedPreferenceModule(this)).build(); // we are injecting the shared preference dependent object sharedPreferenceComponent.inject(this); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.saveBtn: // Saving data to shared preference // inputField acts as key and editText data as value to that key SharedPreferences.Editor editor = sharedPreferences.edit(); editor.putString(\"inputField\", editText.getText().toString().trim()); editor.apply(); break; case R.id.getBtn: // getting shared preferences data and set it to textview // s1: is the default string, You can write any thing there or leave it textView.setText(sharedPreferences.getString(\"inputField\", \"\")); break; } }}", "e": 37338, "s": 34846, "text": null }, { "code": null, "e": 37346, "s": 37338, "text": "android" }, { "code": null, "e": 37370, "s": 37346, "text": "Technical Scripter 2020" }, { "code": null, "e": 37378, "s": 37370, "text": "Android" }, { "code": null, "e": 37383, "s": 37378, "text": "Java" }, { "code": null, "e": 37402, "s": 37383, "text": "Technical Scripter" }, { "code": null, "e": 37407, "s": 37402, "text": "Java" }, { "code": null, "e": 37415, "s": 37407, "text": "Android" }, { "code": null, "e": 37513, "s": 37415, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37571, "s": 37513, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 37609, "s": 37571, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 37652, "s": 37609, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 37685, "s": 37652, "text": "Services in Android with Example" }, { "code": null, "e": 37716, "s": 37685, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 37731, "s": 37716, "text": "Arrays in Java" }, { "code": null, "e": 37775, "s": 37731, "text": "Split() String method in Java with examples" }, { "code": null, "e": 37797, "s": 37775, "text": "For-each loop in Java" }, { "code": null, "e": 37848, "s": 37797, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Biconnected graph
20 Jun, 2022 An undirected graph is called Biconnected if there are two vertex-disjoint paths between any two vertices. In a Biconnected Graph, there is a simple cycle through any two vertices. By convention, two nodes connected by an edge form a biconnected graph, but this does not verify the above properties. For a graph with more than two vertices, the above properties must be there for it to be Biconnected.Or in other words: A graph is said to be Biconnected if: It is connected, i.e. it is possible to reach every vertex from every other vertex, by a simple path. Even after removing any vertex the graph remains connected. It is connected, i.e. it is possible to reach every vertex from every other vertex, by a simple path. Even after removing any vertex the graph remains connected. Following are some examples: Example-1 Example-2 Example-3 Example-4 Example-5 See this for more examples. How to find if a given graph is Biconnected or not? A connected graph is Biconnected if it is connected and doesn’t have any Articulation Point. We mainly need to check two things in a graph. The graph is connected. There is not articulation point in graph. The graph is connected. There is not articulation point in graph. We start from any vertex and do DFS traversal. In DFS traversal, we check if there is any articulation point. If we don’t find any articulation point, then the graph is Biconnected. Finally, we need to check whether all vertices were reachable in DFS or not. If all vertices were not reachable, then the graph is not even connected. Following is the implementation of above approach. C++ Java Python3 C# Javascript // A C++ program to find if a given undirected graph is// biconnected#include<iostream>#include <list>#define NIL -1using namespace std; // A class that represents an undirected graphclass Graph{ int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency lists bool isBCUtil(int v, bool visited[], int disc[], int low[], int parent[]);public: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph bool isBC(); // returns true if graph is Biconnected}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); adj[w].push_back(v); // Note: the graph is undirected} // A recursive function that returns true if there is an articulation// point in given graph, otherwise returns false.// This function is almost same as isAPUtil() here ( http://goo.gl/Me9Fw )// u --> The vertex to be visited next// visited[] --> keeps track of visited vertices// disc[] --> Stores discovery times of visited vertices// parent[] --> Stores parent vertices in DFS treebool Graph::isBCUtil(int u, bool visited[], int disc[],int low[],int parent[]){ // A static variable is used for simplicity, we can avoid use of static // variable by passing a pointer. static int time = 0; // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; // v is current adjacent of u // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; parent[v] = u; // check if subgraph rooted with v has an articulation point if (isBCUtil(v, visited, disc, low, parent)) return true; // Check if the subtree rooted with v has a connection to // one of the ancestors of u low[u] = min(low[u], low[v]); // u is an articulation point in following cases // (1) u is root of DFS tree and has two or more children. if (parent[u] == NIL && children > 1) return true; // (2) If u is not root and low value of one of its child is // more than discovery value of u. if (parent[u] != NIL && low[v] >= disc[u]) return true; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = min(low[u], disc[v]); } return false;} // The main function that returns true if graph is Biconnected,// otherwise false. It uses recursive function isBCUtil()bool Graph::isBC(){ // Mark all the vertices as not visited bool *visited = new bool[V]; int *disc = new int[V]; int *low = new int[V]; int *parent = new int[V]; // Initialize parent and visited, and ap(articulation point) // arrays for (int i = 0; i < V; i++) { parent[i] = NIL; visited[i] = false; } // Call the recursive helper function to find if there is an articulation // point in given graph. We do DFS traversal starting from vertex 0 if (isBCUtil(0, visited, disc, low, parent) == true) return false; // Now check whether the given graph is connected or not. An undirected // graph is connected if all vertices are reachable from any starting // point (we have taken 0 as starting point) for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true;} // Driver program to test above functionint main(){ // Create graphs given in above diagrams Graph g1(2); g1.addEdge(0, 1); g1.isBC()? cout << "Yes\n" : cout << "No\n"; Graph g2(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(2, 4); g2.isBC()? cout << "Yes\n" : cout << "No\n"; Graph g3(3); g3.addEdge(0, 1); g3.addEdge(1, 2); g3.isBC()? cout << "Yes\n" : cout << "No\n"; Graph g4(5); g4.addEdge(1, 0); g4.addEdge(0, 2); g4.addEdge(2, 1); g4.addEdge(0, 3); g4.addEdge(3, 4); g4.isBC()? cout << "Yes\n" : cout << "No\n"; Graph g5(3); g5.addEdge(0, 1); g5.addEdge(1, 2); g5.addEdge(2, 0); g5.isBC()? cout << "Yes\n" : cout << "No\n"; return 0;} // A Java program to find if a given undirected graph is// biconnectedimport java.io.*;import java.util.*;import java.util.LinkedList; // This class represents a directed graph using adjacency// list representationclass Graph{ private int V; // No. of vertices // Array of lists for Adjacency List Representation private LinkedList<Integer> adj[]; int time = 0; static final int NIL = -1; // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); //Note that the graph is undirected. adj[w].add(v); } // A recursive function that returns true if there is an articulation // point in given graph, otherwise returns false. // This function is almost same as isAPUtil() @ http://goo.gl/Me9Fw // u --> The vertex to be visited next // visited[] --> keeps track of visited vertices // disc[] --> Stores discovery times of visited vertices // parent[] --> Stores parent vertices in DFS tree boolean isBCUtil(int u, boolean visited[], int disc[],int low[], int parent[]) { // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this Iterator<Integer> i = adj[u].iterator(); while (i.hasNext()) { int v = i.next(); // v is current adjacent of u // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; parent[v] = u; // check if subgraph rooted with v has an articulation point if (isBCUtil(v, visited, disc, low, parent)) return true; // Check if the subtree rooted with v has a connection to // one of the ancestors of u low[u] = Math.min(low[u], low[v]); // u is an articulation point in following cases // (1) u is root of DFS tree and has two or more children. if (parent[u] == NIL && children > 1) return true; // (2) If u is not root and low value of one of its // child is more than discovery value of u. if (parent[u] != NIL && low[v] >= disc[u]) return true; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = Math.min(low[u], disc[v]); } return false; } // The main function that returns true if graph is Biconnected, // otherwise false. It uses recursive function isBCUtil() boolean isBC() { // Mark all the vertices as not visited boolean visited[] = new boolean[V]; int disc[] = new int[V]; int low[] = new int[V]; int parent[] = new int[V]; // Initialize parent and visited, and ap(articulation point) // arrays for (int i = 0; i < V; i++) { parent[i] = NIL; visited[i] = false; } // Call the recursive helper function to find if there is an // articulation/ point in given graph. We do DFS traversal // starting from vertex 0 if (isBCUtil(0, visited, disc, low, parent) == true) return false; // Now check whether the given graph is connected or not. // An undirected graph is connected if all vertices are // reachable from any starting point (we have taken 0 as // starting point) for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true; } // Driver method public static void main(String args[]) { // Create graphs given in above diagrams Graph g1 =new Graph(2); g1.addEdge(0, 1); if (g1.isBC()) System.out.println("Yes"); else System.out.println("No"); Graph g2 =new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(2, 4); if (g2.isBC()) System.out.println("Yes"); else System.out.println("No"); Graph g3 = new Graph(3); g3.addEdge(0, 1); g3.addEdge(1, 2); if (g3.isBC()) System.out.println("Yes"); else System.out.println("No"); Graph g4 = new Graph(5); g4.addEdge(1, 0); g4.addEdge(0, 2); g4.addEdge(2, 1); g4.addEdge(0, 3); g4.addEdge(3, 4); if (g4.isBC()) System.out.println("Yes"); else System.out.println("No"); Graph g5= new Graph(3); g5.addEdge(0, 1); g5.addEdge(1, 2); g5.addEdge(2, 0); if (g5.isBC()) System.out.println("Yes"); else System.out.println("No"); }}// This code is contributed by Aakash Hasija # A Python program to find if a given undirected graph is# biconnected from collections import defaultdict #This class represents an undirected graph using adjacency list representationclass Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = defaultdict(list) # default dictionary to store graph self.Time = 0 # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) '''A recursive function that returns true if there is an articulation point in given graph, otherwise returns false. This function is almost same as isAPUtil() u --> The vertex to be visited next visited[] --> keeps track of visited vertices disc[] --> Stores discovery times of visited vertices parent[] --> Stores parent vertices in DFS tree''' def isBCUtil(self,u, visited, parent, low, disc): #Count of children in current node children =0 # Mark the current node as visited and print it visited[u]= True # Initialize discovery time and low value disc[u] = self.Time low[u] = self.Time self.Time += 1 #Recur for all the vertices adjacent to this vertex for v in self.graph[u]: # If v is not visited yet, then make it a child of u # in DFS tree and recur for it if visited[v] == False : parent[v] = u children += 1 if self.isBCUtil(v, visited, parent, low, disc): return True # Check if the subtree rooted with v has a connection to # one of the ancestors of u low[u] = min(low[u], low[v]) # u is an articulation point in following cases # (1) u is root of DFS tree and has two or more children. if parent[u] == -1 and children > 1: return True #(2) If u is not root and low value of one of its child is more # than discovery value of u. if parent[u] != -1 and low[v] >= disc[u]: return True elif v != parent[u]: # Update low value of u for parent function calls. low[u] = min(low[u], disc[v]) return False # The main function that returns true if graph is Biconnected, # otherwise false. It uses recursive function isBCUtil() def isBC(self): # Mark all the vertices as not visited and Initialize parent and visited, # and ap(articulation point) arrays visited = [False] * (self.V) disc = [float("Inf")] * (self.V) low = [float("Inf")] * (self.V) parent = [-1] * (self.V) # Call the recursive helper function to find if there is an # articulation points in given graph. We do DFS traversal starting # from vertex 0 if self.isBCUtil(0, visited, parent, low, disc): return False '''Now check whether the given graph is connected or not. An undirected graph is connected if all vertices are reachable from any starting point (we have taken 0 as starting point)''' if any(i == False for i in visited): return False return True # Create a graph given in the above diagramg1 = Graph(2)g1.addEdge(0, 1)print ("Yes" if g1.isBC() else "No") g2 = Graph(5)g2.addEdge(1, 0)g2.addEdge(0, 2)g2.addEdge(2, 1)g2.addEdge(0, 3)g2.addEdge(3, 4)g2.addEdge(2, 4)print ("Yes" if g2.isBC() else "No") g3 = Graph(3)g3.addEdge(0, 1)g3.addEdge(1, 2)print ("Yes" if g3.isBC() else "No") g4 = Graph (5)g4.addEdge(1, 0)g4.addEdge(0, 2)g4.addEdge(2, 1)g4.addEdge(0, 3)g4.addEdge(3, 4)print ("Yes" if g4.isBC() else "No") g5 = Graph(3)g5.addEdge(0, 1)g5.addEdge(1, 2)g5.addEdge(2, 0)print ("Yes" if g5.isBC() else "No") #This code is contributed by Neelam Yadav // A C# program to find if a given undirected// graph is biconnectedusing System;using System.Collections.Generic; // This class represents a directed graph// using adjacency list representationclass Graph{ // No. of verticespublic int V; // Array of lists for Adjacency// List Representationpublic List<int> []adj; int time = 0;static readonly int NIL = -1; // ConstructorGraph(int v){ V = v; adj = new List<int>[v]; for(int i = 0; i < v; ++i) adj[i] = new List<int>();} // Function to add an edge into the graphvoid addEdge(int v, int w){ // Note that the graph is undirected. adj[v].Add(w); adj[w].Add(v);} // A recursive function that returns true// if there is an articulation point in// given graph, otherwise returns false.// This function is almost same as isAPUtil()// @ http://goo.gl/Me9Fw// u --> The vertex to be visited next// visited[] --> keeps track of visited vertices// disc[] --> Stores discovery times of visited vertices// parent[] --> Stores parent vertices in DFS treebool isBCUtil(int u, bool []visited, int []disc,int []low, int []parent){ // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this foreach(int i in adj[u]) { // v is current adjacent of u int v = i; // If v is not visited yet, then // make it a child of u in DFS // tree and recur for it if (!visited[v]) { children++; parent[v] = u; // Check if subgraph rooted with v // has an articulation point if (isBCUtil(v, visited, disc, low, parent)) return true; // Check if the subtree rooted with // v has a connection to one of // the ancestors of u low[u] = Math.Min(low[u], low[v]); // u is an articulation point in // following cases // (1) u is root of DFS tree and // has two or more children. if (parent[u] == NIL && children > 1) return true; // (2) If u is not root and low // value of one of its child is // more than discovery value of u. if (parent[u] != NIL && low[v] >= disc[u]) return true; } // Update low value of u for // parent function calls. else if (v != parent[u]) low[u] = Math.Min(low[u], disc[v]); } return false;} // The main function that returns true// if graph is Biconnected, otherwise// false. It uses recursive function// isBCUtil()bool isBC(){ // Mark all the vertices as not visited bool []visited = new bool[V]; int []disc = new int[V]; int []low = new int[V]; int []parent = new int[V]; // Initialize parent and visited, // and ap(articulation point) // arrays for(int i = 0; i < V; i++) { parent[i] = NIL; visited[i] = false; } // Call the recursive helper function to // find if there is an articulation/ point // in given graph. We do DFS traversal // starting from vertex 0 if (isBCUtil(0, visited, disc, low, parent) == true) return false; // Now check whether the given graph // is connected or not. An undirected // graph is connected if all vertices are // reachable from any starting point // (we have taken 0 as starting point) for(int i = 0; i < V; i++) if (visited[i] == false) return false; return true;} // Driver codepublic static void Main(String []args){ // Create graphs given in above diagrams Graph g1 = new Graph(2); g1.addEdge(0, 1); if (g1.isBC()) Console.WriteLine("Yes"); else Console.WriteLine("No"); Graph g2 = new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(2, 4); if (g2.isBC()) Console.WriteLine("Yes"); else Console.WriteLine("No"); Graph g3 = new Graph(3); g3.addEdge(0, 1); g3.addEdge(1, 2); if (g3.isBC()) Console.WriteLine("Yes"); else Console.WriteLine("No"); Graph g4 = new Graph(5); g4.addEdge(1, 0); g4.addEdge(0, 2); g4.addEdge(2, 1); g4.addEdge(0, 3); g4.addEdge(3, 4); if (g4.isBC()) Console.WriteLine("Yes"); else Console.WriteLine("No"); Graph g5 = new Graph(3); g5.addEdge(0, 1); g5.addEdge(1, 2); g5.addEdge(2, 0); if (g5.isBC()) Console.WriteLine("Yes"); else Console.WriteLine("No");}} // This code is contributed by Amit Katiyar <script>// A Javascript program to find if a given undirected graph is// biconnected // This class represents a directed graph using adjacency// list representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); this.NIL = -1; this.time = 0; for (let i=0; i<v; ++i) this.adj[i] = []; } //Function to add an edge into the graph addEdge(v,w) { this.adj[v].push(w); //Note that the graph is undirected. this.adj[w].push(v); } // A recursive function that returns true if there is an articulation // point in given graph, otherwise returns false. // This function is almost same as isAPUtil() @ http://goo.gl/Me9Fw // u --> The vertex to be visited next // visited[] --> keeps track of visited vertices // disc[] --> Stores discovery times of visited vertices // parent[] --> Stores parent vertices in DFS tree isBCUtil(u,visited,disc,low,parent) { // Count of children in DFS Tree let children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++this.time; // Go through all vertices adjacent to this for(let i of this.adj[u]) { let v = i; // v is current adjacent of u // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; parent[v] = u; // check if subgraph rooted with v has an articulation point if (this.isBCUtil(v, visited, disc, low, parent)) return true; // Check if the subtree rooted with v has a connection to // one of the ancestors of u low[u] = Math.min(low[u], low[v]); // u is an articulation point in following cases // (1) u is root of DFS tree and has two or more children. if (parent[u] == this.NIL && children > 1) return true; // (2) If u is not root and low value of one of its // child is more than discovery value of u. if (parent[u] != this.NIL && low[v] >= disc[u]) return true; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = Math.min(low[u], disc[v]); } return false; } // The main function that returns true if graph is Biconnected, // otherwise false. It uses recursive function isBCUtil() isBC() { // Mark all the vertices as not visited let visited = new Array(this.V); let disc = new Array(this.V); let low = new Array(this.V); let parent = new Array(this.V); // Initialize parent and visited, and ap(articulation point) // arrays for (let i = 0; i < this.V; i++) { parent[i] = this.NIL; visited[i] = false; } // Call the recursive helper function to find if there is an // articulation/ point in given graph. We do DFS traversal // starting from vertex 0 if (this.isBCUtil(0, visited, disc, low, parent) == true) return false; // Now check whether the given graph is connected or not. // An undirected graph is connected if all vertices are // reachable from any starting point (we have taken 0 as // starting point) for (let i = 0; i < this.V; i++) if (visited[i] == false) return false; return true; }} // Driver method// Create graphs given in above diagrams let g1 =new Graph(2); g1.addEdge(0, 1); if (g1.isBC()) document.write("Yes<br>"); else document.write("No<br>"); let g2 =new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(2, 4); if (g2.isBC()) document.write("Yes<br>"); else document.write("No<br>"); let g3 = new Graph(3); g3.addEdge(0, 1); g3.addEdge(1, 2); if (g3.isBC()) document.write("Yes<br>"); else document.write("No<br>"); let g4 = new Graph(5); g4.addEdge(1, 0); g4.addEdge(0, 2); g4.addEdge(2, 1); g4.addEdge(0, 3); g4.addEdge(3, 4); if (g4.isBC()) document.write("Yes<br>"); else document.write("No<br>"); let g5= new Graph(3); g5.addEdge(0, 1); g5.addEdge(1, 2); g5.addEdge(2, 0); if (g5.isBC()) document.write("Yes<br>"); else document.write("No<br>"); // This code is contributed by avanitrachhadiya2155</script> Yes Yes No No Yes Time Complexity: The above function is a simple DFS with additional arrays. So time complexity is same as DFS which is O(V+E) for adjacency list representation of graph. mayank9722 amit143katiyar avanitrachhadiya2155 sagar0719kumar ruhelaa48 gabaa406 amartyaghoshgfg hardikkoriintern graph-connectivity Graph Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n20 Jun, 2022" }, { "code": null, "e": 234, "s": 52, "text": "An undirected graph is called Biconnected if there are two vertex-disjoint paths between any two vertices. In a Biconnected Graph, there is a simple cycle through any two vertices. " }, { "code": null, "e": 474, "s": 234, "text": "By convention, two nodes connected by an edge form a biconnected graph, but this does not verify the above properties. For a graph with more than two vertices, the above properties must be there for it to be Biconnected.Or in other words: " }, { "code": null, "e": 513, "s": 474, "text": "A graph is said to be Biconnected if: " }, { "code": null, "e": 675, "s": 513, "text": "It is connected, i.e. it is possible to reach every vertex from every other vertex, by a simple path. Even after removing any vertex the graph remains connected." }, { "code": null, "e": 778, "s": 675, "text": "It is connected, i.e. it is possible to reach every vertex from every other vertex, by a simple path. " }, { "code": null, "e": 838, "s": 778, "text": "Even after removing any vertex the graph remains connected." }, { "code": null, "e": 867, "s": 838, "text": "Following are some examples:" }, { "code": null, "e": 877, "s": 867, "text": "Example-1" }, { "code": null, "e": 887, "s": 877, "text": "Example-2" }, { "code": null, "e": 897, "s": 887, "text": "Example-3" }, { "code": null, "e": 907, "s": 897, "text": "Example-4" }, { "code": null, "e": 917, "s": 907, "text": "Example-5" }, { "code": null, "e": 947, "s": 919, "text": "See this for more examples." }, { "code": null, "e": 1000, "s": 947, "text": "How to find if a given graph is Biconnected or not? " }, { "code": null, "e": 1141, "s": 1000, "text": "A connected graph is Biconnected if it is connected and doesn’t have any Articulation Point. We mainly need to check two things in a graph. " }, { "code": null, "e": 1207, "s": 1141, "text": "The graph is connected. There is not articulation point in graph." }, { "code": null, "e": 1232, "s": 1207, "text": "The graph is connected. " }, { "code": null, "e": 1274, "s": 1232, "text": "There is not articulation point in graph." }, { "code": null, "e": 1608, "s": 1274, "text": "We start from any vertex and do DFS traversal. In DFS traversal, we check if there is any articulation point. If we don’t find any articulation point, then the graph is Biconnected. Finally, we need to check whether all vertices were reachable in DFS or not. If all vertices were not reachable, then the graph is not even connected. " }, { "code": null, "e": 1659, "s": 1608, "text": "Following is the implementation of above approach." }, { "code": null, "e": 1663, "s": 1659, "text": "C++" }, { "code": null, "e": 1668, "s": 1663, "text": "Java" }, { "code": null, "e": 1676, "s": 1668, "text": "Python3" }, { "code": null, "e": 1679, "s": 1676, "text": "C#" }, { "code": null, "e": 1690, "s": 1679, "text": "Javascript" }, { "code": "// A C++ program to find if a given undirected graph is// biconnected#include<iostream>#include <list>#define NIL -1using namespace std; // A class that represents an undirected graphclass Graph{ int V; // No. of vertices list<int> *adj; // A dynamic array of adjacency lists bool isBCUtil(int v, bool visited[], int disc[], int low[], int parent[]);public: Graph(int V); // Constructor void addEdge(int v, int w); // to add an edge to graph bool isBC(); // returns true if graph is Biconnected}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} void Graph::addEdge(int v, int w){ adj[v].push_back(w); adj[w].push_back(v); // Note: the graph is undirected} // A recursive function that returns true if there is an articulation// point in given graph, otherwise returns false.// This function is almost same as isAPUtil() here ( http://goo.gl/Me9Fw )// u --> The vertex to be visited next// visited[] --> keeps track of visited vertices// disc[] --> Stores discovery times of visited vertices// parent[] --> Stores parent vertices in DFS treebool Graph::isBCUtil(int u, bool visited[], int disc[],int low[],int parent[]){ // A static variable is used for simplicity, we can avoid use of static // variable by passing a pointer. static int time = 0; // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this list<int>::iterator i; for (i = adj[u].begin(); i != adj[u].end(); ++i) { int v = *i; // v is current adjacent of u // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; parent[v] = u; // check if subgraph rooted with v has an articulation point if (isBCUtil(v, visited, disc, low, parent)) return true; // Check if the subtree rooted with v has a connection to // one of the ancestors of u low[u] = min(low[u], low[v]); // u is an articulation point in following cases // (1) u is root of DFS tree and has two or more children. if (parent[u] == NIL && children > 1) return true; // (2) If u is not root and low value of one of its child is // more than discovery value of u. if (parent[u] != NIL && low[v] >= disc[u]) return true; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = min(low[u], disc[v]); } return false;} // The main function that returns true if graph is Biconnected,// otherwise false. It uses recursive function isBCUtil()bool Graph::isBC(){ // Mark all the vertices as not visited bool *visited = new bool[V]; int *disc = new int[V]; int *low = new int[V]; int *parent = new int[V]; // Initialize parent and visited, and ap(articulation point) // arrays for (int i = 0; i < V; i++) { parent[i] = NIL; visited[i] = false; } // Call the recursive helper function to find if there is an articulation // point in given graph. We do DFS traversal starting from vertex 0 if (isBCUtil(0, visited, disc, low, parent) == true) return false; // Now check whether the given graph is connected or not. An undirected // graph is connected if all vertices are reachable from any starting // point (we have taken 0 as starting point) for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true;} // Driver program to test above functionint main(){ // Create graphs given in above diagrams Graph g1(2); g1.addEdge(0, 1); g1.isBC()? cout << \"Yes\\n\" : cout << \"No\\n\"; Graph g2(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(2, 4); g2.isBC()? cout << \"Yes\\n\" : cout << \"No\\n\"; Graph g3(3); g3.addEdge(0, 1); g3.addEdge(1, 2); g3.isBC()? cout << \"Yes\\n\" : cout << \"No\\n\"; Graph g4(5); g4.addEdge(1, 0); g4.addEdge(0, 2); g4.addEdge(2, 1); g4.addEdge(0, 3); g4.addEdge(3, 4); g4.isBC()? cout << \"Yes\\n\" : cout << \"No\\n\"; Graph g5(3); g5.addEdge(0, 1); g5.addEdge(1, 2); g5.addEdge(2, 0); g5.isBC()? cout << \"Yes\\n\" : cout << \"No\\n\"; return 0;}", "e": 6248, "s": 1690, "text": null }, { "code": "// A Java program to find if a given undirected graph is// biconnectedimport java.io.*;import java.util.*;import java.util.LinkedList; // This class represents a directed graph using adjacency// list representationclass Graph{ private int V; // No. of vertices // Array of lists for Adjacency List Representation private LinkedList<Integer> adj[]; int time = 0; static final int NIL = -1; // Constructor Graph(int v) { V = v; adj = new LinkedList[v]; for (int i=0; i<v; ++i) adj[i] = new LinkedList(); } //Function to add an edge into the graph void addEdge(int v, int w) { adj[v].add(w); //Note that the graph is undirected. adj[w].add(v); } // A recursive function that returns true if there is an articulation // point in given graph, otherwise returns false. // This function is almost same as isAPUtil() @ http://goo.gl/Me9Fw // u --> The vertex to be visited next // visited[] --> keeps track of visited vertices // disc[] --> Stores discovery times of visited vertices // parent[] --> Stores parent vertices in DFS tree boolean isBCUtil(int u, boolean visited[], int disc[],int low[], int parent[]) { // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this Iterator<Integer> i = adj[u].iterator(); while (i.hasNext()) { int v = i.next(); // v is current adjacent of u // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; parent[v] = u; // check if subgraph rooted with v has an articulation point if (isBCUtil(v, visited, disc, low, parent)) return true; // Check if the subtree rooted with v has a connection to // one of the ancestors of u low[u] = Math.min(low[u], low[v]); // u is an articulation point in following cases // (1) u is root of DFS tree and has two or more children. if (parent[u] == NIL && children > 1) return true; // (2) If u is not root and low value of one of its // child is more than discovery value of u. if (parent[u] != NIL && low[v] >= disc[u]) return true; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = Math.min(low[u], disc[v]); } return false; } // The main function that returns true if graph is Biconnected, // otherwise false. It uses recursive function isBCUtil() boolean isBC() { // Mark all the vertices as not visited boolean visited[] = new boolean[V]; int disc[] = new int[V]; int low[] = new int[V]; int parent[] = new int[V]; // Initialize parent and visited, and ap(articulation point) // arrays for (int i = 0; i < V; i++) { parent[i] = NIL; visited[i] = false; } // Call the recursive helper function to find if there is an // articulation/ point in given graph. We do DFS traversal // starting from vertex 0 if (isBCUtil(0, visited, disc, low, parent) == true) return false; // Now check whether the given graph is connected or not. // An undirected graph is connected if all vertices are // reachable from any starting point (we have taken 0 as // starting point) for (int i = 0; i < V; i++) if (visited[i] == false) return false; return true; } // Driver method public static void main(String args[]) { // Create graphs given in above diagrams Graph g1 =new Graph(2); g1.addEdge(0, 1); if (g1.isBC()) System.out.println(\"Yes\"); else System.out.println(\"No\"); Graph g2 =new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(2, 4); if (g2.isBC()) System.out.println(\"Yes\"); else System.out.println(\"No\"); Graph g3 = new Graph(3); g3.addEdge(0, 1); g3.addEdge(1, 2); if (g3.isBC()) System.out.println(\"Yes\"); else System.out.println(\"No\"); Graph g4 = new Graph(5); g4.addEdge(1, 0); g4.addEdge(0, 2); g4.addEdge(2, 1); g4.addEdge(0, 3); g4.addEdge(3, 4); if (g4.isBC()) System.out.println(\"Yes\"); else System.out.println(\"No\"); Graph g5= new Graph(3); g5.addEdge(0, 1); g5.addEdge(1, 2); g5.addEdge(2, 0); if (g5.isBC()) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}// This code is contributed by Aakash Hasija", "e": 11534, "s": 6248, "text": null }, { "code": "# A Python program to find if a given undirected graph is# biconnected from collections import defaultdict #This class represents an undirected graph using adjacency list representationclass Graph: def __init__(self,vertices): self.V= vertices #No. of vertices self.graph = defaultdict(list) # default dictionary to store graph self.Time = 0 # function to add an edge to graph def addEdge(self,u,v): self.graph[u].append(v) self.graph[v].append(u) '''A recursive function that returns true if there is an articulation point in given graph, otherwise returns false. This function is almost same as isAPUtil() u --> The vertex to be visited next visited[] --> keeps track of visited vertices disc[] --> Stores discovery times of visited vertices parent[] --> Stores parent vertices in DFS tree''' def isBCUtil(self,u, visited, parent, low, disc): #Count of children in current node children =0 # Mark the current node as visited and print it visited[u]= True # Initialize discovery time and low value disc[u] = self.Time low[u] = self.Time self.Time += 1 #Recur for all the vertices adjacent to this vertex for v in self.graph[u]: # If v is not visited yet, then make it a child of u # in DFS tree and recur for it if visited[v] == False : parent[v] = u children += 1 if self.isBCUtil(v, visited, parent, low, disc): return True # Check if the subtree rooted with v has a connection to # one of the ancestors of u low[u] = min(low[u], low[v]) # u is an articulation point in following cases # (1) u is root of DFS tree and has two or more children. if parent[u] == -1 and children > 1: return True #(2) If u is not root and low value of one of its child is more # than discovery value of u. if parent[u] != -1 and low[v] >= disc[u]: return True elif v != parent[u]: # Update low value of u for parent function calls. low[u] = min(low[u], disc[v]) return False # The main function that returns true if graph is Biconnected, # otherwise false. It uses recursive function isBCUtil() def isBC(self): # Mark all the vertices as not visited and Initialize parent and visited, # and ap(articulation point) arrays visited = [False] * (self.V) disc = [float(\"Inf\")] * (self.V) low = [float(\"Inf\")] * (self.V) parent = [-1] * (self.V) # Call the recursive helper function to find if there is an # articulation points in given graph. We do DFS traversal starting # from vertex 0 if self.isBCUtil(0, visited, parent, low, disc): return False '''Now check whether the given graph is connected or not. An undirected graph is connected if all vertices are reachable from any starting point (we have taken 0 as starting point)''' if any(i == False for i in visited): return False return True # Create a graph given in the above diagramg1 = Graph(2)g1.addEdge(0, 1)print (\"Yes\" if g1.isBC() else \"No\") g2 = Graph(5)g2.addEdge(1, 0)g2.addEdge(0, 2)g2.addEdge(2, 1)g2.addEdge(0, 3)g2.addEdge(3, 4)g2.addEdge(2, 4)print (\"Yes\" if g2.isBC() else \"No\") g3 = Graph(3)g3.addEdge(0, 1)g3.addEdge(1, 2)print (\"Yes\" if g3.isBC() else \"No\") g4 = Graph (5)g4.addEdge(1, 0)g4.addEdge(0, 2)g4.addEdge(2, 1)g4.addEdge(0, 3)g4.addEdge(3, 4)print (\"Yes\" if g4.isBC() else \"No\") g5 = Graph(3)g5.addEdge(0, 1)g5.addEdge(1, 2)g5.addEdge(2, 0)print (\"Yes\" if g5.isBC() else \"No\") #This code is contributed by Neelam Yadav", "e": 15464, "s": 11534, "text": null }, { "code": "// A C# program to find if a given undirected// graph is biconnectedusing System;using System.Collections.Generic; // This class represents a directed graph// using adjacency list representationclass Graph{ // No. of verticespublic int V; // Array of lists for Adjacency// List Representationpublic List<int> []adj; int time = 0;static readonly int NIL = -1; // ConstructorGraph(int v){ V = v; adj = new List<int>[v]; for(int i = 0; i < v; ++i) adj[i] = new List<int>();} // Function to add an edge into the graphvoid addEdge(int v, int w){ // Note that the graph is undirected. adj[v].Add(w); adj[w].Add(v);} // A recursive function that returns true// if there is an articulation point in// given graph, otherwise returns false.// This function is almost same as isAPUtil()// @ http://goo.gl/Me9Fw// u --> The vertex to be visited next// visited[] --> keeps track of visited vertices// disc[] --> Stores discovery times of visited vertices// parent[] --> Stores parent vertices in DFS treebool isBCUtil(int u, bool []visited, int []disc,int []low, int []parent){ // Count of children in DFS Tree int children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++time; // Go through all vertices adjacent to this foreach(int i in adj[u]) { // v is current adjacent of u int v = i; // If v is not visited yet, then // make it a child of u in DFS // tree and recur for it if (!visited[v]) { children++; parent[v] = u; // Check if subgraph rooted with v // has an articulation point if (isBCUtil(v, visited, disc, low, parent)) return true; // Check if the subtree rooted with // v has a connection to one of // the ancestors of u low[u] = Math.Min(low[u], low[v]); // u is an articulation point in // following cases // (1) u is root of DFS tree and // has two or more children. if (parent[u] == NIL && children > 1) return true; // (2) If u is not root and low // value of one of its child is // more than discovery value of u. if (parent[u] != NIL && low[v] >= disc[u]) return true; } // Update low value of u for // parent function calls. else if (v != parent[u]) low[u] = Math.Min(low[u], disc[v]); } return false;} // The main function that returns true// if graph is Biconnected, otherwise// false. It uses recursive function// isBCUtil()bool isBC(){ // Mark all the vertices as not visited bool []visited = new bool[V]; int []disc = new int[V]; int []low = new int[V]; int []parent = new int[V]; // Initialize parent and visited, // and ap(articulation point) // arrays for(int i = 0; i < V; i++) { parent[i] = NIL; visited[i] = false; } // Call the recursive helper function to // find if there is an articulation/ point // in given graph. We do DFS traversal // starting from vertex 0 if (isBCUtil(0, visited, disc, low, parent) == true) return false; // Now check whether the given graph // is connected or not. An undirected // graph is connected if all vertices are // reachable from any starting point // (we have taken 0 as starting point) for(int i = 0; i < V; i++) if (visited[i] == false) return false; return true;} // Driver codepublic static void Main(String []args){ // Create graphs given in above diagrams Graph g1 = new Graph(2); g1.addEdge(0, 1); if (g1.isBC()) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); Graph g2 = new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(2, 4); if (g2.isBC()) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); Graph g3 = new Graph(3); g3.addEdge(0, 1); g3.addEdge(1, 2); if (g3.isBC()) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); Graph g4 = new Graph(5); g4.addEdge(1, 0); g4.addEdge(0, 2); g4.addEdge(2, 1); g4.addEdge(0, 3); g4.addEdge(3, 4); if (g4.isBC()) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); Graph g5 = new Graph(3); g5.addEdge(0, 1); g5.addEdge(1, 2); g5.addEdge(2, 0); if (g5.isBC()) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\");}} // This code is contributed by Amit Katiyar", "e": 20315, "s": 15464, "text": null }, { "code": "<script>// A Javascript program to find if a given undirected graph is// biconnected // This class represents a directed graph using adjacency// list representationclass Graph{ // Constructor constructor(v) { this.V = v; this.adj = new Array(v); this.NIL = -1; this.time = 0; for (let i=0; i<v; ++i) this.adj[i] = []; } //Function to add an edge into the graph addEdge(v,w) { this.adj[v].push(w); //Note that the graph is undirected. this.adj[w].push(v); } // A recursive function that returns true if there is an articulation // point in given graph, otherwise returns false. // This function is almost same as isAPUtil() @ http://goo.gl/Me9Fw // u --> The vertex to be visited next // visited[] --> keeps track of visited vertices // disc[] --> Stores discovery times of visited vertices // parent[] --> Stores parent vertices in DFS tree isBCUtil(u,visited,disc,low,parent) { // Count of children in DFS Tree let children = 0; // Mark the current node as visited visited[u] = true; // Initialize discovery time and low value disc[u] = low[u] = ++this.time; // Go through all vertices adjacent to this for(let i of this.adj[u]) { let v = i; // v is current adjacent of u // If v is not visited yet, then make it a child of u // in DFS tree and recur for it if (!visited[v]) { children++; parent[v] = u; // check if subgraph rooted with v has an articulation point if (this.isBCUtil(v, visited, disc, low, parent)) return true; // Check if the subtree rooted with v has a connection to // one of the ancestors of u low[u] = Math.min(low[u], low[v]); // u is an articulation point in following cases // (1) u is root of DFS tree and has two or more children. if (parent[u] == this.NIL && children > 1) return true; // (2) If u is not root and low value of one of its // child is more than discovery value of u. if (parent[u] != this.NIL && low[v] >= disc[u]) return true; } // Update low value of u for parent function calls. else if (v != parent[u]) low[u] = Math.min(low[u], disc[v]); } return false; } // The main function that returns true if graph is Biconnected, // otherwise false. It uses recursive function isBCUtil() isBC() { // Mark all the vertices as not visited let visited = new Array(this.V); let disc = new Array(this.V); let low = new Array(this.V); let parent = new Array(this.V); // Initialize parent and visited, and ap(articulation point) // arrays for (let i = 0; i < this.V; i++) { parent[i] = this.NIL; visited[i] = false; } // Call the recursive helper function to find if there is an // articulation/ point in given graph. We do DFS traversal // starting from vertex 0 if (this.isBCUtil(0, visited, disc, low, parent) == true) return false; // Now check whether the given graph is connected or not. // An undirected graph is connected if all vertices are // reachable from any starting point (we have taken 0 as // starting point) for (let i = 0; i < this.V; i++) if (visited[i] == false) return false; return true; }} // Driver method// Create graphs given in above diagrams let g1 =new Graph(2); g1.addEdge(0, 1); if (g1.isBC()) document.write(\"Yes<br>\"); else document.write(\"No<br>\"); let g2 =new Graph(5); g2.addEdge(1, 0); g2.addEdge(0, 2); g2.addEdge(2, 1); g2.addEdge(0, 3); g2.addEdge(3, 4); g2.addEdge(2, 4); if (g2.isBC()) document.write(\"Yes<br>\"); else document.write(\"No<br>\"); let g3 = new Graph(3); g3.addEdge(0, 1); g3.addEdge(1, 2); if (g3.isBC()) document.write(\"Yes<br>\"); else document.write(\"No<br>\"); let g4 = new Graph(5); g4.addEdge(1, 0); g4.addEdge(0, 2); g4.addEdge(2, 1); g4.addEdge(0, 3); g4.addEdge(3, 4); if (g4.isBC()) document.write(\"Yes<br>\"); else document.write(\"No<br>\"); let g5= new Graph(3); g5.addEdge(0, 1); g5.addEdge(1, 2); g5.addEdge(2, 0); if (g5.isBC()) document.write(\"Yes<br>\"); else document.write(\"No<br>\"); // This code is contributed by avanitrachhadiya2155</script>", "e": 25331, "s": 20315, "text": null }, { "code": null, "e": 25349, "s": 25331, "text": "Yes\nYes\nNo\nNo\nYes" }, { "code": null, "e": 25519, "s": 25349, "text": "Time Complexity: The above function is a simple DFS with additional arrays. So time complexity is same as DFS which is O(V+E) for adjacency list representation of graph." }, { "code": null, "e": 25530, "s": 25519, "text": "mayank9722" }, { "code": null, "e": 25545, "s": 25530, "text": "amit143katiyar" }, { "code": null, "e": 25566, "s": 25545, "text": "avanitrachhadiya2155" }, { "code": null, "e": 25581, "s": 25566, "text": "sagar0719kumar" }, { "code": null, "e": 25591, "s": 25581, "text": "ruhelaa48" }, { "code": null, "e": 25600, "s": 25591, "text": "gabaa406" }, { "code": null, "e": 25616, "s": 25600, "text": "amartyaghoshgfg" }, { "code": null, "e": 25633, "s": 25616, "text": "hardikkoriintern" }, { "code": null, "e": 25652, "s": 25633, "text": "graph-connectivity" }, { "code": null, "e": 25658, "s": 25652, "text": "Graph" }, { "code": null, "e": 25664, "s": 25658, "text": "Graph" } ]
Vertex Cover Problem | Set 2 (Dynamic Programming Solution for Tree)
10 Jun, 2021 A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. The problem to find minimum size vertex cover of a graph is NP complete. But it can be solved in polynomial time for trees. In this post a solution for Binary Tree is discussed. The same solution can be extended for n-ary trees. For example, consider the following binary tree. The smallest vertex cover is {20, 50, 30} and size of the vertex cover is 3. The idea is to consider following two possibilities for root and recursively for all nodes down the root. 1) Root is part of vertex cover: In this case root covers all children edges. We recursively calculate size of vertex covers for left and right subtrees and add 1 to the result (for root). 2) Root is not part of vertex cover: In this case, both children of root must be included in vertex cover to cover all root to children edges. We recursively calculate size of vertex covers of all grandchildren and number of children to the result (for two children of root). Below are implementation of above idea. C Java Python3 C# Javascript // A naive recursive C implementation for vertex cover problem for a tree#include <stdio.h>#include <stdlib.h> // A utility function to find min of two integersint min(int x, int y) { return (x < y)? x: y; } /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node *left, *right;}; // The function returns size of the minimum vertex coverint vCover(struct node *root){ // The size of minimum vertex cover is zero if tree is empty or there // is only one node if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 0; // Calculate size of vertex cover when root is part of it int size_incl = 1 + vCover(root->left) + vCover(root->right); // Calculate size of vertex cover when root is not part of it int size_excl = 0; if (root->left) size_excl += 1 + vCover(root->left->left) + vCover(root->left->right); if (root->right) size_excl += 1 + vCover(root->right->left) + vCover(root->right->right); // Return the minimum of two sizes return min(size_incl, size_excl);} // A utility function to create a nodestruct node* newNode( int data ){ struct node* temp = (struct node *) malloc( sizeof(struct node) ); temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ // Let us construct the tree given in the above diagram struct node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); printf ("Size of the smallest vertex cover is %d ", vCover(root)); return 0;} // A naive recursive Java implementation// for vertex cover problem for a tree class GFG{ // A utility function to find min of two integers static int min(int x, int y) { return (x < y) ? x : y; } /* * A binary tree node has data, pointer to left child and a pointer to right * child */ static class node { int data; node left, right; }; // The function returns size // of the minimum vertex cover static int vCover(node root) { // The size of minimum vertex cover // is zero if tree is empty or there // is only one node if (root == null) return 0; if (root.left == null && root.right == null) return 0; // Calculate size of vertex cover // when root is part of it int size_incl = 1 + vCover(root.left) + vCover(root.right); // Calculate size of vertex cover // when root is not part of it int size_excl = 0; if (root.left != null) size_excl += 1 + vCover(root.left.left) + vCover(root.left.right); if (root.right != null) size_excl += 1 + vCover(root.right.left) + vCover(root.right.right); // Return the minimum of two sizes return Math.min(size_incl, size_excl); } // A utility function to create a node static node newNode(int data) { node temp = new node(); temp.data = data; temp.left = temp.right = null; return temp; } // Driver code public static void main(String[] args) { // Let us construct tree given in the above diagram node root = newNode(20); root.left = newNode(8); root.left.left = newNode(4); root.left.right = newNode(12); root.left.right.left = newNode(10); root.left.right.right = newNode(14); root.right = newNode(22); root.right.right = newNode(25); System.out.printf("Size of the smallest vertex" + "cover is %d ", vCover(root)); }} // This code is contributed by 29AjayKumar # A naive recursive Python3 implementation# for vertex cover problem for a tree # A utility function to find min of two integers # A binary tree node has data, pointer to# left child and a pointer to right childclass Node: def __init__(self, x): self.data = x self.left = None self.right = None # The function returns size of# the minimum vertex coverdef vCover(root): # The size of minimum vertex cover # is zero if tree is empty or there # is only one node if (root == None): return 0 if (root.left == None and root.right == None): return 0 # Calculate size of vertex cover when # root is part of it size_incl = (1 + vCover(root.left) + vCover(root.right)) # Calculate size of vertex cover # when root is not part of it size_excl = 0 if (root.left): size_excl += (1 + vCover(root.left.left) + vCover(root.left.right)) if (root.right): size_excl += (1 + vCover(root.right.left) + vCover(root.right.right)) # Return the minimum of two sizes return min(size_incl, size_excl) # Driver Codeif __name__ == '__main__': # Let us construct the tree # given in the above diagram root = Node(20) root.left = Node(8) root.left.left = Node(4) root.left.right = Node(12) root.left.right.left = Node(10) root.left.right.right = Node(14) root.right = Node(22) root.right.right = Node(25) print("Size of the smallest vertex cover is", vCover(root)) # This code is contributed by mohit kumar 29 // A naive recursive C# implementation// for vertex cover problem for a treeusing System; class GFG{ // A utility function to find // min of two integers static int min(int x, int y) { return (x < y) ? x : y; } /* * A binary tree node has data, pointer to left child and a pointer to right * child */ public class node { public int data; public node left, right; }; // The function returns size // of the minimum vertex cover static int vCover(node root) { // The size of minimum vertex cover // is zero if tree is empty or there // is only one node if (root == null) return 0; if (root.left == null && root.right == null) return 0; // Calculate size of vertex cover // when root is part of it int size_incl = 1 + vCover(root.left) + vCover(root.right); // Calculate size of vertex cover // when root is not part of it int size_excl = 0; if (root.left != null) size_excl += 1 + vCover(root.left.left) + vCover(root.left.right); if (root.right != null) size_excl += 1 + vCover(root.right.left) + vCover(root.right.right); // Return the minimum of two sizes return Math.Min(size_incl, size_excl); } // A utility function to create a node static node newNode(int data) { node temp = new node(); temp.data = data; temp.left = temp.right = null; return temp; } // Driver code public static void Main(String[] args) { // Let us construct tree given // in the above diagram node root = newNode(20); root.left = newNode(8); root.left.left = newNode(4); root.left.right = newNode(12); root.left.right.left = newNode(10); root.left.right.right = newNode(14); root.right = newNode(22); root.right.right = newNode(25); Console.Write("Size of the smallest vertex" + "cover is {0} ", vCover(root)); }} // This code is contributed by 29AjayKumar <script>// A naive recursive Javascript implementation// for vertex cover problem for a tree // A utility function to find min of two integers function min(x,y) { return (x < y) ? x : y; } /* * A binary tree node has data, pointer to left child and a pointer to right * child */ class Node { constructor(d) { this.data=d; this.left=null; this.right=null; } } // The function returns size // of the minimum vertex cover function vCover(root) { // The size of minimum vertex cover // is zero if tree is empty or there // is only one node if (root == null) return 0; if (root.left == null && root.right == null) return 0; // Calculate size of vertex cover // when root is part of it let size_incl = 1 + vCover(root.left) + vCover(root.right); // Calculate size of vertex cover // when root is not part of it let size_excl = 0; if (root.left != null) size_excl += 1 + vCover(root.left.left) + vCover(root.left.right); if (root.right != null) size_excl += 1 + vCover(root.right.left) + vCover(root.right.right); // Return the minimum of two sizes return Math.min(size_incl, size_excl); } // Driver code // Let us construct tree given in the above diagram root = new Node(20); root.left = new Node(8); root.left.left = new Node(4); root.left.right = new Node(12); root.left.right.left = new Node(10); root.left.right.right = new Node(14); root.right = new Node(22); root.right.right = new Node(25); document.write("Size of the smallest vertex" + "cover is ", vCover(root)); // This code is contributed by unknown2108</script> Output: Size of the smallest vertex cover is 3 Time complexity of the above naive recursive approach is exponential. It should be noted that the above function computes the same subproblems again and again. For example, vCover of node with value 50 is evaluated twice as 50 is grandchild of 10 and child of 20. Since same subproblems are called again, this problem has Overlapping Subproblems property. So Vertex Cover problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, re-computations of same subproblems can be avoided by storing the solutions to subproblems and solving problems in bottom up manner. Following is the implementation of Dynamic Programming based solution. In the following solution, an additional field ‘vc’ is added to tree nodes. The initial value of ‘vc’ is set as 0 for all nodes. The recursive function vCover() calculates ‘vc’ for a node only if it is not already set. C Java C# Javascript /* Dynamic programming based program for Vertex Cover problem for a Binary Tree */#include <stdio.h>#include <stdlib.h> // A utility function to find min of two integersint min(int x, int y) { return (x < y)? x: y; } /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; int vc; struct node *left, *right;}; // A memoization based function that returns size of the minimum vertex cover.int vCover(struct node *root){ // The size of minimum vertex cover is zero if tree is empty or there // is only one node if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 0; // If vertex cover for this node is already evaluated, then return it // to save recomputation of same subproblem again. if (root->vc != 0) return root->vc; // Calculate size of vertex cover when root is part of it int size_incl = 1 + vCover(root->left) + vCover(root->right); // Calculate size of vertex cover when root is not part of it int size_excl = 0; if (root->left) size_excl += 1 + vCover(root->left->left) + vCover(root->left->right); if (root->right) size_excl += 1 + vCover(root->right->left) + vCover(root->right->right); // Minimum of two values is vertex cover, store it before returning root->vc = min(size_incl, size_excl); return root->vc;} // A utility function to create a nodestruct node* newNode( int data ){ struct node* temp = (struct node *) malloc( sizeof(struct node) ); temp->data = data; temp->left = temp->right = NULL; temp->vc = 0; // Set the vertex cover as 0 return temp;} // Driver program to test above functionsint main(){ // Let us construct the tree given in the above diagram struct node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); printf ("Size of the smallest vertex cover is %d ", vCover(root)); return 0;} /* Dynamic programming based program forVertex Cover problem for a Binary Tree */ class GFG{ // A utility function to find min of two integers static int min(int x, int y) { return (x < y) ? x : y; } /* * A binary tree node has data, pointer to left child and a pointer to right * child */ static class node { int data; int vc; node left, right; }; // A memoization based function that returns // size of the minimum vertex cover. static int vCover(node root) { // The size of minimum vertex cover is zero // if tree is empty or there is only one node if (root == null) return 0; if (root.left == null && root.right == null) return 0; // If vertex cover for this node is // already evaluated, then return it // to save recomputation of same subproblem again. if (root.vc != 0) return root.vc; // Calculate size of vertex cover // when root is part of it int size_incl = 1 + vCover(root.left) + vCover(root.right); // Calculate size of vertex cover // when root is not part of it int size_excl = 0; if (root.left != null) size_excl += 1 + vCover(root.left.left) + vCover(root.left.right); if (root.right != null) size_excl += 1 + vCover(root.right.left) + vCover(root.right.right); // Minimum of two values is vertex cover, // store it before returning root.vc = Math.min(size_incl, size_excl); return root.vc; } // A utility function to create a node static node newNode(int data) { node temp = new node(); temp.data = data; temp.left = temp.right = null; temp.vc = 0; // Set the vertex cover as 0 return temp; } // Driver code public static void main(String[] args) { // Let us construct tree given in the above diagram node root = newNode(20); root.left = newNode(8); root.left.left = newNode(4); root.left.right = newNode(12); root.left.right.left = newNode(10); root.left.right.right = newNode(14); root.right = newNode(22); root.right.right = newNode(25); System.out.printf("Size of the smallest vertex" + "cover is %d ", vCover(root)); }} // This code is contributed by PrinciRaj1992 /* Dynamic programming based program forVertex Cover problem for a Binary Tree */using System; class GFG{ // A utility function to find // min of two integers static int min(int x, int y) { return (x < y) ? x : y; } /* * A binary tree node has data, pointer to left child and a pointer to right * child */ class node { public int data; public int vc; public node left, right; }; // A memoization based function that returns // size of the minimum vertex cover. static int vCover(node root) { // The size of minimum vertex cover is zero // if tree is empty or there is only one node if (root == null) return 0; if (root.left == null && root.right == null) return 0; // If vertex cover for this node is // already evaluated, then return it // to save recomputation of same subproblem again. if (root.vc != 0) return root.vc; // Calculate size of vertex cover // when root is part of it int size_incl = 1 + vCover(root.left) + vCover(root.right); // Calculate size of vertex cover // when root is not part of it int size_excl = 0; if (root.left != null) size_excl += 1 + vCover(root.left.left) + vCover(root.left.right); if (root.right != null) size_excl += 1 + vCover(root.right.left) + vCover(root.right.right); // Minimum of two values is vertex cover, // store it before returning root.vc = Math.Min(size_incl, size_excl); return root.vc; } // A utility function to create a node static node newNode(int data) { node temp = new node(); temp.data = data; temp.left = temp.right = null; temp.vc = 0; // Set the vertex cover as 0 return temp; } // Driver code public static void Main(String[] args) { // Let us construct tree given in the above diagram node root = newNode(20); root.left = newNode(8); root.left.left = newNode(4); root.left.right = newNode(12); root.left.right.left = newNode(10); root.left.right.right = newNode(14); root.right = newNode(22); root.right.right = newNode(25); Console.Write("Size of the smallest vertex" + "cover is {0} ", vCover(root)); }} // This code is contributed by PrinciRaj1992 <script> /* Dynamic programming based program forVertex Cover problem for a Binary Tree */ // A utility function to find min of two integersfunction min(x,y){ return (x < y) ? x : y;} /* * A binary tree node has data, pointer to left child and a pointer to right * child */class Node{ constructor(data) { this.vc=0; this.data=data; this.left=this.right=null; }} // A memoization based function that returns// size of the minimum vertex cover.function vCover(root){ // The size of minimum vertex cover is zero // if tree is empty or there is only one node if (root == null) return 0; if (root.left == null && root.right == null) return 0; // If vertex cover for this node is // already evaluated, then return it // to save recomputation of same subproblem again. if (root.vc != 0) return root.vc; // Calculate size of vertex cover // when root is part of it let size_incl = 1 + vCover(root.left) + vCover(root.right); // Calculate size of vertex cover // when root is not part of it let size_excl = 0; if (root.left != null) size_excl += 1 + vCover(root.left.left) + vCover(root.left.right); if (root.right != null) size_excl += 1 + vCover(root.right.left) + vCover(root.right.right); // Minimum of two values is vertex cover, // store it before returning root.vc = Math.min(size_incl, size_excl); return root.vc;} // Driver code// Let us construct tree given in the above diagram let root = new Node(20); root.left = new Node(8); root.left.left = new Node(4); root.left.right = new Node(12); root.left.right.left = new Node(10); root.left.right.right = new Node(14); root.right = new Node(22); root.right.right = new Node(25); document.write("Size of the smallest vertex " + "cover is ", vCover(root)); // This code is contributed by rag2127 </script> Output: Size of the smallest vertex cover is 3 References: http://courses.csail.mit.edu/6.006/spring11/lectures/lec21.pdfExercise: Extend the above solution for n-ary trees. This article is contributed by Udit Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Approach for any general tree : 1. Approach will be same dynamic programming approach as discussed. 2. For every node, if we exclude this node from vertex cover than we have to include its neighbouring nodes, and if we include this node in the vertex cover than we will take the minimum of the two possibilities of taking its neighbouring nodes in the vertex cover to get minimum vertex cover. 3. We will store the above information in the dp array. C++ // C++ implementation for the above approach#include <bits/stdc++.h>using namespace std; // An utility function to add an edge in the treevoid addEdge(vector<int> adj[], int x, int y){ adj[x].push_back(y); adj[y].push_back(x);} void dfs(vector<int> adj[], vector<int> dp[], int src, int par){ for (auto child : adj[src]) { if (child != par) dfs(adj, dp, child, src); } for (auto child : adj[src]) { if (child != par) { // not including source in the vertex cover dp[src][0] += dp[child][1]; // including source in the vertex cover dp[src][1] += min(dp[child][1], dp[child][0]); } }} // function to find minimum size of vertex covervoid minSizeVertexCover(vector<int> adj[], int N){ vector<int> dp[N + 1]; for (int i = 1; i <= N; i++) { // 0 denotes not included in vertex cover dp[i].push_back(0); // 1 denotes included in vertex cover dp[i].push_back(1); } dfs(adj, dp, 1, -1); // printing minimum size vertex cover cout << min(dp[1][0], dp[1][1]) << endl;} // Driver Codeint main(){ /* 1 / \ 2 7 / \ 3 6 / | \ 4 8 5 */ // number of nodes in the tree int N = 8; // adjacency list representation of the tree vector<int> adj[N + 1]; addEdge(adj, 1, 2); addEdge(adj, 1, 7); addEdge(adj, 2, 3); addEdge(adj, 2, 6); addEdge(adj, 3, 4); addEdge(adj, 3, 8); addEdge(adj, 3, 5); minSizeVertexCover(adj, N); return 0;} 3 Time Complexity : O(N) Auxiliary space : O(N) princiraj1992 29AjayKumar mohit kumar 29 unknown2108 sweetyty pawanharwani11 rag2127 NPHard Dynamic Programming Dynamic Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n10 Jun, 2021" }, { "code": null, "e": 511, "s": 52, "text": "A vertex cover of an undirected graph is a subset of its vertices such that for every edge (u, v) of the graph, either ‘u’ or ‘v’ is in vertex cover. Although the name is Vertex Cover, the set covers all edges of the given graph. The problem to find minimum size vertex cover of a graph is NP complete. But it can be solved in polynomial time for trees. In this post a solution for Binary Tree is discussed. The same solution can be extended for n-ary trees." }, { "code": null, "e": 638, "s": 511, "text": "For example, consider the following binary tree. The smallest vertex cover is {20, 50, 30} and size of the vertex cover is 3. " }, { "code": null, "e": 933, "s": 638, "text": "The idea is to consider following two possibilities for root and recursively for all nodes down the root. 1) Root is part of vertex cover: In this case root covers all children edges. We recursively calculate size of vertex covers for left and right subtrees and add 1 to the result (for root)." }, { "code": null, "e": 1209, "s": 933, "text": "2) Root is not part of vertex cover: In this case, both children of root must be included in vertex cover to cover all root to children edges. We recursively calculate size of vertex covers of all grandchildren and number of children to the result (for two children of root)." }, { "code": null, "e": 1250, "s": 1209, "text": "Below are implementation of above idea. " }, { "code": null, "e": 1252, "s": 1250, "text": "C" }, { "code": null, "e": 1257, "s": 1252, "text": "Java" }, { "code": null, "e": 1265, "s": 1257, "text": "Python3" }, { "code": null, "e": 1268, "s": 1265, "text": "C#" }, { "code": null, "e": 1279, "s": 1268, "text": "Javascript" }, { "code": "// A naive recursive C implementation for vertex cover problem for a tree#include <stdio.h>#include <stdlib.h> // A utility function to find min of two integersint min(int x, int y) { return (x < y)? x: y; } /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; struct node *left, *right;}; // The function returns size of the minimum vertex coverint vCover(struct node *root){ // The size of minimum vertex cover is zero if tree is empty or there // is only one node if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 0; // Calculate size of vertex cover when root is part of it int size_incl = 1 + vCover(root->left) + vCover(root->right); // Calculate size of vertex cover when root is not part of it int size_excl = 0; if (root->left) size_excl += 1 + vCover(root->left->left) + vCover(root->left->right); if (root->right) size_excl += 1 + vCover(root->right->left) + vCover(root->right->right); // Return the minimum of two sizes return min(size_incl, size_excl);} // A utility function to create a nodestruct node* newNode( int data ){ struct node* temp = (struct node *) malloc( sizeof(struct node) ); temp->data = data; temp->left = temp->right = NULL; return temp;} // Driver program to test above functionsint main(){ // Let us construct the tree given in the above diagram struct node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); printf (\"Size of the smallest vertex cover is %d \", vCover(root)); return 0;}", "e": 3170, "s": 1279, "text": null }, { "code": "// A naive recursive Java implementation// for vertex cover problem for a tree class GFG{ // A utility function to find min of two integers static int min(int x, int y) { return (x < y) ? x : y; } /* * A binary tree node has data, pointer to left child and a pointer to right * child */ static class node { int data; node left, right; }; // The function returns size // of the minimum vertex cover static int vCover(node root) { // The size of minimum vertex cover // is zero if tree is empty or there // is only one node if (root == null) return 0; if (root.left == null && root.right == null) return 0; // Calculate size of vertex cover // when root is part of it int size_incl = 1 + vCover(root.left) + vCover(root.right); // Calculate size of vertex cover // when root is not part of it int size_excl = 0; if (root.left != null) size_excl += 1 + vCover(root.left.left) + vCover(root.left.right); if (root.right != null) size_excl += 1 + vCover(root.right.left) + vCover(root.right.right); // Return the minimum of two sizes return Math.min(size_incl, size_excl); } // A utility function to create a node static node newNode(int data) { node temp = new node(); temp.data = data; temp.left = temp.right = null; return temp; } // Driver code public static void main(String[] args) { // Let us construct tree given in the above diagram node root = newNode(20); root.left = newNode(8); root.left.left = newNode(4); root.left.right = newNode(12); root.left.right.left = newNode(10); root.left.right.right = newNode(14); root.right = newNode(22); root.right.right = newNode(25); System.out.printf(\"Size of the smallest vertex\" + \"cover is %d \", vCover(root)); }} // This code is contributed by 29AjayKumar", "e": 5342, "s": 3170, "text": null }, { "code": "# A naive recursive Python3 implementation# for vertex cover problem for a tree # A utility function to find min of two integers # A binary tree node has data, pointer to# left child and a pointer to right childclass Node: def __init__(self, x): self.data = x self.left = None self.right = None # The function returns size of# the minimum vertex coverdef vCover(root): # The size of minimum vertex cover # is zero if tree is empty or there # is only one node if (root == None): return 0 if (root.left == None and root.right == None): return 0 # Calculate size of vertex cover when # root is part of it size_incl = (1 + vCover(root.left) + vCover(root.right)) # Calculate size of vertex cover # when root is not part of it size_excl = 0 if (root.left): size_excl += (1 + vCover(root.left.left) + vCover(root.left.right)) if (root.right): size_excl += (1 + vCover(root.right.left) + vCover(root.right.right)) # Return the minimum of two sizes return min(size_incl, size_excl) # Driver Codeif __name__ == '__main__': # Let us construct the tree # given in the above diagram root = Node(20) root.left = Node(8) root.left.left = Node(4) root.left.right = Node(12) root.left.right.left = Node(10) root.left.right.right = Node(14) root.right = Node(22) root.right.right = Node(25) print(\"Size of the smallest vertex cover is\", vCover(root)) # This code is contributed by mohit kumar 29", "e": 6958, "s": 5342, "text": null }, { "code": "// A naive recursive C# implementation// for vertex cover problem for a treeusing System; class GFG{ // A utility function to find // min of two integers static int min(int x, int y) { return (x < y) ? x : y; } /* * A binary tree node has data, pointer to left child and a pointer to right * child */ public class node { public int data; public node left, right; }; // The function returns size // of the minimum vertex cover static int vCover(node root) { // The size of minimum vertex cover // is zero if tree is empty or there // is only one node if (root == null) return 0; if (root.left == null && root.right == null) return 0; // Calculate size of vertex cover // when root is part of it int size_incl = 1 + vCover(root.left) + vCover(root.right); // Calculate size of vertex cover // when root is not part of it int size_excl = 0; if (root.left != null) size_excl += 1 + vCover(root.left.left) + vCover(root.left.right); if (root.right != null) size_excl += 1 + vCover(root.right.left) + vCover(root.right.right); // Return the minimum of two sizes return Math.Min(size_incl, size_excl); } // A utility function to create a node static node newNode(int data) { node temp = new node(); temp.data = data; temp.left = temp.right = null; return temp; } // Driver code public static void Main(String[] args) { // Let us construct tree given // in the above diagram node root = newNode(20); root.left = newNode(8); root.left.left = newNode(4); root.left.right = newNode(12); root.left.right.left = newNode(10); root.left.right.right = newNode(14); root.right = newNode(22); root.right.right = newNode(25); Console.Write(\"Size of the smallest vertex\" + \"cover is {0} \", vCover(root)); }} // This code is contributed by 29AjayKumar", "e": 9165, "s": 6958, "text": null }, { "code": "<script>// A naive recursive Javascript implementation// for vertex cover problem for a tree // A utility function to find min of two integers function min(x,y) { return (x < y) ? x : y; } /* * A binary tree node has data, pointer to left child and a pointer to right * child */ class Node { constructor(d) { this.data=d; this.left=null; this.right=null; } } // The function returns size // of the minimum vertex cover function vCover(root) { // The size of minimum vertex cover // is zero if tree is empty or there // is only one node if (root == null) return 0; if (root.left == null && root.right == null) return 0; // Calculate size of vertex cover // when root is part of it let size_incl = 1 + vCover(root.left) + vCover(root.right); // Calculate size of vertex cover // when root is not part of it let size_excl = 0; if (root.left != null) size_excl += 1 + vCover(root.left.left) + vCover(root.left.right); if (root.right != null) size_excl += 1 + vCover(root.right.left) + vCover(root.right.right); // Return the minimum of two sizes return Math.min(size_incl, size_excl); } // Driver code // Let us construct tree given in the above diagram root = new Node(20); root.left = new Node(8); root.left.left = new Node(4); root.left.right = new Node(12); root.left.right.left = new Node(10); root.left.right.right = new Node(14); root.right = new Node(22); root.right.right = new Node(25); document.write(\"Size of the smallest vertex\" + \"cover is \", vCover(root)); // This code is contributed by unknown2108</script>", "e": 11139, "s": 9165, "text": null }, { "code": null, "e": 11148, "s": 11139, "text": "Output: " }, { "code": null, "e": 11187, "s": 11148, "text": "Size of the smallest vertex cover is 3" }, { "code": null, "e": 11451, "s": 11187, "text": "Time complexity of the above naive recursive approach is exponential. It should be noted that the above function computes the same subproblems again and again. For example, vCover of node with value 50 is evaluated twice as 50 is grandchild of 10 and child of 20." }, { "code": null, "e": 11827, "s": 11451, "text": "Since same subproblems are called again, this problem has Overlapping Subproblems property. So Vertex Cover problem has both properties (see this and this) of a dynamic programming problem. Like other typical Dynamic Programming(DP) problems, re-computations of same subproblems can be avoided by storing the solutions to subproblems and solving problems in bottom up manner." }, { "code": null, "e": 12117, "s": 11827, "text": "Following is the implementation of Dynamic Programming based solution. In the following solution, an additional field ‘vc’ is added to tree nodes. The initial value of ‘vc’ is set as 0 for all nodes. The recursive function vCover() calculates ‘vc’ for a node only if it is not already set." }, { "code": null, "e": 12119, "s": 12117, "text": "C" }, { "code": null, "e": 12124, "s": 12119, "text": "Java" }, { "code": null, "e": 12127, "s": 12124, "text": "C#" }, { "code": null, "e": 12138, "s": 12127, "text": "Javascript" }, { "code": "/* Dynamic programming based program for Vertex Cover problem for a Binary Tree */#include <stdio.h>#include <stdlib.h> // A utility function to find min of two integersint min(int x, int y) { return (x < y)? x: y; } /* A binary tree node has data, pointer to left child and a pointer to right child */struct node{ int data; int vc; struct node *left, *right;}; // A memoization based function that returns size of the minimum vertex cover.int vCover(struct node *root){ // The size of minimum vertex cover is zero if tree is empty or there // is only one node if (root == NULL) return 0; if (root->left == NULL && root->right == NULL) return 0; // If vertex cover for this node is already evaluated, then return it // to save recomputation of same subproblem again. if (root->vc != 0) return root->vc; // Calculate size of vertex cover when root is part of it int size_incl = 1 + vCover(root->left) + vCover(root->right); // Calculate size of vertex cover when root is not part of it int size_excl = 0; if (root->left) size_excl += 1 + vCover(root->left->left) + vCover(root->left->right); if (root->right) size_excl += 1 + vCover(root->right->left) + vCover(root->right->right); // Minimum of two values is vertex cover, store it before returning root->vc = min(size_incl, size_excl); return root->vc;} // A utility function to create a nodestruct node* newNode( int data ){ struct node* temp = (struct node *) malloc( sizeof(struct node) ); temp->data = data; temp->left = temp->right = NULL; temp->vc = 0; // Set the vertex cover as 0 return temp;} // Driver program to test above functionsint main(){ // Let us construct the tree given in the above diagram struct node *root = newNode(20); root->left = newNode(8); root->left->left = newNode(4); root->left->right = newNode(12); root->left->right->left = newNode(10); root->left->right->right = newNode(14); root->right = newNode(22); root->right->right = newNode(25); printf (\"Size of the smallest vertex cover is %d \", vCover(root)); return 0;}", "e": 14352, "s": 12138, "text": null }, { "code": "/* Dynamic programming based program forVertex Cover problem for a Binary Tree */ class GFG{ // A utility function to find min of two integers static int min(int x, int y) { return (x < y) ? x : y; } /* * A binary tree node has data, pointer to left child and a pointer to right * child */ static class node { int data; int vc; node left, right; }; // A memoization based function that returns // size of the minimum vertex cover. static int vCover(node root) { // The size of minimum vertex cover is zero // if tree is empty or there is only one node if (root == null) return 0; if (root.left == null && root.right == null) return 0; // If vertex cover for this node is // already evaluated, then return it // to save recomputation of same subproblem again. if (root.vc != 0) return root.vc; // Calculate size of vertex cover // when root is part of it int size_incl = 1 + vCover(root.left) + vCover(root.right); // Calculate size of vertex cover // when root is not part of it int size_excl = 0; if (root.left != null) size_excl += 1 + vCover(root.left.left) + vCover(root.left.right); if (root.right != null) size_excl += 1 + vCover(root.right.left) + vCover(root.right.right); // Minimum of two values is vertex cover, // store it before returning root.vc = Math.min(size_incl, size_excl); return root.vc; } // A utility function to create a node static node newNode(int data) { node temp = new node(); temp.data = data; temp.left = temp.right = null; temp.vc = 0; // Set the vertex cover as 0 return temp; } // Driver code public static void main(String[] args) { // Let us construct tree given in the above diagram node root = newNode(20); root.left = newNode(8); root.left.left = newNode(4); root.left.right = newNode(12); root.left.right.left = newNode(10); root.left.right.right = newNode(14); root.right = newNode(22); root.right.right = newNode(25); System.out.printf(\"Size of the smallest vertex\" + \"cover is %d \", vCover(root)); }} // This code is contributed by PrinciRaj1992", "e": 16872, "s": 14352, "text": null }, { "code": "/* Dynamic programming based program forVertex Cover problem for a Binary Tree */using System; class GFG{ // A utility function to find // min of two integers static int min(int x, int y) { return (x < y) ? x : y; } /* * A binary tree node has data, pointer to left child and a pointer to right * child */ class node { public int data; public int vc; public node left, right; }; // A memoization based function that returns // size of the minimum vertex cover. static int vCover(node root) { // The size of minimum vertex cover is zero // if tree is empty or there is only one node if (root == null) return 0; if (root.left == null && root.right == null) return 0; // If vertex cover for this node is // already evaluated, then return it // to save recomputation of same subproblem again. if (root.vc != 0) return root.vc; // Calculate size of vertex cover // when root is part of it int size_incl = 1 + vCover(root.left) + vCover(root.right); // Calculate size of vertex cover // when root is not part of it int size_excl = 0; if (root.left != null) size_excl += 1 + vCover(root.left.left) + vCover(root.left.right); if (root.right != null) size_excl += 1 + vCover(root.right.left) + vCover(root.right.right); // Minimum of two values is vertex cover, // store it before returning root.vc = Math.Min(size_incl, size_excl); return root.vc; } // A utility function to create a node static node newNode(int data) { node temp = new node(); temp.data = data; temp.left = temp.right = null; temp.vc = 0; // Set the vertex cover as 0 return temp; } // Driver code public static void Main(String[] args) { // Let us construct tree given in the above diagram node root = newNode(20); root.left = newNode(8); root.left.left = newNode(4); root.left.right = newNode(12); root.left.right.left = newNode(10); root.left.right.right = newNode(14); root.right = newNode(22); root.right.right = newNode(25); Console.Write(\"Size of the smallest vertex\" + \"cover is {0} \", vCover(root)); }} // This code is contributed by PrinciRaj1992", "e": 19420, "s": 16872, "text": null }, { "code": "<script> /* Dynamic programming based program forVertex Cover problem for a Binary Tree */ // A utility function to find min of two integersfunction min(x,y){ return (x < y) ? x : y;} /* * A binary tree node has data, pointer to left child and a pointer to right * child */class Node{ constructor(data) { this.vc=0; this.data=data; this.left=this.right=null; }} // A memoization based function that returns// size of the minimum vertex cover.function vCover(root){ // The size of minimum vertex cover is zero // if tree is empty or there is only one node if (root == null) return 0; if (root.left == null && root.right == null) return 0; // If vertex cover for this node is // already evaluated, then return it // to save recomputation of same subproblem again. if (root.vc != 0) return root.vc; // Calculate size of vertex cover // when root is part of it let size_incl = 1 + vCover(root.left) + vCover(root.right); // Calculate size of vertex cover // when root is not part of it let size_excl = 0; if (root.left != null) size_excl += 1 + vCover(root.left.left) + vCover(root.left.right); if (root.right != null) size_excl += 1 + vCover(root.right.left) + vCover(root.right.right); // Minimum of two values is vertex cover, // store it before returning root.vc = Math.min(size_incl, size_excl); return root.vc;} // Driver code// Let us construct tree given in the above diagram let root = new Node(20); root.left = new Node(8); root.left.left = new Node(4); root.left.right = new Node(12); root.left.right.left = new Node(10); root.left.right.right = new Node(14); root.right = new Node(22); root.right.right = new Node(25); document.write(\"Size of the smallest vertex \" + \"cover is \", vCover(root)); // This code is contributed by rag2127 </script>", "e": 21602, "s": 19420, "text": null }, { "code": null, "e": 21611, "s": 21602, "text": "Output: " }, { "code": null, "e": 21650, "s": 21611, "text": "Size of the smallest vertex cover is 3" }, { "code": null, "e": 21945, "s": 21650, "text": "References: http://courses.csail.mit.edu/6.006/spring11/lectures/lec21.pdfExercise: Extend the above solution for n-ary trees. This article is contributed by Udit Gupta. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 21977, "s": 21945, "text": "Approach for any general tree :" }, { "code": null, "e": 22045, "s": 21977, "text": "1. Approach will be same dynamic programming approach as discussed." }, { "code": null, "e": 22154, "s": 22045, "text": "2. For every node, if we exclude this node from vertex cover than we have to include its neighbouring nodes," }, { "code": null, "e": 22287, "s": 22154, "text": " and if we include this node in the vertex cover than we will take the minimum of the two possibilities of taking its neighbouring" }, { "code": null, "e": 22346, "s": 22287, "text": " nodes in the vertex cover to get minimum vertex cover. " }, { "code": null, "e": 22402, "s": 22346, "text": "3. We will store the above information in the dp array." }, { "code": null, "e": 22406, "s": 22402, "text": "C++" }, { "code": "// C++ implementation for the above approach#include <bits/stdc++.h>using namespace std; // An utility function to add an edge in the treevoid addEdge(vector<int> adj[], int x, int y){ adj[x].push_back(y); adj[y].push_back(x);} void dfs(vector<int> adj[], vector<int> dp[], int src, int par){ for (auto child : adj[src]) { if (child != par) dfs(adj, dp, child, src); } for (auto child : adj[src]) { if (child != par) { // not including source in the vertex cover dp[src][0] += dp[child][1]; // including source in the vertex cover dp[src][1] += min(dp[child][1], dp[child][0]); } }} // function to find minimum size of vertex covervoid minSizeVertexCover(vector<int> adj[], int N){ vector<int> dp[N + 1]; for (int i = 1; i <= N; i++) { // 0 denotes not included in vertex cover dp[i].push_back(0); // 1 denotes included in vertex cover dp[i].push_back(1); } dfs(adj, dp, 1, -1); // printing minimum size vertex cover cout << min(dp[1][0], dp[1][1]) << endl;} // Driver Codeint main(){ /* 1 / \\ 2 7 / \\ 3 6 / | \\ 4 8 5 */ // number of nodes in the tree int N = 8; // adjacency list representation of the tree vector<int> adj[N + 1]; addEdge(adj, 1, 2); addEdge(adj, 1, 7); addEdge(adj, 2, 3); addEdge(adj, 2, 6); addEdge(adj, 3, 4); addEdge(adj, 3, 8); addEdge(adj, 3, 5); minSizeVertexCover(adj, N); return 0;}", "e": 24124, "s": 22406, "text": null }, { "code": null, "e": 24126, "s": 24124, "text": "3" }, { "code": null, "e": 24149, "s": 24126, "text": "Time Complexity : O(N)" }, { "code": null, "e": 24172, "s": 24149, "text": "Auxiliary space : O(N)" }, { "code": null, "e": 24186, "s": 24172, "text": "princiraj1992" }, { "code": null, "e": 24198, "s": 24186, "text": "29AjayKumar" }, { "code": null, "e": 24213, "s": 24198, "text": "mohit kumar 29" }, { "code": null, "e": 24225, "s": 24213, "text": "unknown2108" }, { "code": null, "e": 24234, "s": 24225, "text": "sweetyty" }, { "code": null, "e": 24249, "s": 24234, "text": "pawanharwani11" }, { "code": null, "e": 24257, "s": 24249, "text": "rag2127" }, { "code": null, "e": 24264, "s": 24257, "text": "NPHard" }, { "code": null, "e": 24284, "s": 24264, "text": "Dynamic Programming" }, { "code": null, "e": 24304, "s": 24284, "text": "Dynamic Programming" } ]
Flattening JSON objects in Python
29 Dec, 2020 JSON(JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modules, so there is no need to install it externally. A flatten json is nothing but there is no nesting is present and only key-value pairs are present. Example: Unflattened JSON:{‘user’ :{‘Rachel’:{‘UserID’:1717171717,‘Email’: ‘[email protected]’,‘friends’: [‘John’, ‘Jeremy’, ‘Emily’]}}} Flattened JSON:{‘user_Rachel_friends_2’: ‘Emily’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘[email protected]’, ‘user_Rachel_friends_1’: ‘Jeremy’} There are many reasons for the need of flattening JSON, such as for a better and understandable view that is there are only key-value pairs are present without any nesting. It also allows for context-specific security and constraints to be implemented in a readable, but in more verbose way. There are many ways to flatten JSON. There is one recursive way and another by using the json-flatten library. Recursive Approach: Now we can flatten the dictionary array by a recursive approach which is quite easy to understand. The recursive approach is a bit slower than using json-flatten library.Example:# for a array value of a keyunflat_json = {'user' : {'Rachel': {'UserID':1717171717, 'Email': '[email protected]', 'friends': ['John', 'Jeremy', 'Emily'] } } } # Function for flattening # jsondef flatten_json(y): out = {} def flatten(x, name =''): # If the Nested key-value # pair is of dict type if type(x) is dict: for a in x: flatten(x[a], name + a + '_') # If the Nested key-value # pair is of list type elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(y) return out # Driver codeprint(flatten_json(unflat_json))Output :{‘user_Rachel_friends_2’: ‘Emily’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘[email protected]’, ‘user_Rachel_friends_1’: ‘Jeremy’} Example: # for a array value of a keyunflat_json = {'user' : {'Rachel': {'UserID':1717171717, 'Email': '[email protected]', 'friends': ['John', 'Jeremy', 'Emily'] } } } # Function for flattening # jsondef flatten_json(y): out = {} def flatten(x, name =''): # If the Nested key-value # pair is of dict type if type(x) is dict: for a in x: flatten(x[a], name + a + '_') # If the Nested key-value # pair is of list type elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(y) return out # Driver codeprint(flatten_json(unflat_json)) Output : {‘user_Rachel_friends_2’: ‘Emily’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘[email protected]’, ‘user_Rachel_friends_1’: ‘Jeremy’} Using flatten_json library: json-flatten library provides functions for flattening a JSON object to a single key-value pairs, and unflattening that dictionary back to a JSON object.Installing libraryIn order to use the flatten_json library, we need to install this library. flatten_json can be installed by running the following command in the terminal.pip install json-flattenExample:from flatten_json import flatten unflat_json = {'user' : {'Rachel': {'UserID':1717171717, 'Email': '[email protected]', 'friends': ['John', 'Jeremy', 'Emily'] } } } flat_json = flatten(unflat_json) print(flat_json)Output :{‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘[email protected]’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_friends_1’: ‘Jeremy’, ‘user_Rachel_friends_2’: ‘Emily’} Installing library In order to use the flatten_json library, we need to install this library. flatten_json can be installed by running the following command in the terminal. pip install json-flatten Example: from flatten_json import flatten unflat_json = {'user' : {'Rachel': {'UserID':1717171717, 'Email': '[email protected]', 'friends': ['John', 'Jeremy', 'Emily'] } } } flat_json = flatten(unflat_json) print(flat_json) Output : {‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘[email protected]’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_friends_1’: ‘Jeremy’, ‘user_Rachel_friends_2’: ‘Emily’} Python json-programs Python-json 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": 52, "s": 24, "text": "\n29 Dec, 2020" }, { "code": null, "e": 451, "s": 52, "text": "JSON(JavaScript Object Notation) is a data-interchange format that is human-readable text and is used to transmit data, especially between web applications and servers. The JSON files will be like nested dictionaries in Python. To convert a text file into JSON, there is a json module in Python. This module comes in-built with Python standard modules, so there is no need to install it externally." }, { "code": null, "e": 550, "s": 451, "text": "A flatten json is nothing but there is no nesting is present and only key-value pairs are present." }, { "code": null, "e": 559, "s": 550, "text": "Example:" }, { "code": null, "e": 690, "s": 559, "text": "Unflattened JSON:{‘user’ :{‘Rachel’:{‘UserID’:1717171717,‘Email’: ‘[email protected]’,‘friends’: [‘John’, ‘Jeremy’, ‘Emily’]}}}" }, { "code": null, "e": 887, "s": 690, "text": "Flattened JSON:{‘user_Rachel_friends_2’: ‘Emily’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘[email protected]’, ‘user_Rachel_friends_1’: ‘Jeremy’}" }, { "code": null, "e": 1179, "s": 887, "text": "There are many reasons for the need of flattening JSON, such as for a better and understandable view that is there are only key-value pairs are present without any nesting. It also allows for context-specific security and constraints to be implemented in a readable, but in more verbose way." }, { "code": null, "e": 1290, "s": 1179, "text": "There are many ways to flatten JSON. There is one recursive way and another by using the json-flatten library." }, { "code": null, "e": 2605, "s": 1290, "text": "Recursive Approach: Now we can flatten the dictionary array by a recursive approach which is quite easy to understand. The recursive approach is a bit slower than using json-flatten library.Example:# for a array value of a keyunflat_json = {'user' : {'Rachel': {'UserID':1717171717, 'Email': '[email protected]', 'friends': ['John', 'Jeremy', 'Emily'] } } } # Function for flattening # jsondef flatten_json(y): out = {} def flatten(x, name =''): # If the Nested key-value # pair is of dict type if type(x) is dict: for a in x: flatten(x[a], name + a + '_') # If the Nested key-value # pair is of list type elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(y) return out # Driver codeprint(flatten_json(unflat_json))Output :{‘user_Rachel_friends_2’: ‘Emily’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘[email protected]’, ‘user_Rachel_friends_1’: ‘Jeremy’}" }, { "code": null, "e": 2614, "s": 2605, "text": "Example:" }, { "code": "# for a array value of a keyunflat_json = {'user' : {'Rachel': {'UserID':1717171717, 'Email': '[email protected]', 'friends': ['John', 'Jeremy', 'Emily'] } } } # Function for flattening # jsondef flatten_json(y): out = {} def flatten(x, name =''): # If the Nested key-value # pair is of dict type if type(x) is dict: for a in x: flatten(x[a], name + a + '_') # If the Nested key-value # pair is of list type elif type(x) is list: i = 0 for a in x: flatten(a, name + str(i) + '_') i += 1 else: out[name[:-1]] = x flatten(y) return out # Driver codeprint(flatten_json(unflat_json))", "e": 3542, "s": 2614, "text": null }, { "code": null, "e": 3551, "s": 3542, "text": "Output :" }, { "code": null, "e": 3733, "s": 3551, "text": "{‘user_Rachel_friends_2’: ‘Emily’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘[email protected]’, ‘user_Rachel_friends_1’: ‘Jeremy’}" }, { "code": null, "e": 4630, "s": 3733, "text": "Using flatten_json library: json-flatten library provides functions for flattening a JSON object to a single key-value pairs, and unflattening that dictionary back to a JSON object.Installing libraryIn order to use the flatten_json library, we need to install this library. flatten_json can be installed by running the following command in the terminal.pip install json-flattenExample:from flatten_json import flatten unflat_json = {'user' : {'Rachel': {'UserID':1717171717, 'Email': '[email protected]', 'friends': ['John', 'Jeremy', 'Emily'] } } } flat_json = flatten(unflat_json) print(flat_json)Output :{‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘[email protected]’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_friends_1’: ‘Jeremy’, ‘user_Rachel_friends_2’: ‘Emily’}" }, { "code": null, "e": 4649, "s": 4630, "text": "Installing library" }, { "code": null, "e": 4804, "s": 4649, "text": "In order to use the flatten_json library, we need to install this library. flatten_json can be installed by running the following command in the terminal." }, { "code": null, "e": 4829, "s": 4804, "text": "pip install json-flatten" }, { "code": null, "e": 4838, "s": 4829, "text": "Example:" }, { "code": "from flatten_json import flatten unflat_json = {'user' : {'Rachel': {'UserID':1717171717, 'Email': '[email protected]', 'friends': ['John', 'Jeremy', 'Emily'] } } } flat_json = flatten(unflat_json) print(flat_json)", "e": 5161, "s": 4838, "text": null }, { "code": null, "e": 5170, "s": 5161, "text": "Output :" }, { "code": null, "e": 5352, "s": 5170, "text": "{‘user_Rachel_UserID’: 1717171717, ‘user_Rachel_Email’: ‘[email protected]’, ‘user_Rachel_friends_0’: ‘John’, ‘user_Rachel_friends_1’: ‘Jeremy’, ‘user_Rachel_friends_2’: ‘Emily’}" }, { "code": null, "e": 5373, "s": 5352, "text": "Python json-programs" }, { "code": null, "e": 5385, "s": 5373, "text": "Python-json" }, { "code": null, "e": 5392, "s": 5385, "text": "Python" }, { "code": null, "e": 5490, "s": 5392, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5508, "s": 5490, "text": "Python Dictionary" }, { "code": null, "e": 5550, "s": 5508, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5572, "s": 5550, "text": "Enumerate() in Python" }, { "code": null, "e": 5607, "s": 5572, "text": "Read a file line by line in Python" }, { "code": null, "e": 5639, "s": 5607, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 5665, "s": 5639, "text": "Python String | replace()" }, { "code": null, "e": 5694, "s": 5665, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5721, "s": 5694, "text": "Python Classes and Objects" }, { "code": null, "e": 5742, "s": 5721, "text": "Python OOPs Concepts" } ]
Moment.js isAfter() Function
29 Jul, 2020 You can check whether a date is after a particular date in Moment.js using the isAfter() function that checks if a moment is after another moment. The first argument will be parsed as a moment, if not already so. Syntax: moment().isAfter(Moment|String|Number|Date|Array); moment().isAfter(Moment|String|Number|Date|Array, String); Parameter: It can be either Moment|String|Number|Date|Array. Returns: True or False Installation of moment module: You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter 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 moment module. You can install this package by using this command.npm install moment npm install moment After installing the moment module, you can check your moment version in command prompt using the command.npm version moment npm version moment 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 // Requiring moduleconst moment = require('moment'); var bool1 = moment('2010-10-20') .isAfter('2010-10-21'); //falseconsole.log(bool1); var bool2 = moment('2019-10-20') .isAfter('2010-12-31', 'year'); //trueconsole.log(bool2); Steps to run the program: The project structure will look like this:Make sure you have installed moment module using the following command:npm install momentRun index.js file using below command:node index.jsOutput:false true The project structure will look like this: Make sure you have installed moment module using the following command:npm install moment npm install moment Run index.js file using below command:node index.jsOutput:false true node index.js Output: false true Example 2: Filename: index.js // Requiring moduleconst moment = require('moment'); function checkIsAfter(date1, date2) { return moment(date1).isAfter(date2);} var bool = checkIsAfter('2010-10-20', '2010-10-21'); console.log(bool); Run index.js file using below command: node index.js Output: false Reference: https://momentjs.com/docs/#/query/is-after/ Moment.js Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Jul, 2020" }, { "code": null, "e": 241, "s": 28, "text": "You can check whether a date is after a particular date in Moment.js using the isAfter() function that checks if a moment is after another moment. The first argument will be parsed as a moment, if not already so." }, { "code": null, "e": 249, "s": 241, "text": "Syntax:" }, { "code": null, "e": 360, "s": 249, "text": "moment().isAfter(Moment|String|Number|Date|Array);\nmoment().isAfter(Moment|String|Number|Date|Array, String);\n" }, { "code": null, "e": 421, "s": 360, "text": "Parameter: It can be either Moment|String|Number|Date|Array." }, { "code": null, "e": 444, "s": 421, "text": "Returns: True or False" }, { "code": null, "e": 475, "s": 444, "text": "Installation of moment module:" }, { "code": null, "e": 865, "s": 475, "text": "You can visit the link to Install moment module. You can install this package by using this command.npm install momentAfter installing the moment module, you can check your moment version in command prompt using the command.npm version momentAfter 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": 984, "s": 865, "text": "You can visit the link to Install moment module. You can install this package by using this command.npm install moment" }, { "code": null, "e": 1003, "s": 984, "text": "npm install moment" }, { "code": null, "e": 1128, "s": 1003, "text": "After installing the moment module, you can check your moment version in command prompt using the command.npm version moment" }, { "code": null, "e": 1147, "s": 1128, "text": "npm version moment" }, { "code": null, "e": 1295, "s": 1147, "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": 1309, "s": 1295, "text": "node index.js" }, { "code": null, "e": 1339, "s": 1309, "text": "Example 1: Filename: index.js" }, { "code": "// Requiring moduleconst moment = require('moment'); var bool1 = moment('2010-10-20') .isAfter('2010-10-21'); //falseconsole.log(bool1); var bool2 = moment('2019-10-20') .isAfter('2010-12-31', 'year'); //trueconsole.log(bool2);", "e": 1575, "s": 1339, "text": null }, { "code": null, "e": 1601, "s": 1575, "text": "Steps to run the program:" }, { "code": null, "e": 1802, "s": 1601, "text": "The project structure will look like this:Make sure you have installed moment module using the following command:npm install momentRun index.js file using below command:node index.jsOutput:false\ntrue\n" }, { "code": null, "e": 1845, "s": 1802, "text": "The project structure will look like this:" }, { "code": null, "e": 1935, "s": 1845, "text": "Make sure you have installed moment module using the following command:npm install moment" }, { "code": null, "e": 1954, "s": 1935, "text": "npm install moment" }, { "code": null, "e": 2024, "s": 1954, "text": "Run index.js file using below command:node index.jsOutput:false\ntrue\n" }, { "code": null, "e": 2038, "s": 2024, "text": "node index.js" }, { "code": null, "e": 2046, "s": 2038, "text": "Output:" }, { "code": null, "e": 2058, "s": 2046, "text": "false\ntrue\n" }, { "code": null, "e": 2088, "s": 2058, "text": "Example 2: Filename: index.js" }, { "code": "// Requiring moduleconst moment = require('moment'); function checkIsAfter(date1, date2) { return moment(date1).isAfter(date2);} var bool = checkIsAfter('2010-10-20', '2010-10-21'); console.log(bool);", "e": 2294, "s": 2088, "text": null }, { "code": null, "e": 2333, "s": 2294, "text": "Run index.js file using below command:" }, { "code": null, "e": 2347, "s": 2333, "text": "node index.js" }, { "code": null, "e": 2355, "s": 2347, "text": "Output:" }, { "code": null, "e": 2362, "s": 2355, "text": "false\n" }, { "code": null, "e": 2417, "s": 2362, "text": "Reference: https://momentjs.com/docs/#/query/is-after/" }, { "code": null, "e": 2427, "s": 2417, "text": "Moment.js" }, { "code": null, "e": 2435, "s": 2427, "text": "Node.js" }, { "code": null, "e": 2452, "s": 2435, "text": "Web Technologies" } ]
Sum of array elements which are multiples of a given number
04 May, 2021 Given an array arr[] consisting of positive integers and an integer N, the task is to find the sum of all array elements which are multiples of N Examples: Input: arr[] = {1, 2, 3, 5, 6}, N = 3Output: 9Explanation: From the given array, 3 and 6 are multiples of 3. Therefore, sum = 3 + 6 = 9. Input: arr[] = {1, 2, 3, 5, 7, 11, 13}, N = 5Output: 5 Approach: The idea is to traverse the array and for each array element, check if it is a multiple of N or not and add those elements. Follow the steps below to solve the problem: Initialize a variable, say sum, to store the required sum.Traverse the given array and for each array element, perform the following operations.Check whether the array element is a multiple of N or not.If the element is a multiple of N, then add the element to sum.Finally, print the value of sum. Initialize a variable, say sum, to store the required sum. Traverse the given array and for each array element, perform the following operations. Check whether the array element is a multiple of N or not. If the element is a multiple of N, then add the element to sum. Finally, print the value of sum. Below is the implementation of the above approach: C++ Java Python C# Javascript // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the sum of array// elements which are multiples of Nvoid mulsum(int arr[], int n, int N){ // Stores the sum int sum = 0; // Traverse the given array for (int i = 0; i < n; i++) { // If current element // is a multiple of N if (arr[i] % N == 0) { sum = sum + arr[i]; } } // Print total sum cout << sum;} // Driver Codeint main(){ // Given arr[] int arr[] = { 1, 2, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int N = 3; mulsum(arr, n, N); return 0;} // Java program for the above approachimport java.io.*;import java.util.*;class GFG{ // Function to find the sum of array// elements which are multiples of Nstatic void mulsum(int arr[], int n, int N){ // Stores the sum int sum = 0; // Traverse the given array for (int i = 0; i < n; i++) { // If current element // is a multiple of N if (arr[i] % N == 0) { sum = sum + arr[i]; } } // Print total sum System.out.println(sum);} // Driver Codepublic static void main(String[] args){ // Given arr[] int arr[] = { 1, 2, 3, 5, 6 }; int n = arr.length; int N = 3; mulsum(arr, n, N);}} // This code is contributed by jana_sayantan. # Python3 program for the above approach # Function to find the sum of array# elements which are multiples of Ndef mulsum(arr, n, N): # Stores the sum sums = 0 # Traverse the array for i in range(0, n): if arr[i] % N == 0: sums = sums + arr[i] # Print total sum print(sums) # Driver Codeif __name__ == "__main__": # Given arr[] arr = [ 1, 2, 3, 5, 6 ] n = len(arr) N = 3 # Function call mulsum(arr, n, N) // C# program for the above approachusing System;public class GFG{ // Function to find the sum of array// elements which are multiples of Nstatic void mulsum(int[] arr, int n, int N){ // Stores the sum int sum = 0; // Traverse the given array for (int i = 0; i < n; i++) { // If current element // is a multiple of N if (arr[i] % N == 0) { sum = sum + arr[i]; } } // Print total sum Console.Write(sum);} // Driver Codestatic public void Main (){ // Given arr[] int[] arr = { 1, 2, 3, 5, 6 }; int n = arr.Length; int N = 3; mulsum(arr, n, N);}} // This code is contributed by Dharanendra L V. <script> // JavaScript program for the above approach // Function to find the sum of array// elements which are multiples of Nfunction mulsum(arr, n, N){ // Stores the sum var sum = 0; // Traverse the given array for(var i = 0; i < n; i++) { // If current element // is a multiple of N if (arr[i] % N == 0) { sum = sum + arr[i]; } } // Print total sum document.write(sum);} // Driver Code // Given arr[]var arr = [ 1, 2, 3, 5, 6 ];var n = arr.length;var N = 3; mulsum(arr, n, N); // This code is contributed by rdtank </script> 9 Time Complexity: O(N)Auxiliary Space: O(1) jana_sayantan dharanendralv23 rdtank divisibility Technical Scripter 2020 Arrays Mathematical Searching Technical Scripter Arrays Searching Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n04 May, 2021" }, { "code": null, "e": 199, "s": 53, "text": "Given an array arr[] consisting of positive integers and an integer N, the task is to find the sum of all array elements which are multiples of N" }, { "code": null, "e": 209, "s": 199, "text": "Examples:" }, { "code": null, "e": 346, "s": 209, "text": "Input: arr[] = {1, 2, 3, 5, 6}, N = 3Output: 9Explanation: From the given array, 3 and 6 are multiples of 3. Therefore, sum = 3 + 6 = 9." }, { "code": null, "e": 401, "s": 346, "text": "Input: arr[] = {1, 2, 3, 5, 7, 11, 13}, N = 5Output: 5" }, { "code": null, "e": 580, "s": 401, "text": "Approach: The idea is to traverse the array and for each array element, check if it is a multiple of N or not and add those elements. Follow the steps below to solve the problem:" }, { "code": null, "e": 878, "s": 580, "text": "Initialize a variable, say sum, to store the required sum.Traverse the given array and for each array element, perform the following operations.Check whether the array element is a multiple of N or not.If the element is a multiple of N, then add the element to sum.Finally, print the value of sum." }, { "code": null, "e": 937, "s": 878, "text": "Initialize a variable, say sum, to store the required sum." }, { "code": null, "e": 1024, "s": 937, "text": "Traverse the given array and for each array element, perform the following operations." }, { "code": null, "e": 1083, "s": 1024, "text": "Check whether the array element is a multiple of N or not." }, { "code": null, "e": 1147, "s": 1083, "text": "If the element is a multiple of N, then add the element to sum." }, { "code": null, "e": 1180, "s": 1147, "text": "Finally, print the value of sum." }, { "code": null, "e": 1231, "s": 1180, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1235, "s": 1231, "text": "C++" }, { "code": null, "e": 1240, "s": 1235, "text": "Java" }, { "code": null, "e": 1247, "s": 1240, "text": "Python" }, { "code": null, "e": 1250, "s": 1247, "text": "C#" }, { "code": null, "e": 1261, "s": 1250, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find the sum of array// elements which are multiples of Nvoid mulsum(int arr[], int n, int N){ // Stores the sum int sum = 0; // Traverse the given array for (int i = 0; i < n; i++) { // If current element // is a multiple of N if (arr[i] % N == 0) { sum = sum + arr[i]; } } // Print total sum cout << sum;} // Driver Codeint main(){ // Given arr[] int arr[] = { 1, 2, 3, 5, 6 }; int n = sizeof(arr) / sizeof(arr[0]); int N = 3; mulsum(arr, n, N); return 0;}", "e": 1904, "s": 1261, "text": null }, { "code": "// Java program for the above approachimport java.io.*;import java.util.*;class GFG{ // Function to find the sum of array// elements which are multiples of Nstatic void mulsum(int arr[], int n, int N){ // Stores the sum int sum = 0; // Traverse the given array for (int i = 0; i < n; i++) { // If current element // is a multiple of N if (arr[i] % N == 0) { sum = sum + arr[i]; } } // Print total sum System.out.println(sum);} // Driver Codepublic static void main(String[] args){ // Given arr[] int arr[] = { 1, 2, 3, 5, 6 }; int n = arr.length; int N = 3; mulsum(arr, n, N);}} // This code is contributed by jana_sayantan.", "e": 2624, "s": 1904, "text": null }, { "code": "# Python3 program for the above approach # Function to find the sum of array# elements which are multiples of Ndef mulsum(arr, n, N): # Stores the sum sums = 0 # Traverse the array for i in range(0, n): if arr[i] % N == 0: sums = sums + arr[i] # Print total sum print(sums) # Driver Codeif __name__ == \"__main__\": # Given arr[] arr = [ 1, 2, 3, 5, 6 ] n = len(arr) N = 3 # Function call mulsum(arr, n, N)", "e": 3108, "s": 2624, "text": null }, { "code": "// C# program for the above approachusing System;public class GFG{ // Function to find the sum of array// elements which are multiples of Nstatic void mulsum(int[] arr, int n, int N){ // Stores the sum int sum = 0; // Traverse the given array for (int i = 0; i < n; i++) { // If current element // is a multiple of N if (arr[i] % N == 0) { sum = sum + arr[i]; } } // Print total sum Console.Write(sum);} // Driver Codestatic public void Main (){ // Given arr[] int[] arr = { 1, 2, 3, 5, 6 }; int n = arr.Length; int N = 3; mulsum(arr, n, N);}} // This code is contributed by Dharanendra L V.", "e": 3789, "s": 3108, "text": null }, { "code": "<script> // JavaScript program for the above approach // Function to find the sum of array// elements which are multiples of Nfunction mulsum(arr, n, N){ // Stores the sum var sum = 0; // Traverse the given array for(var i = 0; i < n; i++) { // If current element // is a multiple of N if (arr[i] % N == 0) { sum = sum + arr[i]; } } // Print total sum document.write(sum);} // Driver Code // Given arr[]var arr = [ 1, 2, 3, 5, 6 ];var n = arr.length;var N = 3; mulsum(arr, n, N); // This code is contributed by rdtank </script>", "e": 4411, "s": 3789, "text": null }, { "code": null, "e": 4413, "s": 4411, "text": "9" }, { "code": null, "e": 4458, "s": 4415, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 4472, "s": 4458, "text": "jana_sayantan" }, { "code": null, "e": 4488, "s": 4472, "text": "dharanendralv23" }, { "code": null, "e": 4495, "s": 4488, "text": "rdtank" }, { "code": null, "e": 4508, "s": 4495, "text": "divisibility" }, { "code": null, "e": 4532, "s": 4508, "text": "Technical Scripter 2020" }, { "code": null, "e": 4539, "s": 4532, "text": "Arrays" }, { "code": null, "e": 4552, "s": 4539, "text": "Mathematical" }, { "code": null, "e": 4562, "s": 4552, "text": "Searching" }, { "code": null, "e": 4581, "s": 4562, "text": "Technical Scripter" }, { "code": null, "e": 4588, "s": 4581, "text": "Arrays" }, { "code": null, "e": 4598, "s": 4588, "text": "Searching" }, { "code": null, "e": 4611, "s": 4598, "text": "Mathematical" } ]
File flush() method in Python
29 Sep, 2021 Python allows users to manage files by using the concept of file handling. A user can open, read, write, manipulate files and can perform many other file handling operations to a file. One of these file handling operations is the file flush() method in Python. The flush() method in Python file handling clears the internal buffer of the file. In Python, files are automatically flushed while closing them. However, a programmer can flush a file before closing it by using the flush() method. Syntax: fileObject.flush() This method does not require any parameters and it does not return anything.Example 1: Now let us look at the below example which illustrates the use of flush() method. Before going through the program a text file gfg.txt is created having the below content. Python # opening the file in read modefileObject = open("gfg.txt", "r") # clearing the input bufferfileObject.flush() # reading the content of the filefileContent = fileObject.read() # displaying the content of the fileprint(fileContent) # closing the filefileObject.close() Output: Geeks 4 geeks! In the above program, the gfg.txt is opened in read mode then the flush() method only clears the internal buffer of the file, it does not affect the content of the file. So, the contents of the file can be read and displayed.Example 2: Now let us look at another example which demonstrates the use of the flush() method. Python # program to demonstrate the use of flush() # creating a filefileObject = open("gfg.txt", "w+") # writing into the filefileObject.write("Geeks 4 geeks !") # closing the filefileObject.close() # opening the file to read its contentfileObject = open("gfg.txt", "r") # reading the contents before flush()fileContent = fileObject.read() # displaying the contentsprint("\nBefore flush():\n", fileContent) # clearing the input bufferfileObject.flush() # reading the contents after flush()# reads nothing as the internal buffer is clearedfileContent = fileObject.read() # displaying the contentsprint("\nAfter flush():\n", fileContent) # closing the filefileObject.close() Output: Before flush(): Geeks 4 geeks! After flush(): In this program initially, we create gfg.txt file and write Geeks 4 geeks! as content in it and then we close the file. After that we read and display the contents of the file and then the flush() method is called which clears the input buffer of the file so the fileObject reads nothing and fileContent remains an empty variable. Hence nothing is displayed after flush() method. simmytarika5 Picked python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python | os.path.join() method Introduction To PYTHON Python OOPs Concepts How to drop one or multiple columns in Pandas Dataframe How To Convert Python Dictionary To JSON? Check if element exists in list in Python Python | Get unique values from a list Python | datetime.timedelta() function
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Sep, 2021" }, { "code": null, "e": 316, "s": 53, "text": "Python allows users to manage files by using the concept of file handling. A user can open, read, write, manipulate files and can perform many other file handling operations to a file. One of these file handling operations is the file flush() method in Python. " }, { "code": null, "e": 557, "s": 316, "text": "The flush() method in Python file handling clears the internal buffer of the file. In Python, files are automatically flushed while closing them. However, a programmer can flush a file before closing it by using the flush() method. Syntax: " }, { "code": null, "e": 576, "s": 557, "text": "fileObject.flush()" }, { "code": null, "e": 837, "s": 576, "text": "This method does not require any parameters and it does not return anything.Example 1: Now let us look at the below example which illustrates the use of flush() method. Before going through the program a text file gfg.txt is created having the below content. " }, { "code": null, "e": 846, "s": 839, "text": "Python" }, { "code": "# opening the file in read modefileObject = open(\"gfg.txt\", \"r\") # clearing the input bufferfileObject.flush() # reading the content of the filefileContent = fileObject.read() # displaying the content of the fileprint(fileContent) # closing the filefileObject.close()", "e": 1114, "s": 846, "text": null }, { "code": null, "e": 1123, "s": 1114, "text": "Output: " }, { "code": null, "e": 1138, "s": 1123, "text": "Geeks 4 geeks!" }, { "code": null, "e": 1460, "s": 1138, "text": "In the above program, the gfg.txt is opened in read mode then the flush() method only clears the internal buffer of the file, it does not affect the content of the file. So, the contents of the file can be read and displayed.Example 2: Now let us look at another example which demonstrates the use of the flush() method. " }, { "code": null, "e": 1467, "s": 1460, "text": "Python" }, { "code": "# program to demonstrate the use of flush() # creating a filefileObject = open(\"gfg.txt\", \"w+\") # writing into the filefileObject.write(\"Geeks 4 geeks !\") # closing the filefileObject.close() # opening the file to read its contentfileObject = open(\"gfg.txt\", \"r\") # reading the contents before flush()fileContent = fileObject.read() # displaying the contentsprint(\"\\nBefore flush():\\n\", fileContent) # clearing the input bufferfileObject.flush() # reading the contents after flush()# reads nothing as the internal buffer is clearedfileContent = fileObject.read() # displaying the contentsprint(\"\\nAfter flush():\\n\", fileContent) # closing the filefileObject.close()", "e": 2137, "s": 1467, "text": null }, { "code": null, "e": 2146, "s": 2137, "text": "Output: " }, { "code": null, "e": 2193, "s": 2146, "text": "Before flush():\nGeeks 4 geeks!\n\nAfter flush():" }, { "code": null, "e": 2573, "s": 2193, "text": "In this program initially, we create gfg.txt file and write Geeks 4 geeks! as content in it and then we close the file. After that we read and display the contents of the file and then the flush() method is called which clears the input buffer of the file so the fileObject reads nothing and fileContent remains an empty variable. Hence nothing is displayed after flush() method." }, { "code": null, "e": 2586, "s": 2573, "text": "simmytarika5" }, { "code": null, "e": 2593, "s": 2586, "text": "Picked" }, { "code": null, "e": 2614, "s": 2593, "text": "python-file-handling" }, { "code": null, "e": 2621, "s": 2614, "text": "Python" }, { "code": null, "e": 2719, "s": 2621, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2751, "s": 2719, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2778, "s": 2751, "text": "Python Classes and Objects" }, { "code": null, "e": 2809, "s": 2778, "text": "Python | os.path.join() method" }, { "code": null, "e": 2832, "s": 2809, "text": "Introduction To PYTHON" }, { "code": null, "e": 2853, "s": 2832, "text": "Python OOPs Concepts" }, { "code": null, "e": 2909, "s": 2853, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2951, "s": 2909, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2993, "s": 2951, "text": "Check if element exists in list in Python" }, { "code": null, "e": 3032, "s": 2993, "text": "Python | Get unique values from a list" } ]
turtle.getscreen() function in Python
23 Jul, 2020 The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support. This function is used to Return the TurtleScreen object, the turtle is drawing on. It doesn’t require any argument. So TurtleScreen-methods can be called for that object. Syntax : turtle.getscreen() Below is the implementation of the above method with some examples : Example 1 : Python3 # import packageimport turtle # get turtle screen object# and store it sc=turtle.getscreen() # print the turtle screen objectprint(sc) Output : <__main__.Screen object> Example 2 : Python3 # import packageimport turtle # get turtle screen object# and store it sc=turtle.getscreen() # use it for turtle screen methodssc.setup(400,400)sc.bgcolor("blue") Output : Python-turtle Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jul, 2020" }, { "code": null, "e": 245, "s": 28, "text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support." }, { "code": null, "e": 417, "s": 245, "text": "This function is used to Return the TurtleScreen object, the turtle is drawing on. It doesn’t require any argument. So TurtleScreen-methods can be called for that object." }, { "code": null, "e": 426, "s": 417, "text": "Syntax :" }, { "code": null, "e": 445, "s": 426, "text": "turtle.getscreen()" }, { "code": null, "e": 514, "s": 445, "text": "Below is the implementation of the above method with some examples :" }, { "code": null, "e": 526, "s": 514, "text": "Example 1 :" }, { "code": null, "e": 534, "s": 526, "text": "Python3" }, { "code": "# import packageimport turtle # get turtle screen object# and store it sc=turtle.getscreen() # print the turtle screen objectprint(sc)", "e": 673, "s": 534, "text": null }, { "code": null, "e": 682, "s": 673, "text": "Output :" }, { "code": null, "e": 708, "s": 682, "text": "<__main__.Screen object>\n" }, { "code": null, "e": 720, "s": 708, "text": "Example 2 :" }, { "code": null, "e": 728, "s": 720, "text": "Python3" }, { "code": "# import packageimport turtle # get turtle screen object# and store it sc=turtle.getscreen() # use it for turtle screen methodssc.setup(400,400)sc.bgcolor(\"blue\")", "e": 895, "s": 728, "text": null }, { "code": null, "e": 904, "s": 895, "text": "Output :" }, { "code": null, "e": 918, "s": 904, "text": "Python-turtle" }, { "code": null, "e": 925, "s": 918, "text": "Python" } ]
For-each loop in Java - GeeksforGeeks
03 May, 2021 Prerequisite: Decision making in JavaFor-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5. It starts with the keyword for like a normal for-loop. Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name. In the loop body, you can use the loop variable you created rather than using an indexed array element. It’s commonly used to iterate over an array or a Collections class (eg, ArrayList) Syntax: for (type var : array) { statements using var; } is equivalent to: for (int i=0; i<arr.length; i++) { type var = arr[i]; statements using var; } Java // Java program to illustrate// for-each loopclass For_Each { public static void main(String[] arg) { { int[] marks = { 125, 132, 95, 116, 110 }; int highest_marks = maximum(marks); System.out.println("The highest score is " + highest_marks); } } public static int maximum(int[] numbers) { int maxSoFar = numbers[0]; // for each loop for (int num : numbers) { if (num > maxSoFar) { maxSoFar = num; } } return maxSoFar; }} Output: The highest score is 132 Limitations of for-each loop decision-making For-each loops are not appropriate when you want to modify the array: For-each loops are not appropriate when you want to modify the array: for (int num : marks) { // only changes num, not the array element num = num*2; } 2. For-each loops do not keep track of index. So we can not obtain array index using For-Each loop for (int num : numbers) { if (num == target) { return ???; // do not know the index of num } } 3. For-each only iterates forward over the array in single steps // cannot be converted to a for-each loop for (int i=numbers.length-1; i>0; i--) { System.out.println(numbers[i]); } 4. For-each cannot process two decision making statements at once // cannot be easily converted to a for-each loop for (int i=0; i<numbers.length; i++) { if (numbers[i] == arr[i]) { ... } } 5. For-each also has some performance overhead over simple iteration: Java /*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG { public static void main (String[] args) { List<Integer> list = new ArrayList<>(); long startTime; long endTime; for (int i = 0; i < 1000000; i++) { list.add(i); } // Type 1 startTime = Calendar.getInstance().getTimeInMillis(); for (int i : list) { int a = i; } endTime = Calendar.getInstance().getTimeInMillis(); System.out.println("For each loop :: " + (endTime - startTime) + " ms"); // Type 2 startTime = Calendar.getInstance().getTimeInMillis(); for (int j = 0; j < list.size(); j++) { int a = list.get(j); } endTime = Calendar.getInstance().getTimeInMillis(); System.out.println("Using collection.size() :: " + (endTime - startTime) + " ms"); // Type 3 startTime = Calendar.getInstance().getTimeInMillis(); int size = list.size(); for (int j = 0; j < size; j++) { int a = list.get(j); } endTime = Calendar.getInstance().getTimeInMillis(); System.out.println("By calculating collection.size() first :: " + (endTime - startTime) + " ms"); // Type 4 startTime = Calendar.getInstance().getTimeInMillis(); for(int j = list.size()-1; j >= 0; j--) { int a = list.get(j); } endTime = Calendar.getInstance().getTimeInMillis(); System.out.println("Using [int j = list.size(); j > size ; j--] :: " + (endTime - startTime) + " ms"); }} // This code is contributed by Ayush Choudhary @gfg(code_ayush) YouTubeGeeksforGeeks502K subscribersFor each Loop in Java | 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 / 5:52•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=DUVqtwVJ3DI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> ?list=PLqM7alHXFySF5ErEHA1BXgibGg7uqmA4_ Related Articles: For-each in C++ vs Java Iterator vs For-each in JavaThis article is contributed by Abhishek Verma. 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_ayush java-basics Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java Initialize an ArrayList in Java How to iterate any Map in Java Stream In Java Singleton Class in Java Initializing a List in Java Different ways of Reading a text file in Java How to add an element to an Array in Java?
[ { "code": null, "e": 28950, "s": 28922, "text": "\n03 May, 2021" }, { "code": null, "e": 29098, "s": 28950, "text": "Prerequisite: Decision making in JavaFor-each is another array traversing technique like for loop, while loop, do-while loop introduced in Java5. " }, { "code": null, "e": 29153, "s": 29098, "text": "It starts with the keyword for like a normal for-loop." }, { "code": null, "e": 29355, "s": 29153, "text": "Instead of declaring and initializing a loop counter variable, you declare a variable that is the same type as the base type of the array, followed by a colon, which is then followed by the array name." }, { "code": null, "e": 29461, "s": 29355, "text": "In the loop body, you can use the loop variable you created rather than using an indexed array element. " }, { "code": null, "e": 29544, "s": 29461, "text": "It’s commonly used to iterate over an array or a Collections class (eg, ArrayList)" }, { "code": null, "e": 29555, "s": 29546, "text": "Syntax: " }, { "code": null, "e": 29610, "s": 29555, "text": "for (type var : array) \n{ \n statements using var;\n}" }, { "code": null, "e": 29630, "s": 29610, "text": "is equivalent to: " }, { "code": null, "e": 29718, "s": 29630, "text": "for (int i=0; i<arr.length; i++) \n{ \n type var = arr[i];\n statements using var;\n}" }, { "code": null, "e": 29725, "s": 29720, "text": "Java" }, { "code": "// Java program to illustrate// for-each loopclass For_Each { public static void main(String[] arg) { { int[] marks = { 125, 132, 95, 116, 110 }; int highest_marks = maximum(marks); System.out.println(\"The highest score is \" + highest_marks); } } public static int maximum(int[] numbers) { int maxSoFar = numbers[0]; // for each loop for (int num : numbers) { if (num > maxSoFar) { maxSoFar = num; } } return maxSoFar; }}", "e": 30323, "s": 29725, "text": null }, { "code": null, "e": 30333, "s": 30323, "text": "Output: " }, { "code": null, "e": 30358, "s": 30333, "text": "The highest score is 132" }, { "code": null, "e": 30410, "s": 30358, "text": "Limitations of for-each loop decision-making" }, { "code": null, "e": 30481, "s": 30410, "text": "For-each loops are not appropriate when you want to modify the array: " }, { "code": null, "e": 30552, "s": 30481, "text": "For-each loops are not appropriate when you want to modify the array: " }, { "code": null, "e": 30644, "s": 30552, "text": "for (int num : marks) \n{\n // only changes num, not the array element\n num = num*2; \n}" }, { "code": null, "e": 30752, "s": 30644, "text": " 2. For-each loops do not keep track of index. So we can not obtain array index using For-Each loop " }, { "code": null, "e": 30872, "s": 30752, "text": "for (int num : numbers) \n{ \n if (num == target) \n {\n return ???; // do not know the index of num\n }\n}" }, { "code": null, "e": 30948, "s": 30872, "text": " 3. For-each only iterates forward over the array in single steps " }, { "code": null, "e": 31072, "s": 30948, "text": "// cannot be converted to a for-each loop\nfor (int i=numbers.length-1; i>0; i--) \n{\n System.out.println(numbers[i]);\n}" }, { "code": null, "e": 31148, "s": 31072, "text": " 4. For-each cannot process two decision making statements at once " }, { "code": null, "e": 31288, "s": 31148, "text": "// cannot be easily converted to a for-each loop \nfor (int i=0; i<numbers.length; i++) \n{\n if (numbers[i] == arr[i]) \n { ...\n } \n}" }, { "code": null, "e": 31367, "s": 31288, "text": " 5. For-each also has some performance overhead over simple iteration: " }, { "code": null, "e": 31372, "s": 31367, "text": "Java" }, { "code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG { public static void main (String[] args) { List<Integer> list = new ArrayList<>(); long startTime; long endTime; for (int i = 0; i < 1000000; i++) { list.add(i); } // Type 1 startTime = Calendar.getInstance().getTimeInMillis(); for (int i : list) { int a = i; } endTime = Calendar.getInstance().getTimeInMillis(); System.out.println(\"For each loop :: \" + (endTime - startTime) + \" ms\"); // Type 2 startTime = Calendar.getInstance().getTimeInMillis(); for (int j = 0; j < list.size(); j++) { int a = list.get(j); } endTime = Calendar.getInstance().getTimeInMillis(); System.out.println(\"Using collection.size() :: \" + (endTime - startTime) + \" ms\"); // Type 3 startTime = Calendar.getInstance().getTimeInMillis(); int size = list.size(); for (int j = 0; j < size; j++) { int a = list.get(j); } endTime = Calendar.getInstance().getTimeInMillis(); System.out.println(\"By calculating collection.size() first :: \" + (endTime - startTime) + \" ms\"); // Type 4 startTime = Calendar.getInstance().getTimeInMillis(); for(int j = list.size()-1; j >= 0; j--) { int a = list.get(j); } endTime = Calendar.getInstance().getTimeInMillis(); System.out.println(\"Using [int j = list.size(); j > size ; j--] :: \" + (endTime - startTime) + \" ms\"); }} // This code is contributed by Ayush Choudhary @gfg(code_ayush)", "e": 33063, "s": 31372, "text": null }, { "code": null, "e": 33885, "s": 33065, "text": "YouTubeGeeksforGeeks502K subscribersFor each Loop in Java | 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 / 5:52•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=DUVqtwVJ3DI\" 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": 34423, "s": 33885, "text": "?list=PLqM7alHXFySF5ErEHA1BXgibGg7uqmA4_ Related Articles: For-each in C++ vs Java Iterator vs For-each in JavaThis article is contributed by Abhishek Verma. 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": 34434, "s": 34423, "text": "code_ayush" }, { "code": null, "e": 34446, "s": 34434, "text": "java-basics" }, { "code": null, "e": 34451, "s": 34446, "text": "Java" }, { "code": null, "e": 34456, "s": 34451, "text": "Java" }, { "code": null, "e": 34554, "s": 34456, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34598, "s": 34554, "text": "Split() String method in Java with examples" }, { "code": null, "e": 34634, "s": 34598, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 34659, "s": 34634, "text": "Reverse a string in Java" }, { "code": null, "e": 34691, "s": 34659, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 34722, "s": 34691, "text": "How to iterate any Map in Java" }, { "code": null, "e": 34737, "s": 34722, "text": "Stream In Java" }, { "code": null, "e": 34761, "s": 34737, "text": "Singleton Class in Java" }, { "code": null, "e": 34789, "s": 34761, "text": "Initializing a List in Java" }, { "code": null, "e": 34835, "s": 34789, "text": "Different ways of Reading a text file in Java" } ]
Exploratory Data Analysis in R Programming - GeeksforGeeks
03 Jan, 2022 Exploratory Data Analysis or EDA is a statistical approach or technique for analyzing data sets in order to summarize their important and main characteristics generally by using some visual aids. The EDA approach can be used to gather knowledge about the following aspects of data: Main characteristics or features of the data. The variables and their relationships. Finding out the important variables that can be used in our problem. EDA is an iterative approach that includes: Generating questions about our data Searching for the answers by using visualization, transformation, and modeling of our data. Using the lessons that we learn in order to refine our set of questions or to generate a new set of questions. In R Language, we are going to perform EDA under two broad classifications: Descriptive Statistics, which includes mean, median, mode, inter-quartile range, and so on. Graphical Methods, which includes histogram, density estimation, box plots, and so on. Before we start working with EDA, we must perform the data inspection properly. Here in our analysis, we will be using the loafercreek from the soilDB package in R. We are going to inspect our data in order to find all the typos and blatant errors. Further EDA can be used to determine and identify the outliers and perform the required statistical analysis. For performing the EDA, we will have to install and load the following packages: “aqp” package “ggplot2” package “soilDB” package We can install these packages from the R console using the install.packages() command and load them into our R Script by using the library() command. We will now see how to inspect our data and remove the typos and blatant errors. To ensure that we are dealing with the right information we need a clear view of your data at every stage of the transformation process. Data Inspection is the act of viewing data for verification and debugging purposes, before, during, or after a translation. Now let’s see how to inspect and remove the errors and typos from the data. Example: R # Data Inspection in EDA# loading the required packageslibrary(aqp)library(soilDB) # Load from the the loakercreek datasetdata("loafercreek") # Construct generalized horizon designationsn < - c("A", "BAt", "Bt1", "Bt2", "Cr", "R") # REGEX rulesp < - c("A", "BA|AB", "Bt|Bw", "Bt3|Bt4|2B|C", "Cr", "R") # Compute genhz labels and# add to loafercreek datasetloafercreek$genhz < - generalize.hz( loafercreek$hzname, n, p) # Extract the horizon tableh < - horizons(loafercreek) # Examine the matching of pairing of# the genhz label to the hznamestable(h$genhz, h$hzname) vars < - c("genhz", "clay", "total_frags_pct", "phfield", "effclass")summary(h[, vars]) sort(unique(h$hzname))h$hzname < - ifelse(h$hzname == "BT", "Bt", h$hzname) Output: > table(h$genhz, h$hzname) 2BCt 2Bt1 2Bt2 2Bt3 2Bt4 2Bt5 2CB 2CBt 2Cr 2Crt 2R A A1 A2 AB ABt Ad Ap B BA BAt BC BCt Bt Bt1 Bt2 Bt3 Bt4 Bw Bw1 Bw2 Bw3 C A 0 0 0 0 0 0 0 0 0 0 0 97 7 7 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 BAt 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 31 8 0 0 0 0 0 0 0 0 0 0 0 0 Bt1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 8 94 89 0 0 10 2 2 1 0 Bt2 1 2 7 8 6 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 5 16 0 0 0 47 8 0 0 0 0 6 Cr 0 0 0 0 0 0 0 0 4 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 R 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 not-used 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 CBt Cd Cr Cr/R Crt H1 Oi R Rt A 0 0 0 0 0 0 0 0 0 BAt 0 0 0 0 0 0 0 0 0 Bt1 0 0 0 0 0 0 0 0 0 Bt2 6 1 0 0 0 0 0 0 0 Cr 0 0 49 0 20 0 0 0 0 R 0 0 0 1 0 0 0 41 1 not-used 0 0 0 0 0 1 24 0 0 > summary(h[, vars]) genhz clay total_frags_pct phfield effclass A :113 Min. :10.00 Min. : 0.00 Min. :4.90 very slight: 0 BAt : 40 1st Qu.:18.00 1st Qu.: 0.00 1st Qu.:6.00 slight : 0 Bt1 :208 Median :22.00 Median : 5.00 Median :6.30 strong : 0 Bt2 :116 Mean :23.67 Mean :14.18 Mean :6.18 violent : 0 Cr : 75 3rd Qu.:28.00 3rd Qu.:20.00 3rd Qu.:6.50 none : 86 R : 48 Max. :60.00 Max. :95.00 Max. :7.00 NA's :540 not-used: 26 NA's :173 NA's :381 > sort(unique(h$hzname)) [1] "2BCt" "2Bt1" "2Bt2" "2Bt3" "2Bt4" "2Bt5" "2CB" "2CBt" "2Cr" "2Crt" "2R" "A" "A1" "A2" "AB" "ABt" "Ad" "Ap" "B" [20] "BA" "BAt" "BC" "BCt" "Bt" "Bt1" "Bt2" "Bt3" "Bt4" "Bw" "Bw1" "Bw2" "Bw3" "C" "CBt" "Cd" "Cr" "Cr/R" "Crt" [39] "H1" "Oi" "R" "Rt" Now proceed with the EDA. For Descriptive Statistics in order to perform EDA in R, we will divide all the functions into the following categories: Measures of central tendency Measures of dispersion Correlation We will try to determine the mid-point values using the functions under the Measures of Central tendency. Under this section, we will be calculating the mean, median, mode, and frequencies. Example 1: Now see the measures of central tendency in this example. R # EDA# Descriptive Statistics# Measures of Central Tendency #loading the required packageslibrary(aqp)library(soilDB) # Load from the the loakercreek datasetdata("loafercreek") # Construct generalized horizon designationsn <- c("A", "BAt", "Bt1", "Bt2", "Cr", "R") # REGEX rulesp <- c("A", "BA|AB", "Bt|Bw", "Bt3|Bt4|2B|C", "Cr", "R") # Compute genhz labels and# add to loafercreek datasetloafercreek$genhz <- generalize.hz( loafercreek$hzname, n, p) # Extract the horizon tableh <- horizons(loafercreek) # Examine the matching of pairing# of the genhz label to the hznamestable(h$genhz, h$hzname) vars <- c("genhz", "clay", "total_frags_pct", "phfield", "effclass")summary(h[, vars]) sort(unique(h$hzname))h$hzname <- ifelse(h$hzname == "BT", "Bt", h$hzname) # first remove missing values# and create a new vectorclay <- na.exclude(h$clay) mean(clay)median(clay)sort(table(round(h$clay)), decreasing = TRUE)[1]table(h$genhz)# append the table with# row and column sumsaddmargins(table(h$genhz, h$texcl)) # calculate the proportions# relative to the rows, margin = 1# calculates for rows, margin = 2 calculates# for columns, margin = NULL calculates# for total observationsround(prop.table(table(h$genhz, h$texture_class), margin = 1) * 100)knitr::kable(addmargins(table(h$genhz, h$texcl))) aggregate(clay ~ genhz, data = h, mean)aggregate(clay ~ genhz, data = h, median)aggregate(clay ~ genhz, data = h, summary) Output: > mean(clay) [1] 23.6713 > median(clay) [1] 22 > sort(table(round(h$clay)), decreasing = TRUE)[1] 25 41 > table(h$genhz) A BAt Bt1 Bt2 Cr R not-used 113 40 208 116 75 48 26 > addmargins(table(h$genhz, h$texcl)) cos s fs vfs lcos ls lfs lvfs cosl sl fsl vfsl l sil si scl cl sicl sc sic c Sum A 0 0 0 0 0 0 0 0 0 6 0 0 78 27 0 0 0 0 0 0 0 111 BAt 0 0 0 0 0 0 0 0 0 1 0 0 31 4 0 0 2 1 0 0 0 39 Bt1 0 0 0 0 0 0 0 0 0 1 0 0 125 20 0 4 46 5 0 1 2 204 Bt2 0 0 0 0 0 0 0 0 0 0 0 0 28 5 0 5 52 3 0 1 16 110 Cr 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1 R 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 not-used 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1 Sum 0 0 0 0 0 0 0 0 0 8 0 0 262 56 0 9 101 9 0 2 19 466 > round(prop.table(table(h$genhz, h$texture_class), margin = 1) * 100) br c cb cl gr l pg scl sic sicl sil sl spm A 0 0 0 0 0 70 0 0 0 0 24 5 0 BAt 0 0 0 5 0 79 0 0 0 3 10 3 0 Bt1 0 1 0 23 0 61 0 2 0 2 10 0 0 Bt2 0 14 1 46 2 25 1 4 1 3 4 0 0 Cr 98 2 0 0 0 0 0 0 0 0 0 0 0 R 100 0 0 0 0 0 0 0 0 0 0 0 0 not-used 0 0 0 4 0 0 0 0 0 0 0 0 96 > knitr::kable(addmargins(table(h$genhz, h$texcl))) | | cos| s| fs| vfs| lcos| ls| lfs| lvfs| cosl| sl| fsl| vfsl| l| sil| si| scl| cl| sicl| sc| sic| c| Sum| |:--------|---:|--:|--:|---:|----:|--:|---:|----:|----:|--:|---:|----:|---:|---:|--:|---:|---:|----:|--:|---:|--:|---:| |A | 0| 0| 0| 0| 0| 0| 0| 0| 0| 6| 0| 0| 78| 27| 0| 0| 0| 0| 0| 0| 0| 111| |BAt | 0| 0| 0| 0| 0| 0| 0| 0| 0| 1| 0| 0| 31| 4| 0| 0| 2| 1| 0| 0| 0| 39| |Bt1 | 0| 0| 0| 0| 0| 0| 0| 0| 0| 1| 0| 0| 125| 20| 0| 4| 46| 5| 0| 1| 2| 204| |Bt2 | 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 28| 5| 0| 5| 52| 3| 0| 1| 16| 110| |Cr | 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 1| 1| |R | 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| |not-used | 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 1| 0| 0| 0| 0| 1| |Sum | 0| 0| 0| 0| 0| 0| 0| 0| 0| 8| 0| 0| 262| 56| 0| 9| 101| 9| 0| 2| 19| 466| > aggregate(clay ~ genhz, data = h, mean) genhz clay 1 A 16.23113 2 BAt 19.53889 3 Bt1 24.14221 4 Bt2 31.35045 5 Cr 15.00000 > aggregate(clay ~ genhz, data = h, median) genhz clay 1 A 16.0 2 BAt 19.5 3 Bt1 24.0 4 Bt2 30.0 5 Cr 15.0 > aggregate(clay ~ genhz, data = h, summary) genhz clay.Min. clay.1st Qu. clay.Median clay.Mean clay.3rd Qu. clay.Max. 1 A 10.00000 14.00000 16.00000 16.23113 18.00000 25.00000 2 BAt 14.00000 17.00000 19.50000 19.53889 20.00000 28.00000 3 Bt1 12.00000 20.00000 24.00000 24.14221 28.00000 51.40000 4 Bt2 10.00000 26.00000 30.00000 31.35045 35.00000 60.00000 5 Cr 15.00000 15.00000 15.00000 15.00000 15.00000 15.00000 Now we will see the functions under Measures of Dispersion. In this category, we are going to determine the spread values around the mid-point. Here we are going to calculate the variance, standard deviation, range, inter-quartile range, coefficient of variance, and quartiles. Example 2: We shall see the measures of dispersion in this example. R # EDA# Descriptive Statistics# Measures of Dispersion # loading the packageslibrary(aqp)library(soilDB) # Load from the the loakercreek datasetdata("loafercreek") # Construct generalized horizon designationsn <- c("A", "BAt", "Bt1", "Bt2", "Cr", "R") # REGEX rulesp <- c("A", "BA|AB", "Bt|Bw", "Bt3|Bt4|2B|C", "Cr", "R") # Compute genhz labels and add# to loafercreek datasetloafercreek$genhz <- generalize.hz( loafercreek$hzname, n, p) # Extract the horizon tableh <- horizons(loafercreek) # Examine the matching of pairing of# the genhz label to the hznamestable(h$genhz, h$hzname) vars <- c("genhz", "clay", "total_frags_pct", "phfield", "effclass")summary(h[, vars]) sort(unique(h$hzname))h$hzname <- ifelse(h$hzname == "BT", "Bt", h$hzname) # first remove missing values# and create a new vectorclay <- na.exclude(h$clay)var(h$clay, na.rm=TRUE)sd(h$clay, na.rm = TRUE)cv <- sd(clay) / mean(clay) * 100cvquantile(clay)range(clay)IQR(clay) Output: > var(h$clay, na.rm=TRUE) [1] 64.89187 > sd(h$clay, na.rm = TRUE) [1] 8.055549 > cv [1] 34.03087 > quantile(clay) 0% 25% 50% 75% 100% 10 18 22 28 60 > range(clay) [1] 10 60 > IQR(clay) [1] 10 Now we will work on Correlation. In this part, all the calculated correlation coefficient values of all variables in tabulated as the Correlation Matrix. This gives us a quantitative measure in order to guide our decision-making process. Example 3: We shall now see the correlation in this example. R # EDA# Descriptive Statistics# Correlation # loading the required packageslibrary(aqp)library(soilDB) # Load from the the loakercreek datasetdata("loafercreek") # Construct generalized horizon designationsn <- c("A", "BAt", "Bt1", "Bt2", "Cr", "R") # REGEX rulesp <- c("A", "BA|AB", "Bt|Bw", "Bt3|Bt4|2B|C", "Cr", "R") # Compute genhz labels and add# to loafercreek datasetloafercreek$genhz <- generalize.hz( loafercreek$hzname, n, p) # Extract the horizon tableh <- horizons(loafercreek) # Examine the matching of pairing# of the genhz label to the hznamestable(h$genhz, h$hzname) vars <- c("genhz", "clay", "total_frags_pct", "phfield", "effclass")summary(h[, vars]) sort(unique(h$hzname))h$hzname <- ifelse(h$hzname == "BT", "Bt", h$hzname) # first remove missing values# and create a new vectorclay <- na.exclude(h$clay) # Compute the middle horizon depthh$hzdepm <- (h$hzdepb + h$hzdept) / 2vars <- c("hzdepm", "clay", "sand", "total_frags_pct", "phfield")round(cor(h[, vars], use = "complete.obs"), 2) Output: hzdepm clay sand total_frags_pct phfield hzdepm 1.00 0.59 -0.08 0.50 -0.03 clay 0.59 1.00 -0.17 0.28 0.13 sand -0.08 -0.17 1.00 -0.05 0.12 total_frags_pct 0.50 0.28 -0.05 1.00 -0.16 phfield -0.03 0.13 0.12 -0.16 1.00 Hence, the above three classifications deal with the Descriptive statistics part of EDA. Now we shall move on to the Graphical Method of representing EDA. Since we have already checked our data for missing values, blatant errors, and typos, we can now examine our data graphically in order to perform EDA. We will see the graphical representation under the following categories: Distributions Scatter and Line plot Under the Distribution, we shall examine our data using the bar plot, Histogram, Density curve, box plots, and QQplot. Example 1: We shall see how distribution graphs can be used to examine data in EDA in this example. R # EDA Graphical Method Distributions # loading the required packageslibrary("ggplot2")library(aqp)library(soilDB) # Load from the the loakercreek datasetdata("loafercreek") # Construct generalized horizon designationsn <- c("A", "BAt", "Bt1", "Bt2", "Cr", "R") # REGEX rulesp <- c("A", "BA|AB", "Bt|Bw", "Bt3|Bt4|2B|C", "Cr", "R") # Compute genhz labels and add# to loafercreek datasetloafercreek$genhz <- generalize.hz( loafercreek$hzname, n, p) # Extract the horizon tableh <- horizons(loafercreek) # Examine the matching of pairing# of the genhz label to the hznamestable(h$genhz, h$hzname) vars <- c("genhz", "clay", "total_frags_pct", "phfield", "effclass")summary(h[, vars]) sort(unique(h$hzname))h$hzname <- ifelse(h$hzname == "BT", "Bt", h$hzname) # graphs# bar plotggplot(h, aes(x = texcl)) +geom_bar() # histogramggplot(h, aes(x = clay)) + geom_histogram(bins = nclass.Sturges(h$clay)) # density curveggplot(h, aes(x = clay)) + geom_density() # box plotggplot(h, (aes(x = genhz, y = clay))) +geom_boxplot() # QQ Plot for Clayggplot(h, aes(sample = clay)) +geom_qq() +geom_qq_line() Output: Now we will move on to the Scatter and Line plot. In this category, we are going to see two types of plotting,- scatter plot and line plot. Plotting points of one interval or ratio variable against variable are known as a scatter plot. Example 2: We shall now see how to use scatter and line plots to examine our data. R # EDA# Graphical Method# Scatter and Line plot # loading the required packageslibrary("ggplot2")library(aqp)library(soilDB) # Load from the the loakercreek datasetdata("loafercreek") # Construct generalized horizon designationsn <- c("A", "BAt", "Bt1", "Bt2", "Cr", "R") # REGEX rulesp <- c("A", "BA|AB", "Bt|Bw", "Bt3|Bt4|2B|C", "Cr", "R") # Compute genhz labels and add# to loafercreek datasetloafercreek$genhz <- generalize.hz( loafercreek$hzname, n, p) # Extract the horizon tableh <- horizons(loafercreek) # Examine the matching of pairing# of the genhz label to the hznamestable(h$genhz, h$hzname) vars <- c("genhz", "clay", "total_frags_pct", "phfield", "effclass")summary(h[, vars]) sort(unique(h$hzname))h$hzname <- ifelse(h$hzname == "BT", "Bt", h$hzname) # graph# scatter plotggplot(h, aes(x = clay, y = hzdepm)) + geom_point() + ylim(100, 0) # line plotggplot(h, aes(y = clay, x = hzdepm, group = peiid)) +geom_line() + coord_flip() + xlim(100, 0) Output: simmytarika5 kumar_satyam data-science R Machine-Learning R-Statistics Machine Learning R Language Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Support Vector Machine Algorithm k-nearest neighbor algorithm in Python Singular Value Decomposition (SVD) Intuition of Adam Optimizer ML | Logistic Regression using Python Change column name of a given DataFrame in R How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Adding elements in a vector in R programming - append() method
[ { "code": null, "e": 24344, "s": 24316, "text": "\n03 Jan, 2022" }, { "code": null, "e": 24626, "s": 24344, "text": "Exploratory Data Analysis or EDA is a statistical approach or technique for analyzing data sets in order to summarize their important and main characteristics generally by using some visual aids. The EDA approach can be used to gather knowledge about the following aspects of data:" }, { "code": null, "e": 24672, "s": 24626, "text": "Main characteristics or features of the data." }, { "code": null, "e": 24711, "s": 24672, "text": "The variables and their relationships." }, { "code": null, "e": 24780, "s": 24711, "text": "Finding out the important variables that can be used in our problem." }, { "code": null, "e": 24824, "s": 24780, "text": "EDA is an iterative approach that includes:" }, { "code": null, "e": 24860, "s": 24824, "text": "Generating questions about our data" }, { "code": null, "e": 24952, "s": 24860, "text": "Searching for the answers by using visualization, transformation, and modeling of our data." }, { "code": null, "e": 25063, "s": 24952, "text": "Using the lessons that we learn in order to refine our set of questions or to generate a new set of questions." }, { "code": null, "e": 25139, "s": 25063, "text": "In R Language, we are going to perform EDA under two broad classifications:" }, { "code": null, "e": 25231, "s": 25139, "text": "Descriptive Statistics, which includes mean, median, mode, inter-quartile range, and so on." }, { "code": null, "e": 25318, "s": 25231, "text": "Graphical Methods, which includes histogram, density estimation, box plots, and so on." }, { "code": null, "e": 25758, "s": 25318, "text": "Before we start working with EDA, we must perform the data inspection properly. Here in our analysis, we will be using the loafercreek from the soilDB package in R. We are going to inspect our data in order to find all the typos and blatant errors. Further EDA can be used to determine and identify the outliers and perform the required statistical analysis. For performing the EDA, we will have to install and load the following packages:" }, { "code": null, "e": 25772, "s": 25758, "text": "“aqp” package" }, { "code": null, "e": 25790, "s": 25772, "text": "“ggplot2” package" }, { "code": null, "e": 25807, "s": 25790, "text": "“soilDB” package" }, { "code": null, "e": 26039, "s": 25807, "text": "We can install these packages from the R console using the install.packages() command and load them into our R Script by using the library() command. We will now see how to inspect our data and remove the typos and blatant errors. " }, { "code": null, "e": 26376, "s": 26039, "text": "To ensure that we are dealing with the right information we need a clear view of your data at every stage of the transformation process. Data Inspection is the act of viewing data for verification and debugging purposes, before, during, or after a translation. Now let’s see how to inspect and remove the errors and typos from the data." }, { "code": null, "e": 26385, "s": 26376, "text": "Example:" }, { "code": null, "e": 26387, "s": 26385, "text": "R" }, { "code": "# Data Inspection in EDA# loading the required packageslibrary(aqp)library(soilDB) # Load from the the loakercreek datasetdata(\"loafercreek\") # Construct generalized horizon designationsn < - c(\"A\", \"BAt\", \"Bt1\", \"Bt2\", \"Cr\", \"R\") # REGEX rulesp < - c(\"A\", \"BA|AB\", \"Bt|Bw\", \"Bt3|Bt4|2B|C\", \"Cr\", \"R\") # Compute genhz labels and# add to loafercreek datasetloafercreek$genhz < - generalize.hz( loafercreek$hzname, n, p) # Extract the horizon tableh < - horizons(loafercreek) # Examine the matching of pairing of# the genhz label to the hznamestable(h$genhz, h$hzname) vars < - c(\"genhz\", \"clay\", \"total_frags_pct\", \"phfield\", \"effclass\")summary(h[, vars]) sort(unique(h$hzname))h$hzname < - ifelse(h$hzname == \"BT\", \"Bt\", h$hzname)", "e": 27160, "s": 26387, "text": null }, { "code": null, "e": 27169, "s": 27160, "text": " Output:" }, { "code": null, "e": 29662, "s": 27169, "text": "> table(h$genhz, h$hzname)\n \n 2BCt 2Bt1 2Bt2 2Bt3 2Bt4 2Bt5 2CB 2CBt 2Cr 2Crt 2R A A1 A2 AB ABt Ad Ap B BA BAt BC BCt Bt Bt1 Bt2 Bt3 Bt4 Bw Bw1 Bw2 Bw3 C\n A 0 0 0 0 0 0 0 0 0 0 0 97 7 7 0 0 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n BAt 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 31 8 0 0 0 0 0 0 0 0 0 0 0 0\n Bt1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 8 94 89 0 0 10 2 2 1 0\n Bt2 1 2 7 8 6 1 1 1 0 0 0 0 0 0 0 0 0 0 0 0 0 5 16 0 0 0 47 8 0 0 0 0 6\n Cr 0 0 0 0 0 0 0 0 4 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n R 0 0 0 0 0 0 0 0 0 0 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n not-used 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n \n CBt Cd Cr Cr/R Crt H1 Oi R Rt\n A 0 0 0 0 0 0 0 0 0\n BAt 0 0 0 0 0 0 0 0 0\n Bt1 0 0 0 0 0 0 0 0 0\n Bt2 6 1 0 0 0 0 0 0 0\n Cr 0 0 49 0 20 0 0 0 0\n R 0 0 0 1 0 0 0 41 1\n not-used 0 0 0 0 0 1 24 0 0\n\n> summary(h[, vars])\n genhz clay total_frags_pct phfield effclass \n A :113 Min. :10.00 Min. : 0.00 Min. :4.90 very slight: 0 \n BAt : 40 1st Qu.:18.00 1st Qu.: 0.00 1st Qu.:6.00 slight : 0 \n Bt1 :208 Median :22.00 Median : 5.00 Median :6.30 strong : 0 \n Bt2 :116 Mean :23.67 Mean :14.18 Mean :6.18 violent : 0 \n Cr : 75 3rd Qu.:28.00 3rd Qu.:20.00 3rd Qu.:6.50 none : 86 \n R : 48 Max. :60.00 Max. :95.00 Max. :7.00 NA's :540 \n not-used: 26 NA's :173 NA's :381 \n\n> sort(unique(h$hzname))\n [1] \"2BCt\" \"2Bt1\" \"2Bt2\" \"2Bt3\" \"2Bt4\" \"2Bt5\" \"2CB\" \"2CBt\" \"2Cr\" \"2Crt\" \"2R\" \"A\" \"A1\" \"A2\" \"AB\" \"ABt\" \"Ad\" \"Ap\" \"B\" \n[20] \"BA\" \"BAt\" \"BC\" \"BCt\" \"Bt\" \"Bt1\" \"Bt2\" \"Bt3\" \"Bt4\" \"Bw\" \"Bw1\" \"Bw2\" \"Bw3\" \"C\" \"CBt\" \"Cd\" \"Cr\" \"Cr/R\" \"Crt\" \n[39] \"H1\" \"Oi\" \"R\" \"Rt\" " }, { "code": null, "e": 29688, "s": 29662, "text": "Now proceed with the EDA." }, { "code": null, "e": 29810, "s": 29688, "text": "For Descriptive Statistics in order to perform EDA in R, we will divide all the functions into the following categories: " }, { "code": null, "e": 29839, "s": 29810, "text": "Measures of central tendency" }, { "code": null, "e": 29862, "s": 29839, "text": "Measures of dispersion" }, { "code": null, "e": 29874, "s": 29862, "text": "Correlation" }, { "code": null, "e": 30064, "s": 29874, "text": "We will try to determine the mid-point values using the functions under the Measures of Central tendency. Under this section, we will be calculating the mean, median, mode, and frequencies." }, { "code": null, "e": 30133, "s": 30064, "text": "Example 1: Now see the measures of central tendency in this example." }, { "code": null, "e": 30135, "s": 30133, "text": "R" }, { "code": "# EDA# Descriptive Statistics# Measures of Central Tendency #loading the required packageslibrary(aqp)library(soilDB) # Load from the the loakercreek datasetdata(\"loafercreek\") # Construct generalized horizon designationsn <- c(\"A\", \"BAt\", \"Bt1\", \"Bt2\", \"Cr\", \"R\") # REGEX rulesp <- c(\"A\", \"BA|AB\", \"Bt|Bw\", \"Bt3|Bt4|2B|C\", \"Cr\", \"R\") # Compute genhz labels and# add to loafercreek datasetloafercreek$genhz <- generalize.hz( loafercreek$hzname, n, p) # Extract the horizon tableh <- horizons(loafercreek) # Examine the matching of pairing# of the genhz label to the hznamestable(h$genhz, h$hzname) vars <- c(\"genhz\", \"clay\", \"total_frags_pct\", \"phfield\", \"effclass\")summary(h[, vars]) sort(unique(h$hzname))h$hzname <- ifelse(h$hzname == \"BT\", \"Bt\", h$hzname) # first remove missing values# and create a new vectorclay <- na.exclude(h$clay) mean(clay)median(clay)sort(table(round(h$clay)), decreasing = TRUE)[1]table(h$genhz)# append the table with# row and column sumsaddmargins(table(h$genhz, h$texcl)) # calculate the proportions# relative to the rows, margin = 1# calculates for rows, margin = 2 calculates# for columns, margin = NULL calculates# for total observationsround(prop.table(table(h$genhz, h$texture_class), margin = 1) * 100)knitr::kable(addmargins(table(h$genhz, h$texcl))) aggregate(clay ~ genhz, data = h, mean)aggregate(clay ~ genhz, data = h, median)aggregate(clay ~ genhz, data = h, summary)", "e": 31662, "s": 30135, "text": null }, { "code": null, "e": 31672, "s": 31662, "text": " Output: " }, { "code": null, "e": 35529, "s": 31672, "text": "> mean(clay)\n[1] 23.6713\n> median(clay)\n[1] 22\n> sort(table(round(h$clay)), decreasing = TRUE)[1]\n25 \n41 \n> table(h$genhz)\n\n A BAt Bt1 Bt2 Cr R not-used \n 113 40 208 116 75 48 26 \n\n> addmargins(table(h$genhz, h$texcl))\n \n cos s fs vfs lcos ls lfs lvfs cosl sl fsl vfsl l sil si scl cl sicl sc sic c Sum\n A 0 0 0 0 0 0 0 0 0 6 0 0 78 27 0 0 0 0 0 0 0 111\n BAt 0 0 0 0 0 0 0 0 0 1 0 0 31 4 0 0 2 1 0 0 0 39\n Bt1 0 0 0 0 0 0 0 0 0 1 0 0 125 20 0 4 46 5 0 1 2 204\n Bt2 0 0 0 0 0 0 0 0 0 0 0 0 28 5 0 5 52 3 0 1 16 110\n Cr 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 1\n R 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0\n not-used 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 1\n Sum 0 0 0 0 0 0 0 0 0 8 0 0 262 56 0 9 101 9 0 2 19 466\n\n> round(prop.table(table(h$genhz, h$texture_class), margin = 1) * 100)\n \n br c cb cl gr l pg scl sic sicl sil sl spm\n A 0 0 0 0 0 70 0 0 0 0 24 5 0\n BAt 0 0 0 5 0 79 0 0 0 3 10 3 0\n Bt1 0 1 0 23 0 61 0 2 0 2 10 0 0\n Bt2 0 14 1 46 2 25 1 4 1 3 4 0 0\n Cr 98 2 0 0 0 0 0 0 0 0 0 0 0\n R 100 0 0 0 0 0 0 0 0 0 0 0 0\n not-used 0 0 0 4 0 0 0 0 0 0 0 0 96\n\n> knitr::kable(addmargins(table(h$genhz, h$texcl)))\n\n\n| | cos| s| fs| vfs| lcos| ls| lfs| lvfs| cosl| sl| fsl| vfsl| l| sil| si| scl| cl| sicl| sc| sic| c| Sum|\n|:--------|---:|--:|--:|---:|----:|--:|---:|----:|----:|--:|---:|----:|---:|---:|--:|---:|---:|----:|--:|---:|--:|---:|\n|A | 0| 0| 0| 0| 0| 0| 0| 0| 0| 6| 0| 0| 78| 27| 0| 0| 0| 0| 0| 0| 0| 111|\n|BAt | 0| 0| 0| 0| 0| 0| 0| 0| 0| 1| 0| 0| 31| 4| 0| 0| 2| 1| 0| 0| 0| 39|\n|Bt1 | 0| 0| 0| 0| 0| 0| 0| 0| 0| 1| 0| 0| 125| 20| 0| 4| 46| 5| 0| 1| 2| 204|\n|Bt2 | 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 28| 5| 0| 5| 52| 3| 0| 1| 16| 110|\n|Cr | 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 1| 1|\n|R | 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0|\n|not-used | 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 0| 1| 0| 0| 0| 0| 1|\n|Sum | 0| 0| 0| 0| 0| 0| 0| 0| 0| 8| 0| 0| 262| 56| 0| 9| 101| 9| 0| 2| 19| 466|\n> aggregate(clay ~ genhz, data = h, mean)\n genhz clay\n1 A 16.23113\n2 BAt 19.53889\n3 Bt1 24.14221\n4 Bt2 31.35045\n5 Cr 15.00000\n\n> aggregate(clay ~ genhz, data = h, median)\n genhz clay\n1 A 16.0\n2 BAt 19.5\n3 Bt1 24.0\n4 Bt2 30.0\n5 Cr 15.0\n\n> aggregate(clay ~ genhz, data = h, summary)\n genhz clay.Min. clay.1st Qu. clay.Median clay.Mean clay.3rd Qu. clay.Max.\n1 A 10.00000 14.00000 16.00000 16.23113 18.00000 25.00000\n2 BAt 14.00000 17.00000 19.50000 19.53889 20.00000 28.00000\n3 Bt1 12.00000 20.00000 24.00000 24.14221 28.00000 51.40000\n4 Bt2 10.00000 26.00000 30.00000 31.35045 35.00000 60.00000\n5 Cr 15.00000 15.00000 15.00000 15.00000 15.00000 15.00000" }, { "code": null, "e": 35808, "s": 35529, "text": "Now we will see the functions under Measures of Dispersion. In this category, we are going to determine the spread values around the mid-point. Here we are going to calculate the variance, standard deviation, range, inter-quartile range, coefficient of variance, and quartiles. " }, { "code": null, "e": 35819, "s": 35808, "text": "Example 2:" }, { "code": null, "e": 35877, "s": 35819, "text": "We shall see the measures of dispersion in this example. " }, { "code": null, "e": 35879, "s": 35877, "text": "R" }, { "code": "# EDA# Descriptive Statistics# Measures of Dispersion # loading the packageslibrary(aqp)library(soilDB) # Load from the the loakercreek datasetdata(\"loafercreek\") # Construct generalized horizon designationsn <- c(\"A\", \"BAt\", \"Bt1\", \"Bt2\", \"Cr\", \"R\") # REGEX rulesp <- c(\"A\", \"BA|AB\", \"Bt|Bw\", \"Bt3|Bt4|2B|C\", \"Cr\", \"R\") # Compute genhz labels and add# to loafercreek datasetloafercreek$genhz <- generalize.hz( loafercreek$hzname, n, p) # Extract the horizon tableh <- horizons(loafercreek) # Examine the matching of pairing of# the genhz label to the hznamestable(h$genhz, h$hzname) vars <- c(\"genhz\", \"clay\", \"total_frags_pct\", \"phfield\", \"effclass\")summary(h[, vars]) sort(unique(h$hzname))h$hzname <- ifelse(h$hzname == \"BT\", \"Bt\", h$hzname) # first remove missing values# and create a new vectorclay <- na.exclude(h$clay)var(h$clay, na.rm=TRUE)sd(h$clay, na.rm = TRUE)cv <- sd(clay) / mean(clay) * 100cvquantile(clay)range(clay)IQR(clay)", "e": 36897, "s": 35879, "text": null }, { "code": null, "e": 36907, "s": 36897, "text": " Output: " }, { "code": null, "e": 37121, "s": 36907, "text": "> var(h$clay, na.rm=TRUE)\n[1] 64.89187\n\n> sd(h$clay, na.rm = TRUE)\n[1] 8.055549\n\n> cv\n[1] 34.03087\n\n> quantile(clay)\n 0% 25% 50% 75% 100% \n 10 18 22 28 60 \n\n> range(clay)\n[1] 10 60\n\n> IQR(clay)\n[1] 10" }, { "code": null, "e": 37360, "s": 37121, "text": "Now we will work on Correlation. In this part, all the calculated correlation coefficient values of all variables in tabulated as the Correlation Matrix. This gives us a quantitative measure in order to guide our decision-making process. " }, { "code": null, "e": 37371, "s": 37360, "text": "Example 3:" }, { "code": null, "e": 37422, "s": 37371, "text": "We shall now see the correlation in this example. " }, { "code": null, "e": 37424, "s": 37422, "text": "R" }, { "code": "# EDA# Descriptive Statistics# Correlation # loading the required packageslibrary(aqp)library(soilDB) # Load from the the loakercreek datasetdata(\"loafercreek\") # Construct generalized horizon designationsn <- c(\"A\", \"BAt\", \"Bt1\", \"Bt2\", \"Cr\", \"R\") # REGEX rulesp <- c(\"A\", \"BA|AB\", \"Bt|Bw\", \"Bt3|Bt4|2B|C\", \"Cr\", \"R\") # Compute genhz labels and add# to loafercreek datasetloafercreek$genhz <- generalize.hz( loafercreek$hzname, n, p) # Extract the horizon tableh <- horizons(loafercreek) # Examine the matching of pairing# of the genhz label to the hznamestable(h$genhz, h$hzname) vars <- c(\"genhz\", \"clay\", \"total_frags_pct\", \"phfield\", \"effclass\")summary(h[, vars]) sort(unique(h$hzname))h$hzname <- ifelse(h$hzname == \"BT\", \"Bt\", h$hzname) # first remove missing values# and create a new vectorclay <- na.exclude(h$clay) # Compute the middle horizon depthh$hzdepm <- (h$hzdepb + h$hzdept) / 2vars <- c(\"hzdepm\", \"clay\", \"sand\", \"total_frags_pct\", \"phfield\")round(cor(h[, vars], use = \"complete.obs\"), 2)", "e": 38516, "s": 37424, "text": null }, { "code": null, "e": 38525, "s": 38516, "text": "Output: " }, { "code": null, "e": 38879, "s": 38525, "text": " hzdepm clay sand total_frags_pct phfield\nhzdepm 1.00 0.59 -0.08 0.50 -0.03\nclay 0.59 1.00 -0.17 0.28 0.13\nsand -0.08 -0.17 1.00 -0.05 0.12\ntotal_frags_pct 0.50 0.28 -0.05 1.00 -0.16\nphfield -0.03 0.13 0.12 -0.16 1.00" }, { "code": null, "e": 39034, "s": 38879, "text": "Hence, the above three classifications deal with the Descriptive statistics part of EDA. Now we shall move on to the Graphical Method of representing EDA." }, { "code": null, "e": 39259, "s": 39034, "text": "Since we have already checked our data for missing values, blatant errors, and typos, we can now examine our data graphically in order to perform EDA. We will see the graphical representation under the following categories: " }, { "code": null, "e": 39273, "s": 39259, "text": "Distributions" }, { "code": null, "e": 39295, "s": 39273, "text": "Scatter and Line plot" }, { "code": null, "e": 39415, "s": 39295, "text": "Under the Distribution, we shall examine our data using the bar plot, Histogram, Density curve, box plots, and QQplot. " }, { "code": null, "e": 39427, "s": 39415, "text": "Example 1: " }, { "code": null, "e": 39516, "s": 39427, "text": "We shall see how distribution graphs can be used to examine data in EDA in this example." }, { "code": null, "e": 39518, "s": 39516, "text": "R" }, { "code": "# EDA Graphical Method Distributions # loading the required packageslibrary(\"ggplot2\")library(aqp)library(soilDB) # Load from the the loakercreek datasetdata(\"loafercreek\") # Construct generalized horizon designationsn <- c(\"A\", \"BAt\", \"Bt1\", \"Bt2\", \"Cr\", \"R\") # REGEX rulesp <- c(\"A\", \"BA|AB\", \"Bt|Bw\", \"Bt3|Bt4|2B|C\", \"Cr\", \"R\") # Compute genhz labels and add# to loafercreek datasetloafercreek$genhz <- generalize.hz( loafercreek$hzname, n, p) # Extract the horizon tableh <- horizons(loafercreek) # Examine the matching of pairing# of the genhz label to the hznamestable(h$genhz, h$hzname) vars <- c(\"genhz\", \"clay\", \"total_frags_pct\", \"phfield\", \"effclass\")summary(h[, vars]) sort(unique(h$hzname))h$hzname <- ifelse(h$hzname == \"BT\", \"Bt\", h$hzname) # graphs# bar plotggplot(h, aes(x = texcl)) +geom_bar() # histogramggplot(h, aes(x = clay)) + geom_histogram(bins = nclass.Sturges(h$clay)) # density curveggplot(h, aes(x = clay)) + geom_density() # box plotggplot(h, (aes(x = genhz, y = clay))) +geom_boxplot() # QQ Plot for Clayggplot(h, aes(sample = clay)) +geom_qq() +geom_qq_line()", "e": 40666, "s": 39518, "text": null }, { "code": null, "e": 40674, "s": 40666, "text": "Output:" }, { "code": null, "e": 40911, "s": 40674, "text": "Now we will move on to the Scatter and Line plot. In this category, we are going to see two types of plotting,- scatter plot and line plot. Plotting points of one interval or ratio variable against variable are known as a scatter plot. " }, { "code": null, "e": 40922, "s": 40911, "text": "Example 2:" }, { "code": null, "e": 40995, "s": 40922, "text": "We shall now see how to use scatter and line plots to examine our data. " }, { "code": null, "e": 40997, "s": 40995, "text": "R" }, { "code": "# EDA# Graphical Method# Scatter and Line plot # loading the required packageslibrary(\"ggplot2\")library(aqp)library(soilDB) # Load from the the loakercreek datasetdata(\"loafercreek\") # Construct generalized horizon designationsn <- c(\"A\", \"BAt\", \"Bt1\", \"Bt2\", \"Cr\", \"R\") # REGEX rulesp <- c(\"A\", \"BA|AB\", \"Bt|Bw\", \"Bt3|Bt4|2B|C\", \"Cr\", \"R\") # Compute genhz labels and add# to loafercreek datasetloafercreek$genhz <- generalize.hz( loafercreek$hzname, n, p) # Extract the horizon tableh <- horizons(loafercreek) # Examine the matching of pairing# of the genhz label to the hznamestable(h$genhz, h$hzname) vars <- c(\"genhz\", \"clay\", \"total_frags_pct\", \"phfield\", \"effclass\")summary(h[, vars]) sort(unique(h$hzname))h$hzname <- ifelse(h$hzname == \"BT\", \"Bt\", h$hzname) # graph# scatter plotggplot(h, aes(x = clay, y = hzdepm)) + geom_point() + ylim(100, 0) # line plotggplot(h, aes(y = clay, x = hzdepm, group = peiid)) +geom_line() + coord_flip() + xlim(100, 0)", "e": 42034, "s": 40997, "text": null }, { "code": null, "e": 42042, "s": 42034, "text": "Output:" }, { "code": null, "e": 42055, "s": 42042, "text": "simmytarika5" }, { "code": null, "e": 42068, "s": 42055, "text": "kumar_satyam" }, { "code": null, "e": 42081, "s": 42068, "text": "data-science" }, { "code": null, "e": 42100, "s": 42081, "text": "R Machine-Learning" }, { "code": null, "e": 42113, "s": 42100, "text": "R-Statistics" }, { "code": null, "e": 42130, "s": 42113, "text": "Machine Learning" }, { "code": null, "e": 42141, "s": 42130, "text": "R Language" }, { "code": null, "e": 42158, "s": 42141, "text": "Machine Learning" }, { "code": null, "e": 42256, "s": 42158, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42289, "s": 42256, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 42328, "s": 42289, "text": "k-nearest neighbor algorithm in Python" }, { "code": null, "e": 42363, "s": 42328, "text": "Singular Value Decomposition (SVD)" }, { "code": null, "e": 42391, "s": 42363, "text": "Intuition of Adam Optimizer" }, { "code": null, "e": 42429, "s": 42391, "text": "ML | Logistic Regression using Python" }, { "code": null, "e": 42474, "s": 42429, "text": "Change column name of a given DataFrame in R" }, { "code": null, "e": 42532, "s": 42474, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 42584, "s": 42532, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 42616, "s": 42584, "text": "Loops in R (for, while, repeat)" } ]
Python - Replace all occurrences of a substring in a string - GeeksforGeeks
28 Apr, 2020 Sometimes, while working with Python strings, we can have a problem in which we need to replace all occurrences of a substring with other. Input : test_str = “geeksforgeeks”s1 = “geeks”s2 = “abcd”Output : test_str = “abcdsforabcds”Explanation : We replace all occurrences of s1 with s2 in test_str. Input : test_str = “geeksforgeeks”s1 = “for”s2 = “abcd”Output : test_str = “geeksabcdgeeks” We use maketrans() and translate(). This is inbuild way to perform this task. This function maintains the table internally and performs the task of swapping. # Python3 code to demonstrate working of # Swap Binary substring# Using translate() # initializing stringtest_str = "geeksforgeeks" # printing original stringprint("The original string is : " + test_str) # Swap Binary substring# Using translate()temp = str.maketrans("geek", "abcd")test_str = test_str.translate(temp) # printing result print("The string after swap : " + str(test_str)) The original string is : geeksforgeeks The string after swap : accdsforaccds Python string-programs Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Create a Pandas DataFrame from Lists Box Plot in Python using Matplotlib Python Dictionary Bar Plot in Matplotlib Enumerate() in Python Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Graph Plotting in Python | Set 1 Python - Call function from another file
[ { "code": null, "e": 24550, "s": 24522, "text": "\n28 Apr, 2020" }, { "code": null, "e": 24689, "s": 24550, "text": "Sometimes, while working with Python strings, we can have a problem in which we need to replace all occurrences of a substring with other." }, { "code": null, "e": 24849, "s": 24689, "text": "Input : test_str = “geeksforgeeks”s1 = “geeks”s2 = “abcd”Output : test_str = “abcdsforabcds”Explanation : We replace all occurrences of s1 with s2 in test_str." }, { "code": null, "e": 24941, "s": 24849, "text": "Input : test_str = “geeksforgeeks”s1 = “for”s2 = “abcd”Output : test_str = “geeksabcdgeeks”" }, { "code": null, "e": 25099, "s": 24941, "text": "We use maketrans() and translate(). This is inbuild way to perform this task. This function maintains the table internally and performs the task of swapping." }, { "code": "# Python3 code to demonstrate working of # Swap Binary substring# Using translate() # initializing stringtest_str = \"geeksforgeeks\" # printing original stringprint(\"The original string is : \" + test_str) # Swap Binary substring# Using translate()temp = str.maketrans(\"geek\", \"abcd\")test_str = test_str.translate(temp) # printing result print(\"The string after swap : \" + str(test_str)) ", "e": 25490, "s": 25099, "text": null }, { "code": null, "e": 25568, "s": 25490, "text": "The original string is : geeksforgeeks\nThe string after swap : accdsforaccds\n" }, { "code": null, "e": 25591, "s": 25568, "text": "Python string-programs" }, { "code": null, "e": 25598, "s": 25591, "text": "Python" }, { "code": null, "e": 25696, "s": 25598, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25705, "s": 25696, "text": "Comments" }, { "code": null, "e": 25718, "s": 25705, "text": "Old Comments" }, { "code": null, "e": 25755, "s": 25718, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25791, "s": 25755, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25809, "s": 25791, "text": "Python Dictionary" }, { "code": null, "e": 25832, "s": 25809, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25854, "s": 25832, "text": "Enumerate() in Python" }, { "code": null, "e": 25893, "s": 25854, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25926, "s": 25893, "text": "Python | Convert set into a list" }, { "code": null, "e": 25975, "s": 25926, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 26008, "s": 25975, "text": "Graph Plotting in Python | Set 1" } ]
How to list images in Docker?
Docker provides a plethora of useful Docker commands that will help you to create, manipulate, and manage Docker objects such as volumes, images, containers, networks, etc. If you have been working with Docker for a long time now, you might have several Docker images already in your machine. Keeping track of all these images becomes quite difficult especially through a single command line. However, you can list all Docker images along with filtered outputs to get your desired results. In this article, we will discuss how to use different commands along with multiple options to list all Docker images in our host machine. There are two major commands that can be used interchangeably to list Docker images and both of them provide the same results. The syntaxes of both these commands are mentioned below. $ docker image ls [OPTIONS] [REPOSITORY[:TAG]] You can use multiple options along with this command. These are - --digests - It is used to print the digests of the images. --filter - You can use this option to filter your output. --format - You can pretty-print output using a Go template. --no-trunc - You can use this to avoid output truncate. --quiet - Display only IDs of images. --all - You can list intermediate images using this option. Another command to achieve the same result is - $ docker images Let’s discuss a few examples to modify your result output. If you want to list only those images that belong to a particular repository, you can use the following command. $ docker images <repository-name>:<tag-name> For example, if you want to list all the nginx images, you can use the following command. $ docker images nginx You can also provide the tag name along with the name of the image repository. $ docker images nginx:latest If you see the results carefully, you will find that the Docker images list command displays the image list by truncating the IDs of the images. If you want to override this default behaviour, you can use the --no-trunc option. Let’s see how to do so. $ docker images --no-trunc If you want to list the digests of the images as well, you can simply use the --digests option along with the Docker images command. Image digests are unique IDs given to each tagged image that is often used to check for similar images. $ docker images --digests If you want to list all the dangling or untagged images, you can use the --filter option to do so. You need to provide appropriate key-value pairs. Some examples of filters that you can provide are - label, dangling, before, since, and reference. Let’s see how to list all the dangling images. $ docker images --filter "dangling=true" If you want to filter all those images that were created before a particular image, you can use the before filter. $ docker images --filter "before=fedora" The above command will display a list of all images that were created before the fedora image in your host machine. To list images that were created after a particular image, you can use the since filter. $ docker images --filter "since=fedora" You can also use the reference option to list images matching a particular pattern. For example, if you want to list all images starting with the letter m, you can use the following command. $ docker images --filter=reference='m*' To list all the images including intermediate and dangling ones, you can use the --all option. $ docker images --all If you want to print only the IDs of the images, you can use the --quiet option. $ docker images --quiet You can also use the --format option to pretty-print the output using a Go template. Let’s see how to do so. $ docker images --format "The Image ID for the image is {{.ID}} belonging to {{.Repository}}" Other placeholders that you can use are tag, ID, digest, size, createdat, createdsince, etc. To sum up, in this article we discussed how to use two different commands to list all the Docker images in your host machine. We saw how to use several different options to format the output according to our requirements. We looked at multiple options such as quiet, all, digest, format, filter, etc. We certainly hope that you will now be able to use the Docker image list command in the most precise manner to get accurate results.
[ { "code": null, "e": 1455, "s": 1062, "text": "Docker provides a plethora of useful Docker commands that will help you to create, manipulate, and manage Docker objects such as volumes, images, containers, networks, etc. If you have been working with Docker for a long time now, you might have several Docker images already in your machine. Keeping track of all these images becomes quite difficult especially through a single command line." }, { "code": null, "e": 1690, "s": 1455, "text": "However, you can list all Docker images along with filtered outputs to get your desired results. In this article, we will discuss how to use different commands along with multiple options to list all Docker images in our host machine." }, { "code": null, "e": 1874, "s": 1690, "text": "There are two major commands that can be used interchangeably to list Docker images and both of them provide the same results. The syntaxes of both these commands are mentioned below." }, { "code": null, "e": 1921, "s": 1874, "text": "$ docker image ls [OPTIONS] [REPOSITORY[:TAG]]" }, { "code": null, "e": 1987, "s": 1921, "text": "You can use multiple options along with this command. These are -" }, { "code": null, "e": 2046, "s": 1987, "text": "--digests - It is used to print the digests of the images." }, { "code": null, "e": 2104, "s": 2046, "text": "--filter - You can use this option to filter your output." }, { "code": null, "e": 2164, "s": 2104, "text": "--format - You can pretty-print output using a Go template." }, { "code": null, "e": 2220, "s": 2164, "text": "--no-trunc - You can use this to avoid output truncate." }, { "code": null, "e": 2258, "s": 2220, "text": "--quiet - Display only IDs of images." }, { "code": null, "e": 2318, "s": 2258, "text": "--all - You can list intermediate images using this option." }, { "code": null, "e": 2366, "s": 2318, "text": "Another command to achieve the same result is -" }, { "code": null, "e": 2382, "s": 2366, "text": "$ docker images" }, { "code": null, "e": 2441, "s": 2382, "text": "Let’s discuss a few examples to modify your result output." }, { "code": null, "e": 2554, "s": 2441, "text": "If you want to list only those images that belong to a particular repository, you can use the following command." }, { "code": null, "e": 2599, "s": 2554, "text": "$ docker images <repository-name>:<tag-name>" }, { "code": null, "e": 2689, "s": 2599, "text": "For example, if you want to list all the nginx images, you can use the following command." }, { "code": null, "e": 2711, "s": 2689, "text": "$ docker images nginx" }, { "code": null, "e": 2790, "s": 2711, "text": "You can also provide the tag name along with the name of the image repository." }, { "code": null, "e": 2819, "s": 2790, "text": "$ docker images nginx:latest" }, { "code": null, "e": 3071, "s": 2819, "text": "If you see the results carefully, you will find that the Docker images list command displays the image list by truncating the IDs of the images. If you want to override this default behaviour, you can use the --no-trunc option. Let’s see how to do so." }, { "code": null, "e": 3098, "s": 3071, "text": "$ docker images --no-trunc" }, { "code": null, "e": 3335, "s": 3098, "text": "If you want to list the digests of the images as well, you can simply use the --digests option along with the Docker images command. Image digests are unique IDs given to each tagged image that is often used to check for similar images." }, { "code": null, "e": 3362, "s": 3335, "text": "$ docker images --digests\n" }, { "code": null, "e": 3656, "s": 3362, "text": "If you want to list all the dangling or untagged images, you can use the --filter option to do so. You need to provide appropriate key-value pairs. Some examples of filters that you can provide are - label, dangling, before, since, and reference. Let’s see how to list all the dangling images." }, { "code": null, "e": 3697, "s": 3656, "text": "$ docker images --filter \"dangling=true\"" }, { "code": null, "e": 3812, "s": 3697, "text": "If you want to filter all those images that were created before a particular image, you can use the before filter." }, { "code": null, "e": 3853, "s": 3812, "text": "$ docker images --filter \"before=fedora\"" }, { "code": null, "e": 4058, "s": 3853, "text": "The above command will display a list of all images that were created before the fedora image in your host machine. To list images that were created after a particular image, you can use the since filter." }, { "code": null, "e": 4098, "s": 4058, "text": "$ docker images --filter \"since=fedora\"" }, { "code": null, "e": 4289, "s": 4098, "text": "You can also use the reference option to list images matching a particular pattern. For example, if you want to list all images starting with the letter m, you can use the following command." }, { "code": null, "e": 4330, "s": 4289, "text": "$ docker images --filter=reference='m*'\n" }, { "code": null, "e": 4425, "s": 4330, "text": "To list all the images including intermediate and dangling ones, you can use the --all option." }, { "code": null, "e": 4447, "s": 4425, "text": "$ docker images --all" }, { "code": null, "e": 4528, "s": 4447, "text": "If you want to print only the IDs of the images, you can use the --quiet option." }, { "code": null, "e": 4552, "s": 4528, "text": "$ docker images --quiet" }, { "code": null, "e": 4661, "s": 4552, "text": "You can also use the --format option to pretty-print the output using a Go template. Let’s see how to do so." }, { "code": null, "e": 4755, "s": 4661, "text": "$ docker images --format \"The Image ID for the image is {{.ID}} belonging to {{.Repository}}\"" }, { "code": null, "e": 4848, "s": 4755, "text": "Other placeholders that you can use are tag, ID, digest, size, createdat, createdsince, etc." }, { "code": null, "e": 5282, "s": 4848, "text": "To sum up, in this article we discussed how to use two different commands to list all the Docker images in your host machine. We saw how to use several different options to format the output according to our requirements. We looked at multiple options such as quiet, all, digest, format, filter, etc. We certainly hope that you will now be able to use the Docker image list command in the most precise manner to get accurate results." } ]
An Overview of Deep Learning — from History to Fundamentals | by Pedram Ataee, PhD | Towards Data Science
I recently taught a mini-course on Machine Learning 101 for those who want to become data scientists. One of its modules was about Deep Learning. I found that many newbies are confused with this topic mostly because it is often taught with many complexities. In this article, I aim to describe it simple enough but not too simple. Hope it helps! The article has 4 sections as follow: What is Neural Network? What is Deep Learning? How to build a simple deep learning architecture? How to train a deep learning model? A neural network is a computational model inspired by the biological neural network that processes information in the human brain. A neural network consists of a set of artificial neurons organized in layers (input, hidden, and output). These artificial neurons are connected by synapses that are just weighted values. An artificial neuron is a computing element with a specific mathematical operation. A neuron takes its input (boolean or real) and, after applying the pre-defined operation on the input, passes the result through an activation function to the other neurons. The activation function is the part of each node that turns a linear function into a non-linear function. Basically, it decides whether a neuron should fire or not. The activation function can be different mathematical functions such as Step, Sigmoid, and ReLU. A common neuron (a.k.a., a perceptron neuron) takes inputs, including a bias, and multiplies them by associated weights, and then passes the sum through the step function. Training a neural network refers to a process that calculates (or, finds) the weights in the network to minimize the objective function (or, loss function). You can think of weights in the neural network as parameters in a polynomial function such as ax^2+b*x+c with two main differences. The neural network is a polynomial function with a high degree and potentially nonlinear performance. Here, a high degree means the number of parameters can exceed millions when needed. There are various algorithms to train a neural network, and backward propagation (backpropagation) is one of them. In short, backpropagation is an algorithm that uses the gradient descent technique to calculate weights in a neural network during the training stage. In this method, the errors of outputs in comparison to the desired values are computed and proportionally (i.e., based on the current weights) propagated in a backward direction to update the network weights. The network weights are iteratively updated based on a learning rate until convergence. I recommend watching the video to learn more about this method. The 3Blue1Brown YouTube channel has one of the best visualizations to describe this topic. To train a neural network, you must know the answers to the questions below. You may not understand their importance until start implementing a sample project. How to initialize weights? What are the stopping criteria? What if the algorithm doesn’t converge? Does adding complexity to the network help? One last thing. If you want to find out how the configuration parameters such as learning rate, activation function, or architecture affect the outcome of a neural network, I highly recommend checking the interactive demo named Playground created by TensorFlow. It is so beautiful and insightful! playground.tensorflow.org Deep learning is a series of machine learning methods based on special architectures of deep neural networks (neural networks with many hidden layers) that can conduct both feature extraction and classification in unison and with little human effort. The special architectures are more advanced than layers in neural networks that are simply fully connected. The special architectures are mostly built upon a concept named “capsule”. A capsule is a group of neurons in each layer that do a lot of internal computation and output a compact result representing a property of data such as Convolution. You can read more about the Convolutional Neural Network AlphaGo project created by Deepmind is one of the success stories of deep learning. As stated by Deepmind: “AlphaGo is the first computer program to defeat a Go world champion”. First, let me describe why Go is special. Go is the most challenging classic game to be targeted by artificial intelligence. Why? Mostly due to the number of moves a player can choose. According to this article, after the first 2 moves, there are about 130,000 moves in Go. This number is at 400 possible moves in chess. You can see that the search space in Go is unarguably vast. Deep learning can be a good choice when the search space is drastically vast. Another reason why deep learning is the right method to target the Go is rooted in how Go is being played. If you ask Go players how they decide on a move, they often tell you it just felt right. In these sorts of scenarios when you can not define features, you can not use classical machine learning algorithms. Deep learning can be a good choice when is not feasible to determine a useful feature set. A convolutional neural network (or, CNN) is a class of deep learning architectures commonly used to analyze images such as image classification, object detection, and video action recognition. In general, the convolutional neural network is designed to be used with any data that has some spatial invariance in its structure such as face or speech recognition. Spatial-invariance means that, for example, a cat ear in the top left of the image has the same features like a cat ear in the bottom right of the image. CNNs are built upon two main building blocks described below. Convolution — CNNs are spatially invariant since they are built upon the convolution operator. Convolution is a mathematical operation that does the integral of the product of two functions (signals), with one of the signals flipped (if needed). In the past, convolution operators have been used, for example, to compute the correlation between two signals or find patterns in signals. This operator functions well for feature extraction in visual data. Much of the progress made in computer vision over the past few years is due in part to convolutional neural networks. Pooling — Another building block in CNNs is a pooling layer. Its function is to progressively reduce the spatial size of the data to reduce the network size and the algorithm sensitivity to the precise position of the feature in the input. The network size translates to the number of weights that must be calculated during the training phase. You sometimes also need to add extra pixels with pixel_intensity=0 around the boundary of the input images to increase the effective size. That helps to keep image size fixed after applying convolutional layers. This process is called padding. AlexNet —AlexNet is a successful implementation of convolutional neural networks that won the ImageNet Large Scale Visual Recognition Challenge (ILSVRC) in 2012. The architecture has been published in NeurIPS 2012 by Alex Krizhevsky, Ilya Sutskever, Geoffrey Hinton (Figure 2). In this architecture, the input is an RGB image of size 256×256 which were randomly cropped into size 224×224. The architecture contains 650,000 neurons and 60 million parameters. Plus, it took 5-6 days to train on two GTX 580 3GB GPUs. It consists of 5 Convolutional Layers and 3 Fully Connected Layers. They used Rectified Linear Units (ReLUs) as activation functions for the first time. VGG16 — A standard way to improve the performance of deep neural networks is by increasing the depth. VGG-16 was invented by folks at Visual Geometry Group at the University of Oxford. This architecture has 13 convolutional and 3 fully-connected layers. They also used the ReLU activation function as the tradition carrying over from AlexNet. This network stacks more layers compared to AlexNet and uses smaller size filters (2×2 and 3×3). It consists of 138M parameters. towardsdatascience.com ResNet50 — With the network depth increasing, accuracy gets saturated and then degrades rapidly mostly due to the fact that we can not train it properly. Microsoft Research addressed this problem with ResNet50 — using skip (or, shortcut) connections, while building deeper models. A deeper CNNs (up to 152 layers) without compromising model generalization. This is a great idea .... Keras is a high-level neural-networks library with a Python interface that can be run on top of major scientific computing frameworks such as TensorFlow (created by Google) or CNTK (created by Microsoft). Engineers often prefer Keras providing fast development compared to Pytorch. You can find how to build a VGG-like convolutional neural network using Kears below. To learn more about how to build a deep learning model using Keras, you can check out the original documentation. from keras.models import Sequentialfrom keras.layers import Dense, Dropout, Flattenfrom keras.layers import Conv2D, MaxPooling2Dfrom keras.optimizers import SGDmodel = Sequential()model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))model.add(Conv2D(32, (3, 3), activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Conv2D(64, (3, 3), activation='relu'))model.add(Conv2D(64, (3, 3), activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Flatten())model.add(Dense(256, activation='relu'))model.add(Dropout(0.5))model.add(Dense(10, activation='softmax'))sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)model.compile(loss='categorical_crossentropy', optimizer=sgd)model.fit(x_train, y_train, batch_size=32, epochs=10) PyTorch is a python-based, low-level neural-networks library built upon Facebook scientific computing framework (Torch). Its workflow is similar to Python scientific computing library (Numpy). Pytorch is highly configurable and is more popular among researchers compared to developers who don’t need complex architecture or special layer operations. You can find how to build a convolutional neural network using PyTorch below. To learn more about how to build a deep learning model using PyTorch, you can check out the original documentation. import torch.nn as nnimport torch.nn.functional as Fclass Net(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = torch.flatten(x, 1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return xnet = Net() It is impossible to explain everything about training a neural network in this article. Here, I want to shed light on the most important topics. As described above, training a neural network refers to a process that calculates the weights in the network to minimize the objective function. This is a classical optimization problem where you must search for the optimum set of weights (or, parameters) that minimize the loss function. The efficacy of the search method determines the speed and outcome of the training process. Food For Thought — In machine learning algorithms, we choose a metric (e.g., accuracy) to evaluate a model; however, we optimize a different objective function and “hope” that minimizing its value will improve metric we care about. So, what can we do to ensure reaching to the desired requirements? In general, to implement a search method, you must have answers to the following questions: (1) “How to determine the search direction?”, and (2) “How to determine the search step?”. As described above, the gradient descent technique has been used in the training of neural networks to guide the search process. The search direction is determined by the gradient operator and the search step is determined by a hyperparameter λ that is also called the learning rate. In short, the update mechanism in the gradient descent technique is as follows: xm=xn -λ*∇f(xn). The classic gradient descent techniques can not be simply used for deep learning techniques where a much higher number of weights (parameters) and a number of data points often exist. ⛔ 🚀Stochastic gradient descent (SGD) is a variation of the gradient descent technique that is more efficient for deep learning models. This method calculates the error and updates the model for each data point in the training dataset in contrary to computing error using batch data. The SGD is fast in search and offers more frequent model updates. On the other hand, the SGD results are different in each run and it has slower convergence in comparison to the standard technique. Instead of using only the gradient of the current step to guide the search, we can use the gradient of the past steps knowing that the most recent ones are more important. This is called Momentum in the optimization context. Therefore, we can, for example, use an exponential average of the gradient steps to have a more efficient search process. Check out the article below to learn more about Momentum. distill.pub We have other techniques to solve the optimization problem such as AdaGrad or Adam (Adaptive Moment Estimation). These methods are variations of gradient descent optimization that adaptively change the learning rate to ensure having a more efficient search process. In simple words, the learning rate or search step can be different for each direction in the search space as well as at each moment in time. You can read more here. If you want to learn how to use these techniques in the real world, you can take a look at the Keras official documentation. If you like this post and want to support me... Follow me on Medium! Check out my books on Amazon! Become a member on Medium! Connect on Linkedin! Follow me on Twitter!
[ { "code": null, "e": 518, "s": 172, "text": "I recently taught a mini-course on Machine Learning 101 for those who want to become data scientists. One of its modules was about Deep Learning. I found that many newbies are confused with this topic mostly because it is often taught with many complexities. In this article, I aim to describe it simple enough but not too simple. Hope it helps!" }, { "code": null, "e": 556, "s": 518, "text": "The article has 4 sections as follow:" }, { "code": null, "e": 580, "s": 556, "text": "What is Neural Network?" }, { "code": null, "e": 603, "s": 580, "text": "What is Deep Learning?" }, { "code": null, "e": 653, "s": 603, "text": "How to build a simple deep learning architecture?" }, { "code": null, "e": 689, "s": 653, "text": "How to train a deep learning model?" }, { "code": null, "e": 1008, "s": 689, "text": "A neural network is a computational model inspired by the biological neural network that processes information in the human brain. A neural network consists of a set of artificial neurons organized in layers (input, hidden, and output). These artificial neurons are connected by synapses that are just weighted values." }, { "code": null, "e": 1528, "s": 1008, "text": "An artificial neuron is a computing element with a specific mathematical operation. A neuron takes its input (boolean or real) and, after applying the pre-defined operation on the input, passes the result through an activation function to the other neurons. The activation function is the part of each node that turns a linear function into a non-linear function. Basically, it decides whether a neuron should fire or not. The activation function can be different mathematical functions such as Step, Sigmoid, and ReLU." }, { "code": null, "e": 1700, "s": 1528, "text": "A common neuron (a.k.a., a perceptron neuron) takes inputs, including a bias, and multiplies them by associated weights, and then passes the sum through the step function." }, { "code": null, "e": 2175, "s": 1700, "text": "Training a neural network refers to a process that calculates (or, finds) the weights in the network to minimize the objective function (or, loss function). You can think of weights in the neural network as parameters in a polynomial function such as ax^2+b*x+c with two main differences. The neural network is a polynomial function with a high degree and potentially nonlinear performance. Here, a high degree means the number of parameters can exceed millions when needed." }, { "code": null, "e": 2738, "s": 2175, "text": "There are various algorithms to train a neural network, and backward propagation (backpropagation) is one of them. In short, backpropagation is an algorithm that uses the gradient descent technique to calculate weights in a neural network during the training stage. In this method, the errors of outputs in comparison to the desired values are computed and proportionally (i.e., based on the current weights) propagated in a backward direction to update the network weights. The network weights are iteratively updated based on a learning rate until convergence." }, { "code": null, "e": 2893, "s": 2738, "text": "I recommend watching the video to learn more about this method. The 3Blue1Brown YouTube channel has one of the best visualizations to describe this topic." }, { "code": null, "e": 3053, "s": 2893, "text": "To train a neural network, you must know the answers to the questions below. You may not understand their importance until start implementing a sample project." }, { "code": null, "e": 3080, "s": 3053, "text": "How to initialize weights?" }, { "code": null, "e": 3112, "s": 3080, "text": "What are the stopping criteria?" }, { "code": null, "e": 3152, "s": 3112, "text": "What if the algorithm doesn’t converge?" }, { "code": null, "e": 3196, "s": 3152, "text": "Does adding complexity to the network help?" }, { "code": null, "e": 3493, "s": 3196, "text": "One last thing. If you want to find out how the configuration parameters such as learning rate, activation function, or architecture affect the outcome of a neural network, I highly recommend checking the interactive demo named Playground created by TensorFlow. It is so beautiful and insightful!" }, { "code": null, "e": 3519, "s": 3493, "text": "playground.tensorflow.org" }, { "code": null, "e": 4175, "s": 3519, "text": "Deep learning is a series of machine learning methods based on special architectures of deep neural networks (neural networks with many hidden layers) that can conduct both feature extraction and classification in unison and with little human effort. The special architectures are more advanced than layers in neural networks that are simply fully connected. The special architectures are mostly built upon a concept named “capsule”. A capsule is a group of neurons in each layer that do a lot of internal computation and output a compact result representing a property of data such as Convolution. You can read more about the Convolutional Neural Network" }, { "code": null, "e": 4395, "s": 4175, "text": "AlphaGo project created by Deepmind is one of the success stories of deep learning. As stated by Deepmind: “AlphaGo is the first computer program to defeat a Go world champion”. First, let me describe why Go is special." }, { "code": null, "e": 4812, "s": 4395, "text": "Go is the most challenging classic game to be targeted by artificial intelligence. Why? Mostly due to the number of moves a player can choose. According to this article, after the first 2 moves, there are about 130,000 moves in Go. This number is at 400 possible moves in chess. You can see that the search space in Go is unarguably vast. Deep learning can be a good choice when the search space is drastically vast." }, { "code": null, "e": 5216, "s": 4812, "text": "Another reason why deep learning is the right method to target the Go is rooted in how Go is being played. If you ask Go players how they decide on a move, they often tell you it just felt right. In these sorts of scenarios when you can not define features, you can not use classical machine learning algorithms. Deep learning can be a good choice when is not feasible to determine a useful feature set." }, { "code": null, "e": 5793, "s": 5216, "text": "A convolutional neural network (or, CNN) is a class of deep learning architectures commonly used to analyze images such as image classification, object detection, and video action recognition. In general, the convolutional neural network is designed to be used with any data that has some spatial invariance in its structure such as face or speech recognition. Spatial-invariance means that, for example, a cat ear in the top left of the image has the same features like a cat ear in the bottom right of the image. CNNs are built upon two main building blocks described below." }, { "code": null, "e": 6365, "s": 5793, "text": "Convolution — CNNs are spatially invariant since they are built upon the convolution operator. Convolution is a mathematical operation that does the integral of the product of two functions (signals), with one of the signals flipped (if needed). In the past, convolution operators have been used, for example, to compute the correlation between two signals or find patterns in signals. This operator functions well for feature extraction in visual data. Much of the progress made in computer vision over the past few years is due in part to convolutional neural networks." }, { "code": null, "e": 6709, "s": 6365, "text": "Pooling — Another building block in CNNs is a pooling layer. Its function is to progressively reduce the spatial size of the data to reduce the network size and the algorithm sensitivity to the precise position of the feature in the input. The network size translates to the number of weights that must be calculated during the training phase." }, { "code": null, "e": 6953, "s": 6709, "text": "You sometimes also need to add extra pixels with pixel_intensity=0 around the boundary of the input images to increase the effective size. That helps to keep image size fixed after applying convolutional layers. This process is called padding." }, { "code": null, "e": 7621, "s": 6953, "text": "AlexNet —AlexNet is a successful implementation of convolutional neural networks that won the ImageNet Large Scale Visual Recognition Challenge (ILSVRC) in 2012. The architecture has been published in NeurIPS 2012 by Alex Krizhevsky, Ilya Sutskever, Geoffrey Hinton (Figure 2). In this architecture, the input is an RGB image of size 256×256 which were randomly cropped into size 224×224. The architecture contains 650,000 neurons and 60 million parameters. Plus, it took 5-6 days to train on two GTX 580 3GB GPUs. It consists of 5 Convolutional Layers and 3 Fully Connected Layers. They used Rectified Linear Units (ReLUs) as activation functions for the first time." }, { "code": null, "e": 8093, "s": 7621, "text": "VGG16 — A standard way to improve the performance of deep neural networks is by increasing the depth. VGG-16 was invented by folks at Visual Geometry Group at the University of Oxford. This architecture has 13 convolutional and 3 fully-connected layers. They also used the ReLU activation function as the tradition carrying over from AlexNet. This network stacks more layers compared to AlexNet and uses smaller size filters (2×2 and 3×3). It consists of 138M parameters." }, { "code": null, "e": 8116, "s": 8093, "text": "towardsdatascience.com" }, { "code": null, "e": 8499, "s": 8116, "text": "ResNet50 — With the network depth increasing, accuracy gets saturated and then degrades rapidly mostly due to the fact that we can not train it properly. Microsoft Research addressed this problem with ResNet50 — using skip (or, shortcut) connections, while building deeper models. A deeper CNNs (up to 152 layers) without compromising model generalization. This is a great idea ...." }, { "code": null, "e": 8980, "s": 8499, "text": "Keras is a high-level neural-networks library with a Python interface that can be run on top of major scientific computing frameworks such as TensorFlow (created by Google) or CNTK (created by Microsoft). Engineers often prefer Keras providing fast development compared to Pytorch. You can find how to build a VGG-like convolutional neural network using Kears below. To learn more about how to build a deep learning model using Keras, you can check out the original documentation." }, { "code": null, "e": 9808, "s": 8980, "text": "from keras.models import Sequentialfrom keras.layers import Dense, Dropout, Flattenfrom keras.layers import Conv2D, MaxPooling2Dfrom keras.optimizers import SGDmodel = Sequential()model.add(Conv2D(32, (3, 3), activation='relu', input_shape=(100, 100, 3)))model.add(Conv2D(32, (3, 3), activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Conv2D(64, (3, 3), activation='relu'))model.add(Conv2D(64, (3, 3), activation='relu'))model.add(MaxPooling2D(pool_size=(2, 2)))model.add(Dropout(0.25))model.add(Flatten())model.add(Dense(256, activation='relu'))model.add(Dropout(0.5))model.add(Dense(10, activation='softmax'))sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True)model.compile(loss='categorical_crossentropy', optimizer=sgd)model.fit(x_train, y_train, batch_size=32, epochs=10)" }, { "code": null, "e": 10352, "s": 9808, "text": "PyTorch is a python-based, low-level neural-networks library built upon Facebook scientific computing framework (Torch). Its workflow is similar to Python scientific computing library (Numpy). Pytorch is highly configurable and is more popular among researchers compared to developers who don’t need complex architecture or special layer operations. You can find how to build a convolutional neural network using PyTorch below. To learn more about how to build a deep learning model using PyTorch, you can check out the original documentation." }, { "code": null, "e": 10967, "s": 10352, "text": "import torch.nn as nnimport torch.nn.functional as Fclass Net(nn.Module): def __init__(self): super().__init__() self.conv1 = nn.Conv2d(3, 6, 5) self.pool = nn.MaxPool2d(2, 2) self.conv2 = nn.Conv2d(6, 16, 5) self.fc1 = nn.Linear(16 * 5 * 5, 120) self.fc2 = nn.Linear(120, 84) self.fc3 = nn.Linear(84, 10) def forward(self, x): x = self.pool(F.relu(self.conv1(x))) x = self.pool(F.relu(self.conv2(x))) x = torch.flatten(x, 1) x = F.relu(self.fc1(x)) x = F.relu(self.fc2(x)) x = self.fc3(x) return xnet = Net()" }, { "code": null, "e": 11112, "s": 10967, "text": "It is impossible to explain everything about training a neural network in this article. Here, I want to shed light on the most important topics." }, { "code": null, "e": 11493, "s": 11112, "text": "As described above, training a neural network refers to a process that calculates the weights in the network to minimize the objective function. This is a classical optimization problem where you must search for the optimum set of weights (or, parameters) that minimize the loss function. The efficacy of the search method determines the speed and outcome of the training process." }, { "code": null, "e": 11792, "s": 11493, "text": "Food For Thought — In machine learning algorithms, we choose a metric (e.g., accuracy) to evaluate a model; however, we optimize a different objective function and “hope” that minimizing its value will improve metric we care about. So, what can we do to ensure reaching to the desired requirements?" }, { "code": null, "e": 11975, "s": 11792, "text": "In general, to implement a search method, you must have answers to the following questions: (1) “How to determine the search direction?”, and (2) “How to determine the search step?”." }, { "code": null, "e": 12542, "s": 11975, "text": "As described above, the gradient descent technique has been used in the training of neural networks to guide the search process. The search direction is determined by the gradient operator and the search step is determined by a hyperparameter λ that is also called the learning rate. In short, the update mechanism in the gradient descent technique is as follows: xm=xn -λ*∇f(xn). The classic gradient descent techniques can not be simply used for deep learning techniques where a much higher number of weights (parameters) and a number of data points often exist. ⛔" }, { "code": null, "e": 13021, "s": 12542, "text": "🚀Stochastic gradient descent (SGD) is a variation of the gradient descent technique that is more efficient for deep learning models. This method calculates the error and updates the model for each data point in the training dataset in contrary to computing error using batch data. The SGD is fast in search and offers more frequent model updates. On the other hand, the SGD results are different in each run and it has slower convergence in comparison to the standard technique." }, { "code": null, "e": 13426, "s": 13021, "text": "Instead of using only the gradient of the current step to guide the search, we can use the gradient of the past steps knowing that the most recent ones are more important. This is called Momentum in the optimization context. Therefore, we can, for example, use an exponential average of the gradient steps to have a more efficient search process. Check out the article below to learn more about Momentum." }, { "code": null, "e": 13438, "s": 13426, "text": "distill.pub" }, { "code": null, "e": 13994, "s": 13438, "text": "We have other techniques to solve the optimization problem such as AdaGrad or Adam (Adaptive Moment Estimation). These methods are variations of gradient descent optimization that adaptively change the learning rate to ensure having a more efficient search process. In simple words, the learning rate or search step can be different for each direction in the search space as well as at each moment in time. You can read more here. If you want to learn how to use these techniques in the real world, you can take a look at the Keras official documentation." }, { "code": null, "e": 14042, "s": 13994, "text": "If you like this post and want to support me..." }, { "code": null, "e": 14063, "s": 14042, "text": "Follow me on Medium!" }, { "code": null, "e": 14093, "s": 14063, "text": "Check out my books on Amazon!" }, { "code": null, "e": 14120, "s": 14093, "text": "Become a member on Medium!" }, { "code": null, "e": 14141, "s": 14120, "text": "Connect on Linkedin!" } ]
Super Simple Way to Scrape BBC News Articles in Python | by Petur Einarsson | Towards Data Science
I work in London as a Data Scientist for a consultancy. This effectively means I work for multiple companies, doing different Data Science stuff. Mostly I build Machine Learning solutions in the Cloud. Sometimes general Data Solutions, Dashboards or recommending Data Science best practises. Recently though, it's been mostly NLP or Computer Vision. But enough about me. If you are into Data Science, Machine Learning or Big Data, there’s a good chance you’ve had to collect data from a website. For small projects or Proof-of-Concepts (PoC), doing this by hand is fine. Other times, this is best done in code. This is where Python shines, with many open-source libraries to interact with various websites. Knowing how to wield any scraping library, is a very useful skill. Well worth the investment 💰 The secret is that it’s easy to scrape websites Together, we’ll build a simple Python class that scrapes the BBC. Ps: If you only opened the article for the final code, feel free to skip to the end where it’s all laid out. BeautifulSoup is my all-time favourite way to scrape websites. It’s simple to learn and easy to use. Plus there’s something comical about imagining fishing the good bits out of soup when web scraping! To get started, install the library into your environment using the command line. As a Data Scientist, I usually use Anaconda. We will also need the requests module to get the HTML code from the BBC. Run these in your terminal: conda install beautifulsoup4 requests -y You can also use pip if you prefer. pip install beautifulsoup4 requests Once installed, create a python file (.py) and import the libraries at the top of your code. I recommend using PyCharm, but if you are just starting, Jupyter Notebooks are a great way to get your feet wet. import requestsfrom bs4 import BeautifulSoup as bs We are mostly concerned with the two find functions. They allow us to find any HTML element in our soup, just by specifying its name. find(element_tag, attribute) #return first matching itemfind_all(element_tag, attribute) #return list of matching items Always use a python environment to manage your projects Let’s pick a BBC article to work with. I’ve chosen one where Iceland is commemorating the loss of its first glacier to climate change. Access the raw article via Python: url = 'https://www.bbc.co.uk/news/world-europe-49345912'article = requests.get(url) Then pass the article content over to BeautifulSoup and specify the HTML parser. soup = bs(article.content, 'html.parser') Simple as that and the soup is ready! Let’s fish out the good bits 🎣 The next step is manually inspecting the HTML of the page to find the element we are interested in. I’m using Chrome for this bit, but you can use any browser. Open the webpage in your browser, right-click and ‘inspect’. Hover the mouse over any of the text, and the browser will tell you in which div that paragraph is in. If it’s not working, press Ctrl+ Shift+ C or CMD + shift + C and try again. In this case, “story-body__introduction” contains the highlighted paragraph. The div class “story-body__inner” with the property “articleBody” contains the entire article, and that is what we are after. Find the body in the soup: body = soup.find(property='articleBody') This gives us the content of the page as a list of paragraphs (p) in raw HTML format. Access the text of each paragraph and assign it to a new list using list comprehension: text = [p.text for p in body.find_all('p') We can combine the above in a single function, that takes in the URL of a BBC article: If we wanted to access the title, we again inspect the site, find the div that the title is in, and fish it out of the soup. This is how that code would look like: More experienced coders probably already see the issue with these functions... They are the same for the most part. That’s not very DRY. One way is to refactor them into 3 functions instead and put get_soup in its own function. However, that would mean if we wanted to access both the title and the body, we’d have to download the BBC article twice! This feels like it should be a class instead. Plus, classes look and feel more professional instead of calling functions within functions. They also make it easier to maintain, when the scraper grows in complexity. As the great coders we are, let’s turn it into a class! Start by defining the class. Every class should have an __init__ function, where you pass it any variables to initialise the functions. The __init__ function is called automatically when you call the class. Each function in the class also needs to have self as the first argument. This is the actual instance of that particular class. class BBC: def __init__(self): pass Next, add URL as an argument in __init__, and turn it into a soup. Changes are highlighted in bold. class BBC: def __init__(self, url): article = requests.get(url) self.soup = bs(article.content, "html.parser") Writing the soup variable as self.soup makes it an attribute of that class. Class attributes can be accessed anywhere within a class, within any function. To access the body of the article, we use the body function from before. body is now also an attribute of the class class BBC: def __init__(self, url): article = requests.get(url) self.soup = bs(article.content, "html.parser") self.body = self.get_body() def get_body(self) -> list: body = self.soup.find(property="articleBody") return [p.text for p in body.find_all("p")] Same with the title: class BBC: def __init__(self, url): article = requests.get(url) self.soup = bs(article.content, "html.parser") self.body = self.get_body() self.title = self.get_title() def get_body(self) -> list: body = self.soup.find(property="articleBody") return [p.text for p in body.find_all("p")] def get_title(self) -> str: return self.soup.find(class_="story-body__h1").text The entire code looks like this then: That’s it for now. Here’s how it works in action: In my next post, I apply NLP to the BBC article and build a Streamlit app to interact with it!
[ { "code": null, "e": 317, "s": 171, "text": "I work in London as a Data Scientist for a consultancy. This effectively means I work for multiple companies, doing different Data Science stuff." }, { "code": null, "e": 542, "s": 317, "text": "Mostly I build Machine Learning solutions in the Cloud. Sometimes general Data Solutions, Dashboards or recommending Data Science best practises. Recently though, it's been mostly NLP or Computer Vision. But enough about me." }, { "code": null, "e": 667, "s": 542, "text": "If you are into Data Science, Machine Learning or Big Data, there’s a good chance you’ve had to collect data from a website." }, { "code": null, "e": 878, "s": 667, "text": "For small projects or Proof-of-Concepts (PoC), doing this by hand is fine. Other times, this is best done in code. This is where Python shines, with many open-source libraries to interact with various websites." }, { "code": null, "e": 973, "s": 878, "text": "Knowing how to wield any scraping library, is a very useful skill. Well worth the investment 💰" }, { "code": null, "e": 1021, "s": 973, "text": "The secret is that it’s easy to scrape websites" }, { "code": null, "e": 1087, "s": 1021, "text": "Together, we’ll build a simple Python class that scrapes the BBC." }, { "code": null, "e": 1196, "s": 1087, "text": "Ps: If you only opened the article for the final code, feel free to skip to the end where it’s all laid out." }, { "code": null, "e": 1297, "s": 1196, "text": "BeautifulSoup is my all-time favourite way to scrape websites. It’s simple to learn and easy to use." }, { "code": null, "e": 1397, "s": 1297, "text": "Plus there’s something comical about imagining fishing the good bits out of soup when web scraping!" }, { "code": null, "e": 1524, "s": 1397, "text": "To get started, install the library into your environment using the command line. As a Data Scientist, I usually use Anaconda." }, { "code": null, "e": 1625, "s": 1524, "text": "We will also need the requests module to get the HTML code from the BBC. Run these in your terminal:" }, { "code": null, "e": 1666, "s": 1625, "text": "conda install beautifulsoup4 requests -y" }, { "code": null, "e": 1702, "s": 1666, "text": "You can also use pip if you prefer." }, { "code": null, "e": 1738, "s": 1702, "text": "pip install beautifulsoup4 requests" }, { "code": null, "e": 1831, "s": 1738, "text": "Once installed, create a python file (.py) and import the libraries at the top of your code." }, { "code": null, "e": 1944, "s": 1831, "text": "I recommend using PyCharm, but if you are just starting, Jupyter Notebooks are a great way to get your feet wet." }, { "code": null, "e": 1995, "s": 1944, "text": "import requestsfrom bs4 import BeautifulSoup as bs" }, { "code": null, "e": 2129, "s": 1995, "text": "We are mostly concerned with the two find functions. They allow us to find any HTML element in our soup, just by specifying its name." }, { "code": null, "e": 2249, "s": 2129, "text": "find(element_tag, attribute) #return first matching itemfind_all(element_tag, attribute) #return list of matching items" }, { "code": null, "e": 2305, "s": 2249, "text": "Always use a python environment to manage your projects" }, { "code": null, "e": 2440, "s": 2305, "text": "Let’s pick a BBC article to work with. I’ve chosen one where Iceland is commemorating the loss of its first glacier to climate change." }, { "code": null, "e": 2475, "s": 2440, "text": "Access the raw article via Python:" }, { "code": null, "e": 2559, "s": 2475, "text": "url = 'https://www.bbc.co.uk/news/world-europe-49345912'article = requests.get(url)" }, { "code": null, "e": 2640, "s": 2559, "text": "Then pass the article content over to BeautifulSoup and specify the HTML parser." }, { "code": null, "e": 2682, "s": 2640, "text": "soup = bs(article.content, 'html.parser')" }, { "code": null, "e": 2751, "s": 2682, "text": "Simple as that and the soup is ready! Let’s fish out the good bits 🎣" }, { "code": null, "e": 2911, "s": 2751, "text": "The next step is manually inspecting the HTML of the page to find the element we are interested in. I’m using Chrome for this bit, but you can use any browser." }, { "code": null, "e": 2972, "s": 2911, "text": "Open the webpage in your browser, right-click and ‘inspect’." }, { "code": null, "e": 3075, "s": 2972, "text": "Hover the mouse over any of the text, and the browser will tell you in which div that paragraph is in." }, { "code": null, "e": 3151, "s": 3075, "text": "If it’s not working, press Ctrl+ Shift+ C or CMD + shift + C and try again." }, { "code": null, "e": 3228, "s": 3151, "text": "In this case, “story-body__introduction” contains the highlighted paragraph." }, { "code": null, "e": 3354, "s": 3228, "text": "The div class “story-body__inner” with the property “articleBody” contains the entire article, and that is what we are after." }, { "code": null, "e": 3381, "s": 3354, "text": "Find the body in the soup:" }, { "code": null, "e": 3422, "s": 3381, "text": "body = soup.find(property='articleBody')" }, { "code": null, "e": 3508, "s": 3422, "text": "This gives us the content of the page as a list of paragraphs (p) in raw HTML format." }, { "code": null, "e": 3596, "s": 3508, "text": "Access the text of each paragraph and assign it to a new list using list comprehension:" }, { "code": null, "e": 3639, "s": 3596, "text": "text = [p.text for p in body.find_all('p')" }, { "code": null, "e": 3726, "s": 3639, "text": "We can combine the above in a single function, that takes in the URL of a BBC article:" }, { "code": null, "e": 3851, "s": 3726, "text": "If we wanted to access the title, we again inspect the site, find the div that the title is in, and fish it out of the soup." }, { "code": null, "e": 3890, "s": 3851, "text": "This is how that code would look like:" }, { "code": null, "e": 3969, "s": 3890, "text": "More experienced coders probably already see the issue with these functions..." }, { "code": null, "e": 4027, "s": 3969, "text": "They are the same for the most part. That’s not very DRY." }, { "code": null, "e": 4118, "s": 4027, "text": "One way is to refactor them into 3 functions instead and put get_soup in its own function." }, { "code": null, "e": 4240, "s": 4118, "text": "However, that would mean if we wanted to access both the title and the body, we’d have to download the BBC article twice!" }, { "code": null, "e": 4286, "s": 4240, "text": "This feels like it should be a class instead." }, { "code": null, "e": 4455, "s": 4286, "text": "Plus, classes look and feel more professional instead of calling functions within functions. They also make it easier to maintain, when the scraper grows in complexity." }, { "code": null, "e": 4511, "s": 4455, "text": "As the great coders we are, let’s turn it into a class!" }, { "code": null, "e": 4540, "s": 4511, "text": "Start by defining the class." }, { "code": null, "e": 4647, "s": 4540, "text": "Every class should have an __init__ function, where you pass it any variables to initialise the functions." }, { "code": null, "e": 4718, "s": 4647, "text": "The __init__ function is called automatically when you call the class." }, { "code": null, "e": 4846, "s": 4718, "text": "Each function in the class also needs to have self as the first argument. This is the actual instance of that particular class." }, { "code": null, "e": 4892, "s": 4846, "text": "class BBC: def __init__(self): pass" }, { "code": null, "e": 4992, "s": 4892, "text": "Next, add URL as an argument in __init__, and turn it into a soup. Changes are highlighted in bold." }, { "code": null, "e": 5120, "s": 4992, "text": "class BBC: def __init__(self, url): article = requests.get(url) self.soup = bs(article.content, \"html.parser\")" }, { "code": null, "e": 5275, "s": 5120, "text": "Writing the soup variable as self.soup makes it an attribute of that class. Class attributes can be accessed anywhere within a class, within any function." }, { "code": null, "e": 5391, "s": 5275, "text": "To access the body of the article, we use the body function from before. body is now also an attribute of the class" }, { "code": null, "e": 5689, "s": 5391, "text": "class BBC: def __init__(self, url): article = requests.get(url) self.soup = bs(article.content, \"html.parser\") self.body = self.get_body() def get_body(self) -> list: body = self.soup.find(property=\"articleBody\") return [p.text for p in body.find_all(\"p\")]" }, { "code": null, "e": 5710, "s": 5689, "text": "Same with the title:" }, { "code": null, "e": 6135, "s": 5710, "text": "class BBC: def __init__(self, url): article = requests.get(url) self.soup = bs(article.content, \"html.parser\") self.body = self.get_body() self.title = self.get_title() def get_body(self) -> list: body = self.soup.find(property=\"articleBody\") return [p.text for p in body.find_all(\"p\")] def get_title(self) -> str: return self.soup.find(class_=\"story-body__h1\").text" }, { "code": null, "e": 6173, "s": 6135, "text": "The entire code looks like this then:" }, { "code": null, "e": 6223, "s": 6173, "text": "That’s it for now. Here’s how it works in action:" } ]
Maximum Depth of Binary Tree in Python
Suppose we have one binary tree. We have to find the maximum depth of that tree. The maximum depth of a tree is the maximum number of nodes that are traversed to reach the leaf from the root using the longest path. Suppose the tree is like below. The depth will be 3 here. To solve this, we will follow these steps. Here we will use the recursive approach. The method is solve(root, depth = 0) if the root is empty, then return depth otherwise return max of solve(left, depth + 1) and solve(left, depth + 1) Let us see the following implementation to get a better understanding − Live Demo class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def insert(temp,data): que = [] que.append(temp) while (len(que)): temp = que[0] que.pop(0) if (not temp.left): if data is not None: temp.left = TreeNode(data) else: temp.left = TreeNode(0) break else: que.append(temp.left) if (not temp.right): if data is not None: temp.right = TreeNode(data) else: temp.right = TreeNode(0) break else: que.append(temp.right) def make_tree(elements): Tree = TreeNode(elements[0]) for element in elements[1:]: insert(Tree, element) return Tree class Solution(object): def maxDepth(self, root): """ :type root: TreeNode :rtype: int """ return self.solve(root) def solve(self,root,depth = 0): if root == None: return depth return max(self.solve(root.left,depth+1),self.solve(root.right,depth+1)) tree1 = make_tree([1,2,2,3,4,None,3]) ob1 = Solution() print(ob1.maxDepth(tree1)) tree1 = make_tree([1,2,2,3,4,None,3]) 3
[ { "code": null, "e": 1335, "s": 1062, "text": "Suppose we have one binary tree. We have to find the maximum depth of that tree. The maximum depth of a tree is the maximum number of nodes that are traversed to reach the leaf from the root using the longest path. Suppose the tree is like below. The depth will be 3 here." }, { "code": null, "e": 1378, "s": 1335, "text": "To solve this, we will follow these steps." }, { "code": null, "e": 1456, "s": 1378, "text": "Here we will use the recursive approach. The method is solve(root, depth = 0)" }, { "code": null, "e": 1496, "s": 1456, "text": "if the root is empty, then return depth" }, { "code": null, "e": 1570, "s": 1496, "text": "otherwise return max of solve(left, depth + 1) and solve(left, depth + 1)" }, { "code": null, "e": 1642, "s": 1570, "text": "Let us see the following implementation to get a better understanding −" }, { "code": null, "e": 1653, "s": 1642, "text": " Live Demo" }, { "code": null, "e": 2842, "s": 1653, "text": "class TreeNode:\n def __init__(self, data, left = None, right = None):\n self.data = data\n self.left = left\n self.right = right\ndef insert(temp,data):\n que = []\n que.append(temp)\n while (len(que)):\n temp = que[0]\n que.pop(0)\n if (not temp.left):\n if data is not None:\n temp.left = TreeNode(data)\n else:\n temp.left = TreeNode(0)\n break\n else:\n que.append(temp.left)\n if (not temp.right):\n if data is not None:\n temp.right = TreeNode(data)\n else:\n temp.right = TreeNode(0)\n break\n else:\n que.append(temp.right)\ndef make_tree(elements):\n Tree = TreeNode(elements[0])\n for element in elements[1:]:\n insert(Tree, element)\n return Tree\nclass Solution(object):\n def maxDepth(self, root):\n \"\"\"\n :type root: TreeNode\n :rtype: int\n \"\"\"\n return self.solve(root)\n def solve(self,root,depth = 0):\n if root == None:\n return depth\n return max(self.solve(root.left,depth+1),self.solve(root.right,depth+1))\ntree1 = make_tree([1,2,2,3,4,None,3])\nob1 = Solution()\nprint(ob1.maxDepth(tree1))" }, { "code": null, "e": 2880, "s": 2842, "text": "tree1 = make_tree([1,2,2,3,4,None,3])" }, { "code": null, "e": 2882, "s": 2880, "text": "3" } ]
The margin Shorthand Property in CSS
The CSS margin shorthand property is used to define the margin area for an element. It sets values in clock-wise direction, i.e. margin-top, margin-right, margin-bottom and then margin-left. The syntax of CSS margin property is as follows − Selector { margin: /*value*/ } The following examples illustrate CSS margin shorthand property − Live Demo <!DOCTYPE html> <html> <head> <style> div { margin: 7% auto -3% 25%; width: 40px; height: 40px; padding: 0.9rem; box-shadow: inset 0 0 50px turquoise; border: thin solid; } div > div { border-top-right-radius: 100px; border-bottom-right-radius: 500px; border-top-left-radius: 30px; box-shadow: inset 0 0 6px navy; } div > div > div { padding: 0.3em; margin: 2px -40px; box-shadow: inset 0 0 16px orange; border-radius: 50%; } #one { padding: 50px; border-radius: 10px; } </style> </head> <body> <div id="one"> <div> <div></div> </div> </div> </body> </html> Live Demo <!DOCTYPE html> <html> <head> <style> article { margin: 2em 1em; background-color: bisque; } span { margin: -23% 83%; border-left: dashed; background-image: linear-gradient(to right, lightgreen, forestgreen); font-size: 1.4em; font-style: italic; } </style> </head> <body> <h2>What is Spring Framework?</h2> <article> Spring framework is an open source Java platform. It was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.<span> Spring is lightweight when it comes to size and transparency. The basic version of Spring framework is around 2MB.</span> </article> </body> </html>
[ { "code": null, "e": 1253, "s": 1062, "text": "The CSS margin shorthand property is used to define the margin area for an element. It sets values in clock-wise direction, i.e. margin-top, margin-right, margin-bottom and then margin-left." }, { "code": null, "e": 1303, "s": 1253, "text": "The syntax of CSS margin property is as follows −" }, { "code": null, "e": 1337, "s": 1303, "text": "Selector {\n margin: /*value*/\n}" }, { "code": null, "e": 1403, "s": 1337, "text": "The following examples illustrate CSS margin shorthand property −" }, { "code": null, "e": 1414, "s": 1403, "text": " Live Demo" }, { "code": null, "e": 2020, "s": 1414, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\ndiv {\n margin: 7% auto -3% 25%;\n width: 40px;\n height: 40px;\n padding: 0.9rem;\n box-shadow: inset 0 0 50px turquoise;\n border: thin solid;\n}\ndiv > div {\n border-top-right-radius: 100px;\n border-bottom-right-radius: 500px;\n border-top-left-radius: 30px;\n box-shadow: inset 0 0 6px navy;\n}\ndiv > div > div {\n padding: 0.3em;\n margin: 2px -40px;\n box-shadow: inset 0 0 16px orange;\n border-radius: 50%;\n}\n#one {\n padding: 50px;\n border-radius: 10px;\n}\n</style>\n</head>\n<body>\n<div id=\"one\">\n<div>\n<div></div>\n</div>\n</div>\n</body>\n</html>" }, { "code": null, "e": 2031, "s": 2020, "text": " Live Demo" }, { "code": null, "e": 2681, "s": 2031, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\narticle {\n margin: 2em 1em;\n background-color: bisque;\n}\nspan {\n margin: -23% 83%;\n border-left: dashed;\n background-image: linear-gradient(to right, lightgreen, forestgreen);\n font-size: 1.4em;\n font-style: italic;\n}\n</style>\n</head>\n<body>\n<h2>What is Spring Framework?</h2>\n<article>\nSpring framework is an open source Java platform. It was initially written by Rod Johnson and was first released under the Apache 2.0 license in June 2003.<span> Spring is lightweight when it comes to size and transparency. The basic version of Spring framework is around 2MB.</span>\n</article>\n</body>\n</html>" } ]
C# | Int32 Struct - GeeksforGeeks
02 May, 2019 In C#, Int32 Struct represents 32-bit signed integer(also termed as int data type) starting from range -2,147,483,648 to +2,147,483,647. It also provides different types of method to perform various operations. You can perform the mathematical operation like addition, subtraction, multiplication, etc. on Int32 type. It supports bitwise operations like AND, OR, XOR, etc. It provides full support for standard and custom numeric format strings. You can call the methods of Convert and Math class to perform operations on Int32 value. Int32 struct inherits the ValueType class which inherits the Object class. Example: // C# program to illustrate the // MaxValue and MinValue fieldusing System; class GFG { // Main method static public void Main() { Int32 var1 = 34; Int32 var2 = 30; Int32 var3 = 59; // Get the Maximum and Minimum value // of Int32 type Using MaxValue and // MinValue field Console.WriteLine("Value 1: {0}", var1); Console.WriteLine("Value 2: {0}", var2); Console.WriteLine("Value 3: {0}", var3); Console.WriteLine("Maximum Value: {0}", Int32.MaxValue); Console.WriteLine("Minimum Value: {0}", Int32.MinValue); }} Value 1: 34 Value 2: 30 Value 3: 59 Maximum Value: 2147483647 Minimum Value: -2147483648 Example 1: // C# program to demonstrate the // Int32.Equals(Object) Method using System; using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 int value1 = 70; // Declaring and initializing value2 object value2 = 89; // using Equals(object) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine("{0} is equal to {1}", value1, value2); else Console.WriteLine("{0} is not equal to {1}", value1, value2); } } 70 is not equal to 89 Example 2: // C# program to illustrate the // GetTypeCode() methodusing System; class GFG { // Main method static public void Main() { Int32 var1 = 100; Int32 var2 = 403; Int32 var3 = 503; // Get the type code of // all the variables // Using GetTypeCode() method Console.WriteLine("Get the type code of var1: {0}", var1.GetTypeCode()); Console.WriteLine("Get the type code of var2: {0}", var2.GetTypeCode()); Console.WriteLine("Get the type code of var3: {0}", var3.GetTypeCode()); }} Get the type code of var1: Int32 Get the type code of var2: Int32 Get the type code of var3: Int32 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.int32?view=netframework-4.7.2 CSharp-Int32-Struct C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Destructors in C# Difference between Ref and Out keywords in C# C# | Delegates C# | Constructors C# | Class and Object C# | String.IndexOf( ) Method | Set - 1 Introduction to .NET Framework Extension Method in C# C# | Abstract Classes C# | Data Types
[ { "code": null, "e": 24154, "s": 24126, "text": "\n02 May, 2019" }, { "code": null, "e": 24764, "s": 24154, "text": "In C#, Int32 Struct represents 32-bit signed integer(also termed as int data type) starting from range -2,147,483,648 to +2,147,483,647. It also provides different types of method to perform various operations. You can perform the mathematical operation like addition, subtraction, multiplication, etc. on Int32 type. It supports bitwise operations like AND, OR, XOR, etc. It provides full support for standard and custom numeric format strings. You can call the methods of Convert and Math class to perform operations on Int32 value. Int32 struct inherits the ValueType class which inherits the Object class." }, { "code": null, "e": 24773, "s": 24764, "text": "Example:" }, { "code": "// C# program to illustrate the // MaxValue and MinValue fieldusing System; class GFG { // Main method static public void Main() { Int32 var1 = 34; Int32 var2 = 30; Int32 var3 = 59; // Get the Maximum and Minimum value // of Int32 type Using MaxValue and // MinValue field Console.WriteLine(\"Value 1: {0}\", var1); Console.WriteLine(\"Value 2: {0}\", var2); Console.WriteLine(\"Value 3: {0}\", var3); Console.WriteLine(\"Maximum Value: {0}\", Int32.MaxValue); Console.WriteLine(\"Minimum Value: {0}\", Int32.MinValue); }}", "e": 25446, "s": 24773, "text": null }, { "code": null, "e": 25536, "s": 25446, "text": "Value 1: 34\nValue 2: 30\nValue 3: 59\nMaximum Value: 2147483647\nMinimum Value: -2147483648\n" }, { "code": null, "e": 25547, "s": 25536, "text": "Example 1:" }, { "code": "// C# program to demonstrate the // Int32.Equals(Object) Method using System; using System.Globalization; class GFG { // Main Method public static void Main() { // Declaring and initializing value1 int value1 = 70; // Declaring and initializing value2 object value2 = 89; // using Equals(object) method bool status = value1.Equals(value2); // checking the status if (status) Console.WriteLine(\"{0} is equal to {1}\", value1, value2); else Console.WriteLine(\"{0} is not equal to {1}\", value1, value2); } } ", "e": 26233, "s": 25547, "text": null }, { "code": null, "e": 26256, "s": 26233, "text": "70 is not equal to 89\n" }, { "code": null, "e": 26267, "s": 26256, "text": "Example 2:" }, { "code": "// C# program to illustrate the // GetTypeCode() methodusing System; class GFG { // Main method static public void Main() { Int32 var1 = 100; Int32 var2 = 403; Int32 var3 = 503; // Get the type code of // all the variables // Using GetTypeCode() method Console.WriteLine(\"Get the type code of var1: {0}\", var1.GetTypeCode()); Console.WriteLine(\"Get the type code of var2: {0}\", var2.GetTypeCode()); Console.WriteLine(\"Get the type code of var3: {0}\", var3.GetTypeCode()); }}", "e": 26940, "s": 26267, "text": null }, { "code": null, "e": 27040, "s": 26940, "text": "Get the type code of var1: Int32\nGet the type code of var2: Int32\nGet the type code of var3: Int32\n" }, { "code": null, "e": 27051, "s": 27040, "text": "Reference:" }, { "code": null, "e": 27132, "s": 27051, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.int32?view=netframework-4.7.2" }, { "code": null, "e": 27152, "s": 27132, "text": "CSharp-Int32-Struct" }, { "code": null, "e": 27155, "s": 27152, "text": "C#" }, { "code": null, "e": 27253, "s": 27155, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27271, "s": 27253, "text": "Destructors in C#" }, { "code": null, "e": 27317, "s": 27271, "text": "Difference between Ref and Out keywords in C#" }, { "code": null, "e": 27332, "s": 27317, "text": "C# | Delegates" }, { "code": null, "e": 27350, "s": 27332, "text": "C# | Constructors" }, { "code": null, "e": 27372, "s": 27350, "text": "C# | Class and Object" }, { "code": null, "e": 27412, "s": 27372, "text": "C# | String.IndexOf( ) Method | Set - 1" }, { "code": null, "e": 27443, "s": 27412, "text": "Introduction to .NET Framework" }, { "code": null, "e": 27466, "s": 27443, "text": "Extension Method in C#" }, { "code": null, "e": 27488, "s": 27466, "text": "C# | Abstract Classes" } ]
How to correctly use WITH ROLLUP in MySQL?
The syntax is as follows to use WITH ROLLUP − select yourColumnName1,sum(yourColumnName2) from yourTableName group by yourColumnName1 with rollup; Let us first create a table − mysql> create table DemoTable1622 -> ( -> EmployeeCountryName varchar(20), -> EmployeeSalary int -> ); Query OK, 0 rows affected (0.44 sec) Insert some records in the table using insert command − mysql> insert into DemoTable1622 values('US',4500); Query OK, 1 row affected (0.18 sec) mysql> insert into DemoTable1622 values('UK',1500); Query OK, 1 row affected (0.15 sec) mysql> insert into DemoTable1622 values('AUS',1700); Query OK, 1 row affected (0.19 sec) mysql> insert into DemoTable1622 values('UK',1900); Query OK, 1 row affected (0.17 sec) mysql> insert into DemoTable1622 values('US',3900); Query OK, 1 row affected (0.42 sec) Display all records from the table using select statement − mysql> select * from DemoTable1622; This will produce the following output − +---------------------+----------------+ | EmployeeCountryName | EmployeeSalary | +---------------------+----------------+ | US | 4500 | | UK | 1500 | | AUS | 1700 | | UK | 1900 | | US | 3900 | +---------------------+----------------+ 5 rows in set (0.00 sec) Here is the query to correctly use WITH ROLLUP in MySQL − mysql> select EmployeeCountryName,sum(EmployeeSalary) from DemoTable1622 -> group by EmployeeCountryName with rollup; This will produce the following output − +---------------------+---------------------+ | EmployeeCountryName | sum(EmployeeSalary) | +---------------------+---------------------+ | AUS | 1700 | | UK | 3400 | | US | 8400 | | NULL | 13500 | +---------------------+---------------------+ 4 rows in set (0.02 sec)
[ { "code": null, "e": 1108, "s": 1062, "text": "The syntax is as follows to use WITH ROLLUP −" }, { "code": null, "e": 1210, "s": 1108, "text": "select yourColumnName1,sum(yourColumnName2) from yourTableName\n group by yourColumnName1 with rollup;" }, { "code": null, "e": 1240, "s": 1210, "text": "Let us first create a table −" }, { "code": null, "e": 1396, "s": 1240, "text": "mysql> create table DemoTable1622\n -> (\n -> EmployeeCountryName varchar(20),\n -> EmployeeSalary int\n -> );\nQuery OK, 0 rows affected (0.44 sec)" }, { "code": null, "e": 1452, "s": 1396, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1893, "s": 1452, "text": "mysql> insert into DemoTable1622 values('US',4500);\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable1622 values('UK',1500);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable1622 values('AUS',1700);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable1622 values('UK',1900);\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable1622 values('US',3900);\nQuery OK, 1 row affected (0.42 sec)" }, { "code": null, "e": 1953, "s": 1893, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1989, "s": 1953, "text": "mysql> select * from DemoTable1622;" }, { "code": null, "e": 2030, "s": 1989, "text": "This will produce the following output −" }, { "code": null, "e": 2424, "s": 2030, "text": "+---------------------+----------------+\n| EmployeeCountryName | EmployeeSalary |\n+---------------------+----------------+\n| US | 4500 |\n| UK | 1500 |\n| AUS | 1700 |\n| UK | 1900 |\n| US | 3900 |\n+---------------------+----------------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2482, "s": 2424, "text": "Here is the query to correctly use WITH ROLLUP in MySQL −" }, { "code": null, "e": 2604, "s": 2482, "text": "mysql> select EmployeeCountryName,sum(EmployeeSalary) from DemoTable1622\n -> group by EmployeeCountryName with rollup;" }, { "code": null, "e": 2645, "s": 2604, "text": "This will produce the following output −" }, { "code": null, "e": 3038, "s": 2645, "text": "+---------------------+---------------------+\n| EmployeeCountryName | sum(EmployeeSalary) |\n+---------------------+---------------------+\n| AUS | 1700 |\n| UK | 3400 |\n| US | 8400 |\n| NULL | 13500 |\n+---------------------+---------------------+\n4 rows in set (0.02 sec)" } ]
Survival Modeling — Accelerated Failure Time — XGBoost | by Avinash Barnwal, Ph.D. | Towards Data Science
Survival analysis is a “censored regression” where the goal is to learn time-to-event function. This is similar to the common regression analysis where data-points are uncensored. Survival modeling is not as equally famous as regression and classification. Therefore, I would explain it more in detail with example. This is a modeling task that has censored data. Censored data are the data where the event of interest doesn’t happen during the time of study or we are not able to observe the event of interest due to some reasons. Censoring Types and Examples Left Censoring occurs when we start the study/campaign and the event has already happened leading to higher Example — We want to study about users buying new iPhone given offers, but some users might have already bought it is not useful to throw this data out. Interval Censoring is used when we don’t know the exact time of the event and it could happen between time interval. Example — Users buying Insurance where users not sure about the exact date of purchase. Right Censoring is used when an event has not happened during the time of the study. Example — Treatment received to the cancer patients. Time-to-event modeling is critical for understanding users/companies' behaviors not limited to credit, cancer, and attrition risks. Cox-Proportional Hazard model is a semi-parametric model where we model hazard ratio using predictors while in accelerated Failure time log of survival time is modeled using predictors. It is parametric survival modeling as we are assuming the distribution of response data. Below is the Flow-Chart of Survival Modeling- Tree-based models have improved the supervised learning to lead to many prizes on Kaggle and performed better in the industry as well. We have gradient boosting models implemented in R and python both for Cox-Proportional Hazard Function and Accelerated Failure Time. It is natural to develop more tree-based models for survival modeling as well. For Example — GBM, mboost, Scikit-survival and etc. Currently, XGBoost supports the Cox-Ph model without baseline prediction. Therefore, we have included Accelerated Failure Time in Xgboost to improve survival modeling support. Most of the survival models support only the right censoring data types. We have generally 4 types of data — Right, Left, Interval, and Uncensored. Right censored is the most used censored data type. It is also important to understand other censoring types. Accelerated Failure Time Modeling is parametric survival modeling where survival time follows certain distribution, unlike Cox-Proportional Hazard Model. We support 3 types of distribution — Normal, Logistic, and Extreme. The normal distribution is the most common distribution type but it has a thin tail which might not be the right choice in case of the fat tail events or of extreme events. It's better to visualize it. import numpy as npimport seaborn as snssns.distplot(np.random.normal(0,1,200),hist=False,label=”Normal”)sns.distplot(np.random.logistic(0,1,200),hist=False,label=”Logistic”)sns.distplot(np.random.gumbel(0,1,200),hist=False,label=”Extreme”) When data have fat tails, Logistic/Extreme would lead to better results. Hyperparameter Tuning Hyperparameter optimization is one of the important tasks for machine learning. We have kept the error of the response(\sigma) and base score as hyperparameters. There are many methods to find the best hyperparameter. Grid Search is one of those. We have used GridSearch to find the best hyperparameters. We can also start with sigma equals to an average of sigma of y lower and sigma of y higher for interval-censored datasets and accordingly for different censored datasets and base score equals to average of y lower and y higher. We have used ChIP-seq data sets available here. It has multiple datasets. The output/response of the dataset is log-transformed. We will be using 5 datasets — ATAC_JV_adipose, CTCF_TDH_ENCODE, H3K27ac-H3K4me3_TDHAM_BP, H3K27ac_TDH_some, and H3K36me3_AM_immune. In all datasets, folds are already defined. Base-Score and Sigma are the key hyper-parameters. Below is the code for generating the performance of Accelerated Failure Time with different distributions and sigma. R Code Parametric Censored Regression — Accelerated Failure Time is a powerful alternative to Cox-Proportional Hazard Model. We need more support of the above model in different tree-based models like gradient boosting, XGBoost, and LightGBM. We have implemented it in XGBoost now. Most of the datasets have been flat while varying the sigma meaning we might need more iteration. For Normal, sigma plays a crucial role as it gets flattered when sigma is increased. Hyperparameter tuning is an important aspect here as we might find that there is no movement of training/test loss. It is soon going to be available for all in the XGBoost package. [1] Project Description [2] More Details [3] Derivation P.S. — We have submitted the paper related to this to NeurIPS — 2020 and Arxiv Version of the paper is here — https://arxiv.org/abs/2006.04920.
[ { "code": null, "e": 704, "s": 172, "text": "Survival analysis is a “censored regression” where the goal is to learn time-to-event function. This is similar to the common regression analysis where data-points are uncensored. Survival modeling is not as equally famous as regression and classification. Therefore, I would explain it more in detail with example. This is a modeling task that has censored data. Censored data are the data where the event of interest doesn’t happen during the time of study or we are not able to observe the event of interest due to some reasons." }, { "code": null, "e": 733, "s": 704, "text": "Censoring Types and Examples" }, { "code": null, "e": 994, "s": 733, "text": "Left Censoring occurs when we start the study/campaign and the event has already happened leading to higher Example — We want to study about users buying new iPhone given offers, but some users might have already bought it is not useful to throw this data out." }, { "code": null, "e": 1199, "s": 994, "text": "Interval Censoring is used when we don’t know the exact time of the event and it could happen between time interval. Example — Users buying Insurance where users not sure about the exact date of purchase." }, { "code": null, "e": 1337, "s": 1199, "text": "Right Censoring is used when an event has not happened during the time of the study. Example — Treatment received to the cancer patients." }, { "code": null, "e": 1469, "s": 1337, "text": "Time-to-event modeling is critical for understanding users/companies' behaviors not limited to credit, cancer, and attrition risks." }, { "code": null, "e": 1744, "s": 1469, "text": "Cox-Proportional Hazard model is a semi-parametric model where we model hazard ratio using predictors while in accelerated Failure time log of survival time is modeled using predictors. It is parametric survival modeling as we are assuming the distribution of response data." }, { "code": null, "e": 1790, "s": 1744, "text": "Below is the Flow-Chart of Survival Modeling-" }, { "code": null, "e": 2365, "s": 1790, "text": "Tree-based models have improved the supervised learning to lead to many prizes on Kaggle and performed better in the industry as well. We have gradient boosting models implemented in R and python both for Cox-Proportional Hazard Function and Accelerated Failure Time. It is natural to develop more tree-based models for survival modeling as well. For Example — GBM, mboost, Scikit-survival and etc. Currently, XGBoost supports the Cox-Ph model without baseline prediction. Therefore, we have included Accelerated Failure Time in Xgboost to improve survival modeling support." }, { "code": null, "e": 2623, "s": 2365, "text": "Most of the survival models support only the right censoring data types. We have generally 4 types of data — Right, Left, Interval, and Uncensored. Right censored is the most used censored data type. It is also important to understand other censoring types." }, { "code": null, "e": 3018, "s": 2623, "text": "Accelerated Failure Time Modeling is parametric survival modeling where survival time follows certain distribution, unlike Cox-Proportional Hazard Model. We support 3 types of distribution — Normal, Logistic, and Extreme. The normal distribution is the most common distribution type but it has a thin tail which might not be the right choice in case of the fat tail events or of extreme events." }, { "code": null, "e": 3047, "s": 3018, "text": "It's better to visualize it." }, { "code": null, "e": 3287, "s": 3047, "text": "import numpy as npimport seaborn as snssns.distplot(np.random.normal(0,1,200),hist=False,label=”Normal”)sns.distplot(np.random.logistic(0,1,200),hist=False,label=”Logistic”)sns.distplot(np.random.gumbel(0,1,200),hist=False,label=”Extreme”)" }, { "code": null, "e": 3360, "s": 3287, "text": "When data have fat tails, Logistic/Extreme would lead to better results." }, { "code": null, "e": 3382, "s": 3360, "text": "Hyperparameter Tuning" }, { "code": null, "e": 3600, "s": 3382, "text": "Hyperparameter optimization is one of the important tasks for machine learning. We have kept the error of the response(\\sigma) and base score as hyperparameters. There are many methods to find the best hyperparameter." }, { "code": null, "e": 3687, "s": 3600, "text": "Grid Search is one of those. We have used GridSearch to find the best hyperparameters." }, { "code": null, "e": 3916, "s": 3687, "text": "We can also start with sigma equals to an average of sigma of y lower and sigma of y higher for interval-censored datasets and accordingly for different censored datasets and base score equals to average of y lower and y higher." }, { "code": null, "e": 4221, "s": 3916, "text": "We have used ChIP-seq data sets available here. It has multiple datasets. The output/response of the dataset is log-transformed. We will be using 5 datasets — ATAC_JV_adipose, CTCF_TDH_ENCODE, H3K27ac-H3K4me3_TDHAM_BP, H3K27ac_TDH_some, and H3K36me3_AM_immune. In all datasets, folds are already defined." }, { "code": null, "e": 4272, "s": 4221, "text": "Base-Score and Sigma are the key hyper-parameters." }, { "code": null, "e": 4389, "s": 4272, "text": "Below is the code for generating the performance of Accelerated Failure Time with different distributions and sigma." }, { "code": null, "e": 4396, "s": 4389, "text": "R Code" }, { "code": null, "e": 4854, "s": 4396, "text": "Parametric Censored Regression — Accelerated Failure Time is a powerful alternative to Cox-Proportional Hazard Model. We need more support of the above model in different tree-based models like gradient boosting, XGBoost, and LightGBM. We have implemented it in XGBoost now. Most of the datasets have been flat while varying the sigma meaning we might need more iteration. For Normal, sigma plays a crucial role as it gets flattered when sigma is increased." }, { "code": null, "e": 5035, "s": 4854, "text": "Hyperparameter tuning is an important aspect here as we might find that there is no movement of training/test loss. It is soon going to be available for all in the XGBoost package." }, { "code": null, "e": 5059, "s": 5035, "text": "[1] Project Description" }, { "code": null, "e": 5076, "s": 5059, "text": "[2] More Details" }, { "code": null, "e": 5091, "s": 5076, "text": "[3] Derivation" } ]
Statistics in Python — Generating Random Numbers in Python, NumPy, and sklearn | by Wei-Meng Lee | Towards Data Science
Generating random numbers is one of the common tasks that you need to perform when writing applications. Random numbers serve many purposes — from cryptography to machine learning, random numbers play an extremely important role in making our applications work correctly. As a Python programmer, you are spoilt for choice when it comes to generating random values as there are so many ways to do that. However, this flexibility comes with a price — it is often not very clear when to use what. And this is exactly what I intend to address in this article. At the end of this article, you would have a much clearer picture of what functions to use to generate the random numbers you desire. To generate random numbers in Python, you can use the random module: import random To generate a floating-point random number, call the random() function: random.random() # e.g. 0.49543508709194095 The random() function generates a floating number in the half-open interval — [0,1). This means that the number generated will be from 0 to 1 (where 1 is excluded). If you want to generate a integer value from 0 to 10 (inclusive), use the randint() function: random.randint(0,10) # [0,10] - 0 to 10 (inclusive) e.g. 6 If you want a random floating-point number that is within a specific range (e.g. 1 to 5 (exclusive)), use the uniform() function: random.uniform(1,5) # [1,5) e.g. 4.756596651114043 To generate a list of random integer values within a specific range (e.g. 0 to 32 (exclusive)) without repeating values, use the sample() function: random.sample(range(0, 32), 5) # result is a list of 5 values # from [0,32) with no repeats# [12, 15, 26, 10, 7] The sample() function is useful for cases such as lucky draws where you need to pick some winners from a list of values. If you want a list of random floating-point values in the half-open interval, you can use the random() function via list comprehension: [random.random() for _ in range(5)] # [0, 1)# [0.26800994395551214,# 0.3322334781304659,# 0.5058884832347348,# 0.2552912262686192,# 0.33885158106897195] Likewise, if you need a list of random floating-point values in a specific range, you can do this: [random.uniform(1,5) for _ in range(5)] # [1, 5)# [1.4556516495709206,# 1.94075804553687,# 4.775979596495107,# 4.118159382173641,# 3.860434558608088] Finally, if you want need to generate a list of random integer numbers, use this: [random.randint(0,10) for _ in range(5)] # [0,10]# [3, 9, 8, 7, 10] If you are using the NumPy module, you can also use it to generate random numbers. The random module contains several functions that allows you to generate random numbers. The uniform() function generates a floating-point numbers within the half-open interval: import numpy as npnp.random.uniform() # [0,1) e.g. 0.6603742810407641 You can also specify the range: np.random.uniform(1,5) # [1,5) e.g. 2.1809140016758803 And also the number of random values to generate: np.random.uniform(1,5,8) # [1,5) x 8# array([3.15101237, 3.52431302, 2.43564056, 4.22373224, # 1.82549706, 4.30782957, 2.1383488 , 3.71130947]) You can also specify the shape of the result that you desire: np.random.uniform(1,5,(2,4)) # [1,5) - result is a 2D array of # 2 rows and 4 columns# array([[4.85777402, 2.41464442, 3.47972032, 3.61706258],# [1.39591689, 2.41386733, 3.34813041, 3.13411887]]) If you just want to generate numbers in the half-open interval, there is one more function you can use — rand(): np.random.rand() # [0,1) e.g. 0.11705786929477491 The rand() function makes it easy to generate values of half-open interval in various dimensions: np.random.rand(5) # [0,1) x 5# array([0.52310231, 0.87305847, 0.03870784, 0.69239079, 0.47626848])np.random.rand(2,3) # [0,1) in 2D# array([[0.16926449, 0.06317189, 0.03222409],# [0.24243086, 0.11270682, 0.40499002]]) The rand() function takes in additional arguments for the shape of the result to return while the uniform() function takes in three arguments — low, high, and size. Another function that is similar to the rand() function is random(). It too generates numbers in the half-open interval. The key difference between the two is that the random() function takes in a single argument for the dimension of numbers you want to generate. np.random.random(5) # array([0.90351056, 0.96734226, 0.06753921, # 0.31758607, 0.69686297])np.random.random((2,3)) # passed the dimension you want # as a tuple# array([[0.04207297, 0.92656545, 0.93526291],# [0.8104269 , 0.18834308, 0.58731822]]) The difference between random() and uniform() is that the random() function takes in a single argument. So if you want to generate a multi-dimensional array result, you need to wrap the shape as a tuple. If you need a random integer value, use the randint() function: np.random.randint(0,9) # [0,9) e.g. 7 You can also generate a list of integer values in multi-dimension: np.random.randint(0,9,5) # [0,9) x 5# array([3, 7, 3, 2, 8])np.random.randint(0,9,(4,5)) # [0,9) in 2D array # array([[5, 2, 4, 8, 0],# [5, 2, 3, 7, 2],# [6, 1, 2, 4, 7],# [2, 3, 5, 8, 4]]) So far all the numbers that we have generated are uniformly distributed. The uniform distribution is a continuous probability distribution and is concerned with events that are equally likely to occur. This means that if you try to generate a large number of values, there should be equal chances for any values to be generated. You can see this by trying to generate a million values using the random() function, and then dividing the range of numbers into 25 bins and counting the occurrences of each value that falls into each bin: import matplotlib.pyplot as plt_ = plt.hist(np.random.random(1_000_000), bins = 25) The above statement displays a histogram showing the distribution of the one million numbers: If you want to generate a list of numbers that are normally distributed, you can use the randn() function: np.random.randn(4,3)# array([[-0.58617287, 0.99765344, 1.00439116],# [-0.45170132, -0.01265149, 0.75739522],# [ 0.70970036, -0.1740791 , 1.14584093],# [ 1.2637344 , 0.77962903, -0.97546801]]) Normal distribution, also known as the Gaussian distribution, is a probability distribution that is symmetric about the mean, with most data clustered near the mean. On a graph, a normal distribution appears as a bell curve. The randn() function returns a sample of values from the standard normal distribution. In the above code snippet, the randn() function returns the result in a 2D array. The standard normal distribution is a normal distribution with a mean of zero and standard deviation of 1. For the standard normal distribution, 68.27% of the observations lie within 1 standard deviation of the mean; 95.45% lie within two standard deviation of the mean; and 99.73% lie within 3 standard deviations of the mean. The following example generates one millions numbers that are normally distributed and then used to plot a histogram with the numbers split into 50 bins: _ = plt.hist(np.random.randn(1_000_000), bins=50) You should see something like the following: The irony about random numbers is that they are not really random. Instead, the random number generators in Python uses the current time to generate them, and since every time you run your code to generate the random numbers the time changes, you would think that the numbers are truly random. But that’s not the issue most of us are concerned with. Instead, very often for reproducibility reasons we want to ensure that the random numbers generated are the same, so that we can always get the same result for our analysis. If you generate your random numbers in Python, use the seed() function by passing in an integer value: random.seed(1) # pass in an integer value as the seedrandom.sample(range(0, 32), 5)# [8, 4, 16, 7, 31] The above code snippet will always generate the same list of random numbers. If you use NumPy, use the random.seed() function: np.random.seed(2) # pass in an integer value as the seednp.random.uniform(0, 10, 5)# [4.35994902 0.25926232 5.49662478 4.35322393 4.20367802] NumPy also comes with the RandomState class where you can create an instance of it using a random seed and then use it to generate different types of random values: r = np.random.RandomState(1) # pass in an integer value as the # seedprint(r.uniform(0, 10, 5)) # [0,10)# [4.17022005e+00 7.20324493e+00 1.14374817e-03 3.02332573e+00# 1.46755891e+00]print(r.rand(2,3)) # [0,1)# [[0.09233859 0.18626021 0.34556073]# [0.39676747 0.53881673 0.41919451]] Besides generating random numbers that are uniformly or normally distributed, it is sometimes necessary to generate numbers that are linearly distributed, or clustered around a specific centroids. For example, you might want to try out linear regression using a set of points, or you want to try out some clustering algorithms for unsupervised learning. You can make use of the make_regression() function from the sklearn.datasets module to generate a set of points that are linearly distributed: from sklearn.datasets import make_regressionimport numpy as npx, y = make_regression(n_samples=100, n_features=1, noise=12.3) The n_samples parameter specifies how many numbers to generate, the n_features specifies the number of columns to generate, and noise indicates the standard deviation applied to the numbers (how much they are dispersed). The above code snippet will produce an output that looks like this: print(x)# [[ 1.20630427]# [-1.02041981]# ...# [-0.95098556]# [ 0.09247152]]print(y)# [ 66.34055577 -52.39063718 51.46433162 -12.56089116 # 10.62491393 8.00035735 4.80360232 -28.99765946 # ...# 12.75554229 9.75147261 2.67890648 -32.4981596 # -30.16046261 -4.56704054 -43.56250488 -9.30790306] A better way to understand the numbers is to plot a scatter plot: import matplotlib.pyplot as plt_ = plt.scatter(x, y) If you modify the noise to a larger value: x, y = make_regression(n_samples=100, n_features=1, noise=19)_ = plt.scatter(x, y) You will see that the values are now more dispersed: What if you change the n_features to 2? In this case, X will be a 2D array: X, y = make_regression(n_samples=1000, n_features=2, noise=3)print(X)# [[-0.10171443 1.59563406]# [ 0.39154137 -0.21477808]# [ 0.00732151 0.24783439]# ...# [-0.62820116 0.16688806]# [-0.35656323 -1.1761519 ]# [ 0.04589981 0.59696238]] A good way to visualize the set of random numbers generated is to plot a 3D scatter plot using the scatter3D() function: from sklearn.datasets import make_regressionimport numpy as npimport matplotlib.pyplot as pltX, y = make_regression(n_samples=1000, n_features=2, noise=3)fig = plt.figure(figsize=(13,13))ax = plt.axes(projection='3d')ax.scatter3D(X[:,0], X[:,1], y, c=y, cmap='Greens')ax.set_xlabel('X[0]')ax.set_ylabel('X[1]')ax.set_zlabel('y')plt.show() You should save the above code snippet in a file named random_regression.py and run it in the command prompt. You will then be able to visualize the plot by rotating it around. Here is how the plot looks like from the various angles: The values generated by the make_regression() may not be in the range that you desire. For example, if you want to generate a set of points showing the relationships between the height and weight of a group of people. In this case, you want the height to be between 148cm to 185cm and the weight to be between 44kg and 74kg. The following code snippet scales the x and y values using the interp() function from NumPy: x, y = make_regression(n_samples=100, n_features=1, noise=2.6)# scale x (e.g. height in cm) to 148..185 rangex = np.interp(x, (x.min(), x.max()), (148, 185))# scale y (e.g. weight in kg) to 44..74 rangey = np.interp(y, (y.min(), y.max()), (44, 74))plt.scatter(x, y) The scatter plot confirms the interpolation performed: Very often when you do unsupervised learning, you need to generate random points that cluster around a few centroids. For this purpose, you can use the make_blobs() function from the sklearn.datasets module: from sklearn.datasets import make_blobsX, y = make_blobs(n_samples = 500, centers = 3, n_features = 2) The above code snippet returns 500 pairs of random numbers (contained in X) and y contains the classes that each point is in: print(X)# [[ -9.86754851 9.27779819]# [-11.50057906 8.88609894]# ...# [ -5.96056302 -3.21866963]# [-10.38173377 8.82254368]]print(y)# [2 2 0 1 2 2 0 1 2 1 1 1 0 2 # 1 1 2 1 1 1 2 2 0 1 1 1 1 1 # ...# 2 0 0 0 2 0 1 0 2 2 1 2 1 2# 2 1 2 2 1 1 1 0 0 0 2 1 2 1] As usual, visualization always make things much clearer: rgb = np.array(['r', 'g', 'b'])# plot the blobs using a scatter plot and use color coding_ = plt.scatter(X[:, 0], X[:, 1], color=rgb[y])plt.xlabel('X[0]')plt.ylabel('X[1]') How about 3D points? Sure, just set n_features to 3 and plot using the scatter3D() function: from sklearn.datasets import make_blobsimport numpy as npimport matplotlib.pyplot as pltX, y = make_blobs(n_samples = 1500, centers = 3, n_features = 3)fig = plt.figure(figsize=(13,13))ax = plt.axes(projection='3d')ax.scatter3D(X[:,0], X[:,1], X[:,2], c = y, cmap = 'tab20b')ax.set_xlabel('X[0]')ax.set_ylabel('X[1]')ax.set_zlabel('y')plt.show() You should save the above code snippet in a file named random_blobs.py and run it in the command prompt. You will then be able to visualize the plot by rotating it around. For reproducibility , set the random_state parameter to a value: X, y = make_blobs(n_samples = 1500, centers = 3, n_features = 3, random_state = 0) Phew, looks like there are quite a number of different ways to generate random numbers in Python. The best way to remember what to use it to refer to the following summary of the functions we have discussed in this article. Did I missed out any important functions? Let me know in the comments!
[ { "code": null, "e": 444, "s": 172, "text": "Generating random numbers is one of the common tasks that you need to perform when writing applications. Random numbers serve many purposes — from cryptography to machine learning, random numbers play an extremely important role in making our applications work correctly." }, { "code": null, "e": 728, "s": 444, "text": "As a Python programmer, you are spoilt for choice when it comes to generating random values as there are so many ways to do that. However, this flexibility comes with a price — it is often not very clear when to use what. And this is exactly what I intend to address in this article." }, { "code": null, "e": 862, "s": 728, "text": "At the end of this article, you would have a much clearer picture of what functions to use to generate the random numbers you desire." }, { "code": null, "e": 931, "s": 862, "text": "To generate random numbers in Python, you can use the random module:" }, { "code": null, "e": 945, "s": 931, "text": "import random" }, { "code": null, "e": 1017, "s": 945, "text": "To generate a floating-point random number, call the random() function:" }, { "code": null, "e": 1062, "s": 1017, "text": "random.random() # e.g. 0.49543508709194095" }, { "code": null, "e": 1227, "s": 1062, "text": "The random() function generates a floating number in the half-open interval — [0,1). This means that the number generated will be from 0 to 1 (where 1 is excluded)." }, { "code": null, "e": 1321, "s": 1227, "text": "If you want to generate a integer value from 0 to 10 (inclusive), use the randint() function:" }, { "code": null, "e": 1381, "s": 1321, "text": "random.randint(0,10) # [0,10] - 0 to 10 (inclusive) e.g. 6" }, { "code": null, "e": 1511, "s": 1381, "text": "If you want a random floating-point number that is within a specific range (e.g. 1 to 5 (exclusive)), use the uniform() function:" }, { "code": null, "e": 1563, "s": 1511, "text": "random.uniform(1,5) # [1,5) e.g. 4.756596651114043" }, { "code": null, "e": 1711, "s": 1563, "text": "To generate a list of random integer values within a specific range (e.g. 0 to 32 (exclusive)) without repeating values, use the sample() function:" }, { "code": null, "e": 1861, "s": 1711, "text": "random.sample(range(0, 32), 5) # result is a list of 5 values # from [0,32) with no repeats# [12, 15, 26, 10, 7]" }, { "code": null, "e": 1982, "s": 1861, "text": "The sample() function is useful for cases such as lucky draws where you need to pick some winners from a list of values." }, { "code": null, "e": 2118, "s": 1982, "text": "If you want a list of random floating-point values in the half-open interval, you can use the random() function via list comprehension:" }, { "code": null, "e": 2282, "s": 2118, "text": "[random.random() for _ in range(5)] # [0, 1)# [0.26800994395551214,# 0.3322334781304659,# 0.5058884832347348,# 0.2552912262686192,# 0.33885158106897195]" }, { "code": null, "e": 2381, "s": 2282, "text": "Likewise, if you need a list of random floating-point values in a specific range, you can do this:" }, { "code": null, "e": 2538, "s": 2381, "text": "[random.uniform(1,5) for _ in range(5)] # [1, 5)# [1.4556516495709206,# 1.94075804553687,# 4.775979596495107,# 4.118159382173641,# 3.860434558608088]" }, { "code": null, "e": 2620, "s": 2538, "text": "Finally, if you want need to generate a list of random integer numbers, use this:" }, { "code": null, "e": 2690, "s": 2620, "text": "[random.randint(0,10) for _ in range(5)] # [0,10]# [3, 9, 8, 7, 10]" }, { "code": null, "e": 2862, "s": 2690, "text": "If you are using the NumPy module, you can also use it to generate random numbers. The random module contains several functions that allows you to generate random numbers." }, { "code": null, "e": 2951, "s": 2862, "text": "The uniform() function generates a floating-point numbers within the half-open interval:" }, { "code": null, "e": 3029, "s": 2951, "text": "import numpy as npnp.random.uniform() # [0,1) e.g. 0.6603742810407641" }, { "code": null, "e": 3061, "s": 3029, "text": "You can also specify the range:" }, { "code": null, "e": 3121, "s": 3061, "text": "np.random.uniform(1,5) # [1,5) e.g. 2.1809140016758803" }, { "code": null, "e": 3171, "s": 3121, "text": "And also the number of random values to generate:" }, { "code": null, "e": 3325, "s": 3171, "text": "np.random.uniform(1,5,8) # [1,5) x 8# array([3.15101237, 3.52431302, 2.43564056, 4.22373224, # 1.82549706, 4.30782957, 2.1383488 , 3.71130947])" }, { "code": null, "e": 3387, "s": 3325, "text": "You can also specify the shape of the result that you desire:" }, { "code": null, "e": 3621, "s": 3387, "text": "np.random.uniform(1,5,(2,4)) # [1,5) - result is a 2D array of # 2 rows and 4 columns# array([[4.85777402, 2.41464442, 3.47972032, 3.61706258],# [1.39591689, 2.41386733, 3.34813041, 3.13411887]])" }, { "code": null, "e": 3734, "s": 3621, "text": "If you just want to generate numbers in the half-open interval, there is one more function you can use — rand():" }, { "code": null, "e": 3789, "s": 3734, "text": "np.random.rand() # [0,1) e.g. 0.11705786929477491" }, { "code": null, "e": 3887, "s": 3789, "text": "The rand() function makes it easy to generate values of half-open interval in various dimensions:" }, { "code": null, "e": 4118, "s": 3887, "text": "np.random.rand(5) # [0,1) x 5# array([0.52310231, 0.87305847, 0.03870784, 0.69239079, 0.47626848])np.random.rand(2,3) # [0,1) in 2D# array([[0.16926449, 0.06317189, 0.03222409],# [0.24243086, 0.11270682, 0.40499002]])" }, { "code": null, "e": 4283, "s": 4118, "text": "The rand() function takes in additional arguments for the shape of the result to return while the uniform() function takes in three arguments — low, high, and size." }, { "code": null, "e": 4547, "s": 4283, "text": "Another function that is similar to the rand() function is random(). It too generates numbers in the half-open interval. The key difference between the two is that the random() function takes in a single argument for the dimension of numbers you want to generate." }, { "code": null, "e": 4834, "s": 4547, "text": "np.random.random(5) # array([0.90351056, 0.96734226, 0.06753921, # 0.31758607, 0.69686297])np.random.random((2,3)) # passed the dimension you want # as a tuple# array([[0.04207297, 0.92656545, 0.93526291],# [0.8104269 , 0.18834308, 0.58731822]])" }, { "code": null, "e": 5038, "s": 4834, "text": "The difference between random() and uniform() is that the random() function takes in a single argument. So if you want to generate a multi-dimensional array result, you need to wrap the shape as a tuple." }, { "code": null, "e": 5102, "s": 5038, "text": "If you need a random integer value, use the randint() function:" }, { "code": null, "e": 5147, "s": 5102, "text": "np.random.randint(0,9) # [0,9) e.g. 7" }, { "code": null, "e": 5214, "s": 5147, "text": "You can also generate a list of integer values in multi-dimension:" }, { "code": null, "e": 5432, "s": 5214, "text": "np.random.randint(0,9,5) # [0,9) x 5# array([3, 7, 3, 2, 8])np.random.randint(0,9,(4,5)) # [0,9) in 2D array # array([[5, 2, 4, 8, 0],# [5, 2, 3, 7, 2],# [6, 1, 2, 4, 7],# [2, 3, 5, 8, 4]])" }, { "code": null, "e": 5505, "s": 5432, "text": "So far all the numbers that we have generated are uniformly distributed." }, { "code": null, "e": 5634, "s": 5505, "text": "The uniform distribution is a continuous probability distribution and is concerned with events that are equally likely to occur." }, { "code": null, "e": 5967, "s": 5634, "text": "This means that if you try to generate a large number of values, there should be equal chances for any values to be generated. You can see this by trying to generate a million values using the random() function, and then dividing the range of numbers into 25 bins and counting the occurrences of each value that falls into each bin:" }, { "code": null, "e": 6051, "s": 5967, "text": "import matplotlib.pyplot as plt_ = plt.hist(np.random.random(1_000_000), bins = 25)" }, { "code": null, "e": 6145, "s": 6051, "text": "The above statement displays a histogram showing the distribution of the one million numbers:" }, { "code": null, "e": 6252, "s": 6145, "text": "If you want to generate a list of numbers that are normally distributed, you can use the randn() function:" }, { "code": null, "e": 6470, "s": 6252, "text": "np.random.randn(4,3)# array([[-0.58617287, 0.99765344, 1.00439116],# [-0.45170132, -0.01265149, 0.75739522],# [ 0.70970036, -0.1740791 , 1.14584093],# [ 1.2637344 , 0.77962903, -0.97546801]])" }, { "code": null, "e": 6695, "s": 6470, "text": "Normal distribution, also known as the Gaussian distribution, is a probability distribution that is symmetric about the mean, with most data clustered near the mean. On a graph, a normal distribution appears as a bell curve." }, { "code": null, "e": 6864, "s": 6695, "text": "The randn() function returns a sample of values from the standard normal distribution. In the above code snippet, the randn() function returns the result in a 2D array." }, { "code": null, "e": 7192, "s": 6864, "text": "The standard normal distribution is a normal distribution with a mean of zero and standard deviation of 1. For the standard normal distribution, 68.27% of the observations lie within 1 standard deviation of the mean; 95.45% lie within two standard deviation of the mean; and 99.73% lie within 3 standard deviations of the mean." }, { "code": null, "e": 7346, "s": 7192, "text": "The following example generates one millions numbers that are normally distributed and then used to plot a histogram with the numbers split into 50 bins:" }, { "code": null, "e": 7396, "s": 7346, "text": "_ = plt.hist(np.random.randn(1_000_000), bins=50)" }, { "code": null, "e": 7441, "s": 7396, "text": "You should see something like the following:" }, { "code": null, "e": 7965, "s": 7441, "text": "The irony about random numbers is that they are not really random. Instead, the random number generators in Python uses the current time to generate them, and since every time you run your code to generate the random numbers the time changes, you would think that the numbers are truly random. But that’s not the issue most of us are concerned with. Instead, very often for reproducibility reasons we want to ensure that the random numbers generated are the same, so that we can always get the same result for our analysis." }, { "code": null, "e": 8068, "s": 7965, "text": "If you generate your random numbers in Python, use the seed() function by passing in an integer value:" }, { "code": null, "e": 8184, "s": 8068, "text": "random.seed(1) # pass in an integer value as the seedrandom.sample(range(0, 32), 5)# [8, 4, 16, 7, 31]" }, { "code": null, "e": 8261, "s": 8184, "text": "The above code snippet will always generate the same list of random numbers." }, { "code": null, "e": 8311, "s": 8261, "text": "If you use NumPy, use the random.seed() function:" }, { "code": null, "e": 8463, "s": 8311, "text": "np.random.seed(2) # pass in an integer value as the seednp.random.uniform(0, 10, 5)# [4.35994902 0.25926232 5.49662478 4.35322393 4.20367802]" }, { "code": null, "e": 8628, "s": 8463, "text": "NumPy also comes with the RandomState class where you can create an instance of it using a random seed and then use it to generate different types of random values:" }, { "code": null, "e": 8963, "s": 8628, "text": "r = np.random.RandomState(1) # pass in an integer value as the # seedprint(r.uniform(0, 10, 5)) # [0,10)# [4.17022005e+00 7.20324493e+00 1.14374817e-03 3.02332573e+00# 1.46755891e+00]print(r.rand(2,3)) # [0,1)# [[0.09233859 0.18626021 0.34556073]# [0.39676747 0.53881673 0.41919451]]" }, { "code": null, "e": 9317, "s": 8963, "text": "Besides generating random numbers that are uniformly or normally distributed, it is sometimes necessary to generate numbers that are linearly distributed, or clustered around a specific centroids. For example, you might want to try out linear regression using a set of points, or you want to try out some clustering algorithms for unsupervised learning." }, { "code": null, "e": 9460, "s": 9317, "text": "You can make use of the make_regression() function from the sklearn.datasets module to generate a set of points that are linearly distributed:" }, { "code": null, "e": 9586, "s": 9460, "text": "from sklearn.datasets import make_regressionimport numpy as npx, y = make_regression(n_samples=100, n_features=1, noise=12.3)" }, { "code": null, "e": 9875, "s": 9586, "text": "The n_samples parameter specifies how many numbers to generate, the n_features specifies the number of columns to generate, and noise indicates the standard deviation applied to the numbers (how much they are dispersed). The above code snippet will produce an output that looks like this:" }, { "code": null, "e": 10213, "s": 9875, "text": "print(x)# [[ 1.20630427]# [-1.02041981]# ...# [-0.95098556]# [ 0.09247152]]print(y)# [ 66.34055577 -52.39063718 51.46433162 -12.56089116 # 10.62491393 8.00035735 4.80360232 -28.99765946 # ...# 12.75554229 9.75147261 2.67890648 -32.4981596 # -30.16046261 -4.56704054 -43.56250488 -9.30790306]" }, { "code": null, "e": 10279, "s": 10213, "text": "A better way to understand the numbers is to plot a scatter plot:" }, { "code": null, "e": 10332, "s": 10279, "text": "import matplotlib.pyplot as plt_ = plt.scatter(x, y)" }, { "code": null, "e": 10375, "s": 10332, "text": "If you modify the noise to a larger value:" }, { "code": null, "e": 10458, "s": 10375, "text": "x, y = make_regression(n_samples=100, n_features=1, noise=19)_ = plt.scatter(x, y)" }, { "code": null, "e": 10511, "s": 10458, "text": "You will see that the values are now more dispersed:" }, { "code": null, "e": 10587, "s": 10511, "text": "What if you change the n_features to 2? In this case, X will be a 2D array:" }, { "code": null, "e": 10832, "s": 10587, "text": "X, y = make_regression(n_samples=1000, n_features=2, noise=3)print(X)# [[-0.10171443 1.59563406]# [ 0.39154137 -0.21477808]# [ 0.00732151 0.24783439]# ...# [-0.62820116 0.16688806]# [-0.35656323 -1.1761519 ]# [ 0.04589981 0.59696238]]" }, { "code": null, "e": 10953, "s": 10832, "text": "A good way to visualize the set of random numbers generated is to plot a 3D scatter plot using the scatter3D() function:" }, { "code": null, "e": 11292, "s": 10953, "text": "from sklearn.datasets import make_regressionimport numpy as npimport matplotlib.pyplot as pltX, y = make_regression(n_samples=1000, n_features=2, noise=3)fig = plt.figure(figsize=(13,13))ax = plt.axes(projection='3d')ax.scatter3D(X[:,0], X[:,1], y, c=y, cmap='Greens')ax.set_xlabel('X[0]')ax.set_ylabel('X[1]')ax.set_zlabel('y')plt.show()" }, { "code": null, "e": 11469, "s": 11292, "text": "You should save the above code snippet in a file named random_regression.py and run it in the command prompt. You will then be able to visualize the plot by rotating it around." }, { "code": null, "e": 11526, "s": 11469, "text": "Here is how the plot looks like from the various angles:" }, { "code": null, "e": 11944, "s": 11526, "text": "The values generated by the make_regression() may not be in the range that you desire. For example, if you want to generate a set of points showing the relationships between the height and weight of a group of people. In this case, you want the height to be between 148cm to 185cm and the weight to be between 44kg and 74kg. The following code snippet scales the x and y values using the interp() function from NumPy:" }, { "code": null, "e": 12210, "s": 11944, "text": "x, y = make_regression(n_samples=100, n_features=1, noise=2.6)# scale x (e.g. height in cm) to 148..185 rangex = np.interp(x, (x.min(), x.max()), (148, 185))# scale y (e.g. weight in kg) to 44..74 rangey = np.interp(y, (y.min(), y.max()), (44, 74))plt.scatter(x, y)" }, { "code": null, "e": 12265, "s": 12210, "text": "The scatter plot confirms the interpolation performed:" }, { "code": null, "e": 12473, "s": 12265, "text": "Very often when you do unsupervised learning, you need to generate random points that cluster around a few centroids. For this purpose, you can use the make_blobs() function from the sklearn.datasets module:" }, { "code": null, "e": 12611, "s": 12473, "text": "from sklearn.datasets import make_blobsX, y = make_blobs(n_samples = 500, centers = 3, n_features = 2)" }, { "code": null, "e": 12737, "s": 12611, "text": "The above code snippet returns 500 pairs of random numbers (contained in X) and y contains the classes that each point is in:" }, { "code": null, "e": 13010, "s": 12737, "text": "print(X)# [[ -9.86754851 9.27779819]# [-11.50057906 8.88609894]# ...# [ -5.96056302 -3.21866963]# [-10.38173377 8.82254368]]print(y)# [2 2 0 1 2 2 0 1 2 1 1 1 0 2 # 1 1 2 1 1 1 2 2 0 1 1 1 1 1 # ...# 2 0 0 0 2 0 1 0 2 2 1 2 1 2# 2 1 2 2 1 1 1 0 0 0 2 1 2 1]" }, { "code": null, "e": 13067, "s": 13010, "text": "As usual, visualization always make things much clearer:" }, { "code": null, "e": 13240, "s": 13067, "text": "rgb = np.array(['r', 'g', 'b'])# plot the blobs using a scatter plot and use color coding_ = plt.scatter(X[:, 0], X[:, 1], color=rgb[y])plt.xlabel('X[0]')plt.ylabel('X[1]')" }, { "code": null, "e": 13333, "s": 13240, "text": "How about 3D points? Sure, just set n_features to 3 and plot using the scatter3D() function:" }, { "code": null, "e": 13714, "s": 13333, "text": "from sklearn.datasets import make_blobsimport numpy as npimport matplotlib.pyplot as pltX, y = make_blobs(n_samples = 1500, centers = 3, n_features = 3)fig = plt.figure(figsize=(13,13))ax = plt.axes(projection='3d')ax.scatter3D(X[:,0], X[:,1], X[:,2], c = y, cmap = 'tab20b')ax.set_xlabel('X[0]')ax.set_ylabel('X[1]')ax.set_zlabel('y')plt.show()" }, { "code": null, "e": 13886, "s": 13714, "text": "You should save the above code snippet in a file named random_blobs.py and run it in the command prompt. You will then be able to visualize the plot by rotating it around." }, { "code": null, "e": 13951, "s": 13886, "text": "For reproducibility , set the random_state parameter to a value:" }, { "code": null, "e": 14086, "s": 13951, "text": "X, y = make_blobs(n_samples = 1500, centers = 3, n_features = 3, random_state = 0)" }, { "code": null, "e": 14310, "s": 14086, "text": "Phew, looks like there are quite a number of different ways to generate random numbers in Python. The best way to remember what to use it to refer to the following summary of the functions we have discussed in this article." } ]
Java BeanUtils - Comparing Beans
In Apache Commons Beanutils, you can compare the JavaBean objects by using the BeanComparator class based on a specified shared property value. This can be done by using the org.apache.commons.beanutils.BeanComparator comparator. The below example shows how to compare the two different beans. We will be creating two objects and set the first object to "BMW" and the other object to "AUDI". Then, we will compare the objects by using the BeanComparator by calling its compare() method. Note: For BeanComparator, commons-collection and commons-logging jar files need to be included. package com.javadb.apachecommons.beanutils; import org.apache.commons.beanutils.BeanComparator; public class BeanComparatorExample { public static void main(String[] args) { Car car1 = new Car(); car1.setBrand("BMW"); Car car2 = new Car(); car2.setBrand("AUDI"); BeanComparator comparator = new BeanComparator("brand"); System.out.println("The value after comparing two beans is: " + comparator.compare(car1, car2)); } } Now we will create one more class with the below code and save it as Car.java. package com.javadb.apachecommons.beanutils; public class Car { private String brand; public String getBrand() { return brand; } public void setBrand(String brand) { this.brand = brand; } } Save the above first code as BeanComparatorExample.java. Save the above first code as BeanComparatorExample.java. Now execute the code using Run option or Ctrl+f11 and output as below gets displayed. Now execute the code using Run option or Ctrl+f11 and output as below gets displayed. 16 Lectures 2 hours Malhar Lathkar 19 Lectures 5 hours Malhar Lathkar 25 Lectures 2.5 hours Anadi Sharma 126 Lectures 7 hours Tushar Kale 119 Lectures 17.5 hours Monica Mittal 76 Lectures 7 hours Arnab Chakraborty Print Add Notes Bookmark this page
[ { "code": null, "e": 2386, "s": 2156, "text": "In Apache Commons Beanutils, you can compare the JavaBean objects by using the BeanComparator class based on a specified shared property value. This can be done by using the org.apache.commons.beanutils.BeanComparator comparator." }, { "code": null, "e": 2643, "s": 2386, "text": "The below example shows how to compare the two different beans. We will be creating two objects and set the first object to \"BMW\" and the other object to \"AUDI\". Then, we will compare the objects by using the BeanComparator by calling its compare() method." }, { "code": null, "e": 2739, "s": 2643, "text": "Note: For BeanComparator, commons-collection and commons-logging jar files need to be included." }, { "code": null, "e": 3244, "s": 2739, "text": "package com.javadb.apachecommons.beanutils;\nimport org.apache.commons.beanutils.BeanComparator;\n\npublic class BeanComparatorExample {\n public static void main(String[] args) {\n Car car1 = new Car();\n car1.setBrand(\"BMW\");\n \n Car car2 = new Car();\n car2.setBrand(\"AUDI\");\n \n BeanComparator comparator = new BeanComparator(\"brand\");\n \n System.out.println(\"The value after comparing two beans is: \" + comparator.compare(car1, car2));\n }\n}" }, { "code": null, "e": 3323, "s": 3244, "text": "Now we will create one more class with the below code and save it as Car.java." }, { "code": null, "e": 3556, "s": 3323, "text": "package com.javadb.apachecommons.beanutils;\n\npublic class Car {\n private String brand;\n\t\n public String getBrand() {\n return brand;\n }\n \n public void setBrand(String brand) {\n this.brand = brand;\n }\n}" }, { "code": null, "e": 3613, "s": 3556, "text": "Save the above first code as BeanComparatorExample.java." }, { "code": null, "e": 3670, "s": 3613, "text": "Save the above first code as BeanComparatorExample.java." }, { "code": null, "e": 3756, "s": 3670, "text": "Now execute the code using Run option or Ctrl+f11 and output as below gets displayed." }, { "code": null, "e": 3842, "s": 3756, "text": "Now execute the code using Run option or Ctrl+f11 and output as below gets displayed." }, { "code": null, "e": 3875, "s": 3842, "text": "\n 16 Lectures \n 2 hours \n" }, { "code": null, "e": 3891, "s": 3875, "text": " Malhar Lathkar" }, { "code": null, "e": 3924, "s": 3891, "text": "\n 19 Lectures \n 5 hours \n" }, { "code": null, "e": 3940, "s": 3924, "text": " Malhar Lathkar" }, { "code": null, "e": 3975, "s": 3940, "text": "\n 25 Lectures \n 2.5 hours \n" }, { "code": null, "e": 3989, "s": 3975, "text": " Anadi Sharma" }, { "code": null, "e": 4023, "s": 3989, "text": "\n 126 Lectures \n 7 hours \n" }, { "code": null, "e": 4037, "s": 4023, "text": " Tushar Kale" }, { "code": null, "e": 4074, "s": 4037, "text": "\n 119 Lectures \n 17.5 hours \n" }, { "code": null, "e": 4089, "s": 4074, "text": " Monica Mittal" }, { "code": null, "e": 4122, "s": 4089, "text": "\n 76 Lectures \n 7 hours \n" }, { "code": null, "e": 4141, "s": 4122, "text": " Arnab Chakraborty" }, { "code": null, "e": 4148, "s": 4141, "text": " Print" }, { "code": null, "e": 4159, "s": 4148, "text": " Add Notes" } ]
Build a Vertical Navigation Bar with CSS
To build a vertical navigation bar, you can try to run the following code. Live Demo <!DOCTYPE html> <html> <head> <style> ul { list-style-type: none; margin: 5; padding: 5; } li a { display: block; width: 70px; background-color: orange; } </style> </head> <body> <ul> <li><a href = "#home">Home</a></li> <li><a href = "#company">Company</a></li> <li><a href = "#product">Product</a></li> <li><a href = "#services">Services</a></li> <li><a href = "#contact">Contact</a></li> </ul> </body> </html>
[ { "code": null, "e": 1137, "s": 1062, "text": "To build a vertical navigation bar, you can try to run the following code." }, { "code": null, "e": 1147, "s": 1137, "text": "Live Demo" }, { "code": null, "e": 1748, "s": 1147, "text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n ul {\n list-style-type: none;\n margin: 5;\n padding: 5;\n }\n li a {\n display: block;\n width: 70px;\n background-color: orange;\n }\n </style>\n </head>\n <body>\n <ul>\n <li><a href = \"#home\">Home</a></li>\n <li><a href = \"#company\">Company</a></li>\n <li><a href = \"#product\">Product</a></li>\n <li><a href = \"#services\">Services</a></li>\n <li><a href = \"#contact\">Contact</a></li>\n </ul>\n </body>\n</html>" } ]
Strictly increasing or decreasing array - JavaScript
In Mathematics, a strictly increasing function is that function in which the value to be plotted always increase. Similarly, a strictly decreasing function is that function in which the value to be plotted always decrease. We are required to write a JavaScript function that takes in an array of numbers and returns true if it’s either strictly increasing or strictly decreasing, otherwise returns false. Following is the code − const arr = [12, 45, 6, 4, 23, 23, 21, 1]; const arr2 = [12, 45, 67, 89, 123, 144, 2656, 5657]; const sameSlope = (a, b, c) => (b - a < 0 && c - b < 0) || (b - a > 0 && c - b > 0); const increasingOrDecreasing = (arr = []) => { if(arr.length <= 2){ return true; }; for(let i = 1; i < arr.length - 1; i++){ if(sameSlope(arr[i-1], arr[i], arr[i+1])){ continue; }; return false; }; return true; }; console.log(increasingOrDecreasing(arr)); console.log(increasingOrDecreasing(arr2)); Following is the output in the console − false true
[ { "code": null, "e": 1285, "s": 1062, "text": "In Mathematics, a strictly increasing function is that function in which the value to be plotted always increase. Similarly, a strictly decreasing function is that function in which the value to be plotted always decrease." }, { "code": null, "e": 1467, "s": 1285, "text": "We are required to write a JavaScript function that takes in an array of numbers and returns true if it’s either strictly increasing or strictly decreasing, otherwise returns false." }, { "code": null, "e": 1491, "s": 1467, "text": "Following is the code −" }, { "code": null, "e": 2019, "s": 1491, "text": "const arr = [12, 45, 6, 4, 23, 23, 21, 1];\nconst arr2 = [12, 45, 67, 89, 123, 144, 2656, 5657];\nconst sameSlope = (a, b, c) => (b - a < 0 && c - b < 0) || (b - a > 0 && c\n- b > 0);\nconst increasingOrDecreasing = (arr = []) => {\n if(arr.length <= 2){\n return true;\n };\n for(let i = 1; i < arr.length - 1; i++){\n if(sameSlope(arr[i-1], arr[i], arr[i+1])){\n continue;\n };\n return false;\n };\n return true;\n};\nconsole.log(increasingOrDecreasing(arr));\nconsole.log(increasingOrDecreasing(arr2));" }, { "code": null, "e": 2060, "s": 2019, "text": "Following is the output in the console −" }, { "code": null, "e": 2071, "s": 2060, "text": "false\ntrue" } ]
Use UNION ALL to insert records in two tables with a single query in MYSQL
Here is the query to create first table. mysql> create table DemoTable1 -> ( -> StudentName varchar(20), -> StudentMarks int -> ); Query OK, 0 rows affected (0.67 sec) To understand the above concept, let us create second table. mysql> create table DemoTable2 -> ( -> Name varchar(20) -> ); Query OK, 0 rows affected (0.61 sec) Insert some records in the table using insert command − mysql> insert into DemoTable2 values('Chris'); Query OK, 1 row affected (0.12 sec) Display all records from the table using select statement − mysql> select * from DemoTable2; This will produce the following output − +-------+ | Name | +-------+ | Chris | +-------+ 1 row in set (0.00 sec) Here is the query to select and insert records with a single MySQL query − mysql> insert into DemoTable1 -> select Name,89 from DemoTable2 -> union all -> select Name,98 from DemoTable2; Query OK, 2 rows affected (0.15 sec) Records: 2 Duplicates: 0 Warnings: 0 Now you can select records from the first table − mysql> select * from DemoTable1; This will produce the following output − +-------------+--------------+ | StudentName | StudentMarks | +-------------+--------------+ | Chris | 89 | | Chris | 98 | +-------------+--------------+ 2 rows in set (0.00 sec)
[ { "code": null, "e": 1103, "s": 1062, "text": "Here is the query to create first table." }, { "code": null, "e": 1242, "s": 1103, "text": "mysql> create table DemoTable1\n -> (\n -> StudentName varchar(20),\n -> StudentMarks int\n -> );\nQuery OK, 0 rows affected (0.67 sec)" }, { "code": null, "e": 1303, "s": 1242, "text": "To understand the above concept, let us create second table." }, { "code": null, "e": 1411, "s": 1303, "text": "mysql> create table DemoTable2\n -> (\n -> Name varchar(20)\n -> );\nQuery OK, 0 rows affected (0.61 sec)" }, { "code": null, "e": 1467, "s": 1411, "text": "Insert some records in the table using insert command −" }, { "code": null, "e": 1550, "s": 1467, "text": "mysql> insert into DemoTable2 values('Chris');\nQuery OK, 1 row affected (0.12 sec)" }, { "code": null, "e": 1610, "s": 1550, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1643, "s": 1610, "text": "mysql> select * from DemoTable2;" }, { "code": null, "e": 1684, "s": 1643, "text": "This will produce the following output −" }, { "code": null, "e": 1758, "s": 1684, "text": "+-------+\n| Name |\n+-------+\n| Chris |\n+-------+\n1 row in set (0.00 sec)" }, { "code": null, "e": 1833, "s": 1758, "text": "Here is the query to select and insert records with a single MySQL query −" }, { "code": null, "e": 2030, "s": 1833, "text": "mysql> insert into DemoTable1\n -> select Name,89 from DemoTable2\n -> union all\n -> select Name,98 from DemoTable2;\nQuery OK, 2 rows affected (0.15 sec)\nRecords: 2 Duplicates: 0 Warnings: 0" }, { "code": null, "e": 2080, "s": 2030, "text": "Now you can select records from the first table −" }, { "code": null, "e": 2113, "s": 2080, "text": "mysql> select * from DemoTable1;" }, { "code": null, "e": 2154, "s": 2113, "text": "This will produce the following output −" }, { "code": null, "e": 2365, "s": 2154, "text": "+-------------+--------------+\n| StudentName | StudentMarks |\n+-------------+--------------+\n| Chris | 89 |\n| Chris | 98 |\n+-------------+--------------+\n2 rows in set (0.00 sec)" } ]
CI/CD for Lambda functions with Azure DevOps and .Net Core | by Lucas Bazetto | Towards Data Science
With each passing day, the serverless model is being more present in software development with new resources, tools, and approaches. However, without control, we can easily create a nightmare. Like the uncle Ben said: “With great power comes great responsibility”. One of the ways to help us with this “responsibility”, is having a CI/CD pipeline for the Lambda functions and extract the whole benefits of a full ALM. Motivated by all these points in this post we are going to create a pipeline to deploy our Lambda Function. So, let’s start! :D Azure DevOps account AWS Account Basic knowledge of C# We need to create a Programmatic access user that will be responsible for connecting the AWS and the Azure DevOps accounts. For tests and only for tests you can set this permission to your user: Never, never, never grant all access in production. In terms of security, less is more :) With our AWS programmatic user, access key, and secret key, we can create the Azure DevOps project. One of my favorite features of the Azure DevOps is the Pipeline. I’m a big fan of this resource because it is very easy to use and when necessary it can be used to handle huge and complex scenarios. Firstly we are going to connect both accounts: This Toolkit is necessary to create a service connection and enable the LambdaDeployFunction task that we will use in the pipeline job. You can follow this link to install the tool. With the toolkit installed on our account, we can move to the next step. And create the service account: AWS Service Connection: Fill it with your AWS Credentials and add a Name: For this example, a variable group is necessary as we will use it to store the Lambda Function ARN, this link contains all information necessary to create and configure the group. Awesome! Now we have the Azure DevOps project connected within our AWS account. Let’s finally see a bit of code :D You can clone the full source code from here: git clone https://github.com/lbazetto/dotnet-core-aws-lambda-ci-cd-pipeline-azuredevops.git As the project is based on .Net Lambda Tools, we are keeping the recommended folder structure: .├── awsLambdaCICDPipeline.sln├── azure-pipelines.yml├── src│ └── awsLambdaCICDPipeline│ ├── Function.cs│ └── awsLambdaCICDPipeline.csproj└── test └── awsLambdaCICDPipeline.Tests ├── FunctionTest.cs └── awsLambdaCICDPipeline.Tests.csproj The src folder contains the Lambda function and the test folder contains the unit tests. As the idea is the focus on the process instead of the Lambda function itself, the code is very simple, it just receives a string and does a ToUpper. And in the unit test, it just mocks the context and calls the function: With everything sorted, its time to check the most important part of this tutorial, the pipeline. Our Pipeline has 2 stages: This stage is responsible for build, run the unit tests, and publish the Artifacts to Azure DevOps. That stage deploys the Lambda function that has been created in the first stage. Splitting our build definition into stages makes it more flexible and help us to create some specific rules for each case. In this scenario, we can run the same definition either when creating a pull request or when the pull request is completed. The YAML definition: Now is time to create the Pipeline: Choose the code location: You might be required to put some credentials depending on your code location. And we are able to see the YAML definition now: Just save it and you can see the pipeline in your repo.Important: if your code is on Github, a pull request validation will be created automatically. If not you can set it via branch policies. We have now: The AWS Account linked to AzureDevOps The source code with the Lambda Function and the YAML definition When a pull is created, we can see the checks on Github. And if you click in the pipeline details is possible to notice that the Deploy stage has been skipped. Once the pipeline is completed and code is merged to master we are able to see that now both stages have been run: Finally, we can see our Lambda function deployed from the Azure DevOps: And that is it! What do you think about it? Is there is something that you are doing in another way or do you think that I can improve? Please let me know :) Thank you very much for your time! Originally posted in https://devandops.cloud/ci-cd-for-lambda-functions-with-azure-devops-and-net-core/
[ { "code": null, "e": 304, "s": 171, "text": "With each passing day, the serverless model is being more present in software development with new resources, tools, and approaches." }, { "code": null, "e": 436, "s": 304, "text": "However, without control, we can easily create a nightmare. Like the uncle Ben said: “With great power comes great responsibility”." }, { "code": null, "e": 589, "s": 436, "text": "One of the ways to help us with this “responsibility”, is having a CI/CD pipeline for the Lambda functions and extract the whole benefits of a full ALM." }, { "code": null, "e": 697, "s": 589, "text": "Motivated by all these points in this post we are going to create a pipeline to deploy our Lambda Function." }, { "code": null, "e": 717, "s": 697, "text": "So, let’s start! :D" }, { "code": null, "e": 738, "s": 717, "text": "Azure DevOps account" }, { "code": null, "e": 750, "s": 738, "text": "AWS Account" }, { "code": null, "e": 772, "s": 750, "text": "Basic knowledge of C#" }, { "code": null, "e": 896, "s": 772, "text": "We need to create a Programmatic access user that will be responsible for connecting the AWS and the Azure DevOps accounts." }, { "code": null, "e": 967, "s": 896, "text": "For tests and only for tests you can set this permission to your user:" }, { "code": null, "e": 1057, "s": 967, "text": "Never, never, never grant all access in production. In terms of security, less is more :)" }, { "code": null, "e": 1157, "s": 1057, "text": "With our AWS programmatic user, access key, and secret key, we can create the Azure DevOps project." }, { "code": null, "e": 1356, "s": 1157, "text": "One of my favorite features of the Azure DevOps is the Pipeline. I’m a big fan of this resource because it is very easy to use and when necessary it can be used to handle huge and complex scenarios." }, { "code": null, "e": 1403, "s": 1356, "text": "Firstly we are going to connect both accounts:" }, { "code": null, "e": 1539, "s": 1403, "text": "This Toolkit is necessary to create a service connection and enable the LambdaDeployFunction task that we will use in the pipeline job." }, { "code": null, "e": 1585, "s": 1539, "text": "You can follow this link to install the tool." }, { "code": null, "e": 1658, "s": 1585, "text": "With the toolkit installed on our account, we can move to the next step." }, { "code": null, "e": 1690, "s": 1658, "text": "And create the service account:" }, { "code": null, "e": 1714, "s": 1690, "text": "AWS Service Connection:" }, { "code": null, "e": 1764, "s": 1714, "text": "Fill it with your AWS Credentials and add a Name:" }, { "code": null, "e": 1944, "s": 1764, "text": "For this example, a variable group is necessary as we will use it to store the Lambda Function ARN, this link contains all information necessary to create and configure the group." }, { "code": null, "e": 2059, "s": 1944, "text": "Awesome! Now we have the Azure DevOps project connected within our AWS account. Let’s finally see a bit of code :D" }, { "code": null, "e": 2105, "s": 2059, "text": "You can clone the full source code from here:" }, { "code": null, "e": 2197, "s": 2105, "text": "git clone https://github.com/lbazetto/dotnet-core-aws-lambda-ci-cd-pipeline-azuredevops.git" }, { "code": null, "e": 2292, "s": 2197, "text": "As the project is based on .Net Lambda Tools, we are keeping the recommended folder structure:" }, { "code": null, "e": 2561, "s": 2292, "text": ".├── awsLambdaCICDPipeline.sln├── azure-pipelines.yml├── src│ └── awsLambdaCICDPipeline│ ├── Function.cs│ └── awsLambdaCICDPipeline.csproj└── test └── awsLambdaCICDPipeline.Tests ├── FunctionTest.cs └── awsLambdaCICDPipeline.Tests.csproj" }, { "code": null, "e": 2650, "s": 2561, "text": "The src folder contains the Lambda function and the test folder contains the unit tests." }, { "code": null, "e": 2872, "s": 2650, "text": "As the idea is the focus on the process instead of the Lambda function itself, the code is very simple, it just receives a string and does a ToUpper. And in the unit test, it just mocks the context and calls the function:" }, { "code": null, "e": 2997, "s": 2872, "text": "With everything sorted, its time to check the most important part of this tutorial, the pipeline. Our Pipeline has 2 stages:" }, { "code": null, "e": 3097, "s": 2997, "text": "This stage is responsible for build, run the unit tests, and publish the Artifacts to Azure DevOps." }, { "code": null, "e": 3178, "s": 3097, "text": "That stage deploys the Lambda function that has been created in the first stage." }, { "code": null, "e": 3425, "s": 3178, "text": "Splitting our build definition into stages makes it more flexible and help us to create some specific rules for each case. In this scenario, we can run the same definition either when creating a pull request or when the pull request is completed." }, { "code": null, "e": 3446, "s": 3425, "text": "The YAML definition:" }, { "code": null, "e": 3482, "s": 3446, "text": "Now is time to create the Pipeline:" }, { "code": null, "e": 3508, "s": 3482, "text": "Choose the code location:" }, { "code": null, "e": 3587, "s": 3508, "text": "You might be required to put some credentials depending on your code location." }, { "code": null, "e": 3635, "s": 3587, "text": "And we are able to see the YAML definition now:" }, { "code": null, "e": 3828, "s": 3635, "text": "Just save it and you can see the pipeline in your repo.Important: if your code is on Github, a pull request validation will be created automatically. If not you can set it via branch policies." }, { "code": null, "e": 3841, "s": 3828, "text": "We have now:" }, { "code": null, "e": 3879, "s": 3841, "text": "The AWS Account linked to AzureDevOps" }, { "code": null, "e": 3944, "s": 3879, "text": "The source code with the Lambda Function and the YAML definition" }, { "code": null, "e": 4001, "s": 3944, "text": "When a pull is created, we can see the checks on Github." }, { "code": null, "e": 4104, "s": 4001, "text": "And if you click in the pipeline details is possible to notice that the Deploy stage has been skipped." }, { "code": null, "e": 4219, "s": 4104, "text": "Once the pipeline is completed and code is merged to master we are able to see that now both stages have been run:" }, { "code": null, "e": 4291, "s": 4219, "text": "Finally, we can see our Lambda function deployed from the Azure DevOps:" }, { "code": null, "e": 4307, "s": 4291, "text": "And that is it!" }, { "code": null, "e": 4449, "s": 4307, "text": "What do you think about it? Is there is something that you are doing in another way or do you think that I can improve? Please let me know :)" }, { "code": null, "e": 4484, "s": 4449, "text": "Thank you very much for your time!" } ]
How to set your python path on Linux?
To set the PYTHONPATH on Linux to point Python to look in other directories for the module and package imports, export the PYTHONPATH variable as follows: $ export PYTHONPATH=${PYTHONPATH}:${HOME}/foo In this case, are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble.
[ { "code": null, "e": 1217, "s": 1062, "text": "To set the PYTHONPATH on Linux to point Python to look in other directories for the module and package imports, export the PYTHONPATH variable as follows:" }, { "code": null, "e": 1263, "s": 1217, "text": "$ export PYTHONPATH=${PYTHONPATH}:${HOME}/foo" }, { "code": null, "e": 1537, "s": 1263, "text": "In this case, are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble." } ]
How to get a number of vowels in a string in JavaScript?
Vowels in English language are a,e,i,o and u. Make sure that, in any string these vowels can be both cases ( either small or capital). The following example, using a user defined function called 'noOfVowels()', reads an input string and compares that string with another string which contains only vowels( 'aAeEiIoOuU'). It takes the help of indexOf() method to proceed the task. The indexOf() method displays index of a character whenever the character is common to both the strings, in unmatched case it displays '-1' as the output. Here it compares each and every character of the input string to the vowel string and whenever vowels got matched, it internally increments a user defined variable called "vowelsCount", which is initially 0. Eventually, the value in the "vowelsCount" is displayed as the output. Live Demo <html> <body> <script> function noOfVowels(string) { var listOfVowels = 'aAeEiIoOuU'; var vowelsCount = 0; for(var i = 0; i < string.length ; i++) { if (listOfVowels.indexOf(string[i]) !== -1) { vowelsCount += 1; } } return vowelsCount; } document.write(noOfVowels("Tutorix is one of the best e-platforms")); </script> </body> </html> 12
[ { "code": null, "e": 1198, "s": 1062, "text": "Vowels in English language are a,e,i,o and u. Make sure that, in any string these vowels can be both cases ( either small or capital). " }, { "code": null, "e": 1444, "s": 1198, "text": "The following example, using a user defined function called 'noOfVowels()', reads an input string and compares that string with another string which contains only vowels( 'aAeEiIoOuU'). It takes the help of indexOf() method to proceed the task. " }, { "code": null, "e": 1878, "s": 1444, "text": "The indexOf() method displays index of a character whenever the character is common to both the strings, in unmatched case it displays '-1' as the output. Here it compares each and every character of the input string to the vowel string and whenever vowels got matched, it internally increments a user defined variable called \"vowelsCount\", which is initially 0. Eventually, the value in the \"vowelsCount\" is displayed as the output." }, { "code": null, "e": 1888, "s": 1878, "text": "Live Demo" }, { "code": null, "e": 2288, "s": 1888, "text": "<html>\n<body>\n<script>\n function noOfVowels(string) {\n var listOfVowels = 'aAeEiIoOuU';\n var vowelsCount = 0;\n for(var i = 0; i < string.length ; i++) {\n if (listOfVowels.indexOf(string[i]) !== -1) {\n vowelsCount += 1;\n }\n }\n return vowelsCount;\n }\n document.write(noOfVowels(\"Tutorix is one of the best e-platforms\"));\n</script>\n</body>\n</html>" }, { "code": null, "e": 2291, "s": 2288, "text": "12" } ]
Python | Get matching substrings in string - GeeksforGeeks
25 Jun, 2019 The testing of a single substring in a string has been discussed many times. But sometimes, we have a list of potential substrings and check which ones occur in a target string as a substring. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehensionUsing list comprehension is the naive and brute force method to perform this particular task. In this method, we try to get the matching string using the “in” operator and store it in new list. # Python3 code to demonstrate working of# Get matching substrings in string# Using list comprehension # initializing string test_str = "GfG is good website" # initializing potential substringstest_list = ["GfG", "site", "CS", "Geeks", "Tutorial" ] # printing original string print("The original string is : " + test_str) # printing potential strings listprint("The original list is : " + str(test_list)) # using list comprehension# Get matching substrings in stringres = [sub for sub in test_list if sub in test_str] # printing result print("The list of found substrings : " + str(res)) The original string is : GfG is good website The original list is : ['GfG', 'site', 'CS', 'Geeks', 'Tutorial'] The list of found substrings : ['GfG', 'site'] Method #2 : Using filter() + lambdaThis task can also be performed using the filter function which performs the task of filtering out the resultant strings that is checked for existence using the lambda function. # Python3 code to demonstrate working of# Get matching substrings in string# Using lambda and filter() # initializing string test_str = "GfG is good website" # initializing potential substringstest_list = ["GfG", "site", "CS", "Geeks", "Tutorial" ] # printing original string print("The original string is : " + test_str) # printing potential strings listprint("The original list is : " + str(test_list)) # using lambda and filter()# Get matching substrings in stringres = list(filter(lambda x: x in test_str, test_list)) # printing result print("The list of found substrings : " + str(res)) The original string is : GfG is good website The original list is : ['GfG', 'site', 'CS', 'Geeks', 'Tutorial'] The list of found substrings : ['GfG', 'site'] Python string-programs Python Python Programs 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 ? Selecting rows in pandas DataFrame based on conditions How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Check if element exists in list in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary How to print without newline in Python?
[ { "code": null, "e": 24212, "s": 24184, "text": "\n25 Jun, 2019" }, { "code": null, "e": 24469, "s": 24212, "text": "The testing of a single substring in a string has been discussed many times. But sometimes, we have a list of potential substrings and check which ones occur in a target string as a substring. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 24699, "s": 24469, "text": "Method #1 : Using list comprehensionUsing list comprehension is the naive and brute force method to perform this particular task. In this method, we try to get the matching string using the “in” operator and store it in new list." }, { "code": "# Python3 code to demonstrate working of# Get matching substrings in string# Using list comprehension # initializing string test_str = \"GfG is good website\" # initializing potential substringstest_list = [\"GfG\", \"site\", \"CS\", \"Geeks\", \"Tutorial\" ] # printing original string print(\"The original string is : \" + test_str) # printing potential strings listprint(\"The original list is : \" + str(test_list)) # using list comprehension# Get matching substrings in stringres = [sub for sub in test_list if sub in test_str] # printing result print(\"The list of found substrings : \" + str(res))", "e": 25292, "s": 24699, "text": null }, { "code": null, "e": 25451, "s": 25292, "text": "The original string is : GfG is good website\nThe original list is : ['GfG', 'site', 'CS', 'Geeks', 'Tutorial']\nThe list of found substrings : ['GfG', 'site']\n" }, { "code": null, "e": 25666, "s": 25453, "text": "Method #2 : Using filter() + lambdaThis task can also be performed using the filter function which performs the task of filtering out the resultant strings that is checked for existence using the lambda function." }, { "code": "# Python3 code to demonstrate working of# Get matching substrings in string# Using lambda and filter() # initializing string test_str = \"GfG is good website\" # initializing potential substringstest_list = [\"GfG\", \"site\", \"CS\", \"Geeks\", \"Tutorial\" ] # printing original string print(\"The original string is : \" + test_str) # printing potential strings listprint(\"The original list is : \" + str(test_list)) # using lambda and filter()# Get matching substrings in stringres = list(filter(lambda x: x in test_str, test_list)) # printing result print(\"The list of found substrings : \" + str(res))", "e": 26265, "s": 25666, "text": null }, { "code": null, "e": 26424, "s": 26265, "text": "The original string is : GfG is good website\nThe original list is : ['GfG', 'site', 'CS', 'Geeks', 'Tutorial']\nThe list of found substrings : ['GfG', 'site']\n" }, { "code": null, "e": 26447, "s": 26424, "text": "Python string-programs" }, { "code": null, "e": 26454, "s": 26447, "text": "Python" }, { "code": null, "e": 26470, "s": 26454, "text": "Python Programs" }, { "code": null, "e": 26568, "s": 26470, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26577, "s": 26568, "text": "Comments" }, { "code": null, "e": 26590, "s": 26577, "text": "Old Comments" }, { "code": null, "e": 26622, "s": 26590, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26677, "s": 26622, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 26733, "s": 26677, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 26772, "s": 26733, "text": "Python | Get unique values from a list" }, { "code": null, "e": 26814, "s": 26772, "text": "Check if element exists in list in Python" }, { "code": null, "e": 26836, "s": 26814, "text": "Defaultdict in Python" }, { "code": null, "e": 26875, "s": 26836, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26921, "s": 26875, "text": "Python | Split string into list of characters" }, { "code": null, "e": 26959, "s": 26921, "text": "Python | Convert a list to dictionary" } ]
Java Program to Print any Statement without Using the Main Method - GeeksforGeeks
17 Nov, 2020 As we know that the static block executes before the main method, hence we can place the statement that we want to execute in the static block, But in case of JDK7, and the above versions of the JDK, the code would not execute as compiler firstly looks for the main method before any other thing. Also, it depends on the IDE being used to run the program, ie the program might get executed successfully on some IDE, and might not on some IDE’s. Also, we can abnormally exit our program in the static block so that the JVM will not check the main method, but as discussed it depends on IDE, whether the program will run or not. Example: Below is the code implementation of the above approach. Java // Java Program printing the statement without using main// method. class PrintWithoutMain { // static block static { // prints "Hello World!!" to the console System.out.println("Hello World!!"); // exit from the program System.exit(1); }} Output Hello World!! The above code does not compile before and on JDK7. Also, one might get the error like below if run the above code on some IDE like Intellij or Netbeans or console. Picked Technical Scripter 2020 Java Java Programs Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Constructors in Java Exceptions in Java Functional Interfaces in Java Different ways of Reading a text file in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class How to Iterate HashMap in Java? Program to print ASCII Value of a character
[ { "code": null, "e": 25225, "s": 25197, "text": "\n17 Nov, 2020" }, { "code": null, "e": 25852, "s": 25225, "text": "As we know that the static block executes before the main method, hence we can place the statement that we want to execute in the static block, But in case of JDK7, and the above versions of the JDK, the code would not execute as compiler firstly looks for the main method before any other thing. Also, it depends on the IDE being used to run the program, ie the program might get executed successfully on some IDE, and might not on some IDE’s. Also, we can abnormally exit our program in the static block so that the JVM will not check the main method, but as discussed it depends on IDE, whether the program will run or not." }, { "code": null, "e": 25917, "s": 25852, "text": "Example: Below is the code implementation of the above approach." }, { "code": null, "e": 25922, "s": 25917, "text": "Java" }, { "code": "// Java Program printing the statement without using main// method. class PrintWithoutMain { // static block static { // prints \"Hello World!!\" to the console System.out.println(\"Hello World!!\"); // exit from the program System.exit(1); }}", "e": 26207, "s": 25922, "text": null }, { "code": null, "e": 26214, "s": 26207, "text": "Output" }, { "code": null, "e": 26228, "s": 26214, "text": "Hello World!!" }, { "code": null, "e": 26394, "s": 26228, "text": "The above code does not compile before and on JDK7. Also, one might get the error like below if run the above code on some IDE like Intellij or Netbeans or console. " }, { "code": null, "e": 26401, "s": 26394, "text": "Picked" }, { "code": null, "e": 26425, "s": 26401, "text": "Technical Scripter 2020" }, { "code": null, "e": 26430, "s": 26425, "text": "Java" }, { "code": null, "e": 26444, "s": 26430, "text": "Java Programs" }, { "code": null, "e": 26463, "s": 26444, "text": "Technical Scripter" }, { "code": null, "e": 26468, "s": 26463, "text": "Java" }, { "code": null, "e": 26566, "s": 26468, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26581, "s": 26566, "text": "Stream In Java" }, { "code": null, "e": 26602, "s": 26581, "text": "Constructors in Java" }, { "code": null, "e": 26621, "s": 26602, "text": "Exceptions in Java" }, { "code": null, "e": 26651, "s": 26621, "text": "Functional Interfaces in Java" }, { "code": null, "e": 26697, "s": 26651, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 26723, "s": 26697, "text": "Java Programming Examples" }, { "code": null, "e": 26757, "s": 26723, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 26804, "s": 26757, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 26836, "s": 26804, "text": "How to Iterate HashMap in Java?" } ]
Convert characters of string1 to characters present in string2 by incrementing or decrementing lexicographically - GeeksforGeeks
02 Feb, 2022 Given two strings A and B having lower case English alphabets, the task is to find the number of operations required to convert string A such that it only contains letters that are also in the string B where at each operation, the current character can be changed to either the next character or the previous character. Also, the next character after ‘z‘ is ‘a‘ and the previous character after ‘a‘ is ‘z‘. Examples: Input: A = “abcd”, B = “bc”Output: 2Explanation: The given string A = “abcd” can be converted into the string “bbcc” by incrementing the 1st character of the string in 1st move and decrementing the last character in 2nd move. Hence, A = “bbcc” has all the characters that are also in string B. Therefore, the required number of moves is 2 which is the minimum possible. Input: A = “abcde”, B = “yg”Output: 14 Approach: The given problem can be solved using a greedy approach. The idea is to convert all the characters in string A that are not in the string B into the nearest possible character that exists in string B which can be done by following the below steps: Store the frequency of characters of the string B in an unordered map m. Iterate through the given string A and check for each character in B, the number of steps required to convert the current character to it. The ways to convert a character x to y can be of two different types as follows:The 1st one is to increment the character x until y is reached i.e, clockwise rotation.The 2nd one is to decrement the character x until y is reached, i.e, anticlockwise rotation. The 1st one is to increment the character x until y is reached i.e, clockwise rotation. The 2nd one is to decrement the character x until y is reached, i.e, anticlockwise rotation. Hence, maintain the sum of all the minimum of the moves in clockwise and anticlockwise rotations for each character in A, in a variable ans, which is the required value. 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 calculate minimum number// of operations required to convert A// such that it only contains letters// in the string Bint minOperations(string a, string b){ // Stores the characters in string B unordered_map<char, int> m; for (int i = 0; i < b.size(); i++) { m[b[i]]++; } // Stores the min count of operations int ans = 0; // Loop to iterate the given array for (int i = 0; i < a.size(); i++) { // Stores the minimum number of // moves required for ith index int mn = INT_MAX; // Loop to calculate the number // of moves required to convert // the current index for (int j = 0; j < 26; j++) { int val = a[i] - 'a'; // If the current character // is also in b if (m[a[i]] > 0) { mn = 0; break; } else if (m['a' + j] > 0) { // Minimum of abs(val - j), // clockwise rotation and // anti clockwise rotation mn = min(mn, min(abs(val - j), min((26 - val) + j, val + (26 - j)))); } } // Update answer ans += mn; } // Return Answer return ans;} int main(){ string A = "abcde"; string B = "yg"; cout << minOperations(A, B); return 0;} // Java implementation of the above approachimport java.util.*;class GFG{ // Function to calculate minimum number// of operations required to convert A// such that it only contains letters// in the String Bstatic int minOperations(String a, String b){ // Stores the characters in String B HashMap<Character,Integer> m = new HashMap<Character,Integer>(); for (int i = 0; i < b.length(); i++) { if(m.containsKey(b.charAt(i))){ m.put(b.charAt(i), m.get(b.charAt(i))+1); } else{ m.put(b.charAt(i), 1); } } // Stores the min count of operations int ans = 0; // Loop to iterate the given array for (int i = 0; i < a.length(); i++) { // Stores the minimum number of // moves required for ith index int mn = Integer.MAX_VALUE; // Loop to calculate the number // of moves required to convert // the current index for (int j = 0; j < 26; j++) { int val = a.charAt(i) - 'a'; // If the current character // is also in b if (m.containsKey(a.charAt(i))&&m.get(a.charAt(i)) > 0) { mn = 0; break; } else if (m.containsKey((char)('a' + j))&&m.get((char)('a' + j)) > 0) { // Minimum of Math.abs(val - j), // clockwise rotation and // anti clockwise rotation mn = Math.min(mn, Math.min(Math.abs(val - j), Math.min((26 - val) + j, val + (26 - j)))); } } // Update answer ans += mn; } // Return Answer return ans;} public static void main(String[] args){ String A = "abcde"; String B = "yg"; System.out.print(minOperations(A, B)); }} // This code is contributed by 29AjayKumar # Python3 implementation of the above approachINT_MAX = 2147483647 # Function to calculate minimum number# of operations required to convert A# such that it only contains letters# in the string Bdef minOperations(a, b): # Stores the characters in string B m = {} for i in range(0, len(b)): if b[i] in m: m[b[i]] += 1 else: m[b[i]] = 1 # Stores the min count of operations ans = 0 # Loop to iterate the given array for i in range(0, len(a)): # Stores the minimum number of # moves required for ith index mn = INT_MAX # Loop to calculate the number # of moves required to convert # the current index for j in range(0, 26): val = ord(a[i]) - ord('a') # If the current character # is also in b if (a[i] in m and m[a[i]] > 0): mn = 0 break elif (chr(ord('a') + j) in m and m[chr(ord('a') + j)] > 0): # Minimum of abs(val - j), # clockwise rotation and # anti clockwise rotation mn = min(mn, min(abs(val - j), min((26 - val) + j, val + (26 - j)))) # Update answer ans += mn # Return Answer return ans # Driver codeif __name__ == "__main__": A = "abcde" B = "yg" print(minOperations(A, B)) # This code is contributed by rakeshsahni // C# implementation of the above approachusing System;using System.Collections.Generic;class GFG{ // Function to calculate Minimum number // of operations required to convert A // such that it only contains letters // in the String B static int MinOperations(String a, String b) { // Stores the characters in String B Dictionary<char, int> m = new Dictionary<char, int>(); for (int i = 0; i < b.Length; i++) { if (m.ContainsKey(b[i])) { m[b[i]] += 1; } else { m[b[i]] = 1; } } // Stores the Min count of operations int ans = 0; // Loop to iterate the given array for (int i = 0; i < a.Length; i++) { // Stores the Minimum number of // moves required for ith index int mn = int.MaxValue; // Loop to calculate the number // of moves required to convert // the current index for (int j = 0; j < 26; j++) { int val = a[i] - 'a'; // If the current character // is also in b if (m.ContainsKey(a[i]) && m[a[i]] > 0) { mn = 0; break; } else if (m.ContainsKey((char)('a' + j)) && m[(char)('a' + j)] > 0) { // Minimum of Math.abs(val - j), // clockwise rotation and // anti clockwise rotation mn = Math.Min(mn, Math.Min(Math.Abs(val - j), Math.Min((26 - val) + j, val + (26 - j)))); } } // Update answer ans += mn; } // Return Answer return ans; } public static void Main() { String A = "abcde"; String B = "yg"; Console.Write(MinOperations(A, B)); }} // This code is contributed by gfgking <script> // JavaScript Program to implement // the above approach // Function to calculate minimum number // of operations required to convert A // such that it only contains letters // in the string B function minOperations(a, b) { // Stores the characters in string B let m = new Map(); for (let i = 0; i < b.length; i++) { if (m.has(b[i])) { m.set(b[i], m.get(b[i]) + 1); } else { m.set(b[i], 1); } } // Stores the min count of operations let ans = 0; // Loop to iterate the given array for (let i = 0; i< a.length; i++) { // Stores the minimum number of // moves required for ith index let mn = 999999; // Loop to calculate the number // of moves required to convert // the current index for (let j = 0; j< 26; j++) { let val = a[i].charCodeAt(0) - 'a'.charCodeAt(0); // If the current character // is also in b if (m.get(a[i]) > 0) { mn = 0; break; } else if (m.has(String.fromCharCode('a'.charCodeAt(0) + j)) && m.get(String.fromCharCode('a'.charCodeAt(0) + j)) > 0) { // Minimum of abs(val - j), // clockwise rotation and // anti clockwise rotation mn = Math.min(mn, Math.min(Math.abs(val - j), Math.min((26 - val) + j, val + (26 - j)))); } } // Update answer ans += mn; } // Return Answer return ans; } let A = "abcde"; let B = "yg"; document.write(minOperations(A, B)); // This code is contributed by Potta Lokesh </script> 14 Time Complexity: O(N)Auxiliary Space: O(1) lokeshpotta20 rakeshsahni 29AjayKumar gfgking simranarora5sos surinderdawra388 lexicographic-ordering Arrays Combinatorial Strings Arrays Strings Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Write a program to print all permutations of a given string Permutation and Combination in Python itertools.combinations() module in Python to print all possible combinations Combinational Sum Factorial of a large number
[ { "code": null, "e": 26066, "s": 26038, "text": "\n02 Feb, 2022" }, { "code": null, "e": 26473, "s": 26066, "text": "Given two strings A and B having lower case English alphabets, the task is to find the number of operations required to convert string A such that it only contains letters that are also in the string B where at each operation, the current character can be changed to either the next character or the previous character. Also, the next character after ‘z‘ is ‘a‘ and the previous character after ‘a‘ is ‘z‘." }, { "code": null, "e": 26483, "s": 26473, "text": "Examples:" }, { "code": null, "e": 26853, "s": 26483, "text": "Input: A = “abcd”, B = “bc”Output: 2Explanation: The given string A = “abcd” can be converted into the string “bbcc” by incrementing the 1st character of the string in 1st move and decrementing the last character in 2nd move. Hence, A = “bbcc” has all the characters that are also in string B. Therefore, the required number of moves is 2 which is the minimum possible." }, { "code": null, "e": 26892, "s": 26853, "text": "Input: A = “abcde”, B = “yg”Output: 14" }, { "code": null, "e": 27150, "s": 26892, "text": "Approach: The given problem can be solved using a greedy approach. The idea is to convert all the characters in string A that are not in the string B into the nearest possible character that exists in string B which can be done by following the below steps:" }, { "code": null, "e": 27223, "s": 27150, "text": "Store the frequency of characters of the string B in an unordered map m." }, { "code": null, "e": 27362, "s": 27223, "text": "Iterate through the given string A and check for each character in B, the number of steps required to convert the current character to it." }, { "code": null, "e": 27622, "s": 27362, "text": "The ways to convert a character x to y can be of two different types as follows:The 1st one is to increment the character x until y is reached i.e, clockwise rotation.The 2nd one is to decrement the character x until y is reached, i.e, anticlockwise rotation." }, { "code": null, "e": 27710, "s": 27622, "text": "The 1st one is to increment the character x until y is reached i.e, clockwise rotation." }, { "code": null, "e": 27803, "s": 27710, "text": "The 2nd one is to decrement the character x until y is reached, i.e, anticlockwise rotation." }, { "code": null, "e": 27973, "s": 27803, "text": "Hence, maintain the sum of all the minimum of the moves in clockwise and anticlockwise rotations for each character in A, in a variable ans, which is the required value." }, { "code": null, "e": 28024, "s": 27973, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28028, "s": 28024, "text": "C++" }, { "code": null, "e": 28033, "s": 28028, "text": "Java" }, { "code": null, "e": 28041, "s": 28033, "text": "Python3" }, { "code": null, "e": 28044, "s": 28041, "text": "C#" }, { "code": null, "e": 28055, "s": 28044, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate minimum number// of operations required to convert A// such that it only contains letters// in the string Bint minOperations(string a, string b){ // Stores the characters in string B unordered_map<char, int> m; for (int i = 0; i < b.size(); i++) { m[b[i]]++; } // Stores the min count of operations int ans = 0; // Loop to iterate the given array for (int i = 0; i < a.size(); i++) { // Stores the minimum number of // moves required for ith index int mn = INT_MAX; // Loop to calculate the number // of moves required to convert // the current index for (int j = 0; j < 26; j++) { int val = a[i] - 'a'; // If the current character // is also in b if (m[a[i]] > 0) { mn = 0; break; } else if (m['a' + j] > 0) { // Minimum of abs(val - j), // clockwise rotation and // anti clockwise rotation mn = min(mn, min(abs(val - j), min((26 - val) + j, val + (26 - j)))); } } // Update answer ans += mn; } // Return Answer return ans;} int main(){ string A = \"abcde\"; string B = \"yg\"; cout << minOperations(A, B); return 0;}", "e": 29550, "s": 28055, "text": null }, { "code": "// Java implementation of the above approachimport java.util.*;class GFG{ // Function to calculate minimum number// of operations required to convert A// such that it only contains letters// in the String Bstatic int minOperations(String a, String b){ // Stores the characters in String B HashMap<Character,Integer> m = new HashMap<Character,Integer>(); for (int i = 0; i < b.length(); i++) { if(m.containsKey(b.charAt(i))){ m.put(b.charAt(i), m.get(b.charAt(i))+1); } else{ m.put(b.charAt(i), 1); } } // Stores the min count of operations int ans = 0; // Loop to iterate the given array for (int i = 0; i < a.length(); i++) { // Stores the minimum number of // moves required for ith index int mn = Integer.MAX_VALUE; // Loop to calculate the number // of moves required to convert // the current index for (int j = 0; j < 26; j++) { int val = a.charAt(i) - 'a'; // If the current character // is also in b if (m.containsKey(a.charAt(i))&&m.get(a.charAt(i)) > 0) { mn = 0; break; } else if (m.containsKey((char)('a' + j))&&m.get((char)('a' + j)) > 0) { // Minimum of Math.abs(val - j), // clockwise rotation and // anti clockwise rotation mn = Math.min(mn, Math.min(Math.abs(val - j), Math.min((26 - val) + j, val + (26 - j)))); } } // Update answer ans += mn; } // Return Answer return ans;} public static void main(String[] args){ String A = \"abcde\"; String B = \"yg\"; System.out.print(minOperations(A, B)); }} // This code is contributed by 29AjayKumar", "e": 31436, "s": 29550, "text": null }, { "code": "# Python3 implementation of the above approachINT_MAX = 2147483647 # Function to calculate minimum number# of operations required to convert A# such that it only contains letters# in the string Bdef minOperations(a, b): # Stores the characters in string B m = {} for i in range(0, len(b)): if b[i] in m: m[b[i]] += 1 else: m[b[i]] = 1 # Stores the min count of operations ans = 0 # Loop to iterate the given array for i in range(0, len(a)): # Stores the minimum number of # moves required for ith index mn = INT_MAX # Loop to calculate the number # of moves required to convert # the current index for j in range(0, 26): val = ord(a[i]) - ord('a') # If the current character # is also in b if (a[i] in m and m[a[i]] > 0): mn = 0 break elif (chr(ord('a') + j) in m and m[chr(ord('a') + j)] > 0): # Minimum of abs(val - j), # clockwise rotation and # anti clockwise rotation mn = min(mn, min(abs(val - j), min((26 - val) + j, val + (26 - j)))) # Update answer ans += mn # Return Answer return ans # Driver codeif __name__ == \"__main__\": A = \"abcde\" B = \"yg\" print(minOperations(A, B)) # This code is contributed by rakeshsahni", "e": 32943, "s": 31436, "text": null }, { "code": "// C# implementation of the above approachusing System;using System.Collections.Generic;class GFG{ // Function to calculate Minimum number // of operations required to convert A // such that it only contains letters // in the String B static int MinOperations(String a, String b) { // Stores the characters in String B Dictionary<char, int> m = new Dictionary<char, int>(); for (int i = 0; i < b.Length; i++) { if (m.ContainsKey(b[i])) { m[b[i]] += 1; } else { m[b[i]] = 1; } } // Stores the Min count of operations int ans = 0; // Loop to iterate the given array for (int i = 0; i < a.Length; i++) { // Stores the Minimum number of // moves required for ith index int mn = int.MaxValue; // Loop to calculate the number // of moves required to convert // the current index for (int j = 0; j < 26; j++) { int val = a[i] - 'a'; // If the current character // is also in b if (m.ContainsKey(a[i]) && m[a[i]] > 0) { mn = 0; break; } else if (m.ContainsKey((char)('a' + j)) && m[(char)('a' + j)] > 0) { // Minimum of Math.abs(val - j), // clockwise rotation and // anti clockwise rotation mn = Math.Min(mn, Math.Min(Math.Abs(val - j), Math.Min((26 - val) + j, val + (26 - j)))); } } // Update answer ans += mn; } // Return Answer return ans; } public static void Main() { String A = \"abcde\"; String B = \"yg\"; Console.Write(MinOperations(A, B)); }} // This code is contributed by gfgking", "e": 35022, "s": 32943, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Function to calculate minimum number // of operations required to convert A // such that it only contains letters // in the string B function minOperations(a, b) { // Stores the characters in string B let m = new Map(); for (let i = 0; i < b.length; i++) { if (m.has(b[i])) { m.set(b[i], m.get(b[i]) + 1); } else { m.set(b[i], 1); } } // Stores the min count of operations let ans = 0; // Loop to iterate the given array for (let i = 0; i< a.length; i++) { // Stores the minimum number of // moves required for ith index let mn = 999999; // Loop to calculate the number // of moves required to convert // the current index for (let j = 0; j< 26; j++) { let val = a[i].charCodeAt(0) - 'a'.charCodeAt(0); // If the current character // is also in b if (m.get(a[i]) > 0) { mn = 0; break; } else if (m.has(String.fromCharCode('a'.charCodeAt(0) + j)) && m.get(String.fromCharCode('a'.charCodeAt(0) + j)) > 0) { // Minimum of abs(val - j), // clockwise rotation and // anti clockwise rotation mn = Math.min(mn, Math.min(Math.abs(val - j), Math.min((26 - val) + j, val + (26 - j)))); } } // Update answer ans += mn; } // Return Answer return ans; } let A = \"abcde\"; let B = \"yg\"; document.write(minOperations(A, B)); // This code is contributed by Potta Lokesh </script>", "e": 37308, "s": 35022, "text": null }, { "code": null, "e": 37311, "s": 37308, "text": "14" }, { "code": null, "e": 37354, "s": 37311, "text": "Time Complexity: O(N)Auxiliary Space: O(1)" }, { "code": null, "e": 37370, "s": 37356, "text": "lokeshpotta20" }, { "code": null, "e": 37382, "s": 37370, "text": "rakeshsahni" }, { "code": null, "e": 37394, "s": 37382, "text": "29AjayKumar" }, { "code": null, "e": 37402, "s": 37394, "text": "gfgking" }, { "code": null, "e": 37418, "s": 37402, "text": "simranarora5sos" }, { "code": null, "e": 37435, "s": 37418, "text": "surinderdawra388" }, { "code": null, "e": 37458, "s": 37435, "text": "lexicographic-ordering" }, { "code": null, "e": 37465, "s": 37458, "text": "Arrays" }, { "code": null, "e": 37479, "s": 37465, "text": "Combinatorial" }, { "code": null, "e": 37487, "s": 37479, "text": "Strings" }, { "code": null, "e": 37494, "s": 37487, "text": "Arrays" }, { "code": null, "e": 37502, "s": 37494, "text": "Strings" }, { "code": null, "e": 37516, "s": 37502, "text": "Combinatorial" }, { "code": null, "e": 37614, "s": 37516, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 37641, "s": 37614, "text": "Count pairs with given sum" }, { "code": null, "e": 37672, "s": 37641, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 37697, "s": 37672, "text": "Window Sliding Technique" }, { "code": null, "e": 37735, "s": 37697, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 37756, "s": 37735, "text": "Next Greater Element" }, { "code": null, "e": 37816, "s": 37756, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 37854, "s": 37816, "text": "Permutation and Combination in Python" }, { "code": null, "e": 37931, "s": 37854, "text": "itertools.combinations() module in Python to print all possible combinations" }, { "code": null, "e": 37949, "s": 37931, "text": "Combinational Sum" } ]
Iterative program to Calculate Size of a tree - GeeksforGeeks
30 Jun, 2021 Size of a tree is the number of elements present in the tree. Size of the below tree is 5. Approach The idea is to use Level Order Traversing 1) Create an empty queue q 2) temp_node = root /*start from root*/ 3) Loop while temp_node is not NULL a) Enqueue temp_node’s children (first left then right children) to q b) Increase count with every enqueuing. c) Dequeue a node from q and assign it’s value to temp_node C++ Java Python3 C# Javascript // C++ program to print size of tree in iterative#include<iostream>#include<queue>using namespace std; struct Node{ int data; Node *left, *right;}; // A utility function to// create a new Binary Tree NodeNode *newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} // return size of treeint sizeoftree(Node *root){ // if tree is empty it will // return 0 if(root == NULL) return 0; // Using level order Traversal. queue<Node *> q; int count = 1; q.push(root); while(!q.empty()) { Node *temp = q.front(); if(temp->left) { // Enqueue left child q.push(temp->left); // Increment count count++; } if(temp->right) { // Enqueue right child q.push(temp->right); // Increment count count++; } q.pop(); } return count;} // Driver Codeint main(){ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << "Size of the tree is " << sizeoftree(root) << endl; return 0;} // This code is contributed by SHAKEELMOHAMMAD // Java programn to calculate// Size of a treeimport java.util.LinkedList;import java.util.Queue; class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; public int size() { if (root == null) return 0; // Using level order Traversal. Queue<Node> q = new LinkedList<Node>(); q.offer(root); int count = 1; while (!q.isEmpty()) { Node tmp = q.poll(); // when the queue is empty: // the poll() method returns null. if (tmp != null) { if (tmp.left != null) { // Increment count count++; // Enqueue left child q.offer(tmp.left); } if (tmp.right != null) { // Increment count count++; // Enqueue left child q.offer(tmp.right); } } } return count; } public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println("The size of binary tree" + " is : " + tree.size()); }} # Python Program to calculate size of the tree iteratively # Node Structureclass newNode: def __init__(self,data): self.data = data self.left = self.right = None # Return size of treedef sizeoftree(root): if root == None: return 0 q = [] q.append(root) count = 1 while(len(q) != 0): root = q.pop(0) if(root.left): q.append(root.left) count += 1 if(root.right): q.append(root.right) count += 1 return count # Driver Programroot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.left = newNode(4)root.left.right = newNode(5)print(sizeoftree(root)) # This is code is contributed by simranjenny84 // C# programn to calculate// Size of a treeusing System;using System.Collections.Generic; public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ Node root; public int size() { if (root == null) return 0; // Using level order Traversal. Queue<Node> q = new Queue<Node>(); q.Enqueue(root); int count = 1; while (q.Count != 0) { Node tmp = q.Dequeue(); // when the queue is empty: // the poll() method returns null. if (tmp != null) { if (tmp.left != null) { // Increment count count++; // Enqueue left child q.Enqueue(tmp.left); } if (tmp.right != null) { // Increment count count++; // Enqueue left child q.Enqueue(tmp.right); } } } return count; } // Driver code public static void Main(String []args) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); Console.WriteLine("The size of binary tree" + " is : " + tree.size()); }} // This code has been contributed by 29AjayKumar <script> // JavaScript programn to calculate Size of a tree class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } let root; function size() { if (root == null) return 0; // Using level order Traversal. let q = []; q.push(root); let count = 1; while (q.length > 0) { let tmp = q[0]; q.shift(); // when the queue is empty: // the poll() method returns null. if (tmp != null) { if (tmp.left != null) { // Increment count count++; // Enqueue left child q.push(tmp.left); } if (tmp.right != null) { // Increment count count++; // Enqueue left child q.push(tmp.right); } } } return count; } /* creating a binary tree and entering the nodes */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); document.write("Size of the tree is " + size()); </script> Output: Size of the tree is 5 Time Complexity: O(n) Auxiliary Space: O(level_max) where level max is maximum number of node in any level. YouTubeGeeksforGeeks507K subscribersIterative program to Calculate Size of a tree | 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 / 3:37•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=0gPDf0n4A2M" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> 29AjayKumar SHAKEELMOHAMMAD simranjenny84 decode2207 java-LinkedList Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Tree Data Structure DFS traversal of a tree using recursion Top 50 Tree Coding Problems for Interviews Find the node with minimum value in a Binary Search Tree Print Binary Tree in 2-Dimensions Real-time application of Data Structures Iterative Postorder Traversal | Set 2 (Using One Stack) Find maximum (or minimum) in Binary Tree Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash) Difference between Min Heap and Max Heap
[ { "code": null, "e": 26183, "s": 26155, "text": "\n30 Jun, 2021" }, { "code": null, "e": 26276, "s": 26183, "text": "Size of a tree is the number of elements present in the tree. Size of the below tree is 5. " }, { "code": null, "e": 26331, "s": 26278, "text": "Approach The idea is to use Level Order Traversing " }, { "code": null, "e": 26616, "s": 26331, "text": "1) Create an empty queue q\n2) temp_node = root /*start from root*/\n3) Loop while temp_node is not NULL\n a) Enqueue temp_node’s children (first left then right children) to q\n b) Increase count with every enqueuing.\n c) Dequeue a node from q and assign it’s value to temp_node" }, { "code": null, "e": 26622, "s": 26618, "text": "C++" }, { "code": null, "e": 26627, "s": 26622, "text": "Java" }, { "code": null, "e": 26635, "s": 26627, "text": "Python3" }, { "code": null, "e": 26638, "s": 26635, "text": "C#" }, { "code": null, "e": 26649, "s": 26638, "text": "Javascript" }, { "code": "// C++ program to print size of tree in iterative#include<iostream>#include<queue>using namespace std; struct Node{ int data; Node *left, *right;}; // A utility function to// create a new Binary Tree NodeNode *newNode(int data){ Node *temp = new Node; temp->data = data; temp->left = NULL; temp->right = NULL; return temp;} // return size of treeint sizeoftree(Node *root){ // if tree is empty it will // return 0 if(root == NULL) return 0; // Using level order Traversal. queue<Node *> q; int count = 1; q.push(root); while(!q.empty()) { Node *temp = q.front(); if(temp->left) { // Enqueue left child q.push(temp->left); // Increment count count++; } if(temp->right) { // Enqueue right child q.push(temp->right); // Increment count count++; } q.pop(); } return count;} // Driver Codeint main(){ Node *root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); cout << \"Size of the tree is \" << sizeoftree(root) << endl; return 0;} // This code is contributed by SHAKEELMOHAMMAD", "e": 27998, "s": 26649, "text": null }, { "code": "// Java programn to calculate// Size of a treeimport java.util.LinkedList;import java.util.Queue; class Node{ int data; Node left, right; public Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; public int size() { if (root == null) return 0; // Using level order Traversal. Queue<Node> q = new LinkedList<Node>(); q.offer(root); int count = 1; while (!q.isEmpty()) { Node tmp = q.poll(); // when the queue is empty: // the poll() method returns null. if (tmp != null) { if (tmp.left != null) { // Increment count count++; // Enqueue left child q.offer(tmp.left); } if (tmp.right != null) { // Increment count count++; // Enqueue left child q.offer(tmp.right); } } } return count; } public static void main(String args[]) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); System.out.println(\"The size of binary tree\" + \" is : \" + tree.size()); }}", "e": 29682, "s": 27998, "text": null }, { "code": "# Python Program to calculate size of the tree iteratively # Node Structureclass newNode: def __init__(self,data): self.data = data self.left = self.right = None # Return size of treedef sizeoftree(root): if root == None: return 0 q = [] q.append(root) count = 1 while(len(q) != 0): root = q.pop(0) if(root.left): q.append(root.left) count += 1 if(root.right): q.append(root.right) count += 1 return count # Driver Programroot = newNode(1)root.left = newNode(2)root.right = newNode(3)root.left.left = newNode(4)root.left.right = newNode(5)print(sizeoftree(root)) # This is code is contributed by simranjenny84", "e": 30411, "s": 29682, "text": null }, { "code": "// C# programn to calculate// Size of a treeusing System;using System.Collections.Generic; public class Node{ public int data; public Node left, right; public Node(int item) { data = item; left = right = null; }} public class BinaryTree{ Node root; public int size() { if (root == null) return 0; // Using level order Traversal. Queue<Node> q = new Queue<Node>(); q.Enqueue(root); int count = 1; while (q.Count != 0) { Node tmp = q.Dequeue(); // when the queue is empty: // the poll() method returns null. if (tmp != null) { if (tmp.left != null) { // Increment count count++; // Enqueue left child q.Enqueue(tmp.left); } if (tmp.right != null) { // Increment count count++; // Enqueue left child q.Enqueue(tmp.right); } } } return count; } // Driver code public static void Main(String []args) { /* creating a binary tree and entering the nodes */ BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); Console.WriteLine(\"The size of binary tree\" + \" is : \" + tree.size()); }} // This code has been contributed by 29AjayKumar", "e": 32183, "s": 30411, "text": null }, { "code": "<script> // JavaScript programn to calculate Size of a tree class Node { constructor(item) { this.left = null; this.right = null; this.data = item; } } let root; function size() { if (root == null) return 0; // Using level order Traversal. let q = []; q.push(root); let count = 1; while (q.length > 0) { let tmp = q[0]; q.shift(); // when the queue is empty: // the poll() method returns null. if (tmp != null) { if (tmp.left != null) { // Increment count count++; // Enqueue left child q.push(tmp.left); } if (tmp.right != null) { // Increment count count++; // Enqueue left child q.push(tmp.right); } } } return count; } /* creating a binary tree and entering the nodes */ root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.left.left = new Node(4); root.left.right = new Node(5); document.write(\"Size of the tree is \" + size()); </script>", "e": 33660, "s": 32183, "text": null }, { "code": null, "e": 33670, "s": 33660, "text": "Output: " }, { "code": null, "e": 33692, "s": 33670, "text": "Size of the tree is 5" }, { "code": null, "e": 33802, "s": 33692, "text": "Time Complexity: O(n) Auxiliary Space: O(level_max) where level max is maximum number of node in any level. " }, { "code": null, "e": 34646, "s": 33802, "text": "YouTubeGeeksforGeeks507K subscribersIterative program to Calculate Size of a tree | 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 / 3:37•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=0gPDf0n4A2M\" 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": 34658, "s": 34646, "text": "29AjayKumar" }, { "code": null, "e": 34674, "s": 34658, "text": "SHAKEELMOHAMMAD" }, { "code": null, "e": 34688, "s": 34674, "text": "simranjenny84" }, { "code": null, "e": 34699, "s": 34688, "text": "decode2207" }, { "code": null, "e": 34715, "s": 34699, "text": "java-LinkedList" }, { "code": null, "e": 34720, "s": 34715, "text": "Tree" }, { "code": null, "e": 34725, "s": 34720, "text": "Tree" }, { "code": null, "e": 34823, "s": 34725, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34859, "s": 34823, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 34899, "s": 34859, "text": "DFS traversal of a tree using recursion" }, { "code": null, "e": 34942, "s": 34899, "text": "Top 50 Tree Coding Problems for Interviews" }, { "code": null, "e": 34999, "s": 34942, "text": "Find the node with minimum value in a Binary Search Tree" }, { "code": null, "e": 35033, "s": 34999, "text": "Print Binary Tree in 2-Dimensions" }, { "code": null, "e": 35074, "s": 35033, "text": "Real-time application of Data Structures" }, { "code": null, "e": 35130, "s": 35074, "text": "Iterative Postorder Traversal | Set 2 (Using One Stack)" }, { "code": null, "e": 35171, "s": 35130, "text": "Find maximum (or minimum) in Binary Tree" }, { "code": null, "e": 35241, "s": 35171, "text": "Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)" } ]
getmaxy() function in C - GeeksforGeeks
25 Jan, 2018 The header file graphics.h contains getmaxy() function which returns the maximum Y coordinate for current graphics mode and driver.Syntax : int getmaxy(); Below is the implementation of getmaxy() function: // C Implementation for getmaxy()#include <graphics.h>#include <stdio.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // "graphics.h" header file int gd = DETECT, gm; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, ""); // sprintf stands for “String print”. // Instead of printing on console, it // store output on char buffer which // are specified in sprintf sprintf(arr, "Maximum Y coordinate for current " "graphics mode And driver = %d", getmaxy()); // outtext function displays text at // current position. outtext(arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;} Output : c-graphics computer-graphics C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Multidimensional Arrays in C / C++ Converting Strings to Numbers in C/C++ Left Shift and Right Shift Operators in C/C++ Function Pointer in C Core Dump (Segmentation fault) in C/C++ rand() and srand() in C/C++ std::string class in C++ fork() in C Different methods to reverse a string in C/C++
[ { "code": null, "e": 25625, "s": 25597, "text": "\n25 Jan, 2018" }, { "code": null, "e": 25765, "s": 25625, "text": "The header file graphics.h contains getmaxy() function which returns the maximum Y coordinate for current graphics mode and driver.Syntax :" }, { "code": null, "e": 25781, "s": 25765, "text": "int getmaxy();\n" }, { "code": null, "e": 25832, "s": 25781, "text": "Below is the implementation of getmaxy() function:" }, { "code": "// C Implementation for getmaxy()#include <graphics.h>#include <stdio.h> // driver codeint main(){ // gm is Graphics mode which is // a computer display mode that // generates image using pixels. // DETECT is a macro defined in // \"graphics.h\" header file int gd = DETECT, gm; char arr[100]; // initgraph initializes the // graphics system by loading a // graphics driver from disk initgraph(&gd, &gm, \"\"); // sprintf stands for “String print”. // Instead of printing on console, it // store output on char buffer which // are specified in sprintf sprintf(arr, \"Maximum Y coordinate for current \" \"graphics mode And driver = %d\", getmaxy()); // outtext function displays text at // current position. outtext(arr); getch(); // closegraph function closes the // graphics mode and deallocates // all memory allocated by // graphics system . closegraph(); return 0;}", "e": 26793, "s": 25832, "text": null }, { "code": null, "e": 26802, "s": 26793, "text": "Output :" }, { "code": null, "e": 26815, "s": 26804, "text": "c-graphics" }, { "code": null, "e": 26833, "s": 26815, "text": "computer-graphics" }, { "code": null, "e": 26844, "s": 26833, "text": "C Language" }, { "code": null, "e": 26942, "s": 26844, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26959, "s": 26942, "text": "Substring in C++" }, { "code": null, "e": 26994, "s": 26959, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 27033, "s": 26994, "text": "Converting Strings to Numbers in C/C++" }, { "code": null, "e": 27079, "s": 27033, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 27101, "s": 27079, "text": "Function Pointer in C" }, { "code": null, "e": 27141, "s": 27101, "text": "Core Dump (Segmentation fault) in C/C++" }, { "code": null, "e": 27169, "s": 27141, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 27194, "s": 27169, "text": "std::string class in C++" }, { "code": null, "e": 27206, "s": 27194, "text": "fork() in C" } ]
How to read specific lines from a File in Python? - GeeksforGeeks
11 Dec, 2020 Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers begin with the 0th index. There are various ways to read specific lines from a text file in python, this article is aimed at discussing them. File in use: test.txt Method 1: fileobject.readlines() A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously. It can be easily used to print lines from any random starting index to some ending index. It initially reads the entire content of the file and keep a copy of it in memory. The lines at the specified indices are then accessed. Example: Python3 # open the sample file usedfile = open('test.txt') # read the content of the file openedcontent = file.readlines() # read 10th line from the fileprint("tenth line")print(content[9]) # print first 3 lines of fileprint("first three lines")print(content[0:3]) Output tenth line This is line 10. first three lines This is line 1.This is line 2.This is line 3. Method 2: linecache package The linecache package can be imported in Python and then be used to extract and access specific lines in Python. The package can be used to read multiple lines simultaneously. It makes use of cache storage to perform optimization internally. This package opens the file on its own and gets to the particular line. This package has getline() method which is used for the same. Syntax: getLine(txt-file, line_number) Example: Python3 # importing required packageimport linecache # extracting the 5th lineparticular_line = linecache.getline('test.txt', 4) # print the particular lineprint(particular_line) Output : This is line 5. Method 3: enumerate() The enumerate() method is used to convert a string or a list object to a sequence of data indexed by numbers. It is then used in the listing of the data in combination with for loop. Lines at particular indexes can be accessed by specifying the index numbers required in an array. Example: Python3 # open a filefile = open("test.txt") # lines to printspecified_lines = [0, 7, 11] # loop over lines in a filefor pos, l_num in enumerate(file): # check if the line number is specified in the lines to read array if pos in specified_lines: # print the required line number print(l_num) Output This is line 1. This is line 8. This is line 12. Python file-handling-programs python-file-handling Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Python | Get unique values from a list Defaultdict in Python Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25562, "s": 25534, "text": "\n11 Dec, 2020" }, { "code": null, "e": 26006, "s": 25562, "text": "Text files are composed of plain text content. Text files are also known as flat files or plain files. Python provides easy support to read and access the content within the file. Text files are first opened and then the content is accessed from it in the order of lines. By default, the line numbers begin with the 0th index. There are various ways to read specific lines from a text file in python, this article is aimed at discussing them. " }, { "code": null, "e": 26028, "s": 26006, "text": "File in use: test.txt" }, { "code": null, "e": 26061, "s": 26028, "text": "Method 1: fileobject.readlines()" }, { "code": null, "e": 26528, "s": 26061, "text": "A file object can be created in Python and then readlines() method can be invoked on this object to read lines into a stream. This method is preferred when a single line or a range of lines from a file needs to be accessed simultaneously. It can be easily used to print lines from any random starting index to some ending index. It initially reads the entire content of the file and keep a copy of it in memory. The lines at the specified indices are then accessed. " }, { "code": null, "e": 26537, "s": 26528, "text": "Example:" }, { "code": null, "e": 26545, "s": 26537, "text": "Python3" }, { "code": "# open the sample file usedfile = open('test.txt') # read the content of the file openedcontent = file.readlines() # read 10th line from the fileprint(\"tenth line\")print(content[9]) # print first 3 lines of fileprint(\"first three lines\")print(content[0:3])", "e": 26805, "s": 26545, "text": null }, { "code": null, "e": 26813, "s": 26805, "text": "Output " }, { "code": null, "e": 26825, "s": 26813, "text": "tenth line " }, { "code": null, "e": 26842, "s": 26825, "text": "This is line 10." }, { "code": null, "e": 26861, "s": 26842, "text": "first three lines " }, { "code": null, "e": 26907, "s": 26861, "text": "This is line 1.This is line 2.This is line 3." }, { "code": null, "e": 26936, "s": 26907, "text": "Method 2: linecache package " }, { "code": null, "e": 27313, "s": 26936, "text": "The linecache package can be imported in Python and then be used to extract and access specific lines in Python. The package can be used to read multiple lines simultaneously. It makes use of cache storage to perform optimization internally. This package opens the file on its own and gets to the particular line. This package has getline() method which is used for the same. " }, { "code": null, "e": 27322, "s": 27313, "text": "Syntax: " }, { "code": null, "e": 27353, "s": 27322, "text": "getLine(txt-file, line_number)" }, { "code": null, "e": 27362, "s": 27353, "text": "Example:" }, { "code": null, "e": 27370, "s": 27362, "text": "Python3" }, { "code": "# importing required packageimport linecache # extracting the 5th lineparticular_line = linecache.getline('test.txt', 4) # print the particular lineprint(particular_line)", "e": 27543, "s": 27370, "text": null }, { "code": null, "e": 27552, "s": 27543, "text": "Output :" }, { "code": null, "e": 27568, "s": 27552, "text": "This is line 5." }, { "code": null, "e": 27590, "s": 27568, "text": "Method 3: enumerate()" }, { "code": null, "e": 27872, "s": 27590, "text": "The enumerate() method is used to convert a string or a list object to a sequence of data indexed by numbers. It is then used in the listing of the data in combination with for loop. Lines at particular indexes can be accessed by specifying the index numbers required in an array. " }, { "code": null, "e": 27881, "s": 27872, "text": "Example:" }, { "code": null, "e": 27889, "s": 27881, "text": "Python3" }, { "code": "# open a filefile = open(\"test.txt\") # lines to printspecified_lines = [0, 7, 11] # loop over lines in a filefor pos, l_num in enumerate(file): # check if the line number is specified in the lines to read array if pos in specified_lines: # print the required line number print(l_num)", "e": 28195, "s": 27889, "text": null }, { "code": null, "e": 28202, "s": 28195, "text": "Output" }, { "code": null, "e": 28251, "s": 28202, "text": "This is line 1.\nThis is line 8.\nThis is line 12." }, { "code": null, "e": 28281, "s": 28251, "text": "Python file-handling-programs" }, { "code": null, "e": 28302, "s": 28281, "text": "python-file-handling" }, { "code": null, "e": 28309, "s": 28302, "text": "Python" }, { "code": null, "e": 28407, "s": 28309, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28439, "s": 28407, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28481, "s": 28439, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28523, "s": 28481, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28550, "s": 28523, "text": "Python Classes and Objects" }, { "code": null, "e": 28606, "s": 28550, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28645, "s": 28606, "text": "Python | Get unique values from a list" }, { "code": null, "e": 28667, "s": 28645, "text": "Defaultdict in Python" }, { "code": null, "e": 28698, "s": 28667, "text": "Python | os.path.join() method" }, { "code": null, "e": 28727, "s": 28698, "text": "Create a directory in Python" } ]
PostgreSQL - CREATE PROCEDURE - GeeksforGeeks
28 Aug, 2020 PostgreSQL CREATE PROCEDURE statement as the name suggests is used to create new stored procedures. So far, you have learned how to define user-defined functions using the create function statement. A drawback of user-defined functions is that they cannot execute transactions. In other words, inside a user-defined function, you cannot start a transaction, and commit or rollback it. PostgreSQL 11 introduced stored procedures that support transactions. To define a new stored procedure, you use the create procedure statement. The following illustrates the basic syntax of the create procedure statement: Syntax: create [or replace] procedure procedure_name(parameter_list) language plpgsql as $$ declare -- variable declaration begin -- stored procedure body end; $$ Let’s analyze the above syntax: First, specify the name of the stored procedure after the create procedure keywords. Second, define parameters for the stored procedure. A stored procedure can accept zero or more parameters. Third, specify plpgsql as the procedural language for the stored procedure. Note that you can use other procedural languages for the stored procedure such as SQL, C, etc. Finally, use the dollar-quoted string constant syntax to define the body of the stored procedure. Parameters in stored procedures can have the in and inout modes. They cannot have the out mode. A stored procedure does not return a value. You cannot use the return statement with a value inside a store procedure like this: return expression; However, you can use the return statement without the expression to stop the stored procedure immediately: return; Example: We will use the following accounts table for the demonstration: drop table if exists accounts; create table accounts ( id int generated by default as identity, name varchar(100) not null, balance dec(15, 2) not null, primary key(id) ); insert into accounts(name, balance) values('Raju', 10000); insert into accounts(name, balance) values('Nikhil', 10000); The following query will show the table data: select * from accounts; That depicts the result as shown below: The following query creates a stored procedure named transfer that transfers a specified amount of money from one account to another. create or replace procedure transfer( sender int, receiver int, amount dec ) language plpgsql as $$ begin -- subtracting the amount from the sender's account update accounts set balance = balance - amount where id = sender; -- adding the amount to the receiver's account update accounts set balance = balance + amount where id = receiver; commit; end;$$ To call a stored procedure, you use the CALL statement as follows: call stored_procedure_name(argument_list); Example: The below statement invokes the transfer stored procedure to transfer $1, 000 from Raju’s account to Nikhil’s account: call transfer(1, 2, 1000); The following statement verifies the data in the accounts table after the transfer: SELECT * FROM accounts; Output: postgreSQL-stored-procedures PostgreSQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. PostgreSQL - GROUP BY clause PostgreSQL - DROP INDEX PostgreSQL - REPLACE Function PostgreSQL - Copy Table PostgreSQL - TIME Data Type PostgreSQL - CREATE SCHEMA PostgreSQL - ROW_NUMBER Function PostgreSQL - SELECT PostgreSQL - Identity Column PostgreSQL - Cursor
[ { "code": null, "e": 25315, "s": 25287, "text": "\n28 Aug, 2020" }, { "code": null, "e": 25514, "s": 25315, "text": "PostgreSQL CREATE PROCEDURE statement as the name suggests is used to create new stored procedures. So far, you have learned how to define user-defined functions using the create function statement." }, { "code": null, "e": 25844, "s": 25514, "text": "A drawback of user-defined functions is that they cannot execute transactions. In other words, inside a user-defined function, you cannot start a transaction, and commit or rollback it. PostgreSQL 11 introduced stored procedures that support transactions. To define a new stored procedure, you use the create procedure statement." }, { "code": null, "e": 25922, "s": 25844, "text": "The following illustrates the basic syntax of the create procedure statement:" }, { "code": null, "e": 26086, "s": 25922, "text": "Syntax:\ncreate [or replace] procedure procedure_name(parameter_list)\nlanguage plpgsql\nas $$\ndeclare\n-- variable declaration\nbegin\n-- stored procedure body\nend; $$\n" }, { "code": null, "e": 26118, "s": 26086, "text": "Let’s analyze the above syntax:" }, { "code": null, "e": 26203, "s": 26118, "text": "First, specify the name of the stored procedure after the create procedure keywords." }, { "code": null, "e": 26310, "s": 26203, "text": "Second, define parameters for the stored procedure. A stored procedure can accept zero or more parameters." }, { "code": null, "e": 26481, "s": 26310, "text": "Third, specify plpgsql as the procedural language for the stored procedure. Note that you can use other procedural languages for the stored procedure such as SQL, C, etc." }, { "code": null, "e": 26579, "s": 26481, "text": "Finally, use the dollar-quoted string constant syntax to define the body of the stored procedure." }, { "code": null, "e": 26804, "s": 26579, "text": "Parameters in stored procedures can have the in and inout modes. They cannot have the out mode. A stored procedure does not return a value. You cannot use the return statement with a value inside a store procedure like this:" }, { "code": null, "e": 26824, "s": 26804, "text": "return expression;\n" }, { "code": null, "e": 26931, "s": 26824, "text": "However, you can use the return statement without the expression to stop the stored procedure immediately:" }, { "code": null, "e": 26940, "s": 26931, "text": "return;\n" }, { "code": null, "e": 26949, "s": 26940, "text": "Example:" }, { "code": null, "e": 27013, "s": 26949, "text": "We will use the following accounts table for the demonstration:" }, { "code": null, "e": 27325, "s": 27013, "text": "drop table if exists accounts;\n\ncreate table accounts (\n id int generated by default as identity,\n name varchar(100) not null,\n balance dec(15, 2) not null,\n primary key(id)\n);\n\ninsert into accounts(name, balance)\nvalues('Raju', 10000);\n\ninsert into accounts(name, balance)\nvalues('Nikhil', 10000);\n" }, { "code": null, "e": 27371, "s": 27325, "text": "The following query will show the table data:" }, { "code": null, "e": 27396, "s": 27371, "text": "select * from accounts;\n" }, { "code": null, "e": 27436, "s": 27396, "text": "That depicts the result as shown below:" }, { "code": null, "e": 27570, "s": 27436, "text": "The following query creates a stored procedure named transfer that transfers a specified amount of money from one account to another." }, { "code": null, "e": 27982, "s": 27570, "text": "create or replace procedure transfer(\n sender int,\n receiver int, \n amount dec\n)\nlanguage plpgsql \nas $$\nbegin\n -- subtracting the amount from the sender's account \n update accounts \n set balance = balance - amount \n where id = sender;\n\n -- adding the amount to the receiver's account\n update accounts \n set balance = balance + amount \n where id = receiver;\n\n commit;\nend;$$\n" }, { "code": null, "e": 28049, "s": 27982, "text": "To call a stored procedure, you use the CALL statement as follows:" }, { "code": null, "e": 28093, "s": 28049, "text": "call stored_procedure_name(argument_list);\n" }, { "code": null, "e": 28102, "s": 28093, "text": "Example:" }, { "code": null, "e": 28221, "s": 28102, "text": "The below statement invokes the transfer stored procedure to transfer $1, 000 from Raju’s account to Nikhil’s account:" }, { "code": null, "e": 28249, "s": 28221, "text": "call transfer(1, 2, 1000);\n" }, { "code": null, "e": 28333, "s": 28249, "text": "The following statement verifies the data in the accounts table after the transfer:" }, { "code": null, "e": 28358, "s": 28333, "text": "SELECT * FROM accounts;\n" }, { "code": null, "e": 28366, "s": 28358, "text": "Output:" }, { "code": null, "e": 28395, "s": 28366, "text": "postgreSQL-stored-procedures" }, { "code": null, "e": 28406, "s": 28395, "text": "PostgreSQL" }, { "code": null, "e": 28504, "s": 28406, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28533, "s": 28504, "text": "PostgreSQL - GROUP BY clause" }, { "code": null, "e": 28557, "s": 28533, "text": "PostgreSQL - DROP INDEX" }, { "code": null, "e": 28587, "s": 28557, "text": "PostgreSQL - REPLACE Function" }, { "code": null, "e": 28611, "s": 28587, "text": "PostgreSQL - Copy Table" }, { "code": null, "e": 28639, "s": 28611, "text": "PostgreSQL - TIME Data Type" }, { "code": null, "e": 28666, "s": 28639, "text": "PostgreSQL - CREATE SCHEMA" }, { "code": null, "e": 28699, "s": 28666, "text": "PostgreSQL - ROW_NUMBER Function" }, { "code": null, "e": 28719, "s": 28699, "text": "PostgreSQL - SELECT" }, { "code": null, "e": 28748, "s": 28719, "text": "PostgreSQL - Identity Column" } ]
Kill a Process by name using Python - GeeksforGeeks
30 Jun, 2021 A process is identified on the system by what is referred to as a process ID and no other process can use that number as its process ID while that first process is still running. Imagine you are a system administrator of a company and you start an application from your menu and you start using that application suddenly you notice that the application stopped working or die unexpectedly. You again try to start that application but it turns out that application never shut down completely. Since you are an administrator you type a command to Process ID and kill that process immediately. Imagine this scenario the employees of your company came to you every day complaining about the same situation since they don’t know what is PID and how to kill a process. So you came up with the idea of writing a script in Python which take input only the name of application or process and shut it down completely. You gave this script to your employees so every time this happens they don’t need to complain to you or know what is process id or how to kill the process, just enter the name, and everything will be taken care of. Functions used: os.popen(): This method is used to opens a pip to and from command. In the image below you can see that the process firefox is running os.kill(): This method in Python is used to send a specified signal to the process with specified process id. Below is the implementation. In the image below you can see that the process firefox is running. Python3 import os, signal def process(): # Ask user for the name of process name = input("Enter process Name: ") try: # iterating through each instance of the process for line in os.popen("ps ax | grep " + name + " | grep -v grep"): fields = line.split() # extracting Process ID from the output pid = fields[0] # terminating process os.kill(int(pid), signal.SIGKILL) print("Process Successfully terminated") except: print("Error Encountered while running script") process() Output: In the image above you can see that all the instance of firefox has been terminated. The one that you seeing in the image is the instance that is being called by grep command. You can now check that your firefox browser has been shut completely. varshagumber28 Python os-module-programs python-os-module python-utility Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25951, "s": 25923, "text": "\n30 Jun, 2021" }, { "code": null, "e": 27075, "s": 25951, "text": "A process is identified on the system by what is referred to as a process ID and no other process can use that number as its process ID while that first process is still running. Imagine you are a system administrator of a company and you start an application from your menu and you start using that application suddenly you notice that the application stopped working or die unexpectedly. You again try to start that application but it turns out that application never shut down completely. Since you are an administrator you type a command to Process ID and kill that process immediately. Imagine this scenario the employees of your company came to you every day complaining about the same situation since they don’t know what is PID and how to kill a process. So you came up with the idea of writing a script in Python which take input only the name of application or process and shut it down completely. You gave this script to your employees so every time this happens they don’t need to complain to you or know what is process id or how to kill the process, just enter the name, and everything will be taken care of. " }, { "code": null, "e": 27092, "s": 27075, "text": "Functions used: " }, { "code": null, "e": 27228, "s": 27092, "text": "os.popen(): This method is used to opens a pip to and from command. In the image below you can see that the process firefox is running " }, { "code": null, "e": 27339, "s": 27228, "text": "os.kill(): This method in Python is used to send a specified signal to the process with specified process id. " }, { "code": null, "e": 27368, "s": 27339, "text": "Below is the implementation." }, { "code": null, "e": 27438, "s": 27368, "text": "In the image below you can see that the process firefox is running. " }, { "code": null, "e": 27446, "s": 27438, "text": "Python3" }, { "code": "import os, signal def process(): # Ask user for the name of process name = input(\"Enter process Name: \") try: # iterating through each instance of the process for line in os.popen(\"ps ax | grep \" + name + \" | grep -v grep\"): fields = line.split() # extracting Process ID from the output pid = fields[0] # terminating process os.kill(int(pid), signal.SIGKILL) print(\"Process Successfully terminated\") except: print(\"Error Encountered while running script\") process()", "e": 28058, "s": 27446, "text": null }, { "code": null, "e": 28067, "s": 28058, "text": "Output: " }, { "code": null, "e": 28314, "s": 28067, "text": "In the image above you can see that all the instance of firefox has been terminated. The one that you seeing in the image is the instance that is being called by grep command. You can now check that your firefox browser has been shut completely. " }, { "code": null, "e": 28329, "s": 28314, "text": "varshagumber28" }, { "code": null, "e": 28355, "s": 28329, "text": "Python os-module-programs" }, { "code": null, "e": 28372, "s": 28355, "text": "python-os-module" }, { "code": null, "e": 28387, "s": 28372, "text": "python-utility" }, { "code": null, "e": 28394, "s": 28387, "text": "Python" }, { "code": null, "e": 28492, "s": 28394, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28510, "s": 28492, "text": "Python Dictionary" }, { "code": null, "e": 28545, "s": 28510, "text": "Read a file line by line in Python" }, { "code": null, "e": 28577, "s": 28545, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28599, "s": 28577, "text": "Enumerate() in Python" }, { "code": null, "e": 28641, "s": 28599, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28671, "s": 28641, "text": "Iterate over a list in Python" }, { "code": null, "e": 28697, "s": 28671, "text": "Python String | replace()" }, { "code": null, "e": 28726, "s": 28697, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28770, "s": 28726, "text": "Reading and Writing to text files in Python" } ]