title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
Sort an array of objects using Boolean property in JavaScript
|
30 Jan, 2020
Given the JavaScript array containing Boolean values. The task is to sort the array on the basis of Boolean value with the help of JavaScript. Here 2 approaches are discussed here.Approach 1:
Use JavaScript Array.sort() method.
In Comparison condition, Use === operator to compare the Boolean objects.
Return 0, 1 and -1 means equal, greater and smaller respectively depending upon the comparison.
Example 1: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Sort an array of objects by a Boolean property in JavaScript. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="GFG_Fun();"> click here </button> <p id="GFG_DOWN" style="color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); a = [false, true, false, true, false]; up.innerHTML = "Click on the button to sort the array"+ "on boolean property.<br>Array = [" + a + "]"; function GFG_Fun() { a.sort(function(x, y) { return (x === y) ? 0 : x ? -1 : 1; }); down.innerHTML = "Sorted Array - [" + a + "]"; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Approach 2:
Use JavaScript Array.sort() method.
In Comparison condition, Subtract the first element from the second one to compare the objects and return that value.
Use .reverse() method, If the result is needed to be reversed.
Example 2: This example implements the above approach.
<!DOCTYPE HTML><html> <head> <title> Sort an array of objects by a Boolean property in JavaScript. </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"> </script></head> <body style="text-align:center;"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP"> </p> <button onclick="GFG_Fun();"> click here </button> <p id="GFG_DOWN" style="color: green;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); a = [false, true, false, true, false]; up.innerHTML = "Click on the button to sort the array on boolean "+ "property.<br>Array = [" + a + "]"; function GFG_Fun() { a.sort((a, b) => b - a).reverse(); down.innerHTML = "Sorted Array - [" + a + "]"; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jan, 2020"
},
{
"code": null,
"e": 220,
"s": 28,
"text": "Given the JavaScript array containing Boolean values. The task is to sort the array on the basis of Boolean value with the help of JavaScript. Here 2 approaches are discussed here.Approach 1:"
},
{
"code": null,
"e": 256,
"s": 220,
"text": "Use JavaScript Array.sort() method."
},
{
"code": null,
"e": 330,
"s": 256,
"text": "In Comparison condition, Use === operator to compare the Boolean objects."
},
{
"code": null,
"e": 426,
"s": 330,
"text": "Return 0, 1 and -1 means equal, greater and smaller respectively depending upon the comparison."
},
{
"code": null,
"e": 481,
"s": 426,
"text": "Example 1: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Sort an array of objects by a Boolean property in JavaScript. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); a = [false, true, false, true, false]; up.innerHTML = \"Click on the button to sort the array\"+ \"on boolean property.<br>Array = [\" + a + \"]\"; function GFG_Fun() { a.sort(function(x, y) { return (x === y) ? 0 : x ? -1 : 1; }); down.innerHTML = \"Sorted Array - [\" + a + \"]\"; } </script></body> </html>",
"e": 1486,
"s": 481,
"text": null
},
{
"code": null,
"e": 1494,
"s": 1486,
"text": "Output:"
},
{
"code": null,
"e": 1525,
"s": 1494,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 1555,
"s": 1525,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 1567,
"s": 1555,
"text": "Approach 2:"
},
{
"code": null,
"e": 1603,
"s": 1567,
"text": "Use JavaScript Array.sort() method."
},
{
"code": null,
"e": 1721,
"s": 1603,
"text": "In Comparison condition, Subtract the first element from the second one to compare the objects and return that value."
},
{
"code": null,
"e": 1784,
"s": 1721,
"text": "Use .reverse() method, If the result is needed to be reversed."
},
{
"code": null,
"e": 1839,
"s": 1784,
"text": "Example 2: This example implements the above approach."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> Sort an array of objects by a Boolean property in JavaScript. </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"> </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\"> </p> <button onclick=\"GFG_Fun();\"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); a = [false, true, false, true, false]; up.innerHTML = \"Click on the button to sort the array on boolean \"+ \"property.<br>Array = [\" + a + \"]\"; function GFG_Fun() { a.sort((a, b) => b - a).reverse(); down.innerHTML = \"Sorted Array - [\" + a + \"]\"; } </script></body> </html>",
"e": 2790,
"s": 1839,
"text": null
},
{
"code": null,
"e": 2798,
"s": 2790,
"text": "Output:"
},
{
"code": null,
"e": 2829,
"s": 2798,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 2859,
"s": 2829,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 2875,
"s": 2859,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2886,
"s": 2875,
"text": "JavaScript"
},
{
"code": null,
"e": 2903,
"s": 2886,
"text": "Web Technologies"
},
{
"code": null,
"e": 2930,
"s": 2903,
"text": "Web technologies Questions"
}
] |
getAttribute() – Passing data from Server to JSP
|
03 Dec, 2018
Suppose some data at the Server side has been created and now in order to pass that information in a JSP page, there is a need of request.getAttribute() method. This, in fact differentiates the getAttribute() and getParameter() methods. The latter is used to pass Client side data to a JSP.
Implementation1) First create data at the server side and pass it to a JSP. Here a list of student objects in a servlet will be created and pass it to a JSP using setAttribute().2) Next, the JSP will retrieve the sent data using getAttribute().3) Finally, the JSP will display the data retrieved, in a tabular form.
Servlet to create data and dispatch it to a JSP : StudentServlet.java
package saagnik; import java.io.*;import java.util.ArrayList;import javax.servlet.*;import javax.servlet.http.*; public class StudentServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet StudentServlet</title>"); out.println("</head>"); out.println("<body>"); // List to hold Student objects ArrayList<Student> std = new ArrayList<Student>(); // Adding members to the list. Here we are // using the parameterized constructor of // class "Student.java" std.add(new Student("Roxy Willard", 22, "B.D.S")); std.add(new Student("Todd Lanz", 22, "B.Tech")); std.add(new Student("Varlene Lade", 21, "B.B.A")); std.add(new Student("Julio Fairley", 22, "B.Tech")); std.add(new Student("Helena Carlow", 24, "M.B.B.S")); // Setting the attribute of the request object // which will be later fetched by a JSP page request.setAttribute("data", std); // Creating a RequestDispatcher object to dispatch // the request the request to another resource RequestDispatcher rd = request.getRequestDispatcher("stdlist.jsp"); // The request will be forwarded to the resource // specified, here the resource is a JSP named, // "stdlist.jsp" rd.forward(request, response); out.println("</body>"); out.println("</html>"); } } /** Following methods are used to handle requests coming from the Http protocol request. Inspects method of HttpMethod type and if the request is a POST, the doPost() method will be called or if it is a GET, the doGet() method will be called. **/ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return "Short description"; }}
JSP to retrieve data sent by servlet “StudentServlet.java” and display it : stdlist.jsp
<%@page import="saagnik.Student"%><%@page import="java.util.ArrayList"%><%@page contentType="text/html" pageEncoding="UTF-8"%><!DOCTYPE html><html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Student List</title> </head> <body> <h1>Displaying Student List</h1> <table border ="1" width="500" align="center"> <tr bgcolor="00FF7F"> <th><b>Student Name</b></th> <th><b>Student Age</b></th> <th><b>Course Undertaken</b></th> </tr> <%-- Fetching the attributes of the request object which was previously set by the servlet "StudentServlet.java" --%> <%ArrayList<Student> std = (ArrayList<Student>)request.getAttribute("data"); for(Student s:std){%> <%-- Arranging data in tabular form --%> <tr> <td><%=s.getName()%></td> <td><%=s.getAge()%></td> <td><%=s.getCrs()%></td> </tr> <%}%> </table> <hr/> </body></html>
The Student.java class
package saagnik; public class Student { private int age; private String name; private String crs; // Parameterized Constructor to set Student // name, age, course enrolled in. public Student(String n, int a, String c) { this.name = n; this.age = a; this.crs = c; } // Setter Methods to set table data to be // displayed public String getName() { return name; } public int getAge() { return age; } public String getCrs() { return crs; }}
Running the application1) Run the servlet “StudentServlet.java”, which will pass student data to JSP page “stdlist.jsp”.2) The JSP page “stdlist.jsp” retrieves the data and displays it in a tabular form.
Note : Entire application has been developed and tested on NetBeans IDE 8.1
OutputDisplaying Student Data : stdlist.jsp
HTML-Misc
Java-JSP
HTML
Java Programs
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)
How to set the default value for an HTML <select> element ?
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Dec, 2018"
},
{
"code": null,
"e": 345,
"s": 54,
"text": "Suppose some data at the Server side has been created and now in order to pass that information in a JSP page, there is a need of request.getAttribute() method. This, in fact differentiates the getAttribute() and getParameter() methods. The latter is used to pass Client side data to a JSP."
},
{
"code": null,
"e": 661,
"s": 345,
"text": "Implementation1) First create data at the server side and pass it to a JSP. Here a list of student objects in a servlet will be created and pass it to a JSP using setAttribute().2) Next, the JSP will retrieve the sent data using getAttribute().3) Finally, the JSP will display the data retrieved, in a tabular form."
},
{
"code": null,
"e": 731,
"s": 661,
"text": "Servlet to create data and dispatch it to a JSP : StudentServlet.java"
},
{
"code": "package saagnik; import java.io.*;import java.util.ArrayList;import javax.servlet.*;import javax.servlet.http.*; public class StudentServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType(\"text/html;charset=UTF-8\"); try (PrintWriter out = response.getWriter()) { out.println(\"<!DOCTYPE html>\"); out.println(\"<html>\"); out.println(\"<head>\"); out.println(\"<title>Servlet StudentServlet</title>\"); out.println(\"</head>\"); out.println(\"<body>\"); // List to hold Student objects ArrayList<Student> std = new ArrayList<Student>(); // Adding members to the list. Here we are // using the parameterized constructor of // class \"Student.java\" std.add(new Student(\"Roxy Willard\", 22, \"B.D.S\")); std.add(new Student(\"Todd Lanz\", 22, \"B.Tech\")); std.add(new Student(\"Varlene Lade\", 21, \"B.B.A\")); std.add(new Student(\"Julio Fairley\", 22, \"B.Tech\")); std.add(new Student(\"Helena Carlow\", 24, \"M.B.B.S\")); // Setting the attribute of the request object // which will be later fetched by a JSP page request.setAttribute(\"data\", std); // Creating a RequestDispatcher object to dispatch // the request the request to another resource RequestDispatcher rd = request.getRequestDispatcher(\"stdlist.jsp\"); // The request will be forwarded to the resource // specified, here the resource is a JSP named, // \"stdlist.jsp\" rd.forward(request, response); out.println(\"</body>\"); out.println(\"</html>\"); } } /** Following methods are used to handle requests coming from the Http protocol request. Inspects method of HttpMethod type and if the request is a POST, the doPost() method will be called or if it is a GET, the doGet() method will be called. **/ @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); } @Override public String getServletInfo() { return \"Short description\"; }}",
"e": 3322,
"s": 731,
"text": null
},
{
"code": null,
"e": 3410,
"s": 3322,
"text": "JSP to retrieve data sent by servlet “StudentServlet.java” and display it : stdlist.jsp"
},
{
"code": "<%@page import=\"saagnik.Student\"%><%@page import=\"java.util.ArrayList\"%><%@page contentType=\"text/html\" pageEncoding=\"UTF-8\"%><!DOCTYPE html><html> <head> <meta http-equiv=\"Content-Type\" content=\"text/html; charset=UTF-8\"> <title>Student List</title> </head> <body> <h1>Displaying Student List</h1> <table border =\"1\" width=\"500\" align=\"center\"> <tr bgcolor=\"00FF7F\"> <th><b>Student Name</b></th> <th><b>Student Age</b></th> <th><b>Course Undertaken</b></th> </tr> <%-- Fetching the attributes of the request object which was previously set by the servlet \"StudentServlet.java\" --%> <%ArrayList<Student> std = (ArrayList<Student>)request.getAttribute(\"data\"); for(Student s:std){%> <%-- Arranging data in tabular form --%> <tr> <td><%=s.getName()%></td> <td><%=s.getAge()%></td> <td><%=s.getCrs()%></td> </tr> <%}%> </table> <hr/> </body></html>",
"e": 4493,
"s": 3410,
"text": null
},
{
"code": null,
"e": 4516,
"s": 4493,
"text": "The Student.java class"
},
{
"code": "package saagnik; public class Student { private int age; private String name; private String crs; // Parameterized Constructor to set Student // name, age, course enrolled in. public Student(String n, int a, String c) { this.name = n; this.age = a; this.crs = c; } // Setter Methods to set table data to be // displayed public String getName() { return name; } public int getAge() { return age; } public String getCrs() { return crs; }}",
"e": 5014,
"s": 4516,
"text": null
},
{
"code": null,
"e": 5218,
"s": 5014,
"text": "Running the application1) Run the servlet “StudentServlet.java”, which will pass student data to JSP page “stdlist.jsp”.2) The JSP page “stdlist.jsp” retrieves the data and displays it in a tabular form."
},
{
"code": null,
"e": 5294,
"s": 5218,
"text": "Note : Entire application has been developed and tested on NetBeans IDE 8.1"
},
{
"code": null,
"e": 5338,
"s": 5294,
"text": "OutputDisplaying Student Data : stdlist.jsp"
},
{
"code": null,
"e": 5348,
"s": 5338,
"text": "HTML-Misc"
},
{
"code": null,
"e": 5357,
"s": 5348,
"text": "Java-JSP"
},
{
"code": null,
"e": 5362,
"s": 5357,
"text": "HTML"
},
{
"code": null,
"e": 5376,
"s": 5362,
"text": "Java Programs"
},
{
"code": null,
"e": 5381,
"s": 5376,
"text": "HTML"
},
{
"code": null,
"e": 5479,
"s": 5381,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5527,
"s": 5479,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 5589,
"s": 5527,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5639,
"s": 5589,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 5663,
"s": 5639,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 5723,
"s": 5663,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 5751,
"s": 5723,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 5777,
"s": 5751,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 5821,
"s": 5777,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 5855,
"s": 5821,
"text": "Convert Double to Integer in Java"
}
] |
CSS | fill Property
|
28 Nov, 2019
The fill property is a presentation attribute used to set the color of a SVG shape.
Syntax:
fill: <paint>
Property Values:
paint: It is used to set the color of the fill property. This paint be defined using color names, hex, rgb or hsl values. The default value is black. It can also be used with patterns using the url() function.Example 1: This example illustrates the different color values of fill property.<!DOCTYPE html><html><head> <title> CSS | fill Property </title> <style> .opacity1 { /* using color names */ fill: green; } .opacity2 { /* using hex values */ fill: #ff0000; } .opacity3 { /* using rgb values */ fill: rgb(0, 0, 128); } .opacity4 { /* using hsl values */ fill: hsl(24, 100%, 60%); } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | fill</b> <div class="container"> <svg height="250px" width="600px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <circle class="opacity1" cx="100" cy="100" r="50" /> <circle class="opacity2" cx="250" cy="100" r="50" /> <circle class="opacity3" cx="400" cy="100" r="50" /> <circle class="opacity4" cx="550" cy="100" r="50" /> </svg> </div></body></html>Output:Example 2: This example uses patterns for fill property.<!DOCTYPE html><html><head> <title> CSS | fill property </title> <style> .opacity1 { fill: url(#pattern1); } .opacity2 { fill: url(#pattern2); } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | fill </b> <div class="container"> <svg height="250px" width="600px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <defs> <pattern id="pattern1" viewBox="0, 0, 10, 10" width="10%" height="10%"> <circle r="10" /> </pattern> <pattern id="pattern2" viewBox="0, 0, 10, 10" width="10%" height="10%"> <rect height="5" width="5" fill="green" /> </pattern> </defs> <circle class="opacity1" cx="100" cy="100" r="50" /> <circle class="opacity2" cx="250" cy="100" r="50" /> </svg> </div></body></html>Output:
Example 1: This example illustrates the different color values of fill property.
<!DOCTYPE html><html><head> <title> CSS | fill Property </title> <style> .opacity1 { /* using color names */ fill: green; } .opacity2 { /* using hex values */ fill: #ff0000; } .opacity3 { /* using rgb values */ fill: rgb(0, 0, 128); } .opacity4 { /* using hsl values */ fill: hsl(24, 100%, 60%); } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b>CSS | fill</b> <div class="container"> <svg height="250px" width="600px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <circle class="opacity1" cx="100" cy="100" r="50" /> <circle class="opacity2" cx="250" cy="100" r="50" /> <circle class="opacity3" cx="400" cy="100" r="50" /> <circle class="opacity4" cx="550" cy="100" r="50" /> </svg> </div></body></html>
Output:
Example 2: This example uses patterns for fill property.
<!DOCTYPE html><html><head> <title> CSS | fill property </title> <style> .opacity1 { fill: url(#pattern1); } .opacity2 { fill: url(#pattern2); } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | fill </b> <div class="container"> <svg height="250px" width="600px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <defs> <pattern id="pattern1" viewBox="0, 0, 10, 10" width="10%" height="10%"> <circle r="10" /> </pattern> <pattern id="pattern2" viewBox="0, 0, 10, 10" width="10%" height="10%"> <rect height="5" width="5" fill="green" /> </pattern> </defs> <circle class="opacity1" cx="100" cy="100" r="50" /> <circle class="opacity2" cx="250" cy="100" r="50" /> </svg> </div></body></html>
Output:
Supported Browsers: The browsers supported by fill property are listed below:
Chrome
Firefox
Safari
Opera
Internet Explorer 9
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of CSS (Cascading Style Sheet)
How to set space between the flexbox ?
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
Design a Tribute Page using HTML & CSS
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
How do you run JavaScript script through the Terminal?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2019"
},
{
"code": null,
"e": 112,
"s": 28,
"text": "The fill property is a presentation attribute used to set the color of a SVG shape."
},
{
"code": null,
"e": 120,
"s": 112,
"text": "Syntax:"
},
{
"code": null,
"e": 134,
"s": 120,
"text": "fill: <paint>"
},
{
"code": null,
"e": 151,
"s": 134,
"text": "Property Values:"
},
{
"code": null,
"e": 2296,
"s": 151,
"text": "paint: It is used to set the color of the fill property. This paint be defined using color names, hex, rgb or hsl values. The default value is black. It can also be used with patterns using the url() function.Example 1: This example illustrates the different color values of fill property.<!DOCTYPE html><html><head> <title> CSS | fill Property </title> <style> .opacity1 { /* using color names */ fill: green; } .opacity2 { /* using hex values */ fill: #ff0000; } .opacity3 { /* using rgb values */ fill: rgb(0, 0, 128); } .opacity4 { /* using hsl values */ fill: hsl(24, 100%, 60%); } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | fill</b> <div class=\"container\"> <svg height=\"250px\" width=\"600px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <circle class=\"opacity1\" cx=\"100\" cy=\"100\" r=\"50\" /> <circle class=\"opacity2\" cx=\"250\" cy=\"100\" r=\"50\" /> <circle class=\"opacity3\" cx=\"400\" cy=\"100\" r=\"50\" /> <circle class=\"opacity4\" cx=\"550\" cy=\"100\" r=\"50\" /> </svg> </div></body></html>Output:Example 2: This example uses patterns for fill property.<!DOCTYPE html><html><head> <title> CSS | fill property </title> <style> .opacity1 { fill: url(#pattern1); } .opacity2 { fill: url(#pattern2); } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | fill </b> <div class=\"container\"> <svg height=\"250px\" width=\"600px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <defs> <pattern id=\"pattern1\" viewBox=\"0, 0, 10, 10\" width=\"10%\" height=\"10%\"> <circle r=\"10\" /> </pattern> <pattern id=\"pattern2\" viewBox=\"0, 0, 10, 10\" width=\"10%\" height=\"10%\"> <rect height=\"5\" width=\"5\" fill=\"green\" /> </pattern> </defs> <circle class=\"opacity1\" cx=\"100\" cy=\"100\" r=\"50\" /> <circle class=\"opacity2\" cx=\"250\" cy=\"100\" r=\"50\" /> </svg> </div></body></html>Output:"
},
{
"code": null,
"e": 2377,
"s": 2296,
"text": "Example 1: This example illustrates the different color values of fill property."
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | fill Property </title> <style> .opacity1 { /* using color names */ fill: green; } .opacity2 { /* using hex values */ fill: #ff0000; } .opacity3 { /* using rgb values */ fill: rgb(0, 0, 128); } .opacity4 { /* using hsl values */ fill: hsl(24, 100%, 60%); } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b>CSS | fill</b> <div class=\"container\"> <svg height=\"250px\" width=\"600px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <circle class=\"opacity1\" cx=\"100\" cy=\"100\" r=\"50\" /> <circle class=\"opacity2\" cx=\"250\" cy=\"100\" r=\"50\" /> <circle class=\"opacity3\" cx=\"400\" cy=\"100\" r=\"50\" /> <circle class=\"opacity4\" cx=\"550\" cy=\"100\" r=\"50\" /> </svg> </div></body></html>",
"e": 3258,
"s": 2377,
"text": null
},
{
"code": null,
"e": 3266,
"s": 3258,
"text": "Output:"
},
{
"code": null,
"e": 3323,
"s": 3266,
"text": "Example 2: This example uses patterns for fill property."
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | fill property </title> <style> .opacity1 { fill: url(#pattern1); } .opacity2 { fill: url(#pattern2); } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | fill </b> <div class=\"container\"> <svg height=\"250px\" width=\"600px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <defs> <pattern id=\"pattern1\" viewBox=\"0, 0, 10, 10\" width=\"10%\" height=\"10%\"> <circle r=\"10\" /> </pattern> <pattern id=\"pattern2\" viewBox=\"0, 0, 10, 10\" width=\"10%\" height=\"10%\"> <rect height=\"5\" width=\"5\" fill=\"green\" /> </pattern> </defs> <circle class=\"opacity1\" cx=\"100\" cy=\"100\" r=\"50\" /> <circle class=\"opacity2\" cx=\"250\" cy=\"100\" r=\"50\" /> </svg> </div></body></html>",
"e": 4229,
"s": 3323,
"text": null
},
{
"code": null,
"e": 4237,
"s": 4229,
"text": "Output:"
},
{
"code": null,
"e": 4315,
"s": 4237,
"text": "Supported Browsers: The browsers supported by fill property are listed below:"
},
{
"code": null,
"e": 4322,
"s": 4315,
"text": "Chrome"
},
{
"code": null,
"e": 4330,
"s": 4322,
"text": "Firefox"
},
{
"code": null,
"e": 4337,
"s": 4330,
"text": "Safari"
},
{
"code": null,
"e": 4343,
"s": 4337,
"text": "Opera"
},
{
"code": null,
"e": 4363,
"s": 4343,
"text": "Internet Explorer 9"
},
{
"code": null,
"e": 4378,
"s": 4363,
"text": "CSS-Properties"
},
{
"code": null,
"e": 4382,
"s": 4378,
"text": "CSS"
},
{
"code": null,
"e": 4399,
"s": 4382,
"text": "Web Technologies"
},
{
"code": null,
"e": 4497,
"s": 4399,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4534,
"s": 4497,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 4573,
"s": 4534,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 4637,
"s": 4573,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 4698,
"s": 4637,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 4737,
"s": 4698,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 4770,
"s": 4737,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 4803,
"s": 4770,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 4863,
"s": 4803,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 4924,
"s": 4863,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Sort DataFrame by column name in R
|
26 Mar, 2021
Sorting is the process of ordering items. It can be ascending order, descending order, alphabetical order, numerical order. To sort a DataFrame by column name in R programming, we can use various methods as discussed below. To get a better understanding of how to sort DataFrame by column name, let’s take some examples.
Example:
Let’s suppose we have the following dataset with column names as English alphabets and tuples are integer values. Now we want to sort the column by column name in alphabetical order.
Column Names
R
o
w
s
After sorting DataFrame by column name it should look alike this:
R
o
w
s
dplyr is used to manipulate the DataFrame and names is used to set or get t the object name in R. To use dplyr, it needs to be installed explicitly.
Approach
Import library
Create data frame
Sort the DataFrame using sort function and pass the DataFrame name as an argument.
Syntax:
DataFrame %>% select(sort(names(DataFrame)))
Display sorted dataframe
Example:
R
#Sort DataFrame by column name in R # Creating a dataset.z <- c(1,6,5,5,6)x <- c(6,2,3,7,4)y <- c(2,4,4,0,3)a <- c(4,2,3,9,7) dataframe <- data.frame(Banana = z,Orange=x,Mango=y,Apple=a) # install dplyr packageinstall.packages("dplyr") # loading librarylibrary("dplyr") # sorting dataframe %>% select(sort(names(dataframe)))dataframe
Output:
Sorted DataFrame
We can use the order function to sort the columns by column name.
Syntax:
order(names(dataframe))
Approach
Create dataframe
Pass the names of columns in order function
Save the sorted data
Display result
Program:
R
#Sort DataFrame by column name in R # Creating a dataset.z <- c(1,6,5,5,6)x <- c(6,2,3,7,4)y <- c(2,4,4,0,3)a <- c(4,2,3,9,7) dataframe <- data.frame(Banana = z,Orange=x,Mango=y,Apple=a) # sorting dataframe[order(names(dataframe))]
Output:
Sorted dataframe
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to filter R DataFrame by values in a column?
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
Merge DataFrames by Column Names in R
How to Sort a DataFrame in R ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Mar, 2021"
},
{
"code": null,
"e": 349,
"s": 28,
"text": "Sorting is the process of ordering items. It can be ascending order, descending order, alphabetical order, numerical order. To sort a DataFrame by column name in R programming, we can use various methods as discussed below. To get a better understanding of how to sort DataFrame by column name, let’s take some examples."
},
{
"code": null,
"e": 358,
"s": 349,
"text": "Example:"
},
{
"code": null,
"e": 542,
"s": 358,
"text": "Let’s suppose we have the following dataset with column names as English alphabets and tuples are integer values. Now we want to sort the column by column name in alphabetical order. "
},
{
"code": null,
"e": 569,
"s": 544,
"text": " Column Names "
},
{
"code": null,
"e": 571,
"s": 569,
"text": "R"
},
{
"code": null,
"e": 573,
"s": 571,
"text": "o"
},
{
"code": null,
"e": 575,
"s": 573,
"text": "w"
},
{
"code": null,
"e": 577,
"s": 575,
"text": "s"
},
{
"code": null,
"e": 643,
"s": 577,
"text": "After sorting DataFrame by column name it should look alike this:"
},
{
"code": null,
"e": 645,
"s": 643,
"text": "R"
},
{
"code": null,
"e": 647,
"s": 645,
"text": "o"
},
{
"code": null,
"e": 649,
"s": 647,
"text": "w"
},
{
"code": null,
"e": 651,
"s": 649,
"text": "s"
},
{
"code": null,
"e": 800,
"s": 651,
"text": "dplyr is used to manipulate the DataFrame and names is used to set or get t the object name in R. To use dplyr, it needs to be installed explicitly."
},
{
"code": null,
"e": 809,
"s": 800,
"text": "Approach"
},
{
"code": null,
"e": 824,
"s": 809,
"text": "Import library"
},
{
"code": null,
"e": 842,
"s": 824,
"text": "Create data frame"
},
{
"code": null,
"e": 925,
"s": 842,
"text": "Sort the DataFrame using sort function and pass the DataFrame name as an argument."
},
{
"code": null,
"e": 933,
"s": 925,
"text": "Syntax:"
},
{
"code": null,
"e": 978,
"s": 933,
"text": "DataFrame %>% select(sort(names(DataFrame)))"
},
{
"code": null,
"e": 1003,
"s": 978,
"text": "Display sorted dataframe"
},
{
"code": null,
"e": 1012,
"s": 1003,
"text": "Example:"
},
{
"code": null,
"e": 1014,
"s": 1012,
"text": "R"
},
{
"code": "#Sort DataFrame by column name in R # Creating a dataset.z <- c(1,6,5,5,6)x <- c(6,2,3,7,4)y <- c(2,4,4,0,3)a <- c(4,2,3,9,7) dataframe <- data.frame(Banana = z,Orange=x,Mango=y,Apple=a) # install dplyr packageinstall.packages(\"dplyr\") # loading librarylibrary(\"dplyr\") # sorting dataframe %>% select(sort(names(dataframe)))dataframe",
"e": 1353,
"s": 1014,
"text": null
},
{
"code": null,
"e": 1361,
"s": 1353,
"text": "Output:"
},
{
"code": null,
"e": 1378,
"s": 1361,
"text": "Sorted DataFrame"
},
{
"code": null,
"e": 1444,
"s": 1378,
"text": "We can use the order function to sort the columns by column name."
},
{
"code": null,
"e": 1452,
"s": 1444,
"text": "Syntax:"
},
{
"code": null,
"e": 1476,
"s": 1452,
"text": "order(names(dataframe))"
},
{
"code": null,
"e": 1485,
"s": 1476,
"text": "Approach"
},
{
"code": null,
"e": 1502,
"s": 1485,
"text": "Create dataframe"
},
{
"code": null,
"e": 1546,
"s": 1502,
"text": "Pass the names of columns in order function"
},
{
"code": null,
"e": 1567,
"s": 1546,
"text": "Save the sorted data"
},
{
"code": null,
"e": 1582,
"s": 1567,
"text": "Display result"
},
{
"code": null,
"e": 1591,
"s": 1582,
"text": "Program:"
},
{
"code": null,
"e": 1593,
"s": 1591,
"text": "R"
},
{
"code": "#Sort DataFrame by column name in R # Creating a dataset.z <- c(1,6,5,5,6)x <- c(6,2,3,7,4)y <- c(2,4,4,0,3)a <- c(4,2,3,9,7) dataframe <- data.frame(Banana = z,Orange=x,Mango=y,Apple=a) # sorting dataframe[order(names(dataframe))]",
"e": 1828,
"s": 1593,
"text": null
},
{
"code": null,
"e": 1836,
"s": 1828,
"text": "Output:"
},
{
"code": null,
"e": 1853,
"s": 1836,
"text": "Sorted dataframe"
},
{
"code": null,
"e": 1860,
"s": 1853,
"text": "Picked"
},
{
"code": null,
"e": 1881,
"s": 1860,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 1893,
"s": 1881,
"text": "R-DataFrame"
},
{
"code": null,
"e": 1904,
"s": 1893,
"text": "R Language"
},
{
"code": null,
"e": 1915,
"s": 1904,
"text": "R Programs"
},
{
"code": null,
"e": 2013,
"s": 1915,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2065,
"s": 2013,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 2123,
"s": 2065,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2158,
"s": 2123,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 2196,
"s": 2158,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 2245,
"s": 2196,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2303,
"s": 2245,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 2352,
"s": 2303,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 2395,
"s": 2352,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 2433,
"s": 2395,
"text": "Merge DataFrames by Column Names in R"
}
] |
How to get all HTML content from DOMParser excluding the outer body tag ?
|
23 Feb, 2022
DOM (Document Object Model) allows us to dynamically access and manipulate the HTML data. All the text data from an HTML file can also be extracted using DOMParser. DOM parser returns an HTML/XML/SVG object. All the objects can be accessed using the [ ] operator in javascript. The HTML DOM Tree of objects:
Steps to get all the text from an HTML document using DOMParser:
Declare an instance of DOMParser. Syntax:
const parser = new DOMParser();
Parse the document using .parseFromString() function. It takes two arguments, the string to be parsed and the type of document. Syntax:
const parsedDocument = parser.parseFromString(
htmlInput, "text/html");
Use doc.all element to access the whole HTML page, now get its root element which is stored at 0th index. We can also use getElementByID() to get content of a specific element. Syntax:
var allText = parsedDocument.all[0].textContent;
Finally, we will use the textContent attribute of doc.all[0] to get the text from all HTML elements.Example:
html
<title>This is the title</title><div> <span>Geeks for geeks</span> <p>Content to be parsed </p></div>
Output:
This is the title
Geeks for geeks
Content to be parsed
Code:
html
<!DOCTYPE html><html lang="en" dir="ltr"> <head> <title> Dom Parser Inner Content </title></head> <body> <h2> DomParser to get all HTML content </h2> <p> Click on the button Below to parse the HTML document </p> <!-- Paragraph element to show the output --> <p id="output"> </p> <!-- Button to call the parsing function --> <button onclick="printOutput()"> Parse now </button> <script> // Input HTML string to be parsed var htmlInput = ` <title> This is the title </title> <div> <span>Geeks for geeks</span> <p> Content to be parsed </p> </div> `; // Created instance const parser = new DOMParser(); // Parsing const parsedDocument = parser.parseFromString( htmlInput, "text/html"); // Getting text function printOutput() { var allText = parsedDocument .all[0].textContent; // Printing on page and console document.getElementById("output") .innerHTML = allText; console.log(parsedDocument .all[0].textContent); } </script></body> </html>
Output: Before pressing the button:
After Pressing the button:
The text content from individual components can also be retrieved using getElementsByClassName(‘className’) and getElementById(‘IDName’).Javascript Function that takes the document to be parsed as a string and prints the result.
javascript
function parse(htmlInput) { // Creating Parser instance const parser = new DOMParser(); // Parsing the document using DOM Parser // and storing the returned HTML object in // a variable const parsedDocument = parser .parseFromString(htmlInput, "text/html"); // Retrieve all text content from DOM object var allText = parsedDocument.all[0].textContent; // Printing the output to webpage and console.log(parsedDocument.all[0].textContent);}
varshagumber28
CSS-Misc
HTML-Misc
JavaScript-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 338,
"s": 28,
"text": "DOM (Document Object Model) allows us to dynamically access and manipulate the HTML data. All the text data from an HTML file can also be extracted using DOMParser. DOM parser returns an HTML/XML/SVG object. All the objects can be accessed using the [ ] operator in javascript. The HTML DOM Tree of objects: "
},
{
"code": null,
"e": 404,
"s": 338,
"text": "Steps to get all the text from an HTML document using DOMParser: "
},
{
"code": null,
"e": 447,
"s": 404,
"text": "Declare an instance of DOMParser. Syntax: "
},
{
"code": null,
"e": 479,
"s": 447,
"text": "const parser = new DOMParser();"
},
{
"code": null,
"e": 616,
"s": 479,
"text": "Parse the document using .parseFromString() function. It takes two arguments, the string to be parsed and the type of document. Syntax: "
},
{
"code": null,
"e": 696,
"s": 616,
"text": "const parsedDocument = parser.parseFromString(\n htmlInput, \"text/html\");"
},
{
"code": null,
"e": 882,
"s": 696,
"text": "Use doc.all element to access the whole HTML page, now get its root element which is stored at 0th index. We can also use getElementByID() to get content of a specific element. Syntax: "
},
{
"code": null,
"e": 931,
"s": 882,
"text": "var allText = parsedDocument.all[0].textContent;"
},
{
"code": null,
"e": 1041,
"s": 931,
"text": "Finally, we will use the textContent attribute of doc.all[0] to get the text from all HTML elements.Example: "
},
{
"code": null,
"e": 1046,
"s": 1041,
"text": "html"
},
{
"code": "<title>This is the title</title><div> <span>Geeks for geeks</span> <p>Content to be parsed </p></div>",
"e": 1154,
"s": 1046,
"text": null
},
{
"code": null,
"e": 1164,
"s": 1154,
"text": "Output: "
},
{
"code": null,
"e": 1220,
"s": 1164,
"text": "This is the title \nGeeks for geeks\nContent to be parsed"
},
{
"code": null,
"e": 1227,
"s": 1220,
"text": "Code: "
},
{
"code": null,
"e": 1232,
"s": 1227,
"text": "html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\" dir=\"ltr\"> <head> <title> Dom Parser Inner Content </title></head> <body> <h2> DomParser to get all HTML content </h2> <p> Click on the button Below to parse the HTML document </p> <!-- Paragraph element to show the output --> <p id=\"output\"> </p> <!-- Button to call the parsing function --> <button onclick=\"printOutput()\"> Parse now </button> <script> // Input HTML string to be parsed var htmlInput = ` <title> This is the title </title> <div> <span>Geeks for geeks</span> <p> Content to be parsed </p> </div> `; // Created instance const parser = new DOMParser(); // Parsing const parsedDocument = parser.parseFromString( htmlInput, \"text/html\"); // Getting text function printOutput() { var allText = parsedDocument .all[0].textContent; // Printing on page and console document.getElementById(\"output\") .innerHTML = allText; console.log(parsedDocument .all[0].textContent); } </script></body> </html>",
"e": 2509,
"s": 1232,
"text": null
},
{
"code": null,
"e": 2547,
"s": 2509,
"text": "Output: Before pressing the button: "
},
{
"code": null,
"e": 2576,
"s": 2547,
"text": "After Pressing the button: "
},
{
"code": null,
"e": 2806,
"s": 2576,
"text": "The text content from individual components can also be retrieved using getElementsByClassName(‘className’) and getElementById(‘IDName’).Javascript Function that takes the document to be parsed as a string and prints the result. "
},
{
"code": null,
"e": 2817,
"s": 2806,
"text": "javascript"
},
{
"code": "function parse(htmlInput) { // Creating Parser instance const parser = new DOMParser(); // Parsing the document using DOM Parser // and storing the returned HTML object in // a variable const parsedDocument = parser .parseFromString(htmlInput, \"text/html\"); // Retrieve all text content from DOM object var allText = parsedDocument.all[0].textContent; // Printing the output to webpage and console.log(parsedDocument.all[0].textContent);}",
"e": 3297,
"s": 2817,
"text": null
},
{
"code": null,
"e": 3312,
"s": 3297,
"text": "varshagumber28"
},
{
"code": null,
"e": 3321,
"s": 3312,
"text": "CSS-Misc"
},
{
"code": null,
"e": 3331,
"s": 3321,
"text": "HTML-Misc"
},
{
"code": null,
"e": 3347,
"s": 3331,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 3354,
"s": 3347,
"text": "Picked"
},
{
"code": null,
"e": 3358,
"s": 3354,
"text": "CSS"
},
{
"code": null,
"e": 3363,
"s": 3358,
"text": "HTML"
},
{
"code": null,
"e": 3374,
"s": 3363,
"text": "JavaScript"
},
{
"code": null,
"e": 3391,
"s": 3374,
"text": "Web Technologies"
},
{
"code": null,
"e": 3418,
"s": 3391,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 3423,
"s": 3418,
"text": "HTML"
}
] |
Two-Proportions Z-Test in R Programming
|
16 Jul, 2020
The two-proportions z-test is used to compare two observed proportions. For example, let there are two groups of individuals:
Group A with lung cancer: n = 500
Group B, healthy individuals: n = 500
The number of smokers in each group is as follow:
Group A with lung cancer: n = 500, 490 smokers, pA = 490/500 = 98
Group B, healthy individuals: n = 500, 400 smokers, pB = 400/500 = 80
In this setting:
The overall proportion of smokers is p = frac(490+400) 500 + 500 = 89
The overall proportion of non-smokers is q = 1 – p = 11
So we want to know, whether the proportions of smokers are the same in the two groups of individuals?
The test statistic (also known as z-test) can be calculated as follow:
where,
pA: the proportion observed in group A with size nApB: the proportion observed in group B with size nBp and q: the overall proportions
In R Language, the function used for performing a z-test is prop.test().
Syntax:prop.test(x, n, p = NULL, alternative = “two.sided”, correct = TRUE)
Parameters:x = number of successes and failures in data set.n = size of data set.p = probabilities of success. It must be in the range of 0 to 1.alternative = a character string specifying the alternative hypothesis.correct = a logical indicating whether Yates’ continuity correction should be applied where possible.
Example 1:Let’s say we have two groups of student A and B. Group A with an early morning class of 400 students with 342 female students. Group B with a late class of 400 students with 290 female students. Use a 5% alpha level. We want to know, whether the proportions of females are the same in the two groups of the student? Here let’s use prop.test().
# prop Test in R prop.test(x = c(342, 290), n = c(400, 400))
Output:
2-sample test for equality of proportions with continuity correction
data: c(342, 290) out of c(400, 400)
X-squared = 19.598, df = 1, p-value = 9.559e-06
alternative hypothesis: two.sided
95 percent confidence interval:
0.07177443 0.18822557
sample estimates:
prop 1 prop 2
0.855 0.725
It returns a p-value
alternative hypothesis
a 95% confidence intervals
a probability of success
Thus as the result The p value of the test is 9.558674e-06 is greater than significance level of alpha. which is 0.05. That means there is no difference between Two Proportions. Now if you want to test whether the observed proportion of Females in group A(pA) is less than the observed proportion of Females in group B(pB), then the command is:
# prop Test in R prop.test(x = c(342, 290), n = c(400, 400), alternative = "less")
Output:
2-sample test for equality of proportions with continuity correction
data: c(342, 290) out of c(400, 400)
X-squared = 19.598, df = 1, p-value = 1
alternative hypothesis: less
95 percent confidence interval:
-1.0000000 0.1792664
sample estimates:
prop 1 prop 2
0.855 0.725
If you want to test whether the observed proportion of Females in group A(pA) is greater than the observed proportion of Females in group(pB), then the command is:
# prop Test in R prop.test(x = c(342, 290), n = c(400, 400), alternative = "greater")
Output:
2-sample test for equality of proportions with continuity correction
data: c(342, 290) out of c(400, 400)
X-squared = 19.598, df = 1, p-value = 4.779e-06
alternative hypothesis: greater
95 percent confidence interval:
0.08073363 1.00000000
sample estimates:
prop 1 prop 2
0.855 0.725
Example 2:ABC company manufactures tablets. For quality control, two sets of tablets were tested. In the first group, 32 out of 700 were found to contain some sort of defect. In the second group, 30 out of 400 were found to contain some sort of defect. Is the difference between the two groups significant? Use a 5% alpha level. Here let’s use prop.test().
# prop Test in R prop.test(x = c(32, 30), n = c(700, 400))
Output:
2-sample test for equality of proportions with continuity correction
data: c(32, 30) out of c(700, 400)
X-squared =3.5725, df = 1, p-value = 0.05874
alternative hypothesis: two.sided
95 percent confidence interval:
-0.061344109 0.002772681
sample estimates:
prop 1 prop 2
0.04571429 0.07500000
It returns a p-value
alternative hypothesis
a 95% confidence intervals
a probability of success
Thus as the result The p value of the test is 0.0587449 is greater than significance level of alpha, which is 0.05. That means there is not significance difference between Two Proportions. Now if you want to test whether the observed proportion of defect in group one is less than the observed proportion of defect in group two, then the command is:
# prop Test in R prop.test(x = c(32, 30), n = c(700, 400), alternative = "less")
Output:
2-sample test for equality of proportions with continuity correction
data: c(32, 30) out of c(700, 400)
X-squared = 3.5725, df = 1, p-value = 0.02937
alternative hypothesis: less
95 percent confidence interval:
-1.000000000 -0.002065656
sample estimates:
prop 1 prop 2
0.04571429 0.07500000
If you want to test whether the observed proportion of defects in group one is greater than the observed proportion of defects in group two, then the command is:
# prop.test() in Rprop.test(x = c(32, 30), n = c(700, 400), alternative = "greater")
Output:
2-sample test for equality of proportions with continuity correction
data: c(32, 30) out of c(700, 400)
X-squared = 3.5725, df = 1, p-value = 0.9706
alternative hypothesis: greater
95 percent confidence interval:
-0.05650577 1.00000000
sample estimates:
prop 1 prop 2
0.04571429 0.07500000
data-science
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Filter data by multiple conditions in R using Dplyr
How to Replace specific values in column in R DataFrame ?
Change Color of Bars in Barchart using ggplot2 in R
How to Split Column Into Multiple Columns in R DataFrame?
Loops in R (for, while, repeat)
Group by function in R using Dplyr
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
R Programming Language - Introduction
How to Change Axis Scales in R Plots?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jul, 2020"
},
{
"code": null,
"e": 154,
"s": 28,
"text": "The two-proportions z-test is used to compare two observed proportions. For example, let there are two groups of individuals:"
},
{
"code": null,
"e": 188,
"s": 154,
"text": "Group A with lung cancer: n = 500"
},
{
"code": null,
"e": 226,
"s": 188,
"text": "Group B, healthy individuals: n = 500"
},
{
"code": null,
"e": 276,
"s": 226,
"text": "The number of smokers in each group is as follow:"
},
{
"code": null,
"e": 342,
"s": 276,
"text": "Group A with lung cancer: n = 500, 490 smokers, pA = 490/500 = 98"
},
{
"code": null,
"e": 412,
"s": 342,
"text": "Group B, healthy individuals: n = 500, 400 smokers, pB = 400/500 = 80"
},
{
"code": null,
"e": 429,
"s": 412,
"text": "In this setting:"
},
{
"code": null,
"e": 499,
"s": 429,
"text": "The overall proportion of smokers is p = frac(490+400) 500 + 500 = 89"
},
{
"code": null,
"e": 555,
"s": 499,
"text": "The overall proportion of non-smokers is q = 1 – p = 11"
},
{
"code": null,
"e": 657,
"s": 555,
"text": "So we want to know, whether the proportions of smokers are the same in the two groups of individuals?"
},
{
"code": null,
"e": 728,
"s": 657,
"text": "The test statistic (also known as z-test) can be calculated as follow:"
},
{
"code": null,
"e": 735,
"s": 728,
"text": "where,"
},
{
"code": null,
"e": 870,
"s": 735,
"text": "pA: the proportion observed in group A with size nApB: the proportion observed in group B with size nBp and q: the overall proportions"
},
{
"code": null,
"e": 943,
"s": 870,
"text": "In R Language, the function used for performing a z-test is prop.test()."
},
{
"code": null,
"e": 1019,
"s": 943,
"text": "Syntax:prop.test(x, n, p = NULL, alternative = “two.sided”, correct = TRUE)"
},
{
"code": null,
"e": 1337,
"s": 1019,
"text": "Parameters:x = number of successes and failures in data set.n = size of data set.p = probabilities of success. It must be in the range of 0 to 1.alternative = a character string specifying the alternative hypothesis.correct = a logical indicating whether Yates’ continuity correction should be applied where possible."
},
{
"code": null,
"e": 1691,
"s": 1337,
"text": "Example 1:Let’s say we have two groups of student A and B. Group A with an early morning class of 400 students with 342 female students. Group B with a late class of 400 students with 290 female students. Use a 5% alpha level. We want to know, whether the proportions of females are the same in the two groups of the student? Here let’s use prop.test()."
},
{
"code": "# prop Test in R prop.test(x = c(342, 290), n = c(400, 400))",
"e": 1761,
"s": 1691,
"text": null
},
{
"code": null,
"e": 1769,
"s": 1761,
"text": "Output:"
},
{
"code": null,
"e": 2068,
"s": 1769,
"text": " 2-sample test for equality of proportions with continuity correction\ndata: c(342, 290) out of c(400, 400)\nX-squared = 19.598, df = 1, p-value = 9.559e-06\nalternative hypothesis: two.sided\n95 percent confidence interval:\n0.07177443 0.18822557\nsample estimates:\nprop 1 prop 2 \n0.855 0.725\n"
},
{
"code": null,
"e": 2089,
"s": 2068,
"text": "It returns a p-value"
},
{
"code": null,
"e": 2112,
"s": 2089,
"text": "alternative hypothesis"
},
{
"code": null,
"e": 2139,
"s": 2112,
"text": "a 95% confidence intervals"
},
{
"code": null,
"e": 2164,
"s": 2139,
"text": "a probability of success"
},
{
"code": null,
"e": 2509,
"s": 2164,
"text": "Thus as the result The p value of the test is 9.558674e-06 is greater than significance level of alpha. which is 0.05. That means there is no difference between Two Proportions. Now if you want to test whether the observed proportion of Females in group A(pA) is less than the observed proportion of Females in group B(pB), then the command is:"
},
{
"code": "# prop Test in R prop.test(x = c(342, 290), n = c(400, 400), alternative = \"less\")",
"e": 2612,
"s": 2509,
"text": null
},
{
"code": null,
"e": 2620,
"s": 2612,
"text": "Output:"
},
{
"code": null,
"e": 2901,
"s": 2620,
"text": "2-sample test for equality of proportions with continuity correction\n\ndata: c(342, 290) out of c(400, 400)\nX-squared = 19.598, df = 1, p-value = 1\nalternative hypothesis: less\n95 percent confidence interval:\n -1.0000000 0.1792664\nsample estimates:\nprop 1 prop 2 \n 0.855 0.725 \n"
},
{
"code": null,
"e": 3065,
"s": 2901,
"text": "If you want to test whether the observed proportion of Females in group A(pA) is greater than the observed proportion of Females in group(pB), then the command is:"
},
{
"code": "# prop Test in R prop.test(x = c(342, 290), n = c(400, 400), alternative = \"greater\")",
"e": 3171,
"s": 3065,
"text": null
},
{
"code": null,
"e": 3179,
"s": 3171,
"text": "Output:"
},
{
"code": null,
"e": 3471,
"s": 3179,
"text": "2-sample test for equality of proportions with continuity correction\n\ndata: c(342, 290) out of c(400, 400)\nX-squared = 19.598, df = 1, p-value = 4.779e-06\nalternative hypothesis: greater\n95 percent confidence interval:\n 0.08073363 1.00000000\nsample estimates:\nprop 1 prop 2 \n 0.855 0.725 \n"
},
{
"code": null,
"e": 3828,
"s": 3471,
"text": "Example 2:ABC company manufactures tablets. For quality control, two sets of tablets were tested. In the first group, 32 out of 700 were found to contain some sort of defect. In the second group, 30 out of 400 were found to contain some sort of defect. Is the difference between the two groups significant? Use a 5% alpha level. Here let’s use prop.test()."
},
{
"code": "# prop Test in R prop.test(x = c(32, 30), n = c(700, 400))",
"e": 3897,
"s": 3828,
"text": null
},
{
"code": null,
"e": 3905,
"s": 3897,
"text": "Output:"
},
{
"code": null,
"e": 4217,
"s": 3905,
"text": " 2-sample test for equality of proportions with continuity correction\ndata: c(32, 30) out of c(700, 400)\nX-squared =3.5725, df = 1, p-value = 0.05874\nalternative hypothesis: two.sided\n95 percent confidence interval:\n-0.061344109 0.002772681\nsample estimates:\n prop 1 prop 2 \n0.04571429 0.07500000\n"
},
{
"code": null,
"e": 4238,
"s": 4217,
"text": "It returns a p-value"
},
{
"code": null,
"e": 4261,
"s": 4238,
"text": "alternative hypothesis"
},
{
"code": null,
"e": 4288,
"s": 4261,
"text": "a 95% confidence intervals"
},
{
"code": null,
"e": 4313,
"s": 4288,
"text": "a probability of success"
},
{
"code": null,
"e": 4663,
"s": 4313,
"text": "Thus as the result The p value of the test is 0.0587449 is greater than significance level of alpha, which is 0.05. That means there is not significance difference between Two Proportions. Now if you want to test whether the observed proportion of defect in group one is less than the observed proportion of defect in group two, then the command is:"
},
{
"code": "# prop Test in R prop.test(x = c(32, 30), n = c(700, 400), alternative = \"less\")",
"e": 4764,
"s": 4663,
"text": null
},
{
"code": null,
"e": 4772,
"s": 4764,
"text": "Output:"
},
{
"code": null,
"e": 5077,
"s": 4772,
"text": "2-sample test for equality of proportions with continuity correction\n\ndata: c(32, 30) out of c(700, 400)\nX-squared = 3.5725, df = 1, p-value = 0.02937\nalternative hypothesis: less\n95 percent confidence interval:\n -1.000000000 -0.002065656\nsample estimates:\n prop 1 prop 2 \n0.04571429 0.07500000 \n"
},
{
"code": null,
"e": 5239,
"s": 5077,
"text": "If you want to test whether the observed proportion of defects in group one is greater than the observed proportion of defects in group two, then the command is:"
},
{
"code": "# prop.test() in Rprop.test(x = c(32, 30), n = c(700, 400), alternative = \"greater\")",
"e": 5344,
"s": 5239,
"text": null
},
{
"code": null,
"e": 5352,
"s": 5344,
"text": "Output:"
},
{
"code": null,
"e": 5657,
"s": 5352,
"text": "2-sample test for equality of proportions with continuity correction\n\ndata: c(32, 30) out of c(700, 400)\nX-squared = 3.5725, df = 1, p-value = 0.9706\nalternative hypothesis: greater\n95 percent confidence interval:\n -0.05650577 1.00000000\nsample estimates:\n prop 1 prop 2 \n0.04571429 0.07500000 \n"
},
{
"code": null,
"e": 5670,
"s": 5657,
"text": "data-science"
},
{
"code": null,
"e": 5681,
"s": 5670,
"text": "R Language"
},
{
"code": null,
"e": 5779,
"s": 5681,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5831,
"s": 5779,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 5889,
"s": 5831,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 5941,
"s": 5889,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 5999,
"s": 5941,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 6031,
"s": 5999,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 6066,
"s": 6031,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 6110,
"s": 6066,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 6142,
"s": 6110,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 6180,
"s": 6142,
"text": "R Programming Language - Introduction"
}
] |
Building an Ensemble Learning Model Using Scikit-learn | by Eijaz Allibhai | Towards Data Science
|
Ensemble learning uses multiple machine learning models to try to make better predictions on a dataset. An ensemble model works by training different models on a dataset and having each model make predictions individually. The predictions of these models are then combined in the ensemble model to make a final prediction.
Every model has its strengths and weaknesses. Ensemble models can be beneficial by combining individual models to help hide the weaknesses of an individual model.
In this tutorial, we will be using a Voting Classifier in which the ensemble model makes the prediction by majority vote. For example, if we use three models and they predict [1, 0, 1] for the target variable, the final prediction that the ensemble model would make would be 1, since two out of the three models predicted 1.
We will use three different models to put into our Voting Classifier: k-Nearest Neighbors, Random Forest, and Logistic Regression. We will use the Scikit-learn library in Python to implement these methods and use the diabetes dataset in our example.
Note: Ensemble models can also be used for regression problems, where the ensemble model will use either the mean output of the different models or weighted averages for its final prediction.
The first step is to read in the data we will use as input. For this example, we are using the diabetes dataset. To start, we will use the Pandas library to read in the data.
import pandas as pd#read in the datasetdf = pd.read_csv(‘data/diabetes_data.csv’)#take a look at the datadf.head()
Next, let’s see how much data we have. We will call the ‘shape’ function on our dataframe to see how many rows and columns there are in our data. The rows indicate the number of patients and the columns indicate the number of features (age, weight, etc.) in the dataset for each patient.
#check dataset sizedf.shape
Now let’s split up our dataset into inputs (X) and our target (y). Our input will be every column except ‘diabetes’ because ‘diabetes’ is what we will be attempting to predict. Therefore, ‘diabetes’ will be our target.
We will use the pandas ‘drop’ function to drop the column ‘diabetes’ from our dataframe and store it in the variable ‘X’.
#split data into inputs and targetsX = df.drop(columns = [‘diabetes’])y = df[‘diabetes’]
Now we will split the dataset into into training data and testing data. The training data is the data that the model will learn from. The testing data is the data we will use to see how well the model performs on unseen data.
Scikit-learn has a function we can use called ‘train_test_split’ that makes it easy for us to split our dataset into training and testing data.
from sklearn.model_selection import train_test_split#split data into train and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y)
‘train_test_split’ takes in 5 parameters. The first two parameters are the input and target data we split up earlier. Next, we will set ‘test_size’ to 0.3. This means that 30% of all the data will be used for testing, which leaves 70% of the data as training data for the model to learn from.
Setting ‘stratify’ to y makes our training split represent the proportion of each value in the y variable. For example, in our dataset, if 25% of patients have diabetes and 75% don’t have diabetes, setting ‘stratify’ to y will ensure that the random split has 25% of patients with diabetes and 75% of patients without diabetes.
Next, we have to build our models. Each model we build has a set of hyper parameters that we can tune. Tuning parameters is when you go through a process to find the optimal parameters for your model to improve accuracy. We will use grid search to find the optimal hyperparamters for each model.
Grid search works by training our model multiple times on a range of parameters that we specify. That way, we can test our model with each hyperparameter value and figure out the optimal values to get the best accuracy results.
The first model we will build is k-Nearest Neighbors (k-NN). k-NN models work by taking a data point and looking at the ‘k’ closest labeled data points. The data point is then assigned the label of the majority of the ‘k’ closest points.
For example, if k = 5, and 3 of points are ‘green’ and 2 are ‘red’, then the data point in question would be labeled ‘green’, since ‘green’ is the majority (as shown in the above graph).
Here is the code:
import numpy as npfrom sklearn.model_selection import GridSearchCVfrom sklearn.neighbors import KNeighborsClassifier#create new a knn modelknn = KNeighborsClassifier()#create a dictionary of all values we want to test for n_neighborsparams_knn = {‘n_neighbors’: np.arange(1, 25)}#use gridsearch to test all values for n_neighborsknn_gs = GridSearchCV(knn, params_knn, cv=5)#fit model to training dataknn_gs.fit(X_train, y_train)
First, we will create a new k-NN classifier. Next, we need to create a dictionary to store all the values we will test for ‘n_neighbors’, which is the hyperparameter we need to tune. We will test 24 different values for ‘n_neighbors’. Then we will create our grid search, inputing our k-NN classifier, our set of hyperparamters and our cross validation value.
Cross-validation is when the dataset is randomly split up into ‘k’ groups. One of the groups is used as the test set and the rest are used as the training set. The model is trained on the training set and scored on the test set. Then the process is repeated until each unique group as been used as the test set.
In our case, we are using 5-fold cross validation. The dataset is split into 5 groups, and the model is trained and tested 5 separate times so each group would get a chance to be the test set. This is how we will score our model running with each hyperparamter value to see which value for ‘n_neighbors’ gives us the best score.
Then we will use the ‘fit’ function to run our grid search.
Now we will save our best k-NN model to ‘knn_best’ using the ‘best_estimator_’ function and check what the best value was for ‘n_neighbors’.
#save best modelknn_best = knn_gs.best_estimator_#check best n_neigbors valueprint(knn_gs.best_params_)
For the next two models, I will not go into as much detail since some parts are repeated from building the k-NN model.
The next model we will build is a random forest. A random forest is considered an ensemble model in itself, since it is a collection of decision trees combined to make a more accurate model.
Here is the code:
from sklearn.ensemble import RandomForestClassifier#create a new random forest classifierrf = RandomForestClassifier()#create a dictionary of all values we want to test for n_estimatorsparams_rf = {‘n_estimators’: [50, 100, 200]}#use gridsearch to test all values for n_estimatorsrf_gs = GridSearchCV(rf, params_rf, cv=5)#fit model to training datarf_gs.fit(X_train, y_train)
We will create a new random forest classifier and set the hyperparameters we want to tune. ‘n_estimators’ is the number of trees in our random forest. Then we can run our grid search to find the optimal number of trees.
Just like before, we will save our best model and print the best ‘n_estimators’ value.
#save best modelrf_best = rf_gs.best_estimator_#check best n_estimators valueprint(rf_gs.best_params_)
Our last model is logistic regression. Even though it has ‘regression’ in its name, logistic regression is a classification method. This one is more simple since we won’t tune any hyperparameters. We just need to create and train the model.
from sklearn.linear_model import LogisticRegression#create a new logistic regression modellog_reg = LogisticRegression()#fit the model to the training datalog_reg.fit(X_train, y_train)
Now let’s check the accuracy scores of all three of our models on our test data.
#test the three models with the test data and print their accuracy scoresprint(‘knn: {}’.format(knn_best.score(X_test, y_test)))print(‘rf: {}’.format(rf_best.score(X_test, y_test)))print(‘log_reg: {}’.format(log_reg.score(X_test, y_test)))
As you can see from the output, logistic regression is the most accurate out of the three.
Now that we’ve built our three individual models, it’s time we built our voting classifier.
Here is the code:
from sklearn.ensemble import VotingClassifier#create a dictionary of our modelsestimators=[(‘knn’, knn_best), (‘rf’, rf_best), (‘log_reg’, log_reg)]#create our voting classifier, inputting our modelsensemble = VotingClassifier(estimators, voting=’hard’)
First, let’s place our three models in an array called ‘estimators’. Next, we will create our voting classifier. It takes two inputs. The first is our estimator array of our three models. We will set the voting parameter to hard, which tells our classifier to make predicitons by majority vote.
Now we can fit our ensemble model to our training data and score it on our testing data.
#fit model to training dataensemble.fit(X_train, y_train)#test our model on the test dataensemble.score(X_test, y_test)
Awesome! Our ensemble model performed better than our individual k-NN, random forest and logistic regression models!
That’s it! You’ve now built an ensemble model to combine individual models!
Thanks for reading! The GitHub repository for this tutorial (jupyter notebook and dataset) can be found here.
If you would like to keep updated on my machine learning content, please follow me :)
|
[
{
"code": null,
"e": 495,
"s": 172,
"text": "Ensemble learning uses multiple machine learning models to try to make better predictions on a dataset. An ensemble model works by training different models on a dataset and having each model make predictions individually. The predictions of these models are then combined in the ensemble model to make a final prediction."
},
{
"code": null,
"e": 658,
"s": 495,
"text": "Every model has its strengths and weaknesses. Ensemble models can be beneficial by combining individual models to help hide the weaknesses of an individual model."
},
{
"code": null,
"e": 983,
"s": 658,
"text": "In this tutorial, we will be using a Voting Classifier in which the ensemble model makes the prediction by majority vote. For example, if we use three models and they predict [1, 0, 1] for the target variable, the final prediction that the ensemble model would make would be 1, since two out of the three models predicted 1."
},
{
"code": null,
"e": 1233,
"s": 983,
"text": "We will use three different models to put into our Voting Classifier: k-Nearest Neighbors, Random Forest, and Logistic Regression. We will use the Scikit-learn library in Python to implement these methods and use the diabetes dataset in our example."
},
{
"code": null,
"e": 1425,
"s": 1233,
"text": "Note: Ensemble models can also be used for regression problems, where the ensemble model will use either the mean output of the different models or weighted averages for its final prediction."
},
{
"code": null,
"e": 1600,
"s": 1425,
"text": "The first step is to read in the data we will use as input. For this example, we are using the diabetes dataset. To start, we will use the Pandas library to read in the data."
},
{
"code": null,
"e": 1715,
"s": 1600,
"text": "import pandas as pd#read in the datasetdf = pd.read_csv(‘data/diabetes_data.csv’)#take a look at the datadf.head()"
},
{
"code": null,
"e": 2003,
"s": 1715,
"text": "Next, let’s see how much data we have. We will call the ‘shape’ function on our dataframe to see how many rows and columns there are in our data. The rows indicate the number of patients and the columns indicate the number of features (age, weight, etc.) in the dataset for each patient."
},
{
"code": null,
"e": 2031,
"s": 2003,
"text": "#check dataset sizedf.shape"
},
{
"code": null,
"e": 2250,
"s": 2031,
"text": "Now let’s split up our dataset into inputs (X) and our target (y). Our input will be every column except ‘diabetes’ because ‘diabetes’ is what we will be attempting to predict. Therefore, ‘diabetes’ will be our target."
},
{
"code": null,
"e": 2372,
"s": 2250,
"text": "We will use the pandas ‘drop’ function to drop the column ‘diabetes’ from our dataframe and store it in the variable ‘X’."
},
{
"code": null,
"e": 2461,
"s": 2372,
"text": "#split data into inputs and targetsX = df.drop(columns = [‘diabetes’])y = df[‘diabetes’]"
},
{
"code": null,
"e": 2687,
"s": 2461,
"text": "Now we will split the dataset into into training data and testing data. The training data is the data that the model will learn from. The testing data is the data we will use to see how well the model performs on unseen data."
},
{
"code": null,
"e": 2831,
"s": 2687,
"text": "Scikit-learn has a function we can use called ‘train_test_split’ that makes it easy for us to split our dataset into training and testing data."
},
{
"code": null,
"e": 3004,
"s": 2831,
"text": "from sklearn.model_selection import train_test_split#split data into train and test setsX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y)"
},
{
"code": null,
"e": 3297,
"s": 3004,
"text": "‘train_test_split’ takes in 5 parameters. The first two parameters are the input and target data we split up earlier. Next, we will set ‘test_size’ to 0.3. This means that 30% of all the data will be used for testing, which leaves 70% of the data as training data for the model to learn from."
},
{
"code": null,
"e": 3625,
"s": 3297,
"text": "Setting ‘stratify’ to y makes our training split represent the proportion of each value in the y variable. For example, in our dataset, if 25% of patients have diabetes and 75% don’t have diabetes, setting ‘stratify’ to y will ensure that the random split has 25% of patients with diabetes and 75% of patients without diabetes."
},
{
"code": null,
"e": 3921,
"s": 3625,
"text": "Next, we have to build our models. Each model we build has a set of hyper parameters that we can tune. Tuning parameters is when you go through a process to find the optimal parameters for your model to improve accuracy. We will use grid search to find the optimal hyperparamters for each model."
},
{
"code": null,
"e": 4149,
"s": 3921,
"text": "Grid search works by training our model multiple times on a range of parameters that we specify. That way, we can test our model with each hyperparameter value and figure out the optimal values to get the best accuracy results."
},
{
"code": null,
"e": 4387,
"s": 4149,
"text": "The first model we will build is k-Nearest Neighbors (k-NN). k-NN models work by taking a data point and looking at the ‘k’ closest labeled data points. The data point is then assigned the label of the majority of the ‘k’ closest points."
},
{
"code": null,
"e": 4574,
"s": 4387,
"text": "For example, if k = 5, and 3 of points are ‘green’ and 2 are ‘red’, then the data point in question would be labeled ‘green’, since ‘green’ is the majority (as shown in the above graph)."
},
{
"code": null,
"e": 4592,
"s": 4574,
"text": "Here is the code:"
},
{
"code": null,
"e": 5021,
"s": 4592,
"text": "import numpy as npfrom sklearn.model_selection import GridSearchCVfrom sklearn.neighbors import KNeighborsClassifier#create new a knn modelknn = KNeighborsClassifier()#create a dictionary of all values we want to test for n_neighborsparams_knn = {‘n_neighbors’: np.arange(1, 25)}#use gridsearch to test all values for n_neighborsknn_gs = GridSearchCV(knn, params_knn, cv=5)#fit model to training dataknn_gs.fit(X_train, y_train)"
},
{
"code": null,
"e": 5381,
"s": 5021,
"text": "First, we will create a new k-NN classifier. Next, we need to create a dictionary to store all the values we will test for ‘n_neighbors’, which is the hyperparameter we need to tune. We will test 24 different values for ‘n_neighbors’. Then we will create our grid search, inputing our k-NN classifier, our set of hyperparamters and our cross validation value."
},
{
"code": null,
"e": 5693,
"s": 5381,
"text": "Cross-validation is when the dataset is randomly split up into ‘k’ groups. One of the groups is used as the test set and the rest are used as the training set. The model is trained on the training set and scored on the test set. Then the process is repeated until each unique group as been used as the test set."
},
{
"code": null,
"e": 6022,
"s": 5693,
"text": "In our case, we are using 5-fold cross validation. The dataset is split into 5 groups, and the model is trained and tested 5 separate times so each group would get a chance to be the test set. This is how we will score our model running with each hyperparamter value to see which value for ‘n_neighbors’ gives us the best score."
},
{
"code": null,
"e": 6082,
"s": 6022,
"text": "Then we will use the ‘fit’ function to run our grid search."
},
{
"code": null,
"e": 6223,
"s": 6082,
"text": "Now we will save our best k-NN model to ‘knn_best’ using the ‘best_estimator_’ function and check what the best value was for ‘n_neighbors’."
},
{
"code": null,
"e": 6327,
"s": 6223,
"text": "#save best modelknn_best = knn_gs.best_estimator_#check best n_neigbors valueprint(knn_gs.best_params_)"
},
{
"code": null,
"e": 6446,
"s": 6327,
"text": "For the next two models, I will not go into as much detail since some parts are repeated from building the k-NN model."
},
{
"code": null,
"e": 6637,
"s": 6446,
"text": "The next model we will build is a random forest. A random forest is considered an ensemble model in itself, since it is a collection of decision trees combined to make a more accurate model."
},
{
"code": null,
"e": 6655,
"s": 6637,
"text": "Here is the code:"
},
{
"code": null,
"e": 7031,
"s": 6655,
"text": "from sklearn.ensemble import RandomForestClassifier#create a new random forest classifierrf = RandomForestClassifier()#create a dictionary of all values we want to test for n_estimatorsparams_rf = {‘n_estimators’: [50, 100, 200]}#use gridsearch to test all values for n_estimatorsrf_gs = GridSearchCV(rf, params_rf, cv=5)#fit model to training datarf_gs.fit(X_train, y_train)"
},
{
"code": null,
"e": 7251,
"s": 7031,
"text": "We will create a new random forest classifier and set the hyperparameters we want to tune. ‘n_estimators’ is the number of trees in our random forest. Then we can run our grid search to find the optimal number of trees."
},
{
"code": null,
"e": 7338,
"s": 7251,
"text": "Just like before, we will save our best model and print the best ‘n_estimators’ value."
},
{
"code": null,
"e": 7441,
"s": 7338,
"text": "#save best modelrf_best = rf_gs.best_estimator_#check best n_estimators valueprint(rf_gs.best_params_)"
},
{
"code": null,
"e": 7682,
"s": 7441,
"text": "Our last model is logistic regression. Even though it has ‘regression’ in its name, logistic regression is a classification method. This one is more simple since we won’t tune any hyperparameters. We just need to create and train the model."
},
{
"code": null,
"e": 7867,
"s": 7682,
"text": "from sklearn.linear_model import LogisticRegression#create a new logistic regression modellog_reg = LogisticRegression()#fit the model to the training datalog_reg.fit(X_train, y_train)"
},
{
"code": null,
"e": 7948,
"s": 7867,
"text": "Now let’s check the accuracy scores of all three of our models on our test data."
},
{
"code": null,
"e": 8188,
"s": 7948,
"text": "#test the three models with the test data and print their accuracy scoresprint(‘knn: {}’.format(knn_best.score(X_test, y_test)))print(‘rf: {}’.format(rf_best.score(X_test, y_test)))print(‘log_reg: {}’.format(log_reg.score(X_test, y_test)))"
},
{
"code": null,
"e": 8279,
"s": 8188,
"text": "As you can see from the output, logistic regression is the most accurate out of the three."
},
{
"code": null,
"e": 8371,
"s": 8279,
"text": "Now that we’ve built our three individual models, it’s time we built our voting classifier."
},
{
"code": null,
"e": 8389,
"s": 8371,
"text": "Here is the code:"
},
{
"code": null,
"e": 8643,
"s": 8389,
"text": "from sklearn.ensemble import VotingClassifier#create a dictionary of our modelsestimators=[(‘knn’, knn_best), (‘rf’, rf_best), (‘log_reg’, log_reg)]#create our voting classifier, inputting our modelsensemble = VotingClassifier(estimators, voting=’hard’)"
},
{
"code": null,
"e": 8938,
"s": 8643,
"text": "First, let’s place our three models in an array called ‘estimators’. Next, we will create our voting classifier. It takes two inputs. The first is our estimator array of our three models. We will set the voting parameter to hard, which tells our classifier to make predicitons by majority vote."
},
{
"code": null,
"e": 9027,
"s": 8938,
"text": "Now we can fit our ensemble model to our training data and score it on our testing data."
},
{
"code": null,
"e": 9147,
"s": 9027,
"text": "#fit model to training dataensemble.fit(X_train, y_train)#test our model on the test dataensemble.score(X_test, y_test)"
},
{
"code": null,
"e": 9264,
"s": 9147,
"text": "Awesome! Our ensemble model performed better than our individual k-NN, random forest and logistic regression models!"
},
{
"code": null,
"e": 9340,
"s": 9264,
"text": "That’s it! You’ve now built an ensemble model to combine individual models!"
},
{
"code": null,
"e": 9450,
"s": 9340,
"text": "Thanks for reading! The GitHub repository for this tutorial (jupyter notebook and dataset) can be found here."
}
] |
Automating Real Estate Investment Analysis: Python Web Scraping Bot | by Josh Rab | Towards Data Science
|
The goal is to build a python web tool that is capable of analyzing investment properties. The tool will use data mining to find prices for properties, and then analyze the return rate.
Summary
Index
Motivations
The App
The Functions
Summary and Going Forward
The applications of bots or automation to trading and investments is not new. Multiple examples include stock trading bots tasked with buying or selling assets based on different models or indicators. Renaissance technology received the worlds attention due to their return rates through algorithmic investing that averaged 60%+ annualized returns over a 30-year time span.
The benefits of automation have the potential to transform businesses of varying size. Individual repetitive tasks can be automated by software that can be developed in house, or by third party SaaS platforms.
For the individual retail investor, python bots pose a promising solution to various elements of real estate investing. In this article, we examine automating the process of analyzing properties. Other processes that could be automated include: listing properties, sending notices to tenants, screening tenants (machine learning or AI), and even automatically dispatching maintenance workers.
The program takes three inputs: the listing URL, the monthly rent price, and the property tax rate. It returns monthly cash flow, cap rate, and cash on cash return rate.
Cash flow — The profit each month after paying everything (mortgage, property management, repair allowances, vacancy expense)
Cap rate — The net income per year divided by the price of the asset (in percent)
Cash on cash return rate — Net income per year divided by the down payment used for the asset (in percent)
The following packages were used. Note for those working in the Anacondas environment, it appears that streamlit is not currently available through this package manager. Streamlit was installed with pip, which might cause issues when PIP and Anacondas are used together
Requests — This package was used to access websites in python via HTTP requests.
Beautiful soup 4 — Used for web scraping and data mining. We are able to use this package to retrieve HTML code that describes the content and styling of a website. Once the HTML code is retrieved, beautiful soup can be utilized to isolate specific parts of the site. For example, in this project, we use beautiful soup to fetch the house price.
Streamlit — This package makes deploying web apps super simple. The coded was developed in a Jupyter notebook, then converted to .py scripts once it was working. Streamlit allowed for seamless deployment and minimal time spent on user interface. A classic deployment option of combining python for the backend, flask for deployment, and react for dynamic content is much more straightforward using streamlit.
The functions that do the majority of the heavy lifting are price_mine, mortgage_monthly, and net_operating.
These are the main functions that perform the following duties respectively:
Retrieving the listing price from the URL
Calculating the monthly mortgage cost
Finding the monthly net operating income after all expenses
price_mine | This function was designed to retrieve the house price from the listing. APIs could be used, but web-scraping is empowering. The downside of web scraping is that changes to the sites structure need to be updated in the code. Here, the web scraping package used was beautiful soup. The process is relatively simple, the web page is inspected using f12, then the desired element is found in the HTML code. This code can be isolated in beautiful soup to retrieve a specific part of the page. Once the code was retrieved the built in python function replace was used to remove commas, dollar signs, and unnecessary spaces so that a float variable can be established.
def price_mine(url): #Currently this function takes an input of a URL and returns the listing prices #The site it mines is remax #The input must be a string input, we can reformat the input to force this to work #Next we use regex to remove space and commas and dollar signs headers = ({'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}) response = get(url) response_text = response.text html_soup = BeautifulSoup(response_text, 'html.parser') prices = html_soup.find('h2',{'class': 'price'}).text prices = prices.replace(",", "") prices = prices.replace("$", "") prices = prices.replace(" ", "") prices = float(prices) return prices
mortgage_monthly | This function takes the listing price, mortgage length, and interest rate as inputs, and returns the monthly mortgage price. There are many ways to calculate the monthly mortgage price, no specific decision was made as far as which method to use and a generic algorithm that was fairly easy to implement was used.
def mortgage_monthly(price,years,percent): #This implements an approach to finding a monthly mortgage amount from the purchase price, #years and percent. #Sample input: (300000,20,4) = 2422 # percent = percent /100 down = down_payment(price,20) loan = price - down months = years*12 interest_monthly = percent/12 interest_plus = interest_monthly + 1 exponent = (interest_plus)**(-1*months) subtract = 1 - exponent division = interest_monthly / subtract payment = division * loan return(payment)
net_operating | This function takes the monthly rent, the tax rate, and the price as inputs, and returns the net operating income per month. The amount of net operating income each represents the cash after: paying the mortgage (principle and interest), property taxes, paying a management fee (10% per month), property repairs allowances, and vacancy allowances. The argument could be made that only the monthly interest payment constitutes an expense since the principle builds equity. While this is true, our model wants to find out how much cash is left after paying everything. Individual investment analysis bots could change elements like this to personalize the calculations to the individual investor.
def net_operating(rent, tax_rate, price): #Takes input as monthly mortgage amount and monthly rental amount #Uses managment expense, amount for repairs, vacancy ratio #Example input: net_operating(1000,1,400,200) #879.33 #1000 - 16.67 (tax) - 100 (managment) - 4 (repairs) mortgage_amt = mortgage_monthly(price,20,3) prop_managment = rent * 0.10 prop_tax = (price * (tax_rate/100)/12) prop_repairs = (price * 0.02)/12 vacancy = (rent*0.02) #These sections are a list of all the expenses used and formulas for each net_income = rent - prop_managment - prop_tax - prop_repairs - vacancy - mortgage_amt #Summing up expenses output = [prop_managment, prop_tax, prop_repairs, vacancy, net_income] return output
Other functions:
Other functions used such as cap_rate calculated the ratio of net income to asset price as a percent. The full list of function is available on the project’s GitHub repository but will be excluded from this documentation.
The idea was to have the inputs on the left-hand side of the page, and the output on the right-hand side of the page. The inputs were positioned inside a sidebar, this way the inputs and outputs are visually different.
A common way we could build this dashboard is to create a static website with HTML, deploy the back end using flask, store values in some sort of database, and link everything using react. A new alternative deployment path that has advantages over this approach is called streamlit.
Streamlit allows the fast transition from a python script to a modern user experience. It also offers a straightforward and fast deployment path. The first step in the conversion was to replace the built in python input functions and replace them with the streamlit input boxes. The same replacement was made for the output.
Once is this is done, the streamlit app can be deployed from the console, and accessed through the external IP address.
Once the user interface was built in streamlit, the code was modified to add a sidebar for the inputs as originally depicted in the above sketches.
The final code is available on GitHub.
Although groups such as renaissance technology have been able to profit from mathematical models applied to investing, there are benefits for individual retail investors that can be implemented much easier.
Real estate investors can benefit from automation by handling many tasks that would previously require an assistant, or tie up a lot of time. This was an example of using automation to reduce time spent on filtering deals. More deals could be reviewed by the investor if automated summary reports were generated and only the best assets were presented to a human. Mom and pop shops, real estate investors, and entrepreneurs can benefit from automation and not just fortune 500 companies.
Note from Towards Data Science’s editors: While we allow independent authors to publish articles in accordance with our rules and guidelines, we do not endorse each author’s contribution. You should not rely on an author’s works without seeking professional advice. See our Reader Terms for details.
|
[
{
"code": null,
"e": 358,
"s": 172,
"text": "The goal is to build a python web tool that is capable of analyzing investment properties. The tool will use data mining to find prices for properties, and then analyze the return rate."
},
{
"code": null,
"e": 366,
"s": 358,
"text": "Summary"
},
{
"code": null,
"e": 372,
"s": 366,
"text": "Index"
},
{
"code": null,
"e": 384,
"s": 372,
"text": "Motivations"
},
{
"code": null,
"e": 392,
"s": 384,
"text": "The App"
},
{
"code": null,
"e": 406,
"s": 392,
"text": "The Functions"
},
{
"code": null,
"e": 432,
"s": 406,
"text": "Summary and Going Forward"
},
{
"code": null,
"e": 806,
"s": 432,
"text": "The applications of bots or automation to trading and investments is not new. Multiple examples include stock trading bots tasked with buying or selling assets based on different models or indicators. Renaissance technology received the worlds attention due to their return rates through algorithmic investing that averaged 60%+ annualized returns over a 30-year time span."
},
{
"code": null,
"e": 1016,
"s": 806,
"text": "The benefits of automation have the potential to transform businesses of varying size. Individual repetitive tasks can be automated by software that can be developed in house, or by third party SaaS platforms."
},
{
"code": null,
"e": 1409,
"s": 1016,
"text": "For the individual retail investor, python bots pose a promising solution to various elements of real estate investing. In this article, we examine automating the process of analyzing properties. Other processes that could be automated include: listing properties, sending notices to tenants, screening tenants (machine learning or AI), and even automatically dispatching maintenance workers."
},
{
"code": null,
"e": 1579,
"s": 1409,
"text": "The program takes three inputs: the listing URL, the monthly rent price, and the property tax rate. It returns monthly cash flow, cap rate, and cash on cash return rate."
},
{
"code": null,
"e": 1705,
"s": 1579,
"text": "Cash flow — The profit each month after paying everything (mortgage, property management, repair allowances, vacancy expense)"
},
{
"code": null,
"e": 1787,
"s": 1705,
"text": "Cap rate — The net income per year divided by the price of the asset (in percent)"
},
{
"code": null,
"e": 1894,
"s": 1787,
"text": "Cash on cash return rate — Net income per year divided by the down payment used for the asset (in percent)"
},
{
"code": null,
"e": 2164,
"s": 1894,
"text": "The following packages were used. Note for those working in the Anacondas environment, it appears that streamlit is not currently available through this package manager. Streamlit was installed with pip, which might cause issues when PIP and Anacondas are used together"
},
{
"code": null,
"e": 2245,
"s": 2164,
"text": "Requests — This package was used to access websites in python via HTTP requests."
},
{
"code": null,
"e": 2591,
"s": 2245,
"text": "Beautiful soup 4 — Used for web scraping and data mining. We are able to use this package to retrieve HTML code that describes the content and styling of a website. Once the HTML code is retrieved, beautiful soup can be utilized to isolate specific parts of the site. For example, in this project, we use beautiful soup to fetch the house price."
},
{
"code": null,
"e": 3000,
"s": 2591,
"text": "Streamlit — This package makes deploying web apps super simple. The coded was developed in a Jupyter notebook, then converted to .py scripts once it was working. Streamlit allowed for seamless deployment and minimal time spent on user interface. A classic deployment option of combining python for the backend, flask for deployment, and react for dynamic content is much more straightforward using streamlit."
},
{
"code": null,
"e": 3109,
"s": 3000,
"text": "The functions that do the majority of the heavy lifting are price_mine, mortgage_monthly, and net_operating."
},
{
"code": null,
"e": 3186,
"s": 3109,
"text": "These are the main functions that perform the following duties respectively:"
},
{
"code": null,
"e": 3228,
"s": 3186,
"text": "Retrieving the listing price from the URL"
},
{
"code": null,
"e": 3266,
"s": 3228,
"text": "Calculating the monthly mortgage cost"
},
{
"code": null,
"e": 3326,
"s": 3266,
"text": "Finding the monthly net operating income after all expenses"
},
{
"code": null,
"e": 4002,
"s": 3326,
"text": "price_mine | This function was designed to retrieve the house price from the listing. APIs could be used, but web-scraping is empowering. The downside of web scraping is that changes to the sites structure need to be updated in the code. Here, the web scraping package used was beautiful soup. The process is relatively simple, the web page is inspected using f12, then the desired element is found in the HTML code. This code can be isolated in beautiful soup to retrieve a specific part of the page. Once the code was retrieved the built in python function replace was used to remove commas, dollar signs, and unnecessary spaces so that a float variable can be established."
},
{
"code": null,
"e": 4761,
"s": 4002,
"text": "def price_mine(url): #Currently this function takes an input of a URL and returns the listing prices #The site it mines is remax #The input must be a string input, we can reformat the input to force this to work #Next we use regex to remove space and commas and dollar signs headers = ({'User-Agent': 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36'}) response = get(url) response_text = response.text html_soup = BeautifulSoup(response_text, 'html.parser') prices = html_soup.find('h2',{'class': 'price'}).text prices = prices.replace(\",\", \"\") prices = prices.replace(\"$\", \"\") prices = prices.replace(\" \", \"\") prices = float(prices) return prices"
},
{
"code": null,
"e": 5094,
"s": 4761,
"text": "mortgage_monthly | This function takes the listing price, mortgage length, and interest rate as inputs, and returns the monthly mortgage price. There are many ways to calculate the monthly mortgage price, no specific decision was made as far as which method to use and a generic algorithm that was fairly easy to implement was used."
},
{
"code": null,
"e": 5659,
"s": 5094,
"text": "def mortgage_monthly(price,years,percent): #This implements an approach to finding a monthly mortgage amount from the purchase price, #years and percent. #Sample input: (300000,20,4) = 2422 # percent = percent /100 down = down_payment(price,20) loan = price - down months = years*12 interest_monthly = percent/12 interest_plus = interest_monthly + 1 exponent = (interest_plus)**(-1*months) subtract = 1 - exponent division = interest_monthly / subtract payment = division * loan return(payment)"
},
{
"code": null,
"e": 6370,
"s": 5659,
"text": "net_operating | This function takes the monthly rent, the tax rate, and the price as inputs, and returns the net operating income per month. The amount of net operating income each represents the cash after: paying the mortgage (principle and interest), property taxes, paying a management fee (10% per month), property repairs allowances, and vacancy allowances. The argument could be made that only the monthly interest payment constitutes an expense since the principle builds equity. While this is true, our model wants to find out how much cash is left after paying everything. Individual investment analysis bots could change elements like this to personalize the calculations to the individual investor."
},
{
"code": null,
"e": 7139,
"s": 6370,
"text": "def net_operating(rent, tax_rate, price): #Takes input as monthly mortgage amount and monthly rental amount #Uses managment expense, amount for repairs, vacancy ratio #Example input: net_operating(1000,1,400,200) #879.33 #1000 - 16.67 (tax) - 100 (managment) - 4 (repairs) mortgage_amt = mortgage_monthly(price,20,3) prop_managment = rent * 0.10 prop_tax = (price * (tax_rate/100)/12) prop_repairs = (price * 0.02)/12 vacancy = (rent*0.02) #These sections are a list of all the expenses used and formulas for each net_income = rent - prop_managment - prop_tax - prop_repairs - vacancy - mortgage_amt #Summing up expenses output = [prop_managment, prop_tax, prop_repairs, vacancy, net_income] return output"
},
{
"code": null,
"e": 7156,
"s": 7139,
"text": "Other functions:"
},
{
"code": null,
"e": 7378,
"s": 7156,
"text": "Other functions used such as cap_rate calculated the ratio of net income to asset price as a percent. The full list of function is available on the project’s GitHub repository but will be excluded from this documentation."
},
{
"code": null,
"e": 7597,
"s": 7378,
"text": "The idea was to have the inputs on the left-hand side of the page, and the output on the right-hand side of the page. The inputs were positioned inside a sidebar, this way the inputs and outputs are visually different."
},
{
"code": null,
"e": 7880,
"s": 7597,
"text": "A common way we could build this dashboard is to create a static website with HTML, deploy the back end using flask, store values in some sort of database, and link everything using react. A new alternative deployment path that has advantages over this approach is called streamlit."
},
{
"code": null,
"e": 8205,
"s": 7880,
"text": "Streamlit allows the fast transition from a python script to a modern user experience. It also offers a straightforward and fast deployment path. The first step in the conversion was to replace the built in python input functions and replace them with the streamlit input boxes. The same replacement was made for the output."
},
{
"code": null,
"e": 8325,
"s": 8205,
"text": "Once is this is done, the streamlit app can be deployed from the console, and accessed through the external IP address."
},
{
"code": null,
"e": 8473,
"s": 8325,
"text": "Once the user interface was built in streamlit, the code was modified to add a sidebar for the inputs as originally depicted in the above sketches."
},
{
"code": null,
"e": 8512,
"s": 8473,
"text": "The final code is available on GitHub."
},
{
"code": null,
"e": 8719,
"s": 8512,
"text": "Although groups such as renaissance technology have been able to profit from mathematical models applied to investing, there are benefits for individual retail investors that can be implemented much easier."
},
{
"code": null,
"e": 9207,
"s": 8719,
"text": "Real estate investors can benefit from automation by handling many tasks that would previously require an assistant, or tie up a lot of time. This was an example of using automation to reduce time spent on filtering deals. More deals could be reviewed by the investor if automated summary reports were generated and only the best assets were presented to a human. Mom and pop shops, real estate investors, and entrepreneurs can benefit from automation and not just fortune 500 companies."
}
] |
Longest Mountain Subarray - GeeksforGeeks
|
22 Sep, 2021
Given an array arr[] with N elements, the task is to find out the longest sub-array which has the shape of a mountain.
A mountain sub-array consists of elements that are initially in ascending order until a peak element is reached and beyond the peak element all other elements of the sub-array are in decreasing order.
Examples:
Input: arr = [2, 2, 2] Output: 0 Explanation: No sub-array exists that shows the behavior of a mountain sub-array.
Input: arr = [1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5] Output: 11 Explanation: There are two sub-arrays that can be considered as mountain sub-arrays. The first one is from index 0 – 2 (3 elements) and next one is from index 2 – 12 (11 elements). As 11 > 2, our answer is 11.
Naive Approach:Go through every possible sub-array and check whether it is a mountain sub-array or not. This might take a long time to find the solution and the time complexity for the above approach can be estimated as O(N*N) to go through every possible sub-array and O(N) to check whether it is a mountain sub-array or not. Thus, the overall time complexity for the program is O(N3) which is very high.
Efficient Approach:
If the length of the given array is less than 3, print 0 as it is not possible to have a mountain sub-array in such a case.Set the maximum length to 0 initially.Use the two-pointer technique (‘begin’ pointer and ‘end’ pointer) to find out the longest mountain sub-array in the given array.When an increasing sub-array is encountered, mark the beginning index of that increasing sub-array in the ‘begin’ pointer.If an index value is found in the ‘end’ pointer then reset the values in both the pointers as it marks the beginning of a new mountain sub-array.When a decreasing sub-array us encountered, mark the ending index of the mountain sub-array in the ‘end’ pointer.Calculate the length of the current mountain sub-array, compare it with the current maximum length of all-mountain sub-arrays traversed until now and keep updating the current maximum length.
If the length of the given array is less than 3, print 0 as it is not possible to have a mountain sub-array in such a case.
Set the maximum length to 0 initially.
Use the two-pointer technique (‘begin’ pointer and ‘end’ pointer) to find out the longest mountain sub-array in the given array.
When an increasing sub-array is encountered, mark the beginning index of that increasing sub-array in the ‘begin’ pointer.
If an index value is found in the ‘end’ pointer then reset the values in both the pointers as it marks the beginning of a new mountain sub-array.
When a decreasing sub-array us encountered, mark the ending index of the mountain sub-array in the ‘end’ pointer.
Calculate the length of the current mountain sub-array, compare it with the current maximum length of all-mountain sub-arrays traversed until now and keep updating the current maximum length.
Below is the implementation of the above described efficient approach:
C++
Java
Python3
C#
Javascript
// C++ code for Longest Mountain Subarray #include <bits/stdc++.h>using namespace std; // Function to find the// longest mountain subarrayint LongestMountain(vector<int>& a){ int i = 0, j = -1, k = -1, p = 0, d = 0, n = 0; // If the size of array is less // than 3, the array won't show // mountain like behaviour if (a.size() < 3) { return 0; } for (i = 0; i < a.size() - 1; i++) { if (a[i + 1] > a[i]) { // When a new mountain sub-array // is found, there is a need to // set the variables k, j to -1 // in order to help calculate the // length of new mountain sub-array if (k != -1) { k = -1; j = -1; } // j marks the starting index of a // new mountain sub-array. So set the // value of j to current index i. if (j == -1) { j = i; } } else { // Checks if next element is // less than current element if (a[i + 1] < a[i]) { // Checks if starting element exists // or not, if the starting element // of the mountain sub-array exists // then the index of ending element // is stored in k if (j != -1) { k = i + 1; } // This condition checks if both // starting index and ending index // exists or not, if yes, the // length is calculated. if (k != -1 && j != -1) { // d holds the length of the // longest mountain sub-array. // If the current length is // greater than the // calculated length, then // value of d is updated. if (d < k - j + 1) { d = k - j + 1; } } } // ignore if there is no // increase or decrease in // the value of the next element else { k = -1; j = -1; } } } // Checks and calculates // the length if last element // of the array is the last // element of a mountain sub-array if (k != -1 && j != -1) { if (d < k - j + 1) { d = k - j + 1; } } return d;} // Driver codeint main(){ vector<int> d = { 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 }; cout << LongestMountain(d) << endl; return 0;}
// Java code for Longest Mountain Subarrayimport java.io.*; class GFG{ // Function to find the// longest mountain subarraypublic static int LongestMountain(int a[]){ int i = 0, j = -1, k = -1, d = 0; // If the size of array is less than 3, // the array won't show mountain like // behaviour if (a.length < 3) return 0; for(i = 0; i < a.length - 1; i++) { if (a[i + 1] > a[i]) { // When a new mountain sub-array is // found, there is a need to set the // variables k, j to -1 in order to // help calculate the length of new // mountain sub-array if (k != -1) { k = -1; j = -1; } // j marks the starting index of a // new mountain sub-array. So set the // value of j to current index i. if (j == -1) j = i; } else { // Checks if next element is // less than current element if (a[i + 1] < a[i]) { // Checks if starting element exists // or not, if the starting element of // the mountain sub-array exists then // the index of ending element is // stored in k if (j != -1) k = i + 1; // This condition checks if both // starting index and ending index // exists or not, if yes,the length // is calculated. if (k != -1 && j != -1) { // d holds the length of the // longest mountain sub-array. // If the current length is // greater than the calculated // length, then value of d is // updated. if (d < k - j + 1) d = k - j + 1; } } // Ignore if there is no increase // or decrease in the value of the // next element else { k = -1; j = -1; } } } // Checks and calculates the length // if last element of the array is // the last element of a mountain sub-array if (k != -1 && j != -1) { if (d < k - j + 1) d = k - j + 1; } return d;} // Driver codepublic static void main (String[] args){ int a[] = { 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 }; System.out.println(LongestMountain(a));}} // This code is contributed by piyush3010
# Python3 code for longest mountain subarray # Function to find the# longest mountain subarraydef LongestMountain(a): i = 0 j = -1 k = -1 p = 0 d = 0 n = 0 # If the size of the array is less # than 3, the array won't show # mountain like behaviour if (len(a) < 3): return 0 for i in range(len(a) - 1): if (a[i + 1] > a[i]): # When a new mountain sub-array # is found, there is a need to # set the variables k, j to -1 # in order to help calculate the # length of new mountain sub-array if (k != -1): k = -1 j = -1 # j marks the starting index of a # new mountain sub-array. So set the # value of j to current index i. if (j == -1): j = i else: # Checks if next element is # less than current element if (a[i + 1] < a[i]): # Checks if starting element exists # or not, if the starting element # of the mountain sub-array exists # then the index of ending element # is stored in k if (j != -1): k = i + 1 # This condition checks if both # starting index and ending index # exists or not, if yes, the # length is calculated. if (k != -1 and j != -1): # d holds the length of the # longest mountain sub-array. # If the current length is # greater than the # calculated length, then # value of d is updated. if (d < k - j + 1): d = k - j + 1 # Ignore if there is no # increase or decrease in # the value of the next element else: k = -1 j = -1 # Checks and calculates # the length if last element # of the array is the last # element of a mountain sub-array if (k != -1 and j != -1): if (d < k - j + 1): d = k - j + 1 return d # Driver coded = [ 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 ] print(LongestMountain(d)) # This code is contributed by shubhamsingh10
// C# code for the// longest Mountain Subarrayusing System;class GFG{ // Function to find the// longest mountain subarraypublic static int longestMountain(int []a){ int i = 0, j = -1, k = -1, p = 0, d = 0; // If the size of array is less than 3, // the array won't show mountain like // behaviour if (a.Length < 3) return 0; for(i = 0; i < a.Length - 1; i++) { if (a[i + 1] > a[i]) { // When a new mountain sub-array is // found, there is a need to set the // variables k, j to -1 in order to // help calculate the length of new // mountain sub-array if (k != -1) { k = -1; j = -1; } // j marks the starting index of a // new mountain sub-array. So set the // value of j to current index i. if (j == -1) j = i; } else { // Checks if next element is // less than current element if (a[i + 1] < a[i]) { // Checks if starting element exists // or not, if the starting element of // the mountain sub-array exists then // the index of ending element is // stored in k if (j != -1) k = i + 1; // This condition checks if both // starting index and ending index // exists or not, if yes,the length // is calculated. if (k != -1 && j != -1) { // d holds the length of the // longest mountain sub-array. // If the current length is // greater than the calculated // length, then value of d is // updated. if (d < k - j + 1) d = k - j + 1; } } // Ignore if there is no increase // or decrease in the value of the // next element else { k = -1; j = -1; } } } // Checks and calculates the length // if last element of the array is // the last element of a mountain sub-array if (k != -1 && j != -1) { if (d < k - j + 1) d = k - j + 1; } return d;} // Driver codepublic static void Main(String[] args){ int []a = {1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5}; Console.WriteLine(longestMountain(a));}} // This code is contributed by Princi Singh
<script> // Javascript code for Longest Mountain Subarray // Function to find the// longest mountain subarrayfunction LongestMountain(a){ let i = 0, j = -1, k = -1, p = 0, d = 0, n = 0; // If the size of array is less than 3, // the array won't show mountain like // behaviour if (a.length < 3) return 0; for(i = 0; i < a.length - 1; i++) { if (a[i + 1] > a[i]) { // When a new mountain sub-array is // found, there is a need to set the // variables k, j to -1 in order to // help calculate the length of new // mountain sub-array if (k != -1) { k = -1; j = -1; } // j marks the starting index of a // new mountain sub-array. So set the // value of j to current index i. if (j == -1) j = i; } else { // Checks if next element is // less than current element if (a[i + 1] < a[i]) { // Checks if starting element exists // or not, if the starting element of // the mountain sub-array exists then // the index of ending element is // stored in k if (j != -1) k = i + 1; // This condition checks if both // starting index and ending index // exists or not, if yes,the length // is calculated. if (k != -1 && j != -1) { // d holds the length of the // longest mountain sub-array. // If the current length is // greater than the calculated // length, then value of d is // updated. if (d < k - j + 1) d = k - j + 1; } } // Ignore if there is no increase // or decrease in the value of the // next element else { k = -1; j = -1; } } } // Checks and calculates the length // if last element of the array is // the last element of a mountain sub-array if (k != -1 && j != -1) { if (d < k - j + 1) d = k - j + 1; } return d;} // Driver Code let a = [ 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 ]; document.write(LongestMountain(a)); </script>
11
Time Complexity: O(N) Auxiliary Space Complexity: O(1)
SHUBHAMSINGH10
piyush3010
nidhi_biet
princi singh
target_2
sagartomar9927
parthibhanpa
surinderdawra388
subarray
Algorithms
Arrays
Competitive Programming
Data Structures
Mathematical
Data Structures
Arrays
Mathematical
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
How to Start Learning DSA?
Difference between Algorithm, Pseudocode and Program
K means Clustering - Introduction
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation
|
[
{
"code": null,
"e": 25943,
"s": 25915,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 26062,
"s": 25943,
"text": "Given an array arr[] with N elements, the task is to find out the longest sub-array which has the shape of a mountain."
},
{
"code": null,
"e": 26263,
"s": 26062,
"text": "A mountain sub-array consists of elements that are initially in ascending order until a peak element is reached and beyond the peak element all other elements of the sub-array are in decreasing order."
},
{
"code": null,
"e": 26274,
"s": 26263,
"text": "Examples: "
},
{
"code": null,
"e": 26389,
"s": 26274,
"text": "Input: arr = [2, 2, 2] Output: 0 Explanation: No sub-array exists that shows the behavior of a mountain sub-array."
},
{
"code": null,
"e": 26664,
"s": 26389,
"text": "Input: arr = [1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5] Output: 11 Explanation: There are two sub-arrays that can be considered as mountain sub-arrays. The first one is from index 0 – 2 (3 elements) and next one is from index 2 – 12 (11 elements). As 11 > 2, our answer is 11."
},
{
"code": null,
"e": 27070,
"s": 26664,
"text": "Naive Approach:Go through every possible sub-array and check whether it is a mountain sub-array or not. This might take a long time to find the solution and the time complexity for the above approach can be estimated as O(N*N) to go through every possible sub-array and O(N) to check whether it is a mountain sub-array or not. Thus, the overall time complexity for the program is O(N3) which is very high."
},
{
"code": null,
"e": 27091,
"s": 27070,
"text": "Efficient Approach: "
},
{
"code": null,
"e": 27952,
"s": 27091,
"text": "If the length of the given array is less than 3, print 0 as it is not possible to have a mountain sub-array in such a case.Set the maximum length to 0 initially.Use the two-pointer technique (‘begin’ pointer and ‘end’ pointer) to find out the longest mountain sub-array in the given array.When an increasing sub-array is encountered, mark the beginning index of that increasing sub-array in the ‘begin’ pointer.If an index value is found in the ‘end’ pointer then reset the values in both the pointers as it marks the beginning of a new mountain sub-array.When a decreasing sub-array us encountered, mark the ending index of the mountain sub-array in the ‘end’ pointer.Calculate the length of the current mountain sub-array, compare it with the current maximum length of all-mountain sub-arrays traversed until now and keep updating the current maximum length."
},
{
"code": null,
"e": 28076,
"s": 27952,
"text": "If the length of the given array is less than 3, print 0 as it is not possible to have a mountain sub-array in such a case."
},
{
"code": null,
"e": 28115,
"s": 28076,
"text": "Set the maximum length to 0 initially."
},
{
"code": null,
"e": 28244,
"s": 28115,
"text": "Use the two-pointer technique (‘begin’ pointer and ‘end’ pointer) to find out the longest mountain sub-array in the given array."
},
{
"code": null,
"e": 28367,
"s": 28244,
"text": "When an increasing sub-array is encountered, mark the beginning index of that increasing sub-array in the ‘begin’ pointer."
},
{
"code": null,
"e": 28513,
"s": 28367,
"text": "If an index value is found in the ‘end’ pointer then reset the values in both the pointers as it marks the beginning of a new mountain sub-array."
},
{
"code": null,
"e": 28627,
"s": 28513,
"text": "When a decreasing sub-array us encountered, mark the ending index of the mountain sub-array in the ‘end’ pointer."
},
{
"code": null,
"e": 28819,
"s": 28627,
"text": "Calculate the length of the current mountain sub-array, compare it with the current maximum length of all-mountain sub-arrays traversed until now and keep updating the current maximum length."
},
{
"code": null,
"e": 28890,
"s": 28819,
"text": "Below is the implementation of the above described efficient approach:"
},
{
"code": null,
"e": 28894,
"s": 28890,
"text": "C++"
},
{
"code": null,
"e": 28899,
"s": 28894,
"text": "Java"
},
{
"code": null,
"e": 28907,
"s": 28899,
"text": "Python3"
},
{
"code": null,
"e": 28910,
"s": 28907,
"text": "C#"
},
{
"code": null,
"e": 28921,
"s": 28910,
"text": "Javascript"
},
{
"code": "// C++ code for Longest Mountain Subarray #include <bits/stdc++.h>using namespace std; // Function to find the// longest mountain subarrayint LongestMountain(vector<int>& a){ int i = 0, j = -1, k = -1, p = 0, d = 0, n = 0; // If the size of array is less // than 3, the array won't show // mountain like behaviour if (a.size() < 3) { return 0; } for (i = 0; i < a.size() - 1; i++) { if (a[i + 1] > a[i]) { // When a new mountain sub-array // is found, there is a need to // set the variables k, j to -1 // in order to help calculate the // length of new mountain sub-array if (k != -1) { k = -1; j = -1; } // j marks the starting index of a // new mountain sub-array. So set the // value of j to current index i. if (j == -1) { j = i; } } else { // Checks if next element is // less than current element if (a[i + 1] < a[i]) { // Checks if starting element exists // or not, if the starting element // of the mountain sub-array exists // then the index of ending element // is stored in k if (j != -1) { k = i + 1; } // This condition checks if both // starting index and ending index // exists or not, if yes, the // length is calculated. if (k != -1 && j != -1) { // d holds the length of the // longest mountain sub-array. // If the current length is // greater than the // calculated length, then // value of d is updated. if (d < k - j + 1) { d = k - j + 1; } } } // ignore if there is no // increase or decrease in // the value of the next element else { k = -1; j = -1; } } } // Checks and calculates // the length if last element // of the array is the last // element of a mountain sub-array if (k != -1 && j != -1) { if (d < k - j + 1) { d = k - j + 1; } } return d;} // Driver codeint main(){ vector<int> d = { 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 }; cout << LongestMountain(d) << endl; return 0;}",
"e": 31617,
"s": 28921,
"text": null
},
{
"code": "// Java code for Longest Mountain Subarrayimport java.io.*; class GFG{ // Function to find the// longest mountain subarraypublic static int LongestMountain(int a[]){ int i = 0, j = -1, k = -1, d = 0; // If the size of array is less than 3, // the array won't show mountain like // behaviour if (a.length < 3) return 0; for(i = 0; i < a.length - 1; i++) { if (a[i + 1] > a[i]) { // When a new mountain sub-array is // found, there is a need to set the // variables k, j to -1 in order to // help calculate the length of new // mountain sub-array if (k != -1) { k = -1; j = -1; } // j marks the starting index of a // new mountain sub-array. So set the // value of j to current index i. if (j == -1) j = i; } else { // Checks if next element is // less than current element if (a[i + 1] < a[i]) { // Checks if starting element exists // or not, if the starting element of // the mountain sub-array exists then // the index of ending element is // stored in k if (j != -1) k = i + 1; // This condition checks if both // starting index and ending index // exists or not, if yes,the length // is calculated. if (k != -1 && j != -1) { // d holds the length of the // longest mountain sub-array. // If the current length is // greater than the calculated // length, then value of d is // updated. if (d < k - j + 1) d = k - j + 1; } } // Ignore if there is no increase // or decrease in the value of the // next element else { k = -1; j = -1; } } } // Checks and calculates the length // if last element of the array is // the last element of a mountain sub-array if (k != -1 && j != -1) { if (d < k - j + 1) d = k - j + 1; } return d;} // Driver codepublic static void main (String[] args){ int a[] = { 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 }; System.out.println(LongestMountain(a));}} // This code is contributed by piyush3010",
"e": 34353,
"s": 31617,
"text": null
},
{
"code": "# Python3 code for longest mountain subarray # Function to find the# longest mountain subarraydef LongestMountain(a): i = 0 j = -1 k = -1 p = 0 d = 0 n = 0 # If the size of the array is less # than 3, the array won't show # mountain like behaviour if (len(a) < 3): return 0 for i in range(len(a) - 1): if (a[i + 1] > a[i]): # When a new mountain sub-array # is found, there is a need to # set the variables k, j to -1 # in order to help calculate the # length of new mountain sub-array if (k != -1): k = -1 j = -1 # j marks the starting index of a # new mountain sub-array. So set the # value of j to current index i. if (j == -1): j = i else: # Checks if next element is # less than current element if (a[i + 1] < a[i]): # Checks if starting element exists # or not, if the starting element # of the mountain sub-array exists # then the index of ending element # is stored in k if (j != -1): k = i + 1 # This condition checks if both # starting index and ending index # exists or not, if yes, the # length is calculated. if (k != -1 and j != -1): # d holds the length of the # longest mountain sub-array. # If the current length is # greater than the # calculated length, then # value of d is updated. if (d < k - j + 1): d = k - j + 1 # Ignore if there is no # increase or decrease in # the value of the next element else: k = -1 j = -1 # Checks and calculates # the length if last element # of the array is the last # element of a mountain sub-array if (k != -1 and j != -1): if (d < k - j + 1): d = k - j + 1 return d # Driver coded = [ 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 ] print(LongestMountain(d)) # This code is contributed by shubhamsingh10",
"e": 36854,
"s": 34353,
"text": null
},
{
"code": "// C# code for the// longest Mountain Subarrayusing System;class GFG{ // Function to find the// longest mountain subarraypublic static int longestMountain(int []a){ int i = 0, j = -1, k = -1, p = 0, d = 0; // If the size of array is less than 3, // the array won't show mountain like // behaviour if (a.Length < 3) return 0; for(i = 0; i < a.Length - 1; i++) { if (a[i + 1] > a[i]) { // When a new mountain sub-array is // found, there is a need to set the // variables k, j to -1 in order to // help calculate the length of new // mountain sub-array if (k != -1) { k = -1; j = -1; } // j marks the starting index of a // new mountain sub-array. So set the // value of j to current index i. if (j == -1) j = i; } else { // Checks if next element is // less than current element if (a[i + 1] < a[i]) { // Checks if starting element exists // or not, if the starting element of // the mountain sub-array exists then // the index of ending element is // stored in k if (j != -1) k = i + 1; // This condition checks if both // starting index and ending index // exists or not, if yes,the length // is calculated. if (k != -1 && j != -1) { // d holds the length of the // longest mountain sub-array. // If the current length is // greater than the calculated // length, then value of d is // updated. if (d < k - j + 1) d = k - j + 1; } } // Ignore if there is no increase // or decrease in the value of the // next element else { k = -1; j = -1; } } } // Checks and calculates the length // if last element of the array is // the last element of a mountain sub-array if (k != -1 && j != -1) { if (d < k - j + 1) d = k - j + 1; } return d;} // Driver codepublic static void Main(String[] args){ int []a = {1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5}; Console.WriteLine(longestMountain(a));}} // This code is contributed by Princi Singh",
"e": 39073,
"s": 36854,
"text": null
},
{
"code": "<script> // Javascript code for Longest Mountain Subarray // Function to find the// longest mountain subarrayfunction LongestMountain(a){ let i = 0, j = -1, k = -1, p = 0, d = 0, n = 0; // If the size of array is less than 3, // the array won't show mountain like // behaviour if (a.length < 3) return 0; for(i = 0; i < a.length - 1; i++) { if (a[i + 1] > a[i]) { // When a new mountain sub-array is // found, there is a need to set the // variables k, j to -1 in order to // help calculate the length of new // mountain sub-array if (k != -1) { k = -1; j = -1; } // j marks the starting index of a // new mountain sub-array. So set the // value of j to current index i. if (j == -1) j = i; } else { // Checks if next element is // less than current element if (a[i + 1] < a[i]) { // Checks if starting element exists // or not, if the starting element of // the mountain sub-array exists then // the index of ending element is // stored in k if (j != -1) k = i + 1; // This condition checks if both // starting index and ending index // exists or not, if yes,the length // is calculated. if (k != -1 && j != -1) { // d holds the length of the // longest mountain sub-array. // If the current length is // greater than the calculated // length, then value of d is // updated. if (d < k - j + 1) d = k - j + 1; } } // Ignore if there is no increase // or decrease in the value of the // next element else { k = -1; j = -1; } } } // Checks and calculates the length // if last element of the array is // the last element of a mountain sub-array if (k != -1 && j != -1) { if (d < k - j + 1) d = k - j + 1; } return d;} // Driver Code let a = [ 1, 3, 1, 4, 5, 6, 7, 8, 9, 8, 7, 6, 5 ]; document.write(LongestMountain(a)); </script>",
"e": 41745,
"s": 39073,
"text": null
},
{
"code": null,
"e": 41748,
"s": 41745,
"text": "11"
},
{
"code": null,
"e": 41806,
"s": 41750,
"text": "Time Complexity: O(N) Auxiliary Space Complexity: O(1) "
},
{
"code": null,
"e": 41821,
"s": 41806,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 41832,
"s": 41821,
"text": "piyush3010"
},
{
"code": null,
"e": 41843,
"s": 41832,
"text": "nidhi_biet"
},
{
"code": null,
"e": 41856,
"s": 41843,
"text": "princi singh"
},
{
"code": null,
"e": 41865,
"s": 41856,
"text": "target_2"
},
{
"code": null,
"e": 41880,
"s": 41865,
"text": "sagartomar9927"
},
{
"code": null,
"e": 41893,
"s": 41880,
"text": "parthibhanpa"
},
{
"code": null,
"e": 41910,
"s": 41893,
"text": "surinderdawra388"
},
{
"code": null,
"e": 41919,
"s": 41910,
"text": "subarray"
},
{
"code": null,
"e": 41930,
"s": 41919,
"text": "Algorithms"
},
{
"code": null,
"e": 41937,
"s": 41930,
"text": "Arrays"
},
{
"code": null,
"e": 41961,
"s": 41937,
"text": "Competitive Programming"
},
{
"code": null,
"e": 41977,
"s": 41961,
"text": "Data Structures"
},
{
"code": null,
"e": 41990,
"s": 41977,
"text": "Mathematical"
},
{
"code": null,
"e": 42006,
"s": 41990,
"text": "Data Structures"
},
{
"code": null,
"e": 42013,
"s": 42006,
"text": "Arrays"
},
{
"code": null,
"e": 42026,
"s": 42013,
"text": "Mathematical"
},
{
"code": null,
"e": 42037,
"s": 42026,
"text": "Algorithms"
},
{
"code": null,
"e": 42135,
"s": 42037,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42160,
"s": 42135,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 42187,
"s": 42160,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 42240,
"s": 42187,
"text": "Difference between Algorithm, Pseudocode and Program"
},
{
"code": null,
"e": 42274,
"s": 42240,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 42341,
"s": 42274,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 42356,
"s": 42341,
"text": "Arrays in Java"
},
{
"code": null,
"e": 42372,
"s": 42356,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 42440,
"s": 42372,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 42486,
"s": 42440,
"text": "Write a program to reverse an array or string"
}
] |
Bayesian Neural Networks: 1 Why Bother? | by Adam Woolf | Towards Data Science
|
This is the first chapter in a series on Bayesian Deep Learning. The next chapter is available here while the third is here.
I’m often asked to explain my quirky interest in Bayesian Neural Networks. So this is the start of a series about them. Therefore it’s safe for me to say this is the start of a series about the future of deep learning — a future that’s available right now. Over the weeks you’ll learn how to use one of the new libraries built for the Bayesian-type neural network. I’ll include code and discuss work with both TensorFlow-Probability and Pytorches Pyro including the installation, training and prediction with various different network architectures. In this chapter we’ll cover the following objectives:
• Learn why Bayesian Neural networks are so useful and exciting • Understand how they’re different from normal neural networks • Appreciate how the uncertainty metrics you can obtain are a major advantage • Install a library to start work with all things random
Many developers of deep learning today didn’t begin with a computer-science or academic background. Trial and error, patience with a book and some blogs go a long way. And unsurprisingly Bayesian deep learning doesn’t require anything different.
But the advantage of some basic theoretical knowledge is greater than usual. Reassuringly this can be compressed, expressed and understood fairly simply. Primarily, it’s the unusual terminology that causes confusion. So we’ll have a talk about them with a few chips of code before getting stuck in.
We’re interested in random variables. That means most our variables change values whenever they’re requested. So informally random variables are slippery things (and more formally we call them ‘stochastic variables’, but who benefits from formality?). Working with either TensorFlow-Probability (TFP) or Pytorches Pyro you can call:
rv_normal = dist.Normal(loc=0., scale=3.)rv_normal.sample([1])
This will return a single value which will be different every time we run the second line. That’s the case even when we don’t re-run the first line, because rv_normal is a random variable defined by the normal (gaussian) distribution.
You might therefore plug these random variables into a neural network and use them in the place of the point values we normally use for weights. Why’d you want to bother? Because after the network is trained each prediction we make will be with different random variable weights. Therefore, the whole model will be different. Yet — before I loose you, the importance of our neural networks built with random variables is the variables are constrained as though on a dog leash to only return values over a certain range. That’s because our neural network training has trained our normal distribution to be placed with its bell shaped peak around the very best value.
Three points come up from all this: • The distributions own the random variables that return our random weight values every time we make a prediction. • Our neural network training moves the a whole distribution, not just a point weight value. • This is similar to the process of using a distribution to initialise weights in a conventional neural network (for the starting values for the weights). Except we carry on using the distribution throughout training and for prediction, not just for initialisation.
Training the distributions is more formally called conditioning the distributions (similar in meaning to Pavlov conditioning his dogs. (I can neither escape formality nor dogs it seems)). So all these fiddly random variables and distributions add up to one thing.., different predictions. But if we’ve trained the Bayesian Neural network well our predictions will be very similar (for continuous, floating point, regression outputs) and the same for (categorical outputs.). And if we train our neural network badly we’ll get very different results each time. If the Bayesian network could speak it would say the difference between it’s predictions being similar or its predictions being very different is its uncertainty. Think of uncertainty as confidence (only Bayesian neural networks don’t like to talk of their confidence so call it something different). If we’ve built a good network architecture, and most importantly if we’ve provided good data, the neural network will give confident predictions, and if everything we do is bad we’ll get unconfident predictions. In Bayesian wizardry terms the neural network will be more uncertain when we give bad and less uncertain when we give good. The wizardry difference in terms because Bayesian neural networks are never certain or anything, they’re only less uncertain. While our conventional neural networks are always certain of everything! You’ve may seen something similar already when you first began working with neural networks. You finished training your first model and have moderate performance, then you train another without making any changes and still have moderately good performance on average, only you’re getting entirely different results returned. Bayesian neural networks are like that, only instead of relying on your frustration to keep training neural networks with minor differences, with a Bayesian approach you train once and have an infinite number of models built-in.
Wonderful. Applause. So? So... we can switch that all around and see how suitable our data (predominantly) is for the task by looking at the variability of the results. But much much better than that with a Bayesian model we’re usually able to train a model with less data than we’d conventionally need for a neural network. The Bayesian model will generalise well. Its also less troubled by imbalances in the amount of data for each training class — a much neglected reason for poor performance.
Enough of the chatter my good man, show us how to do-something. Right-oh.
First you’ll need to install one of the two main probabilistic-programming libraries to follow the series. While you can build Bayesian neural networks with just the core libraries you’ll need to implement the training code manually which isn’t shy on math and hidden errors. So we’ll use either Pyro (built on top of Pytorch) or TensorFlow-Probability (perhaps obviously built on top of TensorFlow)1. If you have experience with one of the core libraries it’s probably best to continue with it specifically and benefit from your familiarity rather than changing over. Scroll bellow to one of the relevant library sections you prefer, or if you’re a masochist go ahead and implement them both then email me3.
We’ll be working with TensorFlow 2 as a base library which has some similar implementations to PyTorch, though benefits from many features we’ll use in later chapters2. TensorFlow in general also benefits from language and platform portability. You can call a model written in Python TensorFlow from almost any language from Java to C# and deploy models quite easily to mobile devices.
TensorFlow and TensorFlow-Probability are easy to install. Ensure you have Python installed (Python 3, if you haven’t this or any Python distribution I strongly recommend downloading the Anaconda distribution from: www.anaconda.com which contains everything you need to get going here on in.)
If you want to use Anaconda/Miniconda for installation of TensorFlow then use the conda package manager and type:
conda install tensorflow
or for GPU support:
conda install tensorflow-gpu
At the time of writing there are some benefits to installing with conda rather than pip if you want GPU support. The conda version automatically installs math libraries that significantly improve CPU training performance. GPU installation (tensorflow-gpu) is also easier with conda as by default it installs CUDA and cuDNN which require independent installation with pip. GPU versoins require a CUDA (i.e. NVIDIA) GPU on the machine. However conda doesn’t contain as many different libraries as pip does and breaks easily when using pip along side it.
To install the compute (non-GPU) version with pip:
pip install — upgrade tensorflow==2.*
or if you want to use a GPU version with pip:
pip install — upgrade tensorflow-gpu==2.*)
If you’re unsure choose the first one. The 2.* part ensures installation of the latest 2 version. The series can mostly be worked through with TensorFlow versions >1.13 but requires activation of eager execution (activated by default in TF2) with: tf.enable_eager_execution() after importing TensorFlow in addition to some other changes in latter chapters of the series.
Note: you must install the core TensorFlow library before installing TensorFlow-Probability and surprisingly TensorFlow-Probability installation wont install the core library for you as a dependency.
Install TFP via conda with:
conda install -c conda-forge tensorflow-probability
and with pip:
pip install — upgrade tensorflow-probability
Then to check that everythings working create a new Jupyter Notebook, IPython instance or a Python script and add:
import tensorflow as tfimport tensorflow_probability as tfpdist = tfp.distributionsrv_normal = dist.Normal(loc=0., scale=3.)print(rv_normal.sample([1]))
You’ll recognise the final two lines from the start of the chapter. You’re sampling a random variable so as output you should get a tensor containing a different random value every time you execute the final line.
[Out]: tf.Tensor([2.2621622], shape=(1,), dtype=float32)
For Pyro you first require a PyTorch installation. Typically this can be easiest performed through conda with:
conda install pytorch-cpu torchvision-cpu -c pytorch
or if a NIVIDA GPU is available for you to use:
conda install pytorch torchvision cudatoolkit=9.0 -c pytorch
Pip installation is also possible but unfortunately differs significantly by platform and by CUDA version therefore it’s recommended you refer to the installation guide at pytorch.org if you only want to use pip.
Pyro is then installed with:
conda install -c gwerbin pyro-ppl
or
pip install pyro-ppl
Note of caution: The package ‘pyro’ (without the -ppl) is entirely different software and unrelated to Pytorch-Pyro.
To get going with Pyro create a Jupyter notebook, Ipython console or Python script and type:
import torchimport pyroimport pyro.distributions as distrv_normal = dist.Normal(loc=0., scale=3.)print(rv_normal.sample([1]))
You’ll recognise the final two lines from the start of the chapter. You’re sampling a random variable so as output you should get a tensor containing a different random value every time you execute the final line.
[Out]: tensor([0.0514])
You’ve learnt about the relationship between a random variable and a distribution and seen it in action. You implemented a normal distribution located at 0 with a scale of 3. The location is another word for the distributions mean, while the scale is another word for the standard deviation. We’ll stick with the terms location and scale however as these terms help us to be consistent when working with other (non-normal) distributions.
Next week we’ll learn how to implement a Bayesian neural network and find out a bit more about where these distributions and random variables fit in. I bet you can’t wait! Subscribe to the blog for notifications about the next release.
[1]: You might have heard of PyMC3 too another good library that you can build probabilistic models with. However PyMC3 leans specifically towards statistical modelling in general and isn’t as friendly to people working with neural networks (Autograd and GPU support more challenging for instance).
[2]: TensorFlow 2 for instance removes the ’session’ context needed to setup graphs and instead works with functions.
[3]: If you can’t choose which library to use you’ll find TensorFlow-Probability is considerably simpler and easier than Pyro to both use and understand. However, that said documentation for Pyro is excellent while it’s lighter on explanation for TFP from the perspective of neural networks.
|
[
{
"code": null,
"e": 297,
"s": 172,
"text": "This is the first chapter in a series on Bayesian Deep Learning. The next chapter is available here while the third is here."
},
{
"code": null,
"e": 901,
"s": 297,
"text": "I’m often asked to explain my quirky interest in Bayesian Neural Networks. So this is the start of a series about them. Therefore it’s safe for me to say this is the start of a series about the future of deep learning — a future that’s available right now. Over the weeks you’ll learn how to use one of the new libraries built for the Bayesian-type neural network. I’ll include code and discuss work with both TensorFlow-Probability and Pytorches Pyro including the installation, training and prediction with various different network architectures. In this chapter we’ll cover the following objectives:"
},
{
"code": null,
"e": 1163,
"s": 901,
"text": "• Learn why Bayesian Neural networks are so useful and exciting • Understand how they’re different from normal neural networks • Appreciate how the uncertainty metrics you can obtain are a major advantage • Install a library to start work with all things random"
},
{
"code": null,
"e": 1409,
"s": 1163,
"text": "Many developers of deep learning today didn’t begin with a computer-science or academic background. Trial and error, patience with a book and some blogs go a long way. And unsurprisingly Bayesian deep learning doesn’t require anything different."
},
{
"code": null,
"e": 1708,
"s": 1409,
"text": "But the advantage of some basic theoretical knowledge is greater than usual. Reassuringly this can be compressed, expressed and understood fairly simply. Primarily, it’s the unusual terminology that causes confusion. So we’ll have a talk about them with a few chips of code before getting stuck in."
},
{
"code": null,
"e": 2041,
"s": 1708,
"text": "We’re interested in random variables. That means most our variables change values whenever they’re requested. So informally random variables are slippery things (and more formally we call them ‘stochastic variables’, but who benefits from formality?). Working with either TensorFlow-Probability (TFP) or Pytorches Pyro you can call:"
},
{
"code": null,
"e": 2104,
"s": 2041,
"text": "rv_normal = dist.Normal(loc=0., scale=3.)rv_normal.sample([1])"
},
{
"code": null,
"e": 2339,
"s": 2104,
"text": "This will return a single value which will be different every time we run the second line. That’s the case even when we don’t re-run the first line, because rv_normal is a random variable defined by the normal (gaussian) distribution."
},
{
"code": null,
"e": 3005,
"s": 2339,
"text": "You might therefore plug these random variables into a neural network and use them in the place of the point values we normally use for weights. Why’d you want to bother? Because after the network is trained each prediction we make will be with different random variable weights. Therefore, the whole model will be different. Yet — before I loose you, the importance of our neural networks built with random variables is the variables are constrained as though on a dog leash to only return values over a certain range. That’s because our neural network training has trained our normal distribution to be placed with its bell shaped peak around the very best value."
},
{
"code": null,
"e": 3516,
"s": 3005,
"text": "Three points come up from all this: • The distributions own the random variables that return our random weight values every time we make a prediction. • Our neural network training moves the a whole distribution, not just a point weight value. • This is similar to the process of using a distribution to initialise weights in a conventional neural network (for the starting values for the weights). Except we carry on using the distribution throughout training and for prediction, not just for initialisation."
},
{
"code": null,
"e": 5465,
"s": 3516,
"text": "Training the distributions is more formally called conditioning the distributions (similar in meaning to Pavlov conditioning his dogs. (I can neither escape formality nor dogs it seems)). So all these fiddly random variables and distributions add up to one thing.., different predictions. But if we’ve trained the Bayesian Neural network well our predictions will be very similar (for continuous, floating point, regression outputs) and the same for (categorical outputs.). And if we train our neural network badly we’ll get very different results each time. If the Bayesian network could speak it would say the difference between it’s predictions being similar or its predictions being very different is its uncertainty. Think of uncertainty as confidence (only Bayesian neural networks don’t like to talk of their confidence so call it something different). If we’ve built a good network architecture, and most importantly if we’ve provided good data, the neural network will give confident predictions, and if everything we do is bad we’ll get unconfident predictions. In Bayesian wizardry terms the neural network will be more uncertain when we give bad and less uncertain when we give good. The wizardry difference in terms because Bayesian neural networks are never certain or anything, they’re only less uncertain. While our conventional neural networks are always certain of everything! You’ve may seen something similar already when you first began working with neural networks. You finished training your first model and have moderate performance, then you train another without making any changes and still have moderately good performance on average, only you’re getting entirely different results returned. Bayesian neural networks are like that, only instead of relying on your frustration to keep training neural networks with minor differences, with a Bayesian approach you train once and have an infinite number of models built-in."
},
{
"code": null,
"e": 5962,
"s": 5465,
"text": "Wonderful. Applause. So? So... we can switch that all around and see how suitable our data (predominantly) is for the task by looking at the variability of the results. But much much better than that with a Bayesian model we’re usually able to train a model with less data than we’d conventionally need for a neural network. The Bayesian model will generalise well. Its also less troubled by imbalances in the amount of data for each training class — a much neglected reason for poor performance."
},
{
"code": null,
"e": 6036,
"s": 5962,
"text": "Enough of the chatter my good man, show us how to do-something. Right-oh."
},
{
"code": null,
"e": 6745,
"s": 6036,
"text": "First you’ll need to install one of the two main probabilistic-programming libraries to follow the series. While you can build Bayesian neural networks with just the core libraries you’ll need to implement the training code manually which isn’t shy on math and hidden errors. So we’ll use either Pyro (built on top of Pytorch) or TensorFlow-Probability (perhaps obviously built on top of TensorFlow)1. If you have experience with one of the core libraries it’s probably best to continue with it specifically and benefit from your familiarity rather than changing over. Scroll bellow to one of the relevant library sections you prefer, or if you’re a masochist go ahead and implement them both then email me3."
},
{
"code": null,
"e": 7131,
"s": 6745,
"text": "We’ll be working with TensorFlow 2 as a base library which has some similar implementations to PyTorch, though benefits from many features we’ll use in later chapters2. TensorFlow in general also benefits from language and platform portability. You can call a model written in Python TensorFlow from almost any language from Java to C# and deploy models quite easily to mobile devices."
},
{
"code": null,
"e": 7424,
"s": 7131,
"text": "TensorFlow and TensorFlow-Probability are easy to install. Ensure you have Python installed (Python 3, if you haven’t this or any Python distribution I strongly recommend downloading the Anaconda distribution from: www.anaconda.com which contains everything you need to get going here on in.)"
},
{
"code": null,
"e": 7538,
"s": 7424,
"text": "If you want to use Anaconda/Miniconda for installation of TensorFlow then use the conda package manager and type:"
},
{
"code": null,
"e": 7563,
"s": 7538,
"text": "conda install tensorflow"
},
{
"code": null,
"e": 7583,
"s": 7563,
"text": "or for GPU support:"
},
{
"code": null,
"e": 7612,
"s": 7583,
"text": "conda install tensorflow-gpu"
},
{
"code": null,
"e": 8164,
"s": 7612,
"text": "At the time of writing there are some benefits to installing with conda rather than pip if you want GPU support. The conda version automatically installs math libraries that significantly improve CPU training performance. GPU installation (tensorflow-gpu) is also easier with conda as by default it installs CUDA and cuDNN which require independent installation with pip. GPU versoins require a CUDA (i.e. NVIDIA) GPU on the machine. However conda doesn’t contain as many different libraries as pip does and breaks easily when using pip along side it."
},
{
"code": null,
"e": 8215,
"s": 8164,
"text": "To install the compute (non-GPU) version with pip:"
},
{
"code": null,
"e": 8253,
"s": 8215,
"text": "pip install — upgrade tensorflow==2.*"
},
{
"code": null,
"e": 8299,
"s": 8253,
"text": "or if you want to use a GPU version with pip:"
},
{
"code": null,
"e": 8342,
"s": 8299,
"text": "pip install — upgrade tensorflow-gpu==2.*)"
},
{
"code": null,
"e": 8713,
"s": 8342,
"text": "If you’re unsure choose the first one. The 2.* part ensures installation of the latest 2 version. The series can mostly be worked through with TensorFlow versions >1.13 but requires activation of eager execution (activated by default in TF2) with: tf.enable_eager_execution() after importing TensorFlow in addition to some other changes in latter chapters of the series."
},
{
"code": null,
"e": 8913,
"s": 8713,
"text": "Note: you must install the core TensorFlow library before installing TensorFlow-Probability and surprisingly TensorFlow-Probability installation wont install the core library for you as a dependency."
},
{
"code": null,
"e": 8941,
"s": 8913,
"text": "Install TFP via conda with:"
},
{
"code": null,
"e": 8993,
"s": 8941,
"text": "conda install -c conda-forge tensorflow-probability"
},
{
"code": null,
"e": 9007,
"s": 8993,
"text": "and with pip:"
},
{
"code": null,
"e": 9052,
"s": 9007,
"text": "pip install — upgrade tensorflow-probability"
},
{
"code": null,
"e": 9167,
"s": 9052,
"text": "Then to check that everythings working create a new Jupyter Notebook, IPython instance or a Python script and add:"
},
{
"code": null,
"e": 9320,
"s": 9167,
"text": "import tensorflow as tfimport tensorflow_probability as tfpdist = tfp.distributionsrv_normal = dist.Normal(loc=0., scale=3.)print(rv_normal.sample([1]))"
},
{
"code": null,
"e": 9534,
"s": 9320,
"text": "You’ll recognise the final two lines from the start of the chapter. You’re sampling a random variable so as output you should get a tensor containing a different random value every time you execute the final line."
},
{
"code": null,
"e": 9591,
"s": 9534,
"text": "[Out]: tf.Tensor([2.2621622], shape=(1,), dtype=float32)"
},
{
"code": null,
"e": 9702,
"s": 9591,
"text": "For Pyro you first require a PyTorch installation. Typically this can be easiest performed through conda with:"
},
{
"code": null,
"e": 9755,
"s": 9702,
"text": "conda install pytorch-cpu torchvision-cpu -c pytorch"
},
{
"code": null,
"e": 9803,
"s": 9755,
"text": "or if a NIVIDA GPU is available for you to use:"
},
{
"code": null,
"e": 9864,
"s": 9803,
"text": "conda install pytorch torchvision cudatoolkit=9.0 -c pytorch"
},
{
"code": null,
"e": 10077,
"s": 9864,
"text": "Pip installation is also possible but unfortunately differs significantly by platform and by CUDA version therefore it’s recommended you refer to the installation guide at pytorch.org if you only want to use pip."
},
{
"code": null,
"e": 10106,
"s": 10077,
"text": "Pyro is then installed with:"
},
{
"code": null,
"e": 10140,
"s": 10106,
"text": "conda install -c gwerbin pyro-ppl"
},
{
"code": null,
"e": 10143,
"s": 10140,
"text": "or"
},
{
"code": null,
"e": 10165,
"s": 10143,
"text": "pip install pyro-ppl "
},
{
"code": null,
"e": 10282,
"s": 10165,
"text": "Note of caution: The package ‘pyro’ (without the -ppl) is entirely different software and unrelated to Pytorch-Pyro."
},
{
"code": null,
"e": 10375,
"s": 10282,
"text": "To get going with Pyro create a Jupyter notebook, Ipython console or Python script and type:"
},
{
"code": null,
"e": 10501,
"s": 10375,
"text": "import torchimport pyroimport pyro.distributions as distrv_normal = dist.Normal(loc=0., scale=3.)print(rv_normal.sample([1]))"
},
{
"code": null,
"e": 10715,
"s": 10501,
"text": "You’ll recognise the final two lines from the start of the chapter. You’re sampling a random variable so as output you should get a tensor containing a different random value every time you execute the final line."
},
{
"code": null,
"e": 10739,
"s": 10715,
"text": "[Out]: tensor([0.0514])"
},
{
"code": null,
"e": 11177,
"s": 10739,
"text": "You’ve learnt about the relationship between a random variable and a distribution and seen it in action. You implemented a normal distribution located at 0 with a scale of 3. The location is another word for the distributions mean, while the scale is another word for the standard deviation. We’ll stick with the terms location and scale however as these terms help us to be consistent when working with other (non-normal) distributions."
},
{
"code": null,
"e": 11413,
"s": 11177,
"text": "Next week we’ll learn how to implement a Bayesian neural network and find out a bit more about where these distributions and random variables fit in. I bet you can’t wait! Subscribe to the blog for notifications about the next release."
},
{
"code": null,
"e": 11712,
"s": 11413,
"text": "[1]: You might have heard of PyMC3 too another good library that you can build probabilistic models with. However PyMC3 leans specifically towards statistical modelling in general and isn’t as friendly to people working with neural networks (Autograd and GPU support more challenging for instance)."
},
{
"code": null,
"e": 11830,
"s": 11712,
"text": "[2]: TensorFlow 2 for instance removes the ’session’ context needed to setup graphs and instead works with functions."
}
] |
jQuery - Weather.js
|
Weather.js is a jQuery plugin to find the information about weather details.
A Simple of Weather.js example as shown below −
<!DOCTYPE html>
<html lang = "en">
<head>
<meta charset = "UTF-8">
<meta name = "viewport" content = "width = device-width,
initial-scale = 1">
<link rel = "stylesheet"
href = "https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel = "stylesheet"
href = "https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css">
<link href = 'https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700'
rel = 'stylesheet' type = 'text/css'>
<link rel = "stylesheet" type = "text/css" href = "weather.css">
</head>
<body id = "weather-background" class = "default-weather">
<canvas id = "rain-canvas"></canvas>
<canvas id = "cloud-canvas"></canvas>
<canvas id = "weather-canvas"></canvas>
<canvas id = "time-canvas"></canvas>
<canvas id = "lightning-canvas"></canvas>
<div class = "page-wrap">
<header class = "search-bar">
<p class = "search-text">
<span class = "search-location-text">
What's the weather like in
<input id = "search-location-input"
class = "search-location-input" type = "text"
placeholder = "City"> ?
</span>
</p>
<div class = "search-location-button-group">
<button id = "search-location-button"
class = "fa fa-search search-location-button search-button">
</button>
<!-- -->
<button id = "geo-button" class = "geo-button fa
fa-location-arrow search-button"></button>
</div>
</header>
<div id = "geo-error-message" class = "geo-error-message hide">
<button id = 'close-error' class = 'fa fa-times
close-error'></button>Uh oh! It looks like we can't
find your location. Please type your city into the search
box above!
</div>
<div id = "front-page-description"
class = "front-page-description middle">
<h1>Blank Canvas Weather</h1>
</div>
<div class = "attribution-links hide" id = "attribution-links">
<button id = 'close-attribution'
class = 'fa fa-times close-attribution'></button>
<h3>Icons from <a href = "https://thenounproject.com/">
Noun Project</a></h3>
<ul>
<li class = "icon-attribution">
<a href = "https://thenounproject.com/term/cloud/6852/">
Cloud</a> by Pieter J. Smits</li>
<li class = "icon-attribution">
<a href = "https://thenounproject.com/term/snow/64/">
Snow</a> from National Park Service Collection</li>
<li class = "icon-attribution">
<a href = "https://thenounproject.com/term/drop/11449/">
Drop</a> Alex Fuller</li>
<li class = "icon-attribution">
<a href = "https://thenounproject.com/term/smoke/27750/">
Smoke</a> by Gerardo Martín Martínez</li>
<li class = "icon-attribution">
<a href = "https://thenounproject.com/term/moon/13554/">
Moon</a> by Jory Raphael</li>
<li class = "icon-attribution">
<a href = "https://thenounproject.com/term/warning/18974/">
Warning</a> by Icomatic</li>
<li class = "icon-attribution">
<a href = "https://thenounproject.com/term/sun/13545/">
Sun</a> by Jory Raphael</li>
<li class = "icon-attribution">
<a href = "https://thenounproject.com/term/windsock/135621/">
Windsock</a> by Golden Roof</li>
</ul>
</div>
<div id = "weather" class = "weather middle hide">
<div class = "location" id = "location"></div>
<div class = "weather-container">
<div id = "temperature-info" class = "temperature-info">
<div class = "temperature" id = "temperature">
</div>
<div class = "weather-description" id = "weather-description">
</div>
</div>
<div class = "weather-box">
<ul class = "weather-info" id = "weather-info">
<li class = "weather-item humidity">Humidity:
<span id = "humidity"></span>%</li><!---->
<li class = "weather-item wind">Wind: <span
id = "wind-direction"></span> <span
id = "wind"></span> <span
id = "speed-unit"></span></li>
</ul>
</div>
<div class = "temp-change">
<button id = "celsius"
class = "temp-change-button celsius">°C
</button><button id = "fahrenheit"
class = "temp-change-button fahrenheit">
°F</button>
</div>
</div>
</div>
</div>
<script
src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js">
</script>
<script src = "weather.js">
</script>
</div>
</body>
</html>
This should produce following result −
27 Lectures
1 hours
Mahesh Kumar
27 Lectures
1.5 hours
Pratik Singh
72 Lectures
4.5 hours
Frahaan Hussain
60 Lectures
9 hours
Eduonix Learning Solutions
17 Lectures
2 hours
Sandip Bhattacharya
12 Lectures
53 mins
Laurence Svekis
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2399,
"s": 2322,
"text": "Weather.js is a jQuery plugin to find the information about weather details."
},
{
"code": null,
"e": 2448,
"s": 2399,
"text": "A Simple of Weather.js example as shown below −"
},
{
"code": null,
"e": 8209,
"s": 2448,
"text": "<!DOCTYPE html>\n<html lang = \"en\">\n <head>\n <meta charset = \"UTF-8\">\n <meta name = \"viewport\" content = \"width = device-width, \n initial-scale = 1\">\n <link rel = \"stylesheet\" \n href = \"https://maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css\">\n <link rel = \"stylesheet\" \n href = \"https://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.3/normalize.css\">\n <link href = 'https://fonts.googleapis.com/css?family=Open+Sans:400,300,600,700'\n rel = 'stylesheet' type = 'text/css'>\n <link rel = \"stylesheet\" type = \"text/css\" href = \"weather.css\">\n </head>\n\t\n <body id = \"weather-background\" class = \"default-weather\">\n <canvas id = \"rain-canvas\"></canvas>\n <canvas id = \"cloud-canvas\"></canvas>\n <canvas id = \"weather-canvas\"></canvas>\n <canvas id = \"time-canvas\"></canvas>\n <canvas id = \"lightning-canvas\"></canvas>\n\t\t\n <div class = \"page-wrap\">\n <header class = \"search-bar\">\n\t\t\t\n <p class = \"search-text\">\n <span class = \"search-location-text\">\n What's the weather like in \n \n <input id = \"search-location-input\" \n class = \"search-location-input\" type = \"text\"\n placeholder = \"City\"> ?\n </span>\n </p>\n\t\t\t\t\t\n <div class = \"search-location-button-group\">\n <button id = \"search-location-button\" \n class = \"fa fa-search search-location-button search-button\">\n </button>\n\t\t\t\t\t\t\n <!-- -->\n <button id = \"geo-button\" class = \"geo-button fa\n fa-location-arrow search-button\"></button>\n </div>\n\t\t\t\t\n </header>\n\n <div id = \"geo-error-message\" class = \"geo-error-message hide\">\n <button id = 'close-error' class = 'fa fa-times \n close-error'></button>Uh oh! It looks like we can't \n find your location. Please type your city into the search \n box above!\n </div>\n\n <div id = \"front-page-description\" \n\t\t\t class = \"front-page-description middle\">\n <h1>Blank Canvas Weather</h1>\n </div>\n\t\t\t\n <div class = \"attribution-links hide\" id = \"attribution-links\">\n <button id = 'close-attribution' \n class = 'fa fa-times close-attribution'></button>\n\t\t\t\t\t\n <h3>Icons from <a href = \"https://thenounproject.com/\">\n Noun Project</a></h3>\n\t\t\t\t\t\n <ul>\n <li class = \"icon-attribution\">\n <a href = \"https://thenounproject.com/term/cloud/6852/\">\n Cloud</a> by Pieter J. Smits</li>\n\t\t\t\t\t\t\n <li class = \"icon-attribution\">\n <a href = \"https://thenounproject.com/term/snow/64/\">\n Snow</a> from National Park Service Collection</li>\n\t\t\t\t\t\t\n <li class = \"icon-attribution\">\n <a href = \"https://thenounproject.com/term/drop/11449/\">\n Drop</a> Alex Fuller</li>\n\t\t\t\t\t\t\n <li class = \"icon-attribution\">\n <a href = \"https://thenounproject.com/term/smoke/27750/\">\n Smoke</a> by Gerardo Martín Martínez</li>\n\t\t\t\t\t\t\n <li class = \"icon-attribution\">\n <a href = \"https://thenounproject.com/term/moon/13554/\">\n Moon</a> by Jory Raphael</li>\n\t\t\t\t\t\t\n <li class = \"icon-attribution\">\n <a href = \"https://thenounproject.com/term/warning/18974/\">\n Warning</a> by Icomatic</li>\n\t\t\t\t\t\t\n <li class = \"icon-attribution\">\n <a href = \"https://thenounproject.com/term/sun/13545/\">\n Sun</a> by Jory Raphael</li>\n\t\t\t\t\t\t\n <li class = \"icon-attribution\">\n <a href = \"https://thenounproject.com/term/windsock/135621/\">\n Windsock</a> by Golden Roof</li>\n\t\t\t\t\t\t\n </ul>\t\t\n </div>\n\t\t\t\n <div id = \"weather\" class = \"weather middle hide\">\n <div class = \"location\" id = \"location\"></div>\n \n <div class = \"weather-container\">\n <div id = \"temperature-info\" class = \"temperature-info\">\n <div class = \"temperature\" id = \"temperature\">\n </div>\n <div class = \"weather-description\" id = \"weather-description\">\n </div>\n </div>\n\t\t\t\t\t\t\n <div class = \"weather-box\">\n <ul class = \"weather-info\" id = \"weather-info\">\n <li class = \"weather-item humidity\">Humidity:\n <span id = \"humidity\"></span>%</li><!---->\n <li class = \"weather-item wind\">Wind: <span \n id = \"wind-direction\"></span> <span \n id = \"wind\"></span> <span \n id = \"speed-unit\"></span></li>\n </ul>\n </div>\n\t\t\t\t\t\t\n <div class = \"temp-change\">\n <button id = \"celsius\" \n class = \"temp-change-button celsius\">°C\n </button><button id = \"fahrenheit\" \n class = \"temp-change-button fahrenheit\">\n °F</button>\n </div>\n\t\t\t\t\t\t\n </div>\n </div> \n\t\t\t\t\n </div>\n\t\t\t\n <script \n src = \"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js\">\n </script>\n <script src = \"weather.js\">\n </script>\n </div>\t\n </body>\n</html>"
},
{
"code": null,
"e": 8248,
"s": 8209,
"text": "This should produce following result −"
},
{
"code": null,
"e": 8281,
"s": 8248,
"text": "\n 27 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 8295,
"s": 8281,
"text": " Mahesh Kumar"
},
{
"code": null,
"e": 8330,
"s": 8295,
"text": "\n 27 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 8344,
"s": 8330,
"text": " Pratik Singh"
},
{
"code": null,
"e": 8379,
"s": 8344,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 8396,
"s": 8379,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 8429,
"s": 8396,
"text": "\n 60 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 8457,
"s": 8429,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 8490,
"s": 8457,
"text": "\n 17 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8511,
"s": 8490,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 8543,
"s": 8511,
"text": "\n 12 Lectures \n 53 mins\n"
},
{
"code": null,
"e": 8560,
"s": 8543,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 8567,
"s": 8560,
"text": " Print"
},
{
"code": null,
"e": 8578,
"s": 8567,
"text": " Add Notes"
}
] |
Tryit Editor v3.7
|
Tryit: The padding-left property
|
[] |
How to auto increment with 1 after deleting data from a MySQL table?
|
For this, you can use TRUNCATE TABLE command. Let us first create a table −
mysql> create table DemoTable1796
(
StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
StudentName varchar(20)
);
Query OK, 0 rows affected (0.00 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable1796(StudentName) values('Chris Brown');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1796(StudentName) values('David Miller');
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1796(StudentName) values('John Doe');
Query OK, 1 row affected (0.00 sec)
Display all records from the table using select statement
mysql> select * from DemoTable1796;
This will produce the following output
+-----------+--------------+
| StudentId | StudentName |
+-----------+--------------+
| 1 | Chris Brown |
| 2 | David Miller |
| 3 | John Doe |
+-----------+--------------+
3 rows in set (0.00 sec)
Here is the query to delete records from the table −
mysql> delete from DemoTable1796;
Query OK, 3 rows affected (0.00 sec)
Now insert a record into the table
mysql> insert into DemoTable1796(StudentName) values('John Doe');
Query OK, 1 row affected (0.00 sec)
mysql> select * from DemoTable1796;
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 4 | John Doe |
+-----------+-------------+
1 row in set (0.00 sec)
Now you can use TRUNCATE TABLE command
mysql> truncate table DemoTable1796;
Query OK, 0 rows affected (0.00 sec)
Now, let us insert some records into the table
mysql> insert into DemoTable1796(StudentName) values('John Doe');
Query OK, 1 row affected (0.00 sec)
mysql> select * from DemoTable1796;
+-----------+-------------+
| StudentId | StudentName |
+-----------+-------------+
| 1 | John Doe |
+-----------+-------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "For this, you can use TRUNCATE TABLE command. Let us first create a table −"
},
{
"code": null,
"e": 1309,
"s": 1138,
"text": "mysql> create table DemoTable1796\n (\n StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n StudentName varchar(20)\n );\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 1365,
"s": 1309,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1678,
"s": 1365,
"text": "mysql> insert into DemoTable1796(StudentName) values('Chris Brown');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1796(StudentName) values('David Miller');\nQuery OK, 1 row affected (0.00 sec)\nmysql> insert into DemoTable1796(StudentName) values('John Doe');\nQuery OK, 1 row affected (0.00 sec)"
},
{
"code": null,
"e": 1736,
"s": 1678,
"text": "Display all records from the table using select statement"
},
{
"code": null,
"e": 1772,
"s": 1736,
"text": "mysql> select * from DemoTable1796;"
},
{
"code": null,
"e": 1811,
"s": 1772,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2039,
"s": 1811,
"text": "+-----------+--------------+\n| StudentId | StudentName |\n+-----------+--------------+\n| 1 | Chris Brown |\n| 2 | David Miller |\n| 3 | John Doe |\n+-----------+--------------+\n3 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2092,
"s": 2039,
"text": "Here is the query to delete records from the table −"
},
{
"code": null,
"e": 2163,
"s": 2092,
"text": "mysql> delete from DemoTable1796;\nQuery OK, 3 rows affected (0.00 sec)"
},
{
"code": null,
"e": 2198,
"s": 2163,
"text": "Now insert a record into the table"
},
{
"code": null,
"e": 2500,
"s": 2198,
"text": "mysql> insert into DemoTable1796(StudentName) values('John Doe');\nQuery OK, 1 row affected (0.00 sec)\nmysql> select * from DemoTable1796;\n+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 4 | John Doe |\n+-----------+-------------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2539,
"s": 2500,
"text": "Now you can use TRUNCATE TABLE command"
},
{
"code": null,
"e": 2613,
"s": 2539,
"text": "mysql> truncate table DemoTable1796;\nQuery OK, 0 rows affected (0.00 sec)"
},
{
"code": null,
"e": 2660,
"s": 2613,
"text": "Now, let us insert some records into the table"
},
{
"code": null,
"e": 2962,
"s": 2660,
"text": "mysql> insert into DemoTable1796(StudentName) values('John Doe');\nQuery OK, 1 row affected (0.00 sec)\nmysql> select * from DemoTable1796;\n+-----------+-------------+\n| StudentId | StudentName |\n+-----------+-------------+\n| 1 | John Doe |\n+-----------+-------------+\n1 row in set (0.00 sec)"
}
] |
Java program to find the area of a circle
|
Area of a circle is the product of the square of its radius, and the value of PI, Therefore, to calculate the area of a rectangle
Get the radius of the circle.
Calculate the square of the radius.
Calculate the product of the value of PI and the value of the square of the radius.
Print the result.
import java.util.Scanner;
public class AreaOfCircle {
public static void main(String args[]){
int radius;
double area;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the radius of the circle ::");
radius = sc.nextInt();
area = (radius*radius)*Math.PI;
System.out.println("Area of the circle is ::"+area);
}
}
Enter the radius of the circle ::
55
Area of the circle is ::9503.317777109125
|
[
{
"code": null,
"e": 1192,
"s": 1062,
"text": "Area of a circle is the product of the square of its radius, and the value of PI, Therefore, to calculate the area of a rectangle"
},
{
"code": null,
"e": 1222,
"s": 1192,
"text": "Get the radius of the circle."
},
{
"code": null,
"e": 1258,
"s": 1222,
"text": "Calculate the square of the radius."
},
{
"code": null,
"e": 1342,
"s": 1258,
"text": "Calculate the product of the value of PI and the value of the square of the radius."
},
{
"code": null,
"e": 1360,
"s": 1342,
"text": "Print the result."
},
{
"code": null,
"e": 1733,
"s": 1360,
"text": "import java.util.Scanner;\npublic class AreaOfCircle {\n public static void main(String args[]){\n int radius;\n double area;\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter the radius of the circle ::\");\n radius = sc.nextInt();\n area = (radius*radius)*Math.PI;\n System.out.println(\"Area of the circle is ::\"+area);\n }\n}"
},
{
"code": null,
"e": 1812,
"s": 1733,
"text": "Enter the radius of the circle ::\n55\nArea of the circle is ::9503.317777109125"
}
] |
Tryit Editor v3.7
|
Tryit: Use six of the animation properties
|
[] |
Isolation Forest and Spark. Main characteristics and ways to use... | by Maria Karanasou | Towards Data Science
|
Isolation Forest is an algorithm for anomaly / outlier detection, basically a way to spot the odd one out. We go through the main characteristics and explore two ways to use Isolation Forest with Pyspark.
Most existing model-based approaches to anomaly detection construct a profile of normal instances, then identify instances that do not conform to the normal profile as anomalies. [...] [Isolation Forest] explicitly isolates anomalies instead of profiles normal points
source: https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf
Isolation means separating an instance from the rest of the instances
it uses normal samples as the training set and can allow a few instances of abnormal samples (configurable). You basically feed the algorithm your normal data and it doesn’t mind if your dataset is not that well curated, provided you tune the contamination parameter. In other words it learns what normal looks like to be able to distinguish the abnormal,
it works with the basic assumption that anomalies are few and easily distinguishable,
it has a linear time complexity with a low constant and a low memory requirements*,
it is fast because it doesn’t utilize any distance or density measures,
can scale up very well. It seems to work well with high dimensional problems that may have a large number of irrelevant attributes.
*low memory requirements come from the fact that each tree in the forest does not have to be constructed the wholly, since the anomalies should have a lot shorter paths than the normal instances, so a max depth can be used to cut off the tree construction.
Isolation Forest takes advantage of the two characteristics of anomalies: that they are few and distinct / different
One way to detect anomalies is to sort data points according to their path lengths or anomaly scores; and anomalies are points that are ranked at the top of the list
Path length: the number of edges until we reach an external node
Anomaly Score
This is basically the output of the algorithm, which is ≤1 and ≥0. This is where the path length come in the picture. With the estimation of the average path length in the whole forest, we can deduce whether a point is anomalous or not.
If the anomaly score for an instance is very close to 1 then it is safe to say that this instance is an anomaly, if it is < 0.5 then it is probably a normal instance and if it is ~= 0.5 then the entire sample does not have any distinct anomalies.
number of trees / estimators : how big is the forest
contamination: the fraction of the dataset that contains abnormal instances, e.g. 0.1 or 10%
max samples: The number of samples to draw from the training set to train each Isolation Tree with.
max depth: how deep the tree should be, this can be used to trim the tree and make things faster.
The algorithm learns what normal looks like to be able to distinguish the abnormal
The Scikit-learn way will need us to create a udf to be able to predict upon a dataframe. This is the usual way in general to utilize a Scikit-learn model. Note that we cannot parallelize the training part using spark — but we can use the parameter n_jobs=-1 to utilize all cores on our machine. Another important thing to remember is to set the random_seed to something specific so that the results are reproducible.
All we need to do is install scikit-learn and its dependenciespip install sklearn numpy scipy
Then we can start with a simple example, a dataframe with four samples.
There is more than one way to go about this udf, for example you can load the model within the udf from a file (which can potentially cause errors because of the parallelization), or you could pass the serialized model as a column (which will increase your memory consumption by a lot), but I’ve found that the use of broadcast variables works best in terms of time and memory performance.
Let me know if there’s a better way to do this :)
There is no official package for iForest in the Spark ML library currently. However, I’ve found two implementations, one by LinkedIn which only has the Scala implementation and one by Fangzhou Yang that can be used with Spark and PySpark. We’ll explore the second one.
Steps to use spark-iforest by Fangzhou Yang:
Clone the repositoryBuild the jar (you’ll need Maven for this)
Clone the repository
Build the jar (you’ll need Maven for this)
cd spark-iforest/mvn clean package -DskipTests
3. And either copy it to $SPARK_HOME/jars/ or provide it as extra jar in your spark configuration (I prefer the latter for more flexibility):
cp target/spark-iforest-<version>.jar $SPARK_HOME/jars/
or
conf = SparkConf()conf.set('spark.jars', '/full/path/to/target/spark-iforest-<version>.jar')spark_session = SparkSession.builder.config(conf=conf).appName('IForest').getOrCreate()
4. Install the python version of spark-iforest:
cd spark-iforest/pythonpip install -e . # skip the -e flag if you don't want to edit the project
And we’re ready to use it! Again, it is important to set the random seed to something specific for reproducibility.
In both examples we use a very small and simple dataset, just to demonstrate the process.
data = [ {'feature1': 1., 'feature2': 0., 'feature3': 0.3, 'feature4': 0.01}, {'feature1': 10., 'feature2': 3., 'feature3': 0.9, 'feature4': 0.1}, {'feature1': 101., 'feature2': 13., 'feature3': 0.9, 'feature4': 0.91}, {'feature1': 111., 'feature2': 11., 'feature3': 1.2, 'feature4': 1.91},]
Both implementations of the algorithm conclude that the first sample looks anomalous in comparison to the other three samples, which makes sense if we take a look at the features.
Note the different range of the outputs: [-1, 1] vs [0, 1]
Output of scikit-learn IsolationForest (-1 means anomalous/ outlier, 1 means normal/ inlier)+--------+--------+--------+--------+----------+|feature1|feature2|feature3|feature4|prediction|+--------+--------+--------+--------+----------+| 1.0| 0.0| 0.3| 0.01| -1|| 10.0| 3.0| 0.9| 0.1| 1|| 101.0| 13.0| 0.9| 0.91| 1|| 111.0| 11.0| 1.2| 1.91| 1|+--------+--------+--------+--------+----------+Output of spark-iforest implementation (1.0 means anomalous/ outlier, 0.0 normal/ inlier):+--------+--------+--------+--------+----------+|feature1|feature2|feature3|feature4|prediction|+--------+--------+--------+--------+----------+| 1.0| 0.0| 0.3| 0.01| 1.0|| 10.0| 3.0| 0.9| 0.1| 0.0|| 101.0| 13.0| 0.9| 0.91| 0.0|| 111.0| 11.0| 1.2| 1.91| 0.0|+--------+--------+--------+--------+----------+
It seems that IForest can handle currently only DenseVector input, while VectorAssembler outputs both Dense and Sparse vectors. So, unfortunately, we need to convert the vectors to Dense using a udf.
from pyspark.ml.linalg import Vectors, VectorUDTfrom pyspark.sql import functions as Ffrom pyspark.sql import types as Tlist_to_vector_udf = F.udf(lambda l: Vectors.dense(l), VectorUDT())data.withColumn( 'vectorized_features', list_to_vector_udf('features'))...
Isolation Forest, in my opinion, is a very interesting algorithm, light, scalable, with many applications. It is definitely worth exploring.
For the Pyspark integration:I’ve used the Scikit-learn model quite extensively and while it works well, I’ve found that as the model size increases, so does the time it takes to broadcast the model and complete a prediction cycle. As expected.
I haven’t tested the PySpark ML way enough to be certain that both implementations give the same results, but in the small, meaningless dataset I used in the examples, they seem to agree. I will definitely experiment more with this to investigate how well it scales and how good the outcome is.
I hope this was helpful and that knowing about how to use Isolation Forest in combination with PySpark will save you some time and trouble. Any thoughts, questions, corrections and suggestions are very welcome :)
If you want to know more about how Spark works, take a look at:
towardsdatascience.com
towardsdatascience.com
And if you are coming from the Pandas world and want to get hands on quickly with Spark, check out Koalas:
towardsdatascience.com
Isolation Forest paper: https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf
scikit-learn.org
medium.com
github.com
github.com
Understanding Isolation Forest’s predictions using Shapley Values — Estimating feature importance at scale:
|
[
{
"code": null,
"e": 376,
"s": 171,
"text": "Isolation Forest is an algorithm for anomaly / outlier detection, basically a way to spot the odd one out. We go through the main characteristics and explore two ways to use Isolation Forest with Pyspark."
},
{
"code": null,
"e": 644,
"s": 376,
"text": "Most existing model-based approaches to anomaly detection construct a profile of normal instances, then identify instances that do not conform to the normal profile as anomalies. [...] [Isolation Forest] explicitly isolates anomalies instead of profiles normal points"
},
{
"code": null,
"e": 718,
"s": 644,
"text": "source: https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf"
},
{
"code": null,
"e": 788,
"s": 718,
"text": "Isolation means separating an instance from the rest of the instances"
},
{
"code": null,
"e": 1144,
"s": 788,
"text": "it uses normal samples as the training set and can allow a few instances of abnormal samples (configurable). You basically feed the algorithm your normal data and it doesn’t mind if your dataset is not that well curated, provided you tune the contamination parameter. In other words it learns what normal looks like to be able to distinguish the abnormal,"
},
{
"code": null,
"e": 1230,
"s": 1144,
"text": "it works with the basic assumption that anomalies are few and easily distinguishable,"
},
{
"code": null,
"e": 1314,
"s": 1230,
"text": "it has a linear time complexity with a low constant and a low memory requirements*,"
},
{
"code": null,
"e": 1386,
"s": 1314,
"text": "it is fast because it doesn’t utilize any distance or density measures,"
},
{
"code": null,
"e": 1518,
"s": 1386,
"text": "can scale up very well. It seems to work well with high dimensional problems that may have a large number of irrelevant attributes."
},
{
"code": null,
"e": 1775,
"s": 1518,
"text": "*low memory requirements come from the fact that each tree in the forest does not have to be constructed the wholly, since the anomalies should have a lot shorter paths than the normal instances, so a max depth can be used to cut off the tree construction."
},
{
"code": null,
"e": 1892,
"s": 1775,
"text": "Isolation Forest takes advantage of the two characteristics of anomalies: that they are few and distinct / different"
},
{
"code": null,
"e": 2058,
"s": 1892,
"text": "One way to detect anomalies is to sort data points according to their path lengths or anomaly scores; and anomalies are points that are ranked at the top of the list"
},
{
"code": null,
"e": 2123,
"s": 2058,
"text": "Path length: the number of edges until we reach an external node"
},
{
"code": null,
"e": 2137,
"s": 2123,
"text": "Anomaly Score"
},
{
"code": null,
"e": 2374,
"s": 2137,
"text": "This is basically the output of the algorithm, which is ≤1 and ≥0. This is where the path length come in the picture. With the estimation of the average path length in the whole forest, we can deduce whether a point is anomalous or not."
},
{
"code": null,
"e": 2621,
"s": 2374,
"text": "If the anomaly score for an instance is very close to 1 then it is safe to say that this instance is an anomaly, if it is < 0.5 then it is probably a normal instance and if it is ~= 0.5 then the entire sample does not have any distinct anomalies."
},
{
"code": null,
"e": 2674,
"s": 2621,
"text": "number of trees / estimators : how big is the forest"
},
{
"code": null,
"e": 2767,
"s": 2674,
"text": "contamination: the fraction of the dataset that contains abnormal instances, e.g. 0.1 or 10%"
},
{
"code": null,
"e": 2867,
"s": 2767,
"text": "max samples: The number of samples to draw from the training set to train each Isolation Tree with."
},
{
"code": null,
"e": 2965,
"s": 2867,
"text": "max depth: how deep the tree should be, this can be used to trim the tree and make things faster."
},
{
"code": null,
"e": 3048,
"s": 2965,
"text": "The algorithm learns what normal looks like to be able to distinguish the abnormal"
},
{
"code": null,
"e": 3466,
"s": 3048,
"text": "The Scikit-learn way will need us to create a udf to be able to predict upon a dataframe. This is the usual way in general to utilize a Scikit-learn model. Note that we cannot parallelize the training part using spark — but we can use the parameter n_jobs=-1 to utilize all cores on our machine. Another important thing to remember is to set the random_seed to something specific so that the results are reproducible."
},
{
"code": null,
"e": 3560,
"s": 3466,
"text": "All we need to do is install scikit-learn and its dependenciespip install sklearn numpy scipy"
},
{
"code": null,
"e": 3632,
"s": 3560,
"text": "Then we can start with a simple example, a dataframe with four samples."
},
{
"code": null,
"e": 4022,
"s": 3632,
"text": "There is more than one way to go about this udf, for example you can load the model within the udf from a file (which can potentially cause errors because of the parallelization), or you could pass the serialized model as a column (which will increase your memory consumption by a lot), but I’ve found that the use of broadcast variables works best in terms of time and memory performance."
},
{
"code": null,
"e": 4072,
"s": 4022,
"text": "Let me know if there’s a better way to do this :)"
},
{
"code": null,
"e": 4341,
"s": 4072,
"text": "There is no official package for iForest in the Spark ML library currently. However, I’ve found two implementations, one by LinkedIn which only has the Scala implementation and one by Fangzhou Yang that can be used with Spark and PySpark. We’ll explore the second one."
},
{
"code": null,
"e": 4386,
"s": 4341,
"text": "Steps to use spark-iforest by Fangzhou Yang:"
},
{
"code": null,
"e": 4449,
"s": 4386,
"text": "Clone the repositoryBuild the jar (you’ll need Maven for this)"
},
{
"code": null,
"e": 4470,
"s": 4449,
"text": "Clone the repository"
},
{
"code": null,
"e": 4513,
"s": 4470,
"text": "Build the jar (you’ll need Maven for this)"
},
{
"code": null,
"e": 4560,
"s": 4513,
"text": "cd spark-iforest/mvn clean package -DskipTests"
},
{
"code": null,
"e": 4702,
"s": 4560,
"text": "3. And either copy it to $SPARK_HOME/jars/ or provide it as extra jar in your spark configuration (I prefer the latter for more flexibility):"
},
{
"code": null,
"e": 4758,
"s": 4702,
"text": "cp target/spark-iforest-<version>.jar $SPARK_HOME/jars/"
},
{
"code": null,
"e": 4761,
"s": 4758,
"text": "or"
},
{
"code": null,
"e": 4941,
"s": 4761,
"text": "conf = SparkConf()conf.set('spark.jars', '/full/path/to/target/spark-iforest-<version>.jar')spark_session = SparkSession.builder.config(conf=conf).appName('IForest').getOrCreate()"
},
{
"code": null,
"e": 4989,
"s": 4941,
"text": "4. Install the python version of spark-iforest:"
},
{
"code": null,
"e": 5088,
"s": 4989,
"text": "cd spark-iforest/pythonpip install -e . # skip the -e flag if you don't want to edit the project"
},
{
"code": null,
"e": 5204,
"s": 5088,
"text": "And we’re ready to use it! Again, it is important to set the random seed to something specific for reproducibility."
},
{
"code": null,
"e": 5294,
"s": 5204,
"text": "In both examples we use a very small and simple dataset, just to demonstrate the process."
},
{
"code": null,
"e": 5598,
"s": 5294,
"text": "data = [ {'feature1': 1., 'feature2': 0., 'feature3': 0.3, 'feature4': 0.01}, {'feature1': 10., 'feature2': 3., 'feature3': 0.9, 'feature4': 0.1}, {'feature1': 101., 'feature2': 13., 'feature3': 0.9, 'feature4': 0.91}, {'feature1': 111., 'feature2': 11., 'feature3': 1.2, 'feature4': 1.91},]"
},
{
"code": null,
"e": 5778,
"s": 5598,
"text": "Both implementations of the algorithm conclude that the first sample looks anomalous in comparison to the other three samples, which makes sense if we take a look at the features."
},
{
"code": null,
"e": 5837,
"s": 5778,
"text": "Note the different range of the outputs: [-1, 1] vs [0, 1]"
},
{
"code": null,
"e": 6788,
"s": 5837,
"text": "Output of scikit-learn IsolationForest (-1 means anomalous/ outlier, 1 means normal/ inlier)+--------+--------+--------+--------+----------+|feature1|feature2|feature3|feature4|prediction|+--------+--------+--------+--------+----------+| 1.0| 0.0| 0.3| 0.01| -1|| 10.0| 3.0| 0.9| 0.1| 1|| 101.0| 13.0| 0.9| 0.91| 1|| 111.0| 11.0| 1.2| 1.91| 1|+--------+--------+--------+--------+----------+Output of spark-iforest implementation (1.0 means anomalous/ outlier, 0.0 normal/ inlier):+--------+--------+--------+--------+----------+|feature1|feature2|feature3|feature4|prediction|+--------+--------+--------+--------+----------+| 1.0| 0.0| 0.3| 0.01| 1.0|| 10.0| 3.0| 0.9| 0.1| 0.0|| 101.0| 13.0| 0.9| 0.91| 0.0|| 111.0| 11.0| 1.2| 1.91| 0.0|+--------+--------+--------+--------+----------+"
},
{
"code": null,
"e": 6988,
"s": 6788,
"text": "It seems that IForest can handle currently only DenseVector input, while VectorAssembler outputs both Dense and Sparse vectors. So, unfortunately, we need to convert the vectors to Dense using a udf."
},
{
"code": null,
"e": 7256,
"s": 6988,
"text": "from pyspark.ml.linalg import Vectors, VectorUDTfrom pyspark.sql import functions as Ffrom pyspark.sql import types as Tlist_to_vector_udf = F.udf(lambda l: Vectors.dense(l), VectorUDT())data.withColumn( 'vectorized_features', list_to_vector_udf('features'))..."
},
{
"code": null,
"e": 7397,
"s": 7256,
"text": "Isolation Forest, in my opinion, is a very interesting algorithm, light, scalable, with many applications. It is definitely worth exploring."
},
{
"code": null,
"e": 7641,
"s": 7397,
"text": "For the Pyspark integration:I’ve used the Scikit-learn model quite extensively and while it works well, I’ve found that as the model size increases, so does the time it takes to broadcast the model and complete a prediction cycle. As expected."
},
{
"code": null,
"e": 7936,
"s": 7641,
"text": "I haven’t tested the PySpark ML way enough to be certain that both implementations give the same results, but in the small, meaningless dataset I used in the examples, they seem to agree. I will definitely experiment more with this to investigate how well it scales and how good the outcome is."
},
{
"code": null,
"e": 8149,
"s": 7936,
"text": "I hope this was helpful and that knowing about how to use Isolation Forest in combination with PySpark will save you some time and trouble. Any thoughts, questions, corrections and suggestions are very welcome :)"
},
{
"code": null,
"e": 8213,
"s": 8149,
"text": "If you want to know more about how Spark works, take a look at:"
},
{
"code": null,
"e": 8236,
"s": 8213,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8259,
"s": 8236,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8366,
"s": 8259,
"text": "And if you are coming from the Pandas world and want to get hands on quickly with Spark, check out Koalas:"
},
{
"code": null,
"e": 8389,
"s": 8366,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 8479,
"s": 8389,
"text": "Isolation Forest paper: https://cs.nju.edu.cn/zhouzh/zhouzh.files/publication/icdm08b.pdf"
},
{
"code": null,
"e": 8496,
"s": 8479,
"text": "scikit-learn.org"
},
{
"code": null,
"e": 8507,
"s": 8496,
"text": "medium.com"
},
{
"code": null,
"e": 8518,
"s": 8507,
"text": "github.com"
},
{
"code": null,
"e": 8529,
"s": 8518,
"text": "github.com"
}
] |
MySQL query to return a string as a result of IF statement?
|
Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
EmployeeSalary int
);
Query OK, 0 rows affected (1.68 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(EmployeeSalary) values(12000);
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable(EmployeeSalary) values(20000);
Query OK, 1 row affected (0.55 sec)
mysql> insert into DemoTable(EmployeeSalary) values(11500);
Query OK, 1 row affected (0.94 sec)
mysql> insert into DemoTable(EmployeeSalary) values(15500);
Query OK, 1 row affected (0.44 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+----------------+
| Id | EmployeeSalary |
+----+----------------+
| 1 | 12000 |
| 2 | 20000 |
| 3 | 11500 |
| 4 | 15500 |
+----+----------------+
4 rows in set (0.00 sec)
Following is the query to return a string as a result of IF statement −
mysql> select Id,if(EmployeeSalary <= 12000 ,'Internship Employee','FullTime Employee') as status from DemoTable;
This will produce the following output −
+----+---------------------+
| Id | status |
+----+---------------------+
| 1 | Internship Employee |
| 2 | FullTime Employee |
| 3 | Internship Employee |
| 4 | FullTime Employee |
+----+---------------------+
4 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1233,
"s": 1092,
"text": "mysql> create table DemoTable\n(\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n EmployeeSalary int\n);\nQuery OK, 0 rows affected (1.68 sec)"
},
{
"code": null,
"e": 1289,
"s": 1233,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1673,
"s": 1289,
"text": "mysql> insert into DemoTable(EmployeeSalary) values(12000);\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into DemoTable(EmployeeSalary) values(20000);\nQuery OK, 1 row affected (0.55 sec)\nmysql> insert into DemoTable(EmployeeSalary) values(11500);\nQuery OK, 1 row affected (0.94 sec)\nmysql> insert into DemoTable(EmployeeSalary) values(15500);\nQuery OK, 1 row affected (0.44 sec)"
},
{
"code": null,
"e": 1733,
"s": 1673,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1764,
"s": 1733,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1805,
"s": 1764,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2022,
"s": 1805,
"text": "+----+----------------+\n| Id | EmployeeSalary |\n+----+----------------+\n| 1 | 12000 |\n| 2 | 20000 |\n| 3 | 11500 |\n| 4 | 15500 |\n+----+----------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2094,
"s": 2022,
"text": "Following is the query to return a string as a result of IF statement −"
},
{
"code": null,
"e": 2208,
"s": 2094,
"text": "mysql> select Id,if(EmployeeSalary <= 12000 ,'Internship Employee','FullTime Employee') as status from DemoTable;"
},
{
"code": null,
"e": 2249,
"s": 2208,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2506,
"s": 2249,
"text": "+----+---------------------+\n| Id | status |\n+----+---------------------+\n| 1 | Internship Employee |\n| 2 | FullTime Employee |\n| 3 | Internship Employee |\n| 4 | FullTime Employee |\n+----+---------------------+\n4 rows in set (0.00 sec)"
}
] |
How to create a mega menu (full-width dropdown menu in a navigation bar) with HTML and CSS?
|
Following is the code to create a mega menu using HTML and CSS −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
body {
margin: 0;
padding: 0;
}
*,*::before,*::after{
box-sizing: border-box;
}
nav {
overflow: hidden;
background-color: rgb(2, 161, 127);
font-family: Arial, Helvetica, sans-serif;
}
nav a {
float: left;
font-size: 16px;
color: white;
text-align: center;
padding: 14px 16px;
text-decoration: none;
}
.dropdown {
float: left;
overflow: hidden;
}
.dropdown .megaButton {
font-size: 16px;
border: none;
outline: none;
color: white;
padding: 14px 16px;
background-color: inherit;
font: inherit;
margin: 0;
}
nav a:hover, .dropdown:hover .megaButton {
background-color: rgb(0, 63, 146);
}
.megaContent {
text-align: center;
display: none;
position: absolute;
background-color: #f9f9f9;
width: 100%;
left: 0;
z-index: 1;
}
.megaContent .megaHeader {
background: rgb(119, 6, 194);
padding: 16px;
color: white;
}
.dropdown:hover .megaContent {
display: block;
}
.megaColumn {
float: left;
width: 50%;
padding: 10px;
background-color: rgb(233, 255, 198);
height: 250px;
}
.megaColumn .links {
color: black;
padding: 16px;
margin:10px;
text-decoration: none;
display: block;
text-align: left;
border-bottom: 4px solid rgb(69, 0, 90);
}
.megaColumn a:hover {
background-color: lightblue;
}
/*Float reset trick for clearing floats*/
.megaRow:after {
content: "";
display: table;
clear: both;
}
</style>
</head>
<body>
<nav>
<a class="links" href="#">Home</a>
<a class="links" href="#">About</a>
<a class="links" href="#">Contact Us</a>
<a class="links" href="#">More Info</a>
<div class="dropdown">
<button class="megaButton">Projects ></button>
<div class="megaContent">
<div class="megaHeader">
<h2>Projects Menu</h2>
</div>
<div class="megaRow">
<div class="megaColumn">
<h3>Commercial</h3>
<a class="links" href="#">Project 1</a>
<a class="links" href="#">Project 2</a>
</div>
<div class="megaColumn">
<h3>Non-Commerial</h3>
<a class="links" href="#">Project 1</a>
<a class="links" href="#">Project 2</a>
</div>
</div>
</div>
</div>
</nav>
</body>
</html>
The above code will produce the following output −
On hovering over the Project dropdown button −
|
[
{
"code": null,
"e": 1127,
"s": 1062,
"text": "Following is the code to create a mega menu using HTML and CSS −"
},
{
"code": null,
"e": 1138,
"s": 1127,
"text": " Live Demo"
},
{
"code": null,
"e": 3276,
"s": 1138,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nbody {\n margin: 0;\n padding: 0;\n}\n*,*::before,*::after{\n box-sizing: border-box;\n}\nnav {\n overflow: hidden;\n background-color: rgb(2, 161, 127);\n font-family: Arial, Helvetica, sans-serif;\n}\nnav a {\n float: left;\n font-size: 16px;\n color: white;\n text-align: center;\n padding: 14px 16px;\n text-decoration: none;\n}\n.dropdown {\n float: left;\n overflow: hidden;\n}\n.dropdown .megaButton {\n font-size: 16px;\n border: none;\n outline: none;\n color: white;\n padding: 14px 16px;\n background-color: inherit;\n font: inherit;\n margin: 0;\n}\nnav a:hover, .dropdown:hover .megaButton {\n background-color: rgb(0, 63, 146);\n}\n.megaContent {\n text-align: center;\n display: none;\n position: absolute;\n background-color: #f9f9f9;\n width: 100%;\n left: 0;\n z-index: 1;\n}\n.megaContent .megaHeader {\n background: rgb(119, 6, 194);\n padding: 16px;\n color: white;\n}\n.dropdown:hover .megaContent {\n display: block;\n}\n.megaColumn {\n float: left;\n width: 50%;\n padding: 10px;\n background-color: rgb(233, 255, 198);\n height: 250px;\n}\n.megaColumn .links {\n color: black;\n padding: 16px;\n margin:10px;\n text-decoration: none;\n display: block;\n text-align: left;\n border-bottom: 4px solid rgb(69, 0, 90);\n}\n.megaColumn a:hover {\n background-color: lightblue;\n}\n/*Float reset trick for clearing floats*/\n.megaRow:after {\n content: \"\";\n display: table;\n clear: both;\n}\n</style>\n</head>\n<body>\n<nav>\n<a class=\"links\" href=\"#\">Home</a>\n<a class=\"links\" href=\"#\">About</a>\n<a class=\"links\" href=\"#\">Contact Us</a>\n<a class=\"links\" href=\"#\">More Info</a>\n<div class=\"dropdown\">\n<button class=\"megaButton\">Projects ></button>\n<div class=\"megaContent\">\n<div class=\"megaHeader\">\n<h2>Projects Menu</h2>\n</div>\n<div class=\"megaRow\">\n<div class=\"megaColumn\">\n<h3>Commercial</h3>\n<a class=\"links\" href=\"#\">Project 1</a>\n<a class=\"links\" href=\"#\">Project 2</a>\n</div>\n<div class=\"megaColumn\">\n<h3>Non-Commerial</h3>\n<a class=\"links\" href=\"#\">Project 1</a>\n<a class=\"links\" href=\"#\">Project 2</a>\n</div>\n</div>\n</div>\n</div>\n</nav>\n</body>\n</html>"
},
{
"code": null,
"e": 3327,
"s": 3276,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 3374,
"s": 3327,
"text": "On hovering over the Project dropdown button −"
}
] |
Elasticsearch - SQL Access
|
It is a component that allows SQL-like queries to be executed in real-time against Elasticsearch. You can think of Elasticsearch SQL as a translator, one that understands both SQL and Elasticsearch and makes it easy to read and process data in real-time, at scale by leveraging Elasticsearch capabilities.
It has native integration − Each and every query is efficiently executed against the relevant nodes according to the underlying storage.
It has native integration − Each and every query is efficiently executed against the relevant nodes according to the underlying storage.
No external parts − No need for additional hardware, processes, runtimes or
libraries to query Elasticsearch.
No external parts − No need for additional hardware, processes, runtimes or
libraries to query Elasticsearch.
Lightweight and efficient − it embraces and exposes SQL to allow proper full-text search, in real-time.
Lightweight and efficient − it embraces and exposes SQL to allow proper full-text search, in real-time.
PUT /schoollist/_bulk?refresh
{"index":{"_id": "CBSE"}}
{"name": "GleanDale", "Address": "JR. Court Lane", "start_date": "2011-06-02",
"student_count": 561}
{"index":{"_id": "ICSE"}}
{"name": "Top-Notch", "Address": "Gachibowli Main Road", "start_date": "1989-
05-26", "student_count": 482}
{"index":{"_id": "State Board"}}
{"name": "Sunshine", "Address": "Main Street", "start_date": "1965-06-01",
"student_count": 604}
On running the above code, we get the response as shown below −
{
"took" : 277,
"errors" : false,
"items" : [
{
"index" : {
"_index" : "schoollist",
"_type" : "_doc",
"_id" : "CBSE",
"_version" : 1,
"result" : "created",
"forced_refresh" : true,
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 0,
"_primary_term" : 1,
"status" : 201
}
},
{
"index" : {
"_index" : "schoollist",
"_type" : "_doc",
"_id" : "ICSE",
"_version" : 1,
"result" : "created",
"forced_refresh" : true,
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 1,
"_primary_term" : 1,
"status" : 201
}
},
{
"index" : {
"_index" : "schoollist",
"_type" : "_doc",
"_id" : "State Board",
"_version" : 1,
"result" : "created",
"forced_refresh" : true,
"_shards" : {
"total" : 2,
"successful" : 1,
"failed" : 0
},
"_seq_no" : 2,
"_primary_term" : 1,
"status" : 201
}
}
]
}
The following example shows how we frame the SQL query −
POST /_sql?format=txt
{
"query": "SELECT * FROM schoollist WHERE start_date < '2000-01-01'"
}
On running the above code, we get the response as shown below −
Address | name | start_date | student_count
--------------------+---------------+------------------------+---------------
Gachibowli Main Road|Top-Notch |1989-05-26T00:00:00.000Z|482
Main Street |Sunshine |1965-06-01T00:00:00.000Z|604
Note − By changing the SQL query above, you can get different result sets.
14 Lectures
5 hours
Manuj Aggarwal
20 Lectures
1 hours
Faizan Tayyab
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2887,
"s": 2581,
"text": "It is a component that allows SQL-like queries to be executed in real-time against Elasticsearch. You can think of Elasticsearch SQL as a translator, one that understands both SQL and Elasticsearch and makes it easy to read and process data in real-time, at scale by leveraging Elasticsearch capabilities."
},
{
"code": null,
"e": 3024,
"s": 2887,
"text": "It has native integration − Each and every query is efficiently executed against the relevant nodes according to the underlying storage."
},
{
"code": null,
"e": 3161,
"s": 3024,
"text": "It has native integration − Each and every query is efficiently executed against the relevant nodes according to the underlying storage."
},
{
"code": null,
"e": 3271,
"s": 3161,
"text": "No external parts − No need for additional hardware, processes, runtimes or\nlibraries to query Elasticsearch."
},
{
"code": null,
"e": 3381,
"s": 3271,
"text": "No external parts − No need for additional hardware, processes, runtimes or\nlibraries to query Elasticsearch."
},
{
"code": null,
"e": 3485,
"s": 3381,
"text": "Lightweight and efficient − it embraces and exposes SQL to allow proper full-text search, in real-time."
},
{
"code": null,
"e": 3589,
"s": 3485,
"text": "Lightweight and efficient − it embraces and exposes SQL to allow proper full-text search, in real-time."
},
{
"code": null,
"e": 4037,
"s": 3589,
"text": "PUT /schoollist/_bulk?refresh\n {\"index\":{\"_id\": \"CBSE\"}}\n {\"name\": \"GleanDale\", \"Address\": \"JR. Court Lane\", \"start_date\": \"2011-06-02\",\n \"student_count\": 561}\n {\"index\":{\"_id\": \"ICSE\"}}\n {\"name\": \"Top-Notch\", \"Address\": \"Gachibowli Main Road\", \"start_date\": \"1989-\n 05-26\", \"student_count\": 482}\n {\"index\":{\"_id\": \"State Board\"}}\n {\"name\": \"Sunshine\", \"Address\": \"Main Street\", \"start_date\": \"1965-06-01\",\n \"student_count\": 604}"
},
{
"code": null,
"e": 4101,
"s": 4037,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 5550,
"s": 4101,
"text": "{\n \"took\" : 277,\n \"errors\" : false,\n \"items\" : [\n {\n \"index\" : {\n \"_index\" : \"schoollist\",\n \"_type\" : \"_doc\",\n \"_id\" : \"CBSE\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"forced_refresh\" : true,\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 0,\n \"_primary_term\" : 1,\n \"status\" : 201\n }\n },\n {\n \"index\" : {\n \"_index\" : \"schoollist\",\n \"_type\" : \"_doc\",\n \"_id\" : \"ICSE\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"forced_refresh\" : true,\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 1,\n \"_primary_term\" : 1,\n \"status\" : 201\n }\n },\n {\n \"index\" : {\n \"_index\" : \"schoollist\",\n \"_type\" : \"_doc\",\n \"_id\" : \"State Board\",\n \"_version\" : 1,\n \"result\" : \"created\",\n \"forced_refresh\" : true,\n \"_shards\" : {\n \"total\" : 2,\n \"successful\" : 1,\n \"failed\" : 0\n },\n \"_seq_no\" : 2,\n \"_primary_term\" : 1,\n \"status\" : 201\n }\n }\n ]\n}\n"
},
{
"code": null,
"e": 5607,
"s": 5550,
"text": "The following example shows how we frame the SQL query −"
},
{
"code": null,
"e": 5705,
"s": 5607,
"text": "POST /_sql?format=txt\n{\n \"query\": \"SELECT * FROM schoollist WHERE start_date < '2000-01-01'\"\n}\n"
},
{
"code": null,
"e": 5769,
"s": 5705,
"text": "On running the above code, we get the response as shown below −"
},
{
"code": null,
"e": 6057,
"s": 5769,
"text": "Address | name | start_date | student_count\n--------------------+---------------+------------------------+---------------\nGachibowli Main Road|Top-Notch |1989-05-26T00:00:00.000Z|482\nMain Street |Sunshine |1965-06-01T00:00:00.000Z|604\n"
},
{
"code": null,
"e": 6132,
"s": 6057,
"text": "Note − By changing the SQL query above, you can get different result sets."
},
{
"code": null,
"e": 6165,
"s": 6132,
"text": "\n 14 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6181,
"s": 6165,
"text": " Manuj Aggarwal"
},
{
"code": null,
"e": 6214,
"s": 6181,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6229,
"s": 6214,
"text": " Faizan Tayyab"
},
{
"code": null,
"e": 6236,
"s": 6229,
"text": " Print"
},
{
"code": null,
"e": 6247,
"s": 6236,
"text": " Add Notes"
}
] |
Deep Learning with Tensorflow: Part 1 — theory and setup | by Matteo Kofler | Towards Data Science
|
Hi everyone, welcome to this blog series about Tensorflow. In part 1, I’ll give you some basic information about the framework and I’ll show you how to set up your coding environment on Windows 10. Let’s dive into it.
TensorFlow is a framework created by Google for creating Deep Learning models. Deep Learning is a category of machine learning models (=algorithms) that use multi-layer neural networks.
Machine Learning has enabled us to build complex applications with great accuracy. Whether it has to do with images, videos, text or even audio, Machine Learning can solve problems from a wide range. Tensorflow can be used to achieve all of these applications.
The reason for its popularity is the ease with which developers can build and deploy applications. The GitHub projects which we’ll look closer at due the next parts are very powerful but also so easy to work with. Moreover, Tensorflow was created with processing power limitations in mind. The library can be ran on computers of all kinds, even on smartphones (yes, even on that overpriced thing with half an apple on it). I can guarantee you, working on a Intel Core i3 with 8 GB of RAM, you won’t have performance issues.
The human brain consists of billions of neurons which are interconnected by synapses. If “enough” synaptic inputs to the neuron fires, then the neuron will also fire. This process is called thinking. To replicate that process on computers, we need machine learning and neural networks. In case you aren’t that settled on this terms, I’ll explain them.
Quite simply, machine learning allows computers to ‘learn’. Traditionally, we always got computers to do things by providing a strict set of instructions. Machine Learning uses a very different approach. Instead of giving the computer a set of instructions on how to do something, we give it instructions on how to learn to do something. For example: think of a system that can classify pictures of animals as ‘cat’, ‘dog’, or ‘mouse’. Instead of manually finding unique characteristics from images of those animals and then coding it up, machine learning takes in images of those animals and finds characteristics and differences by itself. This process of teaching the computer is referred to as training.
Deep learning is a Technique for implementing Machine Learning. It uses neural networks to learn, sometimes, using decision trees may also be referred to as deep learning, but for the most part deep learning involves the use of neural networks.
So, what is a neural network? Here’s an analogy: imagine a neural network as a series of doors one after another and think of yourself as the ‘input’ to the neural network. Every time you open a door, you become a different person. By the time you open the last door, you have become a very different person. When you exit through the last door, you become the ‘output’ of the neural network. Each door, in this case, represents a layer. A neural network, therefore, is a collection of layers that transform the input in some way to produce an output.
If you want to know more, give the following article a try:https://medium.com/towards-data-science/tensorflow-for-absolute-beginners-28c1544fb0d6
This manual is meant for Tensorflow 1.2.1 with Python 3.6. Before following it, you might also want to take a look at the official installation guide.
Tensorflow programs are written in Python, which you can download at https://www.python.org/downloads/
You can choose between Python 3 and Python 2, but I would highly recommend you to install a version newer as 3.5, simply because these versions already come with a integrated PIP-Package. Otherwise, you have to install that as well.
The next step is to install Python. Open a command line as administrator(!), and write the following line:
pip3 install --upgrade tensorflow
If you want to test the installation, write this:
python >>> import tensorflow as tf>>> hello = tf.constant('Hello, Tensorflow')>>> sess = tf.Session()>>> print(sess.run(hello))
You should see a “Hello, Tensorflow” output now.
Congratulations! You just learned the theoretical basics of Tensorflow and set up everything to dig in deeper in the matter. The next part will be about image processing and recognition with Inception. So stay tuned till next time!
__
Link to Part 2: https://medium.com/@m_ko/deep-learning-with-tensorflow-part-2-image-classification-58fcdffa7b84
|
[
{
"code": null,
"e": 389,
"s": 171,
"text": "Hi everyone, welcome to this blog series about Tensorflow. In part 1, I’ll give you some basic information about the framework and I’ll show you how to set up your coding environment on Windows 10. Let’s dive into it."
},
{
"code": null,
"e": 575,
"s": 389,
"text": "TensorFlow is a framework created by Google for creating Deep Learning models. Deep Learning is a category of machine learning models (=algorithms) that use multi-layer neural networks."
},
{
"code": null,
"e": 836,
"s": 575,
"text": "Machine Learning has enabled us to build complex applications with great accuracy. Whether it has to do with images, videos, text or even audio, Machine Learning can solve problems from a wide range. Tensorflow can be used to achieve all of these applications."
},
{
"code": null,
"e": 1360,
"s": 836,
"text": "The reason for its popularity is the ease with which developers can build and deploy applications. The GitHub projects which we’ll look closer at due the next parts are very powerful but also so easy to work with. Moreover, Tensorflow was created with processing power limitations in mind. The library can be ran on computers of all kinds, even on smartphones (yes, even on that overpriced thing with half an apple on it). I can guarantee you, working on a Intel Core i3 with 8 GB of RAM, you won’t have performance issues."
},
{
"code": null,
"e": 1712,
"s": 1360,
"text": "The human brain consists of billions of neurons which are interconnected by synapses. If “enough” synaptic inputs to the neuron fires, then the neuron will also fire. This process is called thinking. To replicate that process on computers, we need machine learning and neural networks. In case you aren’t that settled on this terms, I’ll explain them."
},
{
"code": null,
"e": 2420,
"s": 1712,
"text": "Quite simply, machine learning allows computers to ‘learn’. Traditionally, we always got computers to do things by providing a strict set of instructions. Machine Learning uses a very different approach. Instead of giving the computer a set of instructions on how to do something, we give it instructions on how to learn to do something. For example: think of a system that can classify pictures of animals as ‘cat’, ‘dog’, or ‘mouse’. Instead of manually finding unique characteristics from images of those animals and then coding it up, machine learning takes in images of those animals and finds characteristics and differences by itself. This process of teaching the computer is referred to as training."
},
{
"code": null,
"e": 2665,
"s": 2420,
"text": "Deep learning is a Technique for implementing Machine Learning. It uses neural networks to learn, sometimes, using decision trees may also be referred to as deep learning, but for the most part deep learning involves the use of neural networks."
},
{
"code": null,
"e": 3217,
"s": 2665,
"text": "So, what is a neural network? Here’s an analogy: imagine a neural network as a series of doors one after another and think of yourself as the ‘input’ to the neural network. Every time you open a door, you become a different person. By the time you open the last door, you have become a very different person. When you exit through the last door, you become the ‘output’ of the neural network. Each door, in this case, represents a layer. A neural network, therefore, is a collection of layers that transform the input in some way to produce an output."
},
{
"code": null,
"e": 3363,
"s": 3217,
"text": "If you want to know more, give the following article a try:https://medium.com/towards-data-science/tensorflow-for-absolute-beginners-28c1544fb0d6"
},
{
"code": null,
"e": 3514,
"s": 3363,
"text": "This manual is meant for Tensorflow 1.2.1 with Python 3.6. Before following it, you might also want to take a look at the official installation guide."
},
{
"code": null,
"e": 3617,
"s": 3514,
"text": "Tensorflow programs are written in Python, which you can download at https://www.python.org/downloads/"
},
{
"code": null,
"e": 3850,
"s": 3617,
"text": "You can choose between Python 3 and Python 2, but I would highly recommend you to install a version newer as 3.5, simply because these versions already come with a integrated PIP-Package. Otherwise, you have to install that as well."
},
{
"code": null,
"e": 3957,
"s": 3850,
"text": "The next step is to install Python. Open a command line as administrator(!), and write the following line:"
},
{
"code": null,
"e": 3991,
"s": 3957,
"text": "pip3 install --upgrade tensorflow"
},
{
"code": null,
"e": 4041,
"s": 3991,
"text": "If you want to test the installation, write this:"
},
{
"code": null,
"e": 4169,
"s": 4041,
"text": "python >>> import tensorflow as tf>>> hello = tf.constant('Hello, Tensorflow')>>> sess = tf.Session()>>> print(sess.run(hello))"
},
{
"code": null,
"e": 4218,
"s": 4169,
"text": "You should see a “Hello, Tensorflow” output now."
},
{
"code": null,
"e": 4450,
"s": 4218,
"text": "Congratulations! You just learned the theoretical basics of Tensorflow and set up everything to dig in deeper in the matter. The next part will be about image processing and recognition with Inception. So stay tuned till next time!"
},
{
"code": null,
"e": 4453,
"s": 4450,
"text": "__"
}
] |
Count of Range Sum in C++
|
Suppose we have an integer array nums, we have to find the number of range sums that lie in range [lower, upper] both inclusive. The range sum S(i, j) is defined as the sum of the elements in nums from index i to index j where i ≤ j.
So if the input is like [-3,6,-1], lower = -2 and upper = 2, then the result will be 2, as the ranges are [0,2], the sum is 2, [2,2], sum is -2.
To solve this, we will follow these steps −
Define a function mergeIt(), this will take array prefix, start, mid, end, lower, upper,
i := start, j := mid + 1
temp := end - start + 1
low := mid + 1, high := mid + 1
k := 0
Define an array arr of size: temp.
while i <= mid, do −while (low <= end and prefix[low] - prefix[i] < lower), do −increase low by 1while (high <= end and prefix[high] - prefix[i] <= upper), do −increase high by 1while (j <= end and prefix[j] < prefix[i]), do −arr[k] := prefix[j](increase j by 1)(increase k by 1)arr[k] := prefix[i](increase i by 1)(increase k by 1)count := count + high - low
while (low <= end and prefix[low] - prefix[i] < lower), do −increase low by 1
increase low by 1
while (high <= end and prefix[high] - prefix[i] <= upper), do −increase high by 1
increase high by 1
while (j <= end and prefix[j] < prefix[i]), do −arr[k] := prefix[j](increase j by 1)(increase k by 1)
arr[k] := prefix[j]
(increase j by 1)
(increase k by 1)
arr[k] := prefix[i]
(increase i by 1)
(increase k by 1)
count := count + high - low
while j <= end, do −arr[k] := prefix[j](increase k by 1)(increase j by 1)
arr[k] := prefix[j]
(increase k by 1)
(increase j by 1)
for initialize i := 0, when i < temp, update (increase i by 1), do −prefix[start] := arr[i](increase start by 1)
prefix[start] := arr[i]
(increase start by 1)
Define a function merge(), this will take prefix[], start, end, lower, upper,if start >= end, then return
if start >= end, then return
mid := start + (end - start)
call the function merge(prefix, start, mid, lower, upper)
call the function merge(prefix, mid + 1, end, lower, upper)
call the function mergeIt(prefix, start, mid, end, lower, upper)
From the main method, do the following −
n := size of nums
count := 0
Define an array prefix of size: n+1.
prefix[0] := 0
for initialize i := 1, when i <= n, update (increase i by 1), do −prefix[i] := prefix[i - 1] + nums[i - 1]
prefix[i] := prefix[i - 1] + nums[i - 1]
call the function merge(prefix, 0, n, lower, upper)
return count
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
typedef long long int lli;
class Solution {
public:
int count = 0;
void mergeIt(lli prefix[], lli start ,lli mid, lli end, lli lower, lli upper){
lli i = start, j = mid + 1;
lli temp = end - start + 1;
lli low = mid + 1, high = mid + 1;
lli k = 0;
lli arr[temp];
while(i <= mid){
while(low <= end && prefix[low] - prefix[i] < lower) low++;
while(high <= end && prefix[high] - prefix[i] <= upper) high++;
while(j<= end && prefix[j] < prefix[i]){
arr[k] = prefix[j];
j++;
k++;
}
arr[k] = prefix[i];
i++;
k++;
count += high - low;
}
while(j <= end){
arr[k] = prefix[j];
k++;
j++;
}
for(i = 0; i < temp; i++){
prefix[start] = arr[i];
start++;
}
}
void merge(lli prefix[], lli start, lli end, lli lower, lli upper){
if(start >= end)return;
lli mid = start + (end - start) / 2;
merge(prefix, start, mid, lower, upper);
merge(prefix, mid + 1, end, lower, upper);
mergeIt(prefix, start, mid, end, lower, upper);
}
int countRangeSum(vector<int>& nums, int lower, int upper) {
lli n = nums.size();
count = 0;
lli prefix[n + 1];
prefix[0] = 0;
for(lli i = 1; i <= n; i++){
prefix[i] = prefix[i - 1] + nums[i - 1];
}
merge(prefix, 0, n, lower, upper);
return count;
}
};
main(){
Solution ob;
vector<int> v = {-3,6,-1};
cout << (ob.countRangeSum(v, -2, 2));
}
{-3,6,-1}
-2
2
2
|
[
{
"code": null,
"e": 1296,
"s": 1062,
"text": "Suppose we have an integer array nums, we have to find the number of range sums that lie in range [lower, upper] both inclusive. The range sum S(i, j) is defined as the sum of the elements in nums from index i to index j where i ≤ j."
},
{
"code": null,
"e": 1441,
"s": 1296,
"text": "So if the input is like [-3,6,-1], lower = -2 and upper = 2, then the result will be 2, as the ranges are [0,2], the sum is 2, [2,2], sum is -2."
},
{
"code": null,
"e": 1485,
"s": 1441,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1574,
"s": 1485,
"text": "Define a function mergeIt(), this will take array prefix, start, mid, end, lower, upper,"
},
{
"code": null,
"e": 1599,
"s": 1574,
"text": "i := start, j := mid + 1"
},
{
"code": null,
"e": 1623,
"s": 1599,
"text": "temp := end - start + 1"
},
{
"code": null,
"e": 1655,
"s": 1623,
"text": "low := mid + 1, high := mid + 1"
},
{
"code": null,
"e": 1662,
"s": 1655,
"text": "k := 0"
},
{
"code": null,
"e": 1697,
"s": 1662,
"text": "Define an array arr of size: temp."
},
{
"code": null,
"e": 2057,
"s": 1697,
"text": "while i <= mid, do −while (low <= end and prefix[low] - prefix[i] < lower), do −increase low by 1while (high <= end and prefix[high] - prefix[i] <= upper), do −increase high by 1while (j <= end and prefix[j] < prefix[i]), do −arr[k] := prefix[j](increase j by 1)(increase k by 1)arr[k] := prefix[i](increase i by 1)(increase k by 1)count := count + high - low"
},
{
"code": null,
"e": 2135,
"s": 2057,
"text": "while (low <= end and prefix[low] - prefix[i] < lower), do −increase low by 1"
},
{
"code": null,
"e": 2153,
"s": 2135,
"text": "increase low by 1"
},
{
"code": null,
"e": 2235,
"s": 2153,
"text": "while (high <= end and prefix[high] - prefix[i] <= upper), do −increase high by 1"
},
{
"code": null,
"e": 2254,
"s": 2235,
"text": "increase high by 1"
},
{
"code": null,
"e": 2356,
"s": 2254,
"text": "while (j <= end and prefix[j] < prefix[i]), do −arr[k] := prefix[j](increase j by 1)(increase k by 1)"
},
{
"code": null,
"e": 2376,
"s": 2356,
"text": "arr[k] := prefix[j]"
},
{
"code": null,
"e": 2394,
"s": 2376,
"text": "(increase j by 1)"
},
{
"code": null,
"e": 2412,
"s": 2394,
"text": "(increase k by 1)"
},
{
"code": null,
"e": 2432,
"s": 2412,
"text": "arr[k] := prefix[i]"
},
{
"code": null,
"e": 2450,
"s": 2432,
"text": "(increase i by 1)"
},
{
"code": null,
"e": 2468,
"s": 2450,
"text": "(increase k by 1)"
},
{
"code": null,
"e": 2496,
"s": 2468,
"text": "count := count + high - low"
},
{
"code": null,
"e": 2570,
"s": 2496,
"text": "while j <= end, do −arr[k] := prefix[j](increase k by 1)(increase j by 1)"
},
{
"code": null,
"e": 2590,
"s": 2570,
"text": "arr[k] := prefix[j]"
},
{
"code": null,
"e": 2608,
"s": 2590,
"text": "(increase k by 1)"
},
{
"code": null,
"e": 2626,
"s": 2608,
"text": "(increase j by 1)"
},
{
"code": null,
"e": 2739,
"s": 2626,
"text": "for initialize i := 0, when i < temp, update (increase i by 1), do −prefix[start] := arr[i](increase start by 1)"
},
{
"code": null,
"e": 2763,
"s": 2739,
"text": "prefix[start] := arr[i]"
},
{
"code": null,
"e": 2785,
"s": 2763,
"text": "(increase start by 1)"
},
{
"code": null,
"e": 2891,
"s": 2785,
"text": "Define a function merge(), this will take prefix[], start, end, lower, upper,if start >= end, then return"
},
{
"code": null,
"e": 2920,
"s": 2891,
"text": "if start >= end, then return"
},
{
"code": null,
"e": 2949,
"s": 2920,
"text": "mid := start + (end - start)"
},
{
"code": null,
"e": 3007,
"s": 2949,
"text": "call the function merge(prefix, start, mid, lower, upper)"
},
{
"code": null,
"e": 3067,
"s": 3007,
"text": "call the function merge(prefix, mid + 1, end, lower, upper)"
},
{
"code": null,
"e": 3132,
"s": 3067,
"text": "call the function mergeIt(prefix, start, mid, end, lower, upper)"
},
{
"code": null,
"e": 3173,
"s": 3132,
"text": "From the main method, do the following −"
},
{
"code": null,
"e": 3191,
"s": 3173,
"text": "n := size of nums"
},
{
"code": null,
"e": 3202,
"s": 3191,
"text": "count := 0"
},
{
"code": null,
"e": 3239,
"s": 3202,
"text": "Define an array prefix of size: n+1."
},
{
"code": null,
"e": 3254,
"s": 3239,
"text": "prefix[0] := 0"
},
{
"code": null,
"e": 3361,
"s": 3254,
"text": "for initialize i := 1, when i <= n, update (increase i by 1), do −prefix[i] := prefix[i - 1] + nums[i - 1]"
},
{
"code": null,
"e": 3402,
"s": 3361,
"text": "prefix[i] := prefix[i - 1] + nums[i - 1]"
},
{
"code": null,
"e": 3454,
"s": 3402,
"text": "call the function merge(prefix, 0, n, lower, upper)"
},
{
"code": null,
"e": 3467,
"s": 3454,
"text": "return count"
},
{
"code": null,
"e": 3537,
"s": 3467,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 3548,
"s": 3537,
"text": " Live Demo"
},
{
"code": null,
"e": 5177,
"s": 3548,
"text": "#include <bits/stdc++.h>\nusing namespace std;\ntypedef long long int lli;\nclass Solution {\npublic:\n int count = 0;\n void mergeIt(lli prefix[], lli start ,lli mid, lli end, lli lower, lli upper){\n lli i = start, j = mid + 1;\n lli temp = end - start + 1;\n lli low = mid + 1, high = mid + 1;\n lli k = 0;\n lli arr[temp];\n while(i <= mid){\n while(low <= end && prefix[low] - prefix[i] < lower) low++;\n while(high <= end && prefix[high] - prefix[i] <= upper) high++;\n while(j<= end && prefix[j] < prefix[i]){\n arr[k] = prefix[j];\n j++;\n k++;\n }\n arr[k] = prefix[i];\n i++;\n k++;\n count += high - low;\n }\n while(j <= end){\n arr[k] = prefix[j];\n k++;\n j++;\n }\n for(i = 0; i < temp; i++){\n prefix[start] = arr[i];\n start++;\n }\n }\n void merge(lli prefix[], lli start, lli end, lli lower, lli upper){\n if(start >= end)return;\n lli mid = start + (end - start) / 2;\n merge(prefix, start, mid, lower, upper);\n merge(prefix, mid + 1, end, lower, upper);\n mergeIt(prefix, start, mid, end, lower, upper);\n }\n int countRangeSum(vector<int>& nums, int lower, int upper) {\n lli n = nums.size();\n count = 0;\n lli prefix[n + 1];\n prefix[0] = 0;\n for(lli i = 1; i <= n; i++){\n prefix[i] = prefix[i - 1] + nums[i - 1];\n }\n merge(prefix, 0, n, lower, upper);\n return count;\n }\n};\nmain(){\n Solution ob;\n vector<int> v = {-3,6,-1};\n cout << (ob.countRangeSum(v, -2, 2));\n}"
},
{
"code": null,
"e": 5192,
"s": 5177,
"text": "{-3,6,-1}\n-2\n2"
},
{
"code": null,
"e": 5194,
"s": 5192,
"text": "2"
}
] |
Snowflake S3 integration. Access files stored in S3 as a regular... | by Amit Singh Rathore | Towards Data Science
|
Snowflake integration objects enable us to connect with external systems from Snowflake. In my last blog, we went through how to create an API integration to invoke an AWS Lambda. In this blog, we will see how we can integrate AWS S3 so that we can access data stored and query it in snowflake.
For snowflake to be able to talk to our AWS account we need to add cross account role. This role will be assumed by an IAM identity in Snowflake account and perform actions in our AWS Account.
Create a cross-account IAM Role in your AWS account. Put a dummy account and we will update the trust policy later.
Attach an inline policy to the role created above.
Version: '2012-10-17'Statement:- Effect: Allow Action: - s3:GetObject - s3:GetObjectVersion Resource: arn:aws:s3:::my-snowflake-data-bucket/dev/gold/*- Effect: Allow Action: s3:ListBucket Resource: arn:aws:s3:::my-snowflake-data-bucket
The above policy allows the role to access S3 bucket under a prefix. As a security practice only add minimum access needed by snowflake.
Create a Storage integration object
create or replace storage integration my_s3_int_01 type = external_stage storage_provider = s3 enabled = true storage_aws_role_arn = '<IAM_ROLE_ARN>' storage_allowed_locations = ('s3://my-snowflake-data-bucket/dev/gold/');
The above command when run in snowflake creates an S3 integration object. This object creates the IAM identity in snowflake account. All API action in AWS account will be performed by this user by assuming the role we mentioned in the storage_aws_role_arn.
As mentioned, the integration object creates a user and external identity. We need those to add trust relationship between AWS and Snowflake account. To get that we describe the integration object just created and note down the values of STORAGE_AWS_IAM_USER_ARN & STORAGE_AWS_EXTERNAL_ID
describe integration my_s3_int_01;
OUTPUT:
Once we have the user & external identity we Update the trust relationship of the role created in 1st step. Add the value of STORAGE_AWS_IAM_USER_ARN in Principal & STORAGE_AWS_EXTERNAL_ID under condition
Version: '2012-10-17'Statement:- Effect: Allow Principal: AWS: "<STORAGE_AWS_IAM_USER_ARN>" Action: sts:AssumeRole Condition: ForAnyValue:StringLike: sts:ExternalId: - "<STORAGE_AWS_EXTERNAL_ID>"
We need to tell snowflake of any special formatting we are having in the files which are stored in the S3 bucket. This is only needed we snowflake provided file formats are not enough.
(Optional) Create file format
CREATE OR REPLACE FILE FORMAT my_csv_format_01 TYPE = CSV FIELD_OPTIONALLY_ENCLOSED_BY='"'
Once we have the access and format setup done, we create the stage. Stage stores the metadata of the external files, in our case s3. This is used to find the data which needs to be loaded in the snowflake table(s). We have created a simple stage, you can also look at other options like encryption.
Create External stage
create or replace stage my_s3_stage_01 storage_integration = my_s3_int_01 url = 's3://my-snowflake-data-bucket/dev/gold/' file_format = my_csv_format_01;
The above command creates a mapping between snowflake and S3 file prefixes. It also tells snowflake to use a file format which is suitable for data stored in S3.
Create External table
create or replace external table ext_ccfinput_test_01 with location = @my_s3_stage_01/ auto_refresh = true file_format = (type = CSV) pattern='.*ganalytics.*[.]csv';describe stage my_s3_stage_01;
Similar to how stage store info on where to find data, External tables store file-level metadata, such as the filename, a version identifier and related properties. This adds an abstraction, which allows us to query data as if it was present in snowflake.
Now we are ready to query the data from S3 in snowflake. We issue a select statement on the table we created.
select t.$1, t.$2, t.$3, t.$4, t.$5, t.$6 from @my_s3_stage_01 as t;
And voila, we get the result which resonates with the content of s3 data files.
In this blog, we saw how we can access and query data stored in S3 from snowflake.
|
[
{
"code": null,
"e": 467,
"s": 172,
"text": "Snowflake integration objects enable us to connect with external systems from Snowflake. In my last blog, we went through how to create an API integration to invoke an AWS Lambda. In this blog, we will see how we can integrate AWS S3 so that we can access data stored and query it in snowflake."
},
{
"code": null,
"e": 660,
"s": 467,
"text": "For snowflake to be able to talk to our AWS account we need to add cross account role. This role will be assumed by an IAM identity in Snowflake account and perform actions in our AWS Account."
},
{
"code": null,
"e": 776,
"s": 660,
"text": "Create a cross-account IAM Role in your AWS account. Put a dummy account and we will update the trust policy later."
},
{
"code": null,
"e": 827,
"s": 776,
"text": "Attach an inline policy to the role created above."
},
{
"code": null,
"e": 1069,
"s": 827,
"text": "Version: '2012-10-17'Statement:- Effect: Allow Action: - s3:GetObject - s3:GetObjectVersion Resource: arn:aws:s3:::my-snowflake-data-bucket/dev/gold/*- Effect: Allow Action: s3:ListBucket Resource: arn:aws:s3:::my-snowflake-data-bucket"
},
{
"code": null,
"e": 1206,
"s": 1069,
"text": "The above policy allows the role to access S3 bucket under a prefix. As a security practice only add minimum access needed by snowflake."
},
{
"code": null,
"e": 1242,
"s": 1206,
"text": "Create a Storage integration object"
},
{
"code": null,
"e": 1470,
"s": 1242,
"text": "create or replace storage integration my_s3_int_01 type = external_stage storage_provider = s3 enabled = true storage_aws_role_arn = '<IAM_ROLE_ARN>' storage_allowed_locations = ('s3://my-snowflake-data-bucket/dev/gold/');"
},
{
"code": null,
"e": 1727,
"s": 1470,
"text": "The above command when run in snowflake creates an S3 integration object. This object creates the IAM identity in snowflake account. All API action in AWS account will be performed by this user by assuming the role we mentioned in the storage_aws_role_arn."
},
{
"code": null,
"e": 2016,
"s": 1727,
"text": "As mentioned, the integration object creates a user and external identity. We need those to add trust relationship between AWS and Snowflake account. To get that we describe the integration object just created and note down the values of STORAGE_AWS_IAM_USER_ARN & STORAGE_AWS_EXTERNAL_ID"
},
{
"code": null,
"e": 2051,
"s": 2016,
"text": "describe integration my_s3_int_01;"
},
{
"code": null,
"e": 2059,
"s": 2051,
"text": "OUTPUT:"
},
{
"code": null,
"e": 2264,
"s": 2059,
"text": "Once we have the user & external identity we Update the trust relationship of the role created in 1st step. Add the value of STORAGE_AWS_IAM_USER_ARN in Principal & STORAGE_AWS_EXTERNAL_ID under condition"
},
{
"code": null,
"e": 2479,
"s": 2264,
"text": "Version: '2012-10-17'Statement:- Effect: Allow Principal: AWS: \"<STORAGE_AWS_IAM_USER_ARN>\" Action: sts:AssumeRole Condition: ForAnyValue:StringLike: sts:ExternalId: - \"<STORAGE_AWS_EXTERNAL_ID>\""
},
{
"code": null,
"e": 2664,
"s": 2479,
"text": "We need to tell snowflake of any special formatting we are having in the files which are stored in the S3 bucket. This is only needed we snowflake provided file formats are not enough."
},
{
"code": null,
"e": 2694,
"s": 2664,
"text": "(Optional) Create file format"
},
{
"code": null,
"e": 2787,
"s": 2694,
"text": "CREATE OR REPLACE FILE FORMAT my_csv_format_01 TYPE = CSV FIELD_OPTIONALLY_ENCLOSED_BY='\"'"
},
{
"code": null,
"e": 3086,
"s": 2787,
"text": "Once we have the access and format setup done, we create the stage. Stage stores the metadata of the external files, in our case s3. This is used to find the data which needs to be loaded in the snowflake table(s). We have created a simple stage, you can also look at other options like encryption."
},
{
"code": null,
"e": 3108,
"s": 3086,
"text": "Create External stage"
},
{
"code": null,
"e": 3266,
"s": 3108,
"text": "create or replace stage my_s3_stage_01 storage_integration = my_s3_int_01 url = 's3://my-snowflake-data-bucket/dev/gold/' file_format = my_csv_format_01;"
},
{
"code": null,
"e": 3428,
"s": 3266,
"text": "The above command creates a mapping between snowflake and S3 file prefixes. It also tells snowflake to use a file format which is suitable for data stored in S3."
},
{
"code": null,
"e": 3450,
"s": 3428,
"text": "Create External table"
},
{
"code": null,
"e": 3650,
"s": 3450,
"text": "create or replace external table ext_ccfinput_test_01 with location = @my_s3_stage_01/ auto_refresh = true file_format = (type = CSV) pattern='.*ganalytics.*[.]csv';describe stage my_s3_stage_01;"
},
{
"code": null,
"e": 3906,
"s": 3650,
"text": "Similar to how stage store info on where to find data, External tables store file-level metadata, such as the filename, a version identifier and related properties. This adds an abstraction, which allows us to query data as if it was present in snowflake."
},
{
"code": null,
"e": 4016,
"s": 3906,
"text": "Now we are ready to query the data from S3 in snowflake. We issue a select statement on the table we created."
},
{
"code": null,
"e": 4085,
"s": 4016,
"text": "select t.$1, t.$2, t.$3, t.$4, t.$5, t.$6 from @my_s3_stage_01 as t;"
},
{
"code": null,
"e": 4165,
"s": 4085,
"text": "And voila, we get the result which resonates with the content of s3 data files."
}
] |
Ruby Integer abs() function with example - GeeksforGeeks
|
09 Jan, 2020
The abs() function in Ruby returns the absolute value of the integer.
Syntax: (number).abs
Parameter: The function takes the integer whose absolute value is to be returned.
Return Value: The function returns the absolute value of the integer.
Example #1:
# Ruby program Integer abs() function # Initializing the numbers num1 = -21num2 = 21 num3 = 0 num4 = -100 # Printing the absolute value of integers puts (num1).absputs (num2).absputs (num3).absputs (num4).abs
Output :
21
21
0
100
Example #2:
# Ruby program of Integer abs() function # Initializing the numbers num1 =29num2 = -7num3 = 90num4 = -10 # Printing the absolute value of integers puts (num1).absputs (num2).absputs (num3).absputs (num4).abs
Output:
29
7
90
10
Ruby Integer-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Array count() operation
Include v/s Extend in Ruby
Ruby | Array slice() function
Ruby | Enumerator each_with_index function
Global Variable in Ruby
Ruby | Array select() function
Ruby | Hash delete() function
Ruby | String capitalize() Method
Ruby | String gsub! Method
How to Make a Custom Array of Hashes in Ruby?
|
[
{
"code": null,
"e": 23491,
"s": 23463,
"text": "\n09 Jan, 2020"
},
{
"code": null,
"e": 23561,
"s": 23491,
"text": "The abs() function in Ruby returns the absolute value of the integer."
},
{
"code": null,
"e": 23582,
"s": 23561,
"text": "Syntax: (number).abs"
},
{
"code": null,
"e": 23664,
"s": 23582,
"text": "Parameter: The function takes the integer whose absolute value is to be returned."
},
{
"code": null,
"e": 23734,
"s": 23664,
"text": "Return Value: The function returns the absolute value of the integer."
},
{
"code": null,
"e": 23746,
"s": 23734,
"text": "Example #1:"
},
{
"code": "# Ruby program Integer abs() function # Initializing the numbers num1 = -21num2 = 21 num3 = 0 num4 = -100 # Printing the absolute value of integers puts (num1).absputs (num2).absputs (num3).absputs (num4).abs",
"e": 23965,
"s": 23746,
"text": null
},
{
"code": null,
"e": 23974,
"s": 23965,
"text": "Output :"
},
{
"code": null,
"e": 23987,
"s": 23974,
"text": "21\n21\n0\n100\n"
},
{
"code": null,
"e": 23999,
"s": 23987,
"text": "Example #2:"
},
{
"code": "# Ruby program of Integer abs() function # Initializing the numbers num1 =29num2 = -7num3 = 90num4 = -10 # Printing the absolute value of integers puts (num1).absputs (num2).absputs (num3).absputs (num4).abs",
"e": 24216,
"s": 23999,
"text": null
},
{
"code": null,
"e": 24224,
"s": 24216,
"text": "Output:"
},
{
"code": null,
"e": 24236,
"s": 24224,
"text": "29\n7\n90\n10\n"
},
{
"code": null,
"e": 24255,
"s": 24236,
"text": "Ruby Integer-class"
},
{
"code": null,
"e": 24268,
"s": 24255,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 24273,
"s": 24268,
"text": "Ruby"
},
{
"code": null,
"e": 24371,
"s": 24273,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24380,
"s": 24371,
"text": "Comments"
},
{
"code": null,
"e": 24393,
"s": 24380,
"text": "Old Comments"
},
{
"code": null,
"e": 24424,
"s": 24393,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 24451,
"s": 24424,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 24481,
"s": 24451,
"text": "Ruby | Array slice() function"
},
{
"code": null,
"e": 24524,
"s": 24481,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 24548,
"s": 24524,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 24579,
"s": 24548,
"text": "Ruby | Array select() function"
},
{
"code": null,
"e": 24609,
"s": 24579,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 24643,
"s": 24609,
"text": "Ruby | String capitalize() Method"
},
{
"code": null,
"e": 24670,
"s": 24643,
"text": "Ruby | String gsub! Method"
}
] |
Laravel - CSRF Protection
|
CSRF refers to Cross Site Forgery attacks on web applications. CSRF attacks are the unauthorized activities which the authenticated users of the system perform. As such, many web applications are prone to these attacks.
Laravel offers CSRF protection in the following way −
Laravel includes an in built CSRF plug-in, that generates tokens for each active user session. These tokens verify that the operations or requests are sent by the concerned authenticated user.
The implementation of CSRF protection in Laravel is discussed in detail in this section. The following points are notable before proceeding further on CSRF protection −
CSRF is implemented within HTML forms declared inside the web applications. You have to include a hidden validated CSRF token in the form, so that the CSRF protection middleware of Laravel can validate the request. The syntax is shown below −
CSRF is implemented within HTML forms declared inside the web applications. You have to include a hidden validated CSRF token in the form, so that the CSRF protection middleware of Laravel can validate the request. The syntax is shown below −
<form method = "POST" action="/profile">
{{ csrf_field() }}
...
</form>
You can conveniently build JavaScript driven applications using JavaScript HTTP library, as this includes CSRF token to every outgoing request.
You can conveniently build JavaScript driven applications using JavaScript HTTP library, as this includes CSRF token to every outgoing request.
The file namely resources/assets/js/bootstrap.js registers all the tokens for Laravel applications and includes meta tag which stores csrf-token with Axios HTTP library.
The file namely resources/assets/js/bootstrap.js registers all the tokens for Laravel applications and includes meta tag which stores csrf-token with Axios HTTP library.
Consider the following lines of code. They show a form which takes two parameters as input: email and message.
<form>
<label> Email </label>
<input type = "text" name = "email"/>
<br/>
<label> Message </label> <input type="text" name = "message"/>
<input type = ”submit” name = ”submitButton” value = ”submit”>
</form>
The result of the above code is the form shown below which the end user can view −
The form shown above will accept any input information from an authorized user. This may make the web application prone to various attacks.
Please note that the submit button includes functionality in the controller section. The postContact function is used in controllers for that associated views. It is shown below −
public function postContact(Request $request) {
return $request-> all();
}
Observe that the form does not include any CSRF tokens so the sensitive information shared as input parameters are prone to various attacks.
The following lines of code shows you the form re-designed using CSRF tokens −
<form method = ”post” >
{{ csrf_field() }}
<label> Email </label>
<input type = "text" name = "email"/>
<br/>
<label> Message </label>
<input type = "text" name = "message"/>
<input type = ”submit” name = ”submitButton” value = ”submit”>
</form>
The output achieved will return JSON with a token as given below −
{
"token": "ghfleifxDSUYEW9WE67877CXNVFJKL",
"name": "TutorialsPoint",
"email": "[email protected]"
}
This is the CSRF token created on clicking the submit button.
13 Lectures
3 hours
Sebastian Sulinski
35 Lectures
3.5 hours
Antonio Papa
7 Lectures
1.5 hours
Sebastian Sulinski
42 Lectures
1 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
116 Lectures
13 hours
Hafizullah Masoudi
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2692,
"s": 2472,
"text": "CSRF refers to Cross Site Forgery attacks on web applications. CSRF attacks are the unauthorized activities which the authenticated users of the system perform. As such, many web applications are prone to these attacks."
},
{
"code": null,
"e": 2746,
"s": 2692,
"text": "Laravel offers CSRF protection in the following way −"
},
{
"code": null,
"e": 2939,
"s": 2746,
"text": "Laravel includes an in built CSRF plug-in, that generates tokens for each active user session. These tokens verify that the operations or requests are sent by the concerned authenticated user."
},
{
"code": null,
"e": 3108,
"s": 2939,
"text": "The implementation of CSRF protection in Laravel is discussed in detail in this section. The following points are notable before proceeding further on CSRF protection −"
},
{
"code": null,
"e": 3351,
"s": 3108,
"text": "CSRF is implemented within HTML forms declared inside the web applications. You have to include a hidden validated CSRF token in the form, so that the CSRF protection middleware of Laravel can validate the request. The syntax is shown below −"
},
{
"code": null,
"e": 3594,
"s": 3351,
"text": "CSRF is implemented within HTML forms declared inside the web applications. You have to include a hidden validated CSRF token in the form, so that the CSRF protection middleware of Laravel can validate the request. The syntax is shown below −"
},
{
"code": null,
"e": 3673,
"s": 3594,
"text": "<form method = \"POST\" action=\"/profile\">\n {{ csrf_field() }}\n ...\n</form>\n"
},
{
"code": null,
"e": 3817,
"s": 3673,
"text": "You can conveniently build JavaScript driven applications using JavaScript HTTP library, as this includes CSRF token to every outgoing request."
},
{
"code": null,
"e": 3961,
"s": 3817,
"text": "You can conveniently build JavaScript driven applications using JavaScript HTTP library, as this includes CSRF token to every outgoing request."
},
{
"code": null,
"e": 4131,
"s": 3961,
"text": "The file namely resources/assets/js/bootstrap.js registers all the tokens for Laravel applications and includes meta tag which stores csrf-token with Axios HTTP library."
},
{
"code": null,
"e": 4301,
"s": 4131,
"text": "The file namely resources/assets/js/bootstrap.js registers all the tokens for Laravel applications and includes meta tag which stores csrf-token with Axios HTTP library."
},
{
"code": null,
"e": 4412,
"s": 4301,
"text": "Consider the following lines of code. They show a form which takes two parameters as input: email and message."
},
{
"code": null,
"e": 4641,
"s": 4412,
"text": "<form>\n <label> Email </label>\n <input type = \"text\" name = \"email\"/>\n <br/>\n <label> Message </label> <input type=\"text\" name = \"message\"/>\n <input type = ”submit” name = ”submitButton” value = ”submit”>\n</form>"
},
{
"code": null,
"e": 4724,
"s": 4641,
"text": "The result of the above code is the form shown below which the end user can view −"
},
{
"code": null,
"e": 4864,
"s": 4724,
"text": "The form shown above will accept any input information from an authorized user. This may make the web application prone to various attacks."
},
{
"code": null,
"e": 5044,
"s": 4864,
"text": "Please note that the submit button includes functionality in the controller section. The postContact function is used in controllers for that associated views. It is shown below −"
},
{
"code": null,
"e": 5123,
"s": 5044,
"text": "public function postContact(Request $request) {\n return $request-> all();\n}\n"
},
{
"code": null,
"e": 5264,
"s": 5123,
"text": "Observe that the form does not include any CSRF tokens so the sensitive information shared as input parameters are prone to various attacks."
},
{
"code": null,
"e": 5343,
"s": 5264,
"text": "The following lines of code shows you the form re-designed using CSRF tokens −"
},
{
"code": null,
"e": 5610,
"s": 5343,
"text": "<form method = ”post” >\n {{ csrf_field() }}\n <label> Email </label>\n <input type = \"text\" name = \"email\"/>\n <br/>\n <label> Message </label>\n <input type = \"text\" name = \"message\"/>\n <input type = ”submit” name = ”submitButton” value = ”submit”>\n</form>"
},
{
"code": null,
"e": 5677,
"s": 5610,
"text": "The output achieved will return JSON with a token as given below −"
},
{
"code": null,
"e": 5798,
"s": 5677,
"text": "{\n \"token\": \"ghfleifxDSUYEW9WE67877CXNVFJKL\",\n \"name\": \"TutorialsPoint\",\n \"email\": \"[email protected]\"\n}\n"
},
{
"code": null,
"e": 5860,
"s": 5798,
"text": "This is the CSRF token created on clicking the submit button."
},
{
"code": null,
"e": 5893,
"s": 5860,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5913,
"s": 5893,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 5948,
"s": 5913,
"text": "\n 35 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5962,
"s": 5948,
"text": " Antonio Papa"
},
{
"code": null,
"e": 5996,
"s": 5962,
"text": "\n 7 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6016,
"s": 5996,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 6049,
"s": 6016,
"text": "\n 42 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6069,
"s": 6049,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 6104,
"s": 6069,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6127,
"s": 6104,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 6162,
"s": 6127,
"text": "\n 116 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 6182,
"s": 6162,
"text": " Hafizullah Masoudi"
},
{
"code": null,
"e": 6189,
"s": 6182,
"text": " Print"
},
{
"code": null,
"e": 6200,
"s": 6189,
"text": " Add Notes"
}
] |
HTML5 using src using raw binary data
|
If an audio file is stored in database and then we want to use this file as a blob or binary in an application where audio source is according to session then binary data is returned through ${sessionScope.user.music}. To load the audio file in an audio tag, data:audio/mp3;base64 works well.
As for the image, image tag is used as follows:
<img src="data:image/gif;base64,source “,width="30" height="25" alt="My Image">
Similarly for audio, audio tag data:audio/mp3 is used.
|
[
{
"code": null,
"e": 1355,
"s": 1062,
"text": "If an audio file is stored in database and then we want to use this file as a blob or binary in an application where audio source is according to session then binary data is returned through ${sessionScope.user.music}. To load the audio file in an audio tag, data:audio/mp3;base64 works well."
},
{
"code": null,
"e": 1403,
"s": 1355,
"text": "As for the image, image tag is used as follows:"
},
{
"code": null,
"e": 1483,
"s": 1403,
"text": "<img src=\"data:image/gif;base64,source “,width=\"30\" height=\"25\" alt=\"My Image\">"
},
{
"code": null,
"e": 1538,
"s": 1483,
"text": "Similarly for audio, audio tag data:audio/mp3 is used."
}
] |
Debugging with Stetho in Android - GeeksforGeeks
|
06 Jan, 2021
Stetho is an open-source debug library developed by Facebook. It allows you to use chrome debugging tools to troubleshoot network traffic., thus it provides a rich, interactive debugging experience for android developers. Stetho easily and smoothly debug network calls. It is a sophisticated debug bridge for Android applications. When enabled, developers have a path to the Chrome Developer Tools feature natively part of the Chrome desktop browser. Developers can also prefer to allow the optional dumpapp tool which allows a powerful command-line interface to application internals. Without limiting its functionality to just network inspection, JavaScript console, database inspection, etc.
Stetho is an open-source debugging platform.It provides a rich and highly interactive experience.With the help of Stetho native applications debugging very simple.It offers you to use Google Chrome debugging tool for various activities.It provides hierarchy inspection during debugging.Also, Stetho allows network, database management, and more interacting features.Stetho uses HTTP web-socket to send data.
Stetho is an open-source debugging platform.
It provides a rich and highly interactive experience.
With the help of Stetho native applications debugging very simple.
It offers you to use Google Chrome debugging tool for various activities.
It provides hierarchy inspection during debugging.
Also, Stetho allows network, database management, and more interacting features.
Stetho uses HTTP web-socket to send data.
The problem with debugging network traffic while developing android applications, debugger facing problems with traditional debugging tools get messed up and inspection got very complex while switching the devices.
The debugging is more reliable and easy with the Stetho library because it uses the chrome debugging tool which is supports web-socket and using it for network debugging. Stetho automated the call inspection, so it becomes more important for android developers.
Stetho uses an HTTP web Socket server that sends all debugging information to the browser. It is accessible through:
chrome://inspect
Step 1: Add the following dependency in the build.gradle file.
implementation ‘com.facebook.stetho:stetho-okhttp3:1.5.1’
Step 2: Register your class in AndroidManifest.xml, and initialize it in the application.
Java
import android.app.Application;import android.content.Context;import com.facebook.stetho.InspectorModulesProvider;import com.facebook.stetho.Stetho;import com.facebook.stetho.inspector.protocol.ChromeDevtoolsDomain;import com.facebook.stetho.okhttp3.StethoInterceptor;import com.facebook.stetho.rhino.JsRuntimeReplFactoryBuilder;import com.jakewharton.caso.OkHttp3Downloader;import com.squareup.caso.Caso;import okhttp3.OkHttpClient; public class Stetho extends Application { public OkHttpClient httpClient; @Override public void onCreate() { super.onCreate(); final Context context = this; if (BuildConfig.DEBUG) { // Create an InitializerBuilder Stetho.InitializerBuilder initializerBuilder = Stetho.newInitializerBuilder(this); // Enable Chrome DevTools initializerBuilder.enableWebKitInspector(new InspectorModulesProvider() { @Override public Iterable<ChromeDevtoolsDomain> get() { // Enable command line interface return new Stetho.DefaultInspectorModulesBuilder(context).runtimeRepl( new JsRuntimeReplFactoryBuilder(context) .addVariable("foo", "bar") .build() ).finish(); } }); // Use the InitializerBuilder to generate an Initializer Stetho.Initializer initializer = initializerBuilder.build(); // Initialize Stetho with the Initializer Stetho.initialize(initializer); // Add Stetho interceptor httpClient = new OkHttpClient.Builder().addNetworkInterceptor(new StethoInterceptor()).build(); } else { httpClient = new OkHttpClient(); } Caso caso = new Caso.Builder(this).downloader(new OkHttp3Downloader(httpClient)).build(); Caso.setSingletonInstance(caso); }}
Or
Initialize your library with a single line of code (for example ):
Java
public class Applicationstetho extends Application { public void onCreate() { super.onCreate(); if(BuildConfig.DEBUG ){ Stetho.initializeWithDefault(this) } }}
Updating your manifest file in your android project:
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://geeksforgeeks.com/apk/res/android" package="com.geeksforgeeks.sthetosample"> <uses-permission android:name="android.permission.INTERNET"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme" android:name=".StethoSample"> ... </application> </manifest>
Step 3: Enable network inspection.
Following method is the easiest and simpler w2ay to enable network inspection when you constructing the okHttpClient instance:
okHttpClient.Builder()
.addNetworkInterceptor(StethoInterceptor())
.build()
How to check?
Start emulator on the device. Then open chrome://inspect on Chrome and your emulator device should appear, after that click inspects to launch a new window and click the network tab to watch network traffics.
android
Picked
Android
Java
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Retrofit with Kotlin Coroutine in Android
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
How to Post Data to API using Retrofit in Android?
Android Listview in Java with Example
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Reverse a string in Java
Arrays.sort() in Java with examples
|
[
{
"code": null,
"e": 25062,
"s": 25034,
"text": "\n06 Jan, 2021"
},
{
"code": null,
"e": 25758,
"s": 25062,
"text": "Stetho is an open-source debug library developed by Facebook. It allows you to use chrome debugging tools to troubleshoot network traffic., thus it provides a rich, interactive debugging experience for android developers. Stetho easily and smoothly debug network calls. It is a sophisticated debug bridge for Android applications. When enabled, developers have a path to the Chrome Developer Tools feature natively part of the Chrome desktop browser. Developers can also prefer to allow the optional dumpapp tool which allows a powerful command-line interface to application internals. Without limiting its functionality to just network inspection, JavaScript console, database inspection, etc. "
},
{
"code": null,
"e": 26166,
"s": 25758,
"text": "Stetho is an open-source debugging platform.It provides a rich and highly interactive experience.With the help of Stetho native applications debugging very simple.It offers you to use Google Chrome debugging tool for various activities.It provides hierarchy inspection during debugging.Also, Stetho allows network, database management, and more interacting features.Stetho uses HTTP web-socket to send data."
},
{
"code": null,
"e": 26211,
"s": 26166,
"text": "Stetho is an open-source debugging platform."
},
{
"code": null,
"e": 26265,
"s": 26211,
"text": "It provides a rich and highly interactive experience."
},
{
"code": null,
"e": 26332,
"s": 26265,
"text": "With the help of Stetho native applications debugging very simple."
},
{
"code": null,
"e": 26406,
"s": 26332,
"text": "It offers you to use Google Chrome debugging tool for various activities."
},
{
"code": null,
"e": 26457,
"s": 26406,
"text": "It provides hierarchy inspection during debugging."
},
{
"code": null,
"e": 26538,
"s": 26457,
"text": "Also, Stetho allows network, database management, and more interacting features."
},
{
"code": null,
"e": 26580,
"s": 26538,
"text": "Stetho uses HTTP web-socket to send data."
},
{
"code": null,
"e": 26795,
"s": 26580,
"text": "The problem with debugging network traffic while developing android applications, debugger facing problems with traditional debugging tools get messed up and inspection got very complex while switching the devices."
},
{
"code": null,
"e": 27058,
"s": 26795,
"text": "The debugging is more reliable and easy with the Stetho library because it uses the chrome debugging tool which is supports web-socket and using it for network debugging. Stetho automated the call inspection, so it becomes more important for android developers. "
},
{
"code": null,
"e": 27175,
"s": 27058,
"text": "Stetho uses an HTTP web Socket server that sends all debugging information to the browser. It is accessible through:"
},
{
"code": null,
"e": 27192,
"s": 27175,
"text": "chrome://inspect"
},
{
"code": null,
"e": 27255,
"s": 27192,
"text": "Step 1: Add the following dependency in the build.gradle file."
},
{
"code": null,
"e": 27313,
"s": 27255,
"text": "implementation ‘com.facebook.stetho:stetho-okhttp3:1.5.1’"
},
{
"code": null,
"e": 27403,
"s": 27313,
"text": "Step 2: Register your class in AndroidManifest.xml, and initialize it in the application."
},
{
"code": null,
"e": 27408,
"s": 27403,
"text": "Java"
},
{
"code": "import android.app.Application;import android.content.Context;import com.facebook.stetho.InspectorModulesProvider;import com.facebook.stetho.Stetho;import com.facebook.stetho.inspector.protocol.ChromeDevtoolsDomain;import com.facebook.stetho.okhttp3.StethoInterceptor;import com.facebook.stetho.rhino.JsRuntimeReplFactoryBuilder;import com.jakewharton.caso.OkHttp3Downloader;import com.squareup.caso.Caso;import okhttp3.OkHttpClient; public class Stetho extends Application { public OkHttpClient httpClient; @Override public void onCreate() { super.onCreate(); final Context context = this; if (BuildConfig.DEBUG) { // Create an InitializerBuilder Stetho.InitializerBuilder initializerBuilder = Stetho.newInitializerBuilder(this); // Enable Chrome DevTools initializerBuilder.enableWebKitInspector(new InspectorModulesProvider() { @Override public Iterable<ChromeDevtoolsDomain> get() { // Enable command line interface return new Stetho.DefaultInspectorModulesBuilder(context).runtimeRepl( new JsRuntimeReplFactoryBuilder(context) .addVariable(\"foo\", \"bar\") .build() ).finish(); } }); // Use the InitializerBuilder to generate an Initializer Stetho.Initializer initializer = initializerBuilder.build(); // Initialize Stetho with the Initializer Stetho.initialize(initializer); // Add Stetho interceptor httpClient = new OkHttpClient.Builder().addNetworkInterceptor(new StethoInterceptor()).build(); } else { httpClient = new OkHttpClient(); } Caso caso = new Caso.Builder(this).downloader(new OkHttp3Downloader(httpClient)).build(); Caso.setSingletonInstance(caso); }}",
"e": 29478,
"s": 27408,
"text": null
},
{
"code": null,
"e": 29481,
"s": 29478,
"text": "Or"
},
{
"code": null,
"e": 29548,
"s": 29481,
"text": "Initialize your library with a single line of code (for example ):"
},
{
"code": null,
"e": 29553,
"s": 29548,
"text": "Java"
},
{
"code": "public class Applicationstetho extends Application { public void onCreate() { super.onCreate(); if(BuildConfig.DEBUG ){ Stetho.initializeWithDefault(this) } }}",
"e": 29731,
"s": 29553,
"text": null
},
{
"code": null,
"e": 29784,
"s": 29731,
"text": "Updating your manifest file in your android project:"
},
{
"code": null,
"e": 29788,
"s": 29784,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://geeksforgeeks.com/apk/res/android\" package=\"com.geeksforgeeks.sthetosample\"> <uses-permission android:name=\"android.permission.INTERNET\"/> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\" android:name=\".StethoSample\"> ... </application> </manifest>",
"e": 30291,
"s": 29788,
"text": null
},
{
"code": null,
"e": 30326,
"s": 30291,
"text": "Step 3: Enable network inspection."
},
{
"code": null,
"e": 30453,
"s": 30326,
"text": "Following method is the easiest and simpler w2ay to enable network inspection when you constructing the okHttpClient instance:"
},
{
"code": null,
"e": 30476,
"s": 30453,
"text": "okHttpClient.Builder()"
},
{
"code": null,
"e": 30531,
"s": 30476,
"text": " .addNetworkInterceptor(StethoInterceptor())"
},
{
"code": null,
"e": 30551,
"s": 30531,
"text": " .build()"
},
{
"code": null,
"e": 30565,
"s": 30551,
"text": "How to check?"
},
{
"code": null,
"e": 30774,
"s": 30565,
"text": "Start emulator on the device. Then open chrome://inspect on Chrome and your emulator device should appear, after that click inspects to launch a new window and click the network tab to watch network traffics."
},
{
"code": null,
"e": 30782,
"s": 30774,
"text": "android"
},
{
"code": null,
"e": 30789,
"s": 30782,
"text": "Picked"
},
{
"code": null,
"e": 30797,
"s": 30789,
"text": "Android"
},
{
"code": null,
"e": 30802,
"s": 30797,
"text": "Java"
},
{
"code": null,
"e": 30807,
"s": 30802,
"text": "Java"
},
{
"code": null,
"e": 30815,
"s": 30807,
"text": "Android"
},
{
"code": null,
"e": 30913,
"s": 30815,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30922,
"s": 30913,
"text": "Comments"
},
{
"code": null,
"e": 30935,
"s": 30922,
"text": "Old Comments"
},
{
"code": null,
"e": 30977,
"s": 30935,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 31016,
"s": 30977,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 31066,
"s": 31016,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 31117,
"s": 31066,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 31155,
"s": 31117,
"text": "Android Listview in Java with Example"
},
{
"code": null,
"e": 31170,
"s": 31155,
"text": "Arrays in Java"
},
{
"code": null,
"e": 31214,
"s": 31170,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 31236,
"s": 31214,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 31261,
"s": 31236,
"text": "Reverse a string in Java"
}
] |
Important Artifacts In Windows-I
|
This chapter will explain various concepts involved in Microsoft Windows forensics and the important artifacts that an investigator can obtain from the investigation process.
Artifacts are the objects or areas within a computer system that have important information related to the activities performed by the computer user. The type and location of this information depends upon the operating system. During forensic analysis, these artifacts play a very important role in approving or disapproving the investigator’s observation.
Windows artifacts assume significance due to the following reasons −
Around 90% of the traffic in world comes from the computers using Windows as their operating system. That is why for digital forensics examiners Windows artifacts are very essentials.
Around 90% of the traffic in world comes from the computers using Windows as their operating system. That is why for digital forensics examiners Windows artifacts are very essentials.
The Windows operating system stores different types of evidences related to the user activity on computer system. This is another reason which shows the importance of Windows artifacts for digital forensics.
The Windows operating system stores different types of evidences related to the user activity on computer system. This is another reason which shows the importance of Windows artifacts for digital forensics.
Many times the investigator revolves the investigation around old and traditional areas like user crated data. Windows artifacts can lead the investigation towards non-traditional areas like system created data or the artifacts.
Many times the investigator revolves the investigation around old and traditional areas like user crated data. Windows artifacts can lead the investigation towards non-traditional areas like system created data or the artifacts.
Great abundance of artifacts is provided by Windows which are helpful for investigators as well as for companies and individuals performing informal investigations.
Great abundance of artifacts is provided by Windows which are helpful for investigators as well as for companies and individuals performing informal investigations.
Increase in cyber-crime in recent years is another reason that Windows artifacts are important.
Increase in cyber-crime in recent years is another reason that Windows artifacts are important.
In this section, we are going to discuss about some Windows artifacts and Python scripts to fetch information from them.
It is one of the important Windows artifacts for forensic investigation. Windows recycle bin contains the files that have been deleted by the user, but not physically removed by the system yet. Even if the user completely removes the file from system, it serves as an important source of investigation. This is because the examiner can extract valuable information, like original file path as well as time that it was sent to Recycle Bin, from the deleted files.
Note that the storage of Recycle Bin evidence depends upon the version of Windows. In the following Python script, we are going to deal with Windows 7 where it creates two files: $R file that contains the actual content of the recycled file and $I file that contains original file name, path, file size when file was deleted.
For Python script we need to install third party modules namely pytsk3, pyewf and unicodecsv. We can use pip to install them. We can follow the following steps to extract information from Recycle Bin −
First, we need to use recursive method to scan through the $Recycle.bin folder and select all the files starting with $I.
First, we need to use recursive method to scan through the $Recycle.bin folder and select all the files starting with $I.
Next, we will read the contents of the files and parse the available metadata structures.
Next, we will read the contents of the files and parse the available metadata structures.
Now, we will search for the associated $R file.
Now, we will search for the associated $R file.
At last, we will write the results into CSV file for review.
At last, we will write the results into CSV file for review.
Let us see how to use Python code for this purpose −
First, we need to import the following Python libraries −
from __future__ import print_function
from argparse import ArgumentParser
import datetime
import os
import struct
from utility.pytskutil import TSKUtil
import unicodecsv as csv
Next, we need to provide argument for command-line handler. Note that here it will accept three arguments – first is the path to evidence file, second is the type of evidence file and third is the desired output path to the CSV report, as shown below −
if __name__ == '__main__':
parser = argparse.ArgumentParser('Recycle Bin evidences')
parser.add_argument('EVIDENCE_FILE', help = "Path to evidence file")
parser.add_argument('IMAGE_TYPE', help = "Evidence file format",
choices = ('ewf', 'raw'))
parser.add_argument('CSV_REPORT', help = "Path to CSV report")
args = parser.parse_args()
main(args.EVIDENCE_FILE, args.IMAGE_TYPE, args.CSV_REPORT)
Now, define the main() function that will handle all the processing. It will search for $I file as follows −
def main(evidence, image_type, report_file):
tsk_util = TSKUtil(evidence, image_type)
dollar_i_files = tsk_util.recurse_files("$I", path = '/$Recycle.bin',logic = "startswith")
if dollar_i_files is not None:
processed_files = process_dollar_i(tsk_util, dollar_i_files)
write_csv(report_file,['file_path', 'file_size', 'deleted_time','dollar_i_file', 'dollar_r_file', 'is_directory'],processed_files)
else:
print("No $I files found")
Now, if we found $I file, then it must be sent to process_dollar_i() function which will accept the tsk_util object as well as the list of $I files, as shown below −
def process_dollar_i(tsk_util, dollar_i_files):
processed_files = []
for dollar_i in dollar_i_files:
file_attribs = read_dollar_i(dollar_i[2])
if file_attribs is None:
continue
file_attribs['dollar_i_file'] = os.path.join('/$Recycle.bin', dollar_i[1][1:])
Now, search for $R files as follows −
recycle_file_path = os.path.join('/$Recycle.bin',dollar_i[1].rsplit("/", 1)[0][1:])
dollar_r_files = tsk_util.recurse_files(
"$R" + dollar_i[0][2:],path = recycle_file_path, logic = "startswith")
if dollar_r_files is None:
dollar_r_dir = os.path.join(recycle_file_path,"$R" + dollar_i[0][2:])
dollar_r_dirs = tsk_util.query_directory(dollar_r_dir)
if dollar_r_dirs is None:
file_attribs['dollar_r_file'] = "Not Found"
file_attribs['is_directory'] = 'Unknown'
else:
file_attribs['dollar_r_file'] = dollar_r_dir
file_attribs['is_directory'] = True
else:
dollar_r = [os.path.join(recycle_file_path, r[1][1:])for r in dollar_r_files]
file_attribs['dollar_r_file'] = ";".join(dollar_r)
file_attribs['is_directory'] = False
processed_files.append(file_attribs)
return processed_files
Now, define read_dollar_i() method to read the $I files, in other words, parse the metadata. We will use read_random() method to read the signature’s first eight bytes. This will return none if signature does not match. After that, we will have to read and unpack the values from $I file if that is a valid file.
def read_dollar_i(file_obj):
if file_obj.read_random(0, 8) != '\x01\x00\x00\x00\x00\x00\x00\x00':
return None
raw_file_size = struct.unpack('<q', file_obj.read_random(8, 8))
raw_deleted_time = struct.unpack('<q', file_obj.read_random(16, 8))
raw_file_path = file_obj.read_random(24, 520)
Now, after extracting these files we need to interpret the integers into human-readable values by using sizeof_fmt() function as shown below −
file_size = sizeof_fmt(raw_file_size[0])
deleted_time = parse_windows_filetime(raw_deleted_time[0])
file_path = raw_file_path.decode("utf16").strip("\x00")
return {'file_size': file_size, 'file_path': file_path,'deleted_time': deleted_time}
Now, we need to define sizeof_fmt() function as follows −
def sizeof_fmt(num, suffix = 'B'):
for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:
if abs(num) < 1024.0:
return "%3.1f%s%s" % (num, unit, suffix)
num /= 1024.0
return "%.1f%s%s" % (num, 'Yi', suffix)
Now, define a function for interpreted integers into formatted date and time as follows −
def parse_windows_filetime(date_value):
microseconds = float(date_value) / 10
ts = datetime.datetime(1601, 1, 1) + datetime.timedelta(
microseconds = microseconds)
return ts.strftime('%Y-%m-%d %H:%M:%S.%f')
Now, we will define write_csv() method to write the processed results into a CSV file as follows −
def write_csv(outfile, fieldnames, data):
with open(outfile, 'wb') as open_outfile:
csvfile = csv.DictWriter(open_outfile, fieldnames)
csvfile.writeheader()
csvfile.writerows(data)
When you run the above script, we will get the data from $I and $R file.
Windows Sticky Notes replaces the real world habit of writing with pen and paper. These notes used to float on the desktop with different options for colors, fonts etc. In Windows 7 the Sticky Notes file is stored as an OLE file hence in the following Python script we will investigate this OLE file to extract metadata from Sticky Notes.
For this Python script, we need to install third party modules namely olefile, pytsk3, pyewf and unicodecsv. We can use the command pip to install them.
We can follow the steps discussed below for extracting the information from Sticky note file namely StickyNote.sn −
Firstly, open the evidence file and find all the StickyNote.snt files.
Firstly, open the evidence file and find all the StickyNote.snt files.
Then, parse the metadata and content from the OLE stream and write the RTF content to files.
Then, parse the metadata and content from the OLE stream and write the RTF content to files.
Lastly, create CSV report of this metadata.
Lastly, create CSV report of this metadata.
Let us see how to use Python code for this purpose −
First, import the following Python libraries −
from __future__ import print_function
from argparse import ArgumentParser
import unicodecsv as csv
import os
import StringIO
from utility.pytskutil import TSKUtil
import olefile
Next, define a global variable which will be used across this script −
REPORT_COLS = ['note_id', 'created', 'modified', 'note_text', 'note_file']
Next, we need to provide argument for command-line handler. Note that here it will accept three arguments – first is the path to evidence file, second is the type of evidence file and third is the desired output path as follows −
if __name__ == '__main__':
parser = argparse.ArgumentParser('Evidence from Sticky Notes')
parser.add_argument('EVIDENCE_FILE', help="Path to evidence file")
parser.add_argument('IMAGE_TYPE', help="Evidence file format",choices=('ewf', 'raw'))
parser.add_argument('REPORT_FOLDER', help="Path to report folder")
args = parser.parse_args()
main(args.EVIDENCE_FILE, args.IMAGE_TYPE, args.REPORT_FOLDER)
Now, we will define main() function which will be similar to the previous script as shown below −
def main(evidence, image_type, report_folder):
tsk_util = TSKUtil(evidence, image_type)
note_files = tsk_util.recurse_files('StickyNotes.snt', '/Users','equals')
Now, let us iterate through the resulting files. Then we will call parse_snt_file() function to process the file and then we will write RTF file with the write_note_rtf() method as follows −
report_details = []
for note_file in note_files:
user_dir = note_file[1].split("/")[1]
file_like_obj = create_file_like_obj(note_file[2])
note_data = parse_snt_file(file_like_obj)
if note_data is None:
continue
write_note_rtf(note_data, os.path.join(report_folder, user_dir))
report_details += prep_note_report(note_data, REPORT_COLS,"/Users" + note_file[1])
write_csv(os.path.join(report_folder, 'sticky_notes.csv'), REPORT_COLS,report_details)
Next, we need to define various functions used in this script.
First of all we will define create_file_like_obj() function for reading the size of the file by taking pytsk file object. Then we will define parse_snt_file() function that will accept the file-like object as its input and is used to read and interpret the sticky note file.
def parse_snt_file(snt_file):
if not olefile.isOleFile(snt_file):
print("This is not an OLE file")
return None
ole = olefile.OleFileIO(snt_file)
note = {}
for stream in ole.listdir():
if stream[0].count("-") == 3:
if stream[0] not in note:
note[stream[0]] = {"created": ole.getctime(stream[0]),"modified": ole.getmtime(stream[0])}
content = None
if stream[1] == '0':
content = ole.openstream(stream).read()
elif stream[1] == '3':
content = ole.openstream(stream).read().decode("utf-16")
if content:
note[stream[0]][stream[1]] = content
return note
Now, create a RTF file by defining write_note_rtf() function as follows
def write_note_rtf(note_data, report_folder):
if not os.path.exists(report_folder):
os.makedirs(report_folder)
for note_id, stream_data in note_data.items():
fname = os.path.join(report_folder, note_id + ".rtf")
with open(fname, 'w') as open_file:
open_file.write(stream_data['0'])
Now, we will translate the nested dictionary into a flat list of dictionaries that are more appropriate for a CSV spreadsheet. It will be done by defining prep_note_report() function. Lastly, we will define write_csv() function.
def prep_note_report(note_data, report_cols, note_file):
report_details = []
for note_id, stream_data in note_data.items():
report_details.append({
"note_id": note_id,
"created": stream_data['created'],
"modified": stream_data['modified'],
"note_text": stream_data['3'].strip("\x00"),
"note_file": note_file
})
return report_details
def write_csv(outfile, fieldnames, data):
with open(outfile, 'wb') as open_outfile:
csvfile = csv.DictWriter(open_outfile, fieldnames)
csvfile.writeheader()
csvfile.writerows(data)
After running the above script, we will get the metadata from Sticky Notes file.
Windows registry files contain many important details which are like a treasure trove of information for a forensic analyst. It is a hierarchical database that contains details related to operating system configuration, user activity, software installation etc. In the following Python script we are going to access common baseline information from the SYSTEM and SOFTWARE hives.
For this Python script, we need to install third party modules namely pytsk3, pyewf and registry. We can use pip to install them.
We can follow the steps given below for extracting the information from Windows registry −
First, find registry hives to process by its name as well as by path.
First, find registry hives to process by its name as well as by path.
Then we to open these files by using StringIO and Registry modules.
Then we to open these files by using StringIO and Registry modules.
At last we need to process each and every hive and print the parsed values to the console for interpretation.
At last we need to process each and every hive and print the parsed values to the console for interpretation.
Let us see how to use Python code for this purpose −
First, import the following Python libraries −
from __future__ import print_function
from argparse import ArgumentParser
import datetime
import StringIO
import struct
from utility.pytskutil import TSKUtil
from Registry import Registry
Now, provide argument for the command-line handler. Here it will accept two arguments - first is the path to the evidence file, second is the type of evidence file, as shown below −
if __name__ == '__main__':
parser = argparse.ArgumentParser('Evidence from Windows Registry')
parser.add_argument('EVIDENCE_FILE', help = "Path to evidence file")
parser.add_argument('IMAGE_TYPE', help = "Evidence file format",
choices = ('ewf', 'raw'))
args = parser.parse_args()
main(args.EVIDENCE_FILE, args.IMAGE_TYPE)
Now we will define main() function for searching SYSTEM and SOFTWARE hives within /Windows/System32/config folder as follows −
def main(evidence, image_type):
tsk_util = TSKUtil(evidence, image_type)
tsk_system_hive = tsk_util.recurse_files('system', '/Windows/system32/config', 'equals')
tsk_software_hive = tsk_util.recurse_files('software', '/Windows/system32/config', 'equals')
system_hive = open_file_as_reg(tsk_system_hive[0][2])
software_hive = open_file_as_reg(tsk_software_hive[0][2])
process_system_hive(system_hive)
process_software_hive(software_hive)
Now, define the function for opening the registry file. For this purpose, we need to gather the size of file from pytsk metadata as follows −
def open_file_as_reg(reg_file):
file_size = reg_file.info.meta.size
file_content = reg_file.read_random(0, file_size)
file_like_obj = StringIO.StringIO(file_content)
return Registry.Registry(file_like_obj)
Now, with the help of following method, we can process SYSTEM> hive −
def process_system_hive(hive):
root = hive.root()
current_control_set = root.find_key("Select").value("Current").value()
control_set = root.find_key("ControlSet{:03d}".format(current_control_set))
raw_shutdown_time = struct.unpack(
'<Q', control_set.find_key("Control").find_key("Windows").value("ShutdownTime").value())
shutdown_time = parse_windows_filetime(raw_shutdown_time[0])
print("Last Shutdown Time: {}".format(shutdown_time))
time_zone = control_set.find_key("Control").find_key("TimeZoneInformation")
.value("TimeZoneKeyName").value()
print("Machine Time Zone: {}".format(time_zone))
computer_name = control_set.find_key("Control").find_key("ComputerName").find_key("ComputerName")
.value("ComputerName").value()
print("Machine Name: {}".format(computer_name))
last_access = control_set.find_key("Control").find_key("FileSystem")
.value("NtfsDisableLastAccessUpdate").value()
last_access = "Disabled" if last_access == 1 else "enabled"
print("Last Access Updates: {}".format(last_access))
Now, we need to define a function for interpreted integers into formatted date and time as follows −
def parse_windows_filetime(date_value):
microseconds = float(date_value) / 10
ts = datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds = microseconds)
return ts.strftime('%Y-%m-%d %H:%M:%S.%f')
def parse_unix_epoch(date_value):
ts = datetime.datetime.fromtimestamp(date_value)
return ts.strftime('%Y-%m-%d %H:%M:%S.%f')
Now with the help of following method we can process SOFTWARE hive −
def process_software_hive(hive):
root = hive.root()
nt_curr_ver = root.find_key("Microsoft").find_key("Windows NT")
.find_key("CurrentVersion")
print("Product name: {}".format(nt_curr_ver.value("ProductName").value()))
print("CSD Version: {}".format(nt_curr_ver.value("CSDVersion").value()))
print("Current Build: {}".format(nt_curr_ver.value("CurrentBuild").value()))
print("Registered Owner: {}".format(nt_curr_ver.value("RegisteredOwner").value()))
print("Registered Org:
{}".format(nt_curr_ver.value("RegisteredOrganization").value()))
raw_install_date = nt_curr_ver.value("InstallDate").value()
install_date = parse_unix_epoch(raw_install_date)
print("Installation Date: {}".format(install_date))
After running the above script, we will get the metadata stored in Windows Registry files.
187 Lectures
17.5 hours
Malhar Lathkar
55 Lectures
8 hours
Arnab Chakraborty
136 Lectures
11 hours
In28Minutes Official
75 Lectures
13 hours
Eduonix Learning Solutions
70 Lectures
8.5 hours
Lets Kode It
63 Lectures
6 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2128,
"s": 1953,
"text": "This chapter will explain various concepts involved in Microsoft Windows forensics and the important artifacts that an investigator can obtain from the investigation process."
},
{
"code": null,
"e": 2485,
"s": 2128,
"text": "Artifacts are the objects or areas within a computer system that have important information related to the activities performed by the computer user. The type and location of this information depends upon the operating system. During forensic analysis, these artifacts play a very important role in approving or disapproving the investigator’s observation."
},
{
"code": null,
"e": 2554,
"s": 2485,
"text": "Windows artifacts assume significance due to the following reasons −"
},
{
"code": null,
"e": 2738,
"s": 2554,
"text": "Around 90% of the traffic in world comes from the computers using Windows as their operating system. That is why for digital forensics examiners Windows artifacts are very essentials."
},
{
"code": null,
"e": 2922,
"s": 2738,
"text": "Around 90% of the traffic in world comes from the computers using Windows as their operating system. That is why for digital forensics examiners Windows artifacts are very essentials."
},
{
"code": null,
"e": 3130,
"s": 2922,
"text": "The Windows operating system stores different types of evidences related to the user activity on computer system. This is another reason which shows the importance of Windows artifacts for digital forensics."
},
{
"code": null,
"e": 3338,
"s": 3130,
"text": "The Windows operating system stores different types of evidences related to the user activity on computer system. This is another reason which shows the importance of Windows artifacts for digital forensics."
},
{
"code": null,
"e": 3567,
"s": 3338,
"text": "Many times the investigator revolves the investigation around old and traditional areas like user crated data. Windows artifacts can lead the investigation towards non-traditional areas like system created data or the artifacts."
},
{
"code": null,
"e": 3796,
"s": 3567,
"text": "Many times the investigator revolves the investigation around old and traditional areas like user crated data. Windows artifacts can lead the investigation towards non-traditional areas like system created data or the artifacts."
},
{
"code": null,
"e": 3961,
"s": 3796,
"text": "Great abundance of artifacts is provided by Windows which are helpful for investigators as well as for companies and individuals performing informal investigations."
},
{
"code": null,
"e": 4126,
"s": 3961,
"text": "Great abundance of artifacts is provided by Windows which are helpful for investigators as well as for companies and individuals performing informal investigations."
},
{
"code": null,
"e": 4222,
"s": 4126,
"text": "Increase in cyber-crime in recent years is another reason that Windows artifacts are important."
},
{
"code": null,
"e": 4318,
"s": 4222,
"text": "Increase in cyber-crime in recent years is another reason that Windows artifacts are important."
},
{
"code": null,
"e": 4439,
"s": 4318,
"text": "In this section, we are going to discuss about some Windows artifacts and Python scripts to fetch information from them."
},
{
"code": null,
"e": 4902,
"s": 4439,
"text": "It is one of the important Windows artifacts for forensic investigation. Windows recycle bin contains the files that have been deleted by the user, but not physically removed by the system yet. Even if the user completely removes the file from system, it serves as an important source of investigation. This is because the examiner can extract valuable information, like original file path as well as time that it was sent to Recycle Bin, from the deleted files."
},
{
"code": null,
"e": 5228,
"s": 4902,
"text": "Note that the storage of Recycle Bin evidence depends upon the version of Windows. In the following Python script, we are going to deal with Windows 7 where it creates two files: $R file that contains the actual content of the recycled file and $I file that contains original file name, path, file size when file was deleted."
},
{
"code": null,
"e": 5430,
"s": 5228,
"text": "For Python script we need to install third party modules namely pytsk3, pyewf and unicodecsv. We can use pip to install them. We can follow the following steps to extract information from Recycle Bin −"
},
{
"code": null,
"e": 5552,
"s": 5430,
"text": "First, we need to use recursive method to scan through the $Recycle.bin folder and select all the files starting with $I."
},
{
"code": null,
"e": 5674,
"s": 5552,
"text": "First, we need to use recursive method to scan through the $Recycle.bin folder and select all the files starting with $I."
},
{
"code": null,
"e": 5764,
"s": 5674,
"text": "Next, we will read the contents of the files and parse the available metadata structures."
},
{
"code": null,
"e": 5854,
"s": 5764,
"text": "Next, we will read the contents of the files and parse the available metadata structures."
},
{
"code": null,
"e": 5902,
"s": 5854,
"text": "Now, we will search for the associated $R file."
},
{
"code": null,
"e": 5950,
"s": 5902,
"text": "Now, we will search for the associated $R file."
},
{
"code": null,
"e": 6011,
"s": 5950,
"text": "At last, we will write the results into CSV file for review."
},
{
"code": null,
"e": 6072,
"s": 6011,
"text": "At last, we will write the results into CSV file for review."
},
{
"code": null,
"e": 6125,
"s": 6072,
"text": "Let us see how to use Python code for this purpose −"
},
{
"code": null,
"e": 6183,
"s": 6125,
"text": "First, we need to import the following Python libraries −"
},
{
"code": null,
"e": 6362,
"s": 6183,
"text": "from __future__ import print_function\nfrom argparse import ArgumentParser\n\nimport datetime\nimport os\nimport struct\n\nfrom utility.pytskutil import TSKUtil\nimport unicodecsv as csv"
},
{
"code": null,
"e": 6615,
"s": 6362,
"text": "Next, we need to provide argument for command-line handler. Note that here it will accept three arguments – first is the path to evidence file, second is the type of evidence file and third is the desired output path to the CSV report, as shown below −"
},
{
"code": null,
"e": 7030,
"s": 6615,
"text": "if __name__ == '__main__':\n parser = argparse.ArgumentParser('Recycle Bin evidences')\n parser.add_argument('EVIDENCE_FILE', help = \"Path to evidence file\")\n parser.add_argument('IMAGE_TYPE', help = \"Evidence file format\",\n choices = ('ewf', 'raw'))\n parser.add_argument('CSV_REPORT', help = \"Path to CSV report\")\n args = parser.parse_args()\n main(args.EVIDENCE_FILE, args.IMAGE_TYPE, args.CSV_REPORT)"
},
{
"code": null,
"e": 7139,
"s": 7030,
"text": "Now, define the main() function that will handle all the processing. It will search for $I file as follows −"
},
{
"code": null,
"e": 7606,
"s": 7139,
"text": "def main(evidence, image_type, report_file):\n tsk_util = TSKUtil(evidence, image_type)\n dollar_i_files = tsk_util.recurse_files(\"$I\", path = '/$Recycle.bin',logic = \"startswith\")\n \n if dollar_i_files is not None:\n processed_files = process_dollar_i(tsk_util, dollar_i_files)\n write_csv(report_file,['file_path', 'file_size', 'deleted_time','dollar_i_file', 'dollar_r_file', 'is_directory'],processed_files)\n else:\n print(\"No $I files found\")"
},
{
"code": null,
"e": 7772,
"s": 7606,
"text": "Now, if we found $I file, then it must be sent to process_dollar_i() function which will accept the tsk_util object as well as the list of $I files, as shown below −"
},
{
"code": null,
"e": 8065,
"s": 7772,
"text": "def process_dollar_i(tsk_util, dollar_i_files):\n processed_files = []\n \n for dollar_i in dollar_i_files:\n file_attribs = read_dollar_i(dollar_i[2])\n if file_attribs is None:\n continue\n file_attribs['dollar_i_file'] = os.path.join('/$Recycle.bin', dollar_i[1][1:])"
},
{
"code": null,
"e": 8103,
"s": 8065,
"text": "Now, search for $R files as follows −"
},
{
"code": null,
"e": 8977,
"s": 8103,
"text": "recycle_file_path = os.path.join('/$Recycle.bin',dollar_i[1].rsplit(\"/\", 1)[0][1:])\ndollar_r_files = tsk_util.recurse_files(\n \"$R\" + dollar_i[0][2:],path = recycle_file_path, logic = \"startswith\")\n \n if dollar_r_files is None:\n dollar_r_dir = os.path.join(recycle_file_path,\"$R\" + dollar_i[0][2:])\n dollar_r_dirs = tsk_util.query_directory(dollar_r_dir)\n \n if dollar_r_dirs is None:\n file_attribs['dollar_r_file'] = \"Not Found\"\n file_attribs['is_directory'] = 'Unknown'\n \n else:\n file_attribs['dollar_r_file'] = dollar_r_dir\n file_attribs['is_directory'] = True\n \n else:\n dollar_r = [os.path.join(recycle_file_path, r[1][1:])for r in dollar_r_files]\n file_attribs['dollar_r_file'] = \";\".join(dollar_r)\n file_attribs['is_directory'] = False\n processed_files.append(file_attribs)\n return processed_files "
},
{
"code": null,
"e": 9290,
"s": 8977,
"text": "Now, define read_dollar_i() method to read the $I files, in other words, parse the metadata. We will use read_random() method to read the signature’s first eight bytes. This will return none if signature does not match. After that, we will have to read and unpack the values from $I file if that is a valid file."
},
{
"code": null,
"e": 9598,
"s": 9290,
"text": "def read_dollar_i(file_obj):\n if file_obj.read_random(0, 8) != '\\x01\\x00\\x00\\x00\\x00\\x00\\x00\\x00':\n return None\n raw_file_size = struct.unpack('<q', file_obj.read_random(8, 8))\n raw_deleted_time = struct.unpack('<q', file_obj.read_random(16, 8))\n raw_file_path = file_obj.read_random(24, 520)"
},
{
"code": null,
"e": 9741,
"s": 9598,
"text": "Now, after extracting these files we need to interpret the integers into human-readable values by using sizeof_fmt() function as shown below −"
},
{
"code": null,
"e": 9983,
"s": 9741,
"text": "file_size = sizeof_fmt(raw_file_size[0])\ndeleted_time = parse_windows_filetime(raw_deleted_time[0])\n\nfile_path = raw_file_path.decode(\"utf16\").strip(\"\\x00\")\nreturn {'file_size': file_size, 'file_path': file_path,'deleted_time': deleted_time}"
},
{
"code": null,
"e": 10041,
"s": 9983,
"text": "Now, we need to define sizeof_fmt() function as follows −"
},
{
"code": null,
"e": 10280,
"s": 10041,
"text": "def sizeof_fmt(num, suffix = 'B'):\n for unit in ['', 'Ki', 'Mi', 'Gi', 'Ti', 'Pi', 'Ei', 'Zi']:\n if abs(num) < 1024.0:\n return \"%3.1f%s%s\" % (num, unit, suffix)\n num /= 1024.0\n return \"%.1f%s%s\" % (num, 'Yi', suffix)"
},
{
"code": null,
"e": 10370,
"s": 10280,
"text": "Now, define a function for interpreted integers into formatted date and time as follows −"
},
{
"code": null,
"e": 10592,
"s": 10370,
"text": "def parse_windows_filetime(date_value):\n microseconds = float(date_value) / 10\n ts = datetime.datetime(1601, 1, 1) + datetime.timedelta(\n microseconds = microseconds)\n return ts.strftime('%Y-%m-%d %H:%M:%S.%f')"
},
{
"code": null,
"e": 10691,
"s": 10592,
"text": "Now, we will define write_csv() method to write the processed results into a CSV file as follows −"
},
{
"code": null,
"e": 10893,
"s": 10691,
"text": "def write_csv(outfile, fieldnames, data):\n with open(outfile, 'wb') as open_outfile:\n csvfile = csv.DictWriter(open_outfile, fieldnames)\n csvfile.writeheader()\n csvfile.writerows(data)"
},
{
"code": null,
"e": 10966,
"s": 10893,
"text": "When you run the above script, we will get the data from $I and $R file."
},
{
"code": null,
"e": 11305,
"s": 10966,
"text": "Windows Sticky Notes replaces the real world habit of writing with pen and paper. These notes used to float on the desktop with different options for colors, fonts etc. In Windows 7 the Sticky Notes file is stored as an OLE file hence in the following Python script we will investigate this OLE file to extract metadata from Sticky Notes."
},
{
"code": null,
"e": 11458,
"s": 11305,
"text": "For this Python script, we need to install third party modules namely olefile, pytsk3, pyewf and unicodecsv. We can use the command pip to install them."
},
{
"code": null,
"e": 11574,
"s": 11458,
"text": "We can follow the steps discussed below for extracting the information from Sticky note file namely StickyNote.sn −"
},
{
"code": null,
"e": 11645,
"s": 11574,
"text": "Firstly, open the evidence file and find all the StickyNote.snt files."
},
{
"code": null,
"e": 11716,
"s": 11645,
"text": "Firstly, open the evidence file and find all the StickyNote.snt files."
},
{
"code": null,
"e": 11809,
"s": 11716,
"text": "Then, parse the metadata and content from the OLE stream and write the RTF content to files."
},
{
"code": null,
"e": 11902,
"s": 11809,
"text": "Then, parse the metadata and content from the OLE stream and write the RTF content to files."
},
{
"code": null,
"e": 11946,
"s": 11902,
"text": "Lastly, create CSV report of this metadata."
},
{
"code": null,
"e": 11990,
"s": 11946,
"text": "Lastly, create CSV report of this metadata."
},
{
"code": null,
"e": 12043,
"s": 11990,
"text": "Let us see how to use Python code for this purpose −"
},
{
"code": null,
"e": 12090,
"s": 12043,
"text": "First, import the following Python libraries −"
},
{
"code": null,
"e": 12270,
"s": 12090,
"text": "from __future__ import print_function\nfrom argparse import ArgumentParser\n\nimport unicodecsv as csv\nimport os\nimport StringIO\n\nfrom utility.pytskutil import TSKUtil\nimport olefile"
},
{
"code": null,
"e": 12341,
"s": 12270,
"text": "Next, define a global variable which will be used across this script −"
},
{
"code": null,
"e": 12417,
"s": 12341,
"text": "REPORT_COLS = ['note_id', 'created', 'modified', 'note_text', 'note_file']\n"
},
{
"code": null,
"e": 12647,
"s": 12417,
"text": "Next, we need to provide argument for command-line handler. Note that here it will accept three arguments – first is the path to evidence file, second is the type of evidence file and third is the desired output path as follows −"
},
{
"code": null,
"e": 13064,
"s": 12647,
"text": "if __name__ == '__main__':\n parser = argparse.ArgumentParser('Evidence from Sticky Notes')\n parser.add_argument('EVIDENCE_FILE', help=\"Path to evidence file\")\n parser.add_argument('IMAGE_TYPE', help=\"Evidence file format\",choices=('ewf', 'raw'))\n parser.add_argument('REPORT_FOLDER', help=\"Path to report folder\")\n args = parser.parse_args()\n main(args.EVIDENCE_FILE, args.IMAGE_TYPE, args.REPORT_FOLDER)"
},
{
"code": null,
"e": 13162,
"s": 13064,
"text": "Now, we will define main() function which will be similar to the previous script as shown below −"
},
{
"code": null,
"e": 13330,
"s": 13162,
"text": "def main(evidence, image_type, report_folder):\n tsk_util = TSKUtil(evidence, image_type)\n note_files = tsk_util.recurse_files('StickyNotes.snt', '/Users','equals')"
},
{
"code": null,
"e": 13521,
"s": 13330,
"text": "Now, let us iterate through the resulting files. Then we will call parse_snt_file() function to process the file and then we will write RTF file with the write_note_rtf() method as follows −"
},
{
"code": null,
"e": 13998,
"s": 13521,
"text": "report_details = []\nfor note_file in note_files:\n user_dir = note_file[1].split(\"/\")[1]\n file_like_obj = create_file_like_obj(note_file[2])\n note_data = parse_snt_file(file_like_obj)\n \n if note_data is None:\n continue\n write_note_rtf(note_data, os.path.join(report_folder, user_dir))\n report_details += prep_note_report(note_data, REPORT_COLS,\"/Users\" + note_file[1])\n write_csv(os.path.join(report_folder, 'sticky_notes.csv'), REPORT_COLS,report_details)"
},
{
"code": null,
"e": 14061,
"s": 13998,
"text": "Next, we need to define various functions used in this script."
},
{
"code": null,
"e": 14336,
"s": 14061,
"text": "First of all we will define create_file_like_obj() function for reading the size of the file by taking pytsk file object. Then we will define parse_snt_file() function that will accept the file-like object as its input and is used to read and interpret the sticky note file."
},
{
"code": null,
"e": 15016,
"s": 14336,
"text": "def parse_snt_file(snt_file):\n \n if not olefile.isOleFile(snt_file):\n print(\"This is not an OLE file\")\n return None\n ole = olefile.OleFileIO(snt_file)\n note = {}\n \n for stream in ole.listdir():\n if stream[0].count(\"-\") == 3:\n if stream[0] not in note:\n note[stream[0]] = {\"created\": ole.getctime(stream[0]),\"modified\": ole.getmtime(stream[0])}\n content = None\n if stream[1] == '0':\n content = ole.openstream(stream).read()\n elif stream[1] == '3':\n content = ole.openstream(stream).read().decode(\"utf-16\")\n if content:\n note[stream[0]][stream[1]] = content\n\treturn note"
},
{
"code": null,
"e": 15088,
"s": 15016,
"text": "Now, create a RTF file by defining write_note_rtf() function as follows"
},
{
"code": null,
"e": 15407,
"s": 15088,
"text": "def write_note_rtf(note_data, report_folder):\n if not os.path.exists(report_folder):\n os.makedirs(report_folder)\n \n for note_id, stream_data in note_data.items():\n fname = os.path.join(report_folder, note_id + \".rtf\")\n with open(fname, 'w') as open_file:\n open_file.write(stream_data['0'])"
},
{
"code": null,
"e": 15636,
"s": 15407,
"text": "Now, we will translate the nested dictionary into a flat list of dictionaries that are more appropriate for a CSV spreadsheet. It will be done by defining prep_note_report() function. Lastly, we will define write_csv() function."
},
{
"code": null,
"e": 16241,
"s": 15636,
"text": "def prep_note_report(note_data, report_cols, note_file):\n report_details = []\n \n for note_id, stream_data in note_data.items():\n report_details.append({\n \"note_id\": note_id,\n \"created\": stream_data['created'],\n \"modified\": stream_data['modified'],\n \"note_text\": stream_data['3'].strip(\"\\x00\"),\n \"note_file\": note_file\n })\n return report_details\ndef write_csv(outfile, fieldnames, data):\n with open(outfile, 'wb') as open_outfile:\n csvfile = csv.DictWriter(open_outfile, fieldnames)\n csvfile.writeheader()\n csvfile.writerows(data)"
},
{
"code": null,
"e": 16322,
"s": 16241,
"text": "After running the above script, we will get the metadata from Sticky Notes file."
},
{
"code": null,
"e": 16702,
"s": 16322,
"text": "Windows registry files contain many important details which are like a treasure trove of information for a forensic analyst. It is a hierarchical database that contains details related to operating system configuration, user activity, software installation etc. In the following Python script we are going to access common baseline information from the SYSTEM and SOFTWARE hives."
},
{
"code": null,
"e": 16832,
"s": 16702,
"text": "For this Python script, we need to install third party modules namely pytsk3, pyewf and registry. We can use pip to install them."
},
{
"code": null,
"e": 16923,
"s": 16832,
"text": "We can follow the steps given below for extracting the information from Windows registry −"
},
{
"code": null,
"e": 16993,
"s": 16923,
"text": "First, find registry hives to process by its name as well as by path."
},
{
"code": null,
"e": 17063,
"s": 16993,
"text": "First, find registry hives to process by its name as well as by path."
},
{
"code": null,
"e": 17131,
"s": 17063,
"text": "Then we to open these files by using StringIO and Registry modules."
},
{
"code": null,
"e": 17199,
"s": 17131,
"text": "Then we to open these files by using StringIO and Registry modules."
},
{
"code": null,
"e": 17309,
"s": 17199,
"text": "At last we need to process each and every hive and print the parsed values to the console for interpretation."
},
{
"code": null,
"e": 17419,
"s": 17309,
"text": "At last we need to process each and every hive and print the parsed values to the console for interpretation."
},
{
"code": null,
"e": 17472,
"s": 17419,
"text": "Let us see how to use Python code for this purpose −"
},
{
"code": null,
"e": 17519,
"s": 17472,
"text": "First, import the following Python libraries −"
},
{
"code": null,
"e": 17709,
"s": 17519,
"text": "from __future__ import print_function\nfrom argparse import ArgumentParser\n\nimport datetime\nimport StringIO\nimport struct\n\nfrom utility.pytskutil import TSKUtil\nfrom Registry import Registry"
},
{
"code": null,
"e": 17891,
"s": 17709,
"text": "Now, provide argument for the command-line handler. Here it will accept two arguments - first is the path to the evidence file, second is the type of evidence file, as shown below −"
},
{
"code": null,
"e": 18232,
"s": 17891,
"text": "if __name__ == '__main__':\n parser = argparse.ArgumentParser('Evidence from Windows Registry')\n parser.add_argument('EVIDENCE_FILE', help = \"Path to evidence file\")\n parser.add_argument('IMAGE_TYPE', help = \"Evidence file format\",\n choices = ('ewf', 'raw'))\n args = parser.parse_args()\n main(args.EVIDENCE_FILE, args.IMAGE_TYPE)"
},
{
"code": null,
"e": 18359,
"s": 18232,
"text": "Now we will define main() function for searching SYSTEM and SOFTWARE hives within /Windows/System32/config folder as follows −"
},
{
"code": null,
"e": 18817,
"s": 18359,
"text": "def main(evidence, image_type):\n tsk_util = TSKUtil(evidence, image_type)\n tsk_system_hive = tsk_util.recurse_files('system', '/Windows/system32/config', 'equals')\n tsk_software_hive = tsk_util.recurse_files('software', '/Windows/system32/config', 'equals')\n system_hive = open_file_as_reg(tsk_system_hive[0][2])\n software_hive = open_file_as_reg(tsk_software_hive[0][2])\n process_system_hive(system_hive)\n process_software_hive(software_hive)"
},
{
"code": null,
"e": 18959,
"s": 18817,
"text": "Now, define the function for opening the registry file. For this purpose, we need to gather the size of file from pytsk metadata as follows −"
},
{
"code": null,
"e": 19177,
"s": 18959,
"text": "def open_file_as_reg(reg_file):\n file_size = reg_file.info.meta.size\n file_content = reg_file.read_random(0, file_size)\n file_like_obj = StringIO.StringIO(file_content)\n return Registry.Registry(file_like_obj)"
},
{
"code": null,
"e": 19247,
"s": 19177,
"text": "Now, with the help of following method, we can process SYSTEM> hive −"
},
{
"code": null,
"e": 20326,
"s": 19247,
"text": "def process_system_hive(hive):\n root = hive.root()\n current_control_set = root.find_key(\"Select\").value(\"Current\").value()\n control_set = root.find_key(\"ControlSet{:03d}\".format(current_control_set))\n raw_shutdown_time = struct.unpack(\n '<Q', control_set.find_key(\"Control\").find_key(\"Windows\").value(\"ShutdownTime\").value())\n \n shutdown_time = parse_windows_filetime(raw_shutdown_time[0])\n print(\"Last Shutdown Time: {}\".format(shutdown_time))\n \n time_zone = control_set.find_key(\"Control\").find_key(\"TimeZoneInformation\")\n .value(\"TimeZoneKeyName\").value()\n \n print(\"Machine Time Zone: {}\".format(time_zone))\n computer_name = control_set.find_key(\"Control\").find_key(\"ComputerName\").find_key(\"ComputerName\")\n .value(\"ComputerName\").value()\n \n print(\"Machine Name: {}\".format(computer_name))\n last_access = control_set.find_key(\"Control\").find_key(\"FileSystem\")\n .value(\"NtfsDisableLastAccessUpdate\").value()\n last_access = \"Disabled\" if last_access == 1 else \"enabled\"\n print(\"Last Access Updates: {}\".format(last_access))"
},
{
"code": null,
"e": 20427,
"s": 20326,
"text": "Now, we need to define a function for interpreted integers into formatted date and time as follows −"
},
{
"code": null,
"e": 20775,
"s": 20427,
"text": "def parse_windows_filetime(date_value):\n microseconds = float(date_value) / 10\n ts = datetime.datetime(1601, 1, 1) + datetime.timedelta(microseconds = microseconds)\n return ts.strftime('%Y-%m-%d %H:%M:%S.%f')\n\ndef parse_unix_epoch(date_value):\n ts = datetime.datetime.fromtimestamp(date_value)\n return ts.strftime('%Y-%m-%d %H:%M:%S.%f')"
},
{
"code": null,
"e": 20844,
"s": 20775,
"text": "Now with the help of following method we can process SOFTWARE hive −"
},
{
"code": null,
"e": 21597,
"s": 20844,
"text": "def process_software_hive(hive):\n root = hive.root()\n nt_curr_ver = root.find_key(\"Microsoft\").find_key(\"Windows NT\")\n .find_key(\"CurrentVersion\")\n \n print(\"Product name: {}\".format(nt_curr_ver.value(\"ProductName\").value()))\n print(\"CSD Version: {}\".format(nt_curr_ver.value(\"CSDVersion\").value()))\n print(\"Current Build: {}\".format(nt_curr_ver.value(\"CurrentBuild\").value()))\n print(\"Registered Owner: {}\".format(nt_curr_ver.value(\"RegisteredOwner\").value()))\n print(\"Registered Org: \n {}\".format(nt_curr_ver.value(\"RegisteredOrganization\").value()))\n \n raw_install_date = nt_curr_ver.value(\"InstallDate\").value()\n install_date = parse_unix_epoch(raw_install_date)\n print(\"Installation Date: {}\".format(install_date))"
},
{
"code": null,
"e": 21688,
"s": 21597,
"text": "After running the above script, we will get the metadata stored in Windows Registry files."
},
{
"code": null,
"e": 21725,
"s": 21688,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 21741,
"s": 21725,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 21774,
"s": 21741,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 21793,
"s": 21774,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 21828,
"s": 21793,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 21850,
"s": 21828,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 21884,
"s": 21850,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 21912,
"s": 21884,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 21947,
"s": 21912,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 21961,
"s": 21947,
"text": " Lets Kode It"
},
{
"code": null,
"e": 21994,
"s": 21961,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 22011,
"s": 21994,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 22018,
"s": 22011,
"text": " Print"
},
{
"code": null,
"e": 22029,
"s": 22018,
"text": " Add Notes"
}
] |
DoubleStream max() in Java with examples - GeeksforGeeks
|
06 Dec, 2018
java.util.stream.DoubleStream in Java 8, deals with primitive doubles. It helps to solve the problems like finding maximum value in array, finding minimum value in array, sum of all elements in array, and average of all values in array in a new way. DoubleStream max() returns an OptionalDouble describing the maximum element of this stream, or an empty optional if this stream is empty.
Syntax :
OptionalDouble() max()
Where, OptionalDouble is a container object which
may or may not contain a double value.
Note :
Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero.This is a special case of a reduction.
Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero.
This is a special case of a reduction.
Example 1 :
// Java code for DoubleStream max()import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // creating a stream DoubleStream stream = DoubleStream.of(-9.5, -18.6, 54.3, 8.5, 7.4, 14.2, 3.9); // OptionalDouble is a container object // which may or may not contain a // double value. OptionalDouble obj = stream.max(); // If a value is present, isPresent() will // return true and getAsDouble() will // return the value if (obj.isPresent()) { System.out.println(obj.getAsDouble()); } else { System.out.println("-1"); } }}
54.3
Example 2 :
// Java code for DoubleStream max()import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // OptionalDouble is a container object // which may or may not contain a // double value. OptionalDouble obj = DoubleStream.empty() .max(); // If a value is present, isPresent() will // return true and getAsDouble() will // return the value if (obj.isPresent()) { System.out.println(obj.getAsDouble()); } else { System.out.println("-1"); } }}
-1
Java - util package
java-DoubleStream
Java-Functions
java-stream
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
HashMap in Java with Examples
Object Oriented Programming (OOPs) Concept in Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Overriding in Java
LinkedList in Java
How to iterate any Map in Java
Queue Interface In Java
Collections in Java
|
[
{
"code": null,
"e": 24087,
"s": 24059,
"text": "\n06 Dec, 2018"
},
{
"code": null,
"e": 24475,
"s": 24087,
"text": "java.util.stream.DoubleStream in Java 8, deals with primitive doubles. It helps to solve the problems like finding maximum value in array, finding minimum value in array, sum of all elements in array, and average of all values in array in a new way. DoubleStream max() returns an OptionalDouble describing the maximum element of this stream, or an empty optional if this stream is empty."
},
{
"code": null,
"e": 24484,
"s": 24475,
"text": "Syntax :"
},
{
"code": null,
"e": 24599,
"s": 24484,
"text": "OptionalDouble() max()\n\nWhere, OptionalDouble is a container object which \nmay or may not contain a double value.\n"
},
{
"code": null,
"e": 24606,
"s": 24599,
"text": "Note :"
},
{
"code": null,
"e": 24766,
"s": 24606,
"text": "Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero.This is a special case of a reduction."
},
{
"code": null,
"e": 24888,
"s": 24766,
"text": "Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero."
},
{
"code": null,
"e": 24927,
"s": 24888,
"text": "This is a special case of a reduction."
},
{
"code": null,
"e": 24939,
"s": 24927,
"text": "Example 1 :"
},
{
"code": "// Java code for DoubleStream max()import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // creating a stream DoubleStream stream = DoubleStream.of(-9.5, -18.6, 54.3, 8.5, 7.4, 14.2, 3.9); // OptionalDouble is a container object // which may or may not contain a // double value. OptionalDouble obj = stream.max(); // If a value is present, isPresent() will // return true and getAsDouble() will // return the value if (obj.isPresent()) { System.out.println(obj.getAsDouble()); } else { System.out.println(\"-1\"); } }}",
"e": 25703,
"s": 24939,
"text": null
},
{
"code": null,
"e": 25709,
"s": 25703,
"text": "54.3\n"
},
{
"code": null,
"e": 25721,
"s": 25709,
"text": "Example 2 :"
},
{
"code": "// Java code for DoubleStream max()import java.util.*;import java.util.stream.DoubleStream; class GFG { // Driver code public static void main(String[] args) { // OptionalDouble is a container object // which may or may not contain a // double value. OptionalDouble obj = DoubleStream.empty() .max(); // If a value is present, isPresent() will // return true and getAsDouble() will // return the value if (obj.isPresent()) { System.out.println(obj.getAsDouble()); } else { System.out.println(\"-1\"); } }}",
"e": 26373,
"s": 25721,
"text": null
},
{
"code": null,
"e": 26377,
"s": 26373,
"text": "-1\n"
},
{
"code": null,
"e": 26397,
"s": 26377,
"text": "Java - util package"
},
{
"code": null,
"e": 26415,
"s": 26397,
"text": "java-DoubleStream"
},
{
"code": null,
"e": 26430,
"s": 26415,
"text": "Java-Functions"
},
{
"code": null,
"e": 26442,
"s": 26430,
"text": "java-stream"
},
{
"code": null,
"e": 26447,
"s": 26442,
"text": "Java"
},
{
"code": null,
"e": 26452,
"s": 26447,
"text": "Java"
},
{
"code": null,
"e": 26550,
"s": 26452,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26559,
"s": 26550,
"text": "Comments"
},
{
"code": null,
"e": 26572,
"s": 26559,
"text": "Old Comments"
},
{
"code": null,
"e": 26602,
"s": 26572,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 26653,
"s": 26602,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 26672,
"s": 26653,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 26690,
"s": 26672,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 26722,
"s": 26690,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 26741,
"s": 26722,
"text": "Overriding in Java"
},
{
"code": null,
"e": 26760,
"s": 26741,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 26791,
"s": 26760,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 26815,
"s": 26791,
"text": "Queue Interface In Java"
}
] |
Compiler Design - Run-Time Environment
|
A program as a source code is merely a collection of text (code, statements etc.) and to make it alive, it requires actions to be performed on the target machine. A program needs memory resources to execute instructions. A program contains names for procedures, identifiers etc., that require mapping with the actual memory location at runtime.
By runtime, we mean a program in execution. Runtime environment is a state of the target machine, which may include software libraries, environment variables, etc., to provide services to the processes running in the system.
Runtime support system is a package, mostly generated with the executable program itself and facilitates the process communication between the process and the runtime environment. It takes care of memory allocation and de-allocation while the program is being executed.
A program is a sequence of instructions combined into a number of procedures. Instructions in a procedure are executed sequentially. A procedure has a start and an end delimiter and everything inside it is called the body of the procedure. The procedure identifier and the sequence of finite instructions inside it make up the body of the procedure.
The execution of a procedure is called its activation. An activation record contains all the necessary information required to call a procedure. An activation record may contain the following units (depending upon the source language used).
Whenever a procedure is executed, its activation record is stored on the stack, also known as control stack. When a procedure calls another procedure, the execution of the caller is suspended until the called procedure finishes execution. At this time, the activation record of the called procedure is stored on the stack.
We assume that the program control flows in a sequential manner and when a procedure is called, its control is transferred to the called procedure. When a called procedure is executed, it returns the control back to the caller. This type of control flow makes it easier to represent a series of activations in the form of a tree, known as the activation tree.
To understand this concept, we take a piece of code as an example:
. . .
printf(“Enter Your Name: “);
scanf(“%s”, username);
show_data(username);
printf(“Press any key to continue...”);
. . .
int show_data(char *user)
{
printf(“Your name is %s”, username);
return 0;
}
. . .
Below is the activation tree of the code given.
Now we understand that procedures are executed in depth-first manner, thus stack allocation is the best suitable form of storage for procedure activations.
Runtime environment manages runtime memory requirements for the following entities:
Code : It is known as the text part of a program that does not change at runtime. Its memory requirements are known at the compile time.
Code : It is known as the text part of a program that does not change at runtime. Its memory requirements are known at the compile time.
Procedures : Their text part is static but they are called in a random manner. That is why, stack storage is used to manage procedure calls and activations.
Procedures : Their text part is static but they are called in a random manner. That is why, stack storage is used to manage procedure calls and activations.
Variables : Variables are known at the runtime only, unless they are global or constant. Heap memory allocation scheme is used for managing allocation and de-allocation of memory for variables in runtime.
Variables : Variables are known at the runtime only, unless they are global or constant. Heap memory allocation scheme is used for managing allocation and de-allocation of memory for variables in runtime.
In this allocation scheme, the compilation data is bound to a fixed location in the memory and it does not change when the program executes. As the memory requirement and storage locations are known in advance, runtime support package for memory allocation and de-allocation is not required.
Procedure calls and their activations are managed by means of stack memory allocation. It works in last-in-first-out (LIFO) method and this allocation strategy is very useful for recursive procedure calls.
Variables local to a procedure are allocated and de-allocated only at runtime. Heap allocation is used to dynamically allocate memory to the variables and claim it back when the variables are no more required.
Except statically allocated memory area, both stack and heap memory can grow and shrink dynamically and unexpectedly. Therefore, they cannot be provided with a fixed amount of memory in the system.
As shown in the image above, the text part of the code is allocated a fixed amount of memory. Stack and heap memory are arranged at the extremes of total memory allocated to the program. Both shrink and grow against each other.
The communication medium among procedures is known as parameter passing. The values of the variables from a calling procedure are transferred to the called procedure by some mechanism. Before moving ahead, first go through some basic terminologies pertaining to the values in a program.
The value of an expression is called its r-value. The value contained in a single variable also becomes an r-value if it appears on the right-hand side of the assignment operator. r-values can always be assigned to some other variable.
The location of memory (address) where an expression is stored is known as the l-value of that expression. It always appears at the left hand side of an assignment operator.
For example:
day = 1;
week = day * 7;
month = 1;
year = month * 12;
From this example, we understand that constant values like 1, 7, 12, and variables like day, week, month and year, all have r-values. Only variables have l-values as they also represent the memory location assigned to them.
For example:
7 = x + y;
is an l-value error, as the constant 7 does not represent any memory location.
Variables that take the information passed by the caller procedure are called formal parameters. These variables are declared in the definition of the called function.
Variables whose values or addresses are being passed to the called procedure are called actual parameters. These variables are specified in the function call as arguments.
Example:
fun_one()
{
int actual_parameter = 10;
call fun_two(int actual_parameter);
}
fun_two(int formal_parameter)
{
print formal_parameter;
}
Formal parameters hold the information of the actual parameter, depending upon the parameter passing technique used. It may be a value or an address.
In pass by value mechanism, the calling procedure passes the r-value of actual parameters and the compiler puts that into the called procedure’s activation record. Formal parameters then hold the values passed by the calling procedure. If the values held by the formal parameters are changed, it should have no impact on the actual parameters.
In pass by reference mechanism, the l-value of the actual parameter is copied to the activation record of the called procedure. This way, the called procedure now has the address (memory location) of the actual parameter and the formal parameter refers to the same memory location. Therefore, if the value pointed by the formal parameter is changed, the impact should be seen on the actual parameter as they should also point to the same value.
This parameter passing mechanism works similar to ‘pass-by-reference’ except that the changes to actual parameters are made when the called procedure ends. Upon function call, the values of actual parameters are copied in the activation record of the called procedure. Formal parameters if manipulated have no real-time effect on actual parameters (as l-values are passed), but when the called procedure ends, the l-values of formal parameters are copied to the l-values of actual parameters.
Example:
int y;
calling_procedure()
{
y = 10;
copy_restore(y); //l-value of y is passed
printf y; //prints 99
}
copy_restore(int x)
{
x = 99; // y still has value 10 (unaffected)
y = 0; // y is now 0
}
When this function ends, the l-value of formal parameter x is copied to the actual parameter y. Even if the value of y is changed before the procedure ends, the l-value of x is copied to the l-value of y making it behave like call by reference.
Languages like Algol provide a new kind of parameter passing mechanism that works like preprocessor in C language. In pass by name mechanism, the name of the procedure being called is replaced by its actual body. Pass-by-name textually substitutes the argument expressions in a procedure call for the corresponding parameters in the body of the procedure so that it can now work on actual parameters, much like pass-by-reference.
102 Lectures
10 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2538,
"s": 2193,
"text": "A program as a source code is merely a collection of text (code, statements etc.) and to make it alive, it requires actions to be performed on the target machine. A program needs memory resources to execute instructions. A program contains names for procedures, identifiers etc., that require mapping with the actual memory location at runtime."
},
{
"code": null,
"e": 2763,
"s": 2538,
"text": "By runtime, we mean a program in execution. Runtime environment is a state of the target machine, which may include software libraries, environment variables, etc., to provide services to the processes running in the system."
},
{
"code": null,
"e": 3033,
"s": 2763,
"text": "Runtime support system is a package, mostly generated with the executable program itself and facilitates the process communication between the process and the runtime environment. It takes care of memory allocation and de-allocation while the program is being executed."
},
{
"code": null,
"e": 3384,
"s": 3033,
"text": "A program is a sequence of instructions combined into a number of procedures. Instructions in a procedure are executed sequentially. A procedure has a start and an end delimiter and everything inside it is called the body of the procedure. The procedure identifier and the sequence of finite instructions inside it make up the body of the procedure."
},
{
"code": null,
"e": 3625,
"s": 3384,
"text": "The execution of a procedure is called its activation. An activation record contains all the necessary information required to call a procedure. An activation record may contain the following units (depending upon the source language used)."
},
{
"code": null,
"e": 3948,
"s": 3625,
"text": "Whenever a procedure is executed, its activation record is stored on the stack, also known as control stack. When a procedure calls another procedure, the execution of the caller is suspended until the called procedure finishes execution. At this time, the activation record of the called procedure is stored on the stack."
},
{
"code": null,
"e": 4308,
"s": 3948,
"text": "We assume that the program control flows in a sequential manner and when a procedure is called, its control is transferred to the called procedure. When a called procedure is executed, it returns the control back to the caller. This type of control flow makes it easier to represent a series of activations in the form of a tree, known as the activation tree."
},
{
"code": null,
"e": 4375,
"s": 4308,
"text": "To understand this concept, we take a piece of code as an example:"
},
{
"code": null,
"e": 4596,
"s": 4375,
"text": ". . .\nprintf(“Enter Your Name: “);\nscanf(“%s”, username);\nshow_data(username);\nprintf(“Press any key to continue...”);\n. . .\nint show_data(char *user)\n {\n printf(“Your name is %s”, username);\n return 0;\n }\n. . . "
},
{
"code": null,
"e": 4644,
"s": 4596,
"text": "Below is the activation tree of the code given."
},
{
"code": null,
"e": 4800,
"s": 4644,
"text": "Now we understand that procedures are executed in depth-first manner, thus stack allocation is the best suitable form of storage for procedure activations."
},
{
"code": null,
"e": 4884,
"s": 4800,
"text": "Runtime environment manages runtime memory requirements for the following entities:"
},
{
"code": null,
"e": 5021,
"s": 4884,
"text": "Code : It is known as the text part of a program that does not change at runtime. Its memory requirements are known at the compile time."
},
{
"code": null,
"e": 5158,
"s": 5021,
"text": "Code : It is known as the text part of a program that does not change at runtime. Its memory requirements are known at the compile time."
},
{
"code": null,
"e": 5315,
"s": 5158,
"text": "Procedures : Their text part is static but they are called in a random manner. That is why, stack storage is used to manage procedure calls and activations."
},
{
"code": null,
"e": 5472,
"s": 5315,
"text": "Procedures : Their text part is static but they are called in a random manner. That is why, stack storage is used to manage procedure calls and activations."
},
{
"code": null,
"e": 5677,
"s": 5472,
"text": "Variables : Variables are known at the runtime only, unless they are global or constant. Heap memory allocation scheme is used for managing allocation and de-allocation of memory for variables in runtime."
},
{
"code": null,
"e": 5882,
"s": 5677,
"text": "Variables : Variables are known at the runtime only, unless they are global or constant. Heap memory allocation scheme is used for managing allocation and de-allocation of memory for variables in runtime."
},
{
"code": null,
"e": 6174,
"s": 5882,
"text": "In this allocation scheme, the compilation data is bound to a fixed location in the memory and it does not change when the program executes. As the memory requirement and storage locations are known in advance, runtime support package for memory allocation and de-allocation is not required."
},
{
"code": null,
"e": 6380,
"s": 6174,
"text": "Procedure calls and their activations are managed by means of stack memory allocation. It works in last-in-first-out (LIFO) method and this allocation strategy is very useful for recursive procedure calls."
},
{
"code": null,
"e": 6590,
"s": 6380,
"text": "Variables local to a procedure are allocated and de-allocated only at runtime. Heap allocation is used to dynamically allocate memory to the variables and claim it back when the variables are no more required."
},
{
"code": null,
"e": 6788,
"s": 6590,
"text": "Except statically allocated memory area, both stack and heap memory can grow and shrink dynamically and unexpectedly. Therefore, they cannot be provided with a fixed amount of memory in the system."
},
{
"code": null,
"e": 7016,
"s": 6788,
"text": "As shown in the image above, the text part of the code is allocated a fixed amount of memory. Stack and heap memory are arranged at the extremes of total memory allocated to the program. Both shrink and grow against each other."
},
{
"code": null,
"e": 7303,
"s": 7016,
"text": "The communication medium among procedures is known as parameter passing. The values of the variables from a calling procedure are transferred to the called procedure by some mechanism. Before moving ahead, first go through some basic terminologies pertaining to the values in a program."
},
{
"code": null,
"e": 7539,
"s": 7303,
"text": "The value of an expression is called its r-value. The value contained in a single variable also becomes an r-value if it appears on the right-hand side of the assignment operator. r-values can always be assigned to some other variable."
},
{
"code": null,
"e": 7713,
"s": 7539,
"text": "The location of memory (address) where an expression is stored is known as the l-value of that expression. It always appears at the left hand side of an assignment operator."
},
{
"code": null,
"e": 7726,
"s": 7713,
"text": "For example:"
},
{
"code": null,
"e": 7781,
"s": 7726,
"text": "day = 1;\nweek = day * 7;\nmonth = 1;\nyear = month * 12;"
},
{
"code": null,
"e": 8005,
"s": 7781,
"text": "From this example, we understand that constant values like 1, 7, 12, and variables like day, week, month and year, all have r-values. Only variables have l-values as they also represent the memory location assigned to them."
},
{
"code": null,
"e": 8018,
"s": 8005,
"text": "For example:"
},
{
"code": null,
"e": 8029,
"s": 8018,
"text": "7 = x + y;"
},
{
"code": null,
"e": 8108,
"s": 8029,
"text": "is an l-value error, as the constant 7 does not represent any memory location."
},
{
"code": null,
"e": 8276,
"s": 8108,
"text": "Variables that take the information passed by the caller procedure are called formal parameters. These variables are declared in the definition of the called function."
},
{
"code": null,
"e": 8448,
"s": 8276,
"text": "Variables whose values or addresses are being passed to the called procedure are called actual parameters. These variables are specified in the function call as arguments."
},
{
"code": null,
"e": 8457,
"s": 8448,
"text": "Example:"
},
{
"code": null,
"e": 8604,
"s": 8457,
"text": "fun_one()\n{\n int actual_parameter = 10;\n call fun_two(int actual_parameter);\n}\n fun_two(int formal_parameter)\n{\n print formal_parameter;\n}"
},
{
"code": null,
"e": 8754,
"s": 8604,
"text": "Formal parameters hold the information of the actual parameter, depending upon the parameter passing technique used. It may be a value or an address."
},
{
"code": null,
"e": 9098,
"s": 8754,
"text": "In pass by value mechanism, the calling procedure passes the r-value of actual parameters and the compiler puts that into the called procedure’s activation record. Formal parameters then hold the values passed by the calling procedure. If the values held by the formal parameters are changed, it should have no impact on the actual parameters."
},
{
"code": null,
"e": 9543,
"s": 9098,
"text": "In pass by reference mechanism, the l-value of the actual parameter is copied to the activation record of the called procedure. This way, the called procedure now has the address (memory location) of the actual parameter and the formal parameter refers to the same memory location. Therefore, if the value pointed by the formal parameter is changed, the impact should be seen on the actual parameter as they should also point to the same value."
},
{
"code": null,
"e": 10036,
"s": 9543,
"text": "This parameter passing mechanism works similar to ‘pass-by-reference’ except that the changes to actual parameters are made when the called procedure ends. Upon function call, the values of actual parameters are copied in the activation record of the called procedure. Formal parameters if manipulated have no real-time effect on actual parameters (as l-values are passed), but when the called procedure ends, the l-values of formal parameters are copied to the l-values of actual parameters."
},
{
"code": null,
"e": 10045,
"s": 10036,
"text": "Example:"
},
{
"code": null,
"e": 10268,
"s": 10045,
"text": "int y; \ncalling_procedure() \n{\n y = 10; \n copy_restore(y); //l-value of y is passed\n printf y; //prints 99 \n}\ncopy_restore(int x) \n{ \n x = 99; // y still has value 10 (unaffected)\n y = 0; // y is now 0 \n}"
},
{
"code": null,
"e": 10513,
"s": 10268,
"text": "When this function ends, the l-value of formal parameter x is copied to the actual parameter y. Even if the value of y is changed before the procedure ends, the l-value of x is copied to the l-value of y making it behave like call by reference."
},
{
"code": null,
"e": 10943,
"s": 10513,
"text": "Languages like Algol provide a new kind of parameter passing mechanism that works like preprocessor in C language. In pass by name mechanism, the name of the procedure being called is replaced by its actual body. Pass-by-name textually substitutes the argument expressions in a procedure call for the corresponding parameters in the body of the procedure so that it can now work on actual parameters, much like pass-by-reference."
},
{
"code": null,
"e": 10978,
"s": 10943,
"text": "\n 102 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 10997,
"s": 10978,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 11004,
"s": 10997,
"text": " Print"
},
{
"code": null,
"e": 11015,
"s": 11004,
"text": " Add Notes"
}
] |
Change the padding of a button with CSS
|
To change the padding of a button, use the padding property.
You can try to run the following code to change the button’s padding
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
.button {
background-color: yellow;
color: black;
text-align: center;
font-size: 15px;
padding: 10px;
}
</style>
</head>
<body>
<h2>Result</h2>
<p>Click below for result:</p>
<button class = "button">Result</button>
</body>
</html>
|
[
{
"code": null,
"e": 1123,
"s": 1062,
"text": "To change the padding of a button, use the padding property."
},
{
"code": null,
"e": 1192,
"s": 1123,
"text": "You can try to run the following code to change the button’s padding"
},
{
"code": null,
"e": 1202,
"s": 1192,
"text": "Live Demo"
},
{
"code": null,
"e": 1592,
"s": 1202,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n .button {\n background-color: yellow;\n color: black;\n text-align: center;\n font-size: 15px;\n padding: 10px;\n }\n </style>\n </head>\n <body>\n <h2>Result</h2>\n <p>Click below for result:</p>\n <button class = \"button\">Result</button>\n </body>\n</html>"
}
] |
Erlang - Web Programming
|
In Erlang, the inets library is available to build web servers in Erlang. Let’s look at some of the functions available in Erlang for web programming. One can implement the HTTP server, also referred to as httpd to handle HTTP requests.
The server implements numerous features, such as −
Secure Sockets Layer (SSL)
Erlang Scripting Interface (ESI)
Common Gateway Interface (CGI)
User Authentication (using Mnesia, Dets or plain text database)
Common Logfile Format (with or without disk_log(3) support)
URL Aliasing
Action Mappings
Directory Listings
The first job is to start the web library via the command.
inets:start()
The next step is to implement the start function of the inets library so that the web server can be implemented.
Following is an example of creating a web server process in Erlang.
-module(helloworld).
-export([start/0]).
start() ->
inets:start(),
Pid = inets:start(httpd, [{port, 8081}, {server_name,"httpd_test"},
{server_root,"D://tmp"},{document_root,"D://tmp/htdocs"},
{bind_address, "localhost"}]), io:fwrite("~p",[Pid]).
The following points need to be noted about the above program.
The port number needs to be unique and not used by any other program. The httpd service would be started on this port no.
The port number needs to be unique and not used by any other program. The httpd service would be started on this port no.
The server_root and document_root are mandatory parameters.
The server_root and document_root are mandatory parameters.
Following is the output of the above program.
{ok,<0.42.0>}
To implement a Hello world web server in Erlang, perform the following steps −
Step 1 − Implement the following code −
-module(helloworld).
-export([start/0,service/3]).
start() ->
inets:start(httpd, [
{modules, [
mod_alias,
mod_auth,
mod_esi,
mod_actions,
mod_cgi,
mod_dir,
mod_get,
mod_head,
mod_log,
mod_disk_log
]},
{port,8081},
{server_name,"helloworld"},
{server_root,"D://tmp"},
{document_root,"D://tmp/htdocs"},
{erl_script_alias, {"/erl", [helloworld]}},
{error_log, "error.log"},
{security_log, "security.log"},
{transfer_log, "transfer.log"},
{mime_types,[
{"html","text/html"}, {"css","text/css"}, {"js","application/x-javascript"} ]}
]).
service(SessionID, _Env, _Input) -> mod_esi:deliver(SessionID, [
"Content-Type: text/html\r\n\r\n", "<html><body>Hello, World!</body></html>" ]).
Step 2 − Run the code as follows. Compile the above file and then run the following commands in erl.
c(helloworld).
You will get the following output.
{ok,helloworld}
The next command is −
inets:start().
You will get the following output.
ok
The next command is −
helloworld:start().
You will get the following output.
{ok,<0.50.0>}
Step 3 − You can now access the url - http://localhost:8081/erl/hello_world:service.
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2538,
"s": 2301,
"text": "In Erlang, the inets library is available to build web servers in Erlang. Let’s look at some of the functions available in Erlang for web programming. One can implement the HTTP server, also referred to as httpd to handle HTTP requests."
},
{
"code": null,
"e": 2589,
"s": 2538,
"text": "The server implements numerous features, such as −"
},
{
"code": null,
"e": 2616,
"s": 2589,
"text": "Secure Sockets Layer (SSL)"
},
{
"code": null,
"e": 2649,
"s": 2616,
"text": "Erlang Scripting Interface (ESI)"
},
{
"code": null,
"e": 2680,
"s": 2649,
"text": "Common Gateway Interface (CGI)"
},
{
"code": null,
"e": 2744,
"s": 2680,
"text": "User Authentication (using Mnesia, Dets or plain text database)"
},
{
"code": null,
"e": 2804,
"s": 2744,
"text": "Common Logfile Format (with or without disk_log(3) support)"
},
{
"code": null,
"e": 2817,
"s": 2804,
"text": "URL Aliasing"
},
{
"code": null,
"e": 2833,
"s": 2817,
"text": "Action Mappings"
},
{
"code": null,
"e": 2852,
"s": 2833,
"text": "Directory Listings"
},
{
"code": null,
"e": 2911,
"s": 2852,
"text": "The first job is to start the web library via the command."
},
{
"code": null,
"e": 2926,
"s": 2911,
"text": "inets:start()\n"
},
{
"code": null,
"e": 3039,
"s": 2926,
"text": "The next step is to implement the start function of the inets library so that the web server can be implemented."
},
{
"code": null,
"e": 3107,
"s": 3039,
"text": "Following is an example of creating a web server process in Erlang."
},
{
"code": null,
"e": 3371,
"s": 3107,
"text": "-module(helloworld). \n-export([start/0]). \n\nstart() ->\n inets:start(), \n Pid = inets:start(httpd, [{port, 8081}, {server_name,\"httpd_test\"}, \n {server_root,\"D://tmp\"},{document_root,\"D://tmp/htdocs\"},\n {bind_address, \"localhost\"}]), io:fwrite(\"~p\",[Pid])."
},
{
"code": null,
"e": 3434,
"s": 3371,
"text": "The following points need to be noted about the above program."
},
{
"code": null,
"e": 3556,
"s": 3434,
"text": "The port number needs to be unique and not used by any other program. The httpd service would be started on this port no."
},
{
"code": null,
"e": 3678,
"s": 3556,
"text": "The port number needs to be unique and not used by any other program. The httpd service would be started on this port no."
},
{
"code": null,
"e": 3738,
"s": 3678,
"text": "The server_root and document_root are mandatory parameters."
},
{
"code": null,
"e": 3798,
"s": 3738,
"text": "The server_root and document_root are mandatory parameters."
},
{
"code": null,
"e": 3844,
"s": 3798,
"text": "Following is the output of the above program."
},
{
"code": null,
"e": 3859,
"s": 3844,
"text": "{ok,<0.42.0>}\n"
},
{
"code": null,
"e": 3938,
"s": 3859,
"text": "To implement a Hello world web server in Erlang, perform the following steps −"
},
{
"code": null,
"e": 3978,
"s": 3938,
"text": "Step 1 − Implement the following code −"
},
{
"code": null,
"e": 4881,
"s": 3978,
"text": "-module(helloworld). \n-export([start/0,service/3]). \n\nstart() ->\n inets:start(httpd, [ \n {modules, [ \n mod_alias, \n mod_auth, \n mod_esi, \n mod_actions, \n mod_cgi, \n mod_dir,\n mod_get, \n mod_head, \n mod_log, \n mod_disk_log \n ]}, \n \n {port,8081}, \n {server_name,\"helloworld\"}, \n {server_root,\"D://tmp\"}, \n {document_root,\"D://tmp/htdocs\"}, \n {erl_script_alias, {\"/erl\", [helloworld]}}, \n {error_log, \"error.log\"}, \n {security_log, \"security.log\"}, \n {transfer_log, \"transfer.log\"}, \n \n {mime_types,[ \n {\"html\",\"text/html\"}, {\"css\",\"text/css\"}, {\"js\",\"application/x-javascript\"} ]} \n ]). \n \nservice(SessionID, _Env, _Input) -> mod_esi:deliver(SessionID, [ \n \"Content-Type: text/html\\r\\n\\r\\n\", \"<html><body>Hello, World!</body></html>\" ])."
},
{
"code": null,
"e": 4982,
"s": 4881,
"text": "Step 2 − Run the code as follows. Compile the above file and then run the following commands in erl."
},
{
"code": null,
"e": 4998,
"s": 4982,
"text": "c(helloworld).\n"
},
{
"code": null,
"e": 5033,
"s": 4998,
"text": "You will get the following output."
},
{
"code": null,
"e": 5050,
"s": 5033,
"text": "{ok,helloworld}\n"
},
{
"code": null,
"e": 5072,
"s": 5050,
"text": "The next command is −"
},
{
"code": null,
"e": 5088,
"s": 5072,
"text": "inets:start().\n"
},
{
"code": null,
"e": 5123,
"s": 5088,
"text": "You will get the following output."
},
{
"code": null,
"e": 5127,
"s": 5123,
"text": "ok\n"
},
{
"code": null,
"e": 5149,
"s": 5127,
"text": "The next command is −"
},
{
"code": null,
"e": 5170,
"s": 5149,
"text": "helloworld:start().\n"
},
{
"code": null,
"e": 5205,
"s": 5170,
"text": "You will get the following output."
},
{
"code": null,
"e": 5220,
"s": 5205,
"text": "{ok,<0.50.0>}\n"
},
{
"code": null,
"e": 5305,
"s": 5220,
"text": "Step 3 − You can now access the url - http://localhost:8081/erl/hello_world:service."
},
{
"code": null,
"e": 5312,
"s": 5305,
"text": " Print"
},
{
"code": null,
"e": 5323,
"s": 5312,
"text": " Add Notes"
}
] |
C program to find the length of a string?
|
The string is actually a one-dimensional array of characters which is terminated by a null character '\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null.
To find the length of a string we need to loop and count all words in the loop until the ‘\0’ character is matched.
Input −naman
Output − string length is 5
Explanation − we need to iterate over each index of the string until reach the end of string means ‘\0’ which is the null character.
#include <stdio.h>
#include<string.h>
int main() {
char string1[]={"naman"};
int i=0, length;
while(string1[i] !='\0') {
i++;
}
length=i;
printf(" string length is %d",length);
return 0;
}
string length is 5
|
[
{
"code": null,
"e": 1268,
"s": 1062,
"text": "The string is actually a one-dimensional array of characters which is terminated by a null character '\\0'. Thus a null-terminated string contains the characters that comprise the string followed by a null."
},
{
"code": null,
"e": 1384,
"s": 1268,
"text": "To find the length of a string we need to loop and count all words in the loop until the ‘\\0’ character is matched."
},
{
"code": null,
"e": 1398,
"s": 1384,
"text": "Input −naman "
},
{
"code": null,
"e": 1426,
"s": 1398,
"text": "Output − string length is 5"
},
{
"code": null,
"e": 1560,
"s": 1426,
"text": "Explanation − we need to iterate over each index of the string until reach the end of string means ‘\\0’ which is the null character. "
},
{
"code": null,
"e": 1776,
"s": 1560,
"text": "#include <stdio.h>\n#include<string.h>\nint main() {\n char string1[]={\"naman\"};\n int i=0, length;\n while(string1[i] !='\\0') {\n i++;\n }\n length=i;\n printf(\" string length is %d\",length);\n return 0;\n}"
},
{
"code": null,
"e": 1795,
"s": 1776,
"text": "string length is 5"
}
] |
Powershell - Delete Folder
|
Remove-Item cmdlet is used to delete a directory by passing the path of the directory to be deleted.
In this example, we'll delete a folder D:\Temp\Test Folder1
Type the following command in PowerShell ISE Console
Remove-Item 'D:\temp\Test Folder1'
You can see the Test Folder1 in Windows Explorer is deleted now.
In this example, we'll remove the folder D:\Temp\Test Folder1 recursively. In first example, PowerShell confirms if directory is not empty. In this case, it will simply delete the item.
Type the following command in PowerShell ISE Console
Remove-Item 'D:\temp\Test Folder' -Recurse
You can see the content of temp folder in Windows Explorer where its folders are now removed.
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2135,
"s": 2034,
"text": "Remove-Item cmdlet is used to delete a directory by passing the path of the directory to be deleted."
},
{
"code": null,
"e": 2195,
"s": 2135,
"text": "In this example, we'll delete a folder D:\\Temp\\Test Folder1"
},
{
"code": null,
"e": 2248,
"s": 2195,
"text": "Type the following command in PowerShell ISE Console"
},
{
"code": null,
"e": 2283,
"s": 2248,
"text": "Remove-Item 'D:\\temp\\Test Folder1'"
},
{
"code": null,
"e": 2348,
"s": 2283,
"text": "You can see the Test Folder1 in Windows Explorer is deleted now."
},
{
"code": null,
"e": 2534,
"s": 2348,
"text": "In this example, we'll remove the folder D:\\Temp\\Test Folder1 recursively. In first example, PowerShell confirms if directory is not empty. In this case, it will simply delete the item."
},
{
"code": null,
"e": 2587,
"s": 2534,
"text": "Type the following command in PowerShell ISE Console"
},
{
"code": null,
"e": 2630,
"s": 2587,
"text": "Remove-Item 'D:\\temp\\Test Folder' -Recurse"
},
{
"code": null,
"e": 2724,
"s": 2630,
"text": "You can see the content of temp folder in Windows Explorer where its folders are now removed."
},
{
"code": null,
"e": 2759,
"s": 2724,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2780,
"s": 2759,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 2815,
"s": 2780,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2828,
"s": 2815,
"text": " Vijay Saini"
},
{
"code": null,
"e": 2865,
"s": 2828,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 2877,
"s": 2865,
"text": " Fettah Ben"
},
{
"code": null,
"e": 2884,
"s": 2877,
"text": " Print"
},
{
"code": null,
"e": 2895,
"s": 2884,
"text": " Add Notes"
}
] |
Bubble sort in Java.
|
Following is the required program.
Live Demo
public class Tester {
static void bubbleSort(int[] arr) {
int n = arr.length;
int temp = 0;
for(int i = 0; i < n; i++){
for(int j = 1; j < (n-i); j++){
if(arr[j-1] > arr[j]){
//swap elements
temp = arr[j-1];
arr[j-1] = arr[j];
arr[j] = temp;
}
}
}
}
public static void main(String[] args) {
int arr[] = {21,60,32,01,41,34,5};
System.out.println("Before Bubble Sort");
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
System.out.println();
bubbleSort(arr);
System.out.println("After Bubble Sort");
for(int i = 0; i < arr.length; i++){
System.out.print(arr[i] + " ");
}
}
}
Before Bubble Sort
21 60 32 1 41 34 5
After Bubble Sort
1 5 21 32 34 41 60
|
[
{
"code": null,
"e": 1097,
"s": 1062,
"text": "Following is the required program."
},
{
"code": null,
"e": 1107,
"s": 1097,
"text": "Live Demo"
},
{
"code": null,
"e": 1965,
"s": 1107,
"text": "public class Tester {\n static void bubbleSort(int[] arr) { \n int n = arr.length; \n int temp = 0; \n for(int i = 0; i < n; i++){ \n for(int j = 1; j < (n-i); j++){ \n if(arr[j-1] > arr[j]){ \n //swap elements \n temp = arr[j-1]; \n arr[j-1] = arr[j]; \n arr[j] = temp; \n } \n } \n }\n } \n public static void main(String[] args) { \n int arr[] = {21,60,32,01,41,34,5};\n System.out.println(\"Before Bubble Sort\"); \n for(int i = 0; i < arr.length; i++){ \n System.out.print(arr[i] + \" \"); \n } \n System.out.println(); \n bubbleSort(arr);\n System.out.println(\"After Bubble Sort\"); \n for(int i = 0; i < arr.length; i++){ \n System.out.print(arr[i] + \" \"); \n } \n }\n}"
},
{
"code": null,
"e": 2040,
"s": 1965,
"text": "Before Bubble Sort\n21 60 32 1 41 34 5\nAfter Bubble Sort\n1 5 21 32 34 41 60"
}
] |
GATE | GATE-CS-2017 (Set 2) | Question 62 - GeeksforGeeks
|
28 Jun, 2021
If a random variable X has a Poisson distribution with mean 5, then the expression E[(X + 2)2] equals _____.
Note: This question appeared as Numerical Answer Type.(A) 54(B) 55(C) 56(D) 57Answer: (A)Explanation:
Using Linearity of Expectation, we can write,
E[(X+2)2] = E[X2] + E[4X] + E[4]
In Poisson distribution, mean and variance are same.
Mean is given as 5. So variance should also be 5.
Also, variance = E[X2] – (E[X])2
5 = E[X2] – 25
E[X2] = 30
Thus E[(X+2)2] = 30 + 4*5 + 4 = 54.
Quiz of this Question
GATE-CS-2017 (Set 2)
GATE-GATE-CS-2017 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25695,
"s": 25667,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 25804,
"s": 25695,
"text": "If a random variable X has a Poisson distribution with mean 5, then the expression E[(X + 2)2] equals _____."
},
{
"code": null,
"e": 25906,
"s": 25804,
"text": "Note: This question appeared as Numerical Answer Type.(A) 54(B) 55(C) 56(D) 57Answer: (A)Explanation:"
},
{
"code": null,
"e": 26188,
"s": 25906,
"text": "Using Linearity of Expectation, we can write, \nE[(X+2)2] = E[X2] + E[4X] + E[4]\n\nIn Poisson distribution, mean and variance are same.\nMean is given as 5. So variance should also be 5.\nAlso, variance = E[X2] – (E[X])2\n5 = E[X2] – 25\nE[X2] = 30\n\nThus E[(X+2)2] = 30 + 4*5 + 4 = 54. "
},
{
"code": null,
"e": 26210,
"s": 26188,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 26231,
"s": 26210,
"text": "GATE-CS-2017 (Set 2)"
},
{
"code": null,
"e": 26257,
"s": 26231,
"text": "GATE-GATE-CS-2017 (Set 2)"
},
{
"code": null,
"e": 26262,
"s": 26257,
"text": "GATE"
},
{
"code": null,
"e": 26360,
"s": 26262,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26394,
"s": 26360,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 26428,
"s": 26394,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 26462,
"s": 26428,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 26495,
"s": 26462,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 26531,
"s": 26495,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 26567,
"s": 26531,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 26601,
"s": 26567,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 26635,
"s": 26601,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 26669,
"s": 26635,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
How to append a whole dataframe to a CSV in R ? - GeeksforGeeks
|
30 May, 2021
A data frame in R programming language is a tabular arrangement of rows and columns arranged in the form of a table. A CSV file also contains data stored together to form rows stacked together. Content can be read from and written to the CSV file. Base R contains multiple methods to work with these files. The write.csv() method overwrites the entire contents of the file. Therefore, it results in the deletion of original CSV content.
The modification is made to the contents of the file. If the row.names are set to TRUE, then the data may become ambiguous, since row numbers are appended to the beginning of the data and all the rows shift one position to the right side. The sep argument is necessary to discriminate between rows, otherwise incorrect results are produced.
Syntax:
write.table(df, csv- file , append = TRUE, sep = “,”, col.names = FALSE, row.names = FALSE)
Parameters :
df – The data frame to be appended
csv-file – The file name to append to
append – Indicator of whether to merge to existing contents or not
col.names – Indicator of whether to append column headings to the csv.
Row numbers are appended in the beginning of the row by default, beginning from integer value of 1.
Dataset in use:
Example:
R
# specifying the path of csv filepath <- "gfg.csv" # read contents of filecontent1 <- read.csv(path)print ("Original content") # displaying original contentprint (content1) # creating data frame to appenddata_frame <- data.frame(ID = c(8:9), Name = c("K","L"), Post= c("IT","Writer"), Age = c(18,27)) # writing contents of the filecontent <- write.table(data_frame , path, append = T , col.names = FALSE,sep = ",", row.names = F) # contents of the csv filecontent2 <- read.csv(path)print ("Modified content") # displaying modified contentprint (content2)
Output
[1] “Original content”
ID Name Post Age
1 5 H CA 67
2 6 K SDE 39
3 7 Z Admin 28
[1] “Modified content”
ID Name Post Age
1 5 H CA 67
2 6 K SDE 39
3 7 Z Admin 28
4 8 K IT 18
5 9 L Writer 27
In case, the col.names argument is set to TRUE, the column headings are appended as a row before the data. This leads to the display of column headings twice, and one extra row is returned in the result. The column names of the data frame may or may not be same as row headers of CSV file.
Example:
R
path <- "gfg.csv" content1 <- read.csv(path)print ("Original content")print (content1) # creating data frame to appenddata_frame <- data.frame(ID = c(8:9),Name = c("K","L"), Post= c("IT","Writer"),Age = c(18,27)) # writing contents of the filecontent <- write.table(data_frame , path, append = T , col.names = TRUE,sep = ",", row.names = F) # contents of the csv filecontent2 <- read.csv(path)print ("Modified content")print (content2)
Output
[1] “Original content”
ID Name Post Age
1 5 H CA 67
2 6 K SDE 39
3 7 Z Admin 28
[1] “Modified content”
ID Name Post Age
1 5 H CA 67
2 6 K SDE 39
3 7 Z Admin 28
4 ID Name Post Age
5 8 K IT 18
6 9 L Writer 27
Picked
R-CSV
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Change Axis Scales in R Plots?
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to import an Excel File into R ?
R - if statement
Time Series Analysis in R
How to filter R dataframe by multiple conditions?
|
[
{
"code": null,
"e": 26487,
"s": 26459,
"text": "\n30 May, 2021"
},
{
"code": null,
"e": 26925,
"s": 26487,
"text": "A data frame in R programming language is a tabular arrangement of rows and columns arranged in the form of a table. A CSV file also contains data stored together to form rows stacked together. Content can be read from and written to the CSV file. Base R contains multiple methods to work with these files. The write.csv() method overwrites the entire contents of the file. Therefore, it results in the deletion of original CSV content. "
},
{
"code": null,
"e": 27267,
"s": 26925,
"text": "The modification is made to the contents of the file. If the row.names are set to TRUE, then the data may become ambiguous, since row numbers are appended to the beginning of the data and all the rows shift one position to the right side. The sep argument is necessary to discriminate between rows, otherwise incorrect results are produced. "
},
{
"code": null,
"e": 27275,
"s": 27267,
"text": "Syntax:"
},
{
"code": null,
"e": 27367,
"s": 27275,
"text": "write.table(df, csv- file , append = TRUE, sep = “,”, col.names = FALSE, row.names = FALSE)"
},
{
"code": null,
"e": 27381,
"s": 27367,
"text": "Parameters : "
},
{
"code": null,
"e": 27416,
"s": 27381,
"text": "df – The data frame to be appended"
},
{
"code": null,
"e": 27455,
"s": 27416,
"text": "csv-file – The file name to append to "
},
{
"code": null,
"e": 27522,
"s": 27455,
"text": "append – Indicator of whether to merge to existing contents or not"
},
{
"code": null,
"e": 27593,
"s": 27522,
"text": "col.names – Indicator of whether to append column headings to the csv."
},
{
"code": null,
"e": 27694,
"s": 27593,
"text": "Row numbers are appended in the beginning of the row by default, beginning from integer value of 1. "
},
{
"code": null,
"e": 27710,
"s": 27694,
"text": "Dataset in use:"
},
{
"code": null,
"e": 27719,
"s": 27710,
"text": "Example:"
},
{
"code": null,
"e": 27721,
"s": 27719,
"text": "R"
},
{
"code": "# specifying the path of csv filepath <- \"gfg.csv\" # read contents of filecontent1 <- read.csv(path)print (\"Original content\") # displaying original contentprint (content1) # creating data frame to appenddata_frame <- data.frame(ID = c(8:9), Name = c(\"K\",\"L\"), Post= c(\"IT\",\"Writer\"), Age = c(18,27)) # writing contents of the filecontent <- write.table(data_frame , path, append = T , col.names = FALSE,sep = \",\", row.names = F) # contents of the csv filecontent2 <- read.csv(path)print (\"Modified content\") # displaying modified contentprint (content2)",
"e": 28399,
"s": 27721,
"text": null
},
{
"code": null,
"e": 28406,
"s": 28399,
"text": "Output"
},
{
"code": null,
"e": 28429,
"s": 28406,
"text": "[1] “Original content”"
},
{
"code": null,
"e": 28449,
"s": 28429,
"text": "ID Name Post Age"
},
{
"code": null,
"e": 28471,
"s": 28449,
"text": "1 5 H CA 67"
},
{
"code": null,
"e": 28493,
"s": 28471,
"text": "2 6 K SDE 39"
},
{
"code": null,
"e": 28516,
"s": 28493,
"text": "3 7 Z Admin 28 "
},
{
"code": null,
"e": 28539,
"s": 28516,
"text": "[1] “Modified content”"
},
{
"code": null,
"e": 28559,
"s": 28539,
"text": "ID Name Post Age"
},
{
"code": null,
"e": 28581,
"s": 28559,
"text": "1 5 H CA 67"
},
{
"code": null,
"e": 28603,
"s": 28581,
"text": "2 6 K SDE 39"
},
{
"code": null,
"e": 28625,
"s": 28603,
"text": "3 7 Z Admin 28"
},
{
"code": null,
"e": 28647,
"s": 28625,
"text": "4 8 K IT 18"
},
{
"code": null,
"e": 28669,
"s": 28647,
"text": "5 9 L Writer 27"
},
{
"code": null,
"e": 28960,
"s": 28669,
"text": "In case, the col.names argument is set to TRUE, the column headings are appended as a row before the data. This leads to the display of column headings twice, and one extra row is returned in the result. The column names of the data frame may or may not be same as row headers of CSV file. "
},
{
"code": null,
"e": 28969,
"s": 28960,
"text": "Example:"
},
{
"code": null,
"e": 28971,
"s": 28969,
"text": "R"
},
{
"code": "path <- \"gfg.csv\" content1 <- read.csv(path)print (\"Original content\")print (content1) # creating data frame to appenddata_frame <- data.frame(ID = c(8:9),Name = c(\"K\",\"L\"), Post= c(\"IT\",\"Writer\"),Age = c(18,27)) # writing contents of the filecontent <- write.table(data_frame , path, append = T , col.names = TRUE,sep = \",\", row.names = F) # contents of the csv filecontent2 <- read.csv(path)print (\"Modified content\")print (content2)",
"e": 29458,
"s": 28971,
"text": null
},
{
"code": null,
"e": 29465,
"s": 29458,
"text": "Output"
},
{
"code": null,
"e": 29488,
"s": 29465,
"text": "[1] “Original content”"
},
{
"code": null,
"e": 29508,
"s": 29488,
"text": "ID Name Post Age"
},
{
"code": null,
"e": 29530,
"s": 29508,
"text": "1 5 H CA 67"
},
{
"code": null,
"e": 29552,
"s": 29530,
"text": "2 6 K SDE 39"
},
{
"code": null,
"e": 29574,
"s": 29552,
"text": "3 7 Z Admin 28"
},
{
"code": null,
"e": 29597,
"s": 29574,
"text": "[1] “Modified content”"
},
{
"code": null,
"e": 29621,
"s": 29597,
"text": " ID Name Post Age "
},
{
"code": null,
"e": 29645,
"s": 29621,
"text": "1 5 H CA 67 "
},
{
"code": null,
"e": 29669,
"s": 29645,
"text": "2 6 K SDE 39 "
},
{
"code": null,
"e": 29693,
"s": 29669,
"text": "3 7 Z Admin 28 "
},
{
"code": null,
"e": 29717,
"s": 29693,
"text": "4 ID Name Post Age "
},
{
"code": null,
"e": 29741,
"s": 29717,
"text": "5 8 K IT 18 "
},
{
"code": null,
"e": 29764,
"s": 29741,
"text": "6 9 L Writer 27"
},
{
"code": null,
"e": 29771,
"s": 29764,
"text": "Picked"
},
{
"code": null,
"e": 29777,
"s": 29771,
"text": "R-CSV"
},
{
"code": null,
"e": 29788,
"s": 29777,
"text": "R Language"
},
{
"code": null,
"e": 29886,
"s": 29788,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29938,
"s": 29886,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 29973,
"s": 29938,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 30011,
"s": 29973,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 30069,
"s": 30011,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 30112,
"s": 30069,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 30161,
"s": 30112,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 30198,
"s": 30161,
"text": "How to import an Excel File into R ?"
},
{
"code": null,
"e": 30215,
"s": 30198,
"text": "R - if statement"
},
{
"code": null,
"e": 30241,
"s": 30215,
"text": "Time Series Analysis in R"
}
] |
How to use aplay and spd-say command in Linux? - GeeksforGeeks
|
03 Aug, 2021
We can send the text to the terminal to play that as an audio clip. These are basically command-line audio player and works using Linux Sound Architecture. To send audio to the terminal to play, you can use aplay and spd-say command as shown below.
1. aplay: This command in linux is used to play the audio file.
Syntax:
aplay filename
Example:
Here, the maybe-next-time.wav is the audio file that we are playing. This command is especially for the Advanced Linux Sound Architecture) sound card drivers.
2. spd-say This command in linux is used to play the given text as the sound. Basically, this works as text to speech converter.
Syntax:
spd-say "Your text"
Example:
sagar0719kumar
linux-command
Picked
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ZIP command in Linux with examples
TCP Server-Client implementation in C
SORT command in Linux/Unix with examples
tar command in Linux with examples
curl command in Linux with Examples
Conditional Statements | Shell Script
diff command in Linux with examples
Tail command in Linux with examples
UDP Server-Client implementation in C
scp command in Linux with Examples
|
[
{
"code": null,
"e": 25489,
"s": 25461,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 25739,
"s": 25489,
"text": "We can send the text to the terminal to play that as an audio clip. These are basically command-line audio player and works using Linux Sound Architecture. To send audio to the terminal to play, you can use aplay and spd-say command as shown below. "
},
{
"code": null,
"e": 25804,
"s": 25739,
"text": "1. aplay: This command in linux is used to play the audio file. "
},
{
"code": null,
"e": 25814,
"s": 25804,
"text": "Syntax: "
},
{
"code": null,
"e": 25829,
"s": 25814,
"text": "aplay filename"
},
{
"code": null,
"e": 25839,
"s": 25829,
"text": "Example: "
},
{
"code": null,
"e": 26001,
"s": 25841,
"text": "Here, the maybe-next-time.wav is the audio file that we are playing. This command is especially for the Advanced Linux Sound Architecture) sound card drivers. "
},
{
"code": null,
"e": 26131,
"s": 26001,
"text": "2. spd-say This command in linux is used to play the given text as the sound. Basically, this works as text to speech converter. "
},
{
"code": null,
"e": 26141,
"s": 26131,
"text": "Syntax: "
},
{
"code": null,
"e": 26161,
"s": 26141,
"text": "spd-say \"Your text\""
},
{
"code": null,
"e": 26171,
"s": 26161,
"text": "Example: "
},
{
"code": null,
"e": 26190,
"s": 26175,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 26204,
"s": 26190,
"text": "linux-command"
},
{
"code": null,
"e": 26211,
"s": 26204,
"text": "Picked"
},
{
"code": null,
"e": 26222,
"s": 26211,
"text": "Linux-Unix"
},
{
"code": null,
"e": 26320,
"s": 26222,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26355,
"s": 26320,
"text": "ZIP command in Linux with examples"
},
{
"code": null,
"e": 26393,
"s": 26355,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 26434,
"s": 26393,
"text": "SORT command in Linux/Unix with examples"
},
{
"code": null,
"e": 26469,
"s": 26434,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 26505,
"s": 26469,
"text": "curl command in Linux with Examples"
},
{
"code": null,
"e": 26543,
"s": 26505,
"text": "Conditional Statements | Shell Script"
},
{
"code": null,
"e": 26579,
"s": 26543,
"text": "diff command in Linux with examples"
},
{
"code": null,
"e": 26615,
"s": 26579,
"text": "Tail command in Linux with examples"
},
{
"code": null,
"e": 26653,
"s": 26615,
"text": "UDP Server-Client implementation in C"
}
] |
Kolmogorov-Smirnov Test (KS Test) - GeeksforGeeks
|
10 Jun, 2020
Kolmogorov–Smirnov test a very efficient way to determine if two samples are significantly different from each other. It is usually used to check the uniformity of random numbers. Uniformity is one of the most important properties of any random number generator and Kolmogorov–Smirnov test can be used to test it.
The Kolmogorov–Smirnov test may also be used to test whether two underlying one-dimensional probability distributions differ. It is a very efficient way to determine if two samples are significantly different from each other.
The Kolmogorov–Smirnov statistic quantifies a distance between the empirical distribution function of the sample and the cumulative distribution function of the reference distribution, or between the empirical distribution functions of two samples.
To use the test for checking the uniformity of random numbers, we use the CDF (cumulative distribution function) of U[0, 1].
F(x)= x for 0<=x<=1
Empirical CDF, Sn(x)= (number of R1, R2...Rn < x)/N array of random numbers, the random numbers must be in the range of [0, 1].
H0(Null Hypothesis): Null hypothesis assumes that the numbers are uniformly distributed between 0-1. If we are able to reject the Null Hypothesis, this means that the numbers are not uniformly distributed between 0-1. Failure to reject the Null Hypothesis although does not necessarily mean that the numbers follow the uniform distribution.
Algorithm:
-> Rank the N random numbers in ascending order.
-> Calculate D+ as max(i/N-Ri) for all i in(1, N)
-> Calculate D- as max(Ri-((i-1)/N)) for all i in(1, N)
-> Calculate D as max(sqrt(N) * D+, sqrt(N) * D-)
-> If D>D(alpha)
Rejects Uniformity
else
It fails to reject the Null Hypothesis.
Below is the Python implementation of above algorithm :
import random N = int(input("Enter the size of random numbers to be produced : "))D_plus =[]D_minus =[]_random =[] # Rank the N random numbersfor i in range(0, N): _random.append(random.random()) _random.sort() # Calculate max(i/N-Ri)for i in range(1, N + 1): x = i / N - _random[i-1] D_plus.append(x) # Calculate max(Ri-((i-1)/N))for i in range(1, N + 1): y =(i-1)/N y =_random[i-1]-y D_minus.append(y) # Calculate max(D+, D-)ans = max(sqrt(N) * D_plus, sqrt(N) * D_minus)print("Value of D is :")print(ans)
Reference – https://dl.acm.org/doi/pdf/10.1145/355719.355724
ardadrl
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Linear Regression
Reinforcement learning
Decision Tree
Activation functions in Neural Networks
Introduction to Recurrent Neural Network
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": 25545,
"s": 25517,
"text": "\n10 Jun, 2020"
},
{
"code": null,
"e": 25859,
"s": 25545,
"text": "Kolmogorov–Smirnov test a very efficient way to determine if two samples are significantly different from each other. It is usually used to check the uniformity of random numbers. Uniformity is one of the most important properties of any random number generator and Kolmogorov–Smirnov test can be used to test it."
},
{
"code": null,
"e": 26085,
"s": 25859,
"text": "The Kolmogorov–Smirnov test may also be used to test whether two underlying one-dimensional probability distributions differ. It is a very efficient way to determine if two samples are significantly different from each other."
},
{
"code": null,
"e": 26334,
"s": 26085,
"text": "The Kolmogorov–Smirnov statistic quantifies a distance between the empirical distribution function of the sample and the cumulative distribution function of the reference distribution, or between the empirical distribution functions of two samples."
},
{
"code": null,
"e": 26459,
"s": 26334,
"text": "To use the test for checking the uniformity of random numbers, we use the CDF (cumulative distribution function) of U[0, 1]."
},
{
"code": null,
"e": 26479,
"s": 26459,
"text": "F(x)= x for 0<=x<=1"
},
{
"code": null,
"e": 26607,
"s": 26479,
"text": "Empirical CDF, Sn(x)= (number of R1, R2...Rn < x)/N array of random numbers, the random numbers must be in the range of [0, 1]."
},
{
"code": null,
"e": 26948,
"s": 26607,
"text": "H0(Null Hypothesis): Null hypothesis assumes that the numbers are uniformly distributed between 0-1. If we are able to reject the Null Hypothesis, this means that the numbers are not uniformly distributed between 0-1. Failure to reject the Null Hypothesis although does not necessarily mean that the numbers follow the uniform distribution."
},
{
"code": null,
"e": 26959,
"s": 26948,
"text": "Algorithm:"
},
{
"code": null,
"e": 27257,
"s": 26959,
"text": "-> Rank the N random numbers in ascending order.\n-> Calculate D+ as max(i/N-Ri) for all i in(1, N)\n-> Calculate D- as max(Ri-((i-1)/N)) for all i in(1, N)\n-> Calculate D as max(sqrt(N) * D+, sqrt(N) * D-)\n-> If D>D(alpha) \n Rejects Uniformity\n else\n It fails to reject the Null Hypothesis."
},
{
"code": null,
"e": 27313,
"s": 27257,
"text": "Below is the Python implementation of above algorithm :"
},
{
"code": "import random N = int(input(\"Enter the size of random numbers to be produced : \"))D_plus =[]D_minus =[]_random =[] # Rank the N random numbersfor i in range(0, N): _random.append(random.random()) _random.sort() # Calculate max(i/N-Ri)for i in range(1, N + 1): x = i / N - _random[i-1] D_plus.append(x) # Calculate max(Ri-((i-1)/N))for i in range(1, N + 1): y =(i-1)/N y =_random[i-1]-y D_minus.append(y) # Calculate max(D+, D-)ans = max(sqrt(N) * D_plus, sqrt(N) * D_minus)print(\"Value of D is :\")print(ans)",
"e": 27847,
"s": 27313,
"text": null
},
{
"code": null,
"e": 27908,
"s": 27847,
"text": "Reference – https://dl.acm.org/doi/pdf/10.1145/355719.355724"
},
{
"code": null,
"e": 27916,
"s": 27908,
"text": "ardadrl"
},
{
"code": null,
"e": 27933,
"s": 27916,
"text": "Machine Learning"
},
{
"code": null,
"e": 27940,
"s": 27933,
"text": "Python"
},
{
"code": null,
"e": 27957,
"s": 27940,
"text": "Machine Learning"
},
{
"code": null,
"e": 28055,
"s": 27957,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28078,
"s": 28055,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 28101,
"s": 28078,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 28115,
"s": 28101,
"text": "Decision Tree"
},
{
"code": null,
"e": 28155,
"s": 28115,
"text": "Activation functions in Neural Networks"
},
{
"code": null,
"e": 28196,
"s": 28155,
"text": "Introduction to Recurrent Neural Network"
},
{
"code": null,
"e": 28224,
"s": 28196,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 28274,
"s": 28224,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 28296,
"s": 28274,
"text": "Python map() function"
}
] |
What are the C programming concepts used as Data Structures - GeeksforGeeks
|
13 Dec, 2021
Data-type in simple terms gives us information about the type of data. Example, integer, character, etc. Data-types in C language are declarations for the variables. Data-types are classified as:
Some of the examples of primitive data types are as follows
Variable named ch refers to the memory address 100, has occupied 1 byte of memory, which holds the value of char datatype ‘A’.
num is of integer type referring to the memory address 200, has occupied 4 bytes of memory, and holds value 123456.
marks is of double type, referring to the memory location 300, has occupied 8 bytes of memory, and holds value 97.123456.
Note: These addresses(100, 200 & 300) are just for understanding purpose, actual addresses are large hexadecimal numbers.
An Array is a variable that can store multiple values of the same datatype. Array is a contiguous memory segment.
Example:
If you want to store 100 integers, you can use one array instead of using 100 different integer variables.
Syntax for declaration of array:
data_type array_name[array_size];
Amount of space allocated = sizeof(data_type) * array_size
Example: Declare an array that can hold values of 4 integers
int arr[4];
In this case, sizeof(int) = 4. Therefore, 4*4 = 16 bytes of memory is reserved for array.
Array declaration & Initialization Example:
int arr[5] = {10, 20, 30, 40, 50};
Array elements can be accessed using indices, which range from 0 to (array_size-1).
Below is the sample code for the usage of arrays in C:
C
// C implementation to demonstrate// the usage of arrays #include <stdio.h> int main(){ // Array Indexs-0 1 2 3 4 int arr[5] = { 10, 20, 30, 40, 50 }; int size = sizeof(arr); printf("Size of array is %d\n", size); printf("Data at index 2 is %d\n", arr[2]);}
Size of array is 20
Data at index 2 is 30
We have used primitive data types to store data. But what if the data we want to store is more complex?
Let’s consider an example, we want to store information of the students in a class in a single variable. So, a student has :
Roll Number
Name
Here, Roll number is of integer type and Name is string(array of characters) type.
Here, is the solution: structures
Structure is a collection of variables(can be of different data types), under a single name.
It is also a contiguous memory segment like array, but it allows data members of different data types.
Syntax to define structures:
struct structure_name
{
datatype member1_name;
datatype member2_name;
..
datatype membern_name;
};
Example:
struct student
{
int roll_number;
char name[20];
};
Now we have newly defined data type, struct student. We can create it’s variables.
Syntax for variable declaration:
struct structure_name variable_name;
Example:
struct student ram;
// Members of structures can
// be accessed using "." operator
stu.roll_number = 64;
stu.name = “Saurabh”;
No memory is allocated when we define a structure.
Size of structure is equal to total amount of space consumed by each data member.
Example:
In case of student structure, it is 4 + 20 = 24 bytes
Below is the illustration of structures with the help of code:
C
// C implementation to demonstrate// the usage of structures #include <stdio.h>#include <string.h> // Structure Definitionstruct student { // data members int roll_no; // 4 bytes char name[20]; // 20 bytes}; int main(){ // Structure variable Declaration struct student stu; stu.roll_no = 64; strcpy(stu.name, "Saurabh"); printf("Structure Data\n"); printf("Roll No: %d\n", stu.roll_no); printf("Name: %s\n", stu.name); int size = sizeof(stu); printf("Size of Structure student"); printf("is %d", size);}
Structure Data
Roll No: 64
Name: Saurabh
Size of Structure studentis 24
Pointers are the special type of variables that stores the address, rather than the value of the variable.
They are used for indirect access of variables.
If var is the name of variable, then &var gives the address of var.
Remembered the ampersand(&) symbol used in scanf function
scanf(“%d”, &var);
This is because we assign the values scanned to the memory location of var.
We are not interested in addresses, but the values stored at that address.
Syntax for declaration of pointer:
data_type* pointer_name; // (* = asterisk)
Example:
int* ptr;
Pointer may point to any datatypeIt can hold address of any variable of the datatype it is pointing to.An uninitialized pointer variable has NULL value.
Example:
int* ptr;
int num = 5;
ptr = #
To get the value at the address, the pointer is pointing to, we use asterisk(*) operator.
So, in the above example, the ptr is holding address 250 and the value at address is 5.
Hence, *ptr is equal to 5.
Below is the illustration of the pointers with the help of code:
C
// C implementation to demonstrate// pointers in C #include <stdio.h> int main(){ int* ptr; int num = 5; ptr = # // This gives address of num printf("Value at ptr is %p\n", ptr); // This gives value at num printf("Value at *ptr is %d\n", *ptr);}
Value at ptr is 0x7ffdff4dca9c
Value at *ptr is 5
Size of Pointer variable is always constant in a system, irrespective of the datatype it is pointing to and it is usually 8 bytes.
Pointer to the structure can be declared as normal variable.
Example:
struct student *p;
Here, p is pointer and *p is the structure
Hence, to access the data members, we have to use
(*p).roll_no
(*p).name
C provides a special operator for accessing the data members via pointer i.e. -> arrow operator.
Note: (*p).x equivalent to p->x
Below is the illustration of the pointers to the structure:
C
// C implementation to illustrate// the code of the structures #include <stdio.h>#include <stdlib.h> // Structure Definitionstruct student { int roll_no; char name[20];}; int main(){ struct student* p; p = (struct student*) malloc(sizeof(struct student)); // Arrow operator p->roll_no = 99; printf("The value at roll"); printf("number is %d", p->roll_no); return 0;}
The value at rollnumber is 99
A function is a block of code that performs a specific task.
A function may have an input, performs so tasks, then may provide some output.
In the above example, we are giving inputs as 2 numbers to a function. It is performing function of addition. Then, it is return the sum of the two inputted numbers.
Inputs are called are parameters of the function
Output is called a return value
Functions can be classified into two categories:
These are defined in the standard library of C language. We don’t have to define these functions, only thing needed is to call these functions. We just need to know the proper syntax and we can readily use these functions.
Example:
printf(), scanf(), main(), etc are the predefined function.
These are the function, defined by the programmer to execute some task in the program.
Dividing a complex problem into smaller chunks makes our program easy to understand.
To use the user-defined function, we have to perform two steps
Defining functionCalling function
Defining function
Calling function
Syntax of function definition:
return_type function_name(<parameters_list>)
{
--tasks/operations--
return return_value;
}
Note:
A function can have 0 or more parameters.A function can have 0 or 1 return value.Function that doesn’t return anything has return type void.
A function can have 0 or more parameters.
A function can have 0 or 1 return value.
Function that doesn’t return anything has return type void.
Below is the illustration of the functions in C:
C
// C implementation to// illustrate functions in C #include <stdio.h> // program to demonstrate functions// function definition// function to print something void print(){ printf("GeeksforGeeks\n");} // Function to add two numbersint add(int a, int b){ int sum; sum = a + b; return sum;} // Main Functionint main(){ int res; // Function call print(); res = add(5, 7); printf("Sum is %d", res);}
GeeksforGeeks
Sum is 12
Note: The type passed in the function call should be compatible with the received by the function body as a parameter. Else, it will cause compilation error.
When we call function by passing value(as in above program), values of original variables are unaffected.
Instead of sending original variable, it sends copy of a variable.
Below is the illustration of the function call by passing value in C:
C
// C implementation for the// function call by passing value #include <stdio.h> // Function pass by valuevoid increase_by_one(int x){ x++;} int main(){ int num = 5; printf("Value before function"); printf(" call %d\n", num); increase_by_one(num); printf("Value after function"); printf(" call %d\n", num);}
Value before function call 5
Value after function call 5
In this program, we have passed variable a to the function, which was holding value 5. Then, we incremented the value of variable received by function i.e. x by 1. So, value of x now is 6. But, this change is limited to function scope only. The value of a in main will still be 5.
If we want to change value of the variable passed, we have to pass the variable by address.
This method uses the same variable instead of creating its new copy.
Below is the code of the function call by passing address:
C
// C implementation to demonstrate// the usage of function call by// passing reference #include <stdio.h> // function to demonstrate// call by valuevoid increase_by_one(int* x){ (*x)++;} int main(){ int num = 5; printf("Value before function"); printf(" call %d\n", num); increase_by_one(&num); printf("Value after function"); printf(" call %d\n", num);}
Value before function call 5
Value after function call 6
As we are passing address of variable, we have to receive it as pointer variable.
C
// C implementation to demonstrate// the example of the passing as// parameter in the function #include <stdio.h> // Function to print the arrayvoid print_array(int arr[], int n){ // N is size of array int i; for (i = 0; i < n; i++) printf("%d ", arr[i]);} int main(){ int arr[5] = { 10, 20, 30, 40, 50 }; // Function Call print_array(arr, 5);}
10 20 30 40 50
Type casting is basically conversion of one datatype into another.
Syntax of type casting:
var2 = (datatype2) var1
where,
var1 is of datatype1 & var2 is of datatype2
Example:
If you want to convert value of an integer variable into float variable
float x = (float)7/5;
To learn more about typecasting, refer Type Conversion in C
As you know, an array is a collection of a fixed number of values. Once the size of an array is declared, you cannot change it.
Sometimes the size of an array you declare may be insufficient. To solve this issue, you can allocate memory dynamically at runtime. This is known as dynamic memory allocation.
Predefined functions used in dynamic memory allocation:
malloc stands for memory allocation.
The malloc() function reserves a block of memory of the specified number of bytes and void* which can be casted into pointers of any form.
Syntax of malloc():
pointer_name = (cast_datatype*)malloc(size);
Dynamically allocated memory using malloc() doesn’t get freed on its own. You must explicitly use free() to release this space.
Syntax for free:
free(pointer_name);
Note: These functions are declared in header file stdlib.h. To use these functions, you must first include this header.
Below is the illustration of the Dynamic Memory Allocation in C:
C
// C implementation to demonstrate// the code the Dynamic Memory// Allocation #include <stdio.h>#include <stdlib.h> int main(){ int* ptr; int n = 5, i; ptr = (int*)malloc(n * sizeof(int)); for (i = 0; i < n; i++) ptr[i] = i; printf("\nArray Elements are\n"); for (i = 0; i < n; i++) printf("%d ", ptr[i]); free(ptr);}
Array Elements are
0 1 2 3 4
To learn more about Dynamic Memory Allocation, refer Dynamic Memory Allocation in C
nidhi_biet
varshagumber28
anikaseth98
sooda367
C-Arrays
C-Data Types
C-Dynamic Memory Allocation
C-Structure & Union
Arrays
C Language
Data Structures
Data Structures
Arrays
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
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
Substring in C++
Multidimensional Arrays in C / C++
|
[
{
"code": null,
"e": 26065,
"s": 26037,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 26261,
"s": 26065,
"text": "Data-type in simple terms gives us information about the type of data. Example, integer, character, etc. Data-types in C language are declarations for the variables. Data-types are classified as:"
},
{
"code": null,
"e": 26322,
"s": 26261,
"text": "Some of the examples of primitive data types are as follows "
},
{
"code": null,
"e": 26449,
"s": 26322,
"text": "Variable named ch refers to the memory address 100, has occupied 1 byte of memory, which holds the value of char datatype ‘A’."
},
{
"code": null,
"e": 26565,
"s": 26449,
"text": "num is of integer type referring to the memory address 200, has occupied 4 bytes of memory, and holds value 123456."
},
{
"code": null,
"e": 26687,
"s": 26565,
"text": "marks is of double type, referring to the memory location 300, has occupied 8 bytes of memory, and holds value 97.123456."
},
{
"code": null,
"e": 26809,
"s": 26687,
"text": "Note: These addresses(100, 200 & 300) are just for understanding purpose, actual addresses are large hexadecimal numbers."
},
{
"code": null,
"e": 26923,
"s": 26809,
"text": "An Array is a variable that can store multiple values of the same datatype. Array is a contiguous memory segment."
},
{
"code": null,
"e": 26932,
"s": 26923,
"text": "Example:"
},
{
"code": null,
"e": 27039,
"s": 26932,
"text": "If you want to store 100 integers, you can use one array instead of using 100 different integer variables."
},
{
"code": null,
"e": 27072,
"s": 27039,
"text": "Syntax for declaration of array:"
},
{
"code": null,
"e": 27108,
"s": 27072,
"text": "data_type array_name[array_size];"
},
{
"code": null,
"e": 27167,
"s": 27108,
"text": "Amount of space allocated = sizeof(data_type) * array_size"
},
{
"code": null,
"e": 27228,
"s": 27167,
"text": "Example: Declare an array that can hold values of 4 integers"
},
{
"code": null,
"e": 27240,
"s": 27228,
"text": "int arr[4];"
},
{
"code": null,
"e": 27330,
"s": 27240,
"text": "In this case, sizeof(int) = 4. Therefore, 4*4 = 16 bytes of memory is reserved for array."
},
{
"code": null,
"e": 27374,
"s": 27330,
"text": "Array declaration & Initialization Example:"
},
{
"code": null,
"e": 27409,
"s": 27374,
"text": "int arr[5] = {10, 20, 30, 40, 50};"
},
{
"code": null,
"e": 27493,
"s": 27409,
"text": "Array elements can be accessed using indices, which range from 0 to (array_size-1)."
},
{
"code": null,
"e": 27548,
"s": 27493,
"text": "Below is the sample code for the usage of arrays in C:"
},
{
"code": null,
"e": 27550,
"s": 27548,
"text": "C"
},
{
"code": "// C implementation to demonstrate// the usage of arrays #include <stdio.h> int main(){ // Array Indexs-0 1 2 3 4 int arr[5] = { 10, 20, 30, 40, 50 }; int size = sizeof(arr); printf(\"Size of array is %d\\n\", size); printf(\"Data at index 2 is %d\\n\", arr[2]);}",
"e": 27834,
"s": 27550,
"text": null
},
{
"code": null,
"e": 27876,
"s": 27834,
"text": "Size of array is 20\nData at index 2 is 30"
},
{
"code": null,
"e": 27980,
"s": 27876,
"text": "We have used primitive data types to store data. But what if the data we want to store is more complex?"
},
{
"code": null,
"e": 28105,
"s": 27980,
"text": "Let’s consider an example, we want to store information of the students in a class in a single variable. So, a student has :"
},
{
"code": null,
"e": 28117,
"s": 28105,
"text": "Roll Number"
},
{
"code": null,
"e": 28122,
"s": 28117,
"text": "Name"
},
{
"code": null,
"e": 28206,
"s": 28122,
"text": "Here, Roll number is of integer type and Name is string(array of characters) type. "
},
{
"code": null,
"e": 28240,
"s": 28206,
"text": "Here, is the solution: structures"
},
{
"code": null,
"e": 28333,
"s": 28240,
"text": "Structure is a collection of variables(can be of different data types), under a single name."
},
{
"code": null,
"e": 28436,
"s": 28333,
"text": "It is also a contiguous memory segment like array, but it allows data members of different data types."
},
{
"code": null,
"e": 28465,
"s": 28436,
"text": "Syntax to define structures:"
},
{
"code": null,
"e": 28576,
"s": 28465,
"text": "struct structure_name\n{\n datatype member1_name;\n datatype member2_name;\n ..\n datatype membern_name;\n};"
},
{
"code": null,
"e": 28585,
"s": 28576,
"text": "Example:"
},
{
"code": null,
"e": 28643,
"s": 28585,
"text": "struct student\n{\n int roll_number;\n char name[20];\n};"
},
{
"code": null,
"e": 28726,
"s": 28643,
"text": "Now we have newly defined data type, struct student. We can create it’s variables."
},
{
"code": null,
"e": 28759,
"s": 28726,
"text": "Syntax for variable declaration:"
},
{
"code": null,
"e": 28796,
"s": 28759,
"text": "struct structure_name variable_name;"
},
{
"code": null,
"e": 28806,
"s": 28796,
"text": "Example: "
},
{
"code": null,
"e": 28936,
"s": 28806,
"text": "struct student ram;\n\n// Members of structures can\n// be accessed using \".\" operator\nstu.roll_number = 64;\nstu.name = “Saurabh”;"
},
{
"code": null,
"e": 28988,
"s": 28936,
"text": "No memory is allocated when we define a structure. "
},
{
"code": null,
"e": 29071,
"s": 28988,
"text": "Size of structure is equal to total amount of space consumed by each data member. "
},
{
"code": null,
"e": 29080,
"s": 29071,
"text": "Example:"
},
{
"code": null,
"e": 29134,
"s": 29080,
"text": "In case of student structure, it is 4 + 20 = 24 bytes"
},
{
"code": null,
"e": 29197,
"s": 29134,
"text": "Below is the illustration of structures with the help of code:"
},
{
"code": null,
"e": 29199,
"s": 29197,
"text": "C"
},
{
"code": "// C implementation to demonstrate// the usage of structures #include <stdio.h>#include <string.h> // Structure Definitionstruct student { // data members int roll_no; // 4 bytes char name[20]; // 20 bytes}; int main(){ // Structure variable Declaration struct student stu; stu.roll_no = 64; strcpy(stu.name, \"Saurabh\"); printf(\"Structure Data\\n\"); printf(\"Roll No: %d\\n\", stu.roll_no); printf(\"Name: %s\\n\", stu.name); int size = sizeof(stu); printf(\"Size of Structure student\"); printf(\"is %d\", size);}",
"e": 29746,
"s": 29199,
"text": null
},
{
"code": null,
"e": 29818,
"s": 29746,
"text": "Structure Data\nRoll No: 64\nName: Saurabh\nSize of Structure studentis 24"
},
{
"code": null,
"e": 29925,
"s": 29818,
"text": "Pointers are the special type of variables that stores the address, rather than the value of the variable."
},
{
"code": null,
"e": 29973,
"s": 29925,
"text": "They are used for indirect access of variables."
},
{
"code": null,
"e": 30041,
"s": 29973,
"text": "If var is the name of variable, then &var gives the address of var."
},
{
"code": null,
"e": 30099,
"s": 30041,
"text": "Remembered the ampersand(&) symbol used in scanf function"
},
{
"code": null,
"e": 30118,
"s": 30099,
"text": "scanf(“%d”, &var);"
},
{
"code": null,
"e": 30194,
"s": 30118,
"text": "This is because we assign the values scanned to the memory location of var."
},
{
"code": null,
"e": 30269,
"s": 30194,
"text": "We are not interested in addresses, but the values stored at that address."
},
{
"code": null,
"e": 30304,
"s": 30269,
"text": "Syntax for declaration of pointer:"
},
{
"code": null,
"e": 30357,
"s": 30304,
"text": "data_type* pointer_name; // (* = asterisk) "
},
{
"code": null,
"e": 30366,
"s": 30357,
"text": "Example:"
},
{
"code": null,
"e": 30376,
"s": 30366,
"text": "int* ptr;"
},
{
"code": null,
"e": 30529,
"s": 30376,
"text": "Pointer may point to any datatypeIt can hold address of any variable of the datatype it is pointing to.An uninitialized pointer variable has NULL value."
},
{
"code": null,
"e": 30538,
"s": 30529,
"text": "Example:"
},
{
"code": null,
"e": 30573,
"s": 30538,
"text": "int* ptr;\nint num = 5;\nptr = #"
},
{
"code": null,
"e": 30663,
"s": 30573,
"text": "To get the value at the address, the pointer is pointing to, we use asterisk(*) operator."
},
{
"code": null,
"e": 30751,
"s": 30663,
"text": "So, in the above example, the ptr is holding address 250 and the value at address is 5."
},
{
"code": null,
"e": 30778,
"s": 30751,
"text": "Hence, *ptr is equal to 5."
},
{
"code": null,
"e": 30843,
"s": 30778,
"text": "Below is the illustration of the pointers with the help of code:"
},
{
"code": null,
"e": 30845,
"s": 30843,
"text": "C"
},
{
"code": "// C implementation to demonstrate// pointers in C #include <stdio.h> int main(){ int* ptr; int num = 5; ptr = # // This gives address of num printf(\"Value at ptr is %p\\n\", ptr); // This gives value at num printf(\"Value at *ptr is %d\\n\", *ptr);}",
"e": 31115,
"s": 30845,
"text": null
},
{
"code": null,
"e": 31165,
"s": 31115,
"text": "Value at ptr is 0x7ffdff4dca9c\nValue at *ptr is 5"
},
{
"code": null,
"e": 31296,
"s": 31165,
"text": "Size of Pointer variable is always constant in a system, irrespective of the datatype it is pointing to and it is usually 8 bytes."
},
{
"code": null,
"e": 31357,
"s": 31296,
"text": "Pointer to the structure can be declared as normal variable."
},
{
"code": null,
"e": 31367,
"s": 31357,
"text": "Example: "
},
{
"code": null,
"e": 31386,
"s": 31367,
"text": "struct student *p;"
},
{
"code": null,
"e": 31430,
"s": 31386,
"text": "Here, p is pointer and *p is the structure"
},
{
"code": null,
"e": 31480,
"s": 31430,
"text": "Hence, to access the data members, we have to use"
},
{
"code": null,
"e": 31503,
"s": 31480,
"text": "(*p).roll_no\n(*p).name"
},
{
"code": null,
"e": 31600,
"s": 31503,
"text": "C provides a special operator for accessing the data members via pointer i.e. -> arrow operator."
},
{
"code": null,
"e": 31632,
"s": 31600,
"text": "Note: (*p).x equivalent to p->x"
},
{
"code": null,
"e": 31692,
"s": 31632,
"text": "Below is the illustration of the pointers to the structure:"
},
{
"code": null,
"e": 31694,
"s": 31692,
"text": "C"
},
{
"code": "// C implementation to illustrate// the code of the structures #include <stdio.h>#include <stdlib.h> // Structure Definitionstruct student { int roll_no; char name[20];}; int main(){ struct student* p; p = (struct student*) malloc(sizeof(struct student)); // Arrow operator p->roll_no = 99; printf(\"The value at roll\"); printf(\"number is %d\", p->roll_no); return 0;}",
"e": 32099,
"s": 31694,
"text": null
},
{
"code": null,
"e": 32129,
"s": 32099,
"text": "The value at rollnumber is 99"
},
{
"code": null,
"e": 32190,
"s": 32129,
"text": "A function is a block of code that performs a specific task."
},
{
"code": null,
"e": 32269,
"s": 32190,
"text": "A function may have an input, performs so tasks, then may provide some output."
},
{
"code": null,
"e": 32435,
"s": 32269,
"text": "In the above example, we are giving inputs as 2 numbers to a function. It is performing function of addition. Then, it is return the sum of the two inputted numbers."
},
{
"code": null,
"e": 32484,
"s": 32435,
"text": "Inputs are called are parameters of the function"
},
{
"code": null,
"e": 32516,
"s": 32484,
"text": "Output is called a return value"
},
{
"code": null,
"e": 32565,
"s": 32516,
"text": "Functions can be classified into two categories:"
},
{
"code": null,
"e": 32788,
"s": 32565,
"text": "These are defined in the standard library of C language. We don’t have to define these functions, only thing needed is to call these functions. We just need to know the proper syntax and we can readily use these functions."
},
{
"code": null,
"e": 32797,
"s": 32788,
"text": "Example:"
},
{
"code": null,
"e": 32857,
"s": 32797,
"text": "printf(), scanf(), main(), etc are the predefined function."
},
{
"code": null,
"e": 32944,
"s": 32857,
"text": "These are the function, defined by the programmer to execute some task in the program."
},
{
"code": null,
"e": 33029,
"s": 32944,
"text": "Dividing a complex problem into smaller chunks makes our program easy to understand."
},
{
"code": null,
"e": 33093,
"s": 33029,
"text": "To use the user-defined function, we have to perform two steps "
},
{
"code": null,
"e": 33127,
"s": 33093,
"text": "Defining functionCalling function"
},
{
"code": null,
"e": 33145,
"s": 33127,
"text": "Defining function"
},
{
"code": null,
"e": 33162,
"s": 33145,
"text": "Calling function"
},
{
"code": null,
"e": 33193,
"s": 33162,
"text": "Syntax of function definition:"
},
{
"code": null,
"e": 33291,
"s": 33193,
"text": "return_type function_name(<parameters_list>)\n{\n --tasks/operations--\n return return_value;\n}"
},
{
"code": null,
"e": 33297,
"s": 33291,
"text": "Note:"
},
{
"code": null,
"e": 33438,
"s": 33297,
"text": "A function can have 0 or more parameters.A function can have 0 or 1 return value.Function that doesn’t return anything has return type void."
},
{
"code": null,
"e": 33480,
"s": 33438,
"text": "A function can have 0 or more parameters."
},
{
"code": null,
"e": 33521,
"s": 33480,
"text": "A function can have 0 or 1 return value."
},
{
"code": null,
"e": 33581,
"s": 33521,
"text": "Function that doesn’t return anything has return type void."
},
{
"code": null,
"e": 33630,
"s": 33581,
"text": "Below is the illustration of the functions in C:"
},
{
"code": null,
"e": 33632,
"s": 33630,
"text": "C"
},
{
"code": "// C implementation to// illustrate functions in C #include <stdio.h> // program to demonstrate functions// function definition// function to print something void print(){ printf(\"GeeksforGeeks\\n\");} // Function to add two numbersint add(int a, int b){ int sum; sum = a + b; return sum;} // Main Functionint main(){ int res; // Function call print(); res = add(5, 7); printf(\"Sum is %d\", res);}",
"e": 34057,
"s": 33632,
"text": null
},
{
"code": null,
"e": 34081,
"s": 34057,
"text": "GeeksforGeeks\nSum is 12"
},
{
"code": null,
"e": 34239,
"s": 34081,
"text": "Note: The type passed in the function call should be compatible with the received by the function body as a parameter. Else, it will cause compilation error."
},
{
"code": null,
"e": 34345,
"s": 34239,
"text": "When we call function by passing value(as in above program), values of original variables are unaffected."
},
{
"code": null,
"e": 34412,
"s": 34345,
"text": "Instead of sending original variable, it sends copy of a variable."
},
{
"code": null,
"e": 34482,
"s": 34412,
"text": "Below is the illustration of the function call by passing value in C:"
},
{
"code": null,
"e": 34484,
"s": 34482,
"text": "C"
},
{
"code": "// C implementation for the// function call by passing value #include <stdio.h> // Function pass by valuevoid increase_by_one(int x){ x++;} int main(){ int num = 5; printf(\"Value before function\"); printf(\" call %d\\n\", num); increase_by_one(num); printf(\"Value after function\"); printf(\" call %d\\n\", num);}",
"e": 34815,
"s": 34484,
"text": null
},
{
"code": null,
"e": 34872,
"s": 34815,
"text": "Value before function call 5\nValue after function call 5"
},
{
"code": null,
"e": 35153,
"s": 34872,
"text": "In this program, we have passed variable a to the function, which was holding value 5. Then, we incremented the value of variable received by function i.e. x by 1. So, value of x now is 6. But, this change is limited to function scope only. The value of a in main will still be 5."
},
{
"code": null,
"e": 35245,
"s": 35153,
"text": "If we want to change value of the variable passed, we have to pass the variable by address."
},
{
"code": null,
"e": 35314,
"s": 35245,
"text": "This method uses the same variable instead of creating its new copy."
},
{
"code": null,
"e": 35373,
"s": 35314,
"text": "Below is the code of the function call by passing address:"
},
{
"code": null,
"e": 35375,
"s": 35373,
"text": "C"
},
{
"code": "// C implementation to demonstrate// the usage of function call by// passing reference #include <stdio.h> // function to demonstrate// call by valuevoid increase_by_one(int* x){ (*x)++;} int main(){ int num = 5; printf(\"Value before function\"); printf(\" call %d\\n\", num); increase_by_one(&num); printf(\"Value after function\"); printf(\" call %d\\n\", num);}",
"e": 35754,
"s": 35375,
"text": null
},
{
"code": null,
"e": 35811,
"s": 35754,
"text": "Value before function call 5\nValue after function call 6"
},
{
"code": null,
"e": 35893,
"s": 35811,
"text": "As we are passing address of variable, we have to receive it as pointer variable."
},
{
"code": null,
"e": 35895,
"s": 35893,
"text": "C"
},
{
"code": "// C implementation to demonstrate// the example of the passing as// parameter in the function #include <stdio.h> // Function to print the arrayvoid print_array(int arr[], int n){ // N is size of array int i; for (i = 0; i < n; i++) printf(\"%d \", arr[i]);} int main(){ int arr[5] = { 10, 20, 30, 40, 50 }; // Function Call print_array(arr, 5);}",
"e": 36267,
"s": 35895,
"text": null
},
{
"code": null,
"e": 36283,
"s": 36267,
"text": "10 20 30 40 50 "
},
{
"code": null,
"e": 36350,
"s": 36283,
"text": "Type casting is basically conversion of one datatype into another."
},
{
"code": null,
"e": 36374,
"s": 36350,
"text": "Syntax of type casting:"
},
{
"code": null,
"e": 36451,
"s": 36374,
"text": "var2 = (datatype2) var1\nwhere, \nvar1 is of datatype1 & var2 is of datatype2"
},
{
"code": null,
"e": 36460,
"s": 36451,
"text": "Example:"
},
{
"code": null,
"e": 36532,
"s": 36460,
"text": "If you want to convert value of an integer variable into float variable"
},
{
"code": null,
"e": 36554,
"s": 36532,
"text": "float x = (float)7/5;"
},
{
"code": null,
"e": 36615,
"s": 36554,
"text": "To learn more about typecasting, refer Type Conversion in C "
},
{
"code": null,
"e": 36743,
"s": 36615,
"text": "As you know, an array is a collection of a fixed number of values. Once the size of an array is declared, you cannot change it."
},
{
"code": null,
"e": 36920,
"s": 36743,
"text": "Sometimes the size of an array you declare may be insufficient. To solve this issue, you can allocate memory dynamically at runtime. This is known as dynamic memory allocation."
},
{
"code": null,
"e": 36976,
"s": 36920,
"text": "Predefined functions used in dynamic memory allocation:"
},
{
"code": null,
"e": 37013,
"s": 36976,
"text": "malloc stands for memory allocation."
},
{
"code": null,
"e": 37152,
"s": 37013,
"text": "The malloc() function reserves a block of memory of the specified number of bytes and void* which can be casted into pointers of any form."
},
{
"code": null,
"e": 37172,
"s": 37152,
"text": "Syntax of malloc():"
},
{
"code": null,
"e": 37217,
"s": 37172,
"text": "pointer_name = (cast_datatype*)malloc(size);"
},
{
"code": null,
"e": 37345,
"s": 37217,
"text": "Dynamically allocated memory using malloc() doesn’t get freed on its own. You must explicitly use free() to release this space."
},
{
"code": null,
"e": 37362,
"s": 37345,
"text": "Syntax for free:"
},
{
"code": null,
"e": 37382,
"s": 37362,
"text": "free(pointer_name);"
},
{
"code": null,
"e": 37502,
"s": 37382,
"text": "Note: These functions are declared in header file stdlib.h. To use these functions, you must first include this header."
},
{
"code": null,
"e": 37567,
"s": 37502,
"text": "Below is the illustration of the Dynamic Memory Allocation in C:"
},
{
"code": null,
"e": 37569,
"s": 37567,
"text": "C"
},
{
"code": "// C implementation to demonstrate// the code the Dynamic Memory// Allocation #include <stdio.h>#include <stdlib.h> int main(){ int* ptr; int n = 5, i; ptr = (int*)malloc(n * sizeof(int)); for (i = 0; i < n; i++) ptr[i] = i; printf(\"\\nArray Elements are\\n\"); for (i = 0; i < n; i++) printf(\"%d \", ptr[i]); free(ptr);}",
"e": 37927,
"s": 37569,
"text": null
},
{
"code": null,
"e": 37957,
"s": 37927,
"text": "Array Elements are\n0 1 2 3 4 "
},
{
"code": null,
"e": 38041,
"s": 37957,
"text": "To learn more about Dynamic Memory Allocation, refer Dynamic Memory Allocation in C"
},
{
"code": null,
"e": 38052,
"s": 38041,
"text": "nidhi_biet"
},
{
"code": null,
"e": 38067,
"s": 38052,
"text": "varshagumber28"
},
{
"code": null,
"e": 38079,
"s": 38067,
"text": "anikaseth98"
},
{
"code": null,
"e": 38088,
"s": 38079,
"text": "sooda367"
},
{
"code": null,
"e": 38097,
"s": 38088,
"text": "C-Arrays"
},
{
"code": null,
"e": 38110,
"s": 38097,
"text": "C-Data Types"
},
{
"code": null,
"e": 38138,
"s": 38110,
"text": "C-Dynamic Memory Allocation"
},
{
"code": null,
"e": 38158,
"s": 38138,
"text": "C-Structure & Union"
},
{
"code": null,
"e": 38165,
"s": 38158,
"text": "Arrays"
},
{
"code": null,
"e": 38176,
"s": 38165,
"text": "C Language"
},
{
"code": null,
"e": 38192,
"s": 38176,
"text": "Data Structures"
},
{
"code": null,
"e": 38208,
"s": 38192,
"text": "Data Structures"
},
{
"code": null,
"e": 38215,
"s": 38208,
"text": "Arrays"
},
{
"code": null,
"e": 38313,
"s": 38215,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38340,
"s": 38313,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 38371,
"s": 38340,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 38396,
"s": 38371,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 38434,
"s": 38396,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 38455,
"s": 38434,
"text": "Next Greater Element"
},
{
"code": null,
"e": 38533,
"s": 38455,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 38556,
"s": 38533,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 38583,
"s": 38556,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 38600,
"s": 38583,
"text": "Substring in C++"
}
] |
Min difference between maximum and minimum element in all Y size subarrays - GeeksforGeeks
|
31 Aug, 2021
Given an array arr[] of size N and integer Y, the task is to find a minimum of all the differences between the maximum and minimum elements in all the sub-arrays of size Y.
Examples:
Input: arr[] = { 3, 2, 4, 5, 6, 1, 9 } Y = 3Output: 2Explanation:All subarrays of length = 3 are:{3, 2, 4} where maximum element = 4 and minimum element = 2 difference = 2{2, 4, 5} where maximum element = 5 and minimum element = 2 difference = 3{4, 5, 6} where maximum element = 6 and minimum element = 4 difference = 2{5, 6, 1} where maximum element = 6 and minimum element = 1 difference = 5{6, 1, 9} where maximum element = 9 and minimum element = 6 difference = 3 Out of these, the minimum is 2.
Input: arr[] = { 1, 2, 3, 3, 2, 2 } Y = 4Output: 1Explanation:All subarrays of length = 4 are:{1, 2, 3, 3} maximum element = 3 and minimum element = 1 difference = 2{2, 3, 3, 2} maximum element = 3 and minimum element = 2 difference = 1{3, 3, 2, 2} maximum element = 3 and minimum element = 2 difference = 1 Out of these, the minimum is 1.
Naive Approach: The naive idea is to traverse for every index i in the range [0, N – Y] use another loop to traverse from ith index to (i + Y – 1)th index and then calculate the minimum and maximum elements in a subarray of size Y and hence calculate the difference of maximum and minimum element for that ith iteration. Finally, by keeping a check on differences, evaluate the minimum difference.
Time Complexity: O(N*Y)Auxiliary Space: O(1)
Efficient Approach: The idea is to use the concept of the approach discussed in the Next Greater Element article. Below are the steps:
Build two arrays maxarr[] and minarr[], where maxarr[] will store the index of the element which is next greater to the element at ith index and minarr[] will store the index of the next element which is less than the element at the ith index.Initialize a stack with 0 to store the indices in both the above cases.For each index, i in the range [0, N – Y], using a nested loop and sliding window approach form two arrays submax and submin. These arrays will store maximum and minimum elements in the subarray in ith iteration.Finally, calculate the minimum difference.
Build two arrays maxarr[] and minarr[], where maxarr[] will store the index of the element which is next greater to the element at ith index and minarr[] will store the index of the next element which is less than the element at the ith index.
Initialize a stack with 0 to store the indices in both the above cases.
For each index, i in the range [0, N – Y], using a nested loop and sliding window approach form two arrays submax and submin. These arrays will store maximum and minimum elements in the subarray in ith iteration.
Finally, calculate the minimum difference.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to get the maximum of all// the subarrays of size Yvector<int> get_submaxarr(int* arr, int n, int y){ int j = 0; stack<int> stk; // ith index of maxarr array // will be the index upto which // Arr[i] is maximum vector<int> maxarr(n); stk.push(0); for (int i = 1; i < n; i++) { // Stack is used to find the // next larger element and // keeps track of index of // current iteration while (stk.empty() == false and arr[i] > arr[stk.top()]) { maxarr[stk.top()] = i - 1; stk.pop(); } stk.push(i); } // Loop for remaining indexes while (!stk.empty()) { maxarr[stk.top()] = n - 1; stk.pop(); } vector<int> submax; for (int i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is // inside or outside the window while (maxarr[j] < i + y - 1 or j < i) { j++; } submax.push_back(arr[j]); } // Return submax return submax;} // Function to get the minimum for// all subarrays of size Yvector<int> get_subminarr(int* arr, int n, int y){ int j = 0; stack<int> stk; // ith index of minarr array // will be the index upto which // Arr[i] is minimum vector<int> minarr(n); stk.push(0); for (int i = 1; i < n; i++) { // Stack is used to find the // next smaller element and // keeping track of index of // current iteration while (stk.empty() == false and arr[i] < arr[stk.top()]) { minarr[stk.top()] = i; stk.pop(); } stk.push(i); } // Loop for remaining indexes while (!stk.empty()) { minarr[stk.top()] = n; stk.pop(); } vector<int> submin; for (int i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is inside // or outside the window while (minarr[j] <= i + y - 1 or j < i) { j++; } submin.push_back(arr[j]); } // Return submin return submin;} // Function to get minimum differencevoid getMinDifference(int Arr[], int N, int Y){ // Create submin and submax arrays vector<int> submin = get_subminarr(Arr, N, Y); vector<int> submax = get_submaxarr(Arr, N, Y); // Store initial difference int minn = submax[0] - submin[0]; int b = submax.size(); for (int i = 1; i < b; i++) { // Calculate temporary difference int dif = submax[i] - submin[i]; minn = min(minn, dif); } // Final minimum difference cout << minn << "\n";} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 2, 3, 3, 2, 2 }; int N = sizeof arr / sizeof arr[0]; // Given subarray size int Y = 4; // Function Call getMinDifference(arr, N, Y); return 0;}
// Java program for the above approachimport java.util.*; class GFG{ // Function to get the maximum of all// the subarrays of size Ystatic Vector<Integer> get_submaxarr(int[] arr, int n, int y){ int j = 0; Stack<Integer> stk = new Stack<Integer>(); // ith index of maxarr array // will be the index upto which // Arr[i] is maximum int[] maxarr = new int[n]; Arrays.fill(maxarr,0); stk.push(0); for(int i = 1; i < n; i++) { // Stack is used to find the // next larger element and // keeps track of index of // current iteration while (stk.size() != 0 && arr[i] > arr[stk.peek()]) { maxarr[stk.peek()] = i - 1; stk.pop(); } stk.push(i); } // Loop for remaining indexes while (stk.size() != 0) { maxarr[stk.size()] = n - 1; stk.pop(); } Vector<Integer> submax = new Vector<Integer>(); for(int i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is // inside or outside the window while (maxarr[j] < i + y - 1 || j < i) { j++; } submax.add(arr[j]); } // Return submax return submax;} // Function to get the minimum for// all subarrays of size Ystatic Vector<Integer> get_subminarr(int[] arr, int n, int y){ int j = 0; Stack<Integer> stk = new Stack<Integer>(); // ith index of minarr array // will be the index upto which // Arr[i] is minimum int[] minarr = new int[n]; Arrays.fill(minarr,0); stk.push(0); for(int i = 1; i < n; i++) { // Stack is used to find the // next smaller element and // keeping track of index of // current iteration while (stk.size() != 0 && arr[i] < arr[stk.peek()]) { minarr[stk.peek()] = i; stk.pop(); } stk.push(i); } // Loop for remaining indexes while (stk.size() != 0) { minarr[stk.peek()] = n; stk.pop(); } Vector<Integer> submin = new Vector<Integer>(); for(int i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is inside // or outside the window while (minarr[j] <= i + y - 1 || j < i) { j++; } submin.add(arr[j]); } // Return submin return submin;} // Function to get minimum differencestatic void getMinDifference(int[] Arr, int N, int Y){ // Create submin and submax arrays Vector<Integer> submin = get_subminarr(Arr, N, Y); Vector<Integer> submax = get_submaxarr(Arr, N, Y); // Store initial difference int minn = submax.get(0) - submin.get(0); int b = submax.size(); for(int i = 1; i < b; i++) { // Calculate temporary difference int dif = submax.get(i) - submin.get(i) + 1; minn = Math.min(minn, dif); } // Final minimum difference System.out.print(minn);} // Driver codepublic static void main(String[] args){ // Given array arr[] int[] arr = { 1, 2, 3, 3, 2, 2 }; int N = arr.length; // Given subarray size int Y = 4; // Function Call getMinDifference(arr, N, Y);}} // This code is contributed by decode2207
# Python3 program for the above approach # Function to get the maximum of all# the subarrays of size Ydef get_submaxarr(arr, n, y): j = 0 stk = [] # ith index of maxarr array # will be the index upto which # Arr[i] is maximum maxarr = [0] * n stk.append(0) for i in range(1, n): # Stack is used to find the # next larger element and # keeps track of index of # current iteration while (len(stk) > 0 and arr[i] > arr[stk[-1]]): maxarr[stk[-1]] = i - 1 stk.pop() stk.append(i) # Loop for remaining indexes while (stk): maxarr[stk[-1]] = n - 1 stk.pop() submax = [] for i in range(n - y + 1): # j < i used to keep track # whether jth element is # inside or outside the window while (maxarr[j] < i + y - 1 or j < i): j += 1 submax.append(arr[j]) # Return submax return submax # Function to get the minimum for# all subarrays of size Ydef get_subminarr(arr, n, y): j = 0 stk = [] # ith index of minarr array # will be the index upto which # Arr[i] is minimum minarr = [0] * n stk.append(0) for i in range(1 , n): # Stack is used to find the # next smaller element and # keeping track of index of # current iteration while (stk and arr[i] < arr[stk[-1]]): minarr[stk[-1]] = i stk.pop() stk.append(i) # Loop for remaining indexes while (stk): minarr[stk[-1]] = n stk.pop() submin = [] for i in range(n - y + 1): # j < i used to keep track # whether jth element is inside # or outside the window while (minarr[j] <= i + y - 1 or j < i): j += 1 submin.append(arr[j]) # Return submin return submin # Function to get minimum differencedef getMinDifference(Arr, N, Y): # Create submin and submax arrays submin = get_subminarr(Arr, N, Y) submax = get_submaxarr(Arr, N, Y) # Store initial difference minn = submax[0] - submin[0] b = len(submax) for i in range(1, b): # Calculate temporary difference diff = submax[i] - submin[i] minn = min(minn, diff) # Final minimum difference print(minn) # Driver code # Given array arr[]arr = [ 1, 2, 3, 3, 2, 2 ]N = len(arr) # Given subarray sizeY = 4 # Function callgetMinDifference(arr, N, Y) # This code is contributed by Stuti Pathak
// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to get the maximum of all // the subarrays of size Y static List<int> get_submaxarr(int[] arr, int n, int y) { int j = 0; Stack<int> stk = new Stack<int>(); // ith index of maxarr array // will be the index upto which // Arr[i] is maximum int[] maxarr = new int[n]; Array.Fill(maxarr,0); stk.Push(0); for (int i = 1; i < n; i++) { // Stack is used to find the // next larger element and // keeps track of index of // current iteration while (stk.Count!=0 && arr[i] > arr[stk.Peek()]) { maxarr[stk.Peek()] = i - 1; stk.Pop(); } stk.Push(i); } // Loop for remaining indexes while (stk.Count!=0) { maxarr[stk.Count] = n - 1; stk.Pop(); } List<int> submax = new List<int>(); for (int i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is // inside or outside the window while (maxarr[j] < i + y - 1 || j < i) { j++; } submax.Add(arr[j]); } // Return submax return submax; } // Function to get the minimum for // all subarrays of size Y static List<int> get_subminarr(int[] arr, int n, int y) { int j = 0; Stack<int> stk = new Stack<int>(); // ith index of minarr array // will be the index upto which // Arr[i] is minimum int[] minarr = new int[n]; Array.Fill(minarr,0); stk.Push(0); for (int i = 1; i < n; i++) { // Stack is used to find the // next smaller element and // keeping track of index of // current iteration while (stk.Count!=0 && arr[i] < arr[stk.Peek()]) { minarr[stk.Peek()] = i; stk.Pop(); } stk.Push(i); } // Loop for remaining indexes while (stk.Count!=0) { minarr[stk.Peek()] = n; stk.Pop(); } List<int> submin = new List<int>(); for (int i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is inside // or outside the window while (minarr[j] <= i + y - 1 || j < i) { j++; } submin.Add(arr[j]); } // Return submin return submin; } // Function to get minimum difference static void getMinDifference(int[] Arr, int N, int Y) { // Create submin and submax arrays List<int> submin = get_subminarr(Arr, N, Y); List<int> submax = get_submaxarr(Arr, N, Y); // Store initial difference int minn = submax[0] - submin[0]; int b = submax.Count; for (int i = 1; i < b; i++) { // Calculate temporary difference int dif = submax[i] - submin[i] + 1; minn = Math.Min(minn, dif); } // Final minimum difference Console.WriteLine(minn); } static void Main() { // Given array arr[] int[] arr = { 1, 2, 3, 3, 2, 2 }; int N = arr.Length; // Given subarray size int Y = 4; // Function Call getMinDifference(arr, N, Y); }} // This code is contributed by rameshtravel07.
<script> // Javascript program for the above approach // Function to get the maximum of all// the subarrays of size Yfunction get_submaxarr(arr, n, y){ var j = 0; var stk = []; // ith index of maxarr array // will be the index upto which // Arr[i] is maximum var maxarr = Array(n); stk.push(0); for (var i = 1; i < n; i++) { // Stack is used to find the // next larger element and // keeps track of index of // current iteration while (stk.length!=0 && arr[i] > arr[stk[stk.length-1]]) { maxarr[stk[stk.length-1]] = i - 1; stk.pop(); } stk.push(i); } // Loop for remaining indexes while (stk.length!=0) { maxarr[stk[stk.length-1]] = n - 1; stk.pop(); } var submax = []; for (var i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is // inside or outside the window while (maxarr[j] < i + y - 1 || j < i) { j++; } submax.push(arr[j]); } // Return submax return submax;} // Function to get the minimum for// all subarrays of size Yfunction get_subminarr(arr, n, y){ var j = 0; var stk = []; // ith index of minarr array // will be the index upto which // Arr[i] is minimum var minarr = Array(n); stk.push(0); for (var i = 1; i < n; i++) { // Stack is used to find the // next smaller element and // keeping track of index of // current iteration while (stk.length!=0 && arr[i] < arr[stk[stk.length-1]]) { minarr[stk[stk.length-1]] = i; stk.pop(); } stk.push(i); } // Loop for remaining indexes while (stk.length!=0) { minarr[stk[stk.length-1]] = n; stk.pop(); } var submin = []; for (var i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is inside // or outside the window while (minarr[j] <= i + y - 1 || j < i) { j++; } submin.push(arr[j]); } // Return submin return submin;} // Function to get minimum differencefunction getMinDifference(Arr, N, Y){ // Create submin and submax arrays var submin = get_subminarr(Arr, N, Y); var submax = get_submaxarr(Arr, N, Y); // Store initial difference var minn = submax[0] - submin[0]; var b = submax.length; for (var i = 1; i < b; i++) { // Calculate temporary difference var dif = submax[i] - submin[i]; minn = Math.min(minn, dif); } // Final minimum difference document.write( minn + "<br>");} // Driver Code// Given array arr[]var arr = [1, 2, 3, 3, 2, 2];var N = arr.length// Given subarray sizevar Y = 4;// Function CallgetMinDifference(arr, N, Y); </script>
1
Time Complexity: O(N)Auxiliary Space: O(N)
stutipathak31jan
itsok
rameshtravel07
decode2207
cpp-stack
sliding-window
subarray
Arrays
Competitive Programming
Searching
Stack
sliding-window
Arrays
Searching
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Introduction to Arrays
Multidimensional Arrays in Java
Linear Search
Linked List vs Array
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming
|
[
{
"code": null,
"e": 26417,
"s": 26389,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 26590,
"s": 26417,
"text": "Given an array arr[] of size N and integer Y, the task is to find a minimum of all the differences between the maximum and minimum elements in all the sub-arrays of size Y."
},
{
"code": null,
"e": 26600,
"s": 26590,
"text": "Examples:"
},
{
"code": null,
"e": 27113,
"s": 26600,
"text": "Input: arr[] = { 3, 2, 4, 5, 6, 1, 9 } Y = 3Output: 2Explanation:All subarrays of length = 3 are:{3, 2, 4} where maximum element = 4 and minimum element = 2 difference = 2{2, 4, 5} where maximum element = 5 and minimum element = 2 difference = 3{4, 5, 6} where maximum element = 6 and minimum element = 4 difference = 2{5, 6, 1} where maximum element = 6 and minimum element = 1 difference = 5{6, 1, 9} where maximum element = 9 and minimum element = 6 difference = 3 Out of these, the minimum is 2. "
},
{
"code": null,
"e": 27486,
"s": 27113,
"text": "Input: arr[] = { 1, 2, 3, 3, 2, 2 } Y = 4Output: 1Explanation:All subarrays of length = 4 are:{1, 2, 3, 3} maximum element = 3 and minimum element = 1 difference = 2{2, 3, 3, 2} maximum element = 3 and minimum element = 2 difference = 1{3, 3, 2, 2} maximum element = 3 and minimum element = 2 difference = 1 Out of these, the minimum is 1. "
},
{
"code": null,
"e": 27884,
"s": 27486,
"text": "Naive Approach: The naive idea is to traverse for every index i in the range [0, N – Y] use another loop to traverse from ith index to (i + Y – 1)th index and then calculate the minimum and maximum elements in a subarray of size Y and hence calculate the difference of maximum and minimum element for that ith iteration. Finally, by keeping a check on differences, evaluate the minimum difference."
},
{
"code": null,
"e": 27929,
"s": 27884,
"text": "Time Complexity: O(N*Y)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28064,
"s": 27929,
"text": "Efficient Approach: The idea is to use the concept of the approach discussed in the Next Greater Element article. Below are the steps:"
},
{
"code": null,
"e": 28633,
"s": 28064,
"text": "Build two arrays maxarr[] and minarr[], where maxarr[] will store the index of the element which is next greater to the element at ith index and minarr[] will store the index of the next element which is less than the element at the ith index.Initialize a stack with 0 to store the indices in both the above cases.For each index, i in the range [0, N – Y], using a nested loop and sliding window approach form two arrays submax and submin. These arrays will store maximum and minimum elements in the subarray in ith iteration.Finally, calculate the minimum difference."
},
{
"code": null,
"e": 28877,
"s": 28633,
"text": "Build two arrays maxarr[] and minarr[], where maxarr[] will store the index of the element which is next greater to the element at ith index and minarr[] will store the index of the next element which is less than the element at the ith index."
},
{
"code": null,
"e": 28949,
"s": 28877,
"text": "Initialize a stack with 0 to store the indices in both the above cases."
},
{
"code": null,
"e": 29162,
"s": 28949,
"text": "For each index, i in the range [0, N – Y], using a nested loop and sliding window approach form two arrays submax and submin. These arrays will store maximum and minimum elements in the subarray in ith iteration."
},
{
"code": null,
"e": 29205,
"s": 29162,
"text": "Finally, calculate the minimum difference."
},
{
"code": null,
"e": 29256,
"s": 29205,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 29260,
"s": 29256,
"text": "C++"
},
{
"code": null,
"e": 29265,
"s": 29260,
"text": "Java"
},
{
"code": null,
"e": 29273,
"s": 29265,
"text": "Python3"
},
{
"code": null,
"e": 29276,
"s": 29273,
"text": "C#"
},
{
"code": null,
"e": 29287,
"s": 29276,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to get the maximum of all// the subarrays of size Yvector<int> get_submaxarr(int* arr, int n, int y){ int j = 0; stack<int> stk; // ith index of maxarr array // will be the index upto which // Arr[i] is maximum vector<int> maxarr(n); stk.push(0); for (int i = 1; i < n; i++) { // Stack is used to find the // next larger element and // keeps track of index of // current iteration while (stk.empty() == false and arr[i] > arr[stk.top()]) { maxarr[stk.top()] = i - 1; stk.pop(); } stk.push(i); } // Loop for remaining indexes while (!stk.empty()) { maxarr[stk.top()] = n - 1; stk.pop(); } vector<int> submax; for (int i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is // inside or outside the window while (maxarr[j] < i + y - 1 or j < i) { j++; } submax.push_back(arr[j]); } // Return submax return submax;} // Function to get the minimum for// all subarrays of size Yvector<int> get_subminarr(int* arr, int n, int y){ int j = 0; stack<int> stk; // ith index of minarr array // will be the index upto which // Arr[i] is minimum vector<int> minarr(n); stk.push(0); for (int i = 1; i < n; i++) { // Stack is used to find the // next smaller element and // keeping track of index of // current iteration while (stk.empty() == false and arr[i] < arr[stk.top()]) { minarr[stk.top()] = i; stk.pop(); } stk.push(i); } // Loop for remaining indexes while (!stk.empty()) { minarr[stk.top()] = n; stk.pop(); } vector<int> submin; for (int i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is inside // or outside the window while (minarr[j] <= i + y - 1 or j < i) { j++; } submin.push_back(arr[j]); } // Return submin return submin;} // Function to get minimum differencevoid getMinDifference(int Arr[], int N, int Y){ // Create submin and submax arrays vector<int> submin = get_subminarr(Arr, N, Y); vector<int> submax = get_submaxarr(Arr, N, Y); // Store initial difference int minn = submax[0] - submin[0]; int b = submax.size(); for (int i = 1; i < b; i++) { // Calculate temporary difference int dif = submax[i] - submin[i]; minn = min(minn, dif); } // Final minimum difference cout << minn << \"\\n\";} // Driver Codeint main(){ // Given array arr[] int arr[] = { 1, 2, 3, 3, 2, 2 }; int N = sizeof arr / sizeof arr[0]; // Given subarray size int Y = 4; // Function Call getMinDifference(arr, N, Y); return 0;}",
"e": 32348,
"s": 29287,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG{ // Function to get the maximum of all// the subarrays of size Ystatic Vector<Integer> get_submaxarr(int[] arr, int n, int y){ int j = 0; Stack<Integer> stk = new Stack<Integer>(); // ith index of maxarr array // will be the index upto which // Arr[i] is maximum int[] maxarr = new int[n]; Arrays.fill(maxarr,0); stk.push(0); for(int i = 1; i < n; i++) { // Stack is used to find the // next larger element and // keeps track of index of // current iteration while (stk.size() != 0 && arr[i] > arr[stk.peek()]) { maxarr[stk.peek()] = i - 1; stk.pop(); } stk.push(i); } // Loop for remaining indexes while (stk.size() != 0) { maxarr[stk.size()] = n - 1; stk.pop(); } Vector<Integer> submax = new Vector<Integer>(); for(int i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is // inside or outside the window while (maxarr[j] < i + y - 1 || j < i) { j++; } submax.add(arr[j]); } // Return submax return submax;} // Function to get the minimum for// all subarrays of size Ystatic Vector<Integer> get_subminarr(int[] arr, int n, int y){ int j = 0; Stack<Integer> stk = new Stack<Integer>(); // ith index of minarr array // will be the index upto which // Arr[i] is minimum int[] minarr = new int[n]; Arrays.fill(minarr,0); stk.push(0); for(int i = 1; i < n; i++) { // Stack is used to find the // next smaller element and // keeping track of index of // current iteration while (stk.size() != 0 && arr[i] < arr[stk.peek()]) { minarr[stk.peek()] = i; stk.pop(); } stk.push(i); } // Loop for remaining indexes while (stk.size() != 0) { minarr[stk.peek()] = n; stk.pop(); } Vector<Integer> submin = new Vector<Integer>(); for(int i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is inside // or outside the window while (minarr[j] <= i + y - 1 || j < i) { j++; } submin.add(arr[j]); } // Return submin return submin;} // Function to get minimum differencestatic void getMinDifference(int[] Arr, int N, int Y){ // Create submin and submax arrays Vector<Integer> submin = get_subminarr(Arr, N, Y); Vector<Integer> submax = get_submaxarr(Arr, N, Y); // Store initial difference int minn = submax.get(0) - submin.get(0); int b = submax.size(); for(int i = 1; i < b; i++) { // Calculate temporary difference int dif = submax.get(i) - submin.get(i) + 1; minn = Math.min(minn, dif); } // Final minimum difference System.out.print(minn);} // Driver codepublic static void main(String[] args){ // Given array arr[] int[] arr = { 1, 2, 3, 3, 2, 2 }; int N = arr.length; // Given subarray size int Y = 4; // Function Call getMinDifference(arr, N, Y);}} // This code is contributed by decode2207",
"e": 35769,
"s": 32348,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to get the maximum of all# the subarrays of size Ydef get_submaxarr(arr, n, y): j = 0 stk = [] # ith index of maxarr array # will be the index upto which # Arr[i] is maximum maxarr = [0] * n stk.append(0) for i in range(1, n): # Stack is used to find the # next larger element and # keeps track of index of # current iteration while (len(stk) > 0 and arr[i] > arr[stk[-1]]): maxarr[stk[-1]] = i - 1 stk.pop() stk.append(i) # Loop for remaining indexes while (stk): maxarr[stk[-1]] = n - 1 stk.pop() submax = [] for i in range(n - y + 1): # j < i used to keep track # whether jth element is # inside or outside the window while (maxarr[j] < i + y - 1 or j < i): j += 1 submax.append(arr[j]) # Return submax return submax # Function to get the minimum for# all subarrays of size Ydef get_subminarr(arr, n, y): j = 0 stk = [] # ith index of minarr array # will be the index upto which # Arr[i] is minimum minarr = [0] * n stk.append(0) for i in range(1 , n): # Stack is used to find the # next smaller element and # keeping track of index of # current iteration while (stk and arr[i] < arr[stk[-1]]): minarr[stk[-1]] = i stk.pop() stk.append(i) # Loop for remaining indexes while (stk): minarr[stk[-1]] = n stk.pop() submin = [] for i in range(n - y + 1): # j < i used to keep track # whether jth element is inside # or outside the window while (minarr[j] <= i + y - 1 or j < i): j += 1 submin.append(arr[j]) # Return submin return submin # Function to get minimum differencedef getMinDifference(Arr, N, Y): # Create submin and submax arrays submin = get_subminarr(Arr, N, Y) submax = get_submaxarr(Arr, N, Y) # Store initial difference minn = submax[0] - submin[0] b = len(submax) for i in range(1, b): # Calculate temporary difference diff = submax[i] - submin[i] minn = min(minn, diff) # Final minimum difference print(minn) # Driver code # Given array arr[]arr = [ 1, 2, 3, 3, 2, 2 ]N = len(arr) # Given subarray sizeY = 4 # Function callgetMinDifference(arr, N, Y) # This code is contributed by Stuti Pathak",
"e": 38453,
"s": 35769,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG { // Function to get the maximum of all // the subarrays of size Y static List<int> get_submaxarr(int[] arr, int n, int y) { int j = 0; Stack<int> stk = new Stack<int>(); // ith index of maxarr array // will be the index upto which // Arr[i] is maximum int[] maxarr = new int[n]; Array.Fill(maxarr,0); stk.Push(0); for (int i = 1; i < n; i++) { // Stack is used to find the // next larger element and // keeps track of index of // current iteration while (stk.Count!=0 && arr[i] > arr[stk.Peek()]) { maxarr[stk.Peek()] = i - 1; stk.Pop(); } stk.Push(i); } // Loop for remaining indexes while (stk.Count!=0) { maxarr[stk.Count] = n - 1; stk.Pop(); } List<int> submax = new List<int>(); for (int i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is // inside or outside the window while (maxarr[j] < i + y - 1 || j < i) { j++; } submax.Add(arr[j]); } // Return submax return submax; } // Function to get the minimum for // all subarrays of size Y static List<int> get_subminarr(int[] arr, int n, int y) { int j = 0; Stack<int> stk = new Stack<int>(); // ith index of minarr array // will be the index upto which // Arr[i] is minimum int[] minarr = new int[n]; Array.Fill(minarr,0); stk.Push(0); for (int i = 1; i < n; i++) { // Stack is used to find the // next smaller element and // keeping track of index of // current iteration while (stk.Count!=0 && arr[i] < arr[stk.Peek()]) { minarr[stk.Peek()] = i; stk.Pop(); } stk.Push(i); } // Loop for remaining indexes while (stk.Count!=0) { minarr[stk.Peek()] = n; stk.Pop(); } List<int> submin = new List<int>(); for (int i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is inside // or outside the window while (minarr[j] <= i + y - 1 || j < i) { j++; } submin.Add(arr[j]); } // Return submin return submin; } // Function to get minimum difference static void getMinDifference(int[] Arr, int N, int Y) { // Create submin and submax arrays List<int> submin = get_subminarr(Arr, N, Y); List<int> submax = get_submaxarr(Arr, N, Y); // Store initial difference int minn = submax[0] - submin[0]; int b = submax.Count; for (int i = 1; i < b; i++) { // Calculate temporary difference int dif = submax[i] - submin[i] + 1; minn = Math.Min(minn, dif); } // Final minimum difference Console.WriteLine(minn); } static void Main() { // Given array arr[] int[] arr = { 1, 2, 3, 3, 2, 2 }; int N = arr.Length; // Given subarray size int Y = 4; // Function Call getMinDifference(arr, N, Y); }} // This code is contributed by rameshtravel07.",
"e": 42169,
"s": 38453,
"text": null
},
{
"code": "<script> // Javascript program for the above approach // Function to get the maximum of all// the subarrays of size Yfunction get_submaxarr(arr, n, y){ var j = 0; var stk = []; // ith index of maxarr array // will be the index upto which // Arr[i] is maximum var maxarr = Array(n); stk.push(0); for (var i = 1; i < n; i++) { // Stack is used to find the // next larger element and // keeps track of index of // current iteration while (stk.length!=0 && arr[i] > arr[stk[stk.length-1]]) { maxarr[stk[stk.length-1]] = i - 1; stk.pop(); } stk.push(i); } // Loop for remaining indexes while (stk.length!=0) { maxarr[stk[stk.length-1]] = n - 1; stk.pop(); } var submax = []; for (var i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is // inside or outside the window while (maxarr[j] < i + y - 1 || j < i) { j++; } submax.push(arr[j]); } // Return submax return submax;} // Function to get the minimum for// all subarrays of size Yfunction get_subminarr(arr, n, y){ var j = 0; var stk = []; // ith index of minarr array // will be the index upto which // Arr[i] is minimum var minarr = Array(n); stk.push(0); for (var i = 1; i < n; i++) { // Stack is used to find the // next smaller element and // keeping track of index of // current iteration while (stk.length!=0 && arr[i] < arr[stk[stk.length-1]]) { minarr[stk[stk.length-1]] = i; stk.pop(); } stk.push(i); } // Loop for remaining indexes while (stk.length!=0) { minarr[stk[stk.length-1]] = n; stk.pop(); } var submin = []; for (var i = 0; i <= n - y; i++) { // j < i used to keep track // whether jth element is inside // or outside the window while (minarr[j] <= i + y - 1 || j < i) { j++; } submin.push(arr[j]); } // Return submin return submin;} // Function to get minimum differencefunction getMinDifference(Arr, N, Y){ // Create submin and submax arrays var submin = get_subminarr(Arr, N, Y); var submax = get_submaxarr(Arr, N, Y); // Store initial difference var minn = submax[0] - submin[0]; var b = submax.length; for (var i = 1; i < b; i++) { // Calculate temporary difference var dif = submax[i] - submin[i]; minn = Math.min(minn, dif); } // Final minimum difference document.write( minn + \"<br>\");} // Driver Code// Given array arr[]var arr = [1, 2, 3, 3, 2, 2];var N = arr.length// Given subarray sizevar Y = 4;// Function CallgetMinDifference(arr, N, Y); </script>",
"e": 45043,
"s": 42169,
"text": null
},
{
"code": null,
"e": 45045,
"s": 45043,
"text": "1"
},
{
"code": null,
"e": 45090,
"s": 45047,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 45107,
"s": 45090,
"text": "stutipathak31jan"
},
{
"code": null,
"e": 45113,
"s": 45107,
"text": "itsok"
},
{
"code": null,
"e": 45128,
"s": 45113,
"text": "rameshtravel07"
},
{
"code": null,
"e": 45139,
"s": 45128,
"text": "decode2207"
},
{
"code": null,
"e": 45149,
"s": 45139,
"text": "cpp-stack"
},
{
"code": null,
"e": 45164,
"s": 45149,
"text": "sliding-window"
},
{
"code": null,
"e": 45173,
"s": 45164,
"text": "subarray"
},
{
"code": null,
"e": 45180,
"s": 45173,
"text": "Arrays"
},
{
"code": null,
"e": 45204,
"s": 45180,
"text": "Competitive Programming"
},
{
"code": null,
"e": 45214,
"s": 45204,
"text": "Searching"
},
{
"code": null,
"e": 45220,
"s": 45214,
"text": "Stack"
},
{
"code": null,
"e": 45235,
"s": 45220,
"text": "sliding-window"
},
{
"code": null,
"e": 45242,
"s": 45235,
"text": "Arrays"
},
{
"code": null,
"e": 45252,
"s": 45242,
"text": "Searching"
},
{
"code": null,
"e": 45258,
"s": 45252,
"text": "Stack"
},
{
"code": null,
"e": 45356,
"s": 45258,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45424,
"s": 45356,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 45447,
"s": 45424,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 45479,
"s": 45447,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 45493,
"s": 45479,
"text": "Linear Search"
},
{
"code": null,
"e": 45514,
"s": 45493,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 45557,
"s": 45514,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 45600,
"s": 45557,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 45641,
"s": 45600,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 45719,
"s": 45641,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
Print characters in decreasing order of frequency - GeeksforGeeks
|
25 Apr, 2022
Given string str, the task is to print the characters in decreasing order of their frequency. If the frequency of two characters is the same then sort them in descending order alphabetically.Examples:
Input: str = “geeksforgeeks” Output: e – 4 s – 2 k – 2 g – 2 r – 1 o – 1 f – 1Input: str = “bbcc” Output: c – 2 b – 2
Approach 1:
Use an unordered_map to store the frequencies of all the elements of the given string.
Find the maximum frequency element from the map, print it with its frequency, and remove it from the map.
Repeat the previous step while the map is not empty.
Below is the implementation of the above approach:
CPP
Java
Python3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the characters// of the given string in decreasing// order of their frequenciesvoid printChar(string str, int len){ // To store the unordered_map<char, int> occ; for (int i = 0; i < len; i++) occ[str[i]]++; // Map's size int size = occ.size(); unordered_map<char, int>::iterator it; // While there are elements in the map while (size--) { // Finding the maximum value // from the map unsigned currentMax = 0; char arg_max; for (it = occ.begin(); it != occ.end(); ++it) { if (it->second > currentMax || (it->second == currentMax && it->first > arg_max)) { arg_max = it->first; currentMax = it->second; } } // Print the character // alongwith its frequency cout << arg_max << " - " << currentMax << endl; // Delete the maximum value occ.erase(arg_max); }} // Driver codeint main(){ string str = "geeksforgeeks"; int len = str.length(); printChar(str, len); return 0;}
// Java implementation of the approachimport java.util.*;class GFG{ // Function to print the characters// of the given String in decreasing// order of their frequenciesstatic void printChar(char []arr, int len){ // To store the HashMap<Character, Integer> occ = new HashMap<Character, Integer>(); for (int i = 0; i < len; i++) if(occ.containsKey(arr[i])) { occ.put(arr[i], occ.get(arr[i]) + 1); } else { occ.put(arr[i], 1); } // Map's size int size = occ.size(); // While there are elements in the map while (size-- > 0) { // Finding the maximum value // from the map int currentMax = 0; char arg_max = 0; for (Map.Entry<Character, Integer> it : occ.entrySet()) { if (it.getValue() > currentMax || (it.getValue() == currentMax && it.getKey() > arg_max)) { arg_max = it.getKey(); currentMax = it.getValue(); } } // Print the character // alongwith its frequency System.out.print(arg_max + " - " + currentMax + "\n"); // Delete the maximum value occ.remove(arg_max); }} // Driver codepublic static void main(String[] args){ String str = "geeksforgeeks"; int len = str.length(); printChar(str.toCharArray(), len);}} // This code is contributed by gauravrajput1
# Python implementation of the approach # Function to print the characters# of the given String in decreasing# order of their frequenciesdef printChar(arr, Len): # To store the occ = {} for i in range(Len): if(arr[i] in occ): occ[arr[i]] = occ[arr[i]] + 1 else: occ[arr[i]] = 1 # Map's size size = len(occ) # While there are elements in the map while (size > 0): # Finding the maximum value # from the map currentMax = 0 arg_max = 0 for key, value in occ.items(): if (value > currentMax or (value == currentMax and key > arg_max)): arg_max = key currentMax = value # Print the character # alongwith its frequency print(f"{arg_max} - {currentMax}") # Delete the maximum value occ.pop(arg_max) size -= 1 # Driver codeStr = "geeksforgeeks"Len = len(Str) printChar(list(Str), Len) # This code is contributed by shinjanpatra
// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to print the characters// of the given String in decreasing// order of their frequenciesstatic void printChar(char []arr, int len){ // To store the Dictionary<char, int> occ = new Dictionary<char, int>(); for (int i = 0; i < len; i++) if(occ.ContainsKey(arr[i])) { occ[arr[i]] = occ[arr[i]] + 1; } else { occ.Add(arr[i], 1); } // Map's size int size = occ.Count; // While there are elements in the map while (size-- > 0) { // Finding the maximum value // from the map int currentMax = 0; char arg_max = (char)0; foreach (KeyValuePair<char, int> it in occ) { if (it.Value > currentMax || (it.Value == currentMax && it.Key > arg_max)) { arg_max = it.Key; currentMax = it.Value; } } // Print the character // alongwith its frequency Console.Write(arg_max + " - " + currentMax + "\n"); // Delete the maximum value occ.Remove(arg_max); }} // Driver codepublic static void Main(String[] args){ String str = "geeksforgeeks"; int len = str.Length; printChar(str.ToCharArray(), len);}} // This code is contributed by Princi Singh
<script>// Javascript implementation of the approach // Function to print the characters// of the given String in decreasing// order of their frequenciesfunction printChar(arr, len){ // To store the let occ = new Map(); for (let i = 0; i < len; i++) if(occ.has(arr[i])) { occ.set(arr[i], occ.get(arr[i]) + 1); } else { occ.set(arr[i], 1); } // Map's size let size = occ.size; // While there are elements in the map while (size-- > 0) { // Finding the maximum value // from the map let currentMax = 0; let arg_max = 0; for (let [key, value] of occ.entries()) { if (value > currentMax || (value == currentMax && key > arg_max)) { arg_max = key; currentMax = value; } } // Print the character // alongwith its frequency document.write(arg_max + " - " + currentMax + "<br>"); // Delete the maximum value occ.delete(arg_max); }} // Driver codelet str = "geeksforgeeks";let len = str.length; printChar(str.split(""), len); // This code is contributed by patel2127</script>
e - 4
s - 2
k - 2
g - 2
r - 1
o - 1
f - 1
Approach 2 : We will make an array arr of size one more than the size of given string length in which we will store List of characters whose frequency is equal to the index of arr and follow the below steps :
Make a frequency map using array of characters present in the given string.
Traverse frequency array, if its value is greater than zero let say k.
On kth index of arr store it’s character value in List at index 0(As we need descending order of alphabets if frequency is same).
Traverse arr from backwards as we need greater frequency first if List at that index is not empty than print its frequency and character.
Implementation of above approach :
Java
// Java implementation of above approachimport java.util.*; class GFG { // Driver Code public static void main(String[] args) { String str = "geeksforgeeks"; printChar(str); } @SuppressWarnings("unchecked") // Function to print the characters // of the given string in decreasing // order of their frequencies public static void printChar(String str) { // Initializing array of List type. List<Character>[] arr = new List[str.length() + 1]; for (int i = 0; i <= str.length(); i++) { // Initializing List of type Character. arr[i] = new ArrayList<>(); } int[] freq = new int[256]; // Mapking frequency map for (int i = 0; i < str.length(); i++) { freq[(char)str.charAt(i)]++; } // Traversing frequency array for (int i = 0; i < 256; i++) { if (freq[i] > 0) { // If frequency array is greater than zero // then storing its character on // i-th(frequency of that character) index // of arr arr[freq[i]].add(0, (char)(i)); } } // Traversing arr from backwards as we need greater // frequency character first for (int i = arr.length - 1; i >= 0; i--) { if (!arr[i].isEmpty()) { for (char ch : arr[i]) { System.out.println(ch + "-" + i); } } } }}
e-4
s-2
k-2
g-2
r-1
o-1
f-1
Time Complexity : O(n), n is the length of given string
Auxiliary Space : O(n)
GauravRajput1
princi singh
patel2127
Kdheeraj
shinjanpatra
frequency-counting
Mallow Technologies
Strings
Mallow Technologies
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews
|
[
{
"code": null,
"e": 26019,
"s": 25991,
"text": "\n25 Apr, 2022"
},
{
"code": null,
"e": 26222,
"s": 26019,
"text": "Given string str, the task is to print the characters in decreasing order of their frequency. If the frequency of two characters is the same then sort them in descending order alphabetically.Examples: "
},
{
"code": null,
"e": 26341,
"s": 26222,
"text": "Input: str = “geeksforgeeks” Output: e – 4 s – 2 k – 2 g – 2 r – 1 o – 1 f – 1Input: str = “bbcc” Output: c – 2 b – 2 "
},
{
"code": null,
"e": 26357,
"s": 26343,
"text": "Approach 1: "
},
{
"code": null,
"e": 26444,
"s": 26357,
"text": "Use an unordered_map to store the frequencies of all the elements of the given string."
},
{
"code": null,
"e": 26550,
"s": 26444,
"text": "Find the maximum frequency element from the map, print it with its frequency, and remove it from the map."
},
{
"code": null,
"e": 26603,
"s": 26550,
"text": "Repeat the previous step while the map is not empty."
},
{
"code": null,
"e": 26655,
"s": 26603,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26659,
"s": 26655,
"text": "CPP"
},
{
"code": null,
"e": 26664,
"s": 26659,
"text": "Java"
},
{
"code": null,
"e": 26672,
"s": 26664,
"text": "Python3"
},
{
"code": null,
"e": 26675,
"s": 26672,
"text": "C#"
},
{
"code": null,
"e": 26686,
"s": 26675,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to print the characters// of the given string in decreasing// order of their frequenciesvoid printChar(string str, int len){ // To store the unordered_map<char, int> occ; for (int i = 0; i < len; i++) occ[str[i]]++; // Map's size int size = occ.size(); unordered_map<char, int>::iterator it; // While there are elements in the map while (size--) { // Finding the maximum value // from the map unsigned currentMax = 0; char arg_max; for (it = occ.begin(); it != occ.end(); ++it) { if (it->second > currentMax || (it->second == currentMax && it->first > arg_max)) { arg_max = it->first; currentMax = it->second; } } // Print the character // alongwith its frequency cout << arg_max << \" - \" << currentMax << endl; // Delete the maximum value occ.erase(arg_max); }} // Driver codeint main(){ string str = \"geeksforgeeks\"; int len = str.length(); printChar(str, len); return 0;}",
"e": 27873,
"s": 26686,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*;class GFG{ // Function to print the characters// of the given String in decreasing// order of their frequenciesstatic void printChar(char []arr, int len){ // To store the HashMap<Character, Integer> occ = new HashMap<Character, Integer>(); for (int i = 0; i < len; i++) if(occ.containsKey(arr[i])) { occ.put(arr[i], occ.get(arr[i]) + 1); } else { occ.put(arr[i], 1); } // Map's size int size = occ.size(); // While there are elements in the map while (size-- > 0) { // Finding the maximum value // from the map int currentMax = 0; char arg_max = 0; for (Map.Entry<Character, Integer> it : occ.entrySet()) { if (it.getValue() > currentMax || (it.getValue() == currentMax && it.getKey() > arg_max)) { arg_max = it.getKey(); currentMax = it.getValue(); } } // Print the character // alongwith its frequency System.out.print(arg_max + \" - \" + currentMax + \"\\n\"); // Delete the maximum value occ.remove(arg_max); }} // Driver codepublic static void main(String[] args){ String str = \"geeksforgeeks\"; int len = str.length(); printChar(str.toCharArray(), len);}} // This code is contributed by gauravrajput1",
"e": 29416,
"s": 27873,
"text": null
},
{
"code": "# Python implementation of the approach # Function to print the characters# of the given String in decreasing# order of their frequenciesdef printChar(arr, Len): # To store the occ = {} for i in range(Len): if(arr[i] in occ): occ[arr[i]] = occ[arr[i]] + 1 else: occ[arr[i]] = 1 # Map's size size = len(occ) # While there are elements in the map while (size > 0): # Finding the maximum value # from the map currentMax = 0 arg_max = 0 for key, value in occ.items(): if (value > currentMax or (value == currentMax and key > arg_max)): arg_max = key currentMax = value # Print the character # alongwith its frequency print(f\"{arg_max} - {currentMax}\") # Delete the maximum value occ.pop(arg_max) size -= 1 # Driver codeStr = \"geeksforgeeks\"Len = len(Str) printChar(list(Str), Len) # This code is contributed by shinjanpatra",
"e": 30442,
"s": 29416,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GFG{ // Function to print the characters// of the given String in decreasing// order of their frequenciesstatic void printChar(char []arr, int len){ // To store the Dictionary<char, int> occ = new Dictionary<char, int>(); for (int i = 0; i < len; i++) if(occ.ContainsKey(arr[i])) { occ[arr[i]] = occ[arr[i]] + 1; } else { occ.Add(arr[i], 1); } // Map's size int size = occ.Count; // While there are elements in the map while (size-- > 0) { // Finding the maximum value // from the map int currentMax = 0; char arg_max = (char)0; foreach (KeyValuePair<char, int> it in occ) { if (it.Value > currentMax || (it.Value == currentMax && it.Key > arg_max)) { arg_max = it.Key; currentMax = it.Value; } } // Print the character // alongwith its frequency Console.Write(arg_max + \" - \" + currentMax + \"\\n\"); // Delete the maximum value occ.Remove(arg_max); }} // Driver codepublic static void Main(String[] args){ String str = \"geeksforgeeks\"; int len = str.Length; printChar(str.ToCharArray(), len);}} // This code is contributed by Princi Singh",
"e": 31930,
"s": 30442,
"text": null
},
{
"code": "<script>// Javascript implementation of the approach // Function to print the characters// of the given String in decreasing// order of their frequenciesfunction printChar(arr, len){ // To store the let occ = new Map(); for (let i = 0; i < len; i++) if(occ.has(arr[i])) { occ.set(arr[i], occ.get(arr[i]) + 1); } else { occ.set(arr[i], 1); } // Map's size let size = occ.size; // While there are elements in the map while (size-- > 0) { // Finding the maximum value // from the map let currentMax = 0; let arg_max = 0; for (let [key, value] of occ.entries()) { if (value > currentMax || (value == currentMax && key > arg_max)) { arg_max = key; currentMax = value; } } // Print the character // alongwith its frequency document.write(arg_max + \" - \" + currentMax + \"<br>\"); // Delete the maximum value occ.delete(arg_max); }} // Driver codelet str = \"geeksforgeeks\";let len = str.length; printChar(str.split(\"\"), len); // This code is contributed by patel2127</script>",
"e": 33202,
"s": 31930,
"text": null
},
{
"code": null,
"e": 33244,
"s": 33202,
"text": "e - 4\ns - 2\nk - 2\ng - 2\nr - 1\no - 1\nf - 1"
},
{
"code": null,
"e": 33453,
"s": 33244,
"text": "Approach 2 : We will make an array arr of size one more than the size of given string length in which we will store List of characters whose frequency is equal to the index of arr and follow the below steps :"
},
{
"code": null,
"e": 33529,
"s": 33453,
"text": "Make a frequency map using array of characters present in the given string."
},
{
"code": null,
"e": 33600,
"s": 33529,
"text": "Traverse frequency array, if its value is greater than zero let say k."
},
{
"code": null,
"e": 33730,
"s": 33600,
"text": "On kth index of arr store it’s character value in List at index 0(As we need descending order of alphabets if frequency is same)."
},
{
"code": null,
"e": 33868,
"s": 33730,
"text": "Traverse arr from backwards as we need greater frequency first if List at that index is not empty than print its frequency and character."
},
{
"code": null,
"e": 33903,
"s": 33868,
"text": "Implementation of above approach :"
},
{
"code": null,
"e": 33908,
"s": 33903,
"text": "Java"
},
{
"code": "// Java implementation of above approachimport java.util.*; class GFG { // Driver Code public static void main(String[] args) { String str = \"geeksforgeeks\"; printChar(str); } @SuppressWarnings(\"unchecked\") // Function to print the characters // of the given string in decreasing // order of their frequencies public static void printChar(String str) { // Initializing array of List type. List<Character>[] arr = new List[str.length() + 1]; for (int i = 0; i <= str.length(); i++) { // Initializing List of type Character. arr[i] = new ArrayList<>(); } int[] freq = new int[256]; // Mapking frequency map for (int i = 0; i < str.length(); i++) { freq[(char)str.charAt(i)]++; } // Traversing frequency array for (int i = 0; i < 256; i++) { if (freq[i] > 0) { // If frequency array is greater than zero // then storing its character on // i-th(frequency of that character) index // of arr arr[freq[i]].add(0, (char)(i)); } } // Traversing arr from backwards as we need greater // frequency character first for (int i = arr.length - 1; i >= 0; i--) { if (!arr[i].isEmpty()) { for (char ch : arr[i]) { System.out.println(ch + \"-\" + i); } } } }}",
"e": 35402,
"s": 33908,
"text": null
},
{
"code": null,
"e": 35430,
"s": 35402,
"text": "e-4\ns-2\nk-2\ng-2\nr-1\no-1\nf-1"
},
{
"code": null,
"e": 35486,
"s": 35430,
"text": "Time Complexity : O(n), n is the length of given string"
},
{
"code": null,
"e": 35509,
"s": 35486,
"text": "Auxiliary Space : O(n)"
},
{
"code": null,
"e": 35523,
"s": 35509,
"text": "GauravRajput1"
},
{
"code": null,
"e": 35536,
"s": 35523,
"text": "princi singh"
},
{
"code": null,
"e": 35546,
"s": 35536,
"text": "patel2127"
},
{
"code": null,
"e": 35555,
"s": 35546,
"text": "Kdheeraj"
},
{
"code": null,
"e": 35568,
"s": 35555,
"text": "shinjanpatra"
},
{
"code": null,
"e": 35587,
"s": 35568,
"text": "frequency-counting"
},
{
"code": null,
"e": 35607,
"s": 35587,
"text": "Mallow Technologies"
},
{
"code": null,
"e": 35615,
"s": 35607,
"text": "Strings"
},
{
"code": null,
"e": 35635,
"s": 35615,
"text": "Mallow Technologies"
},
{
"code": null,
"e": 35643,
"s": 35635,
"text": "Strings"
},
{
"code": null,
"e": 35741,
"s": 35643,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35816,
"s": 35741,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 35873,
"s": 35816,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 35909,
"s": 35873,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 35956,
"s": 35909,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 36009,
"s": 35956,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 36045,
"s": 36009,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 36083,
"s": 36045,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 36113,
"s": 36083,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 36165,
"s": 36113,
"text": "Check whether two strings are anagram of each other"
}
] |
GATE | GATE-IT-2004 | Question 13 - GeeksforGeeks
|
28 Jun, 2021
Let P be a singly linked list. Let Q be the pointer to an intermediate node x in the list. What is the worst-case time complexity of the best known algorithm to delete the node x from the list?(A) O(n)(B) O(log2 n)(C) O(logn)(D) O(1)Answer: (D)Explanation: A simple solution is to traverse the linked list until you find the node you want to delete. But this solution requires pointer to the head node which contradicts the problem statement.
Fast solution is to copy the data from the next node to the node to be deleted and delete the next node. Something like following.
// Find next node using next pointer
struct node *temp = node_ptr->next;
// Copy data of next node to this node
node_ptr->data = temp->data;
// Unlink next node
node_ptr->next = temp->next;
// Delete next node
free(temp);
Time complexity of this approach is O(1)
Refer this for implementation.
Note that this approach doesn’t work when node to deleted is last node. Since the question says intermediate node, we can use this approach.Quiz of this Question
GATE IT 2004
GATE-GATE IT 2004
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | Gate IT 2007 | Question 25
GATE | GATE-CS-2001 | Question 39
GATE | GATE-CS-2000 | Question 41
GATE | GATE-CS-2005 | Question 6
GATE | GATE MOCK 2017 | Question 21
GATE | GATE MOCK 2017 | Question 24
GATE | GATE-CS-2006 | Question 47
GATE | Gate IT 2008 | Question 43
GATE | GATE-CS-2009 | Question 38
GATE | GATE-CS-2003 | Question 90
|
[
{
"code": null,
"e": 25743,
"s": 25715,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 26186,
"s": 25743,
"text": "Let P be a singly linked list. Let Q be the pointer to an intermediate node x in the list. What is the worst-case time complexity of the best known algorithm to delete the node x from the list?(A) O(n)(B) O(log2 n)(C) O(logn)(D) O(1)Answer: (D)Explanation: A simple solution is to traverse the linked list until you find the node you want to delete. But this solution requires pointer to the head node which contradicts the problem statement."
},
{
"code": null,
"e": 26317,
"s": 26186,
"text": "Fast solution is to copy the data from the next node to the node to be deleted and delete the next node. Something like following."
},
{
"code": null,
"e": 26578,
"s": 26317,
"text": " // Find next node using next pointer\n struct node *temp = node_ptr->next;\n\n // Copy data of next node to this node\n node_ptr->data = temp->data;\n\n // Unlink next node\n node_ptr->next = temp->next;\n\n // Delete next node\n free(temp);\n"
},
{
"code": null,
"e": 26619,
"s": 26578,
"text": "Time complexity of this approach is O(1)"
},
{
"code": null,
"e": 26650,
"s": 26619,
"text": "Refer this for implementation."
},
{
"code": null,
"e": 26812,
"s": 26650,
"text": "Note that this approach doesn’t work when node to deleted is last node. Since the question says intermediate node, we can use this approach.Quiz of this Question"
},
{
"code": null,
"e": 26825,
"s": 26812,
"text": "GATE IT 2004"
},
{
"code": null,
"e": 26843,
"s": 26825,
"text": "GATE-GATE IT 2004"
},
{
"code": null,
"e": 26848,
"s": 26843,
"text": "GATE"
},
{
"code": null,
"e": 26946,
"s": 26848,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26980,
"s": 26946,
"text": "GATE | Gate IT 2007 | Question 25"
},
{
"code": null,
"e": 27014,
"s": 26980,
"text": "GATE | GATE-CS-2001 | Question 39"
},
{
"code": null,
"e": 27048,
"s": 27014,
"text": "GATE | GATE-CS-2000 | Question 41"
},
{
"code": null,
"e": 27081,
"s": 27048,
"text": "GATE | GATE-CS-2005 | Question 6"
},
{
"code": null,
"e": 27117,
"s": 27081,
"text": "GATE | GATE MOCK 2017 | Question 21"
},
{
"code": null,
"e": 27153,
"s": 27117,
"text": "GATE | GATE MOCK 2017 | Question 24"
},
{
"code": null,
"e": 27187,
"s": 27153,
"text": "GATE | GATE-CS-2006 | Question 47"
},
{
"code": null,
"e": 27221,
"s": 27187,
"text": "GATE | Gate IT 2008 | Question 43"
},
{
"code": null,
"e": 27255,
"s": 27221,
"text": "GATE | GATE-CS-2009 | Question 38"
}
] |
Find all Array elements that are smaller than all elements to their right - GeeksforGeeks
|
05 Apr, 2022
Given an array arr[] containing N positive integers. The task is to find all the elements which are smaller than all the elements to their right.
Examples:
Input: arr[] = {6, 14, 13, 21, 17, 19}Output: [6, 13, 17, 19]Explanation: All the elements in the output are following the condition.
Input: arr[] = {10, 3, 4, 8, 7}Output: [3, 4, 7]
Naive approach: This approach uses two loops. For each element, traverse the array to its right and check if any smaller element exists or not. If all elements in the right part of the array are greater than it, then print this element.
Time complexity: O(N*N)Auxiliary Space: O(1)
Efficient approach: In the efficient approach, the idea is to use a Stack. Follow the steps mentioned below:
Iterate the array from the beginning of the array.
For every element in the array, pop all the elements present in the stack that are greater than it and then push it into the stack.
If no element is greater than it, then the current element is an answer.
At last, the stack remains with elements that are smaller than all elements present to their right.
Below is the code implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to find all elements in array// that are smaller than all elements// to their right.#include <iostream>#include <stack>#include <vector>using namespace std; // Function to print all elements which are// smaller than all elements present// to their rightvoid FindDesiredElements(vector<int> const& arr){ // Create an empty stack stack<int> stk; // Do for each element for (int i : arr) { // Pop all the elements that // are greater than the // current element while (!stk.empty() && stk.top() > i) { stk.pop(); } // Push current element into the stack stk.push(i); } // Print all elements in the stack while (!stk.empty()) { cout << stk.top() << " "; stk.pop(); }} // Driver Codeint main(){ vector<int> arr = { 6, 14, 13, 21, 17, 19 }; FindDesiredElements(arr); return 0;}
// Java program to find all elements in array// that are smaller than all elements// to their right.import java.util.ArrayList;import java.util.Stack; class GFG { // Function to print all elements which are // smaller than all elements present // to their right static void FindDesiredElements(ArrayList<Integer> arr) { // Create an empty stack Stack<Integer> stk = new Stack<Integer>(); // Do for each element for (int i : arr) { // Pop all the elements that // are greater than the // current element while (!stk.empty() && stk.peek() > i) { stk.pop(); } // Push current element into the stack stk.push(i); } // Print all elements in the stack while (!stk.empty()) { System.out.print(stk.peek() + " "); stk.pop(); } } // Driver Code public static void main(String args[]) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(6); arr.add(14); arr.add(13); arr.add(21); arr.add(17); arr.add(19); FindDesiredElements(arr); }} // This code is contributed by saurabh_jaiswal.
# Oython program to find all elements in array# that are smaller than all elements# to their right. # Function to print all elements which are# smaller than all elements present# to their rightdef FindDesiredElements(arr): # Create an empty stack stk = [] # Do for each element for i in arr : # Pop all the elements that # are greater than the # current element while (len(stk)!=0 and stk[len(stk)-1] > i): stk.pop() # Push current element into the stack stk.append(i) # Print all elements in the stack while (len(stk) != 0): print(stk[len(stk)-1],end = " ") stk.pop() # Driver Codearr = []arr.append(6)arr.append(14)arr.append(13)arr.append(21)arr.append(17)arr.append(19) FindDesiredElements(arr) # This code is contributed by shinjanpatra
// C# program to find all elements in array// that are smaller than all elements// to their right.using System;using System.Collections.Generic;public class GFG { // Function to print all elements which are // smaller than all elements present // to their right static void FindDesiredElements(List<int> arr) { // Create an empty stack Stack<int> stk = new Stack<int>(); // Do for each element foreach (int i in arr) { // Pop all the elements that // are greater than the // current element while (stk.Count!=0 && stk.Peek() > i) { stk.Pop(); } // Push current element into the stack stk.Push(i); } // Print all elements in the stack while (stk.Count>0) { Console.Write(stk.Peek() + " "); stk.Pop(); } } // Driver Code public static void Main(String []args) { List<int> arr = new List<int>(); arr.Add(6); arr.Add(14); arr.Add(13); arr.Add(21); arr.Add(17); arr.Add(19); FindDesiredElements(arr); }} // This code is contributed by Rajput-Ji
<script>// javascript program to find all elements in array// that are smaller than all elements// to their right. // Function to print all elements which are // smaller than all elements present // to their right function FindDesiredElements( arr) { // Create an empty stack var stk = []; // Do for each element for (var i of arr) { // Pop all the elements that // are greater than the // current element while (stk.length!=0 && stk[stk.length-1] > i) { stk.pop(); } // Push current element into the stack stk.push(i); } // Print all elements in the stack while (stk.length != 0) { document.write(stk[stk.length-1] + " "); stk.pop(); } } // Driver Code var arr = []; arr.push(6); arr.push(14); arr.push(13); arr.push(21); arr.push(17); arr.push(19); FindDesiredElements(arr); // This code is contributed by Rajput-Ji</script>
19 17 13 6
Time complexity: O(N)Auxiliary Space: O(N)
Space Optimized approach: The idea is to traverse the array from right to left (reverse order) and maintain an auxiliary variable that stores the minimum element found so far. This approach will neglect the use of stack. Follow the below steps:
Start iterating from the end of the array.
If the current element is smaller than the minimum so far, then the element is found. Update the value storing minimum value so far. Print all such values as the answer.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ program to print all elements which are// smaller than all elements present to their right #include <iostream>#include <limits.h>using namespace std; // Function to print all elements which are// smaller than all elements// present to their rightvoid FindDesiredElements(int arr[], int n){ int min_so_far = INT_MAX; // Traverse the array from right to left for (int j = n - 1; j >= 0; j--) { // If the current element is greater // than the maximum so far, print it // and update `max_so_far` if (arr[j] <= min_so_far) { min_so_far = arr[j]; cout << arr[j] << " "; } }} // Driver Codeint main(){ int arr[] = { 6, 14, 13, 21, 17, 19 }; int N = sizeof(arr) / sizeof(arr[0]); FindDesiredElements(arr, N); return 0;}
// Java program for the above approachimport java.util.*;class GFG { // Function to print all elements which are // smaller than all elements // present to their right static void FindDesiredElements(int[] arr, int n) { int min_so_far = Integer.MAX_VALUE; // Traverse the array from right to left for (int j = n - 1; j >= 0; j--) { // If the current element is greater // than the maximum so far, print it // and update `max_so_far` if (arr[j] <= min_so_far) { min_so_far = arr[j]; System.out.print(arr[j] + " "); } } } // Driver Code public static void main(String[] args) { int[] arr = { 6, 14, 13, 21, 17, 19 }; int N = arr.length; FindDesiredElements(arr, N); }} // This code is contributed by code_hunt.
# Python code for the above approach # Function to print all elements which are# smaller than all elements# present to their rightdef FindDesiredElements(arr, n): min_so_far = 10 ** 9; # Traverse the array from right to left for j in range(n - 1, -1, -1): # If the current element is greater # than the maximum so far, print it # and update `max_so_far` if (arr[j] <= min_so_far): min_so_far = arr[j]; print(arr[j], end=" ") # Driver Codearr = [6, 14, 13, 21, 17, 19];N = len(arr) FindDesiredElements(arr, N); # This code is contributed by Saurabh Jaiswal
// C# program to print all elements which are// smaller than all elements present to their right using System;class GFG { // Function to print all elements which are // smaller than all elements // present to their right static void FindDesiredElements(int[] arr, int n) { int min_so_far = Int32.MaxValue; // Traverse the array from right to left for (int j = n - 1; j >= 0; j--) { // If the current element is greater // than the maximum so far, print it // and update `max_so_far` if (arr[j] <= min_so_far) { min_so_far = arr[j]; Console.Write(arr[j] + " "); } } } // Driver Code public static void Main() { int[] arr = { 6, 14, 13, 21, 17, 19 }; int N = arr.Length; FindDesiredElements(arr, N); }}
<script> // JavaScript code for the above approach // Function to print all elements which are // smaller than all elements // present to their right function FindDesiredElements(arr, n) { let min_so_far = Number.MAX_VALUE; // Traverse the array from right to left for (let j = n - 1; j >= 0; j--) { // If the current element is greater // than the maximum so far, print it // and update `max_so_far` if (arr[j] <= min_so_far) { min_so_far = arr[j]; document.write(arr[j] + " "); } } } // Driver Code let arr = [6, 14, 13, 21, 17, 19]; let N = arr.length; FindDesiredElements(arr, N); // This code is contributed by Potta Lokesh </script>
19 17 13 6
Time complexity: O(N)Auxiliary Space: O(1)
lokeshpotta20
_saurabh_jaiswal
ukasp
code_hunt
Rajput-Ji
simranarora5sos
shinjanpatra
Algo-Geek 2021
Algo Geek
Arrays
Greedy
Mathematical
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check if the given string is valid English word or not
Sort strings on the basis of their numeric part
Divide given number into two even parts
Smallest set of vertices to visit all nodes of the given Graph
Bit Manipulation technique to replace boolean arrays of fixed size less than 64
Arrays in Java
Arrays in C/C++
Maximum and minimum of an array using minimum number of comparisons
Write a program to reverse an array or string
Program for array rotation
|
[
{
"code": null,
"e": 27535,
"s": 27507,
"text": "\n05 Apr, 2022"
},
{
"code": null,
"e": 27681,
"s": 27535,
"text": "Given an array arr[] containing N positive integers. The task is to find all the elements which are smaller than all the elements to their right."
},
{
"code": null,
"e": 27691,
"s": 27681,
"text": "Examples:"
},
{
"code": null,
"e": 27825,
"s": 27691,
"text": "Input: arr[] = {6, 14, 13, 21, 17, 19}Output: [6, 13, 17, 19]Explanation: All the elements in the output are following the condition."
},
{
"code": null,
"e": 27874,
"s": 27825,
"text": "Input: arr[] = {10, 3, 4, 8, 7}Output: [3, 4, 7]"
},
{
"code": null,
"e": 28112,
"s": 27874,
"text": "Naive approach: This approach uses two loops. For each element, traverse the array to its right and check if any smaller element exists or not. If all elements in the right part of the array are greater than it, then print this element. "
},
{
"code": null,
"e": 28157,
"s": 28112,
"text": "Time complexity: O(N*N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 28266,
"s": 28157,
"text": "Efficient approach: In the efficient approach, the idea is to use a Stack. Follow the steps mentioned below:"
},
{
"code": null,
"e": 28317,
"s": 28266,
"text": "Iterate the array from the beginning of the array."
},
{
"code": null,
"e": 28449,
"s": 28317,
"text": "For every element in the array, pop all the elements present in the stack that are greater than it and then push it into the stack."
},
{
"code": null,
"e": 28522,
"s": 28449,
"text": "If no element is greater than it, then the current element is an answer."
},
{
"code": null,
"e": 28622,
"s": 28522,
"text": "At last, the stack remains with elements that are smaller than all elements present to their right."
},
{
"code": null,
"e": 28678,
"s": 28622,
"text": "Below is the code implementation of the above approach."
},
{
"code": null,
"e": 28682,
"s": 28678,
"text": "C++"
},
{
"code": null,
"e": 28687,
"s": 28682,
"text": "Java"
},
{
"code": null,
"e": 28695,
"s": 28687,
"text": "Python3"
},
{
"code": null,
"e": 28698,
"s": 28695,
"text": "C#"
},
{
"code": null,
"e": 28709,
"s": 28698,
"text": "Javascript"
},
{
"code": "// C++ program to find all elements in array// that are smaller than all elements// to their right.#include <iostream>#include <stack>#include <vector>using namespace std; // Function to print all elements which are// smaller than all elements present// to their rightvoid FindDesiredElements(vector<int> const& arr){ // Create an empty stack stack<int> stk; // Do for each element for (int i : arr) { // Pop all the elements that // are greater than the // current element while (!stk.empty() && stk.top() > i) { stk.pop(); } // Push current element into the stack stk.push(i); } // Print all elements in the stack while (!stk.empty()) { cout << stk.top() << \" \"; stk.pop(); }} // Driver Codeint main(){ vector<int> arr = { 6, 14, 13, 21, 17, 19 }; FindDesiredElements(arr); return 0;}",
"e": 29607,
"s": 28709,
"text": null
},
{
"code": "// Java program to find all elements in array// that are smaller than all elements// to their right.import java.util.ArrayList;import java.util.Stack; class GFG { // Function to print all elements which are // smaller than all elements present // to their right static void FindDesiredElements(ArrayList<Integer> arr) { // Create an empty stack Stack<Integer> stk = new Stack<Integer>(); // Do for each element for (int i : arr) { // Pop all the elements that // are greater than the // current element while (!stk.empty() && stk.peek() > i) { stk.pop(); } // Push current element into the stack stk.push(i); } // Print all elements in the stack while (!stk.empty()) { System.out.print(stk.peek() + \" \"); stk.pop(); } } // Driver Code public static void main(String args[]) { ArrayList<Integer> arr = new ArrayList<Integer>(); arr.add(6); arr.add(14); arr.add(13); arr.add(21); arr.add(17); arr.add(19); FindDesiredElements(arr); }} // This code is contributed by saurabh_jaiswal.",
"e": 30715,
"s": 29607,
"text": null
},
{
"code": "# Oython program to find all elements in array# that are smaller than all elements# to their right. # Function to print all elements which are# smaller than all elements present# to their rightdef FindDesiredElements(arr): # Create an empty stack stk = [] # Do for each element for i in arr : # Pop all the elements that # are greater than the # current element while (len(stk)!=0 and stk[len(stk)-1] > i): stk.pop() # Push current element into the stack stk.append(i) # Print all elements in the stack while (len(stk) != 0): print(stk[len(stk)-1],end = \" \") stk.pop() # Driver Codearr = []arr.append(6)arr.append(14)arr.append(13)arr.append(21)arr.append(17)arr.append(19) FindDesiredElements(arr) # This code is contributed by shinjanpatra",
"e": 31547,
"s": 30715,
"text": null
},
{
"code": "// C# program to find all elements in array// that are smaller than all elements// to their right.using System;using System.Collections.Generic;public class GFG { // Function to print all elements which are // smaller than all elements present // to their right static void FindDesiredElements(List<int> arr) { // Create an empty stack Stack<int> stk = new Stack<int>(); // Do for each element foreach (int i in arr) { // Pop all the elements that // are greater than the // current element while (stk.Count!=0 && stk.Peek() > i) { stk.Pop(); } // Push current element into the stack stk.Push(i); } // Print all elements in the stack while (stk.Count>0) { Console.Write(stk.Peek() + \" \"); stk.Pop(); } } // Driver Code public static void Main(String []args) { List<int> arr = new List<int>(); arr.Add(6); arr.Add(14); arr.Add(13); arr.Add(21); arr.Add(17); arr.Add(19); FindDesiredElements(arr); }} // This code is contributed by Rajput-Ji",
"e": 32603,
"s": 31547,
"text": null
},
{
"code": "<script>// javascript program to find all elements in array// that are smaller than all elements// to their right. // Function to print all elements which are // smaller than all elements present // to their right function FindDesiredElements( arr) { // Create an empty stack var stk = []; // Do for each element for (var i of arr) { // Pop all the elements that // are greater than the // current element while (stk.length!=0 && stk[stk.length-1] > i) { stk.pop(); } // Push current element into the stack stk.push(i); } // Print all elements in the stack while (stk.length != 0) { document.write(stk[stk.length-1] + \" \"); stk.pop(); } } // Driver Code var arr = []; arr.push(6); arr.push(14); arr.push(13); arr.push(21); arr.push(17); arr.push(19); FindDesiredElements(arr); // This code is contributed by Rajput-Ji</script>",
"e": 33682,
"s": 32603,
"text": null
},
{
"code": null,
"e": 33697,
"s": 33685,
"text": "19 17 13 6 "
},
{
"code": null,
"e": 33741,
"s": 33697,
"text": " Time complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 33986,
"s": 33741,
"text": "Space Optimized approach: The idea is to traverse the array from right to left (reverse order) and maintain an auxiliary variable that stores the minimum element found so far. This approach will neglect the use of stack. Follow the below steps:"
},
{
"code": null,
"e": 34029,
"s": 33986,
"text": "Start iterating from the end of the array."
},
{
"code": null,
"e": 34199,
"s": 34029,
"text": "If the current element is smaller than the minimum so far, then the element is found. Update the value storing minimum value so far. Print all such values as the answer."
},
{
"code": null,
"e": 34251,
"s": 34199,
"text": " Below is the implementation of the above approach."
},
{
"code": null,
"e": 34257,
"s": 34253,
"text": "C++"
},
{
"code": null,
"e": 34262,
"s": 34257,
"text": "Java"
},
{
"code": null,
"e": 34270,
"s": 34262,
"text": "Python3"
},
{
"code": null,
"e": 34273,
"s": 34270,
"text": "C#"
},
{
"code": null,
"e": 34284,
"s": 34273,
"text": "Javascript"
},
{
"code": "// C++ program to print all elements which are// smaller than all elements present to their right #include <iostream>#include <limits.h>using namespace std; // Function to print all elements which are// smaller than all elements// present to their rightvoid FindDesiredElements(int arr[], int n){ int min_so_far = INT_MAX; // Traverse the array from right to left for (int j = n - 1; j >= 0; j--) { // If the current element is greater // than the maximum so far, print it // and update `max_so_far` if (arr[j] <= min_so_far) { min_so_far = arr[j]; cout << arr[j] << \" \"; } }} // Driver Codeint main(){ int arr[] = { 6, 14, 13, 21, 17, 19 }; int N = sizeof(arr) / sizeof(arr[0]); FindDesiredElements(arr, N); return 0;}",
"e": 35088,
"s": 34284,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;class GFG { // Function to print all elements which are // smaller than all elements // present to their right static void FindDesiredElements(int[] arr, int n) { int min_so_far = Integer.MAX_VALUE; // Traverse the array from right to left for (int j = n - 1; j >= 0; j--) { // If the current element is greater // than the maximum so far, print it // and update `max_so_far` if (arr[j] <= min_so_far) { min_so_far = arr[j]; System.out.print(arr[j] + \" \"); } } } // Driver Code public static void main(String[] args) { int[] arr = { 6, 14, 13, 21, 17, 19 }; int N = arr.length; FindDesiredElements(arr, N); }} // This code is contributed by code_hunt.",
"e": 35877,
"s": 35088,
"text": null
},
{
"code": "# Python code for the above approach # Function to print all elements which are# smaller than all elements# present to their rightdef FindDesiredElements(arr, n): min_so_far = 10 ** 9; # Traverse the array from right to left for j in range(n - 1, -1, -1): # If the current element is greater # than the maximum so far, print it # and update `max_so_far` if (arr[j] <= min_so_far): min_so_far = arr[j]; print(arr[j], end=\" \") # Driver Codearr = [6, 14, 13, 21, 17, 19];N = len(arr) FindDesiredElements(arr, N); # This code is contributed by Saurabh Jaiswal",
"e": 36499,
"s": 35877,
"text": null
},
{
"code": "// C# program to print all elements which are// smaller than all elements present to their right using System;class GFG { // Function to print all elements which are // smaller than all elements // present to their right static void FindDesiredElements(int[] arr, int n) { int min_so_far = Int32.MaxValue; // Traverse the array from right to left for (int j = n - 1; j >= 0; j--) { // If the current element is greater // than the maximum so far, print it // and update `max_so_far` if (arr[j] <= min_so_far) { min_so_far = arr[j]; Console.Write(arr[j] + \" \"); } } } // Driver Code public static void Main() { int[] arr = { 6, 14, 13, 21, 17, 19 }; int N = arr.Length; FindDesiredElements(arr, N); }}",
"e": 37368,
"s": 36499,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Function to print all elements which are // smaller than all elements // present to their right function FindDesiredElements(arr, n) { let min_so_far = Number.MAX_VALUE; // Traverse the array from right to left for (let j = n - 1; j >= 0; j--) { // If the current element is greater // than the maximum so far, print it // and update `max_so_far` if (arr[j] <= min_so_far) { min_so_far = arr[j]; document.write(arr[j] + \" \"); } } } // Driver Code let arr = [6, 14, 13, 21, 17, 19]; let N = arr.length; FindDesiredElements(arr, N); // This code is contributed by Potta Lokesh </script>",
"e": 38223,
"s": 37368,
"text": null
},
{
"code": null,
"e": 38238,
"s": 38226,
"text": "19 17 13 6 "
},
{
"code": null,
"e": 38283,
"s": 38240,
"text": "Time complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 38299,
"s": 38285,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 38316,
"s": 38299,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 38322,
"s": 38316,
"text": "ukasp"
},
{
"code": null,
"e": 38332,
"s": 38322,
"text": "code_hunt"
},
{
"code": null,
"e": 38342,
"s": 38332,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 38358,
"s": 38342,
"text": "simranarora5sos"
},
{
"code": null,
"e": 38371,
"s": 38358,
"text": "shinjanpatra"
},
{
"code": null,
"e": 38386,
"s": 38371,
"text": "Algo-Geek 2021"
},
{
"code": null,
"e": 38396,
"s": 38386,
"text": "Algo Geek"
},
{
"code": null,
"e": 38403,
"s": 38396,
"text": "Arrays"
},
{
"code": null,
"e": 38410,
"s": 38403,
"text": "Greedy"
},
{
"code": null,
"e": 38423,
"s": 38410,
"text": "Mathematical"
},
{
"code": null,
"e": 38430,
"s": 38423,
"text": "Arrays"
},
{
"code": null,
"e": 38437,
"s": 38430,
"text": "Greedy"
},
{
"code": null,
"e": 38450,
"s": 38437,
"text": "Mathematical"
},
{
"code": null,
"e": 38548,
"s": 38450,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38603,
"s": 38548,
"text": "Check if the given string is valid English word or not"
},
{
"code": null,
"e": 38651,
"s": 38603,
"text": "Sort strings on the basis of their numeric part"
},
{
"code": null,
"e": 38691,
"s": 38651,
"text": "Divide given number into two even parts"
},
{
"code": null,
"e": 38754,
"s": 38691,
"text": "Smallest set of vertices to visit all nodes of the given Graph"
},
{
"code": null,
"e": 38834,
"s": 38754,
"text": "Bit Manipulation technique to replace boolean arrays of fixed size less than 64"
},
{
"code": null,
"e": 38849,
"s": 38834,
"text": "Arrays in Java"
},
{
"code": null,
"e": 38865,
"s": 38849,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 38933,
"s": 38865,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 38979,
"s": 38933,
"text": "Write a program to reverse an array or string"
}
] |
Compiling a C program:- Behind the Scenes - GeeksforGeeks
|
18 Nov, 2021
C is a mid-level language and it needs a compiler to convert it into an executable code so that the program can be run on our machine.
How do we compile and run a C program?Below are the steps we use on an Ubuntu machine with gcc compiler.
We first create a C program using an editor and save the file as filename.c
$ vi filename.c
The diagram on right shows a simple program to add two numbers.
Then compile it using below command.
$ gcc -Wall filename.c –o filename
The option -Wall enables all compiler’s warning messages. This option is recommended to generate better code. The option -o is used to specify the output file name. If we do not use this option, then an output file with name a.out is generated.
After compilation executable is generated and we run the generated executable using below command.
$ ./filename
What goes inside the compilation process?Compiler converts a C program into an executable. There are four phases for a C program to become an executable:
Pre-processingCompilationAssemblyLinking
Pre-processing
Compilation
Assembly
Linking
By executing below command, We get the all intermediate files in the current directory along with the executable.
$gcc -Wall -save-temps filename.c –o filename
The following screenshot shows all generated intermediate files.
Let us one by one see what these intermediate files contain.
Pre-processing
This is the first phase through which source code is passed. This phase include:
Removal of Comments
Expansion of Macros
Expansion of the included files.
Conditional compilation
The preprocessed output is stored in the filename.i. Let’s see what’s inside filename.i: using $vi filename.i In the above output, source file is filled with lots and lots of info, but at the end our code is preserved. Analysis:
printf contains now a + b rather than add(a, b) that’s because macros have expanded.
Comments are stripped off.
#include<stdio.h> is missing instead we see lots of code. So header files has been expanded and included in our source file.
Compiling
The next step is to compile filename.i and produce an; intermediate compiled output file filename.s. This file is in assembly level instructions. Let’s see through this file using $vi filename.s
The snapshot shows that it is in assembly language, which assembler can understand.
AssemblyIn this phase the filename.s is taken as input and turned into filename.o by assembler. This file contain machine level instructions. At this phase, only existing code is converted into machine language, the function calls like printf() are not resolved. Let’s view this file using $vi filename.o
Linking
This is the final phase in which all the linking of function calls with their definitions are done. Linker knows where all these functions are implemented. Linker does some extra work also, it adds some extra code to our program which is required when the program starts and ends. For example, there is a code which is required for setting up the environment like passing command line arguments. This task can be easily verified by using $size filename.o and $size filename. Through these commands, we know that how output file increases from an object file to an executable file. This is because of the extra code that linker adds with our program.
Note that GCC by default does dynamic linking, so printf() is dynamically linked in above program. Refer this, this and this for more details on static and dynamic linkings. This article is contributed by Vikash Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
akshaychaudhari2
jindmahla238
crazyfeelings111
C Basics
system-programming
C Quiz
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C | Structure & Union | Question 10
C | Advanced Pointer | Question 1
C | Operators | Question 2
C | Pointer Basics | Question 14
C | Advanced Pointer | Question 2
C | Pointer Basics | Question 4
C | Storage Classes and Type Qualifiers | Question 9
C | String | Question 4
C | Pointer Basics | Question 17
C | Advanced Pointer | Question 9
|
[
{
"code": null,
"e": 25525,
"s": 25497,
"text": "\n18 Nov, 2021"
},
{
"code": null,
"e": 25661,
"s": 25525,
"text": "C is a mid-level language and it needs a compiler to convert it into an executable code so that the program can be run on our machine. "
},
{
"code": null,
"e": 25768,
"s": 25661,
"text": "How do we compile and run a C program?Below are the steps we use on an Ubuntu machine with gcc compiler. "
},
{
"code": null,
"e": 25844,
"s": 25768,
"text": "We first create a C program using an editor and save the file as filename.c"
},
{
"code": null,
"e": 25861,
"s": 25844,
"text": " $ vi filename.c"
},
{
"code": null,
"e": 25925,
"s": 25861,
"text": "The diagram on right shows a simple program to add two numbers."
},
{
"code": null,
"e": 25962,
"s": 25925,
"text": "Then compile it using below command."
},
{
"code": null,
"e": 25998,
"s": 25962,
"text": " $ gcc -Wall filename.c –o filename"
},
{
"code": null,
"e": 26243,
"s": 25998,
"text": "The option -Wall enables all compiler’s warning messages. This option is recommended to generate better code. The option -o is used to specify the output file name. If we do not use this option, then an output file with name a.out is generated."
},
{
"code": null,
"e": 26342,
"s": 26243,
"text": "After compilation executable is generated and we run the generated executable using below command."
},
{
"code": null,
"e": 26357,
"s": 26342,
"text": " $ ./filename "
},
{
"code": null,
"e": 26512,
"s": 26357,
"text": "What goes inside the compilation process?Compiler converts a C program into an executable. There are four phases for a C program to become an executable: "
},
{
"code": null,
"e": 26553,
"s": 26512,
"text": "Pre-processingCompilationAssemblyLinking"
},
{
"code": null,
"e": 26568,
"s": 26553,
"text": "Pre-processing"
},
{
"code": null,
"e": 26580,
"s": 26568,
"text": "Compilation"
},
{
"code": null,
"e": 26589,
"s": 26580,
"text": "Assembly"
},
{
"code": null,
"e": 26597,
"s": 26589,
"text": "Linking"
},
{
"code": null,
"e": 26711,
"s": 26597,
"text": "By executing below command, We get the all intermediate files in the current directory along with the executable."
},
{
"code": null,
"e": 26759,
"s": 26711,
"text": " $gcc -Wall -save-temps filename.c –o filename "
},
{
"code": null,
"e": 26825,
"s": 26759,
"text": "The following screenshot shows all generated intermediate files. "
},
{
"code": null,
"e": 26887,
"s": 26825,
"text": "Let us one by one see what these intermediate files contain. "
},
{
"code": null,
"e": 26902,
"s": 26887,
"text": "Pre-processing"
},
{
"code": null,
"e": 26985,
"s": 26902,
"text": "This is the first phase through which source code is passed. This phase include: "
},
{
"code": null,
"e": 27005,
"s": 26985,
"text": "Removal of Comments"
},
{
"code": null,
"e": 27025,
"s": 27005,
"text": "Expansion of Macros"
},
{
"code": null,
"e": 27058,
"s": 27025,
"text": "Expansion of the included files."
},
{
"code": null,
"e": 27082,
"s": 27058,
"text": "Conditional compilation"
},
{
"code": null,
"e": 27313,
"s": 27082,
"text": "The preprocessed output is stored in the filename.i. Let’s see what’s inside filename.i: using $vi filename.i In the above output, source file is filled with lots and lots of info, but at the end our code is preserved. Analysis: "
},
{
"code": null,
"e": 27398,
"s": 27313,
"text": "printf contains now a + b rather than add(a, b) that’s because macros have expanded."
},
{
"code": null,
"e": 27425,
"s": 27398,
"text": "Comments are stripped off."
},
{
"code": null,
"e": 27550,
"s": 27425,
"text": "#include<stdio.h> is missing instead we see lots of code. So header files has been expanded and included in our source file."
},
{
"code": null,
"e": 27560,
"s": 27550,
"text": "Compiling"
},
{
"code": null,
"e": 27757,
"s": 27560,
"text": "The next step is to compile filename.i and produce an; intermediate compiled output file filename.s. This file is in assembly level instructions. Let’s see through this file using $vi filename.s "
},
{
"code": null,
"e": 27842,
"s": 27757,
"text": "The snapshot shows that it is in assembly language, which assembler can understand. "
},
{
"code": null,
"e": 28148,
"s": 27842,
"text": "AssemblyIn this phase the filename.s is taken as input and turned into filename.o by assembler. This file contain machine level instructions. At this phase, only existing code is converted into machine language, the function calls like printf() are not resolved. Let’s view this file using $vi filename.o "
},
{
"code": null,
"e": 28158,
"s": 28150,
"text": "Linking"
},
{
"code": null,
"e": 28810,
"s": 28158,
"text": "This is the final phase in which all the linking of function calls with their definitions are done. Linker knows where all these functions are implemented. Linker does some extra work also, it adds some extra code to our program which is required when the program starts and ends. For example, there is a code which is required for setting up the environment like passing command line arguments. This task can be easily verified by using $size filename.o and $size filename. Through these commands, we know that how output file increases from an object file to an executable file. This is because of the extra code that linker adds with our program. "
},
{
"code": null,
"e": 29154,
"s": 28810,
"text": "Note that GCC by default does dynamic linking, so printf() is dynamically linked in above program. Refer this, this and this for more details on static and dynamic linkings. This article is contributed by Vikash Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29171,
"s": 29154,
"text": "akshaychaudhari2"
},
{
"code": null,
"e": 29184,
"s": 29171,
"text": "jindmahla238"
},
{
"code": null,
"e": 29201,
"s": 29184,
"text": "crazyfeelings111"
},
{
"code": null,
"e": 29210,
"s": 29201,
"text": "C Basics"
},
{
"code": null,
"e": 29229,
"s": 29210,
"text": "system-programming"
},
{
"code": null,
"e": 29236,
"s": 29229,
"text": "C Quiz"
},
{
"code": null,
"e": 29334,
"s": 29236,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29370,
"s": 29334,
"text": "C | Structure & Union | Question 10"
},
{
"code": null,
"e": 29404,
"s": 29370,
"text": "C | Advanced Pointer | Question 1"
},
{
"code": null,
"e": 29431,
"s": 29404,
"text": "C | Operators | Question 2"
},
{
"code": null,
"e": 29464,
"s": 29431,
"text": "C | Pointer Basics | Question 14"
},
{
"code": null,
"e": 29498,
"s": 29464,
"text": "C | Advanced Pointer | Question 2"
},
{
"code": null,
"e": 29530,
"s": 29498,
"text": "C | Pointer Basics | Question 4"
},
{
"code": null,
"e": 29583,
"s": 29530,
"text": "C | Storage Classes and Type Qualifiers | Question 9"
},
{
"code": null,
"e": 29607,
"s": 29583,
"text": "C | String | Question 4"
},
{
"code": null,
"e": 29640,
"s": 29607,
"text": "C | Pointer Basics | Question 17"
}
] |
Golang | Searching an element of int type in slice of ints - GeeksforGeeks
|
28 Aug, 2019
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.In the Go slice, you can search an element of int type in the given slice of ints with the help of SearchInts() function. This function searches for the given element in a sorted slice of ints and returns the index of that element if present in the given slice. And if the given element is not available in the slice(it could be len(s_slice)), then it returns the index to insert the element in the slice. The specified slice must be sorted in ascending order. It is defined under the sort package so, you have to import sort package in your program for accessing SearchInts function.
Syntax:
func SearchInts(s_slice []int, i int) int
Example 1:
// Go program to illustrate how to search// an int type element in the slice of intspackage main import ( "fmt" "sort") // Main functionfunc main() { // Creating and searching an element // in the given slice of ints // Using SearchInts function res1 := sort.SearchInts([]int{1, 2, 3, 4, 5, 6, 7, 8}, 5) res2 := sort.SearchInts([]int{200, 300, 400, 500, 600, 700}, 400) // Displaying the results fmt.Println("Result 1: ", res1) fmt.Println("Result 2: ", res2) }
Output:
Result 1: 4
Result 2: 2
Example 2:
// Go program to illustrate how to search an // element of int type in the slice of intspackage main import ( "fmt" "sort") // Main functionfunc main() { // Creating and initializing // slice of ints using the // shorthand declaration slice_1 := []int{34, 67, 78, 10, 43, 67, 8} slice_2 := []int{100, 500, 300, 600, 900, 1000} var f1, f2, f3 int f1 = 67 f2 = 300 f3 = 100 // Sorting the given slice of ints sort.Ints(slice_1) sort.Ints(slice_2) // Displaying the slices fmt.Println("Slice 1: ", slice_1) fmt.Println("Slice 2: ", slice_2) // Searching a int type element // in the given slice using // the SearchInts function res1 := sort.SearchInts(slice_1, f1) res2 := sort.SearchInts(slice_2, f2) res3 := sort.SearchInts(slice_2, f3) // Displaying the results fmt.Println("Result 1: ", res1) fmt.Println("Result 2: ", res2) fmt.Println("Result 3: ", res3) }
Output:
Slice 1: [8 10 34 43 67 67 78]
Slice 2: [100 300 500 600 900 1000]
Result 1: 4
Result 2: 1
Result 3: 0
Golang
Golang-Slices
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
6 Best Books to Learn Go Programming Language
How to Parse JSON in Golang?
Strings in Golang
Time Durations in Golang
Structures in Golang
How to iterate over an Array using for loop in Golang?
Rune in Golang
Loops in Go Language
Defer Keyword in Golang
Class and Object in Golang
|
[
{
"code": null,
"e": 25703,
"s": 25675,
"text": "\n28 Aug, 2019"
},
{
"code": null,
"e": 26555,
"s": 25703,
"text": "In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice.In the Go slice, you can search an element of int type in the given slice of ints with the help of SearchInts() function. This function searches for the given element in a sorted slice of ints and returns the index of that element if present in the given slice. And if the given element is not available in the slice(it could be len(s_slice)), then it returns the index to insert the element in the slice. The specified slice must be sorted in ascending order. It is defined under the sort package so, you have to import sort package in your program for accessing SearchInts function."
},
{
"code": null,
"e": 26563,
"s": 26555,
"text": "Syntax:"
},
{
"code": null,
"e": 26605,
"s": 26563,
"text": "func SearchInts(s_slice []int, i int) int"
},
{
"code": null,
"e": 26616,
"s": 26605,
"text": "Example 1:"
},
{
"code": "// Go program to illustrate how to search// an int type element in the slice of intspackage main import ( \"fmt\" \"sort\") // Main functionfunc main() { // Creating and searching an element // in the given slice of ints // Using SearchInts function res1 := sort.SearchInts([]int{1, 2, 3, 4, 5, 6, 7, 8}, 5) res2 := sort.SearchInts([]int{200, 300, 400, 500, 600, 700}, 400) // Displaying the results fmt.Println(\"Result 1: \", res1) fmt.Println(\"Result 2: \", res2) }",
"e": 27162,
"s": 26616,
"text": null
},
{
"code": null,
"e": 27170,
"s": 27162,
"text": "Output:"
},
{
"code": null,
"e": 27197,
"s": 27170,
"text": "Result 1: 4\nResult 2: 2\n"
},
{
"code": null,
"e": 27208,
"s": 27197,
"text": "Example 2:"
},
{
"code": "// Go program to illustrate how to search an // element of int type in the slice of intspackage main import ( \"fmt\" \"sort\") // Main functionfunc main() { // Creating and initializing // slice of ints using the // shorthand declaration slice_1 := []int{34, 67, 78, 10, 43, 67, 8} slice_2 := []int{100, 500, 300, 600, 900, 1000} var f1, f2, f3 int f1 = 67 f2 = 300 f3 = 100 // Sorting the given slice of ints sort.Ints(slice_1) sort.Ints(slice_2) // Displaying the slices fmt.Println(\"Slice 1: \", slice_1) fmt.Println(\"Slice 2: \", slice_2) // Searching a int type element // in the given slice using // the SearchInts function res1 := sort.SearchInts(slice_1, f1) res2 := sort.SearchInts(slice_2, f2) res3 := sort.SearchInts(slice_2, f3) // Displaying the results fmt.Println(\"Result 1: \", res1) fmt.Println(\"Result 2: \", res2) fmt.Println(\"Result 3: \", res3) }",
"e": 28167,
"s": 27208,
"text": null
},
{
"code": null,
"e": 28175,
"s": 28167,
"text": "Output:"
},
{
"code": null,
"e": 28284,
"s": 28175,
"text": "Slice 1: [8 10 34 43 67 67 78]\nSlice 2: [100 300 500 600 900 1000]\nResult 1: 4\nResult 2: 1\nResult 3: 0\n"
},
{
"code": null,
"e": 28291,
"s": 28284,
"text": "Golang"
},
{
"code": null,
"e": 28305,
"s": 28291,
"text": "Golang-Slices"
},
{
"code": null,
"e": 28317,
"s": 28305,
"text": "Go Language"
},
{
"code": null,
"e": 28415,
"s": 28317,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28461,
"s": 28415,
"text": "6 Best Books to Learn Go Programming Language"
},
{
"code": null,
"e": 28490,
"s": 28461,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 28508,
"s": 28490,
"text": "Strings in Golang"
},
{
"code": null,
"e": 28533,
"s": 28508,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 28554,
"s": 28533,
"text": "Structures in Golang"
},
{
"code": null,
"e": 28609,
"s": 28554,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 28624,
"s": 28609,
"text": "Rune in Golang"
},
{
"code": null,
"e": 28645,
"s": 28624,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 28669,
"s": 28645,
"text": "Defer Keyword in Golang"
}
] |
Check if a Number is Odd or Even using Bitwise Operators - GeeksforGeeks
|
11 Nov, 2021
Given a number N, the task is to check whether the number is even or odd using Bitwise Operators.Examples:
Input: N = 11 Output: OddInput: N = 10 Output: Even
Following Bitwise Operators can be used to check if a number is odd or even:
1. Using Bitwise XOR operator: The idea is to check whether the last bit of the number is set or not. If the last bit is set then the number is odd, otherwise even. As we know bitwise XOR Operation of the Number by 1 increment the value of the number by 1 if the number is even otherwise it decrements the value of the number by 1 if the value is odd.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check for even or odd// using Bitwise XOR operator #include <iostream>using namespace std; // Returns true if n is even, else oddbool isEven(int n){ // n^1 is n+1, then even, else odd if (n ^ 1 == n + 1) return true; else return false;} // Driver codeint main(){ int n = 100; isEven(n)? cout << "Even": cout << "Odd"; return 0;}
// Java program to check for even or odd// using Bitwise XOR operatorclass GFG{ // Returns true if n is even, else odd static boolean isEven(int n) { // n^1 is n+1, then even, else odd if ((n ^ 1) == n + 1) return true; else return false; } // Driver code public static void main(String[] args) { int n = 100; System.out.print(isEven(n) == true ? "Even" : "Odd"); }} // This code is contributed by Rajput-Ji
# Python3 program to check for even or odd# using Bitwise XOR operator # Returns true if n is even, else odddef isEven( n) : # n^1 is n+1, then even, else odd if (n ^ 1 == n + 1) : return True; else : return False; # Driver codeif __name__ == "__main__" : n = 100; print("Even") if isEven(n) else print( "Odd"); # This code is contributed by AnkitRai01
// C# program to check for even or odd// using Bitwise XOR operatorusing System; class GFG{ // Returns true if n is even, else odd static bool isEven(int n) { // n^1 is n+1, then even, else odd if ((n ^ 1) == n + 1) return true; else return false; } // Driver code public static void Main(String[] args) { int n = 100; Console.Write(isEven(n) == true ? "Even" : "Odd"); }} // This code is contributed by Rajput-Ji
<script> // JavaScript program to check for even or odd// using Bitwise XOR operator // Returns true if n is even, else oddfunction isEven(n){ // n^1 is n+1, then even, else odd if (n ^ 1 == n + 1) return true; else return false;} // Driver code let n = 100; isEven(n)? document.write("Even"): document.write("Odd"); // This code is contributed by Surbhi Tyagi. </script>
Even
2. Using Bitwise AND operator: The idea is to check whether the last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.As we know bitwise AND Operation of the Number by 1 will be 1, If it is odd because the last bit will be already set. Otherwise it will give 0 as output.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check for even or odd// using Bitwise AND operator#include <iostream>using namespace std; // Returns true if n is even, else oddbool isEven(int n){ // n&1 is 1, then odd, else even return (!(n & 1));} // Driver codeint main(){ int n = 101; isEven(n) ? cout << "Even" : cout << "Odd"; return 0;}
// Java program to check for even or odd// using Bitwise AND operatorclass GFG{ // Returns true if n is even, else oddstatic boolean isEven(int n){ // n&1 is 1, then odd, else even return ((n & 1)!=1);} // Driver codepublic static void main(String[] args){ int n = 101; System.out.print(isEven(n) == true ? "Even" : "Odd");}} // This code is contributed by PrinciRaj1992
# Python3 program to check for even or odd# using Bitwise AND operator # Returns true if n is even, else odddef isEven(n) : # n&1 is 1, then odd, else even return (not(n & 1)); # Driver codeif __name__ == "__main__" : n = 101; if isEven(n) : print("Even") else: print("Odd"); # This code is contributed by AnkitRai01
// C# program to check for even or odd// using Bitwise AND operatorusing System; class GFG{ // Returns true if n is even, else odd static bool isEven(int n) { // n&1 is 1, then odd, else even return ((n & 1) != 1); } // Driver code public static void Main() { int n = 101; Console.Write(isEven(n) == true ? "Even" : "Odd"); }} // This code is contributed by AnkitRai01
<script>// javascript program to check for even or odd// using Bitwise AND operator // Returns true if n is even, else oddfunction isEven(n){ // n&1 is 1, then odd, else even return ((n & 1)!=1);} // Driver codevar n = 101;document.write(isEven(n) == true ? "Even" : "Odd"); // This code is contributed by Princi Singh</script>
Odd
3. Using Bitwise OR operator: The idea is to check whether the last bit of the number is set or not. If the last bit is set then the number is odd, otherwise even. As we know bitwise OR Operation of the Number by 1 increment the value of the number by 1 if the number is even otherwise it will remain unchanged. So, if after OR operation of number with 1 gives a result which is greater than the number then it is even and we will return true otherwise it is odd and we will return false.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check for even or odd// using Bitwise OR operator #include <iostream>using namespace std; // Returns true if n is even, else oddbool isEven(int n){ // n|1 is greater than n, then even, else odd if ((n | 1) > n) return true; else return false;} // Driver codeint main(){ int n = 100; isEven(n) ? cout << "Even" : cout << "Odd"; return 0;}
// Java program to check for even or odd// using Bitwise OR operatorclass GFG{ // Returns true if n is even, else odd static boolean isEven(int n) { // n|1 is greater than n, then even, else odd if ((n | 1) > n) return true; else return false; } // Driver code public static void main(String[] args) { int n = 100; System.out.print(isEven(n) == true ? "Even" : "Odd"); }}
# Python3 program to check for even or odd# using Bitwise OR operator # Returns true if n is even, else odddef isEven( n) : # n|1 is greater then n, then even, else odd if (n | 1 > n) : return True; else : return False; # Driver codeif __name__ == "__main__" : n = 100; print("Even") if isEven(n) else print( "Odd");
// C# program to check for even or odd// using Bitwise XOR operatorusing System; class GFG{ // Returns true if n is even, else odd static bool isEven(int n) { // n|1 is greater then n, then even, else odd if ((n | 1) > n) return true; else return false; } // Driver code public static void Main(String[] args) { int n = 100; Console.Write(isEven(n) == true ? "Even" : "Odd"); }} // This code is contributed by Rajput-Ji
<script>// javascript program to check for even or odd// using Bitwise OR operator // Returns true if n is even, else oddfunction isEven(n){ // n|1 is greater than n, then even, else odd if ((n | 1) > n) return true; else return false;} // Driver codevar n = 100;document.write(isEven(n) == true ? "Even" : "Odd"); // This code is contributed by Amit Katiyar.</script>
Even
Time Complexity: O(1)
Rajput-Ji
ankthon
princiraj1992
coder_nero
surbhityagi15
princi singh
amit143katiyar
ahampriyanshu
Bitwise-AND
Bitwise-XOR
Bit Magic
School Programming
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Cyclic Redundancy Check and Modulo-2 Division
Add two numbers without using arithmetic operators
Josephus problem | Set 1 (A O(n) Solution)
Set, Clear and Toggle a given bit of a number in C
Bit Fields in C
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
C++ Classes and Objects
|
[
{
"code": null,
"e": 26574,
"s": 26546,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 26683,
"s": 26574,
"text": "Given a number N, the task is to check whether the number is even or odd using Bitwise Operators.Examples: "
},
{
"code": null,
"e": 26737,
"s": 26683,
"text": "Input: N = 11 Output: OddInput: N = 10 Output: Even "
},
{
"code": null,
"e": 26817,
"s": 26739,
"text": "Following Bitwise Operators can be used to check if a number is odd or even: "
},
{
"code": null,
"e": 27169,
"s": 26817,
"text": "1. Using Bitwise XOR operator: The idea is to check whether the last bit of the number is set or not. If the last bit is set then the number is odd, otherwise even. As we know bitwise XOR Operation of the Number by 1 increment the value of the number by 1 if the number is even otherwise it decrements the value of the number by 1 if the value is odd."
},
{
"code": null,
"e": 27221,
"s": 27169,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27225,
"s": 27221,
"text": "C++"
},
{
"code": null,
"e": 27230,
"s": 27225,
"text": "Java"
},
{
"code": null,
"e": 27238,
"s": 27230,
"text": "Python3"
},
{
"code": null,
"e": 27241,
"s": 27238,
"text": "C#"
},
{
"code": null,
"e": 27252,
"s": 27241,
"text": "Javascript"
},
{
"code": "// C++ program to check for even or odd// using Bitwise XOR operator #include <iostream>using namespace std; // Returns true if n is even, else oddbool isEven(int n){ // n^1 is n+1, then even, else odd if (n ^ 1 == n + 1) return true; else return false;} // Driver codeint main(){ int n = 100; isEven(n)? cout << \"Even\": cout << \"Odd\"; return 0;}",
"e": 27633,
"s": 27252,
"text": null
},
{
"code": "// Java program to check for even or odd// using Bitwise XOR operatorclass GFG{ // Returns true if n is even, else odd static boolean isEven(int n) { // n^1 is n+1, then even, else odd if ((n ^ 1) == n + 1) return true; else return false; } // Driver code public static void main(String[] args) { int n = 100; System.out.print(isEven(n) == true ? \"Even\" : \"Odd\"); }} // This code is contributed by Rajput-Ji",
"e": 28125,
"s": 27633,
"text": null
},
{
"code": "# Python3 program to check for even or odd# using Bitwise XOR operator # Returns true if n is even, else odddef isEven( n) : # n^1 is n+1, then even, else odd if (n ^ 1 == n + 1) : return True; else : return False; # Driver codeif __name__ == \"__main__\" : n = 100; print(\"Even\") if isEven(n) else print( \"Odd\"); # This code is contributed by AnkitRai01",
"e": 28508,
"s": 28125,
"text": null
},
{
"code": "// C# program to check for even or odd// using Bitwise XOR operatorusing System; class GFG{ // Returns true if n is even, else odd static bool isEven(int n) { // n^1 is n+1, then even, else odd if ((n ^ 1) == n + 1) return true; else return false; } // Driver code public static void Main(String[] args) { int n = 100; Console.Write(isEven(n) == true ? \"Even\" : \"Odd\"); }} // This code is contributed by Rajput-Ji",
"e": 29006,
"s": 28508,
"text": null
},
{
"code": "<script> // JavaScript program to check for even or odd// using Bitwise XOR operator // Returns true if n is even, else oddfunction isEven(n){ // n^1 is n+1, then even, else odd if (n ^ 1 == n + 1) return true; else return false;} // Driver code let n = 100; isEven(n)? document.write(\"Even\"): document.write(\"Odd\"); // This code is contributed by Surbhi Tyagi. </script>",
"e": 29409,
"s": 29006,
"text": null
},
{
"code": null,
"e": 29414,
"s": 29409,
"text": "Even"
},
{
"code": null,
"e": 29729,
"s": 29414,
"text": "2. Using Bitwise AND operator: The idea is to check whether the last bit of the number is set or not. If last bit is set then the number is odd, otherwise even.As we know bitwise AND Operation of the Number by 1 will be 1, If it is odd because the last bit will be already set. Otherwise it will give 0 as output. "
},
{
"code": null,
"e": 29782,
"s": 29729,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 29786,
"s": 29782,
"text": "C++"
},
{
"code": null,
"e": 29791,
"s": 29786,
"text": "Java"
},
{
"code": null,
"e": 29799,
"s": 29791,
"text": "Python3"
},
{
"code": null,
"e": 29802,
"s": 29799,
"text": "C#"
},
{
"code": null,
"e": 29813,
"s": 29802,
"text": "Javascript"
},
{
"code": "// C++ program to check for even or odd// using Bitwise AND operator#include <iostream>using namespace std; // Returns true if n is even, else oddbool isEven(int n){ // n&1 is 1, then odd, else even return (!(n & 1));} // Driver codeint main(){ int n = 101; isEven(n) ? cout << \"Even\" : cout << \"Odd\"; return 0;}",
"e": 30151,
"s": 29813,
"text": null
},
{
"code": "// Java program to check for even or odd// using Bitwise AND operatorclass GFG{ // Returns true if n is even, else oddstatic boolean isEven(int n){ // n&1 is 1, then odd, else even return ((n & 1)!=1);} // Driver codepublic static void main(String[] args){ int n = 101; System.out.print(isEven(n) == true ? \"Even\" : \"Odd\");}} // This code is contributed by PrinciRaj1992",
"e": 30542,
"s": 30151,
"text": null
},
{
"code": "# Python3 program to check for even or odd# using Bitwise AND operator # Returns true if n is even, else odddef isEven(n) : # n&1 is 1, then odd, else even return (not(n & 1)); # Driver codeif __name__ == \"__main__\" : n = 101; if isEven(n) : print(\"Even\") else: print(\"Odd\"); # This code is contributed by AnkitRai01",
"e": 30890,
"s": 30542,
"text": null
},
{
"code": "// C# program to check for even or odd// using Bitwise AND operatorusing System; class GFG{ // Returns true if n is even, else odd static bool isEven(int n) { // n&1 is 1, then odd, else even return ((n & 1) != 1); } // Driver code public static void Main() { int n = 101; Console.Write(isEven(n) == true ? \"Even\" : \"Odd\"); }} // This code is contributed by AnkitRai01",
"e": 31325,
"s": 30890,
"text": null
},
{
"code": "<script>// javascript program to check for even or odd// using Bitwise AND operator // Returns true if n is even, else oddfunction isEven(n){ // n&1 is 1, then odd, else even return ((n & 1)!=1);} // Driver codevar n = 101;document.write(isEven(n) == true ? \"Even\" : \"Odd\"); // This code is contributed by Princi Singh</script>",
"e": 31669,
"s": 31325,
"text": null
},
{
"code": null,
"e": 31673,
"s": 31669,
"text": "Odd"
},
{
"code": null,
"e": 32162,
"s": 31673,
"text": "3. Using Bitwise OR operator: The idea is to check whether the last bit of the number is set or not. If the last bit is set then the number is odd, otherwise even. As we know bitwise OR Operation of the Number by 1 increment the value of the number by 1 if the number is even otherwise it will remain unchanged. So, if after OR operation of number with 1 gives a result which is greater than the number then it is even and we will return true otherwise it is odd and we will return false."
},
{
"code": null,
"e": 32214,
"s": 32162,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 32218,
"s": 32214,
"text": "C++"
},
{
"code": null,
"e": 32223,
"s": 32218,
"text": "Java"
},
{
"code": null,
"e": 32231,
"s": 32223,
"text": "Python3"
},
{
"code": null,
"e": 32234,
"s": 32231,
"text": "C#"
},
{
"code": null,
"e": 32245,
"s": 32234,
"text": "Javascript"
},
{
"code": "// C++ program to check for even or odd// using Bitwise OR operator #include <iostream>using namespace std; // Returns true if n is even, else oddbool isEven(int n){ // n|1 is greater than n, then even, else odd if ((n | 1) > n) return true; else return false;} // Driver codeint main(){ int n = 100; isEven(n) ? cout << \"Even\" : cout << \"Odd\"; return 0;}",
"e": 32641,
"s": 32245,
"text": null
},
{
"code": "// Java program to check for even or odd// using Bitwise OR operatorclass GFG{ // Returns true if n is even, else odd static boolean isEven(int n) { // n|1 is greater than n, then even, else odd if ((n | 1) > n) return true; else return false; } // Driver code public static void main(String[] args) { int n = 100; System.out.print(isEven(n) == true ? \"Even\" : \"Odd\"); }}",
"e": 33096,
"s": 32641,
"text": null
},
{
"code": "# Python3 program to check for even or odd# using Bitwise OR operator # Returns true if n is even, else odddef isEven( n) : # n|1 is greater then n, then even, else odd if (n | 1 > n) : return True; else : return False; # Driver codeif __name__ == \"__main__\" : n = 100; print(\"Even\") if isEven(n) else print( \"Odd\");",
"e": 33443,
"s": 33096,
"text": null
},
{
"code": "// C# program to check for even or odd// using Bitwise XOR operatorusing System; class GFG{ // Returns true if n is even, else odd static bool isEven(int n) { // n|1 is greater then n, then even, else odd if ((n | 1) > n) return true; else return false; } // Driver code public static void Main(String[] args) { int n = 100; Console.Write(isEven(n) == true ? \"Even\" : \"Odd\"); }} // This code is contributed by Rajput-Ji",
"e": 33947,
"s": 33443,
"text": null
},
{
"code": "<script>// javascript program to check for even or odd// using Bitwise OR operator // Returns true if n is even, else oddfunction isEven(n){ // n|1 is greater than n, then even, else odd if ((n | 1) > n) return true; else return false;} // Driver codevar n = 100;document.write(isEven(n) == true ? \"Even\" : \"Odd\"); // This code is contributed by Amit Katiyar.</script>",
"e": 34340,
"s": 33947,
"text": null
},
{
"code": null,
"e": 34345,
"s": 34340,
"text": "Even"
},
{
"code": null,
"e": 34367,
"s": 34345,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 34377,
"s": 34367,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 34385,
"s": 34377,
"text": "ankthon"
},
{
"code": null,
"e": 34399,
"s": 34385,
"text": "princiraj1992"
},
{
"code": null,
"e": 34410,
"s": 34399,
"text": "coder_nero"
},
{
"code": null,
"e": 34424,
"s": 34410,
"text": "surbhityagi15"
},
{
"code": null,
"e": 34437,
"s": 34424,
"text": "princi singh"
},
{
"code": null,
"e": 34452,
"s": 34437,
"text": "amit143katiyar"
},
{
"code": null,
"e": 34466,
"s": 34452,
"text": "ahampriyanshu"
},
{
"code": null,
"e": 34478,
"s": 34466,
"text": "Bitwise-AND"
},
{
"code": null,
"e": 34490,
"s": 34478,
"text": "Bitwise-XOR"
},
{
"code": null,
"e": 34500,
"s": 34490,
"text": "Bit Magic"
},
{
"code": null,
"e": 34519,
"s": 34500,
"text": "School Programming"
},
{
"code": null,
"e": 34529,
"s": 34519,
"text": "Bit Magic"
},
{
"code": null,
"e": 34627,
"s": 34529,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34673,
"s": 34627,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 34724,
"s": 34673,
"text": "Add two numbers without using arithmetic operators"
},
{
"code": null,
"e": 34767,
"s": 34724,
"text": "Josephus problem | Set 1 (A O(n) Solution)"
},
{
"code": null,
"e": 34818,
"s": 34767,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 34834,
"s": 34818,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 34852,
"s": 34834,
"text": "Python Dictionary"
},
{
"code": null,
"e": 34868,
"s": 34852,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 34887,
"s": 34868,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 34912,
"s": 34887,
"text": "Reverse a string in Java"
}
] |
find_element_by_name() driver method - Selenium Python - GeeksforGeeks
|
20 Oct, 2021
Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeks for geeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_name() is discussed in this articleSyntax –
driver.find_element_by_name("name_of_element")
Example – For instance, consider this page source:
html
<html> <body> <form id="loginForm"> <input name="username" type="text" /> <input name="password" type="password" /> <input name="continue" type="submit" value="Login" /> </form> </body><html>
Now after you have created a driver, you can grab an element using –
login_form = driver.find_element_by_name('username')
How to use driver.find_element_by_name() method in Selenium?
Let’s try to practically implement this method and get an element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its name “search”. Create a file called run.py to demonstrate the find_element_by_name method –
Python3
# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = "geeksforgeeks" # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get elementelement = driver.find_element_by_name("search") # print complete elementprint(element)
Now run using –
Python run.py
First, it will open the firefox window with geeks for geeks, and then select the element and print it on the terminal as shown below. Browser Output
Terminal Output –
.math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; }
NaveenArora
rajeev0719singh
anikakapoor
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 24809,
"s": 24781,
"text": "\n20 Oct, 2021"
},
{
"code": null,
"e": 25510,
"s": 24809,
"text": "Selenium’s Python Module is built to perform automated testing with Python. Selenium Python bindings provide a simple API to write functional/acceptance tests using Selenium WebDriver. After you have installed selenium and checked out – Navigating links using get method, you might want to play more with Selenium Python. After one has opened a page using selenium such as geeks for geeks, one might want to click some buttons automatically or fill a form automatically or any such automated task. This article revolves around how to grab or locate elements in a webpage using locating strategies of Selenium Web Driver. More specifically, find_element_by_name() is discussed in this articleSyntax – "
},
{
"code": null,
"e": 25557,
"s": 25510,
"text": "driver.find_element_by_name(\"name_of_element\")"
},
{
"code": null,
"e": 25609,
"s": 25557,
"text": "Example – For instance, consider this page source: "
},
{
"code": null,
"e": 25614,
"s": 25609,
"text": "html"
},
{
"code": "<html> <body> <form id=\"loginForm\"> <input name=\"username\" type=\"text\" /> <input name=\"password\" type=\"password\" /> <input name=\"continue\" type=\"submit\" value=\"Login\" /> </form> </body><html>",
"e": 25814,
"s": 25614,
"text": null
},
{
"code": null,
"e": 25885,
"s": 25814,
"text": "Now after you have created a driver, you can grab an element using – "
},
{
"code": null,
"e": 25938,
"s": 25885,
"text": "login_form = driver.find_element_by_name('username')"
},
{
"code": null,
"e": 26000,
"s": 25938,
"text": " How to use driver.find_element_by_name() method in Selenium?"
},
{
"code": null,
"e": 26252,
"s": 26000,
"text": "Let’s try to practically implement this method and get an element instance for “https://www.geeksforgeeks.org/”. Let’s try to grab search form input using its name “search”. Create a file called run.py to demonstrate the find_element_by_name method – "
},
{
"code": null,
"e": 26260,
"s": 26252,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# selenium # import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # enter keyword to searchkeyword = \"geeksforgeeks\" # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get elementelement = driver.find_element_by_name(\"search\") # print complete elementprint(element)",
"e": 26624,
"s": 26260,
"text": null
},
{
"code": null,
"e": 26641,
"s": 26624,
"text": "Now run using – "
},
{
"code": null,
"e": 26655,
"s": 26641,
"text": "Python run.py"
},
{
"code": null,
"e": 26805,
"s": 26655,
"text": "First, it will open the firefox window with geeks for geeks, and then select the element and print it on the terminal as shown below. Browser Output "
},
{
"code": null,
"e": 26825,
"s": 26805,
"text": "Terminal Output – "
},
{
"code": null,
"e": 27167,
"s": 26827,
"text": ".math-table { border-collapse: collapse; width: 100%; } .math-table td { border: 1px solid #5fb962; text-align: left !important; padding: 8px; } .math-table th { border: 1px solid #5fb962; padding: 8px; } .math-table tr>th{ background-color: #c6ebd9; vertical-align: middle; } .math-table tr:nth-child(odd) { background-color: #ffffff; } "
},
{
"code": null,
"e": 27185,
"s": 27173,
"text": "NaveenArora"
},
{
"code": null,
"e": 27201,
"s": 27185,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 27213,
"s": 27201,
"text": "anikakapoor"
},
{
"code": null,
"e": 27229,
"s": 27213,
"text": "Python-selenium"
},
{
"code": null,
"e": 27238,
"s": 27229,
"text": "selenium"
},
{
"code": null,
"e": 27245,
"s": 27238,
"text": "Python"
},
{
"code": null,
"e": 27343,
"s": 27245,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27361,
"s": 27343,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27396,
"s": 27361,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 27418,
"s": 27396,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27450,
"s": 27418,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27480,
"s": 27450,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27522,
"s": 27480,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27548,
"s": 27522,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27585,
"s": 27548,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27628,
"s": 27585,
"text": "Python program to convert a list to string"
}
] |
AbstractSequentialList in Java with Examples - GeeksforGeeks
|
11 Nov, 2020
The AbstractSequentialList class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractCollection class. It is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods.
This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a “sequential access” data store (such as a linked list). For random access data (such as an array), AbstractList should be used in preference to this class.
Class Hierarchy:
Declaration:
public abstract class AbstractSequentialList<E>
extends AbstractList<E>
Where E is the type of element maintained by this List.
It implements Iterable<E>, Collection<E>, List<E> interfaces. LinkedList is the only direct subclass of AbstractSequentialList.
Constructor: protected AbstractSequentialList() – The default constructor, but being protected, it doesn’t allow to create an AbstractSequentialList object.
AbstractSequentialList<E> asl = new LinkedList<E>();
Example 1: AbstractSequentialList is an abstract class, so it should be assigned an instance of its subclass such as LinkedList.
Java
// Java code to illustrate AbstractSequentialListimport java.util.*; public class GfG { public static void main(String[] args) { // Creating an instance of // the AbstractSequentialList AbstractSequentialList<Integer> absl = new LinkedList<>(); // adding elements to absl absl.add(5); absl.add(6); absl.add(7); // Printing the list System.out.println(absl); }}
Output:
[5, 6, 7]
Example 2:
Java
// Java code to illustrate// methods of AbstractSequentialList import java.util.*;import java.util.AbstractSequentialList; public class AbstractSequentialListDemo { public static void main(String args[]) { // Creating an empty AbstractSequentialList AbstractSequentialList<String> absqlist = new LinkedList<String>(); // Using add() method to // add elements in the list absqlist.add("Geeks"); absqlist.add("for"); absqlist.add("Geeks"); absqlist.add("10"); absqlist.add("20"); // Output the list System.out.println("AbstractSequentialList: " + absqlist); // Remove the head using remove() absqlist.remove(3); // Print the final list System.out.println("Final List: " + absqlist); // Fetching the specific // element from the list // using get() method System.out.println("The element is: " + absqlist.get(2)); }}
Output:
AbstractSequentialList: [Geeks, for, Geeks, 10, 20]
Final List: [Geeks, for, Geeks, 20]
The element is: Geeks
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
METHOD
DESCRIPTION
Appends all of the elements in the specified collection to the end of this list, in the order that they are
returned by the specified collection’s iterator (optional operation).
Returns an array containing all of the elements in this list in proper sequence (from first to last element);
the runtime type of the returned array is that of the specified array.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/AbstractSequentialList.html
Ganeshchowdharysadanala
Java - util package
java-AbstractSequentialList
Java-Collections
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Arrays.sort() in Java with examples
Reverse a string in Java
Initialize an ArrayList in Java
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Interfaces in Java
ArrayList in Java
|
[
{
"code": null,
"e": 24852,
"s": 24824,
"text": "\n11 Nov, 2020"
},
{
"code": null,
"e": 25168,
"s": 24852,
"text": "The AbstractSequentialList class in Java is a part of the Java Collection Framework and implements the Collection interface and the AbstractCollection class. It is used to implement an unmodifiable list, for which one needs to only extend this AbstractList Class and implement only the get() and the size() methods."
},
{
"code": null,
"e": 25464,
"s": 25168,
"text": "This class provides a skeletal implementation of the List interface to minimize the effort required to implement this interface backed by a “sequential access” data store (such as a linked list). For random access data (such as an array), AbstractList should be used in preference to this class."
},
{
"code": null,
"e": 25482,
"s": 25464,
"text": "Class Hierarchy: "
},
{
"code": null,
"e": 25496,
"s": 25482,
"text": "Declaration: "
},
{
"code": null,
"e": 25631,
"s": 25496,
"text": "public abstract class AbstractSequentialList<E>\n extends AbstractList<E>\n\nWhere E is the type of element maintained by this List.\n\n"
},
{
"code": null,
"e": 25759,
"s": 25631,
"text": "It implements Iterable<E>, Collection<E>, List<E> interfaces. LinkedList is the only direct subclass of AbstractSequentialList."
},
{
"code": null,
"e": 25916,
"s": 25759,
"text": "Constructor: protected AbstractSequentialList() – The default constructor, but being protected, it doesn’t allow to create an AbstractSequentialList object."
},
{
"code": null,
"e": 25971,
"s": 25916,
"text": "AbstractSequentialList<E> asl = new LinkedList<E>(); "
},
{
"code": null,
"e": 26102,
"s": 25971,
"text": "Example 1: AbstractSequentialList is an abstract class, so it should be assigned an instance of its subclass such as LinkedList. "
},
{
"code": null,
"e": 26107,
"s": 26102,
"text": "Java"
},
{
"code": "// Java code to illustrate AbstractSequentialListimport java.util.*; public class GfG { public static void main(String[] args) { // Creating an instance of // the AbstractSequentialList AbstractSequentialList<Integer> absl = new LinkedList<>(); // adding elements to absl absl.add(5); absl.add(6); absl.add(7); // Printing the list System.out.println(absl); }}",
"e": 26558,
"s": 26107,
"text": null
},
{
"code": null,
"e": 26566,
"s": 26558,
"text": "Output:"
},
{
"code": null,
"e": 26577,
"s": 26566,
"text": "[5, 6, 7]\n"
},
{
"code": null,
"e": 26591,
"s": 26577,
"text": "Example 2: "
},
{
"code": null,
"e": 26596,
"s": 26591,
"text": "Java"
},
{
"code": "// Java code to illustrate// methods of AbstractSequentialList import java.util.*;import java.util.AbstractSequentialList; public class AbstractSequentialListDemo { public static void main(String args[]) { // Creating an empty AbstractSequentialList AbstractSequentialList<String> absqlist = new LinkedList<String>(); // Using add() method to // add elements in the list absqlist.add(\"Geeks\"); absqlist.add(\"for\"); absqlist.add(\"Geeks\"); absqlist.add(\"10\"); absqlist.add(\"20\"); // Output the list System.out.println(\"AbstractSequentialList: \" + absqlist); // Remove the head using remove() absqlist.remove(3); // Print the final list System.out.println(\"Final List: \" + absqlist); // Fetching the specific // element from the list // using get() method System.out.println(\"The element is: \" + absqlist.get(2)); }}",
"e": 27660,
"s": 26596,
"text": null
},
{
"code": null,
"e": 27668,
"s": 27660,
"text": "Output:"
},
{
"code": null,
"e": 27779,
"s": 27668,
"text": "AbstractSequentialList: [Geeks, for, Geeks, 10, 20]\nFinal List: [Geeks, for, Geeks, 20]\nThe element is: Geeks\n"
},
{
"code": null,
"e": 27786,
"s": 27779,
"text": "METHOD"
},
{
"code": null,
"e": 27798,
"s": 27786,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 27805,
"s": 27798,
"text": "METHOD"
},
{
"code": null,
"e": 27817,
"s": 27805,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 27824,
"s": 27817,
"text": "METHOD"
},
{
"code": null,
"e": 27836,
"s": 27824,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 27843,
"s": 27836,
"text": "METHOD"
},
{
"code": null,
"e": 27855,
"s": 27843,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 27862,
"s": 27855,
"text": "METHOD"
},
{
"code": null,
"e": 27874,
"s": 27862,
"text": "DESCRIPTION"
},
{
"code": null,
"e": 27983,
"s": 27874,
"text": "Appends all of the elements in the specified collection to the end of this list, in the order that they are "
},
{
"code": null,
"e": 28053,
"s": 27983,
"text": "returned by the specified collection’s iterator (optional operation)."
},
{
"code": null,
"e": 28163,
"s": 28053,
"text": "Returns an array containing all of the elements in this list in proper sequence (from first to last element);"
},
{
"code": null,
"e": 28235,
"s": 28163,
"text": " the runtime type of the returned array is that of the specified array."
},
{
"code": null,
"e": 28346,
"s": 28235,
"text": "Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/AbstractSequentialList.html "
},
{
"code": null,
"e": 28370,
"s": 28346,
"text": "Ganeshchowdharysadanala"
},
{
"code": null,
"e": 28390,
"s": 28370,
"text": "Java - util package"
},
{
"code": null,
"e": 28418,
"s": 28390,
"text": "java-AbstractSequentialList"
},
{
"code": null,
"e": 28435,
"s": 28418,
"text": "Java-Collections"
},
{
"code": null,
"e": 28440,
"s": 28435,
"text": "Java"
},
{
"code": null,
"e": 28445,
"s": 28440,
"text": "Java"
},
{
"code": null,
"e": 28462,
"s": 28445,
"text": "Java-Collections"
},
{
"code": null,
"e": 28560,
"s": 28462,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28575,
"s": 28560,
"text": "Arrays in Java"
},
{
"code": null,
"e": 28619,
"s": 28575,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 28641,
"s": 28619,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 28677,
"s": 28641,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 28702,
"s": 28677,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 28734,
"s": 28702,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 28785,
"s": 28734,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 28815,
"s": 28785,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 28834,
"s": 28815,
"text": "Interfaces in Java"
}
] |
Adjusting the Image Contrast using CSS3
|
To set image contrast in CSS, use filter contrast(%). Remember, the value 0 makes the image black, 100% is for original image and default. Rest, you can set any value of your choice, but values above 100% would make the image with more contrast.
Let us now see an example to adjust image contrast with CSS3 −
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
img.demo {
filter: brightness(120%);
filter: contrast(120%);
}
</style>
</head>
<body>
<h1>Learn MySQL</h1>
<img src="https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg" alt="MySQL" width="160" height="150">
<h1>Learn MySQL</h1>
<p>Below image is brighter and has more contrast than the original image above.</p>
<img class="demo" src="https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg" alt="MySQL" width="160" height="150">
</body>
</html>
|
[
{
"code": null,
"e": 1308,
"s": 1062,
"text": "To set image contrast in CSS, use filter contrast(%). Remember, the value 0 makes the image black, 100% is for original image and default. Rest, you can set any value of your choice, but values above 100% would make the image with more contrast."
},
{
"code": null,
"e": 1371,
"s": 1308,
"text": "Let us now see an example to adjust image contrast with CSS3 −"
},
{
"code": null,
"e": 1382,
"s": 1371,
"text": " Live Demo"
},
{
"code": null,
"e": 1894,
"s": 1382,
"text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\nimg.demo {\n filter: brightness(120%);\n filter: contrast(120%);\n}\n</style>\n</head>\n<body>\n<h1>Learn MySQL</h1>\n<img src=\"https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg\" alt=\"MySQL\" width=\"160\" height=\"150\">\n<h1>Learn MySQL</h1>\n<p>Below image is brighter and has more contrast than the original image above.</p>\n<img class=\"demo\" src=\"https://www.tutorialspoint.com/mysql/images/mysql-mini-logo.jpg\" alt=\"MySQL\" width=\"160\" height=\"150\">\n</body>\n</html>"
}
] |
Kotlin - Maps
|
Kotlin map is a collection of key/value pairs, where each key is unique, and it can only be associated with one value. The same value can be associated with multiple keys though. We can declare the keys and values to be any type; there are no restrictions.
A Kotlin map can be either mutable (mutableMapOf) or read-only (mapOf).
Maps are also known as dictionaries or associative arrays in other programming languages.
For map creation, use the standard library functions mapOf() for read-only maps and mutableMapOf() for mutable maps.
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
println(theMap)
val theMutableMap = mutableSetOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
println(theMutableMap)
}
When you run the above Kotlin program, it will generate the following output:
{one=1, two=2, three=3, four=4}
[(one, 1), (two, 2), (three, 3), (four, 4)]
A Kotlin map can be created from Java's HashMap.
fun main() {
val theMap = HashMap<String, Int>()
theMap["one"] = 1
theMap["two"] = 2
theMap["three"] = 3
theMap["four"] = 4
println(theMap)
}
When you run the above Kotlin program, it will generate the following output:
{four=4, one=1, two=2, three=3}
We can use Pair() method to create key/value pairs:
fun main() {
val theMap = mapOf(Pair("one", 1), Pair("two", 2), Pair("three", 3))
println(theMap)
}
When you run the above Kotlin program, it will generate the following output:
{one=1, two=2, three=3}
Kotlin map has properties to get all entries, keys, and values of the map.
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
println("Entries: " + theMap.entries)
println("Keys:" + theMap.keys)
println("Values:" + theMap.values)
}
When you run the above Kotlin program, it will generate the following output:
Entries: [one=1, two=2, three=3, four=4]
Keys:[one, two, three, four]
Values:[1, 2, 3, 4]
There are various ways to loop through a Kotlin Maps. Lets study them one by one:
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
println(theMap.toString())
}
When you run the above Kotlin program, it will generate the following output:
{one=1, two=2, three=3, four=4}
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
val itr = theMap.keys.iterator()
while (itr.hasNext()) {
val key = itr.next()
val value = theMap[key]
println("${key}=$value")
}
}
When you run the above Kotlin program, it will generate the following output:
one=1
two=2
three=3
four=4
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
for ((k, v) in theMap) {
println("$k = $v")
}
}
When you run the above Kotlin program, it will generate the following output:
one = 1
two = 2
three = 3
four = 4
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
theMap.forEach {
k, v -> println("Key = $k, Value = $v")
}
}
When you run the above Kotlin program, it will generate the following output:
Key = one, Value = 1
Key = two, Value = 2
Key = three, Value = 3
Key = four, Value = 4
We can use size property or count() method to get the total number of elements in a map:
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
println("Size of the Map " + theMap.size)
println("Size of the Map " + theMap.count())
}
When you run the above Kotlin program, it will generate the following output:
Size of the Map 4
Size of the Map 4
The The containsKey() checks if the map contains a key. The containsValue() checks if the map contains a value.
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
if(theMap.containsKey("two")){
println(true)
}else{
println(false)
}
if(theMap.containsValue("two")){
println(true)
}else{
println(false)
}
}
When you run the above Kotlin program, it will generate the following output:
true
false
The isEmpty() method returns true if the collection is empty (contains no elements), false otherwise.
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
if(theMap.isEmpty()){
println(true)
}else{
println(false)
}
}
When you run the above Kotlin program, it will generate the following output:
false
The get() method can be used to get the value corresponding to the given key. The shorthand [key] syntax is also supported.
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
println("The value for key two " + theMap.get("two"))
println("The value for key two " + theMap["two"])
}
When you run the above Kotlin program, it will generate the following output:
The value for key two 2
The value for key two 2
We can use + operator to add two or more maps into a single set. This will add second map into first map, discarding the duplicate elements.
If there are duplicate keys in two maps then second map's key will override the previous map key.
fun main() {
val firstMap = mapOf("one" to 1, "two" to 2, "three" to 3)
val secondMap = mapOf("one" to 10, "four" to 4)
val resultMap = firstMap + secondMap
println(resultMap)
}
When you run the above Kotlin program, it will generate the following output:
{one=10, two=2, three=3, four=4}
We can use - operator to subtract a list from a map. This operation will remove all the keys of the list from the map and will return the result.
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3)
val theKeyList = listOf("one", "four")
val resultMap = theMap - theKeyList
println(resultMap)
}
When you run the above Kotlin program, it will generate the following output:
{two=2, three=3}
We can use remove() method to remove the element from a mutable map, or we can use minus-assign (-=) operator to perform the same operation
fun main() {
val theMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
theMap.remove( "two")
println(theMap)
theMap -= listOf("three")
println(theMap)
}
When you run the above Kotlin program, it will generate the following output:
{one=1, three=3, four=4}
{one=1, four=4}
We can use toSortedMap() method to sort the elements in ascending order, or sortedDescending() method to sort the set elements in descending order.
You can also create a sorted map with the given key/values using sortedMapOf() method. Just use this method in place of mapOf().
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
var resultMap = theMap.toSortedMap()
println(resultMap)
}
When you run the above Kotlin program, it will generate the following output:
{four=4, one=1, three=3, two=2}
We can use either filterKeys() or filterValues() method to filter out the entries.
We can also use filter() method to filter out the elements matching the both key/value
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
var resultMap = theMap.filterValues{ it > 2}
println(resultMap)
resultMap = theMap.filterKeys{ it == "two"}
println(resultMap)
resultMap = theMap.filter{ it.key == "two" || it.value == 4}
println(resultMap)
}
When you run the above Kotlin program, it will generate the following output:
{three=3, four=4}
{two=2}
{two=2, four=4}
We can use map() method to map all elements using the provided function:.
fun main() {
val theMap = mapOf("one" to 1, "two" to 2, "three" to 3)
val resultMap = theMap.map{ (k, v) -> "Key is $k, Value is $v" }
println(resultMap)
}
When you run the above Kotlin program, it will generate the following output:
[Key is one, Value is 1, Key is two, Value is 2, Key is three, Value is 3]
We can create mutable set using mutableMapOf(), later we can use put to add more elements in the same map, and we can use remove() method to remove the elements from the set.
fun main() {
val theMap = mutableMapOf("one" to 1, "two" to 2, "three" to 3, "four" to 4)
theMap.put("four", 4)
println(theMap)
theMap["five"] = 5
println(theMap)
theMap.remove("two")
println(theMap)
}
When you run the above Kotlin program, it will generate the following output:
{one=1, two=2, three=3, four=4}
{one=1, two=2, three=3, four=4, five=5}
{one=1, three=3, four=4, five=5}
Q 1 - Can we make a mutable Kotlin map as immutable?
A - Yes
B - No
Yes we can make a mutable set to immutable by casting them to Map
Q 2 - We can add two or more maps and create a single set using + operator:
A - True
B - False
Yes we can add or subtract two Kotlin maps and generate a third set. A plus sign works like a union() for set.
Q 2 - Which method will return the value for the given key of Kotlin Map?
A - get()
B - elementAt()
C - Direct index with set variable
D - None of the above
get() method is used to get the value corresponding to a key.
68 Lectures
4.5 hours
Arnab Chakraborty
71 Lectures
5.5 hours
Frahaan Hussain
18 Lectures
1.5 hours
Mahmoud Ramadan
49 Lectures
6 hours
Catalin Stefan
49 Lectures
2.5 hours
Skillbakerystudios
22 Lectures
1 hours
CLEMENT OCHIENG
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2682,
"s": 2425,
"text": "Kotlin map is a collection of key/value pairs, where each key is unique, and it can only be associated with one value. The same value can be associated with multiple keys though. We can declare the keys and values to be any type; there are no restrictions."
},
{
"code": null,
"e": 2754,
"s": 2682,
"text": "A Kotlin map can be either mutable (mutableMapOf) or read-only (mapOf)."
},
{
"code": null,
"e": 2844,
"s": 2754,
"text": "Maps are also known as dictionaries or associative arrays in other programming languages."
},
{
"code": null,
"e": 2961,
"s": 2844,
"text": "For map creation, use the standard library functions mapOf() for read-only maps and mutableMapOf() for mutable maps."
},
{
"code": null,
"e": 3191,
"s": 2961,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n println(theMap)\n \n val theMutableMap = mutableSetOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n println(theMutableMap)\n}\n"
},
{
"code": null,
"e": 3269,
"s": 3191,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 3346,
"s": 3269,
"text": "{one=1, two=2, three=3, four=4}\n[(one, 1), (two, 2), (three, 3), (four, 4)]\n"
},
{
"code": null,
"e": 3395,
"s": 3346,
"text": "A Kotlin map can be created from Java's HashMap."
},
{
"code": null,
"e": 3572,
"s": 3395,
"text": "fun main() {\n val theMap = HashMap<String, Int>()\n \n theMap[\"one\"] = 1\n theMap[\"two\"] = 2\n theMap[\"three\"] = 3\n theMap[\"four\"] = 4\n \n println(theMap)\n}\n"
},
{
"code": null,
"e": 3650,
"s": 3572,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 3683,
"s": 3650,
"text": "{four=4, one=1, two=2, three=3}\n"
},
{
"code": null,
"e": 3735,
"s": 3683,
"text": "We can use Pair() method to create key/value pairs:"
},
{
"code": null,
"e": 3844,
"s": 3735,
"text": "fun main() {\n val theMap = mapOf(Pair(\"one\", 1), Pair(\"two\", 2), Pair(\"three\", 3))\n println(theMap)\n}\n"
},
{
"code": null,
"e": 3922,
"s": 3844,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 3947,
"s": 3922,
"text": "{one=1, two=2, three=3}\n"
},
{
"code": null,
"e": 4022,
"s": 3947,
"text": "Kotlin map has properties to get all entries, keys, and values of the map."
},
{
"code": null,
"e": 4233,
"s": 4022,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n \n println(\"Entries: \" + theMap.entries)\n println(\"Keys:\" + theMap.keys)\n println(\"Values:\" + theMap.values)\n}\n"
},
{
"code": null,
"e": 4311,
"s": 4233,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4402,
"s": 4311,
"text": "Entries: [one=1, two=2, three=3, four=4]\nKeys:[one, two, three, four]\nValues:[1, 2, 3, 4]\n"
},
{
"code": null,
"e": 4484,
"s": 4402,
"text": "There are various ways to loop through a Kotlin Maps. Lets study them one by one:"
},
{
"code": null,
"e": 4605,
"s": 4484,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n println(theMap.toString())\n}\n"
},
{
"code": null,
"e": 4683,
"s": 4605,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 4716,
"s": 4683,
"text": "{one=1, two=2, three=3, four=4}\n"
},
{
"code": null,
"e": 4976,
"s": 4716,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n \n val itr = theMap.keys.iterator()\n while (itr.hasNext()) {\n val key = itr.next()\n val value = theMap[key]\n println(\"${key}=$value\")\n }\n}\n"
},
{
"code": null,
"e": 5054,
"s": 4976,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 5082,
"s": 5054,
"text": "one=1\ntwo=2\nthree=3\nfour=4\n"
},
{
"code": null,
"e": 5238,
"s": 5082,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n \n for ((k, v) in theMap) {\n println(\"$k = $v\")\n }\n \n}\n"
},
{
"code": null,
"e": 5316,
"s": 5238,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 5352,
"s": 5316,
"text": "one = 1\ntwo = 2\nthree = 3\nfour = 4\n"
},
{
"code": null,
"e": 5519,
"s": 5352,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n \n theMap.forEach { \n k, v -> println(\"Key = $k, Value = $v\") \n }\n}\n"
},
{
"code": null,
"e": 5597,
"s": 5519,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 5685,
"s": 5597,
"text": "Key = one, Value = 1\nKey = two, Value = 2\nKey = three, Value = 3\nKey = four, Value = 4\n"
},
{
"code": null,
"e": 5774,
"s": 5685,
"text": "We can use size property or count() method to get the total number of elements in a map:"
},
{
"code": null,
"e": 5964,
"s": 5774,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n \n println(\"Size of the Map \" + theMap.size)\n println(\"Size of the Map \" + theMap.count())\n}\n"
},
{
"code": null,
"e": 6042,
"s": 5964,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 6079,
"s": 6042,
"text": "Size of the Map 4\nSize of the Map 4\n"
},
{
"code": null,
"e": 6191,
"s": 6079,
"text": "The The containsKey() checks if the map contains a key. The containsValue() checks if the map contains a value."
},
{
"code": null,
"e": 6468,
"s": 6191,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n\n if(theMap.containsKey(\"two\")){\n println(true)\n }else{\n println(false)\n }\n \n if(theMap.containsValue(\"two\")){\n println(true)\n }else{\n println(false)\n } \n}\n"
},
{
"code": null,
"e": 6546,
"s": 6468,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 6558,
"s": 6546,
"text": "true\nfalse\n"
},
{
"code": null,
"e": 6660,
"s": 6558,
"text": "The isEmpty() method returns true if the collection is empty (contains no elements), false otherwise."
},
{
"code": null,
"e": 6835,
"s": 6660,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n \n if(theMap.isEmpty()){\n println(true)\n }else{\n println(false)\n }\n}\n"
},
{
"code": null,
"e": 6913,
"s": 6835,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 6920,
"s": 6913,
"text": "false\n"
},
{
"code": null,
"e": 7044,
"s": 6920,
"text": "The get() method can be used to get the value corresponding to the given key. The shorthand [key] syntax is also supported."
},
{
"code": null,
"e": 7244,
"s": 7044,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n\n println(\"The value for key two \" + theMap.get(\"two\"))\n println(\"The value for key two \" + theMap[\"two\"])\n}\n"
},
{
"code": null,
"e": 7322,
"s": 7244,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 7371,
"s": 7322,
"text": "The value for key two 2\nThe value for key two 2\n"
},
{
"code": null,
"e": 7512,
"s": 7371,
"text": "We can use + operator to add two or more maps into a single set. This will add second map into first map, discarding the duplicate elements."
},
{
"code": null,
"e": 7610,
"s": 7512,
"text": "If there are duplicate keys in two maps then second map's key will override the previous map key."
},
{
"code": null,
"e": 7810,
"s": 7610,
"text": "fun main() {\n val firstMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3)\n val secondMap = mapOf(\"one\" to 10, \"four\" to 4)\n val resultMap = firstMap + secondMap\n \n println(resultMap)\n}\n"
},
{
"code": null,
"e": 7888,
"s": 7810,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 7922,
"s": 7888,
"text": "{one=10, two=2, three=3, four=4}\n"
},
{
"code": null,
"e": 8068,
"s": 7922,
"text": "We can use - operator to subtract a list from a map. This operation will remove all the keys of the list from the map and will return the result."
},
{
"code": null,
"e": 8256,
"s": 8068,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3)\n val theKeyList = listOf(\"one\", \"four\")\n val resultMap = theMap - theKeyList\n \n println(resultMap)\n}\n"
},
{
"code": null,
"e": 8334,
"s": 8256,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 8352,
"s": 8334,
"text": "{two=2, three=3}\n"
},
{
"code": null,
"e": 8492,
"s": 8352,
"text": "We can use remove() method to remove the element from a mutable map, or we can use minus-assign (-=) operator to perform the same operation"
},
{
"code": null,
"e": 8690,
"s": 8492,
"text": "fun main() {\n val theMap = mutableMapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n theMap.remove( \"two\")\n println(theMap)\n \n theMap -= listOf(\"three\")\n println(theMap)\n}\n"
},
{
"code": null,
"e": 8768,
"s": 8690,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 8810,
"s": 8768,
"text": "{one=1, three=3, four=4}\n{one=1, four=4}\n"
},
{
"code": null,
"e": 8958,
"s": 8810,
"text": "We can use toSortedMap() method to sort the elements in ascending order, or sortedDescending() method to sort the set elements in descending order."
},
{
"code": null,
"e": 9087,
"s": 8958,
"text": "You can also create a sorted map with the given key/values using sortedMapOf() method. Just use this method in place of mapOf()."
},
{
"code": null,
"e": 9241,
"s": 9087,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n var resultMap = theMap.toSortedMap()\n println(resultMap)\n}\n"
},
{
"code": null,
"e": 9319,
"s": 9241,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 9352,
"s": 9319,
"text": "{four=4, one=1, three=3, two=2}\n"
},
{
"code": null,
"e": 9435,
"s": 9352,
"text": "We can use either filterKeys() or filterValues() method to filter out the entries."
},
{
"code": null,
"e": 9522,
"s": 9435,
"text": "We can also use filter() method to filter out the elements matching the both key/value"
},
{
"code": null,
"e": 9858,
"s": 9522,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n var resultMap = theMap.filterValues{ it > 2}\n println(resultMap)\n \n resultMap = theMap.filterKeys{ it == \"two\"}\n println(resultMap)\n \n resultMap = theMap.filter{ it.key == \"two\" || it.value == 4}\n println(resultMap)\n \n}\n"
},
{
"code": null,
"e": 9936,
"s": 9858,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 9979,
"s": 9936,
"text": "{three=3, four=4}\n{two=2}\n{two=2, four=4}\n"
},
{
"code": null,
"e": 10053,
"s": 9979,
"text": "We can use map() method to map all elements using the provided function:."
},
{
"code": null,
"e": 10228,
"s": 10053,
"text": "fun main() {\n val theMap = mapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3)\n val resultMap = theMap.map{ (k, v) -> \"Key is $k, Value is $v\" }\n \n println(resultMap)\n}\n"
},
{
"code": null,
"e": 10306,
"s": 10228,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 10382,
"s": 10306,
"text": "[Key is one, Value is 1, Key is two, Value is 2, Key is three, Value is 3]\n"
},
{
"code": null,
"e": 10557,
"s": 10382,
"text": "We can create mutable set using mutableMapOf(), later we can use put to add more elements in the same map, and we can use remove() method to remove the elements from the set."
},
{
"code": null,
"e": 10809,
"s": 10557,
"text": "fun main() {\n val theMap = mutableMapOf(\"one\" to 1, \"two\" to 2, \"three\" to 3, \"four\" to 4)\n \n theMap.put(\"four\", 4)\n println(theMap)\n \n theMap[\"five\"] = 5\n println(theMap)\n \n theMap.remove(\"two\")\n println(theMap)\n \n}\n"
},
{
"code": null,
"e": 10887,
"s": 10809,
"text": "When you run the above Kotlin program, it will generate the following output:"
},
{
"code": null,
"e": 10993,
"s": 10887,
"text": "{one=1, two=2, three=3, four=4}\n{one=1, two=2, three=3, four=4, five=5}\n{one=1, three=3, four=4, five=5}\n"
},
{
"code": null,
"e": 11046,
"s": 10993,
"text": "Q 1 - Can we make a mutable Kotlin map as immutable?"
},
{
"code": null,
"e": 11054,
"s": 11046,
"text": "A - Yes"
},
{
"code": null,
"e": 11061,
"s": 11054,
"text": "B - No"
},
{
"code": null,
"e": 11127,
"s": 11061,
"text": "Yes we can make a mutable set to immutable by casting them to Map"
},
{
"code": null,
"e": 11203,
"s": 11127,
"text": "Q 2 - We can add two or more maps and create a single set using + operator:"
},
{
"code": null,
"e": 11212,
"s": 11203,
"text": "A - True"
},
{
"code": null,
"e": 11222,
"s": 11212,
"text": "B - False"
},
{
"code": null,
"e": 11333,
"s": 11222,
"text": "Yes we can add or subtract two Kotlin maps and generate a third set. A plus sign works like a union() for set."
},
{
"code": null,
"e": 11407,
"s": 11333,
"text": "Q 2 - Which method will return the value for the given key of Kotlin Map?"
},
{
"code": null,
"e": 11417,
"s": 11407,
"text": "A - get()"
},
{
"code": null,
"e": 11433,
"s": 11417,
"text": "B - elementAt()"
},
{
"code": null,
"e": 11468,
"s": 11433,
"text": "C - Direct index with set variable"
},
{
"code": null,
"e": 11490,
"s": 11468,
"text": "D - None of the above"
},
{
"code": null,
"e": 11552,
"s": 11490,
"text": "get() method is used to get the value corresponding to a key."
},
{
"code": null,
"e": 11587,
"s": 11552,
"text": "\n 68 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 11606,
"s": 11587,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 11641,
"s": 11606,
"text": "\n 71 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 11658,
"s": 11641,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 11693,
"s": 11658,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 11710,
"s": 11693,
"text": " Mahmoud Ramadan"
},
{
"code": null,
"e": 11743,
"s": 11710,
"text": "\n 49 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 11759,
"s": 11743,
"text": " Catalin Stefan"
},
{
"code": null,
"e": 11794,
"s": 11759,
"text": "\n 49 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 11814,
"s": 11794,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 11847,
"s": 11814,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 11864,
"s": 11847,
"text": " CLEMENT OCHIENG"
},
{
"code": null,
"e": 11871,
"s": 11864,
"text": " Print"
},
{
"code": null,
"e": 11882,
"s": 11871,
"text": " Add Notes"
}
] |
On Average, You’re Using the Wrong Average — Part II | by Daniel McNichol | Towards Data Science
|
Real & Simulated Data + Summary Statistic Dynamics using R & BigQuery
Part I of this series built a practical & conceptual framework for understanding & using lesser known Pythagorean Means in data analysis. I went to lengths (~5k words) to build intuitions for a general audience, requiring little more than primary school maths.
This post will get a bit deeper & more technical, exploring the dynamics of these means under richer simulated datasets derived from several probability distributions. We’ll then juxtapose these with some comparable ‘real world’ big datasets. I’ll also aim for more concision & economy, assuming a level of comfort with a bit higher level maths & probability theory.
Recall that there are 3 Pythagorean means, which conform to the inequality:
harmonic mean ≤ geometric mean ≤ arithmetic mean
They are only mutually equivalent in the limiting case where every number in the dataset is the same number.
The arithmetic mean is produced via simple addition & division.
The geometric mean is produced via multiplication & roots.
The harmonic mean is produced via reciprocals, addition & division.
Their equations are:
As such, each can be derived or expressed as reconfigurations of each other. For example:
The geometric mean is simply the antilog of thearithmetic mean of the log transformed values of the dataset. It can also sometimes preserve the ordering of arithmetic meansof ratios scaled to a common denominator, or at least produce similarly credible summary values.
The harmonic mean is just the reciprocal of the arithmetic mean of the reciprocals of the dataset. It can also be reproduced via an appropriately weighted arithmetic mean of the dataset.
Rules of thumb:
The arithmetic mean is best suited to additive, linear, ‘symmetrical’, ‘normal’ / Gaussian datasets
The geometric mean is best suited to multiplicative, ‘geometric’, exponential, lognormal, skewed datasets, as well as ratios on different scales & compound growth rates.
The harmonic mean is the rarest of the three, but is well suited averaging ratios in terms of the numerator, such as rates of travel, some financial indexes & various specialized applications from physics to sabermetrics & the evaluation of machine learning models.
Limitations:
Due to their relative rarity, geometric & harmonic means can be difficult to interpret & misleading to audiences expecting more conventional meanings of ‘average’
The geometric mean is practically ‘unitless’, as scale & interpretable units are lost in the multiplicative operations (with factors on different scales)
Geometric & harmonic means cannot accommodate inputs ≤ 0
See Part I for a more detailed discussion. We’ll now see some of this in action.
In Part I we observed the dynamics of Pythagorean means under trivial additive & multiplicative datasets. Here we’ll extend this exercise by simulating richer datasets from various probability distributions in R.
For our additive or linear dataset, we’ll draw 10,000 samples from a random normal distribution, with a mean of 100 & standard deviation of 20 to avoid draws ≤ 0:
hist( rnorm( 10000, 100, 20 ) )
Next we’ll simulate three types of multiplicative datasets (which are often difficult to distinguish, despite meaningful differences): a lognormal, exponential & power law distribution.
There are many ways to produce a lognormal distribution — basically any multiplicative interaction of i.i.d. random variables will produce it — which is why it appears so often in the real world, particularly among human endeavors. For simplicity & interpretability, we’ll simply raise Euler’s number to a random exponent drawn from a normal distribution, then add 100 to put it in the range of our normal distribution:
hist( exp(1)^rnorm(10000,3,.9) + 100, breaks = 39 )
This is technically a special case of an exponential distribution, but we’ll simulate another variety via R’s rexp function, where we simply specify the number of samples & the rate of decay (again, adding 100 to the result):
hist( rexp(10000, 1/10) +100 )
Finally, we’ll produce a power law distribution by raising samples from a normal distribution to a constant exponent (Euler’s number again, keeping it natural), then adding 100:
(note that this is the inverse of our lognormal method, where Euler’s number was the base & the distribution was the exponent)
hist( rnorm(10000, 3, 1)^exp(1) + 100 )
Alright, now we’ll use the ggridges package to better plot our distributions. We’ll also load the tidyverse package, like civilized useRs:
library(tidyverse)library(ggridges)
Let’s put our distributions into a tidy tibble with ordered factors:
Now lets take a more artful look at our distributions:
A shapely lot. Let’s compute some summary statistics.
Since R has no native geometric or harmonic mean functions, we’ll have to be a bit crafty:
output:
# A tibble: 4 x 5 distribution median am gm hm <fct> <dbl> <dbl> <dbl> <dbl>1 normal 99.6 99.9 97.7 95.42 lognormal 120 129 127 125 3 exponential 107 110 110 109 4 power law 120 125 124 122
...and add them to our plots:
We immediately notice the impact of skewed densities as well as long & fat tails on the spread of the means and their relationship to the median:
In our normal distribution, being mostly symmetrical, the median & arithmetic mean are nearly identical. (99.6 & 99.9 respectively, per the output table above).
The rightward skew of our other distributions pull all the means to the right of the median, which tends toward the denser humps of the dataset
It’s all a bit crowded here though, so let’s take a closer look by adjusting the x-axis limits, aka xlim():
...xlim(90, 150)...
Again notice that in the normal, symmetrical dataset, geometric & harmonic means meaningfully understate the the ‘midpoint’ of the data, but are roughly equally spaced (each about 2 units apart).
In the lognormal distribution, the long (moderately thin) tail pulls the means far from the ordinal midpoint represented by the median, & even skews the distribution of means so that the arithmetic is farther from the geometric than the harmonic is.
In our exponential distribution, values are so densely packed & the short thin tail of exponential decay vanishes so quickly that our means also crowd close together — though the heavy skew still displaces them from the median.
Our power law distribution has the slowest decay, & thus the fattest tail. Still, it is nearly normal in the ‘body’, with the mildest skew of the asymmetrical distributions. Its means are roughly equidistant, but still removed from the median.
In Part I & above I mentioned the logarithmic relationship between the geometric & arithmetic means:
The geometric mean is simply the antilog of thearithmetic mean of the log transformed values of the dataset.
To demonstrate this, let’s take another look at our summary statistic table:
# A tibble: 4 x 5 distribution median am gm hm <fct> <dbl> <dbl> <dbl> <dbl>1 normal 99.6 99.9 97.7 95.42 lognormal 120 129 127 125 3 exponential 107 110 110 109 4 power law 120 125 124 122
Note our lognormal geometric mean: 127.
Now we’ll compute the arithmetic mean of the log-transformed values:
dist2$x %>% log() %>% mean()# output:[1] 4.84606
...& then take the anti-log of that number:
exp(1)^4.84606# output[1] 127.2381
Et voilà.
Now, to drive home the obvious, let’s see why this is so (& why the lognormal distribution earns its name):
# subtract 100 we originally added before taking the log(dist2$x — 100) %>% log() %>% hist()
True to its name, a log-transformation of the lognormal distribution yields a normal distribution. Thus, the additive basis of the arithmetic mean yields the same result in a normal distribution that the multiplicative nature of the geometric mean yields in a lognormal distribution.
We shouldn’t be too impressed with the impeccable normal distribution resulting from the log-transformed lognormal dataset, since we specified the exact data generating process which produced the lognormal values, & literally just reversed that process to reproduce the underlying normal distribution.
Things are seldom so tidy in the real world, where generating processes are typically more complex & unknown or unknowable. Thus the confusion & controversy over how to model & describe empirically derived datasets.
Let’s take a look at some such datasets & see what the fuss is about.
While usually less docile than our simulated distributions, real world datasets often resemble at least one of the four classes above.
Normal distributions — the ballyhooed ‘bell curve’ — arise most often in natural & biological organisms & scenarios with few interactions. Height & weight are canonical examples. As such, my first instinct is to reach for the trusty iris dataset. It meets the requirement, but there’s just something underwhelming about n = 50 (the number of observations of a single species of flower in the dataset). I’m thinking bigger.
So let’s load the bigrquery package, & do bigRqueries.
library(bigrquery)
Google’s BigQuery makes available numerous public datasets of real data, some quite large, from genomics to patents to wikipedia article stats.
For our initial purposes, the natality dataset appears sufficiently biological:
project <- “YOUR-PROJECT-ID”sql <- “SELECT COUNT(*) FROM `bigquery-public-data.samples.natality`”query_exec(sql, project = project, use_legacy_sql = F)
(protip: there’s lots of data here, & you get charged by the amount of data accessed, but your first TB per month is free. Further, while SELECT * is highly discouraged for obvious reasons, SELECT COUNT(*) is actually a free operation, & a good idea to scope things out)
Output:
0 bytes processed f0_1 137826763
That’s more like it, 137 million baby records. We don’t quite need all of those, so let’s randomly sample 1% of the baby weights, take the first million results & see what we get:
sql <- “SELECT weight_pounds FROM `bigquery-public-data.samples.natality` WHERE RAND() < .01”natal <- query_exec(sql, project = project, use_legacy_sql = F, max_pages = 100)
Output:
Running job /: 7s:1.0 gigabytes processedWarning message: Only first 100 pages of size 10000 retrieved. Use max_pages = Inf to retrieve all.
hist(natal$weight_pounds) yields:
Normal af imo.
Now to find some multiplicative data with some skew, let’s move beyond the biological, to the sociological.
We’ll look at the New York dataset, which contains all sorts of urban info, including trips in yellow & green cabs.
sql <- “SELECT COUNT(*) FROM `nyc-tlc.green.trips_2015`”query_exec(sql, project = project, use_legacy_sql = F)
Output:
0 bytes processed f0_ 1 9896012
Under 10 million, so lets grab trip distances for the whole thing:
(this can take a while)
sql <- "SELECT trip_distance FROM `nyc-tlc.green.trips_2015`"trips <- query_exec(sql, project = project, use_legacy_sql = F)hist(trips$trips_distance)
-_-
Looks like there are some extreme outliers pulling our x-axis out to 800 miles. Hell of a cab ride. Lets trim this down to trips under 20 miles & take another look:
trips$trip_distance %>% subset(. <= 20) %>% hist()
There we are, & with a telltale sign of a lognormal distribution: the long tail. Let’s check our data for lognormalcy by plotting the histogram of the logs:
trips$trip_distance %>% subset(. <= 20) %>% log() %>% hist()
Normalish for sure, but we overshot the mark a bit & now observe a bit of left-skew. Alas, the real world strikes again. But safe to say that a lognormal distribution wouldn’t be a completely preposterous model to employ here.
Moving on. Let’s find some more heavy-tailed data, this time in a domain closer to my own professional affinities of digital web analytics: the Github dataset:
sql <- "SELECT COUNT(*) FROM `bigquery-public-data.samples.github_nested`"query_exec(sql, project = project, use_legacy_sql = F)
Output:
0 bytes processed f0_1 2541639
2.5 million rows. Since I’m starting to worry about my local machine’s memory, we’ll employ our random sampler & million row delimiter to get a count of “watchers” of each github repository:
sql <- “SELECT repository.watchers FROM `bigquery-public-data.samples.github_nested` WHERE RAND() < .5”github <- query_exec(sql, project = project, use_legacy_sql = F, max_pages = 100)github$watchers %>% hist()
Again, extreme long tail dynamics, so let’s do some trimming:
github$watchers %>% subset(5 < . & . < 3000) %>% hist()
Exponential af.
But is it lognormal again?
github$watchers %>% subset(5 < . & . < 3000) %>% log() %>% hist()
Nay.
But behold the rare beast: the (approximately) LOGUNIFORM DISTRIBUTION!
Let’s take one more draw from the big data urn, this time looking at scores of Hacker News posts:
sql <- “SELECT COUNT(*) FROM `bigquery-public-data.hacker_news.full`”query_exec(sql, project = project, use_legacy_sql = F)
Output:
0 bytes processed f0_1 16489224
...
sql <- “SELECT score FROM `bigquery-public-data.hacker_news.full` WHERE RAND() < .1”hn <- query_exec(sql, project = project, use_legacy_sql = F, max_pages = 100)hn$score %>% hist()
...
hn$score %>% subset(10 < . & . <= 300) %>% hist()
A slower decay (once trimmed). And as for the log-transform?
hn$score %>% subset(10 < . & . <= 300) %>% log() %>% hist()
Again roughly loguniform with a rightward decay.
My cursory search for a power law distribution in the wild proved fruitless, which is perhaps not surprising as they are most often posited in network science (&, even there, appear to be scarcer than initially claimed).
In any event, lets organize our real world datasets as we did with our simulated distributions & plot them comparatively. We’ll normalize them & again center them around 100:
Now to plot:
True to the real world they come from, a bit rougher around the edges than our simulated distributions. Still, remarkably similar. Let’s plot them side by side with the new (& excellent) patchwork package from the indispensable Thomas Lin Pedersen:
At a glance, our simulated distributions would provide reasonable models for their adjacent real world datasets, with the exception of power law -> hacker news scores, where the the concavity of the decay & the weight of the tails are substantially different.
There are of course many more rigorous tests of model fit etc, but let’s just take another look by plotting the summary statistics of the distributions as we did before.
Unfortunately, something about the normalized real world data is screwing with my summary statistic calculations, which are all coming back more or less indistinguishable from each other. I suspect this has something to do with computers’ struggles with floating point arithmetic (but might just have to do with my own struggles with numeracy). In any event, we’ll have to use our unnormalized real world data, which means we’ll have to plot them individually & attempt to line up the ggridge patchwork manually.
First to compile our unnormalized distributions & compute summary statistics:
Now to plot (this is ugly since we have to create individual plots for each real distribution, but patchwork allows us to elegantly define the layout):
Interesting that our real world dataset summary stats seem to have substantially more spread than our simulated distributions. Let’s zoom in for a closer look.
I won’t repost all the code, but basically just modified pm1 to have xlim(90, 150) & uncommented the xlim() lines in the rest of the plots:
Here even starker, but for the normalish distributions: summary statistic dynamics diverge widely, which should give us pause when facilely ‘eyeballing’ the fit of an idealized model to real world data.
This concludes our exploration of Pythagorean Means under simulated & real world distributions.
If you haven’t already, check out Part I for a lower level, more explicit & intuitive introduction. And see below for references & further reading.
Also, follow me for more like this!
— Follow on twitter: @dnlmcLinkedIn: linkedin.com/in/dnlmcGithub: https://github.com/dnlmc
Part I
https://en.wikipedia.org/wiki/Pythagorean_means
https://en.wikipedia.org/wiki/Summary_statistics
https://en.wikipedia.org/wiki/Central_tendency
“Measures of Location & Spread” — stat.berkeley.edu
“Median vs Average Household Income” — LinkedIn
“Mean vs Median Income”
“You should summarize data with the geometric mean” — Medium
“Which ‘mean’ to use & when?” — Stack Overflow
“When is it most appropriate to take the arithmetic mean vs. geometric mean vs. harmonic mean?” — Quora
“Arithmetric, Harmonic & Geometric Means with R”
“Using the Price-to-Earnings Harmonic Mean to Improve Firm Valuation Estimates” — Journal article
Part II
https://en.wikipedia.org/wiki/Heavy-tailed_distribution
https://en.wikipedia.org/wiki/Relationships_among_probability_distributions
http://www.win-vector.com/blog/2010/02/living-in-a-lognormal-world/
“A Brief History of Generative Models for Power Law and Lognormal Distributions” — Journal article
“Difference between power law distribution and exponential decay” — Stack Exchange
“Scant Evidence of Power Laws Found in Real-World Networks” — Quanta Magazine
|
[
{
"code": null,
"e": 241,
"s": 171,
"text": "Real & Simulated Data + Summary Statistic Dynamics using R & BigQuery"
},
{
"code": null,
"e": 502,
"s": 241,
"text": "Part I of this series built a practical & conceptual framework for understanding & using lesser known Pythagorean Means in data analysis. I went to lengths (~5k words) to build intuitions for a general audience, requiring little more than primary school maths."
},
{
"code": null,
"e": 869,
"s": 502,
"text": "This post will get a bit deeper & more technical, exploring the dynamics of these means under richer simulated datasets derived from several probability distributions. We’ll then juxtapose these with some comparable ‘real world’ big datasets. I’ll also aim for more concision & economy, assuming a level of comfort with a bit higher level maths & probability theory."
},
{
"code": null,
"e": 945,
"s": 869,
"text": "Recall that there are 3 Pythagorean means, which conform to the inequality:"
},
{
"code": null,
"e": 994,
"s": 945,
"text": "harmonic mean ≤ geometric mean ≤ arithmetic mean"
},
{
"code": null,
"e": 1103,
"s": 994,
"text": "They are only mutually equivalent in the limiting case where every number in the dataset is the same number."
},
{
"code": null,
"e": 1167,
"s": 1103,
"text": "The arithmetic mean is produced via simple addition & division."
},
{
"code": null,
"e": 1226,
"s": 1167,
"text": "The geometric mean is produced via multiplication & roots."
},
{
"code": null,
"e": 1294,
"s": 1226,
"text": "The harmonic mean is produced via reciprocals, addition & division."
},
{
"code": null,
"e": 1315,
"s": 1294,
"text": "Their equations are:"
},
{
"code": null,
"e": 1405,
"s": 1315,
"text": "As such, each can be derived or expressed as reconfigurations of each other. For example:"
},
{
"code": null,
"e": 1674,
"s": 1405,
"text": "The geometric mean is simply the antilog of thearithmetic mean of the log transformed values of the dataset. It can also sometimes preserve the ordering of arithmetic meansof ratios scaled to a common denominator, or at least produce similarly credible summary values."
},
{
"code": null,
"e": 1861,
"s": 1674,
"text": "The harmonic mean is just the reciprocal of the arithmetic mean of the reciprocals of the dataset. It can also be reproduced via an appropriately weighted arithmetic mean of the dataset."
},
{
"code": null,
"e": 1877,
"s": 1861,
"text": "Rules of thumb:"
},
{
"code": null,
"e": 1977,
"s": 1877,
"text": "The arithmetic mean is best suited to additive, linear, ‘symmetrical’, ‘normal’ / Gaussian datasets"
},
{
"code": null,
"e": 2147,
"s": 1977,
"text": "The geometric mean is best suited to multiplicative, ‘geometric’, exponential, lognormal, skewed datasets, as well as ratios on different scales & compound growth rates."
},
{
"code": null,
"e": 2413,
"s": 2147,
"text": "The harmonic mean is the rarest of the three, but is well suited averaging ratios in terms of the numerator, such as rates of travel, some financial indexes & various specialized applications from physics to sabermetrics & the evaluation of machine learning models."
},
{
"code": null,
"e": 2426,
"s": 2413,
"text": "Limitations:"
},
{
"code": null,
"e": 2589,
"s": 2426,
"text": "Due to their relative rarity, geometric & harmonic means can be difficult to interpret & misleading to audiences expecting more conventional meanings of ‘average’"
},
{
"code": null,
"e": 2743,
"s": 2589,
"text": "The geometric mean is practically ‘unitless’, as scale & interpretable units are lost in the multiplicative operations (with factors on different scales)"
},
{
"code": null,
"e": 2800,
"s": 2743,
"text": "Geometric & harmonic means cannot accommodate inputs ≤ 0"
},
{
"code": null,
"e": 2881,
"s": 2800,
"text": "See Part I for a more detailed discussion. We’ll now see some of this in action."
},
{
"code": null,
"e": 3094,
"s": 2881,
"text": "In Part I we observed the dynamics of Pythagorean means under trivial additive & multiplicative datasets. Here we’ll extend this exercise by simulating richer datasets from various probability distributions in R."
},
{
"code": null,
"e": 3257,
"s": 3094,
"text": "For our additive or linear dataset, we’ll draw 10,000 samples from a random normal distribution, with a mean of 100 & standard deviation of 20 to avoid draws ≤ 0:"
},
{
"code": null,
"e": 3293,
"s": 3257,
"text": "hist( rnorm( 10000, 100, 20 ) )"
},
{
"code": null,
"e": 3479,
"s": 3293,
"text": "Next we’ll simulate three types of multiplicative datasets (which are often difficult to distinguish, despite meaningful differences): a lognormal, exponential & power law distribution."
},
{
"code": null,
"e": 3899,
"s": 3479,
"text": "There are many ways to produce a lognormal distribution — basically any multiplicative interaction of i.i.d. random variables will produce it — which is why it appears so often in the real world, particularly among human endeavors. For simplicity & interpretability, we’ll simply raise Euler’s number to a random exponent drawn from a normal distribution, then add 100 to put it in the range of our normal distribution:"
},
{
"code": null,
"e": 3953,
"s": 3899,
"text": "hist( exp(1)^rnorm(10000,3,.9) + 100, breaks = 39 )"
},
{
"code": null,
"e": 4179,
"s": 3953,
"text": "This is technically a special case of an exponential distribution, but we’ll simulate another variety via R’s rexp function, where we simply specify the number of samples & the rate of decay (again, adding 100 to the result):"
},
{
"code": null,
"e": 4211,
"s": 4179,
"text": "hist( rexp(10000, 1/10) +100 )"
},
{
"code": null,
"e": 4389,
"s": 4211,
"text": "Finally, we’ll produce a power law distribution by raising samples from a normal distribution to a constant exponent (Euler’s number again, keeping it natural), then adding 100:"
},
{
"code": null,
"e": 4516,
"s": 4389,
"text": "(note that this is the inverse of our lognormal method, where Euler’s number was the base & the distribution was the exponent)"
},
{
"code": null,
"e": 4557,
"s": 4516,
"text": "hist( rnorm(10000, 3, 1)^exp(1) + 100 )"
},
{
"code": null,
"e": 4696,
"s": 4557,
"text": "Alright, now we’ll use the ggridges package to better plot our distributions. We’ll also load the tidyverse package, like civilized useRs:"
},
{
"code": null,
"e": 4732,
"s": 4696,
"text": "library(tidyverse)library(ggridges)"
},
{
"code": null,
"e": 4801,
"s": 4732,
"text": "Let’s put our distributions into a tidy tibble with ordered factors:"
},
{
"code": null,
"e": 4856,
"s": 4801,
"text": "Now lets take a more artful look at our distributions:"
},
{
"code": null,
"e": 4910,
"s": 4856,
"text": "A shapely lot. Let’s compute some summary statistics."
},
{
"code": null,
"e": 5001,
"s": 4910,
"text": "Since R has no native geometric or harmonic mean functions, we’ll have to be a bit crafty:"
},
{
"code": null,
"e": 5009,
"s": 5001,
"text": "output:"
},
{
"code": null,
"e": 5259,
"s": 5009,
"text": "# A tibble: 4 x 5 distribution median am gm hm <fct> <dbl> <dbl> <dbl> <dbl>1 normal 99.6 99.9 97.7 95.42 lognormal 120 129 127 125 3 exponential 107 110 110 109 4 power law 120 125 124 122"
},
{
"code": null,
"e": 5289,
"s": 5259,
"text": "...and add them to our plots:"
},
{
"code": null,
"e": 5435,
"s": 5289,
"text": "We immediately notice the impact of skewed densities as well as long & fat tails on the spread of the means and their relationship to the median:"
},
{
"code": null,
"e": 5596,
"s": 5435,
"text": "In our normal distribution, being mostly symmetrical, the median & arithmetic mean are nearly identical. (99.6 & 99.9 respectively, per the output table above)."
},
{
"code": null,
"e": 5740,
"s": 5596,
"text": "The rightward skew of our other distributions pull all the means to the right of the median, which tends toward the denser humps of the dataset"
},
{
"code": null,
"e": 5848,
"s": 5740,
"text": "It’s all a bit crowded here though, so let’s take a closer look by adjusting the x-axis limits, aka xlim():"
},
{
"code": null,
"e": 5868,
"s": 5848,
"text": "...xlim(90, 150)..."
},
{
"code": null,
"e": 6064,
"s": 5868,
"text": "Again notice that in the normal, symmetrical dataset, geometric & harmonic means meaningfully understate the the ‘midpoint’ of the data, but are roughly equally spaced (each about 2 units apart)."
},
{
"code": null,
"e": 6314,
"s": 6064,
"text": "In the lognormal distribution, the long (moderately thin) tail pulls the means far from the ordinal midpoint represented by the median, & even skews the distribution of means so that the arithmetic is farther from the geometric than the harmonic is."
},
{
"code": null,
"e": 6542,
"s": 6314,
"text": "In our exponential distribution, values are so densely packed & the short thin tail of exponential decay vanishes so quickly that our means also crowd close together — though the heavy skew still displaces them from the median."
},
{
"code": null,
"e": 6786,
"s": 6542,
"text": "Our power law distribution has the slowest decay, & thus the fattest tail. Still, it is nearly normal in the ‘body’, with the mildest skew of the asymmetrical distributions. Its means are roughly equidistant, but still removed from the median."
},
{
"code": null,
"e": 6887,
"s": 6786,
"text": "In Part I & above I mentioned the logarithmic relationship between the geometric & arithmetic means:"
},
{
"code": null,
"e": 6996,
"s": 6887,
"text": "The geometric mean is simply the antilog of thearithmetic mean of the log transformed values of the dataset."
},
{
"code": null,
"e": 7073,
"s": 6996,
"text": "To demonstrate this, let’s take another look at our summary statistic table:"
},
{
"code": null,
"e": 7323,
"s": 7073,
"text": "# A tibble: 4 x 5 distribution median am gm hm <fct> <dbl> <dbl> <dbl> <dbl>1 normal 99.6 99.9 97.7 95.42 lognormal 120 129 127 125 3 exponential 107 110 110 109 4 power law 120 125 124 122"
},
{
"code": null,
"e": 7363,
"s": 7323,
"text": "Note our lognormal geometric mean: 127."
},
{
"code": null,
"e": 7432,
"s": 7363,
"text": "Now we’ll compute the arithmetic mean of the log-transformed values:"
},
{
"code": null,
"e": 7481,
"s": 7432,
"text": "dist2$x %>% log() %>% mean()# output:[1] 4.84606"
},
{
"code": null,
"e": 7525,
"s": 7481,
"text": "...& then take the anti-log of that number:"
},
{
"code": null,
"e": 7560,
"s": 7525,
"text": "exp(1)^4.84606# output[1] 127.2381"
},
{
"code": null,
"e": 7571,
"s": 7560,
"text": "Et voilà."
},
{
"code": null,
"e": 7679,
"s": 7571,
"text": "Now, to drive home the obvious, let’s see why this is so (& why the lognormal distribution earns its name):"
},
{
"code": null,
"e": 7772,
"s": 7679,
"text": "# subtract 100 we originally added before taking the log(dist2$x — 100) %>% log() %>% hist()"
},
{
"code": null,
"e": 8056,
"s": 7772,
"text": "True to its name, a log-transformation of the lognormal distribution yields a normal distribution. Thus, the additive basis of the arithmetic mean yields the same result in a normal distribution that the multiplicative nature of the geometric mean yields in a lognormal distribution."
},
{
"code": null,
"e": 8358,
"s": 8056,
"text": "We shouldn’t be too impressed with the impeccable normal distribution resulting from the log-transformed lognormal dataset, since we specified the exact data generating process which produced the lognormal values, & literally just reversed that process to reproduce the underlying normal distribution."
},
{
"code": null,
"e": 8574,
"s": 8358,
"text": "Things are seldom so tidy in the real world, where generating processes are typically more complex & unknown or unknowable. Thus the confusion & controversy over how to model & describe empirically derived datasets."
},
{
"code": null,
"e": 8644,
"s": 8574,
"text": "Let’s take a look at some such datasets & see what the fuss is about."
},
{
"code": null,
"e": 8779,
"s": 8644,
"text": "While usually less docile than our simulated distributions, real world datasets often resemble at least one of the four classes above."
},
{
"code": null,
"e": 9202,
"s": 8779,
"text": "Normal distributions — the ballyhooed ‘bell curve’ — arise most often in natural & biological organisms & scenarios with few interactions. Height & weight are canonical examples. As such, my first instinct is to reach for the trusty iris dataset. It meets the requirement, but there’s just something underwhelming about n = 50 (the number of observations of a single species of flower in the dataset). I’m thinking bigger."
},
{
"code": null,
"e": 9257,
"s": 9202,
"text": "So let’s load the bigrquery package, & do bigRqueries."
},
{
"code": null,
"e": 9276,
"s": 9257,
"text": "library(bigrquery)"
},
{
"code": null,
"e": 9420,
"s": 9276,
"text": "Google’s BigQuery makes available numerous public datasets of real data, some quite large, from genomics to patents to wikipedia article stats."
},
{
"code": null,
"e": 9500,
"s": 9420,
"text": "For our initial purposes, the natality dataset appears sufficiently biological:"
},
{
"code": null,
"e": 9660,
"s": 9500,
"text": "project <- “YOUR-PROJECT-ID”sql <- “SELECT COUNT(*) FROM `bigquery-public-data.samples.natality`”query_exec(sql, project = project, use_legacy_sql = F)"
},
{
"code": null,
"e": 9931,
"s": 9660,
"text": "(protip: there’s lots of data here, & you get charged by the amount of data accessed, but your first TB per month is free. Further, while SELECT * is highly discouraged for obvious reasons, SELECT COUNT(*) is actually a free operation, & a good idea to scope things out)"
},
{
"code": null,
"e": 9939,
"s": 9931,
"text": "Output:"
},
{
"code": null,
"e": 9973,
"s": 9939,
"text": "0 bytes processed f0_1 137826763"
},
{
"code": null,
"e": 10153,
"s": 9973,
"text": "That’s more like it, 137 million baby records. We don’t quite need all of those, so let’s randomly sample 1% of the baby weights, take the first million results & see what we get:"
},
{
"code": null,
"e": 10360,
"s": 10153,
"text": "sql <- “SELECT weight_pounds FROM `bigquery-public-data.samples.natality` WHERE RAND() < .01”natal <- query_exec(sql, project = project, use_legacy_sql = F, max_pages = 100)"
},
{
"code": null,
"e": 10368,
"s": 10360,
"text": "Output:"
},
{
"code": null,
"e": 10509,
"s": 10368,
"text": "Running job /: 7s:1.0 gigabytes processedWarning message: Only first 100 pages of size 10000 retrieved. Use max_pages = Inf to retrieve all."
},
{
"code": null,
"e": 10543,
"s": 10509,
"text": "hist(natal$weight_pounds) yields:"
},
{
"code": null,
"e": 10558,
"s": 10543,
"text": "Normal af imo."
},
{
"code": null,
"e": 10666,
"s": 10558,
"text": "Now to find some multiplicative data with some skew, let’s move beyond the biological, to the sociological."
},
{
"code": null,
"e": 10782,
"s": 10666,
"text": "We’ll look at the New York dataset, which contains all sorts of urban info, including trips in yellow & green cabs."
},
{
"code": null,
"e": 10901,
"s": 10782,
"text": "sql <- “SELECT COUNT(*) FROM `nyc-tlc.green.trips_2015`”query_exec(sql, project = project, use_legacy_sql = F)"
},
{
"code": null,
"e": 10909,
"s": 10901,
"text": "Output:"
},
{
"code": null,
"e": 11004,
"s": 10909,
"text": "0 bytes processed f0_ 1 9896012"
},
{
"code": null,
"e": 11071,
"s": 11004,
"text": "Under 10 million, so lets grab trip distances for the whole thing:"
},
{
"code": null,
"e": 11095,
"s": 11071,
"text": "(this can take a while)"
},
{
"code": null,
"e": 11246,
"s": 11095,
"text": "sql <- \"SELECT trip_distance FROM `nyc-tlc.green.trips_2015`\"trips <- query_exec(sql, project = project, use_legacy_sql = F)hist(trips$trips_distance)"
},
{
"code": null,
"e": 11250,
"s": 11246,
"text": "-_-"
},
{
"code": null,
"e": 11415,
"s": 11250,
"text": "Looks like there are some extreme outliers pulling our x-axis out to 800 miles. Hell of a cab ride. Lets trim this down to trips under 20 miles & take another look:"
},
{
"code": null,
"e": 11466,
"s": 11415,
"text": "trips$trip_distance %>% subset(. <= 20) %>% hist()"
},
{
"code": null,
"e": 11623,
"s": 11466,
"text": "There we are, & with a telltale sign of a lognormal distribution: the long tail. Let’s check our data for lognormalcy by plotting the histogram of the logs:"
},
{
"code": null,
"e": 11684,
"s": 11623,
"text": "trips$trip_distance %>% subset(. <= 20) %>% log() %>% hist()"
},
{
"code": null,
"e": 11911,
"s": 11684,
"text": "Normalish for sure, but we overshot the mark a bit & now observe a bit of left-skew. Alas, the real world strikes again. But safe to say that a lognormal distribution wouldn’t be a completely preposterous model to employ here."
},
{
"code": null,
"e": 12071,
"s": 11911,
"text": "Moving on. Let’s find some more heavy-tailed data, this time in a domain closer to my own professional affinities of digital web analytics: the Github dataset:"
},
{
"code": null,
"e": 12207,
"s": 12071,
"text": "sql <- \"SELECT COUNT(*) FROM `bigquery-public-data.samples.github_nested`\"query_exec(sql, project = project, use_legacy_sql = F)"
},
{
"code": null,
"e": 12215,
"s": 12207,
"text": "Output:"
},
{
"code": null,
"e": 12247,
"s": 12215,
"text": "0 bytes processed f0_1 2541639"
},
{
"code": null,
"e": 12438,
"s": 12247,
"text": "2.5 million rows. Since I’m starting to worry about my local machine’s memory, we’ll employ our random sampler & million row delimiter to get a count of “watchers” of each github repository:"
},
{
"code": null,
"e": 12684,
"s": 12438,
"text": "sql <- “SELECT repository.watchers FROM `bigquery-public-data.samples.github_nested` WHERE RAND() < .5”github <- query_exec(sql, project = project, use_legacy_sql = F, max_pages = 100)github$watchers %>% hist()"
},
{
"code": null,
"e": 12746,
"s": 12684,
"text": "Again, extreme long tail dynamics, so let’s do some trimming:"
},
{
"code": null,
"e": 12802,
"s": 12746,
"text": "github$watchers %>% subset(5 < . & . < 3000) %>% hist()"
},
{
"code": null,
"e": 12818,
"s": 12802,
"text": "Exponential af."
},
{
"code": null,
"e": 12845,
"s": 12818,
"text": "But is it lognormal again?"
},
{
"code": null,
"e": 12911,
"s": 12845,
"text": "github$watchers %>% subset(5 < . & . < 3000) %>% log() %>% hist()"
},
{
"code": null,
"e": 12916,
"s": 12911,
"text": "Nay."
},
{
"code": null,
"e": 12988,
"s": 12916,
"text": "But behold the rare beast: the (approximately) LOGUNIFORM DISTRIBUTION!"
},
{
"code": null,
"e": 13086,
"s": 12988,
"text": "Let’s take one more draw from the big data urn, this time looking at scores of Hacker News posts:"
},
{
"code": null,
"e": 13217,
"s": 13086,
"text": "sql <- “SELECT COUNT(*) FROM `bigquery-public-data.hacker_news.full`”query_exec(sql, project = project, use_legacy_sql = F)"
},
{
"code": null,
"e": 13225,
"s": 13217,
"text": "Output:"
},
{
"code": null,
"e": 13258,
"s": 13225,
"text": "0 bytes processed f0_1 16489224"
},
{
"code": null,
"e": 13262,
"s": 13258,
"text": "..."
},
{
"code": null,
"e": 13473,
"s": 13262,
"text": "sql <- “SELECT score FROM `bigquery-public-data.hacker_news.full` WHERE RAND() < .1”hn <- query_exec(sql, project = project, use_legacy_sql = F, max_pages = 100)hn$score %>% hist()"
},
{
"code": null,
"e": 13477,
"s": 13473,
"text": "..."
},
{
"code": null,
"e": 13527,
"s": 13477,
"text": "hn$score %>% subset(10 < . & . <= 300) %>% hist()"
},
{
"code": null,
"e": 13588,
"s": 13527,
"text": "A slower decay (once trimmed). And as for the log-transform?"
},
{
"code": null,
"e": 13648,
"s": 13588,
"text": "hn$score %>% subset(10 < . & . <= 300) %>% log() %>% hist()"
},
{
"code": null,
"e": 13697,
"s": 13648,
"text": "Again roughly loguniform with a rightward decay."
},
{
"code": null,
"e": 13918,
"s": 13697,
"text": "My cursory search for a power law distribution in the wild proved fruitless, which is perhaps not surprising as they are most often posited in network science (&, even there, appear to be scarcer than initially claimed)."
},
{
"code": null,
"e": 14093,
"s": 13918,
"text": "In any event, lets organize our real world datasets as we did with our simulated distributions & plot them comparatively. We’ll normalize them & again center them around 100:"
},
{
"code": null,
"e": 14106,
"s": 14093,
"text": "Now to plot:"
},
{
"code": null,
"e": 14355,
"s": 14106,
"text": "True to the real world they come from, a bit rougher around the edges than our simulated distributions. Still, remarkably similar. Let’s plot them side by side with the new (& excellent) patchwork package from the indispensable Thomas Lin Pedersen:"
},
{
"code": null,
"e": 14615,
"s": 14355,
"text": "At a glance, our simulated distributions would provide reasonable models for their adjacent real world datasets, with the exception of power law -> hacker news scores, where the the concavity of the decay & the weight of the tails are substantially different."
},
{
"code": null,
"e": 14785,
"s": 14615,
"text": "There are of course many more rigorous tests of model fit etc, but let’s just take another look by plotting the summary statistics of the distributions as we did before."
},
{
"code": null,
"e": 15298,
"s": 14785,
"text": "Unfortunately, something about the normalized real world data is screwing with my summary statistic calculations, which are all coming back more or less indistinguishable from each other. I suspect this has something to do with computers’ struggles with floating point arithmetic (but might just have to do with my own struggles with numeracy). In any event, we’ll have to use our unnormalized real world data, which means we’ll have to plot them individually & attempt to line up the ggridge patchwork manually."
},
{
"code": null,
"e": 15376,
"s": 15298,
"text": "First to compile our unnormalized distributions & compute summary statistics:"
},
{
"code": null,
"e": 15528,
"s": 15376,
"text": "Now to plot (this is ugly since we have to create individual plots for each real distribution, but patchwork allows us to elegantly define the layout):"
},
{
"code": null,
"e": 15688,
"s": 15528,
"text": "Interesting that our real world dataset summary stats seem to have substantially more spread than our simulated distributions. Let’s zoom in for a closer look."
},
{
"code": null,
"e": 15828,
"s": 15688,
"text": "I won’t repost all the code, but basically just modified pm1 to have xlim(90, 150) & uncommented the xlim() lines in the rest of the plots:"
},
{
"code": null,
"e": 16031,
"s": 15828,
"text": "Here even starker, but for the normalish distributions: summary statistic dynamics diverge widely, which should give us pause when facilely ‘eyeballing’ the fit of an idealized model to real world data."
},
{
"code": null,
"e": 16127,
"s": 16031,
"text": "This concludes our exploration of Pythagorean Means under simulated & real world distributions."
},
{
"code": null,
"e": 16275,
"s": 16127,
"text": "If you haven’t already, check out Part I for a lower level, more explicit & intuitive introduction. And see below for references & further reading."
},
{
"code": null,
"e": 16311,
"s": 16275,
"text": "Also, follow me for more like this!"
},
{
"code": null,
"e": 16402,
"s": 16311,
"text": "— Follow on twitter: @dnlmcLinkedIn: linkedin.com/in/dnlmcGithub: https://github.com/dnlmc"
},
{
"code": null,
"e": 16409,
"s": 16402,
"text": "Part I"
},
{
"code": null,
"e": 16457,
"s": 16409,
"text": "https://en.wikipedia.org/wiki/Pythagorean_means"
},
{
"code": null,
"e": 16506,
"s": 16457,
"text": "https://en.wikipedia.org/wiki/Summary_statistics"
},
{
"code": null,
"e": 16553,
"s": 16506,
"text": "https://en.wikipedia.org/wiki/Central_tendency"
},
{
"code": null,
"e": 16605,
"s": 16553,
"text": "“Measures of Location & Spread” — stat.berkeley.edu"
},
{
"code": null,
"e": 16653,
"s": 16605,
"text": "“Median vs Average Household Income” — LinkedIn"
},
{
"code": null,
"e": 16677,
"s": 16653,
"text": "“Mean vs Median Income”"
},
{
"code": null,
"e": 16738,
"s": 16677,
"text": "“You should summarize data with the geometric mean” — Medium"
},
{
"code": null,
"e": 16785,
"s": 16738,
"text": "“Which ‘mean’ to use & when?” — Stack Overflow"
},
{
"code": null,
"e": 16889,
"s": 16785,
"text": "“When is it most appropriate to take the arithmetic mean vs. geometric mean vs. harmonic mean?” — Quora"
},
{
"code": null,
"e": 16938,
"s": 16889,
"text": "“Arithmetric, Harmonic & Geometric Means with R”"
},
{
"code": null,
"e": 17036,
"s": 16938,
"text": "“Using the Price-to-Earnings Harmonic Mean to Improve Firm Valuation Estimates” — Journal article"
},
{
"code": null,
"e": 17044,
"s": 17036,
"text": "Part II"
},
{
"code": null,
"e": 17100,
"s": 17044,
"text": "https://en.wikipedia.org/wiki/Heavy-tailed_distribution"
},
{
"code": null,
"e": 17176,
"s": 17100,
"text": "https://en.wikipedia.org/wiki/Relationships_among_probability_distributions"
},
{
"code": null,
"e": 17244,
"s": 17176,
"text": "http://www.win-vector.com/blog/2010/02/living-in-a-lognormal-world/"
},
{
"code": null,
"e": 17343,
"s": 17244,
"text": "“A Brief History of Generative Models for Power Law and Lognormal Distributions” — Journal article"
},
{
"code": null,
"e": 17426,
"s": 17343,
"text": "“Difference between power law distribution and exponential decay” — Stack Exchange"
}
] |
Tryit Editor v3.7
|
Tryit: bigger HTML heading
|
[] |
Python - Check if a list is contained in another list
|
Given two different python lists we need to find if the first list is a part of the second list.
We can first apply the map function to get the elements of the list and then apply the join function to cerate a comma separated list of values. Next we use the in operator to find out if the first list is part of the second list.
Live Demo
listA = ['x', 'y', 't']
listB = ['t', 'z','a','x', 'y', 't']
print("Given listA elemnts: ")
print(', '.join(map(str, listA)))
print("Given listB elemnts:")
print(', '.join(map(str, listB)))
res = ', '.join(map(str, listA)) in ', '.join(map(str, listB))
if res:
print("List A is part of list B")
else:
print("List A is not a part of list B")
Running the above code gives us the following result −
Given listA elemnts:
x, y, t
Given listB elemnts:
t, z, a, x, y, t
List A is part of list B
We can design a for loop to check the presence of elements form one list in another using the range function and the len function.
Live Demo
listA = ['x', 'y', 't']
listB = ['t', 'z','a','x', 'y', 't']
print("Given listA elemnts: \n",listA)
print("Given listB elemnts:\n",listB)
n = len(listA)
res = any(listA == listB[i:i + n] for i in range(len(listB) - n + 1))
if res:
print("List A is part of list B")
else:
print("List A is not a part of list B")
Running the above code gives us the following result −
Given listA elemnts:
['x', 'y', 't']
Given listB elemnts:
['t', 'z', 'a', 'x', 'y', 't']
List A is part of list B
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "Given two different python lists we need to find if the first list is a part of the second list."
},
{
"code": null,
"e": 1390,
"s": 1159,
"text": "We can first apply the map function to get the elements of the list and then apply the join function to cerate a comma separated list of values. Next we use the in operator to find out if the first list is part of the second list."
},
{
"code": null,
"e": 1401,
"s": 1390,
"text": " Live Demo"
},
{
"code": null,
"e": 1749,
"s": 1401,
"text": "listA = ['x', 'y', 't']\nlistB = ['t', 'z','a','x', 'y', 't']\nprint(\"Given listA elemnts: \")\nprint(', '.join(map(str, listA)))\nprint(\"Given listB elemnts:\")\nprint(', '.join(map(str, listB)))\n\nres = ', '.join(map(str, listA)) in ', '.join(map(str, listB))\nif res:\n print(\"List A is part of list B\")\nelse:\n print(\"List A is not a part of list B\")"
},
{
"code": null,
"e": 1804,
"s": 1749,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 1896,
"s": 1804,
"text": "Given listA elemnts:\nx, y, t\nGiven listB elemnts:\nt, z, a, x, y, t\nList A is part of list B"
},
{
"code": null,
"e": 2027,
"s": 1896,
"text": "We can design a for loop to check the presence of elements form one list in another using the range function and the len function."
},
{
"code": null,
"e": 2038,
"s": 2027,
"text": " Live Demo"
},
{
"code": null,
"e": 2357,
"s": 2038,
"text": "listA = ['x', 'y', 't']\nlistB = ['t', 'z','a','x', 'y', 't']\nprint(\"Given listA elemnts: \\n\",listA)\nprint(\"Given listB elemnts:\\n\",listB)\n\nn = len(listA)\nres = any(listA == listB[i:i + n] for i in range(len(listB) - n + 1))\n\nif res:\n print(\"List A is part of list B\")\nelse:\n print(\"List A is not a part of list B\")"
},
{
"code": null,
"e": 2412,
"s": 2357,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2526,
"s": 2412,
"text": "Given listA elemnts:\n['x', 'y', 't']\nGiven listB elemnts:\n['t', 'z', 'a', 'x', 'y', 't']\nList A is part of list B"
}
] |
C# | BitConverter.ToDouble() Method - GeeksforGeeks
|
01 Feb, 2019
BitConverter.ToDouble() Method is used to return a double-precision floating point number converted from eight bytes at a specified position in a byte array.
Syntax:
public static double ToDouble (byte[] value, int startIndex);
Parameters:
value: It is an array of bytes.startIndex: It is the starting position within the value.
Return Value: This method returns a double precision floating point number formed by eight bytes beginning at startIndex.
Exceptions:
ArgumentException: If the startIndex is greater than or equal to the length of value minus 7, and is less than or equal to the length of value minus 1.
ArgumentNullException: If the value is null.
ArgumentOutOfRangeException: If the startIndex is less than zero or greater than the length of value minus 1.
Below programs illustrate the use of BitConverter.ToDouble(Byte[], Int32) Method:
Example 1:
// C# program to demonstrate// BitConverter.ToDouble(Byte[], Int32)// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array of byte values. byte[] bytes = {0,0,1,2,7,126,78,55, 255,78,45,198,200,1, 1,1,1,255,255,2,4,4, 77,77,77,77,77,0,1}; // Display the values of the myArr. Console.WriteLine("Initial Array: "); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(bytes); // print char value Console.WriteLine("index Array elements "+ " double values"); Console.WriteLine(); // getting double value and Display it for (int index = 0; index < bytes.Length - 7; index = index + 8) { double values = BitConverter.ToDouble(bytes, index); Console.WriteLine(" {0} {1} {2}", index, BitConverter.ToString(bytes, index, 8), values); } } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ int count = 0; for (int i = 0; i < myArr.Length; i++) { if (count == 18) { Console.WriteLine(); Console.Write("{0} ", myArr[i]); count = 0; } else { Console.Write("{0} ", myArr[i]); count++; } } Console.WriteLine(); Console.WriteLine();}}
Output:
Initial Array:
0 0 1 2 7 126 78 55 255 78 45 198 200 1 1 1 1 255
255 2 4 4 77 77 77 77 77 0 1
index Array elements double values
0 00-00-01-02-07-7E-4E-37 2.73464354303054E-42
8 FF-4E-2D-C6-C8-01-01-01 7.74999325882041E-304
16 01-FF-FF-02-04-04-4D-4D 2.38727219494443E+64
Example 2: For ArgumentException
// C# program to demonstrate// BitConverter.ToDouble(Byte[], Int32)// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array of byte values. byte[] bytes = {0,0,1,2,7,126,78,55, 255,78,45,198,200,1, 1,1,1,255,255,2,4,4, 77,77,77,77,77,0,1, 0,0,1,2,7,126,78,55, 255,78,45,198,200,1, 1,1,1,255,255,2,4,4, 255,255,255,255,245, 245,245,245,245,245, 245,245,245,245,0,0, 0,0,0,0,0,0,6,5,6,56, 31,31,31,54,23,253,}; // Display the values of the myArr. Console.WriteLine("Initial Array: "); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(bytes); // print char value Console.WriteLine("index Array elements"+ " double values"); Console.WriteLine(); // getting double value and Display it for (int index = 4; index < bytes.Length - 6; index = index + 8) { if (index == bytes.Length - 7) { Console.WriteLine(); Console.WriteLine("startIndex is equal to"+ " the length of bytes minus 7"); double values = BitConverter.ToDouble(bytes, index); Console.WriteLine(" {0} {1} {2}", index, BitConverter.ToString(bytes, index, 4), values); } else { double values = BitConverter.ToDouble(bytes, index); Console.WriteLine(" {0} {1} {2}", index, BitConverter.ToString(bytes, index, 8), values); } } } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ int count = 0; for (int i = 0; i < myArr.Length; i++) { if (count == 18) { Console.WriteLine(); Console.Write("{0} ", myArr[i]); count = 0; } else { Console.Write("{0} ", myArr[i]); count++; } } Console.WriteLine(); Console.WriteLine();}}
Output:
Initial Array:
0 0 1 2 7 126 78 55 255 78 45 198 200 1 1 1 1 255
255 2 4 4 77 77 77 77 77 0 1 0 0 1 2 7 126 78 55
255 78 45 198 200 1 1 1 1 255 255 2 4 4 255 255 255 255 245
245 245 245 245 245 245 245 245 245 0 0 0 0 0 0 0 0 6 5
6 56 31 31 31 54 23 253
index Array elements double values
4 07-7E-4E-37-FF-4E-2D-C6 -1.16103254047091E+30
12 C8-01-01-01-01-FF-FF-02 3.13113229681351E-294
20 04-04-4D-4D-4D-4D-4D-00 3.25995134720157E-307
28 01-00-00-01-02-07-7E-4E 1.29525825666467E+70
36 37-FF-4E-2D-C6-C8-01-01 8.10420695824091E-304
44 01-01-FF-FF-02-04-04-FF -6.86302832487538E+303
52 FF-FF-FF-F5-F5-F5-F5-F5 -1.68827860814431E+260
60 F5-F5-F5-F5-F5-00-00-00 5.21927749055768E-312
68 00-00-00-00-00-06-05-06 1.15818454395586E-279
startIndex is equal to the length of bytes minus 7
Exception Thrown: System.ArgumentException
Example 3: For ArgumentOutOfRangeException
// C# program to demonstrate// BitConverter.ToDouble(Byte[], Int32)// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array of byte values. byte[] bytes = {0,0,1,2,7,126,78,55, 255,78,45,198,200,1, 1,1,1,255,255,2,4,4, 77,77,77,77,77,0,1, 0,0,1,2,7,126,78,55, 255,78,45,198,200,1, 1,1,1,255,255,2,4,4, 255,255,255,255,245, 245,245,245,245,245, 245,245,245,245,0,0, 0,0,0,0,0,0,6,5,6,56, 31,31,31,54,23,253,}; // Display the values of the myArr. Console.WriteLine("Initial Array: "); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(bytes); // getting double value and Display it Console.WriteLine("startIndex is less than zero"); double values = BitConverter.ToDouble(bytes, -1); Console.WriteLine(" {0} {1} {2}", -1, BitConverter.ToString(bytes, -1, 8), values); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ int count = 0; for (int i = 0; i < myArr.Length; i++) { if (count == 18) { Console.WriteLine(); Console.Write("{0} ", myArr[i]); count = 0; } else { Console.Write("{0} ", myArr[i]); count++; } } Console.WriteLine(); Console.WriteLine();}}
Output:
Initial Array:
0 0 1 2 7 126 78 55 255 78 45 198 200 1 1 1 1 255
255 2 4 4 77 77 77 77 77 0 1 0 0 1 2 7 126 78 55
255 78 45 198 200 1 1 1 1 255 255 2 4 4 255 255 255 255 245
245 245 245 245 245 245 245 245 245 0 0 0 0 0 0 0 0 6 5
6 56 31 31 31 54 23 253
startIndex is less than zero
Exception Thrown: System.ArgumentOutOfRangeException
Example 4: For ArgumentNullException
// C# program to demonstrate// BitConverter.ToDouble(Byte[], Int32)// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array of byte values. byte[] bytes = null; // getting double value and Display it Console.WriteLine("array bytes is null"); double values = BitConverter.ToDouble(bytes, 0); Console.WriteLine(" {0} {1} {2}", 0, BitConverter.ToString(bytes, 0, 8), values); } catch (ArgumentNullException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ int count = 0; for (int i = 0; i < myArr.Length; i++) { if (count == 18) { Console.WriteLine(); Console.Write("{0} ", myArr[i]); count = 0; } else { Console.Write("{0} ", myArr[i]); count++; } } Console.WriteLine(); Console.WriteLine();}}
Output:
array bytes is null
Exception Thrown: System.ArgumentNullException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter.todouble?view=netframework-4.7.2
CSharp-BitConverter-Class
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | IsNullOrEmpty() Method
C# | Method Overriding
C# Dictionary with examples
String.Split() Method in C# with Examples
Difference between Ref and Out keywords in C#
C# | Arrays of Strings
C# | Delegates
Top 50 C# Interview Questions & Answers
|
[
{
"code": null,
"e": 22891,
"s": 22863,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 23049,
"s": 22891,
"text": "BitConverter.ToDouble() Method is used to return a double-precision floating point number converted from eight bytes at a specified position in a byte array."
},
{
"code": null,
"e": 23057,
"s": 23049,
"text": "Syntax:"
},
{
"code": null,
"e": 23119,
"s": 23057,
"text": "public static double ToDouble (byte[] value, int startIndex);"
},
{
"code": null,
"e": 23131,
"s": 23119,
"text": "Parameters:"
},
{
"code": null,
"e": 23220,
"s": 23131,
"text": "value: It is an array of bytes.startIndex: It is the starting position within the value."
},
{
"code": null,
"e": 23342,
"s": 23220,
"text": "Return Value: This method returns a double precision floating point number formed by eight bytes beginning at startIndex."
},
{
"code": null,
"e": 23354,
"s": 23342,
"text": "Exceptions:"
},
{
"code": null,
"e": 23506,
"s": 23354,
"text": "ArgumentException: If the startIndex is greater than or equal to the length of value minus 7, and is less than or equal to the length of value minus 1."
},
{
"code": null,
"e": 23551,
"s": 23506,
"text": "ArgumentNullException: If the value is null."
},
{
"code": null,
"e": 23661,
"s": 23551,
"text": "ArgumentOutOfRangeException: If the startIndex is less than zero or greater than the length of value minus 1."
},
{
"code": null,
"e": 23743,
"s": 23661,
"text": "Below programs illustrate the use of BitConverter.ToDouble(Byte[], Int32) Method:"
},
{
"code": null,
"e": 23754,
"s": 23743,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate// BitConverter.ToDouble(Byte[], Int32)// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array of byte values. byte[] bytes = {0,0,1,2,7,126,78,55, 255,78,45,198,200,1, 1,1,1,255,255,2,4,4, 77,77,77,77,77,0,1}; // Display the values of the myArr. Console.WriteLine(\"Initial Array: \"); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(bytes); // print char value Console.WriteLine(\"index Array elements \"+ \" double values\"); Console.WriteLine(); // getting double value and Display it for (int index = 0; index < bytes.Length - 7; index = index + 8) { double values = BitConverter.ToDouble(bytes, index); Console.WriteLine(\" {0} {1} {2}\", index, BitConverter.ToString(bytes, index, 8), values); } } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ int count = 0; for (int i = 0; i < myArr.Length; i++) { if (count == 18) { Console.WriteLine(); Console.Write(\"{0} \", myArr[i]); count = 0; } else { Console.Write(\"{0} \", myArr[i]); count++; } } Console.WriteLine(); Console.WriteLine();}}",
"e": 25764,
"s": 23754,
"text": null
},
{
"code": null,
"e": 25772,
"s": 25764,
"text": "Output:"
},
{
"code": null,
"e": 26095,
"s": 25772,
"text": "Initial Array: \n0 0 1 2 7 126 78 55 255 78 45 198 200 1 1 1 1 255 \n255 2 4 4 77 77 77 77 77 0 1 \n\nindex Array elements double values\n\n 0 00-00-01-02-07-7E-4E-37 2.73464354303054E-42\n 8 FF-4E-2D-C6-C8-01-01-01 7.74999325882041E-304\n 16 01-FF-FF-02-04-04-4D-4D 2.38727219494443E+64\n"
},
{
"code": null,
"e": 26128,
"s": 26095,
"text": "Example 2: For ArgumentException"
},
{
"code": "// C# program to demonstrate// BitConverter.ToDouble(Byte[], Int32)// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array of byte values. byte[] bytes = {0,0,1,2,7,126,78,55, 255,78,45,198,200,1, 1,1,1,255,255,2,4,4, 77,77,77,77,77,0,1, 0,0,1,2,7,126,78,55, 255,78,45,198,200,1, 1,1,1,255,255,2,4,4, 255,255,255,255,245, 245,245,245,245,245, 245,245,245,245,0,0, 0,0,0,0,0,0,6,5,6,56, 31,31,31,54,23,253,}; // Display the values of the myArr. Console.WriteLine(\"Initial Array: \"); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(bytes); // print char value Console.WriteLine(\"index Array elements\"+ \" double values\"); Console.WriteLine(); // getting double value and Display it for (int index = 4; index < bytes.Length - 6; index = index + 8) { if (index == bytes.Length - 7) { Console.WriteLine(); Console.WriteLine(\"startIndex is equal to\"+ \" the length of bytes minus 7\"); double values = BitConverter.ToDouble(bytes, index); Console.WriteLine(\" {0} {1} {2}\", index, BitConverter.ToString(bytes, index, 4), values); } else { double values = BitConverter.ToDouble(bytes, index); Console.WriteLine(\" {0} {1} {2}\", index, BitConverter.ToString(bytes, index, 8), values); } } } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ int count = 0; for (int i = 0; i < myArr.Length; i++) { if (count == 18) { Console.WriteLine(); Console.Write(\"{0} \", myArr[i]); count = 0; } else { Console.Write(\"{0} \", myArr[i]); count++; } } Console.WriteLine(); Console.WriteLine();}}",
"e": 29049,
"s": 26128,
"text": null
},
{
"code": null,
"e": 29057,
"s": 29049,
"text": "Output:"
},
{
"code": null,
"e": 30070,
"s": 29057,
"text": "Initial Array: \n0 0 1 2 7 126 78 55 255 78 45 198 200 1 1 1 1 255 \n255 2 4 4 77 77 77 77 77 0 1 0 0 1 2 7 126 78 55 \n255 78 45 198 200 1 1 1 1 255 255 2 4 4 255 255 255 255 245 \n245 245 245 245 245 245 245 245 245 0 0 0 0 0 0 0 0 6 5 \n6 56 31 31 31 54 23 253 \n\nindex Array elements double values\n\n 4 07-7E-4E-37-FF-4E-2D-C6 -1.16103254047091E+30\n 12 C8-01-01-01-01-FF-FF-02 3.13113229681351E-294\n 20 04-04-4D-4D-4D-4D-4D-00 3.25995134720157E-307\n 28 01-00-00-01-02-07-7E-4E 1.29525825666467E+70\n 36 37-FF-4E-2D-C6-C8-01-01 8.10420695824091E-304\n 44 01-01-FF-FF-02-04-04-FF -6.86302832487538E+303\n 52 FF-FF-FF-F5-F5-F5-F5-F5 -1.68827860814431E+260\n 60 F5-F5-F5-F5-F5-00-00-00 5.21927749055768E-312\n 68 00-00-00-00-00-06-05-06 1.15818454395586E-279\n\nstartIndex is equal to the length of bytes minus 7\nException Thrown: System.ArgumentException\n"
},
{
"code": null,
"e": 30113,
"s": 30070,
"text": "Example 3: For ArgumentOutOfRangeException"
},
{
"code": "// C# program to demonstrate// BitConverter.ToDouble(Byte[], Int32)// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array of byte values. byte[] bytes = {0,0,1,2,7,126,78,55, 255,78,45,198,200,1, 1,1,1,255,255,2,4,4, 77,77,77,77,77,0,1, 0,0,1,2,7,126,78,55, 255,78,45,198,200,1, 1,1,1,255,255,2,4,4, 255,255,255,255,245, 245,245,245,245,245, 245,245,245,245,0,0, 0,0,0,0,0,0,6,5,6,56, 31,31,31,54,23,253,}; // Display the values of the myArr. Console.WriteLine(\"Initial Array: \"); // calling the PrintIndexAndValues() // method to print PrintIndexAndValues(bytes); // getting double value and Display it Console.WriteLine(\"startIndex is less than zero\"); double values = BitConverter.ToDouble(bytes, -1); Console.WriteLine(\" {0} {1} {2}\", -1, BitConverter.ToString(bytes, -1, 8), values); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ int count = 0; for (int i = 0; i < myArr.Length; i++) { if (count == 18) { Console.WriteLine(); Console.Write(\"{0} \", myArr[i]); count = 0; } else { Console.Write(\"{0} \", myArr[i]); count++; } } Console.WriteLine(); Console.WriteLine();}}",
"e": 32192,
"s": 30113,
"text": null
},
{
"code": null,
"e": 32200,
"s": 32192,
"text": "Output:"
},
{
"code": null,
"e": 32544,
"s": 32200,
"text": "Initial Array: \n0 0 1 2 7 126 78 55 255 78 45 198 200 1 1 1 1 255 \n255 2 4 4 77 77 77 77 77 0 1 0 0 1 2 7 126 78 55 \n255 78 45 198 200 1 1 1 1 255 255 2 4 4 255 255 255 255 245 \n245 245 245 245 245 245 245 245 245 0 0 0 0 0 0 0 0 6 5 \n6 56 31 31 31 54 23 253 \n\nstartIndex is less than zero\nException Thrown: System.ArgumentOutOfRangeException\n"
},
{
"code": null,
"e": 32581,
"s": 32544,
"text": "Example 4: For ArgumentNullException"
},
{
"code": "// C# program to demonstrate// BitConverter.ToDouble(Byte[], Int32)// Methodusing System; class GFG { // Main Methodpublic static void Main(){ try { // Define an array of byte values. byte[] bytes = null; // getting double value and Display it Console.WriteLine(\"array bytes is null\"); double values = BitConverter.ToDouble(bytes, 0); Console.WriteLine(\" {0} {1} {2}\", 0, BitConverter.ToString(bytes, 0, 8), values); } catch (ArgumentNullException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } catch (ArgumentException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); }} // Defining the method// PrintIndexAndValuespublic static void PrintIndexAndValues(byte[] myArr){ int count = 0; for (int i = 0; i < myArr.Length; i++) { if (count == 18) { Console.WriteLine(); Console.Write(\"{0} \", myArr[i]); count = 0; } else { Console.Write(\"{0} \", myArr[i]); count++; } } Console.WriteLine(); Console.WriteLine();}}",
"e": 33943,
"s": 32581,
"text": null
},
{
"code": null,
"e": 33951,
"s": 33943,
"text": "Output:"
},
{
"code": null,
"e": 34019,
"s": 33951,
"text": "array bytes is null\nException Thrown: System.ArgumentNullException\n"
},
{
"code": null,
"e": 34030,
"s": 34019,
"text": "Reference:"
},
{
"code": null,
"e": 34127,
"s": 34030,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.bitconverter.todouble?view=netframework-4.7.2"
},
{
"code": null,
"e": 34153,
"s": 34127,
"text": "CSharp-BitConverter-Class"
},
{
"code": null,
"e": 34167,
"s": 34153,
"text": "CSharp-method"
},
{
"code": null,
"e": 34170,
"s": 34167,
"text": "C#"
},
{
"code": null,
"e": 34268,
"s": 34170,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34277,
"s": 34268,
"text": "Comments"
},
{
"code": null,
"e": 34290,
"s": 34277,
"text": "Old Comments"
},
{
"code": null,
"e": 34344,
"s": 34290,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 34406,
"s": 34344,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 34434,
"s": 34406,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 34457,
"s": 34434,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 34485,
"s": 34457,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 34527,
"s": 34485,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 34573,
"s": 34527,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 34596,
"s": 34573,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 34611,
"s": 34596,
"text": "C# | Delegates"
}
] |
Generic Map In Java - GeeksforGeeks
|
29 Oct, 2020
Java Arrays store items in an ordered collection and the values can be accessed using the index(an integer). Whereas HashMap stores as a Key/ Value pair. Using HashMap, we can store the items or values and these values can be accessed by indexes/ keys of any type be it Integer, String, Double, Character, or any user-defined datatype.
The Mappings in a HashMap are from Key → Value
HashMap is a part of Java since Java 1.2. It implements java.util.Map interface.
What is Generic Map and how is it different from the term HashMap?
The term generic simply is the idea of allowing the type (Integer, Double, String, etc. or any user-defined type) to be the parameter to methods, class, or interface. For eg, all the inbuilt collections in java like ArrayList, HashSet, HashMap, etc. use generics.
Generic Map in simple language can be generalized as:
Map< K, V > map = new HashMap< K, V >();
Where K and V are used to specify the generic type parameter passed in the declaration of a HashMap. We can add any type be it Integer, String, Float, Character, or any user-defined type in place of K and V in the above syntax to specify that we can initialize the HashMap of our wish.
Example:
Suppose if the key is of type String and the corresponding value is of type Integer, then we can initialize it as,
Map< String , Integer > map = new HashMap< String ,Integer >();
The map can now only accept String instances as key and Integer instances as values.
This can be done by using put() and get() function.
1. put(): Used to add a new key/value pair to the Hashmap.
2. get(): Used to get the value corresponding to a particular key.
Example :
Map< Integer, String > map = new HashMap<>();
// adding the key 123 and value
// corresponding to it as abc in the map
map.put( 123, "abc");
map.put(65, "a");
map.put(2554 , "GFG");
map.get(65);
Output:
a
Map has two collections for iteration. One is keySet() and the other is values().
Example: Using iterator() method
Map<Integer, Integer> map = new HashMap<>;
//adding key, value pairs to the Map
// iterate keys.
Iterator<Integer> key = map.keySet().iterator();
while(key.hasNext()){
Integer aKey = key.next();
String aValue = map.get(aKey);
}
Iterator<Integer> value = map.values().iterator();
while(valueIterator.hasNext()){
String aString = value.next();
}
Example: Using new for-loop or for-each loop or generic for loop
Map<Integer, String> map = new HashMap<Integer, String>;
//adding key, value pairs to the Map
//using for-each loop
for(Integer key : map.keySet()) {
String value = map.get(key);
System.out.println("" + key + ":" + value);
}
for(String value : map.values()) {
System.out.println(value);
}
Java Program to illustrate the usage of a map
Java
// Java program to demonstrate// Generic Map import java.io.*;import java.util.*; class GenericMap { public static void main(String[] args) { // create array of strings String arr[] = { "gfg", "code", "quiz", "program", "code", "website", "quiz", "gfg", "java", "gfg", "program" }; // to count the frequency of a string and store it // in the map Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < arr.length; i++) { if (map.containsKey(arr[i])) { int count = map.get(arr[i]); map.put(arr[i], count + 1); } else { map.put(arr[i], 1); } } // to get and print the count of the mentioned // string System.out.println(map.get("gfg")); System.out.println(map.get("code")); }}
3
2
Java-Generics
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
StringBuilder Class in Java with Examples
Comparator Interface in Java with Examples
Generics in Java
Functional Interfaces in Java
Java Programming Examples
HashMap get() Method in Java
|
[
{
"code": null,
"e": 23868,
"s": 23840,
"text": "\n29 Oct, 2020"
},
{
"code": null,
"e": 24204,
"s": 23868,
"text": "Java Arrays store items in an ordered collection and the values can be accessed using the index(an integer). Whereas HashMap stores as a Key/ Value pair. Using HashMap, we can store the items or values and these values can be accessed by indexes/ keys of any type be it Integer, String, Double, Character, or any user-defined datatype."
},
{
"code": null,
"e": 24251,
"s": 24204,
"text": "The Mappings in a HashMap are from Key → Value"
},
{
"code": null,
"e": 24332,
"s": 24251,
"text": "HashMap is a part of Java since Java 1.2. It implements java.util.Map interface."
},
{
"code": null,
"e": 24399,
"s": 24332,
"text": "What is Generic Map and how is it different from the term HashMap?"
},
{
"code": null,
"e": 24664,
"s": 24399,
"text": "The term generic simply is the idea of allowing the type (Integer, Double, String, etc. or any user-defined type) to be the parameter to methods, class, or interface. For eg, all the inbuilt collections in java like ArrayList, HashSet, HashMap, etc. use generics. "
},
{
"code": null,
"e": 24718,
"s": 24664,
"text": "Generic Map in simple language can be generalized as:"
},
{
"code": null,
"e": 24760,
"s": 24718,
"text": "Map< K, V > map = new HashMap< K, V >();\n"
},
{
"code": null,
"e": 25046,
"s": 24760,
"text": "Where K and V are used to specify the generic type parameter passed in the declaration of a HashMap. We can add any type be it Integer, String, Float, Character, or any user-defined type in place of K and V in the above syntax to specify that we can initialize the HashMap of our wish."
},
{
"code": null,
"e": 25055,
"s": 25046,
"text": "Example:"
},
{
"code": null,
"e": 25170,
"s": 25055,
"text": "Suppose if the key is of type String and the corresponding value is of type Integer, then we can initialize it as,"
},
{
"code": null,
"e": 25235,
"s": 25170,
"text": "Map< String , Integer > map = new HashMap< String ,Integer >();\n"
},
{
"code": null,
"e": 25320,
"s": 25235,
"text": "The map can now only accept String instances as key and Integer instances as values."
},
{
"code": null,
"e": 25372,
"s": 25320,
"text": "This can be done by using put() and get() function."
},
{
"code": null,
"e": 25431,
"s": 25372,
"text": "1. put(): Used to add a new key/value pair to the Hashmap."
},
{
"code": null,
"e": 25498,
"s": 25431,
"text": "2. get(): Used to get the value corresponding to a particular key."
},
{
"code": null,
"e": 25508,
"s": 25498,
"text": "Example :"
},
{
"code": null,
"e": 25710,
"s": 25508,
"text": "Map< Integer, String > map = new HashMap<>();\n\n// adding the key 123 and value\n// corresponding to it as abc in the map\nmap.put( 123, \"abc\"); \nmap.put(65, \"a\");\nmap.put(2554 , \"GFG\");\nmap.get(65);\n"
},
{
"code": null,
"e": 25718,
"s": 25710,
"text": "Output:"
},
{
"code": null,
"e": 25721,
"s": 25718,
"text": "a\n"
},
{
"code": null,
"e": 25803,
"s": 25721,
"text": "Map has two collections for iteration. One is keySet() and the other is values()."
},
{
"code": null,
"e": 25837,
"s": 25803,
"text": "Example: Using iterator() method "
},
{
"code": null,
"e": 26199,
"s": 25837,
"text": "Map<Integer, Integer> map = new HashMap<>;\n\n//adding key, value pairs to the Map\n\n// iterate keys.\nIterator<Integer> key = map.keySet().iterator();\n\nwhile(key.hasNext()){\n Integer aKey = key.next();\n String aValue = map.get(aKey);\n}\n\nIterator<Integer> value = map.values().iterator();\n\nwhile(valueIterator.hasNext()){\n String aString = value.next();\n}\n"
},
{
"code": null,
"e": 26264,
"s": 26199,
"text": "Example: Using new for-loop or for-each loop or generic for loop"
},
{
"code": null,
"e": 26569,
"s": 26264,
"text": "Map<Integer, String> map = new HashMap<Integer, String>;\n\n//adding key, value pairs to the Map\n\n//using for-each loop\nfor(Integer key : map.keySet()) {\n String value = map.get(key);\n System.out.println(\"\" + key + \":\" + value);\n}\n\nfor(String value : map.values()) {\n System.out.println(value);\n}\n"
},
{
"code": null,
"e": 26616,
"s": 26569,
"text": "Java Program to illustrate the usage of a map "
},
{
"code": null,
"e": 26621,
"s": 26616,
"text": "Java"
},
{
"code": "// Java program to demonstrate// Generic Map import java.io.*;import java.util.*; class GenericMap { public static void main(String[] args) { // create array of strings String arr[] = { \"gfg\", \"code\", \"quiz\", \"program\", \"code\", \"website\", \"quiz\", \"gfg\", \"java\", \"gfg\", \"program\" }; // to count the frequency of a string and store it // in the map Map<String, Integer> map = new HashMap<>(); for (int i = 0; i < arr.length; i++) { if (map.containsKey(arr[i])) { int count = map.get(arr[i]); map.put(arr[i], count + 1); } else { map.put(arr[i], 1); } } // to get and print the count of the mentioned // string System.out.println(map.get(\"gfg\")); System.out.println(map.get(\"code\")); }}",
"e": 27541,
"s": 26621,
"text": null
},
{
"code": null,
"e": 27545,
"s": 27541,
"text": "3\n2"
},
{
"code": null,
"e": 27559,
"s": 27545,
"text": "Java-Generics"
},
{
"code": null,
"e": 27564,
"s": 27559,
"text": "Java"
},
{
"code": null,
"e": 27569,
"s": 27564,
"text": "Java"
},
{
"code": null,
"e": 27667,
"s": 27569,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27676,
"s": 27667,
"text": "Comments"
},
{
"code": null,
"e": 27689,
"s": 27676,
"text": "Old Comments"
},
{
"code": null,
"e": 27735,
"s": 27689,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27756,
"s": 27735,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27771,
"s": 27756,
"text": "Stream In Java"
},
{
"code": null,
"e": 27790,
"s": 27771,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27832,
"s": 27790,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 27875,
"s": 27832,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27892,
"s": 27875,
"text": "Generics in Java"
},
{
"code": null,
"e": 27922,
"s": 27892,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27948,
"s": 27922,
"text": "Java Programming Examples"
}
] |
Git GitHub Getting Started
|
Go to GitHub and sign up for an account:
Note: Remember to use the same e-mail address you used in the Git config.
Now that you have made a GitHub account, sign in, and create a new Repo:
And fill in the relevant details:
We will go over the different options and what they mean later. But for
now, choose Public (if you want the repo to be viewable for anyone) or Private
(if you want to choose who should be able to view the repo). Either way, you
will be able to choose who can contribute to the repo.
Then click "Create repository".
Since we have already set up a local Git repo, we are going to
push that to GitHub:
Copy the URL, or click the clipboard marked in the image above.
Now paste it the following command:
git remote add origin https://github.com/w3schools-test/hello-world.git
git remote add origin URL specifies that you are adding a remote repository, with the specified URL, as an origin to your local Git repo.
Now we are going to push our master branch to the origin url, and set it as the default remote branch:
git push --set-upstream origin master
Enumerating objects: 22, done.
Counting objects: 100% (22/22), done.
Delta compression using up to 16 threads
Compressing objects: 100% (22/22), done.
Writing objects: 100% (22/22), 92.96 KiB | 23.24 MiB/s, done.
Total 22 (delta 11), reused 0 (delta 0), pack-reused 0
remote: Resolving deltas: 100% (11/11), done.
To https://github.com/w3schools-test/hello-world.git
* [new branch] master -> master
Branch 'master' set up to track remote branch 'master' from 'origin'.
Note: Since this is the first time you are connecting to
GitHub, you will get some kind of notification you to authenticate this connection.
Now, go back into GitHub and see that the repository has been updated:
Add a remote repository as an origin:
git https://abc.com/x/y.git
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 41,
"s": 0,
"text": "Go to GitHub and sign up for an account:"
},
{
"code": null,
"e": 115,
"s": 41,
"text": "Note: Remember to use the same e-mail address you used in the Git config."
},
{
"code": null,
"e": 188,
"s": 115,
"text": "Now that you have made a GitHub account, sign in, and create a new Repo:"
},
{
"code": null,
"e": 222,
"s": 188,
"text": "And fill in the relevant details:"
},
{
"code": null,
"e": 508,
"s": 222,
"text": "We will go over the different options and what they mean later. But for \nnow, choose Public (if you want the repo to be viewable for anyone) or Private \n(if you want to choose who should be able to view the repo). Either way, you \nwill be able to choose who can contribute to the repo."
},
{
"code": null,
"e": 540,
"s": 508,
"text": "Then click \"Create repository\"."
},
{
"code": null,
"e": 625,
"s": 540,
"text": "Since we have already set up a local Git repo, we are going to \npush that to GitHub:"
},
{
"code": null,
"e": 689,
"s": 625,
"text": "Copy the URL, or click the clipboard marked in the image above."
},
{
"code": null,
"e": 725,
"s": 689,
"text": "Now paste it the following command:"
},
{
"code": null,
"e": 797,
"s": 725,
"text": "git remote add origin https://github.com/w3schools-test/hello-world.git"
},
{
"code": null,
"e": 937,
"s": 797,
"text": "git remote add origin URL specifies that you are adding a remote repository, with the specified URL, as an origin to your local Git repo."
},
{
"code": null,
"e": 1040,
"s": 937,
"text": "Now we are going to push our master branch to the origin url, and set it as the default remote branch:"
},
{
"code": null,
"e": 1553,
"s": 1040,
"text": "git push --set-upstream origin master\nEnumerating objects: 22, done.\nCounting objects: 100% (22/22), done.\nDelta compression using up to 16 threads\nCompressing objects: 100% (22/22), done.\nWriting objects: 100% (22/22), 92.96 KiB | 23.24 MiB/s, done.\nTotal 22 (delta 11), reused 0 (delta 0), pack-reused 0\nremote: Resolving deltas: 100% (11/11), done.\nTo https://github.com/w3schools-test/hello-world.git\n * [new branch] master -> master\nBranch 'master' set up to track remote branch 'master' from 'origin'."
},
{
"code": null,
"e": 1697,
"s": 1553,
"text": "Note: Since this is the first time you are connecting to \n GitHub, you will get some kind of notification you to authenticate this connection."
},
{
"code": null,
"e": 1768,
"s": 1697,
"text": "Now, go back into GitHub and see that the repository has been updated:"
},
{
"code": null,
"e": 1806,
"s": 1768,
"text": "Add a remote repository as an origin:"
},
{
"code": null,
"e": 1838,
"s": 1806,
"text": "git https://abc.com/x/y.git\n"
},
{
"code": null,
"e": 1858,
"s": 1838,
"text": "\nStart the Exercise"
},
{
"code": null,
"e": 1891,
"s": 1858,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1933,
"s": 1891,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2040,
"s": 1933,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 2059,
"s": 2040,
"text": "[email protected]"
}
] |
Differences between org.simple.json and org.json libraries in Java?
|
The org.json.simple library allows us to read and write JSON data in Java. In other words, we can encode and decode the JSON object. The org.json.simple package contains important classes like JSONValue, JSONObject, JSONArray, JsonString and JsonNumber. We need to install the json-simple.jar file to execute a JSON program whereas org.json library has classes to parse JSON for Java. It also converts between JSON and XML, HTTP header, Cookies, and CDF. The org.json package contains important classes like JSONObject, JSONTokener, JSONWriter, JSONArray, CDL, Cookie and CookieList. We need to install the json.jar file to execute a JSON program.
import org.json.simple.JSONObject;
public class SimpleJsonTest {
public static void main(String[] args) {
JSONObject jsonObj = new JSONObject();
jsonObj.put("empName", "Raja");
jsonObj.put("employeeId", "115");
jsonObj.put("age","30");
System.out.println(jsonObj.toJSONString());
}
}
{"empName":"Raja","employeeId":"115","age":"30"}
import org.json.*;
public class JSONTest {
public static void main(String args[]) throws JSONException {
String json = "{" + "Name : Jai," + "Age : 25, " + "Salary: 25000.00 " + "}";
JSONObject jsonObj = new JSONObject(json);
System.out.println(jsonObj.toString());
}
}
{"Salary":25000,"Age":25,"Name":"Jai"}
|
[
{
"code": null,
"e": 1710,
"s": 1062,
"text": "The org.json.simple library allows us to read and write JSON data in Java. In other words, we can encode and decode the JSON object. The org.json.simple package contains important classes like JSONValue, JSONObject, JSONArray, JsonString and JsonNumber. We need to install the json-simple.jar file to execute a JSON program whereas org.json library has classes to parse JSON for Java. It also converts between JSON and XML, HTTP header, Cookies, and CDF. The org.json package contains important classes like JSONObject, JSONTokener, JSONWriter, JSONArray, CDL, Cookie and CookieList. We need to install the json.jar file to execute a JSON program."
},
{
"code": null,
"e": 2030,
"s": 1710,
"text": "import org.json.simple.JSONObject;\npublic class SimpleJsonTest {\n public static void main(String[] args) {\n JSONObject jsonObj = new JSONObject();\n jsonObj.put(\"empName\", \"Raja\");\n jsonObj.put(\"employeeId\", \"115\");\n jsonObj.put(\"age\",\"30\");\n System.out.println(jsonObj.toJSONString());\n }\n}"
},
{
"code": null,
"e": 2079,
"s": 2030,
"text": "{\"empName\":\"Raja\",\"employeeId\":\"115\",\"age\":\"30\"}"
},
{
"code": null,
"e": 2373,
"s": 2079,
"text": "import org.json.*;\npublic class JSONTest {\n public static void main(String args[]) throws JSONException {\n String json = \"{\" + \"Name : Jai,\" + \"Age : 25, \" + \"Salary: 25000.00 \" + \"}\";\n JSONObject jsonObj = new JSONObject(json);\n System.out.println(jsonObj.toString());\n }\n}"
},
{
"code": null,
"e": 2412,
"s": 2373,
"text": "{\"Salary\":25000,\"Age\":25,\"Name\":\"Jai\"}"
}
] |
Construct the full k-ary tree from its preorder traversal - GeeksforGeeks
|
01 Feb, 2022
Given an array that contains the preorder traversal of the full k-ary tree, construct the full k-ary tree and print its postorder traversal. A full k-ary tree is a tree where each node has either 0 or k children.
Examples:
Input : preorder[] = {1, 2, 5, 6, 7,
3, 8, 9, 10, 4}
k = 3
Output : Postorder traversal of constructed
full k-ary tree is: 5 6 7 2 8 9 10
3 4 1
Tree formed is: 1
/ | \
2 3 4
/|\ /|\
5 6 7 8 9 10
Input : preorder[] = {1, 2, 5, 6, 7, 3, 4}
k = 3
Output : Postorder traversal of constructed
full k-ary tree is: 5 6 7 2 4 3 1
Tree formed is: 1
/ | \
2 3 4
/|\
5 6 7
We have discussed this problem for Binary tree in below post. Construct a special tree from given preorder traversal
In this post, solution for a k-ary tree is discussed.In Preorder traversal, first root node is processed then followed by the left subtree and right subtree. Because of this, to construct a full k-ary tree, we just need to keep on creating the nodes without bothering about the previous constructed nodes. We can use this to build the tree recursively.
Following are the steps to solve the problem: 1. Find the height of the tree. 2. Traverse the preorder array and recursively add each node
C++
Java
Python3
C#
Javascript
// C++ program to build full k-ary tree from// its preorder traversal and to print the// postorder traversal of the tree.#include <bits/stdc++.h>using namespace std; // Structure of a node of an n-ary treestruct Node { int key; vector<Node*> child;}; // Utility function to create a new tree// node with k childrenNode* newNode(int value){ Node* nNode = new Node; nNode->key = value; return nNode;} // Function to build full k-ary treeNode* BuildKaryTree(int A[], int n, int k, int h, int& ind){ // For null tree if (n <= 0) return NULL; Node* nNode = newNode(A[ind]); if (nNode == NULL) { cout << "Memory error" << endl; return NULL; } // For adding k children to a node for (int i = 0; i < k; i++) { // Check if ind is in range of array // Check if height of the tree is greater than 1 if (ind < n - 1 && h > 1) { ind++; // Recursively add each child nNode->child.push_back(BuildKaryTree(A, n, k, h - 1, ind)); } else { nNode->child.push_back(NULL); } } return nNode;} // Function to find the height of the treeNode* BuildKaryTree(int* A, int n, int k, int ind){ int height = (int)ceil(log((double)n * (k - 1) + 1) / log((double)k)); return BuildKaryTree(A, n, k, height, ind);} // Function to print postorder traversal of the treevoid postord(Node* root, int k){ if (root == NULL) return; for (int i = 0; i < k; i++) postord(root->child[i], k); cout << root->key << " ";} // Driver program to implement full k-ary treeint main(){ int ind = 0; int k = 3, n = 10; int preorder[] = { 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 }; Node* root = BuildKaryTree(preorder, n, k, ind); cout << "Postorder traversal of constructed" " full k-ary tree is: "; postord(root, k); cout << endl; return 0;}
// Java program to build full k-ary tree from// its preorder traversal and to print the// postorder traversal of the tree.import java.util.*; class GFG{ // Structure of a node of an n-ary treestatic class Node{ int key; Vector<Node> child;}; // Utility function to create a new tree// node with k childrenstatic Node newNode(int value){ Node nNode = new Node(); nNode.key = value; nNode.child= new Vector<Node>(); return nNode;} static int ind; // Function to build full k-ary treestatic Node BuildKaryTree(int A[], int n, int k, int h){ // For null tree if (n <= 0) return null; Node nNode = newNode(A[ind]); if (nNode == null) { System.out.println("Memory error" ); return null; } // For adding k children to a node for (int i = 0; i < k; i++) { // Check if ind is in range of array // Check if height of the tree is greater than 1 if (ind < n - 1 && h > 1) { ind++; // Recursively add each child nNode.child.add(BuildKaryTree(A, n, k, h - 1)); } else { nNode.child.add(null); } } return nNode;} // Function to find the height of the treestatic Node BuildKaryTree_1(int[] A, int n, int k, int in){ int height = (int)Math.ceil(Math.log((double)n * (k - 1) + 1) / Math.log((double)k)); ind = in; return BuildKaryTree(A, n, k, height);} // Function to print postorder traversal of the treestatic void postord(Node root, int k){ if (root == null) return; for (int i = 0; i < k; i++) postord(root.child.get(i), k); System.out.print(root.key + " ");} // Driver Codepublic static void main(String args[]){ int ind = 0; int k = 3, n = 10; int preorder[] = { 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 }; Node root = BuildKaryTree_1(preorder, n, k, ind); System.out.println("Postorder traversal of " + "constructed full k-ary tree is: "); postord(root, k); System.out.println();}} // This code is contributed by Arnab Kundu
# Python3 program to build full k-ary tree# from its preorder traversal and to print the# postorder traversal of the tree.from math import ceil, log # Utility function to create a new# tree node with k childrenclass newNode: def __init__(self, value): self.key = value self.child = [] # Function to build full k-ary treedef BuildkaryTree(A, n, k, h, ind): # For None tree if (n <= 0): return None nNode = newNode(A[ind[0]]) if (nNode == None): print("Memory error") return None # For adding k children to a node for i in range(k): # Check if ind is in range of array # Check if height of the tree is # greater than 1 if (ind[0] < n - 1 and h > 1): ind[0] += 1 # Recursively add each child nNode.child.append(BuildkaryTree(A, n, k, h - 1, ind)) else: nNode.child.append(None) return nNode # Function to find the height of the treedef BuildKaryTree(A, n, k, ind): height = int(ceil(log(float(n) * (k - 1) + 1) / log(float(k)))) return BuildkaryTree(A, n, k, height, ind) # Function to print postorder traversal# of the treedef postord(root, k): if (root == None): return for i in range(k): postord(root.child[i], k) print(root.key, end = " ") # Driver Codeif __name__ == '__main__': ind = [0] k = 3 n = 10 preorder = [ 1, 2, 5, 6, 7, 3, 8, 9, 10, 4] root = BuildKaryTree(preorder, n, k, ind) print("Postorder traversal of constructed", "full k-ary tree is: ") postord(root, k) # This code is contributed by pranchalK
// C# program to build full k-ary tree from// its preorder traversal and to print the// postorder traversal of the tree.using System;using System.Collections.Generic; class GFG{ // Structure of a node of an n-ary treeclass Node{ public int key; public List<Node> child;}; // Utility function to create a new tree// node with k childrenstatic Node newNode(int value){ Node nNode = new Node(); nNode.key = value; nNode.child= new List<Node>(); return nNode;} static int ind; // Function to build full k-ary treestatic Node BuildKaryTree(int []A, int n, int k, int h){ // For null tree if (n <= 0) return null; Node nNode = newNode(A[ind]); if (nNode == null) { Console.WriteLine("Memory error" ); return null; } // For adding k children to a node for (int i = 0; i < k; i++) { // Check if ind is in range of array // Check if height of the tree is greater than 1 if (ind < n - 1 && h > 1) { ind++; // Recursively add each child nNode.child.Add(BuildKaryTree(A, n, k, h - 1)); } else { nNode.child.Add(null); } } return nNode;} // Function to find the height of the treestatic Node BuildKaryTree_1(int[] A, int n, int k, int iN){ int height = (int)Math.Ceiling(Math.Log((double)n * (k - 1) + 1) / Math.Log((double)k)); ind = iN; return BuildKaryTree(A, n, k, height);} // Function to print postorder traversal of the treestatic void postord(Node root, int k){ if (root == null) return; for (int i = 0; i < k; i++) postord(root.child[i], k); Console.Write(root.key + " ");} // Driver Codepublic static void Main(String []args){ int ind = 0; int k = 3, n = 10; int []preorder = { 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 }; Node root = BuildKaryTree_1(preorder, n, k, ind); Console.WriteLine("Postorder traversal of " + "constructed full k-ary tree is: "); postord(root, k); Console.WriteLine();}} // This code is contributed by PrinciRaj1992
<script> // Javascript program to build full k-ary tree from // its preorder traversal and to print the // postorder traversal of the tree. class Node { constructor(key) { this.child = []; this.key = key; } } // Utility function to create a new tree // node with k children function newNode(value) { let nNode = new Node(value); return nNode; } let ind; // Function to build full k-ary tree function BuildKaryTree(A, n, k, h) { // For null tree if (n <= 0) return null; let nNode = newNode(A[ind]); if (nNode == null) { document.write("Memory error" ); return null; } // For adding k children to a node for (let i = 0; i < k; i++) { // Check if ind is in range of array // Check if height of the tree is greater than 1 if (ind < n - 1 && h > 1) { ind++; // Recursively add each child nNode.child.push(BuildKaryTree(A, n, k, h - 1)); } else { nNode.child.push(null); } } return nNode; } // Function to find the height of the tree function BuildKaryTree_1(A, n, k, In) { let height = Math.ceil(Math.log(n * (k - 1) + 1) / Math.log(k)); ind = In; return BuildKaryTree(A, n, k, height); } // Function to print postorder traversal of the tree function postord(root, k) { if (root == null) return; for (let i = 0; i < k; i++) postord(root.child[i], k); document.write(root.key + " "); } ind = 0; let k = 3, n = 10; let preorder = [ 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 ]; let root = BuildKaryTree_1(preorder, n, k, ind); document.write("Postorder traversal of " + "constructed full k-ary" + "</br>" + "tree is: "); postord(root, k); document.write("</br>"); </script>
Output:
Postorder traversal of constructed full k-ary
tree is: 5 6 7 2 8 9 10 3 4 1
This article is contributed by Prakriti Gupta. 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.
PranchalKatiyar
andrew1234
nidhi_biet
princiraj1992
divyesh072019
simmytarika5
n-ary-tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Binary Tree | Set 3 (Types of Binary Tree)
Binary Tree | Set 2 (Properties)
Decision Tree
A program to check if a binary tree is BST or not
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Introduction to Tree Data Structure
Lowest Common Ancestor in a Binary Tree | Set 1
Expression Tree
Binary Tree (Array implementation)
BFS vs DFS for Binary Tree
|
[
{
"code": null,
"e": 25156,
"s": 25128,
"text": "\n01 Feb, 2022"
},
{
"code": null,
"e": 25369,
"s": 25156,
"text": "Given an array that contains the preorder traversal of the full k-ary tree, construct the full k-ary tree and print its postorder traversal. A full k-ary tree is a tree where each node has either 0 or k children."
},
{
"code": null,
"e": 25380,
"s": 25369,
"text": "Examples: "
},
{
"code": null,
"e": 26085,
"s": 25380,
"text": "Input : preorder[] = {1, 2, 5, 6, 7, \n 3, 8, 9, 10, 4}\n k = 3\nOutput : Postorder traversal of constructed \n full k-ary tree is: 5 6 7 2 8 9 10 \n 3 4 1 \n Tree formed is: 1\n / | \\\n 2 3 4\n /|\\ /|\\\n 5 6 7 8 9 10\n\nInput : preorder[] = {1, 2, 5, 6, 7, 3, 4}\n k = 3 \nOutput : Postorder traversal of constructed \n full k-ary tree is: 5 6 7 2 4 3 1\n Tree formed is: 1\n / | \\\n 2 3 4\n /|\\ \n 5 6 7 "
},
{
"code": null,
"e": 26203,
"s": 26085,
"text": "We have discussed this problem for Binary tree in below post. Construct a special tree from given preorder traversal "
},
{
"code": null,
"e": 26557,
"s": 26203,
"text": "In this post, solution for a k-ary tree is discussed.In Preorder traversal, first root node is processed then followed by the left subtree and right subtree. Because of this, to construct a full k-ary tree, we just need to keep on creating the nodes without bothering about the previous constructed nodes. We can use this to build the tree recursively. "
},
{
"code": null,
"e": 26697,
"s": 26557,
"text": "Following are the steps to solve the problem: 1. Find the height of the tree. 2. Traverse the preorder array and recursively add each node "
},
{
"code": null,
"e": 26701,
"s": 26697,
"text": "C++"
},
{
"code": null,
"e": 26706,
"s": 26701,
"text": "Java"
},
{
"code": null,
"e": 26714,
"s": 26706,
"text": "Python3"
},
{
"code": null,
"e": 26717,
"s": 26714,
"text": "C#"
},
{
"code": null,
"e": 26728,
"s": 26717,
"text": "Javascript"
},
{
"code": "// C++ program to build full k-ary tree from// its preorder traversal and to print the// postorder traversal of the tree.#include <bits/stdc++.h>using namespace std; // Structure of a node of an n-ary treestruct Node { int key; vector<Node*> child;}; // Utility function to create a new tree// node with k childrenNode* newNode(int value){ Node* nNode = new Node; nNode->key = value; return nNode;} // Function to build full k-ary treeNode* BuildKaryTree(int A[], int n, int k, int h, int& ind){ // For null tree if (n <= 0) return NULL; Node* nNode = newNode(A[ind]); if (nNode == NULL) { cout << \"Memory error\" << endl; return NULL; } // For adding k children to a node for (int i = 0; i < k; i++) { // Check if ind is in range of array // Check if height of the tree is greater than 1 if (ind < n - 1 && h > 1) { ind++; // Recursively add each child nNode->child.push_back(BuildKaryTree(A, n, k, h - 1, ind)); } else { nNode->child.push_back(NULL); } } return nNode;} // Function to find the height of the treeNode* BuildKaryTree(int* A, int n, int k, int ind){ int height = (int)ceil(log((double)n * (k - 1) + 1) / log((double)k)); return BuildKaryTree(A, n, k, height, ind);} // Function to print postorder traversal of the treevoid postord(Node* root, int k){ if (root == NULL) return; for (int i = 0; i < k; i++) postord(root->child[i], k); cout << root->key << \" \";} // Driver program to implement full k-ary treeint main(){ int ind = 0; int k = 3, n = 10; int preorder[] = { 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 }; Node* root = BuildKaryTree(preorder, n, k, ind); cout << \"Postorder traversal of constructed\" \" full k-ary tree is: \"; postord(root, k); cout << endl; return 0;}",
"e": 28634,
"s": 26728,
"text": null
},
{
"code": "// Java program to build full k-ary tree from// its preorder traversal and to print the// postorder traversal of the tree.import java.util.*; class GFG{ // Structure of a node of an n-ary treestatic class Node{ int key; Vector<Node> child;}; // Utility function to create a new tree// node with k childrenstatic Node newNode(int value){ Node nNode = new Node(); nNode.key = value; nNode.child= new Vector<Node>(); return nNode;} static int ind; // Function to build full k-ary treestatic Node BuildKaryTree(int A[], int n, int k, int h){ // For null tree if (n <= 0) return null; Node nNode = newNode(A[ind]); if (nNode == null) { System.out.println(\"Memory error\" ); return null; } // For adding k children to a node for (int i = 0; i < k; i++) { // Check if ind is in range of array // Check if height of the tree is greater than 1 if (ind < n - 1 && h > 1) { ind++; // Recursively add each child nNode.child.add(BuildKaryTree(A, n, k, h - 1)); } else { nNode.child.add(null); } } return nNode;} // Function to find the height of the treestatic Node BuildKaryTree_1(int[] A, int n, int k, int in){ int height = (int)Math.ceil(Math.log((double)n * (k - 1) + 1) / Math.log((double)k)); ind = in; return BuildKaryTree(A, n, k, height);} // Function to print postorder traversal of the treestatic void postord(Node root, int k){ if (root == null) return; for (int i = 0; i < k; i++) postord(root.child.get(i), k); System.out.print(root.key + \" \");} // Driver Codepublic static void main(String args[]){ int ind = 0; int k = 3, n = 10; int preorder[] = { 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 }; Node root = BuildKaryTree_1(preorder, n, k, ind); System.out.println(\"Postorder traversal of \" + \"constructed full k-ary tree is: \"); postord(root, k); System.out.println();}} // This code is contributed by Arnab Kundu",
"e": 30745,
"s": 28634,
"text": null
},
{
"code": "# Python3 program to build full k-ary tree# from its preorder traversal and to print the# postorder traversal of the tree.from math import ceil, log # Utility function to create a new# tree node with k childrenclass newNode: def __init__(self, value): self.key = value self.child = [] # Function to build full k-ary treedef BuildkaryTree(A, n, k, h, ind): # For None tree if (n <= 0): return None nNode = newNode(A[ind[0]]) if (nNode == None): print(\"Memory error\") return None # For adding k children to a node for i in range(k): # Check if ind is in range of array # Check if height of the tree is # greater than 1 if (ind[0] < n - 1 and h > 1): ind[0] += 1 # Recursively add each child nNode.child.append(BuildkaryTree(A, n, k, h - 1, ind)) else: nNode.child.append(None) return nNode # Function to find the height of the treedef BuildKaryTree(A, n, k, ind): height = int(ceil(log(float(n) * (k - 1) + 1) / log(float(k)))) return BuildkaryTree(A, n, k, height, ind) # Function to print postorder traversal# of the treedef postord(root, k): if (root == None): return for i in range(k): postord(root.child[i], k) print(root.key, end = \" \") # Driver Codeif __name__ == '__main__': ind = [0] k = 3 n = 10 preorder = [ 1, 2, 5, 6, 7, 3, 8, 9, 10, 4] root = BuildKaryTree(preorder, n, k, ind) print(\"Postorder traversal of constructed\", \"full k-ary tree is: \") postord(root, k) # This code is contributed by pranchalK",
"e": 32465,
"s": 30745,
"text": null
},
{
"code": "// C# program to build full k-ary tree from// its preorder traversal and to print the// postorder traversal of the tree.using System;using System.Collections.Generic; class GFG{ // Structure of a node of an n-ary treeclass Node{ public int key; public List<Node> child;}; // Utility function to create a new tree// node with k childrenstatic Node newNode(int value){ Node nNode = new Node(); nNode.key = value; nNode.child= new List<Node>(); return nNode;} static int ind; // Function to build full k-ary treestatic Node BuildKaryTree(int []A, int n, int k, int h){ // For null tree if (n <= 0) return null; Node nNode = newNode(A[ind]); if (nNode == null) { Console.WriteLine(\"Memory error\" ); return null; } // For adding k children to a node for (int i = 0; i < k; i++) { // Check if ind is in range of array // Check if height of the tree is greater than 1 if (ind < n - 1 && h > 1) { ind++; // Recursively add each child nNode.child.Add(BuildKaryTree(A, n, k, h - 1)); } else { nNode.child.Add(null); } } return nNode;} // Function to find the height of the treestatic Node BuildKaryTree_1(int[] A, int n, int k, int iN){ int height = (int)Math.Ceiling(Math.Log((double)n * (k - 1) + 1) / Math.Log((double)k)); ind = iN; return BuildKaryTree(A, n, k, height);} // Function to print postorder traversal of the treestatic void postord(Node root, int k){ if (root == null) return; for (int i = 0; i < k; i++) postord(root.child[i], k); Console.Write(root.key + \" \");} // Driver Codepublic static void Main(String []args){ int ind = 0; int k = 3, n = 10; int []preorder = { 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 }; Node root = BuildKaryTree_1(preorder, n, k, ind); Console.WriteLine(\"Postorder traversal of \" + \"constructed full k-ary tree is: \"); postord(root, k); Console.WriteLine();}} // This code is contributed by PrinciRaj1992",
"e": 34601,
"s": 32465,
"text": null
},
{
"code": "<script> // Javascript program to build full k-ary tree from // its preorder traversal and to print the // postorder traversal of the tree. class Node { constructor(key) { this.child = []; this.key = key; } } // Utility function to create a new tree // node with k children function newNode(value) { let nNode = new Node(value); return nNode; } let ind; // Function to build full k-ary tree function BuildKaryTree(A, n, k, h) { // For null tree if (n <= 0) return null; let nNode = newNode(A[ind]); if (nNode == null) { document.write(\"Memory error\" ); return null; } // For adding k children to a node for (let i = 0; i < k; i++) { // Check if ind is in range of array // Check if height of the tree is greater than 1 if (ind < n - 1 && h > 1) { ind++; // Recursively add each child nNode.child.push(BuildKaryTree(A, n, k, h - 1)); } else { nNode.child.push(null); } } return nNode; } // Function to find the height of the tree function BuildKaryTree_1(A, n, k, In) { let height = Math.ceil(Math.log(n * (k - 1) + 1) / Math.log(k)); ind = In; return BuildKaryTree(A, n, k, height); } // Function to print postorder traversal of the tree function postord(root, k) { if (root == null) return; for (let i = 0; i < k; i++) postord(root.child[i], k); document.write(root.key + \" \"); } ind = 0; let k = 3, n = 10; let preorder = [ 1, 2, 5, 6, 7, 3, 8, 9, 10, 4 ]; let root = BuildKaryTree_1(preorder, n, k, ind); document.write(\"Postorder traversal of \" + \"constructed full k-ary\" + \"</br>\" + \"tree is: \"); postord(root, k); document.write(\"</br>\"); </script>",
"e": 36664,
"s": 34601,
"text": null
},
{
"code": null,
"e": 36674,
"s": 36664,
"text": "Output: "
},
{
"code": null,
"e": 36751,
"s": 36674,
"text": "Postorder traversal of constructed full k-ary\ntree is: 5 6 7 2 8 9 10 3 4 1 "
},
{
"code": null,
"e": 37174,
"s": 36751,
"text": "This article is contributed by Prakriti Gupta. 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": 37190,
"s": 37174,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 37201,
"s": 37190,
"text": "andrew1234"
},
{
"code": null,
"e": 37212,
"s": 37201,
"text": "nidhi_biet"
},
{
"code": null,
"e": 37226,
"s": 37212,
"text": "princiraj1992"
},
{
"code": null,
"e": 37240,
"s": 37226,
"text": "divyesh072019"
},
{
"code": null,
"e": 37253,
"s": 37240,
"text": "simmytarika5"
},
{
"code": null,
"e": 37264,
"s": 37253,
"text": "n-ary-tree"
},
{
"code": null,
"e": 37269,
"s": 37264,
"text": "Tree"
},
{
"code": null,
"e": 37274,
"s": 37269,
"text": "Tree"
},
{
"code": null,
"e": 37372,
"s": 37274,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37381,
"s": 37372,
"text": "Comments"
},
{
"code": null,
"e": 37394,
"s": 37381,
"text": "Old Comments"
},
{
"code": null,
"e": 37437,
"s": 37394,
"text": "Binary Tree | Set 3 (Types of Binary Tree)"
},
{
"code": null,
"e": 37470,
"s": 37437,
"text": "Binary Tree | Set 2 (Properties)"
},
{
"code": null,
"e": 37484,
"s": 37470,
"text": "Decision Tree"
},
{
"code": null,
"e": 37534,
"s": 37484,
"text": "A program to check if a binary tree is BST or not"
},
{
"code": null,
"e": 37617,
"s": 37534,
"text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree"
},
{
"code": null,
"e": 37653,
"s": 37617,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 37701,
"s": 37653,
"text": "Lowest Common Ancestor in a Binary Tree | Set 1"
},
{
"code": null,
"e": 37717,
"s": 37701,
"text": "Expression Tree"
},
{
"code": null,
"e": 37752,
"s": 37717,
"text": "Binary Tree (Array implementation)"
}
] |
Amazon Interview Experience for SDE-2 | 4 Years Experienced - GeeksforGeeks
|
06 May, 2021
Virtual Interviews
I got a call from an Amazon recruiter via LinkedIn. She sent me the coding test link which I had to complete within a week. Once I completed the test, I got a call to schedule the interviews. All interviews were held on Amazon Chime as per schedule. Overall process took 1 month to complete the test and interviews.Following are the questions that were asked:
HackerRank Test (90 Minutes online test)1. Shopping Options: We are given the costs of a list of pants, shirts, shoes, skirts. We have a certain amount of cash with us, we need to determine the total number of possible combinations which we can buy given that we must buy one and only one of each type.
Eg: pants=[3, 5, 7], shirts = [4, 7, 8],
skirts = [5, 8], shoes = [3], budget = 25
So in the above e.g., apart from the combination [7, 8, 8, 3], all others are possible.
Hint: Since we have to buy all, we can combine the first two lists and the last two lists, so we would have cost lists like pants_shirts = [...] and
skirts_shoes = [...], now we can just iterate over one list and binary search the remaining amount over the other list and add accordingly.
2. Storage Optimization: Amazon is experimenting with a flexible storage system for their warehouses. The storage unit consists of a shelving system that is one meter deep with removable vertical and horizontal separators. When all separators are installed each storage space is one cubic meter(1*1*1). Determine the volume of the largest space when a series of horizontal and vertical separators are removed.
n = 6
m = 6;
h = [4]
v = [2]
Round 1(Problem Solving): 50 Minutes
First round was taken by a Software Engineer Manager who was residing in US. He introduced himself and then asked about some question related to Amazon leadership Principle.Then asked one problem solving question. Given a list of words return a Map of words which can be formed by using other words which exist in the same list. He asked only one problem solving question. Most focus was on leadership Principle.
input = [“happy”, “rise”, “for”, “set”, “sunrise”, “su”, “nset”, “sunset”, “mind”, “happymind”, “n”, “rise”, “happysunrise”]
output = { “happymind” : [[“happy”, “mind]], “sunrise” : [[“su”, “n”, “rise”], [“sun”, “rise”]], “sunset” : [[“sun”, “set”], [“su”, “n”, “set]], “happysunrise” : [[“happy”, “sunrise”], [“happy”, “sun”, “rise”], [“happy”, “su”, “n”, “rise”]]}
Round 2(Problem Solving): 50 Minutes
Second round was taken by a SDE3 guy who was also in US. He introduced himself and then asked some questions related to Amazon leadership Principle.
He also asked me only one Problem Solving question.
Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i.
For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6].
I solved it by multiplying the complete array then divide each index item to the complete sum.
Then he asked me not to use division. Was able to do in O(n) time complexity
https://www.geeksforgeeks.org/a-product-array-puzzle/
Round 3(System Design): 1 hr 10 minutes
Third round was a system design round which is taken by Senior engineer manager.
He introduced himself and the team he was hiring for. He asked some question related Amazon leaderShip principles.
He asked me to design a Distributed Scheduler which should work for all kinds of clients (Human, Machines {APIs}). Main functionality he asked me to implement was to schedule a job and remind the client about the job at set time.
Mostly High level design,
More questions on scalability, availability, fault tolerance, and resilience.
Ensure all jobs will work.
How system will work in peak time.
What should be the time frame in which user will notify?
Round 4(Bar-Raiser): 1 hr 25 minutes
Fourth round was the bar raiser round. In this round 2 interviewers were there. One of them was Senior Software Dev Manager and another was Technical Program Manager. (One of them was shadowing)
Started with the introduction.
He asked some question related Amazon leaderShip principles.
Design an Online Book Store.
Expectations :
Function Requirements (Explanation)Non – Function Requirements (Explanation)Domain ObjectsHigh Level Components (Complete Services, Caches, Search, Message Broker, Data Base, Service Interactions)Services Dependency with responsibilityData FlowsAPIsEntity RelationsDB SchemaScalabilityDistribution and management
Function Requirements (Explanation)
Non – Function Requirements (Explanation)
Domain Objects
High Level Components (Complete Services, Caches, Search, Message Broker, Data Base, Service Interactions)
Services Dependency with responsibility
Data Flows
APIs
Entity Relations
DB Schema
Scalability
Distribution and management
He asked me some more Amazon Leadership principle questions with STAR(Situation, Task, Action, Result) process.
Note:
In every round amazon leadership principle questions were asked. So don’t forget to prepare for them too.HR called before every interview and told about how this round goes and principles on which focus will be the most.
Amazon
Marketing
Experienced
Interview Experiences
Amazon
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Infosys Interview Experience for Java Backend Developer (3-5 Years Experienced)
Amazon Interview Experience for System Development Engineer (Exp - 6 months)
Paypal Interview Experience for SSE
Walmart Interview Experience for SDE-III
Amazon Interview Questions
Microsoft Interview Experience for Internship (Via Engage)
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience for SDE-1 (On-Campus)
Infosys Interview Experience for DSE - System Engineer | On-Campus 2022
|
[
{
"code": null,
"e": 25213,
"s": 25185,
"text": "\n06 May, 2021"
},
{
"code": null,
"e": 25232,
"s": 25213,
"text": "Virtual Interviews"
},
{
"code": null,
"e": 25592,
"s": 25232,
"text": "I got a call from an Amazon recruiter via LinkedIn. She sent me the coding test link which I had to complete within a week. Once I completed the test, I got a call to schedule the interviews. All interviews were held on Amazon Chime as per schedule. Overall process took 1 month to complete the test and interviews.Following are the questions that were asked:"
},
{
"code": null,
"e": 25895,
"s": 25592,
"text": "HackerRank Test (90 Minutes online test)1. Shopping Options: We are given the costs of a list of pants, shirts, shoes, skirts. We have a certain amount of cash with us, we need to determine the total number of possible combinations which we can buy given that we must buy one and only one of each type."
},
{
"code": null,
"e": 25978,
"s": 25895,
"text": "Eg: pants=[3, 5, 7], shirts = [4, 7, 8],\nskirts = [5, 8], shoes = [3], budget = 25"
},
{
"code": null,
"e": 26066,
"s": 25978,
"text": "So in the above e.g., apart from the combination [7, 8, 8, 3], all others are possible."
},
{
"code": null,
"e": 26215,
"s": 26066,
"text": "Hint: Since we have to buy all, we can combine the first two lists and the last two lists, so we would have cost lists like pants_shirts = [...] and"
},
{
"code": null,
"e": 26355,
"s": 26215,
"text": "skirts_shoes = [...], now we can just iterate over one list and binary search the remaining amount over the other list and add accordingly."
},
{
"code": null,
"e": 26767,
"s": 26355,
"text": "2. Storage Optimization: Amazon is experimenting with a flexible storage system for their warehouses. The storage unit consists of a shelving system that is one meter deep with removable vertical and horizontal separators. When all separators are installed each storage space is one cubic meter(1*1*1). Determine the volume of the largest space when a series of horizontal and vertical separators are removed. "
},
{
"code": null,
"e": 26796,
"s": 26767,
"text": "n = 6\nm = 6;\nh = [4]\nv = [2]"
},
{
"code": null,
"e": 26833,
"s": 26796,
"text": "Round 1(Problem Solving): 50 Minutes"
},
{
"code": null,
"e": 27246,
"s": 26833,
"text": "First round was taken by a Software Engineer Manager who was residing in US. He introduced himself and then asked about some question related to Amazon leadership Principle.Then asked one problem solving question. Given a list of words return a Map of words which can be formed by using other words which exist in the same list. He asked only one problem solving question. Most focus was on leadership Principle."
},
{
"code": null,
"e": 27371,
"s": 27246,
"text": "input = [“happy”, “rise”, “for”, “set”, “sunrise”, “su”, “nset”, “sunset”, “mind”, “happymind”, “n”, “rise”, “happysunrise”]"
},
{
"code": null,
"e": 27630,
"s": 27371,
"text": "output = { “happymind” : [[“happy”, “mind]], “sunrise” : [[“su”, “n”, “rise”], [“sun”, “rise”]], “sunset” : [[“sun”, “set”], [“su”, “n”, “set]], “happysunrise” : [[“happy”, “sunrise”], [“happy”, “sun”, “rise”], [“happy”, “su”, “n”, “rise”]]}"
},
{
"code": null,
"e": 27667,
"s": 27630,
"text": "Round 2(Problem Solving): 50 Minutes"
},
{
"code": null,
"e": 27816,
"s": 27667,
"text": "Second round was taken by a SDE3 guy who was also in US. He introduced himself and then asked some questions related to Amazon leadership Principle."
},
{
"code": null,
"e": 27868,
"s": 27816,
"text": "He also asked me only one Problem Solving question."
},
{
"code": null,
"e": 28044,
"s": 27868,
"text": "Given an array of integers, return a new array such that each element at index i of the new array is the product of all the numbers in the original array except the one at i. "
},
{
"code": null,
"e": 28211,
"s": 28044,
"text": "For example, if our input was [1, 2, 3, 4, 5], the expected output would be [120, 60, 40, 30, 24]. If our input was [3, 2, 1], the expected output would be [2, 3, 6]."
},
{
"code": null,
"e": 28306,
"s": 28211,
"text": "I solved it by multiplying the complete array then divide each index item to the complete sum."
},
{
"code": null,
"e": 28383,
"s": 28306,
"text": "Then he asked me not to use division. Was able to do in O(n) time complexity"
},
{
"code": null,
"e": 28437,
"s": 28383,
"text": "https://www.geeksforgeeks.org/a-product-array-puzzle/"
},
{
"code": null,
"e": 28477,
"s": 28437,
"text": "Round 3(System Design): 1 hr 10 minutes"
},
{
"code": null,
"e": 28558,
"s": 28477,
"text": "Third round was a system design round which is taken by Senior engineer manager."
},
{
"code": null,
"e": 28676,
"s": 28558,
"text": "He introduced himself and the team he was hiring for. He asked some question related Amazon leaderShip principles. "
},
{
"code": null,
"e": 28907,
"s": 28676,
"text": "He asked me to design a Distributed Scheduler which should work for all kinds of clients (Human, Machines {APIs}). Main functionality he asked me to implement was to schedule a job and remind the client about the job at set time. "
},
{
"code": null,
"e": 28934,
"s": 28907,
"text": "Mostly High level design, "
},
{
"code": null,
"e": 29012,
"s": 28934,
"text": "More questions on scalability, availability, fault tolerance, and resilience."
},
{
"code": null,
"e": 29040,
"s": 29012,
"text": "Ensure all jobs will work. "
},
{
"code": null,
"e": 29075,
"s": 29040,
"text": "How system will work in peak time."
},
{
"code": null,
"e": 29133,
"s": 29075,
"text": "What should be the time frame in which user will notify? "
},
{
"code": null,
"e": 29170,
"s": 29133,
"text": "Round 4(Bar-Raiser): 1 hr 25 minutes"
},
{
"code": null,
"e": 29365,
"s": 29170,
"text": "Fourth round was the bar raiser round. In this round 2 interviewers were there. One of them was Senior Software Dev Manager and another was Technical Program Manager. (One of them was shadowing)"
},
{
"code": null,
"e": 29396,
"s": 29365,
"text": "Started with the introduction."
},
{
"code": null,
"e": 29457,
"s": 29396,
"text": "He asked some question related Amazon leaderShip principles."
},
{
"code": null,
"e": 29486,
"s": 29457,
"text": "Design an Online Book Store."
},
{
"code": null,
"e": 29501,
"s": 29486,
"text": "Expectations :"
},
{
"code": null,
"e": 29815,
"s": 29501,
"text": "Function Requirements (Explanation)Non – Function Requirements (Explanation)Domain ObjectsHigh Level Components (Complete Services, Caches, Search, Message Broker, Data Base, Service Interactions)Services Dependency with responsibilityData FlowsAPIsEntity RelationsDB SchemaScalabilityDistribution and management "
},
{
"code": null,
"e": 29851,
"s": 29815,
"text": "Function Requirements (Explanation)"
},
{
"code": null,
"e": 29893,
"s": 29851,
"text": "Non – Function Requirements (Explanation)"
},
{
"code": null,
"e": 29908,
"s": 29893,
"text": "Domain Objects"
},
{
"code": null,
"e": 30015,
"s": 29908,
"text": "High Level Components (Complete Services, Caches, Search, Message Broker, Data Base, Service Interactions)"
},
{
"code": null,
"e": 30055,
"s": 30015,
"text": "Services Dependency with responsibility"
},
{
"code": null,
"e": 30066,
"s": 30055,
"text": "Data Flows"
},
{
"code": null,
"e": 30071,
"s": 30066,
"text": "APIs"
},
{
"code": null,
"e": 30088,
"s": 30071,
"text": "Entity Relations"
},
{
"code": null,
"e": 30098,
"s": 30088,
"text": "DB Schema"
},
{
"code": null,
"e": 30110,
"s": 30098,
"text": "Scalability"
},
{
"code": null,
"e": 30139,
"s": 30110,
"text": "Distribution and management "
},
{
"code": null,
"e": 30251,
"s": 30139,
"text": "He asked me some more Amazon Leadership principle questions with STAR(Situation, Task, Action, Result) process."
},
{
"code": null,
"e": 30257,
"s": 30251,
"text": "Note:"
},
{
"code": null,
"e": 30478,
"s": 30257,
"text": "In every round amazon leadership principle questions were asked. So don’t forget to prepare for them too.HR called before every interview and told about how this round goes and principles on which focus will be the most."
},
{
"code": null,
"e": 30485,
"s": 30478,
"text": "Amazon"
},
{
"code": null,
"e": 30495,
"s": 30485,
"text": "Marketing"
},
{
"code": null,
"e": 30507,
"s": 30495,
"text": "Experienced"
},
{
"code": null,
"e": 30529,
"s": 30507,
"text": "Interview Experiences"
},
{
"code": null,
"e": 30536,
"s": 30529,
"text": "Amazon"
},
{
"code": null,
"e": 30634,
"s": 30536,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30643,
"s": 30634,
"text": "Comments"
},
{
"code": null,
"e": 30656,
"s": 30643,
"text": "Old Comments"
},
{
"code": null,
"e": 30721,
"s": 30656,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 30801,
"s": 30721,
"text": "Infosys Interview Experience for Java Backend Developer (3-5 Years Experienced)"
},
{
"code": null,
"e": 30878,
"s": 30801,
"text": "Amazon Interview Experience for System Development Engineer (Exp - 6 months)"
},
{
"code": null,
"e": 30914,
"s": 30878,
"text": "Paypal Interview Experience for SSE"
},
{
"code": null,
"e": 30955,
"s": 30914,
"text": "Walmart Interview Experience for SDE-III"
},
{
"code": null,
"e": 30982,
"s": 30955,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 31041,
"s": 30982,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 31101,
"s": 31041,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 31151,
"s": 31101,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
}
] |
Java Program for Depth First Search or DFS for a Graph
|
22 Jun, 2022
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array.
For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don\’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Depth First Traversal of the following graph is 2, 0, 1, 3.
See this post for all applications of Depth First Traversal.Following are implementations of simple Depth First Traversal. The C++ implementation uses adjacency list representation of graphs. STL\’s list container is used to store lists of adjacent nodes.
Java
// Java program to print DFS traversal from a given graphimport java.io.*;import java.util.*; // 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[]; // 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); // Add w to v\'s list. } // A function used by DFS void DFSUtil(int v,boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; System.out.print(v+" "); // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n,visited); } } // The function to do DFS traversal. It uses recursive DFSUtil() void DFS() { // Mark all the vertices as not visited(set as // false by default in java) boolean visited[] = new boolean[V]; // Call the recursive helper function to print DFS traversal // starting from all vertices one by one for (int i=0; i<V; ++i) if (visited[i] == false) DFSUtil(i, visited); } public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println("Following is Depth First Traversal"); g.DFS(); }}// This code is contributed by Aakash Hasija
Time Complexity : O(V+E) where V is the number of vertices in graph and E is the number of edgesAuxiliary Space: O(V)Please refer complete article on Depth First Search or DFS for a Graph for more details!
sweetyty
ishankhandelwals
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate Over the Characters of a String in Java
How to Convert Char to String in Java?
How to Insert an element at a specific position in an Array in Java
Java Program to Write an Array of Strings to the Output Console
SHA-1 Hash
How to Create a Package in Java?
Java Program to Write into a File
Java Program to Convert String to String Array
Java Program to Find Sum of Array Elements
How to Get Elements By Index from HashSet in Java?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 300,
"s": 28,
"text": "Depth First Traversal (or Search) for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array."
},
{
"code": null,
"e": 648,
"s": 300,
"text": "For example, in the following graph, we start traversal from vertex 2. When we come to vertex 0, we look for all adjacent vertices of it. 2 is also an adjacent vertex of 0. If we don\\’t mark visited vertices, then 2 will be processed again and it will become a non-terminating process. A Depth First Traversal of the following graph is 2, 0, 1, 3."
},
{
"code": null,
"e": 904,
"s": 648,
"text": "See this post for all applications of Depth First Traversal.Following are implementations of simple Depth First Traversal. The C++ implementation uses adjacency list representation of graphs. STL\\’s list container is used to store lists of adjacent nodes."
},
{
"code": null,
"e": 909,
"s": 904,
"text": "Java"
},
{
"code": "// Java program to print DFS traversal from a given graphimport java.io.*;import java.util.*; // 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[]; // 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); // Add w to v\\'s list. } // A function used by DFS void DFSUtil(int v,boolean visited[]) { // Mark the current node as visited and print it visited[v] = true; System.out.print(v+\" \"); // Recur for all the vertices adjacent to this vertex Iterator<Integer> i = adj[v].listIterator(); while (i.hasNext()) { int n = i.next(); if (!visited[n]) DFSUtil(n,visited); } } // The function to do DFS traversal. It uses recursive DFSUtil() void DFS() { // Mark all the vertices as not visited(set as // false by default in java) boolean visited[] = new boolean[V]; // Call the recursive helper function to print DFS traversal // starting from all vertices one by one for (int i=0; i<V; ++i) if (visited[i] == false) DFSUtil(i, visited); } public static void main(String args[]) { Graph g = new Graph(4); g.addEdge(0, 1); g.addEdge(0, 2); g.addEdge(1, 2); g.addEdge(2, 0); g.addEdge(2, 3); g.addEdge(3, 3); System.out.println(\"Following is Depth First Traversal\"); g.DFS(); }}// This code is contributed by Aakash Hasija",
"e": 2771,
"s": 909,
"text": null
},
{
"code": null,
"e": 2977,
"s": 2771,
"text": "Time Complexity : O(V+E) where V is the number of vertices in graph and E is the number of edgesAuxiliary Space: O(V)Please refer complete article on Depth First Search or DFS for a Graph for more details!"
},
{
"code": null,
"e": 2986,
"s": 2977,
"text": "sweetyty"
},
{
"code": null,
"e": 3003,
"s": 2986,
"text": "ishankhandelwals"
},
{
"code": null,
"e": 3017,
"s": 3003,
"text": "Java Programs"
},
{
"code": null,
"e": 3115,
"s": 3017,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3163,
"s": 3115,
"text": "Iterate Over the Characters of a String in Java"
},
{
"code": null,
"e": 3202,
"s": 3163,
"text": "How to Convert Char to String in Java?"
},
{
"code": null,
"e": 3270,
"s": 3202,
"text": "How to Insert an element at a specific position in an Array in Java"
},
{
"code": null,
"e": 3334,
"s": 3270,
"text": "Java Program to Write an Array of Strings to the Output Console"
},
{
"code": null,
"e": 3345,
"s": 3334,
"text": "SHA-1 Hash"
},
{
"code": null,
"e": 3378,
"s": 3345,
"text": "How to Create a Package in Java?"
},
{
"code": null,
"e": 3412,
"s": 3378,
"text": "Java Program to Write into a File"
},
{
"code": null,
"e": 3459,
"s": 3412,
"text": "Java Program to Convert String to String Array"
},
{
"code": null,
"e": 3502,
"s": 3459,
"text": "Java Program to Find Sum of Array Elements"
}
] |
Inplace rotate square matrix by 90 degrees | Set 1
|
30 Jun, 2022
Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space.
Examples :
Input:
Matrix:
1 2 3
4 5 6
7 8 9
Output:
3 6 9
2 5 8
1 4 7
The given matrix is rotated by 90 degree
in anti-clockwise direction.
Input:
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Output:
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
The given matrix is rotated by 90 degree
in anti-clockwise direction.
An approach that requires extra space is already discussed here.
Approach: To solve the question without any extra space, rotate the array in form of squares, dividing the matrix into squares or cycles. For example, A 4 X 4 matrix will have 2 cycles. The first cycle is formed by its 1st row, last column, last row and 1st column. The second cycle is formed by 2nd row, second-last column, second-last row and 2nd column. The idea is for each square cycle, swap the elements involved with the corresponding cell in the matrix in anti-clockwise direction i.e. from top to left, left to bottom, bottom to right and from right to top one at a time using nothing but a temporary variable to achieve this.
Demonstration:
First Cycle (Involves Red Elements)
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
Moving first group of four elements (First
elements of 1st row, last row, 1st column
and last column) of first cycle in counter
clockwise.
4 2 3 16
5 6 7 8
9 10 11 12
1 14 15 13
Moving next group of four elements of
first cycle in counter clockwise
4 8 3 16
5 6 7 15
2 10 11 12
1 14 9 13
Moving final group of four elements of
first cycle in counter clockwise
4 8 12 16
3 6 7 15
2 10 11 14
1 5 9 13
Second Cycle (Involves Blue Elements)
4 8 12 16
3 6 7 15
2 10 11 14
1 5 9 13
Fixing second cycle
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Algorithm:
There is N/2 squares or cycles in a matrix of side N. Process a square one at a time. Run a loop to traverse the matrix a cycle at a time, i.e loop from 0 to N/2 – 1, loop counter is iConsider elements in group of 4 in current square, rotate the 4 elements at a time. So the number of such groups in a cycle is N – 2*i.So run a loop in each cycle from x to N – x – 1, loop counter is yThe elements in the current group is (x, y), (y, N-1-x), (N-1-x, N-1-y), (N-1-y, x), now rotate the these 4 elements, i.e (x, y) <- (y, N-1-x), (y, N-1-x)<- (N-1-x, N-1-y), (N-1-x, N-1-y)<- (N-1-y, x), (N-1-y, x)<- (x, y)Print the matrix.
There is N/2 squares or cycles in a matrix of side N. Process a square one at a time. Run a loop to traverse the matrix a cycle at a time, i.e loop from 0 to N/2 – 1, loop counter is i
Consider elements in group of 4 in current square, rotate the 4 elements at a time. So the number of such groups in a cycle is N – 2*i.
So run a loop in each cycle from x to N – x – 1, loop counter is y
The elements in the current group is (x, y), (y, N-1-x), (N-1-x, N-1-y), (N-1-y, x), now rotate the these 4 elements, i.e (x, y) <- (y, N-1-x), (y, N-1-x)<- (N-1-x, N-1-y), (N-1-x, N-1-y)<- (N-1-y, x), (N-1-y, x)<- (x, y)
Print the matrix.
Implementation:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to rotate a matrix// by 90 degrees#include <bits/stdc++.h>#define N 4using namespace std; // An Inplace function to// rotate a N x N matrix// by 90 degrees in// anti-clockwise directionvoid rotateMatrix(int mat[][N]){ // Consider all squares one by one for (int x = 0; x < N / 2; x++) { // Consider elements in group // of 4 in current square for (int y = x; y < N - x - 1; y++) { // Store current cell in // temp variable int temp = mat[x][y]; // Move values from right to top mat[x][y] = mat[y][N - 1 - x]; // Move values from bottom to right mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y]; // Move values from left to bottom mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x]; // Assign temp to left mat[N - 1 - y][x] = temp; } }} // Function to print the matrixvoid displayMatrix(int mat[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout<<mat[i][j]<<" "; } cout<<endl; } cout<<endl;} /* Driver program to test above functions */int main(){ // Test Case 1 int mat[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Test Case 2 /* int mat[N][N] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; */ // Test Case 3 /*int mat[N][N] = { {1, 2}, {4, 5} };*/ // displayMatrix(mat); rotateMatrix(mat); // Print rotated matrix displayMatrix(mat); return 0;}
// Java program to rotate a// matrix by 90 degreesimport java.io.*; class GFG { // An Inplace function to // rotate a N x N matrix // by 90 degrees in // anti-clockwise direction static void rotateMatrix(int N, int mat[][]) { // Consider all squares one by one for (int x = 0; x < N / 2; x++) { // Consider elements in group // of 4 in current square for (int y = x; y < N - x - 1; y++) { // Store current cell in // temp variable int temp = mat[x][y]; // Move values from right to top mat[x][y] = mat[y][N - 1 - x]; // Move values from bottom to right mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y]; // Move values from left to bottom mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x]; // Assign temp to left mat[N - 1 - y][x] = temp; } } } // Function to print the matrix static void displayMatrix(int N, int mat[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(" " + mat[i][j]); System.out.print("\n"); } System.out.print("\n"); } /* Driver program to test above functions */ public static void main(String[] args) { int N = 4; // Test Case 1 int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Test Case 2 /* int mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; */ // Test Case 3 /*int mat[][] = { {1, 2}, {4, 5} };*/ // displayMatrix(mat); rotateMatrix(N, mat); // Print rotated matrix displayMatrix(N, mat); }} // This code is contributed by Prakriti Gupta
# Python3 program to rotate a matrix by 90 degreesN = 4 # An Inplace function to rotate# N x N matrix by 90 degrees in# anti-clockwise direction def rotateMatrix(mat): # Consider all squares one by one for x in range(0, int(N / 2)): # Consider elements in group # of 4 in current square for y in range(x, N-x-1): # store current cell in temp variable temp = mat[x][y] # move values from right to top mat[x][y] = mat[y][N-1-x] # move values from bottom to right mat[y][N-1-x] = mat[N-1-x][N-1-y] # move values from left to bottom mat[N-1-x][N-1-y] = mat[N-1-y][x] # assign temp to left mat[N-1-y][x] = temp # Function to print the matrixdef displayMatrix(mat): for i in range(0, N): for j in range(0, N): print(mat[i][j], end=' ') print("") # Driver Codemat = [[0 for x in range(N)] for y in range(N)] # Test case 1mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] '''# Test case 2mat = [ [1, 2, 3 ], [4, 5, 6 ], [7, 8, 9 ] ] # Test case 3mat = [ [1, 2 ], [4, 5 ] ] ''' rotateMatrix(mat) # Print rotated matrixdisplayMatrix(mat) # This code is contributed by saloni1297
// C# program to rotate a// matrix by 90 degreesusing System; class GFG { // An Inplace function to // rotate a N x N matrix // by 90 degrees in anti- // clockwise direction static void rotateMatrix(int N, int[, ] mat) { // Consider all // squares one by one for (int x = 0; x < N / 2; x++) { // Consider elements // in group of 4 in // current square for (int y = x; y < N - x - 1; y++) { // store current cell // in temp variable int temp = mat[x, y]; // move values from // right to top mat[x, y] = mat[y, N - 1 - x]; // move values from // bottom to right mat[y, N - 1 - x] = mat[N - 1 - x, N - 1 - y]; // move values from // left to bottom mat[N - 1 - x, N - 1 - y] = mat[N - 1 - y, x]; // assign temp to left mat[N - 1 - y, x] = temp; } } } // Function to print the matrix static void displayMatrix(int N, int[, ] mat) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(" " + mat[i, j]); Console.WriteLine(); } Console.WriteLine(); } // Driver Code static public void Main() { int N = 4; // Test Case 1 int[, ] mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Test Case 2 /* int mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; */ // Test Case 3 /*int mat[][] = { {1, 2}, {4, 5} };*/ // displayMatrix(mat); rotateMatrix(N, mat); // Print rotated matrix displayMatrix(N, mat); }} // This code is contributed by ajit
<?php// PHP program to rotate a// matrix by 90 degrees$N = 4; // An Inplace function to// rotate a N x N matrix// by 90 degrees in// anti-clockwise directionfunction rotateMatrix(&$mat){ global $N; // Consider all // squares one by one for ($x = 0; $x < $N / 2; $x++) { // Consider elements // in group of 4 in // current square for ($y = $x; $y < $N - $x - 1; $y++) { // store current cell // in temp variable $temp = $mat[$x][$y]; // move values from // right to top $mat[$x][$y] = $mat[$y][$N - 1 - $x]; // move values from // bottom to right $mat[$y][$N - 1 - $x] = $mat[$N - 1 - $x][$N - 1 - $y]; // move values from // left to bottom $mat[$N - 1 - $x][$N - 1 - $y] = $mat[$N - 1 - $y][$x]; // assign temp to left $mat[$N - 1 - $y][$x] = $temp; } }} // Function to// print the matrixfunction displayMatrix(&$mat){ global $N; for ($i = 0; $i < $N; $i++) { for ($j = 0; $j < $N; $j++) echo $mat[$i][$j] . " "; echo "\n"; } echo "\n";} // Driver code // Test Case 1$mat = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16)); // Test Case 2/* $mat = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9));*/ // Test Case 3/*$mat = array(array(1, 2), array(4, 5));*/ // displayMatrix($mat);rotateMatrix($mat); // Print rotated matrixdisplayMatrix($mat); // This code is contributed// by ChitraNayal?>
<script>// Javascript program to rotate a// matrix by 90 degrees // An Inplace function to // rotate a N x N matrix // by 90 degrees in // anti-clockwise direction function rotateMatrix(N,mat) { // Consider all squares one by one for (let x = 0; x < N / 2; x++) { // Consider elements in group // of 4 in current square for (let y = x; y < N - x - 1; y++) { // Store current cell in // temp variable let temp = mat[x][y]; // Move values from right to top mat[x][y] = mat[y][N - 1 - x]; // Move values from bottom to right mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y]; // Move values from left to bottom mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x]; // Assign temp to left mat[N - 1 - y][x] = temp; } } } // Function to print the matrix function displayMatrix(N,mat) { for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write( " " + mat[i][j]); document.write("<br>"); } document.write("<br>"); } /* Driver program to test above functions */ let N = 4; let mat=[[1, 2, 3, 4],[ 5, 6, 7, 8 ],[9, 10, 11, 12 ],[13, 14, 15, 16]]; // displayMatrix(mat); rotateMatrix(N, mat); // Print rotated matrix displayMatrix(N, mat); // This code is contributed by rag2127. </script>
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Complexity Analysis:
Time Complexity: O(n2), where n is side of array. A single traversal of the matrix is needed.
Space Complexity: O(1). As a constant space is needed
Easy to understand and apply
Another Approach:
Reverse every individual rowPerform Transpose
Reverse every individual row
Perform Transpose
Implementation:
C++
Java
Python3
C#
Javascript
// C++ program to rotate a matrix// by 90 degrees#include <bits/stdc++.h>#define N 4using namespace std; // An Inplace function to// rotate a N x N matrix// by 90 degrees in// anti-clockwise directionvoid rotateMatrix(int mat[][N]){ // REVERSE every row for (int i = 0; i < N; i++) reverse(mat[i], mat[i] + N); // Performing Transpose for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) swap(mat[i][j], mat[j][i]); }} // Function to print the matrixvoid displayMatrix(int mat[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << mat[i][j] << " "; } cout << endl; } cout << endl;} /* Driver program to test above functions */int main(){ // Test Case 1 int mat[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Test Case 2 /* int mat[N][N] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; */ // Test Case 3 /*int mat[N][N] = { {1, 2}, {4, 5} };*/ // displayMatrix(mat); rotateMatrix(mat); // Print rotated matrix displayMatrix(mat); return 0;}
// Java program to rotate a// matrix by 90 degreesimport java.io.*; class GFG { // Function to reverse // the given 2D arr[][] static void Reverse(int i,int mat[][], int N) { // Initialise start and end index int start = 0; int end = N - 1; // Till start < end, swap the element // at start and end index while (start < end) { // Swap the element int temp = mat[i][start]; mat[i][start] = mat[i][end]; mat[i][end] = temp; // Increment start and decrement // end for next pair of swapping start++; end--; } } // An Inplace function to // rotate a N x N matrix // by 90 degrees in // anti-clockwise direction static void rotateMatrix(int N, int mat[][]) { // REVERSE every row for (int i = 0; i < N; i++) Reverse(i,mat,N); // Performing Transpose for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) { int temp=mat[i][j]; mat[i][j]=mat[j][i]; mat[j][i]=temp; } } } // Function to print the matrix static void displayMatrix(int N, int mat[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(" " + mat[i][j]); System.out.print("\n"); } System.out.print("\n"); } /* Driver program to test above functions */ public static void main(String[] args) { int N = 4; // Test Case 1 int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateMatrix(N, mat); // Print rotated matrix displayMatrix(N, mat); }} // This code is contributed by Aarti_Rathi
# Python program to rotate# a matrix by 90 degrees def rotateMatrix(mat): # reversing the matrix for i in range(len(mat)): mat[i].reverse() # make transpose of the matrix for i in range(len(mat)): for j in range(i, len(mat)): # swapping mat[i][j] and mat[j][i] mat[i][j], mat[j][i] = mat[j][i], mat[i][j] # Function to print the matrixdef displayMatrix(mat): for i in range(0, len(mat)): for j in range(0, len(mat)): print(mat[i][j], end=' ') print() mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] rotateMatrix(mat) # Print rotated matrixdisplayMatrix(mat) # This code is contributed by shivambhagat02(CC).
// C# program to rotate a// matrix by 90 degreesusing System; class GFG { // Reverse each row of matrix static void reverse(int N, int[, ] mat) { // Traverse each row of [,]mat for (int i = 0; i < N; i++) { // Initialise start and end index int start = 0; int end = N - 1; // Till start < end, swap the element // at start and end index while (start < end) { // Swap the element int temp = mat[i,start]; mat[i, start] = mat[i, end]; mat[i, end] = temp; // Increment start and decrement // end for next pair of swapping start++; end--; } } } // An Inplace function to // rotate a N x N matrix // by 90 degrees in anti- // clockwise direction static void rotateMatrix(int N, int[, ] mat) { reverse(N, mat); // Performing Transpose for(int i=0;i<N;i++) { for(int j=i;j<N;j++) { int temp = mat[i,j]; mat[i, j] = mat[j, i]; mat[j, i] = temp; } } } // Function to print the matrix static void displayMatrix(int N, int[, ] mat) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(mat[i, j] + " "); Console.Write("\n"); } } // Driver Code static public void Main() { int N = 4; // Test Case 1 int[, ] mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Test Case 2 /* int mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; */ // Test Case 3 /*int mat[][] = { {1, 2}, {4, 5} };*/ // displayMatrix(mat); rotateMatrix(N, mat); // Print rotated matrix displayMatrix(N, mat); }} // This code is contributed by Aarti_Rathi
<script> // JavaScript program to rotate// a matrix by 90 degreesfunction rotateMatrix(mat){ // reversing the matrix for(let i = 0; i < mat.length; i++){ mat[i].reverse() } // make transpose of the matrix for(let i = 0; i < mat.length; i++){ for(let j = i; j < mat.length; j++){ // swapping mat[i][j] and mat[j][i] let temp = mat[i][j] mat[i][j] = mat[j][i] mat[j][i] = temp } }} // Function to print the matrixfunction displayMatrix(mat){ for(let i = 0; i < mat.length; i++){ for(let j = 0; j < mat.length; j++){ document.write(mat[i][j],' ') } document.write("</br>") }} let mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] rotateMatrix(mat) // Print rotated matrixdisplayMatrix(mat) // This code is contributed by shinjanpatra </script>
4 8 12 16
3 7 11 15
2 6 10 14
1 5 9 13
Complexity Analysis:
Time Complexity: O(n2) + O(n2) where n is size of array.
Auxiliary Space: O(1). As a constant space is needed
Exercise: Turn 2D matrix by 90 degrees in clockwise direction without using extra space.Rotate a matrix by 90 degree without using any extra space | Set 2
This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
jit_t
ukasp
Akanksha_Rai
andrew1234
rag2127
anushikasethh
rajeev0719singh
code_hunt
shivampkrr
surinderdawra388
shinjanpatra
dhruvkejri9
_shinchancode
codewithshinchan
hardikkoriintern
Amazon
Facebook
Google
Microsoft
Morgan Stanley
rotation
Zoho
Arrays
Matrix
Zoho
Morgan Stanley
Amazon
Microsoft
Google
Facebook
Arrays
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Rat in a Maze | Backtracking-2
Sudoku | Backtracking-7
Find the number of islands | Set 1 (Using DFS)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Jun, 2022"
},
{
"code": null,
"e": 156,
"s": 52,
"text": "Given a square matrix, turn it by 90 degrees in anti-clockwise direction without using any extra space."
},
{
"code": null,
"e": 168,
"s": 156,
"text": "Examples : "
},
{
"code": null,
"e": 509,
"s": 168,
"text": "Input:\nMatrix:\n 1 2 3\n 4 5 6\n 7 8 9\nOutput:\n 3 6 9 \n 2 5 8 \n 1 4 7 \nThe given matrix is rotated by 90 degree \nin anti-clockwise direction.\n\nInput:\n 1 2 3 4 \n 5 6 7 8 \n 9 10 11 12 \n13 14 15 16 \nOutput:\n 4 8 12 16 \n 3 7 11 15 \n 2 6 10 14 \n 1 5 9 13\nThe given matrix is rotated by 90 degree \nin anti-clockwise direction."
},
{
"code": null,
"e": 574,
"s": 509,
"text": "An approach that requires extra space is already discussed here."
},
{
"code": null,
"e": 1210,
"s": 574,
"text": "Approach: To solve the question without any extra space, rotate the array in form of squares, dividing the matrix into squares or cycles. For example, A 4 X 4 matrix will have 2 cycles. The first cycle is formed by its 1st row, last column, last row and 1st column. The second cycle is formed by 2nd row, second-last column, second-last row and 2nd column. The idea is for each square cycle, swap the elements involved with the corresponding cell in the matrix in anti-clockwise direction i.e. from top to left, left to bottom, bottom to right and from right to top one at a time using nothing but a temporary variable to achieve this."
},
{
"code": null,
"e": 1226,
"s": 1210,
"text": "Demonstration: "
},
{
"code": null,
"e": 1929,
"s": 1226,
"text": "First Cycle (Involves Red Elements)\n 1 2 3 4 \n 5 6 7 8 \n 9 10 11 12 \n 13 14 15 16 \n\nMoving first group of four elements (First\nelements of 1st row, last row, 1st column \nand last column) of first cycle in counter\nclockwise. \n 4 2 3 16\n 5 6 7 8 \n 9 10 11 12 \n 1 14 15 13 \n \nMoving next group of four elements of \nfirst cycle in counter clockwise \n 4 8 3 16 \n 5 6 7 15 \n 2 10 11 12 \n 1 14 9 13 \n\nMoving final group of four elements of \nfirst cycle in counter clockwise \n 4 8 12 16 \n 3 6 7 15 \n 2 10 11 14 \n 1 5 9 13 \n\n\nSecond Cycle (Involves Blue Elements)\n 4 8 12 16 \n 3 6 7 15 \n 2 10 11 14 \n 1 5 9 13 \n\nFixing second cycle\n 4 8 12 16 \n 3 7 11 15 \n 2 6 10 14 \n 1 5 9 13"
},
{
"code": null,
"e": 1941,
"s": 1929,
"text": "Algorithm: "
},
{
"code": null,
"e": 2565,
"s": 1941,
"text": "There is N/2 squares or cycles in a matrix of side N. Process a square one at a time. Run a loop to traverse the matrix a cycle at a time, i.e loop from 0 to N/2 – 1, loop counter is iConsider elements in group of 4 in current square, rotate the 4 elements at a time. So the number of such groups in a cycle is N – 2*i.So run a loop in each cycle from x to N – x – 1, loop counter is yThe elements in the current group is (x, y), (y, N-1-x), (N-1-x, N-1-y), (N-1-y, x), now rotate the these 4 elements, i.e (x, y) <- (y, N-1-x), (y, N-1-x)<- (N-1-x, N-1-y), (N-1-x, N-1-y)<- (N-1-y, x), (N-1-y, x)<- (x, y)Print the matrix."
},
{
"code": null,
"e": 2750,
"s": 2565,
"text": "There is N/2 squares or cycles in a matrix of side N. Process a square one at a time. Run a loop to traverse the matrix a cycle at a time, i.e loop from 0 to N/2 – 1, loop counter is i"
},
{
"code": null,
"e": 2886,
"s": 2750,
"text": "Consider elements in group of 4 in current square, rotate the 4 elements at a time. So the number of such groups in a cycle is N – 2*i."
},
{
"code": null,
"e": 2953,
"s": 2886,
"text": "So run a loop in each cycle from x to N – x – 1, loop counter is y"
},
{
"code": null,
"e": 3175,
"s": 2953,
"text": "The elements in the current group is (x, y), (y, N-1-x), (N-1-x, N-1-y), (N-1-y, x), now rotate the these 4 elements, i.e (x, y) <- (y, N-1-x), (y, N-1-x)<- (N-1-x, N-1-y), (N-1-x, N-1-y)<- (N-1-y, x), (N-1-y, x)<- (x, y)"
},
{
"code": null,
"e": 3193,
"s": 3175,
"text": "Print the matrix."
},
{
"code": null,
"e": 3209,
"s": 3193,
"text": "Implementation:"
},
{
"code": null,
"e": 3213,
"s": 3209,
"text": "C++"
},
{
"code": null,
"e": 3218,
"s": 3213,
"text": "Java"
},
{
"code": null,
"e": 3226,
"s": 3218,
"text": "Python3"
},
{
"code": null,
"e": 3229,
"s": 3226,
"text": "C#"
},
{
"code": null,
"e": 3233,
"s": 3229,
"text": "PHP"
},
{
"code": null,
"e": 3244,
"s": 3233,
"text": "Javascript"
},
{
"code": "// C++ program to rotate a matrix// by 90 degrees#include <bits/stdc++.h>#define N 4using namespace std; // An Inplace function to// rotate a N x N matrix// by 90 degrees in// anti-clockwise directionvoid rotateMatrix(int mat[][N]){ // Consider all squares one by one for (int x = 0; x < N / 2; x++) { // Consider elements in group // of 4 in current square for (int y = x; y < N - x - 1; y++) { // Store current cell in // temp variable int temp = mat[x][y]; // Move values from right to top mat[x][y] = mat[y][N - 1 - x]; // Move values from bottom to right mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y]; // Move values from left to bottom mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x]; // Assign temp to left mat[N - 1 - y][x] = temp; } }} // Function to print the matrixvoid displayMatrix(int mat[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout<<mat[i][j]<<\" \"; } cout<<endl; } cout<<endl;} /* Driver program to test above functions */int main(){ // Test Case 1 int mat[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Test Case 2 /* int mat[N][N] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; */ // Test Case 3 /*int mat[N][N] = { {1, 2}, {4, 5} };*/ // displayMatrix(mat); rotateMatrix(mat); // Print rotated matrix displayMatrix(mat); return 0;}",
"e": 5012,
"s": 3244,
"text": null
},
{
"code": "// Java program to rotate a// matrix by 90 degreesimport java.io.*; class GFG { // An Inplace function to // rotate a N x N matrix // by 90 degrees in // anti-clockwise direction static void rotateMatrix(int N, int mat[][]) { // Consider all squares one by one for (int x = 0; x < N / 2; x++) { // Consider elements in group // of 4 in current square for (int y = x; y < N - x - 1; y++) { // Store current cell in // temp variable int temp = mat[x][y]; // Move values from right to top mat[x][y] = mat[y][N - 1 - x]; // Move values from bottom to right mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y]; // Move values from left to bottom mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x]; // Assign temp to left mat[N - 1 - y][x] = temp; } } } // Function to print the matrix static void displayMatrix(int N, int mat[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(\" \" + mat[i][j]); System.out.print(\"\\n\"); } System.out.print(\"\\n\"); } /* Driver program to test above functions */ public static void main(String[] args) { int N = 4; // Test Case 1 int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Test Case 2 /* int mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; */ // Test Case 3 /*int mat[][] = { {1, 2}, {4, 5} };*/ // displayMatrix(mat); rotateMatrix(N, mat); // Print rotated matrix displayMatrix(N, mat); }} // This code is contributed by Prakriti Gupta",
"e": 7148,
"s": 5012,
"text": null
},
{
"code": "# Python3 program to rotate a matrix by 90 degreesN = 4 # An Inplace function to rotate# N x N matrix by 90 degrees in# anti-clockwise direction def rotateMatrix(mat): # Consider all squares one by one for x in range(0, int(N / 2)): # Consider elements in group # of 4 in current square for y in range(x, N-x-1): # store current cell in temp variable temp = mat[x][y] # move values from right to top mat[x][y] = mat[y][N-1-x] # move values from bottom to right mat[y][N-1-x] = mat[N-1-x][N-1-y] # move values from left to bottom mat[N-1-x][N-1-y] = mat[N-1-y][x] # assign temp to left mat[N-1-y][x] = temp # Function to print the matrixdef displayMatrix(mat): for i in range(0, N): for j in range(0, N): print(mat[i][j], end=' ') print(\"\") # Driver Codemat = [[0 for x in range(N)] for y in range(N)] # Test case 1mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] '''# Test case 2mat = [ [1, 2, 3 ], [4, 5, 6 ], [7, 8, 9 ] ] # Test case 3mat = [ [1, 2 ], [4, 5 ] ] ''' rotateMatrix(mat) # Print rotated matrixdisplayMatrix(mat) # This code is contributed by saloni1297",
"e": 8463,
"s": 7148,
"text": null
},
{
"code": "// C# program to rotate a// matrix by 90 degreesusing System; class GFG { // An Inplace function to // rotate a N x N matrix // by 90 degrees in anti- // clockwise direction static void rotateMatrix(int N, int[, ] mat) { // Consider all // squares one by one for (int x = 0; x < N / 2; x++) { // Consider elements // in group of 4 in // current square for (int y = x; y < N - x - 1; y++) { // store current cell // in temp variable int temp = mat[x, y]; // move values from // right to top mat[x, y] = mat[y, N - 1 - x]; // move values from // bottom to right mat[y, N - 1 - x] = mat[N - 1 - x, N - 1 - y]; // move values from // left to bottom mat[N - 1 - x, N - 1 - y] = mat[N - 1 - y, x]; // assign temp to left mat[N - 1 - y, x] = temp; } } } // Function to print the matrix static void displayMatrix(int N, int[, ] mat) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(\" \" + mat[i, j]); Console.WriteLine(); } Console.WriteLine(); } // Driver Code static public void Main() { int N = 4; // Test Case 1 int[, ] mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Test Case 2 /* int mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; */ // Test Case 3 /*int mat[][] = { {1, 2}, {4, 5} };*/ // displayMatrix(mat); rotateMatrix(N, mat); // Print rotated matrix displayMatrix(N, mat); }} // This code is contributed by ajit",
"e": 10522,
"s": 8463,
"text": null
},
{
"code": "<?php// PHP program to rotate a// matrix by 90 degrees$N = 4; // An Inplace function to// rotate a N x N matrix// by 90 degrees in// anti-clockwise directionfunction rotateMatrix(&$mat){ global $N; // Consider all // squares one by one for ($x = 0; $x < $N / 2; $x++) { // Consider elements // in group of 4 in // current square for ($y = $x; $y < $N - $x - 1; $y++) { // store current cell // in temp variable $temp = $mat[$x][$y]; // move values from // right to top $mat[$x][$y] = $mat[$y][$N - 1 - $x]; // move values from // bottom to right $mat[$y][$N - 1 - $x] = $mat[$N - 1 - $x][$N - 1 - $y]; // move values from // left to bottom $mat[$N - 1 - $x][$N - 1 - $y] = $mat[$N - 1 - $y][$x]; // assign temp to left $mat[$N - 1 - $y][$x] = $temp; } }} // Function to// print the matrixfunction displayMatrix(&$mat){ global $N; for ($i = 0; $i < $N; $i++) { for ($j = 0; $j < $N; $j++) echo $mat[$i][$j] . \" \"; echo \"\\n\"; } echo \"\\n\";} // Driver code // Test Case 1$mat = array(array(1, 2, 3, 4), array(5, 6, 7, 8), array(9, 10, 11, 12), array(13, 14, 15, 16)); // Test Case 2/* $mat = array(array(1, 2, 3), array(4, 5, 6), array(7, 8, 9));*/ // Test Case 3/*$mat = array(array(1, 2), array(4, 5));*/ // displayMatrix($mat);rotateMatrix($mat); // Print rotated matrixdisplayMatrix($mat); // This code is contributed// by ChitraNayal?>",
"e": 12258,
"s": 10522,
"text": null
},
{
"code": "<script>// Javascript program to rotate a// matrix by 90 degrees // An Inplace function to // rotate a N x N matrix // by 90 degrees in // anti-clockwise direction function rotateMatrix(N,mat) { // Consider all squares one by one for (let x = 0; x < N / 2; x++) { // Consider elements in group // of 4 in current square for (let y = x; y < N - x - 1; y++) { // Store current cell in // temp variable let temp = mat[x][y]; // Move values from right to top mat[x][y] = mat[y][N - 1 - x]; // Move values from bottom to right mat[y][N - 1 - x] = mat[N - 1 - x][N - 1 - y]; // Move values from left to bottom mat[N - 1 - x][N - 1 - y] = mat[N - 1 - y][x]; // Assign temp to left mat[N - 1 - y][x] = temp; } } } // Function to print the matrix function displayMatrix(N,mat) { for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write( \" \" + mat[i][j]); document.write(\"<br>\"); } document.write(\"<br>\"); } /* Driver program to test above functions */ let N = 4; let mat=[[1, 2, 3, 4],[ 5, 6, 7, 8 ],[9, 10, 11, 12 ],[13, 14, 15, 16]]; // displayMatrix(mat); rotateMatrix(N, mat); // Print rotated matrix displayMatrix(N, mat); // This code is contributed by rag2127. </script>",
"e": 13915,
"s": 12258,
"text": null
},
{
"code": null,
"e": 13958,
"s": 13915,
"text": "4 8 12 16 \n3 7 11 15 \n2 6 10 14 \n1 5 9 13 "
},
{
"code": null,
"e": 13980,
"s": 13958,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 14074,
"s": 13980,
"text": "Time Complexity: O(n2), where n is side of array. A single traversal of the matrix is needed."
},
{
"code": null,
"e": 14128,
"s": 14074,
"text": "Space Complexity: O(1). As a constant space is needed"
},
{
"code": null,
"e": 14159,
"s": 14128,
"text": " Easy to understand and apply"
},
{
"code": null,
"e": 14177,
"s": 14159,
"text": "Another Approach:"
},
{
"code": null,
"e": 14224,
"s": 14177,
"text": "Reverse every individual rowPerform Transpose"
},
{
"code": null,
"e": 14254,
"s": 14224,
"text": "Reverse every individual row"
},
{
"code": null,
"e": 14272,
"s": 14254,
"text": "Perform Transpose"
},
{
"code": null,
"e": 14288,
"s": 14272,
"text": "Implementation:"
},
{
"code": null,
"e": 14292,
"s": 14288,
"text": "C++"
},
{
"code": null,
"e": 14297,
"s": 14292,
"text": "Java"
},
{
"code": null,
"e": 14305,
"s": 14297,
"text": "Python3"
},
{
"code": null,
"e": 14308,
"s": 14305,
"text": "C#"
},
{
"code": null,
"e": 14319,
"s": 14308,
"text": "Javascript"
},
{
"code": "// C++ program to rotate a matrix// by 90 degrees#include <bits/stdc++.h>#define N 4using namespace std; // An Inplace function to// rotate a N x N matrix// by 90 degrees in// anti-clockwise directionvoid rotateMatrix(int mat[][N]){ // REVERSE every row for (int i = 0; i < N; i++) reverse(mat[i], mat[i] + N); // Performing Transpose for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) swap(mat[i][j], mat[j][i]); }} // Function to print the matrixvoid displayMatrix(int mat[N][N]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { cout << mat[i][j] << \" \"; } cout << endl; } cout << endl;} /* Driver program to test above functions */int main(){ // Test Case 1 int mat[N][N] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Test Case 2 /* int mat[N][N] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; */ // Test Case 3 /*int mat[N][N] = { {1, 2}, {4, 5} };*/ // displayMatrix(mat); rotateMatrix(mat); // Print rotated matrix displayMatrix(mat); return 0;}",
"e": 15642,
"s": 14319,
"text": null
},
{
"code": "// Java program to rotate a// matrix by 90 degreesimport java.io.*; class GFG { // Function to reverse // the given 2D arr[][] static void Reverse(int i,int mat[][], int N) { // Initialise start and end index int start = 0; int end = N - 1; // Till start < end, swap the element // at start and end index while (start < end) { // Swap the element int temp = mat[i][start]; mat[i][start] = mat[i][end]; mat[i][end] = temp; // Increment start and decrement // end for next pair of swapping start++; end--; } } // An Inplace function to // rotate a N x N matrix // by 90 degrees in // anti-clockwise direction static void rotateMatrix(int N, int mat[][]) { // REVERSE every row for (int i = 0; i < N; i++) Reverse(i,mat,N); // Performing Transpose for (int i = 0; i < N; i++) { for (int j = i; j < N; j++) { int temp=mat[i][j]; mat[i][j]=mat[j][i]; mat[j][i]=temp; } } } // Function to print the matrix static void displayMatrix(int N, int mat[][]) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(\" \" + mat[i][j]); System.out.print(\"\\n\"); } System.out.print(\"\\n\"); } /* Driver program to test above functions */ public static void main(String[] args) { int N = 4; // Test Case 1 int mat[][] = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; rotateMatrix(N, mat); // Print rotated matrix displayMatrix(N, mat); }} // This code is contributed by Aarti_Rathi",
"e": 17296,
"s": 15642,
"text": null
},
{
"code": "# Python program to rotate# a matrix by 90 degrees def rotateMatrix(mat): # reversing the matrix for i in range(len(mat)): mat[i].reverse() # make transpose of the matrix for i in range(len(mat)): for j in range(i, len(mat)): # swapping mat[i][j] and mat[j][i] mat[i][j], mat[j][i] = mat[j][i], mat[i][j] # Function to print the matrixdef displayMatrix(mat): for i in range(0, len(mat)): for j in range(0, len(mat)): print(mat[i][j], end=' ') print() mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] rotateMatrix(mat) # Print rotated matrixdisplayMatrix(mat) # This code is contributed by shivambhagat02(CC).",
"e": 18027,
"s": 17296,
"text": null
},
{
"code": "// C# program to rotate a// matrix by 90 degreesusing System; class GFG { // Reverse each row of matrix static void reverse(int N, int[, ] mat) { // Traverse each row of [,]mat for (int i = 0; i < N; i++) { // Initialise start and end index int start = 0; int end = N - 1; // Till start < end, swap the element // at start and end index while (start < end) { // Swap the element int temp = mat[i,start]; mat[i, start] = mat[i, end]; mat[i, end] = temp; // Increment start and decrement // end for next pair of swapping start++; end--; } } } // An Inplace function to // rotate a N x N matrix // by 90 degrees in anti- // clockwise direction static void rotateMatrix(int N, int[, ] mat) { reverse(N, mat); // Performing Transpose for(int i=0;i<N;i++) { for(int j=i;j<N;j++) { int temp = mat[i,j]; mat[i, j] = mat[j, i]; mat[j, i] = temp; } } } // Function to print the matrix static void displayMatrix(int N, int[, ] mat) { for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(mat[i, j] + \" \"); Console.Write(\"\\n\"); } } // Driver Code static public void Main() { int N = 4; // Test Case 1 int[, ] mat = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 }, { 13, 14, 15, 16 } }; // Test Case 2 /* int mat[][] = { {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }; */ // Test Case 3 /*int mat[][] = { {1, 2}, {4, 5} };*/ // displayMatrix(mat); rotateMatrix(N, mat); // Print rotated matrix displayMatrix(N, mat); }} // This code is contributed by Aarti_Rathi",
"e": 20240,
"s": 18027,
"text": null
},
{
"code": "<script> // JavaScript program to rotate// a matrix by 90 degreesfunction rotateMatrix(mat){ // reversing the matrix for(let i = 0; i < mat.length; i++){ mat[i].reverse() } // make transpose of the matrix for(let i = 0; i < mat.length; i++){ for(let j = i; j < mat.length; j++){ // swapping mat[i][j] and mat[j][i] let temp = mat[i][j] mat[i][j] = mat[j][i] mat[j][i] = temp } }} // Function to print the matrixfunction displayMatrix(mat){ for(let i = 0; i < mat.length; i++){ for(let j = 0; j < mat.length; j++){ document.write(mat[i][j],' ') } document.write(\"</br>\") }} let mat = [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]] rotateMatrix(mat) // Print rotated matrixdisplayMatrix(mat) // This code is contributed by shinjanpatra </script>",
"e": 21140,
"s": 20240,
"text": null
},
{
"code": null,
"e": 21183,
"s": 21140,
"text": "4 8 12 16 \n3 7 11 15 \n2 6 10 14 \n1 5 9 13 "
},
{
"code": null,
"e": 21206,
"s": 21183,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 21265,
"s": 21206,
"text": "Time Complexity: O(n2) + O(n2) where n is size of array."
},
{
"code": null,
"e": 21318,
"s": 21265,
"text": "Auxiliary Space: O(1). As a constant space is needed"
},
{
"code": null,
"e": 21473,
"s": 21318,
"text": "Exercise: Turn 2D matrix by 90 degrees in clockwise direction without using extra space.Rotate a matrix by 90 degree without using any extra space | Set 2"
},
{
"code": null,
"e": 21740,
"s": 21473,
"text": "This article is contributed by Aditya Goel. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 21746,
"s": 21740,
"text": "jit_t"
},
{
"code": null,
"e": 21752,
"s": 21746,
"text": "ukasp"
},
{
"code": null,
"e": 21765,
"s": 21752,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 21776,
"s": 21765,
"text": "andrew1234"
},
{
"code": null,
"e": 21784,
"s": 21776,
"text": "rag2127"
},
{
"code": null,
"e": 21798,
"s": 21784,
"text": "anushikasethh"
},
{
"code": null,
"e": 21814,
"s": 21798,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 21824,
"s": 21814,
"text": "code_hunt"
},
{
"code": null,
"e": 21835,
"s": 21824,
"text": "shivampkrr"
},
{
"code": null,
"e": 21852,
"s": 21835,
"text": "surinderdawra388"
},
{
"code": null,
"e": 21865,
"s": 21852,
"text": "shinjanpatra"
},
{
"code": null,
"e": 21877,
"s": 21865,
"text": "dhruvkejri9"
},
{
"code": null,
"e": 21891,
"s": 21877,
"text": "_shinchancode"
},
{
"code": null,
"e": 21908,
"s": 21891,
"text": "codewithshinchan"
},
{
"code": null,
"e": 21925,
"s": 21908,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 21932,
"s": 21925,
"text": "Amazon"
},
{
"code": null,
"e": 21941,
"s": 21932,
"text": "Facebook"
},
{
"code": null,
"e": 21948,
"s": 21941,
"text": "Google"
},
{
"code": null,
"e": 21958,
"s": 21948,
"text": "Microsoft"
},
{
"code": null,
"e": 21973,
"s": 21958,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 21982,
"s": 21973,
"text": "rotation"
},
{
"code": null,
"e": 21987,
"s": 21982,
"text": "Zoho"
},
{
"code": null,
"e": 21994,
"s": 21987,
"text": "Arrays"
},
{
"code": null,
"e": 22001,
"s": 21994,
"text": "Matrix"
},
{
"code": null,
"e": 22006,
"s": 22001,
"text": "Zoho"
},
{
"code": null,
"e": 22021,
"s": 22006,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 22028,
"s": 22021,
"text": "Amazon"
},
{
"code": null,
"e": 22038,
"s": 22028,
"text": "Microsoft"
},
{
"code": null,
"e": 22045,
"s": 22038,
"text": "Google"
},
{
"code": null,
"e": 22054,
"s": 22045,
"text": "Facebook"
},
{
"code": null,
"e": 22061,
"s": 22054,
"text": "Arrays"
},
{
"code": null,
"e": 22068,
"s": 22061,
"text": "Matrix"
},
{
"code": null,
"e": 22166,
"s": 22068,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 22181,
"s": 22166,
"text": "Arrays in Java"
},
{
"code": null,
"e": 22227,
"s": 22181,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 22295,
"s": 22227,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 22339,
"s": 22295,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 22371,
"s": 22339,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 22406,
"s": 22371,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 22450,
"s": 22406,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 22481,
"s": 22450,
"text": "Rat in a Maze | Backtracking-2"
},
{
"code": null,
"e": 22505,
"s": 22481,
"text": "Sudoku | Backtracking-7"
}
] |
PostgreSQL – IN operator
|
28 Aug, 2020
The PostgreSQL IN operator is used with the WHERE clause to check against a list of values.
The syntax for using IN operator with the WHERE clause to check against a list of values which returns a boolean value depending upon the match is as below:
Syntax: value IN (value1, value2, ...)
The syntax for using IN operator to return the matching values in contrast with the SELECT statement is as below:
Syntax: value IN (SELECT value FROM tbl_name);
For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link.
Now, let’s look into a few examples.Example 1:Here we will make a query for the rental information of customer id 10 and 12, using the WHERE clause and IN operator.
SELECT
customer_id,
rental_id,
return_date
FROM
rental
WHERE
customer_id IN (10, 12)
ORDER BY
return_date DESC;
Output:
Example 2:Here we will make a query for a list of customer id of customers that has rental’s return date on 2005-05-27.
SELECT
first_name,
last_name
FROM
customer
WHERE
customer_id IN (
SELECT
customer_id
FROM
rental
WHERE
CAST (return_date AS DATE) = '2005-05-27'
);
Output:
postgreSQL-operators
PostgreSQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - Function Returning A Table
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - DROP INDEX
PostgreSQL - Create Auto-increment Column using SERIAL
PostgreSQL - Copy Table
How to use PostgreSQL Database in Django?
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Aug, 2020"
},
{
"code": null,
"e": 144,
"s": 52,
"text": "The PostgreSQL IN operator is used with the WHERE clause to check against a list of values."
},
{
"code": null,
"e": 301,
"s": 144,
"text": "The syntax for using IN operator with the WHERE clause to check against a list of values which returns a boolean value depending upon the match is as below:"
},
{
"code": null,
"e": 340,
"s": 301,
"text": "Syntax: value IN (value1, value2, ...)"
},
{
"code": null,
"e": 454,
"s": 340,
"text": "The syntax for using IN operator to return the matching values in contrast with the SELECT statement is as below:"
},
{
"code": null,
"e": 501,
"s": 454,
"text": "Syntax: value IN (SELECT value FROM tbl_name);"
},
{
"code": null,
"e": 651,
"s": 501,
"text": "For the sake of this article we will be using the sample DVD rental database, which is explained here and can be downloaded by clicking on this link."
},
{
"code": null,
"e": 816,
"s": 651,
"text": "Now, let’s look into a few examples.Example 1:Here we will make a query for the rental information of customer id 10 and 12, using the WHERE clause and IN operator."
},
{
"code": null,
"e": 949,
"s": 816,
"text": "SELECT\n customer_id,\n rental_id,\n return_date\nFROM\n rental\nWHERE\n customer_id IN (10, 12)\nORDER BY\n return_date DESC;"
},
{
"code": null,
"e": 957,
"s": 949,
"text": "Output:"
},
{
"code": null,
"e": 1077,
"s": 957,
"text": "Example 2:Here we will make a query for a list of customer id of customers that has rental’s return date on 2005-05-27."
},
{
"code": null,
"e": 1305,
"s": 1077,
"text": "SELECT\n first_name,\n last_name\nFROM\n customer\nWHERE\n customer_id IN (\n SELECT\n customer_id\n FROM\n rental\n WHERE\n CAST (return_date AS DATE) = '2005-05-27'\n );"
},
{
"code": null,
"e": 1313,
"s": 1305,
"text": "Output:"
},
{
"code": null,
"e": 1334,
"s": 1313,
"text": "postgreSQL-operators"
},
{
"code": null,
"e": 1345,
"s": 1334,
"text": "PostgreSQL"
},
{
"code": null,
"e": 1443,
"s": 1345,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1470,
"s": 1443,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 1502,
"s": 1470,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 1525,
"s": 1502,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 1565,
"s": 1525,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 1603,
"s": 1565,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 1637,
"s": 1603,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 1661,
"s": 1637,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 1716,
"s": 1661,
"text": "PostgreSQL - Create Auto-increment Column using SERIAL"
},
{
"code": null,
"e": 1740,
"s": 1716,
"text": "PostgreSQL - Copy Table"
}
] |
Custom C++ User Snippet in Visual Studio Code
|
12 Mar, 2021
Snippets are the small portion of re-usable code wrapped in some prefix word, It allows programmers to bind a particular block of code in a single prefix keyword. Visual Studio Code is a Lightweight and powerful source code editor available in Windows, Linux, and macOS, It comes with many built-in snippets for the loops, control statements, and some keywords. But you know, we can also create our own custom code snippets for time saving and avoiding writing the same piece of code again and again. Users can code faster and productively with the help of custom code snippets.
Built-in the snippet for the loop.
Now let’s take a look at how we can create our own code snippets for c++ language.
Here we were going to create a user snippet for the C++ language header template, In the Windows machine.
Step 1: Open the Visual Studio Code, and go to the ‘Manage’ (Gear icon in the bottom left corner).
Step 2: From opened options, Select the ‘User Snippets’ option.
Step 3: Select your programming language in which you are going to create a snippet. (Here we are selecting C++).
Step 4: Now, one cpp.json file will open Where we have to write a code for our code snippet. First, un-comment the code present below their instructions. (refer to screenshot).
Step 5: In this step, we have to do appropriate changes to their code.
First, Let’s understand the meaning of terms present in the code. Snippets generally have four main properties.
Print to console: This is the word, which will open our snippet when we call it.Prefix: This prefix is used when selecting the snippet in intellisence.Body: In the body we are writing our main snippet code.Description: In this we have to mention brief description of snippet for our reference only.
Print to console: This is the word, which will open our snippet when we call it.
Prefix: This prefix is used when selecting the snippet in intellisence.
Body: In the body we are writing our main snippet code.
Description: In this we have to mention brief description of snippet for our reference only.
Note –
In body ‘$1’ sign determines the position of our cursor when the snippet is activated in code (Tab Stop).
Note that while writing snippet code in the body, For multiline snippets, the body becomes an array with each line of the snippet becoming a string in that array.
To format our code properly, we’re adding a “\t”, “\n” to lines for proper Indentation.
In our snippet, we have used a ‘boilerplate‘ as ‘print to console’, which means when we type boilerplate and press Enter, our snippet is executed.
Prefix gave as ‘boilerplate code’. This will visible while typing the name of the snippet.
The prefix is visible while writing snippet name
In the body, we have included iostream header file and template code for c++. A description of the snippet is also added. “\t” and “\n” are added for proper formatting of code.
The tab is on the 6th line with four spaces.
Snippet Outcome
C++
#include <iostream>using namespace std; int main(){ return 0;}
Here all the above-mentioned steps are performed creating a Snippet. This will give you a clearer understanding.
That’s all. In this way, you can create a user snippet for different languages in Visual Studio Code. Each snippet is associated with a particular name, When we type that name and hit the enter key, Snippet code is executed.
C++
TechTips
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
std::string class in C++
How to Find the Wi-Fi Password Using CMD in Windows?
Docker - COPY Instruction
Setting up the environment in Java
How to Run a Python Script using Docker?
Running Python script on GPU.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n12 Mar, 2021"
},
{
"code": null,
"e": 631,
"s": 52,
"text": "Snippets are the small portion of re-usable code wrapped in some prefix word, It allows programmers to bind a particular block of code in a single prefix keyword. Visual Studio Code is a Lightweight and powerful source code editor available in Windows, Linux, and macOS, It comes with many built-in snippets for the loops, control statements, and some keywords. But you know, we can also create our own custom code snippets for time saving and avoiding writing the same piece of code again and again. Users can code faster and productively with the help of custom code snippets."
},
{
"code": null,
"e": 666,
"s": 631,
"text": "Built-in the snippet for the loop."
},
{
"code": null,
"e": 749,
"s": 666,
"text": "Now let’s take a look at how we can create our own code snippets for c++ language."
},
{
"code": null,
"e": 855,
"s": 749,
"text": "Here we were going to create a user snippet for the C++ language header template, In the Windows machine."
},
{
"code": null,
"e": 954,
"s": 855,
"text": "Step 1: Open the Visual Studio Code, and go to the ‘Manage’ (Gear icon in the bottom left corner)."
},
{
"code": null,
"e": 1018,
"s": 954,
"text": "Step 2: From opened options, Select the ‘User Snippets’ option."
},
{
"code": null,
"e": 1132,
"s": 1018,
"text": "Step 3: Select your programming language in which you are going to create a snippet. (Here we are selecting C++)."
},
{
"code": null,
"e": 1309,
"s": 1132,
"text": "Step 4: Now, one cpp.json file will open Where we have to write a code for our code snippet. First, un-comment the code present below their instructions. (refer to screenshot)."
},
{
"code": null,
"e": 1380,
"s": 1309,
"text": "Step 5: In this step, we have to do appropriate changes to their code."
},
{
"code": null,
"e": 1492,
"s": 1380,
"text": "First, Let’s understand the meaning of terms present in the code. Snippets generally have four main properties."
},
{
"code": null,
"e": 1791,
"s": 1492,
"text": "Print to console: This is the word, which will open our snippet when we call it.Prefix: This prefix is used when selecting the snippet in intellisence.Body: In the body we are writing our main snippet code.Description: In this we have to mention brief description of snippet for our reference only."
},
{
"code": null,
"e": 1872,
"s": 1791,
"text": "Print to console: This is the word, which will open our snippet when we call it."
},
{
"code": null,
"e": 1944,
"s": 1872,
"text": "Prefix: This prefix is used when selecting the snippet in intellisence."
},
{
"code": null,
"e": 2000,
"s": 1944,
"text": "Body: In the body we are writing our main snippet code."
},
{
"code": null,
"e": 2093,
"s": 2000,
"text": "Description: In this we have to mention brief description of snippet for our reference only."
},
{
"code": null,
"e": 2101,
"s": 2093,
"text": "Note – "
},
{
"code": null,
"e": 2207,
"s": 2101,
"text": "In body ‘$1’ sign determines the position of our cursor when the snippet is activated in code (Tab Stop)."
},
{
"code": null,
"e": 2370,
"s": 2207,
"text": "Note that while writing snippet code in the body, For multiline snippets, the body becomes an array with each line of the snippet becoming a string in that array."
},
{
"code": null,
"e": 2458,
"s": 2370,
"text": "To format our code properly, we’re adding a “\\t”, “\\n” to lines for proper Indentation."
},
{
"code": null,
"e": 2605,
"s": 2458,
"text": "In our snippet, we have used a ‘boilerplate‘ as ‘print to console’, which means when we type boilerplate and press Enter, our snippet is executed."
},
{
"code": null,
"e": 2696,
"s": 2605,
"text": "Prefix gave as ‘boilerplate code’. This will visible while typing the name of the snippet."
},
{
"code": null,
"e": 2745,
"s": 2696,
"text": "The prefix is visible while writing snippet name"
},
{
"code": null,
"e": 2922,
"s": 2745,
"text": "In the body, we have included iostream header file and template code for c++. A description of the snippet is also added. “\\t” and “\\n” are added for proper formatting of code."
},
{
"code": null,
"e": 2967,
"s": 2922,
"text": "The tab is on the 6th line with four spaces."
},
{
"code": null,
"e": 2983,
"s": 2967,
"text": "Snippet Outcome"
},
{
"code": null,
"e": 2987,
"s": 2983,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; int main(){ return 0;}",
"e": 3060,
"s": 2987,
"text": null
},
{
"code": null,
"e": 3174,
"s": 3060,
"text": "Here all the above-mentioned steps are performed creating a Snippet. This will give you a clearer understanding. "
},
{
"code": null,
"e": 3399,
"s": 3174,
"text": "That’s all. In this way, you can create a user snippet for different languages in Visual Studio Code. Each snippet is associated with a particular name, When we type that name and hit the enter key, Snippet code is executed."
},
{
"code": null,
"e": 3403,
"s": 3399,
"text": "C++"
},
{
"code": null,
"e": 3412,
"s": 3403,
"text": "TechTips"
},
{
"code": null,
"e": 3416,
"s": 3412,
"text": "CPP"
},
{
"code": null,
"e": 3514,
"s": 3416,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3538,
"s": 3514,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 3558,
"s": 3538,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 3591,
"s": 3558,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 3635,
"s": 3591,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3660,
"s": 3635,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3713,
"s": 3660,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 3739,
"s": 3713,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 3774,
"s": 3739,
"text": "Setting up the environment in Java"
},
{
"code": null,
"e": 3815,
"s": 3774,
"text": "How to Run a Python Script using Docker?"
}
] |
Lodash | _.remove() Method
|
23 Jan, 2022
The _.remove() method is used to remove all elements from the array that predicate returns True and returns the removed elements.
Syntax:
_.remove(array, function)
Parameters: This method accept two parameters as mentioned above and described below:
array: This parameter holds the array that need to be modify.
function: This parameter holds the function that invoked per iteration.
Return Value: It returns an array of removed elements.
Example: Here all the elements returning true are even elements. The function is invoked on all the elements (n) of the array.
Javascript
let x = [1, 2, 3, 4, 5]; let even = _.remove(x, function(n) { return n % 2 == 0;}); console.log('Original Array ', x);console.log('Removed element array ', even);
Here, const _ = require(‘lodash’) is used to import the lodash library into the file.
Output:
Original Array [ 1, 3, 5 ]
Removed element array [ 2, 4 ]
Example 2: This example removes all the vowels from an array containing alphabets and store them in a new array.
Javascript
const _ = require('lodash'); let x = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']; let vowelArray = _.remove(x, function(n) { let vowels = ['a', 'e', 'i', 'o', 'u']; for (let i = 0; i < 5; i++) { if (n === vowels[i]) { return true; } }});
Output:
Original Array [ 'b', 'c', 'd', 'f', 'g', 'h' ]
Removed element array [ 'a', 'e', 'i' ]
Example 3: This example removes all the integers from a given array containing floats, characters, and integers.
Javascript
let x = ['a', 'b', 1, 5.6, 'e', -7, 'g', 4, 10.8]; let intsArray = _.remove(x, function(n) { return Number.isInteger(n);}); console.log('Original Array ', x);console.log('Removed element array ', intsArray);
Output:
Original Array [ 'a', 'b', 5.6, 'e', 'g', 10.8 ]
Removed element array [ 1, -7, 4 ]
Note: This will not work in normal JavaScript because it requires the library lodash to be installed.Reference: https://lodash.com/docs/4.17.15#remove
gulshankumarar231
sagar0719kumar
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
How to append HTML code to a div using JavaScript ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Jan, 2022"
},
{
"code": null,
"e": 158,
"s": 28,
"text": "The _.remove() method is used to remove all elements from the array that predicate returns True and returns the removed elements."
},
{
"code": null,
"e": 167,
"s": 158,
"text": "Syntax: "
},
{
"code": null,
"e": 193,
"s": 167,
"text": "_.remove(array, function)"
},
{
"code": null,
"e": 281,
"s": 193,
"text": "Parameters: This method accept two parameters as mentioned above and described below: "
},
{
"code": null,
"e": 343,
"s": 281,
"text": "array: This parameter holds the array that need to be modify."
},
{
"code": null,
"e": 415,
"s": 343,
"text": "function: This parameter holds the function that invoked per iteration."
},
{
"code": null,
"e": 470,
"s": 415,
"text": "Return Value: It returns an array of removed elements."
},
{
"code": null,
"e": 598,
"s": 470,
"text": "Example: Here all the elements returning true are even elements. The function is invoked on all the elements (n) of the array. "
},
{
"code": null,
"e": 609,
"s": 598,
"text": "Javascript"
},
{
"code": "let x = [1, 2, 3, 4, 5]; let even = _.remove(x, function(n) { return n % 2 == 0;}); console.log('Original Array ', x);console.log('Removed element array ', even);",
"e": 775,
"s": 609,
"text": null
},
{
"code": null,
"e": 861,
"s": 775,
"text": "Here, const _ = require(‘lodash’) is used to import the lodash library into the file."
},
{
"code": null,
"e": 870,
"s": 861,
"text": "Output: "
},
{
"code": null,
"e": 930,
"s": 870,
"text": "Original Array [ 1, 3, 5 ]\nRemoved element array [ 2, 4 ]"
},
{
"code": null,
"e": 1045,
"s": 930,
"text": "Example 2: This example removes all the vowels from an array containing alphabets and store them in a new array. "
},
{
"code": null,
"e": 1056,
"s": 1045,
"text": "Javascript"
},
{
"code": "const _ = require('lodash'); let x = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']; let vowelArray = _.remove(x, function(n) { let vowels = ['a', 'e', 'i', 'o', 'u']; for (let i = 0; i < 5; i++) { if (n === vowels[i]) { return true; } }});",
"e": 1350,
"s": 1056,
"text": null
},
{
"code": null,
"e": 1359,
"s": 1350,
"text": "Output: "
},
{
"code": null,
"e": 1449,
"s": 1359,
"text": "Original Array [ 'b', 'c', 'd', 'f', 'g', 'h' ]\nRemoved element array [ 'a', 'e', 'i' ]"
},
{
"code": null,
"e": 1563,
"s": 1449,
"text": "Example 3: This example removes all the integers from a given array containing floats, characters, and integers. "
},
{
"code": null,
"e": 1574,
"s": 1563,
"text": "Javascript"
},
{
"code": "let x = ['a', 'b', 1, 5.6, 'e', -7, 'g', 4, 10.8]; let intsArray = _.remove(x, function(n) { return Number.isInteger(n);}); console.log('Original Array ', x);console.log('Removed element array ', intsArray);",
"e": 1792,
"s": 1574,
"text": null
},
{
"code": null,
"e": 1801,
"s": 1792,
"text": "Output: "
},
{
"code": null,
"e": 1887,
"s": 1801,
"text": "Original Array [ 'a', 'b', 5.6, 'e', 'g', 10.8 ]\nRemoved element array [ 1, -7, 4 ]"
},
{
"code": null,
"e": 2039,
"s": 1887,
"text": "Note: This will not work in normal JavaScript because it requires the library lodash to be installed.Reference: https://lodash.com/docs/4.17.15#remove "
},
{
"code": null,
"e": 2057,
"s": 2039,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 2072,
"s": 2057,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 2090,
"s": 2072,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 2101,
"s": 2090,
"text": "JavaScript"
},
{
"code": null,
"e": 2118,
"s": 2101,
"text": "Web Technologies"
},
{
"code": null,
"e": 2216,
"s": 2118,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2277,
"s": 2216,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2349,
"s": 2277,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2389,
"s": 2349,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2430,
"s": 2389,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 2482,
"s": 2430,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2515,
"s": 2482,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2577,
"s": 2515,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2638,
"s": 2577,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2688,
"s": 2638,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to Write Data into Excel Sheet using Java?
|
27 Nov, 2020
Handling files is an important part of any programming language. Java provides various in-built methods for creating, reading, updating, and deleting files. These methods are provided by the File class which is present in the java.io package. To perform file operations, Java uses the stream class.
To do operations in excel sheets using JAVA, it comes in handy to use the CSV files because CSV files can easily be used with Microsoft Excel, Google spreadsheets, and almost all other spreadsheets available.
To write data into an excel sheet itself using poi :
1. Create a blank workbook.
XSSFWorkbook workbook = new XSSFWorkbook();
2. Create a sheet and name it.
XSSFSheet spreadsheet = workbook.createSheet(" Student Data ");
3. Create a row
Row row = sheet.createRow(rownum++);
4. Add cells to the sheet.
5. Repeat Steps 3 and 4 to write the complete data.
Prerequisite: Add all jar files downloaded from Apache POI download site in Java Program’s build path.
Example:
Java
// Java program to write data in excel sheet using java code import java.io.File;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.xssf.usermodel.XSSFRow;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.FileOutputStream;import java.util.Map;import java.util.Set;import java.util.TreeMap; public class WriteDataToExcel { // any exceptions need to be caught public static void main(String[] args) throws Exception { // workbook object XSSFWorkbook workbook = new XSSFWorkbook(); // spreadsheet object XSSFSheet spreadsheet = workbook.createSheet(" Student Data "); // creating a row object XSSFRow row; // This data needs to be written (Object[]) Map<String, Object[]> studentData = new TreeMap<String, Object[]>(); studentData.put( "1", new Object[] { "Roll No", "NAME", "Year" }); studentData.put("2", new Object[] { "128", "Aditya", "2nd year" }); studentData.put( "3", new Object[] { "129", "Narayana", "2nd year" }); studentData.put("4", new Object[] { "130", "Mohan", "2nd year" }); studentData.put("5", new Object[] { "131", "Radha", "2nd year" }); studentData.put("6", new Object[] { "132", "Gopal", "2nd year" }); Set<String> keyid = studentData.keySet(); int rowid = 0; // writing the data into the sheets... for (String key : keyid) { row = spreadsheet.createRow(rowid++); Object[] objectArr = studentData.get(key); int cellid = 0; for (Object obj : objectArr) { Cell cell = row.createCell(cellid++); cell.setCellValue((String)obj); } } // .xlsx is the format for Excel Sheets... // writing the workbook into the file... FileOutputStream out = new FileOutputStream( new File("C:/savedexcel/GFGsheet.xlsx")); workbook.write(out); out.close(); }}
Output:
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.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Nov, 2020"
},
{
"code": null,
"e": 353,
"s": 54,
"text": "Handling files is an important part of any programming language. Java provides various in-built methods for creating, reading, updating, and deleting files. These methods are provided by the File class which is present in the java.io package. To perform file operations, Java uses the stream class."
},
{
"code": null,
"e": 562,
"s": 353,
"text": "To do operations in excel sheets using JAVA, it comes in handy to use the CSV files because CSV files can easily be used with Microsoft Excel, Google spreadsheets, and almost all other spreadsheets available."
},
{
"code": null,
"e": 615,
"s": 562,
"text": "To write data into an excel sheet itself using poi :"
},
{
"code": null,
"e": 643,
"s": 615,
"text": "1. Create a blank workbook."
},
{
"code": null,
"e": 687,
"s": 643,
"text": "XSSFWorkbook workbook = new XSSFWorkbook();"
},
{
"code": null,
"e": 848,
"s": 687,
"text": "2. Create a sheet and name it. "
},
{
"code": null,
"e": 912,
"s": 848,
"text": "XSSFSheet spreadsheet = workbook.createSheet(\" Student Data \");"
},
{
"code": null,
"e": 1092,
"s": 912,
"text": "3. Create a row "
},
{
"code": null,
"e": 1129,
"s": 1092,
"text": "Row row = sheet.createRow(rownum++);"
},
{
"code": null,
"e": 1156,
"s": 1129,
"text": "4. Add cells to the sheet."
},
{
"code": null,
"e": 1208,
"s": 1156,
"text": "5. Repeat Steps 3 and 4 to write the complete data."
},
{
"code": null,
"e": 1311,
"s": 1208,
"text": "Prerequisite: Add all jar files downloaded from Apache POI download site in Java Program’s build path."
},
{
"code": null,
"e": 1320,
"s": 1311,
"text": "Example:"
},
{
"code": null,
"e": 1325,
"s": 1320,
"text": "Java"
},
{
"code": "// Java program to write data in excel sheet using java code import java.io.File;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.xssf.usermodel.XSSFRow;import org.apache.poi.xssf.usermodel.XSSFSheet;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import java.io.FileOutputStream;import java.util.Map;import java.util.Set;import java.util.TreeMap; public class WriteDataToExcel { // any exceptions need to be caught public static void main(String[] args) throws Exception { // workbook object XSSFWorkbook workbook = new XSSFWorkbook(); // spreadsheet object XSSFSheet spreadsheet = workbook.createSheet(\" Student Data \"); // creating a row object XSSFRow row; // This data needs to be written (Object[]) Map<String, Object[]> studentData = new TreeMap<String, Object[]>(); studentData.put( \"1\", new Object[] { \"Roll No\", \"NAME\", \"Year\" }); studentData.put(\"2\", new Object[] { \"128\", \"Aditya\", \"2nd year\" }); studentData.put( \"3\", new Object[] { \"129\", \"Narayana\", \"2nd year\" }); studentData.put(\"4\", new Object[] { \"130\", \"Mohan\", \"2nd year\" }); studentData.put(\"5\", new Object[] { \"131\", \"Radha\", \"2nd year\" }); studentData.put(\"6\", new Object[] { \"132\", \"Gopal\", \"2nd year\" }); Set<String> keyid = studentData.keySet(); int rowid = 0; // writing the data into the sheets... for (String key : keyid) { row = spreadsheet.createRow(rowid++); Object[] objectArr = studentData.get(key); int cellid = 0; for (Object obj : objectArr) { Cell cell = row.createCell(cellid++); cell.setCellValue((String)obj); } } // .xlsx is the format for Excel Sheets... // writing the workbook into the file... FileOutputStream out = new FileOutputStream( new File(\"C:/savedexcel/GFGsheet.xlsx\")); workbook.write(out); out.close(); }}",
"e": 3606,
"s": 1325,
"text": null
},
{
"code": null,
"e": 3614,
"s": 3606,
"text": "Output:"
},
{
"code": null,
"e": 3621,
"s": 3614,
"text": "Picked"
},
{
"code": null,
"e": 3645,
"s": 3621,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3650,
"s": 3645,
"text": "Java"
},
{
"code": null,
"e": 3664,
"s": 3650,
"text": "Java Programs"
},
{
"code": null,
"e": 3683,
"s": 3664,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3688,
"s": 3683,
"text": "Java"
},
{
"code": null,
"e": 3786,
"s": 3688,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3837,
"s": 3786,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3868,
"s": 3837,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3887,
"s": 3868,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3917,
"s": 3887,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3935,
"s": 3917,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3963,
"s": 3935,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 3989,
"s": 3963,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4033,
"s": 3989,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 4067,
"s": 4033,
"text": "Convert Double to Integer in Java"
}
] |
Jython - Loops
|
In general, statements in a program are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Statements that provide such repetition capability are called looping statements.
In Jython, a loop can be formed by two statements, which are −
The while statement and
The while statement and
The for statement
The for statement
A while loop statement in Jython is similar to that in Java. It repeatedly executes a block of statements as long as a given condition is true. The following flowchart describes the behavior of a while loop.
The general syntax of the while statement is given below.
while expression:
statement(s)
The following Jython code uses the while loop to repeatedly increment and print value of a variable until it is less than zero.
count = 0
while count<10:
count = count+1
print "count = ",count
print "Good Bye!"
Output − The output would be as follows.
count = 1
count = 2
count = 3
count = 4
count = 5
count = 6
count = 7
count = 8
count = 9
count = 10
Good Bye!
The FOR loop in Jython is not a counted loop as in Java. Instead, it has the ability to traverse elements in a sequence data type such as string, list or tuple. The general syntax of the FOR statement in Jython is as shown below −
for iterating_var in sequence:
statements(s)
We can display each character in a string, as well as each item in a List or Tuple by using the FOR statement as shown below −
#each letter in string
for letter in 'Python':
print 'Current Letter :', letter
Output − The output would be as follows.
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Let us consider another instance as follows.
#each item in list
libs = [‘PyQt’, 'WxPython', 'Tkinter']
for lib in libs: # Second Example
print 'Current library :', lib
Output − The output will be as follows.
Current library : PyQt
Current library : WxPython
Current library : Tkinter
Here is another instance to consider.
#each item in tuple
libs = (‘PyQt’, 'WxPython', 'Tkinter')
for lib in libs: # Second Example
print 'Current library :', lib
Output − The output of the above program is as follows.
Current library : PyQt
Current library : WxPython
Current library : Tkinter
In Jython, the for statement is also used to iterate over a list of numbers generated by range() function. The range() function takes following form −
range[([start],stop,[step])
The start and step parameters are 0 and 1 by default. The last number generated is stop step. The FOR statement traverses the list formed by the range() function. For example −
for num in range(5):
print num
It produces the following output −
0
1
2
3
4
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2405,
"s": 2081,
"text": "In general, statements in a program are executed sequentially: The first statement in a function is executed first, followed by the second, and so on. There may be a situation when you need to execute a block of code several number of times. Statements that provide such repetition capability are called looping statements."
},
{
"code": null,
"e": 2468,
"s": 2405,
"text": "In Jython, a loop can be formed by two statements, which are −"
},
{
"code": null,
"e": 2492,
"s": 2468,
"text": "The while statement and"
},
{
"code": null,
"e": 2516,
"s": 2492,
"text": "The while statement and"
},
{
"code": null,
"e": 2534,
"s": 2516,
"text": "The for statement"
},
{
"code": null,
"e": 2552,
"s": 2534,
"text": "The for statement"
},
{
"code": null,
"e": 2760,
"s": 2552,
"text": "A while loop statement in Jython is similar to that in Java. It repeatedly executes a block of statements as long as a given condition is true. The following flowchart describes the behavior of a while loop."
},
{
"code": null,
"e": 2818,
"s": 2760,
"text": "The general syntax of the while statement is given below."
},
{
"code": null,
"e": 2853,
"s": 2818,
"text": "while expression:\n statement(s)\n"
},
{
"code": null,
"e": 2981,
"s": 2853,
"text": "The following Jython code uses the while loop to repeatedly increment and print value of a variable until it is less than zero."
},
{
"code": null,
"e": 3070,
"s": 2981,
"text": "count = 0\nwhile count<10:\n count = count+1\n print \"count = \",count\nprint \"Good Bye!\""
},
{
"code": null,
"e": 3111,
"s": 3070,
"text": "Output − The output would be as follows."
},
{
"code": null,
"e": 3233,
"s": 3111,
"text": "count = 1\ncount = 2\ncount = 3\ncount = 4\ncount = 5\ncount = 6\ncount = 7\ncount = 8\ncount = 9\ncount = 10\nGood Bye!\n"
},
{
"code": null,
"e": 3464,
"s": 3233,
"text": "The FOR loop in Jython is not a counted loop as in Java. Instead, it has the ability to traverse elements in a sequence data type such as string, list or tuple. The general syntax of the FOR statement in Jython is as shown below −"
},
{
"code": null,
"e": 3513,
"s": 3464,
"text": "for iterating_var in sequence:\n statements(s)\n"
},
{
"code": null,
"e": 3640,
"s": 3513,
"text": "We can display each character in a string, as well as each item in a List or Tuple by using the FOR statement as shown below −"
},
{
"code": null,
"e": 3723,
"s": 3640,
"text": "#each letter in string\nfor letter in 'Python':\n print 'Current Letter :', letter"
},
{
"code": null,
"e": 3764,
"s": 3723,
"text": "Output − The output would be as follows."
},
{
"code": null,
"e": 3879,
"s": 3764,
"text": "Current Letter : P\nCurrent Letter : y\nCurrent Letter : t\nCurrent Letter : h\nCurrent Letter : o\nCurrent Letter : n\n"
},
{
"code": null,
"e": 3924,
"s": 3879,
"text": "Let us consider another instance as follows."
},
{
"code": null,
"e": 4058,
"s": 3924,
"text": "#each item in list\nlibs = [‘PyQt’, 'WxPython', 'Tkinter']\nfor lib in libs: # Second Example\n print 'Current library :', lib"
},
{
"code": null,
"e": 4098,
"s": 4058,
"text": "Output − The output will be as follows."
},
{
"code": null,
"e": 4175,
"s": 4098,
"text": "Current library : PyQt\nCurrent library : WxPython\nCurrent library : Tkinter\n"
},
{
"code": null,
"e": 4213,
"s": 4175,
"text": "Here is another instance to consider."
},
{
"code": null,
"e": 4348,
"s": 4213,
"text": "#each item in tuple\nlibs = (‘PyQt’, 'WxPython', 'Tkinter')\nfor lib in libs: # Second Example\n print 'Current library :', lib"
},
{
"code": null,
"e": 4404,
"s": 4348,
"text": "Output − The output of the above program is as follows."
},
{
"code": null,
"e": 4481,
"s": 4404,
"text": "Current library : PyQt\nCurrent library : WxPython\nCurrent library : Tkinter\n"
},
{
"code": null,
"e": 4632,
"s": 4481,
"text": "In Jython, the for statement is also used to iterate over a list of numbers generated by range() function. The range() function takes following form −"
},
{
"code": null,
"e": 4661,
"s": 4632,
"text": "range[([start],stop,[step])\n"
},
{
"code": null,
"e": 4838,
"s": 4661,
"text": "The start and step parameters are 0 and 1 by default. The last number generated is stop step. The FOR statement traverses the list formed by the range() function. For example −"
},
{
"code": null,
"e": 4872,
"s": 4838,
"text": "for num in range(5):\n print num"
},
{
"code": null,
"e": 4907,
"s": 4872,
"text": "It produces the following output −"
},
{
"code": null,
"e": 4918,
"s": 4907,
"text": "0\n1\n2\n3\n4\n"
},
{
"code": null,
"e": 4925,
"s": 4918,
"text": " Print"
},
{
"code": null,
"e": 4936,
"s": 4925,
"text": " Add Notes"
}
] |
How to create side by side histograms in base R?
|
To create side by side histograms in base R, we first need to create a histogram using hist function by defining a larger limit of X-axis with xlim argument. After that we can create another histogram that has the larger mean and smaller standard deviation so that the bars do not clash with each other and add=T argument must also be added inside the second hist function.
Live Demo
hist(rnorm(5000,mean=5,sd=2.1),col="green",xlim=c(1,20))
hist(rnorm(5000,mean=15,sd=1.25),col="red",add=T)
|
[
{
"code": null,
"e": 1436,
"s": 1062,
"text": "To create side by side histograms in base R, we first need to create a histogram using hist function by defining a larger limit of X-axis with xlim argument. After that we can create another histogram that has the larger mean and smaller standard deviation so that the bars do not clash with each other and add=T argument must also be added inside the second hist function."
},
{
"code": null,
"e": 1447,
"s": 1436,
"text": " Live Demo"
},
{
"code": null,
"e": 1504,
"s": 1447,
"text": "hist(rnorm(5000,mean=5,sd=2.1),col=\"green\",xlim=c(1,20))"
},
{
"code": null,
"e": 1554,
"s": 1504,
"text": "hist(rnorm(5000,mean=15,sd=1.25),col=\"red\",add=T)"
}
] |
Assembly - Variables
|
NASM provides various define directives for reserving storage space for variables. The define assembler directive is used for allocation of storage space. It can be used to reserve as well as initialize one or more bytes.
The syntax for storage allocation statement for initialized data is −
[variable-name] define-directive initial-value [,initial-value]...
Where, variable-name is the identifier for each storage space. The assembler associates an offset value for each variable name defined in the data segment.
There are five basic forms of the define directive −
Following are some examples of using define directives −
choice DB 'y'
number DW 12345
neg_number DW -12345
big_number DQ 123456789
real_number1 DD 1.234
real_number2 DQ 123.456
Please note that −
Each byte of character is stored as its ASCII value in hexadecimal.
Each byte of character is stored as its ASCII value in hexadecimal.
Each decimal value is automatically converted to its 16-bit binary equivalent and stored as a hexadecimal number.
Each decimal value is automatically converted to its 16-bit binary equivalent and stored as a hexadecimal number.
Processor uses the little-endian byte ordering.
Processor uses the little-endian byte ordering.
Negative numbers are converted to its 2's complement representation.
Negative numbers are converted to its 2's complement representation.
Short and long floating-point numbers are represented using 32 or 64 bits, respectively.
Short and long floating-point numbers are represented using 32 or 64 bits, respectively.
The following program shows the use of define directive −
section .text
global _start ;must be declared for linker (gcc)
_start: ;tell linker entry point
mov edx,1 ;message length
mov ecx,choice ;message to write
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
choice DB 'y'
When the above code is compiled and executed, it produces the following result −
y
The reserve directives are used for reserving space for uninitialized data. The reserve directives take a single operand that specifies the number of units of space to be reserved. Each define directive has a related reserve directive.
There are five basic forms of the reserve directive −
You can have multiple data definition statements in a program. For example −
choice DB 'Y' ;ASCII of y = 79H
number1 DW 12345 ;12345D = 3039H
number2 DD 12345679 ;123456789D = 75BCD15H
The assembler allocates contiguous memory for multiple variable definitions.
The TIMES directive allows multiple initializations to the same value. For example, an array named marks of size 9 can be defined and initialized to zero using the following statement −
marks TIMES 9 DW 0
The TIMES directive is useful in defining arrays and tables. The following program displays 9 asterisks on the screen −
section .text
global _start ;must be declared for linker (ld)
_start: ;tell linker entry point
mov edx,9 ;message length
mov ecx, stars ;message to write
mov ebx,1 ;file descriptor (stdout)
mov eax,4 ;system call number (sys_write)
int 0x80 ;call kernel
mov eax,1 ;system call number (sys_exit)
int 0x80 ;call kernel
section .data
stars times 9 db '*'
When the above code is compiled and executed, it produces the following result −
*********
46 Lectures
2 hours
Frahaan Hussain
23 Lectures
12 hours
Uplatz
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2307,
"s": 2085,
"text": "NASM provides various define directives for reserving storage space for variables. The define assembler directive is used for allocation of storage space. It can be used to reserve as well as initialize one or more bytes."
},
{
"code": null,
"e": 2377,
"s": 2307,
"text": "The syntax for storage allocation statement for initialized data is −"
},
{
"code": null,
"e": 2453,
"s": 2377,
"text": "[variable-name] define-directive initial-value [,initial-value]...\n"
},
{
"code": null,
"e": 2609,
"s": 2453,
"text": "Where, variable-name is the identifier for each storage space. The assembler associates an offset value for each variable name defined in the data segment."
},
{
"code": null,
"e": 2662,
"s": 2609,
"text": "There are five basic forms of the define directive −"
},
{
"code": null,
"e": 2719,
"s": 2662,
"text": "Following are some examples of using define directives −"
},
{
"code": null,
"e": 2842,
"s": 2719,
"text": "choice\t\tDB\t'y'\nnumber\t\tDW\t12345\nneg_number\tDW\t-12345\nbig_number\tDQ\t123456789\nreal_number1\tDD\t1.234\nreal_number2\tDQ\t123.456"
},
{
"code": null,
"e": 2861,
"s": 2842,
"text": "Please note that −"
},
{
"code": null,
"e": 2929,
"s": 2861,
"text": "Each byte of character is stored as its ASCII value in hexadecimal."
},
{
"code": null,
"e": 2997,
"s": 2929,
"text": "Each byte of character is stored as its ASCII value in hexadecimal."
},
{
"code": null,
"e": 3111,
"s": 2997,
"text": "Each decimal value is automatically converted to its 16-bit binary equivalent and stored as a hexadecimal number."
},
{
"code": null,
"e": 3225,
"s": 3111,
"text": "Each decimal value is automatically converted to its 16-bit binary equivalent and stored as a hexadecimal number."
},
{
"code": null,
"e": 3273,
"s": 3225,
"text": "Processor uses the little-endian byte ordering."
},
{
"code": null,
"e": 3321,
"s": 3273,
"text": "Processor uses the little-endian byte ordering."
},
{
"code": null,
"e": 3391,
"s": 3321,
"text": "Negative numbers are converted to its 2's complement representation. "
},
{
"code": null,
"e": 3461,
"s": 3391,
"text": "Negative numbers are converted to its 2's complement representation. "
},
{
"code": null,
"e": 3550,
"s": 3461,
"text": "Short and long floating-point numbers are represented using 32 or 64 bits, respectively."
},
{
"code": null,
"e": 3639,
"s": 3550,
"text": "Short and long floating-point numbers are represented using 32 or 64 bits, respectively."
},
{
"code": null,
"e": 3697,
"s": 3639,
"text": "The following program shows the use of define directive −"
},
{
"code": null,
"e": 4123,
"s": 3697,
"text": "section .text\n global _start ;must be declared for linker (gcc)\n\t\n_start: ;tell linker entry point\n mov\tedx,1\t\t ;message length\n mov\tecx,choice ;message to write\n mov\tebx,1\t\t ;file descriptor (stdout)\n mov\teax,4\t\t ;system call number (sys_write)\n int\t0x80\t\t ;call kernel\n\n mov\teax,1\t\t ;system call number (sys_exit)\n int\t0x80\t\t ;call kernel\n\nsection .data\nchoice DB 'y'"
},
{
"code": null,
"e": 4204,
"s": 4123,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4207,
"s": 4204,
"text": "y\n"
},
{
"code": null,
"e": 4443,
"s": 4207,
"text": "The reserve directives are used for reserving space for uninitialized data. The reserve directives take a single operand that specifies the number of units of space to be reserved. Each define directive has a related reserve directive."
},
{
"code": null,
"e": 4497,
"s": 4443,
"text": "There are five basic forms of the reserve directive −"
},
{
"code": null,
"e": 4574,
"s": 4497,
"text": "You can have multiple data definition statements in a program. For example −"
},
{
"code": null,
"e": 4698,
"s": 4574,
"text": "choice\t DB \t'Y' \t\t ;ASCII of y = 79H\nnumber1\t DW \t12345 \t ;12345D = 3039H\nnumber2 DD 12345679 ;123456789D = 75BCD15H"
},
{
"code": null,
"e": 4775,
"s": 4698,
"text": "The assembler allocates contiguous memory for multiple variable definitions."
},
{
"code": null,
"e": 4961,
"s": 4775,
"text": "The TIMES directive allows multiple initializations to the same value. For example, an array named marks of size 9 can be defined and initialized to zero using the following statement −"
},
{
"code": null,
"e": 4985,
"s": 4961,
"text": "marks TIMES 9 DW 0\n"
},
{
"code": null,
"e": 5105,
"s": 4985,
"text": "The TIMES directive is useful in defining arrays and tables. The following program displays 9 asterisks on the screen −"
},
{
"code": null,
"e": 5516,
"s": 5105,
"text": "section\t.text\n global _start ;must be declared for linker (ld)\n\t\n_start: ;tell linker entry point\n mov\tedx,9\t\t;message length\n mov\tecx, stars\t;message to write\n mov\tebx,1\t\t;file descriptor (stdout)\n mov\teax,4\t\t;system call number (sys_write)\n int\t0x80\t\t;call kernel\n\n mov\teax,1\t\t;system call number (sys_exit)\n int\t0x80\t\t;call kernel\n\nsection\t.data\nstars times 9 db '*'"
},
{
"code": null,
"e": 5597,
"s": 5516,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5608,
"s": 5597,
"text": "*********\n"
},
{
"code": null,
"e": 5641,
"s": 5608,
"text": "\n 46 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 5658,
"s": 5641,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 5692,
"s": 5658,
"text": "\n 23 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 5700,
"s": 5692,
"text": " Uplatz"
},
{
"code": null,
"e": 5707,
"s": 5700,
"text": " Print"
},
{
"code": null,
"e": 5718,
"s": 5707,
"text": " Add Notes"
}
] |
C# | Stack Class - GeeksforGeeks
|
20 Feb, 2019
Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. This class comes under System.Collections namespace.
Characteristics of Stack Class:
The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation.
If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation.
Stack accepts null as a valid value and allows duplicate elements.
Example:
// C# code to create a Stackusing System;using System.Collections;class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push("1st Element"); myStack.Push("2nd Element"); myStack.Push("3rd Element"); myStack.Push("4th Element"); myStack.Push("5th Element"); myStack.Push("6th Element"); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); // Displaying the top element of Stack // without removing it from the Stack Console.WriteLine("Element at the top is : " + myStack.Peek()); // Displaying the top element of Stack // without removing it from the Stack Console.WriteLine("Element at the top is : " + myStack.Peek()); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); }}
Output:
Total number of elements in the Stack are : 6
Element at the top is : 6th Element
Element at the top is : 6th Element
Total number of elements in the Stack are : 6
Example:
// C# code to Get the number of// elements contained in the Stackusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push("Chandigarh"); myStack.Push("Delhi"); myStack.Push("Noida"); myStack.Push("Himachal"); myStack.Push("Punjab"); myStack.Push("Jammu"); // Displaying the count of elements // contained in the Stack Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); }}
Output:
Total number of elements in the Stack are : 6
Example :
// C# code to Remove all// objects from the Stackusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push("1st Element"); myStack.Push("2nd Element"); myStack.Push("3rd Element"); myStack.Push("4th Element"); myStack.Push("5th Element"); myStack.Push("6th Element"); // Displaying the count of elements // contained in the Stack before // removing all the elements Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); // Removing all elements from Stack myStack.Clear(); // Displaying the count of elements // contained in the Stack after // removing all the elements Console.Write("Total number of elements in the Stack are : "); Console.WriteLine(myStack.Count); }}
Total number of elements in the Stack are : 6
Total number of elements in the Stack are : 0
Example :
// C# code to Check if a Stack// contains an elementusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack of strings Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push("Geeks"); myStack.Push("Geeks Classes"); myStack.Push("Noida"); myStack.Push("Data Structures"); myStack.Push("GeeksforGeeks"); // Checking whether the element is // present in the Stack or not // The function returns True if the // element is present in the Stack, else // returns False Console.WriteLine(myStack.Contains("GeeksforGeeks")); }}
True
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Collections-Stack
CSharp-Stack-Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between Abstract Class and Interface in C#
C# | How to check whether a List contains a specified element
C# | Method Overriding
C# | IsNullOrEmpty() Method
C# Dictionary with examples
String.Split() Method in C# with Examples
Difference between Ref and Out keywords in C#
C# | Arrays of Strings
C# | Delegates
Top 50 C# Interview Questions & Answers
|
[
{
"code": null,
"e": 22897,
"s": 22869,
"text": "\n20 Feb, 2019"
},
{
"code": null,
"e": 23192,
"s": 22897,
"text": "Stack represents a last-in, first out collection of object. It is used when you need a last-in, first-out access to items. When you add an item in the list, it is called pushing the item and when you remove it, it is called popping the item. This class comes under System.Collections namespace."
},
{
"code": null,
"e": 23224,
"s": 23192,
"text": "Characteristics of Stack Class:"
},
{
"code": null,
"e": 23402,
"s": 23224,
"text": "The capacity of a Stack is the number of elements the Stack can hold. As elements are added to a Stack, the capacity is automatically increased as required through reallocation."
},
{
"code": null,
"e": 23624,
"s": 23402,
"text": "If Count is less than the capacity of the stack, Push is an O(1) operation. If the capacity needs to be increased to accommodate the new element, Push becomes an O(n) operation, where n is Count. Pop is an O(1) operation."
},
{
"code": null,
"e": 23691,
"s": 23624,
"text": "Stack accepts null as a valid value and allows duplicate elements."
},
{
"code": null,
"e": 23700,
"s": 23691,
"text": "Example:"
},
{
"code": "// C# code to create a Stackusing System;using System.Collections;class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(\"1st Element\"); myStack.Push(\"2nd Element\"); myStack.Push(\"3rd Element\"); myStack.Push(\"4th Element\"); myStack.Push(\"5th Element\"); myStack.Push(\"6th Element\"); // Displaying the count of elements // contained in the Stack Console.Write(\"Total number of elements in the Stack are : \"); Console.WriteLine(myStack.Count); // Displaying the top element of Stack // without removing it from the Stack Console.WriteLine(\"Element at the top is : \" + myStack.Peek()); // Displaying the top element of Stack // without removing it from the Stack Console.WriteLine(\"Element at the top is : \" + myStack.Peek()); // Displaying the count of elements // contained in the Stack Console.Write(\"Total number of elements in the Stack are : \"); Console.WriteLine(myStack.Count); }}",
"e": 24879,
"s": 23700,
"text": null
},
{
"code": null,
"e": 24887,
"s": 24879,
"text": "Output:"
},
{
"code": null,
"e": 25052,
"s": 24887,
"text": "Total number of elements in the Stack are : 6\nElement at the top is : 6th Element\nElement at the top is : 6th Element\nTotal number of elements in the Stack are : 6\n"
},
{
"code": null,
"e": 25061,
"s": 25052,
"text": "Example:"
},
{
"code": "// C# code to Get the number of// elements contained in the Stackusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(\"Chandigarh\"); myStack.Push(\"Delhi\"); myStack.Push(\"Noida\"); myStack.Push(\"Himachal\"); myStack.Push(\"Punjab\"); myStack.Push(\"Jammu\"); // Displaying the count of elements // contained in the Stack Console.Write(\"Total number of elements in the Stack are : \"); Console.WriteLine(myStack.Count); }}",
"e": 25733,
"s": 25061,
"text": null
},
{
"code": null,
"e": 25741,
"s": 25733,
"text": "Output:"
},
{
"code": null,
"e": 25788,
"s": 25741,
"text": "Total number of elements in the Stack are : 6\n"
},
{
"code": null,
"e": 25798,
"s": 25788,
"text": "Example :"
},
{
"code": "// C# code to Remove all// objects from the Stackusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(\"1st Element\"); myStack.Push(\"2nd Element\"); myStack.Push(\"3rd Element\"); myStack.Push(\"4th Element\"); myStack.Push(\"5th Element\"); myStack.Push(\"6th Element\"); // Displaying the count of elements // contained in the Stack before // removing all the elements Console.Write(\"Total number of elements in the Stack are : \"); Console.WriteLine(myStack.Count); // Removing all elements from Stack myStack.Clear(); // Displaying the count of elements // contained in the Stack after // removing all the elements Console.Write(\"Total number of elements in the Stack are : \"); Console.WriteLine(myStack.Count); }}",
"e": 26827,
"s": 25798,
"text": null
},
{
"code": null,
"e": 26920,
"s": 26827,
"text": "Total number of elements in the Stack are : 6\nTotal number of elements in the Stack are : 0\n"
},
{
"code": null,
"e": 26930,
"s": 26920,
"text": "Example :"
},
{
"code": "// C# code to Check if a Stack// contains an elementusing System;using System.Collections; class GFG { // Driver code public static void Main() { // Creating a Stack of strings Stack myStack = new Stack(); // Inserting the elements into the Stack myStack.Push(\"Geeks\"); myStack.Push(\"Geeks Classes\"); myStack.Push(\"Noida\"); myStack.Push(\"Data Structures\"); myStack.Push(\"GeeksforGeeks\"); // Checking whether the element is // present in the Stack or not // The function returns True if the // element is present in the Stack, else // returns False Console.WriteLine(myStack.Contains(\"GeeksforGeeks\")); }}",
"e": 27654,
"s": 26930,
"text": null
},
{
"code": null,
"e": 27660,
"s": 27654,
"text": "True\n"
},
{
"code": null,
"e": 27671,
"s": 27660,
"text": "Reference:"
},
{
"code": null,
"e": 27764,
"s": 27671,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.stack?view=netframework-4.7.2"
},
{
"code": null,
"e": 27793,
"s": 27764,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 27818,
"s": 27793,
"text": "CSharp-Collections-Stack"
},
{
"code": null,
"e": 27837,
"s": 27818,
"text": "CSharp-Stack-Class"
},
{
"code": null,
"e": 27840,
"s": 27837,
"text": "C#"
},
{
"code": null,
"e": 27938,
"s": 27840,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27947,
"s": 27938,
"text": "Comments"
},
{
"code": null,
"e": 27960,
"s": 27947,
"text": "Old Comments"
},
{
"code": null,
"e": 28014,
"s": 27960,
"text": "Difference between Abstract Class and Interface in C#"
},
{
"code": null,
"e": 28076,
"s": 28014,
"text": "C# | How to check whether a List contains a specified element"
},
{
"code": null,
"e": 28099,
"s": 28076,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28127,
"s": 28099,
"text": "C# | IsNullOrEmpty() Method"
},
{
"code": null,
"e": 28155,
"s": 28127,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 28197,
"s": 28155,
"text": "String.Split() Method in C# with Examples"
},
{
"code": null,
"e": 28243,
"s": 28197,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 28266,
"s": 28243,
"text": "C# | Arrays of Strings"
},
{
"code": null,
"e": 28281,
"s": 28266,
"text": "C# | Delegates"
}
] |
A Free And Powerful Labelling Tool Every Data Scientist Should Know | by Lai Woen Yon | Towards Data Science
|
As a data scientist, you will definitely need to train models to meet your organization’s needs. Most of the time, you require labelled data from within your company in order to build a customized solution.
You’re approached by a product manager one day who wants you to build a named entity recognition model to improve the quality of the downstream data science product. Due to the short time frame this product needs to be launched, he hired a bunch of human labellers to assist you. What should you do next?
“ Give us the tools, and we will finish the job “
by Winston Churchill
The task objective is clear, manpower is ample, and a deadline is set. What’s next? A useful labelling tool. Please note the emphasis on “useful”. But what is it that I mean by “useful”? The tool should at least give you the ability to:
Track the labelling quality, on-premises or in the cloud, at any time. The annotation staff can be informed if they are not following the instructions before the entire labelling project is completed.Keep track of the progress of every annotator. The deadline is given to you, so it is imperative that every annotator be given a specific deadline for finishing their labelling. As a project leader, you should be able to track the progress to ensure everyone stays on track.Allow multiple annotations to work together. Bias is one of the most problematic topics in machine learning. As a data scientist, you do not want annotation bias to affect your model after spending several days or weeks training your model, only to find out that it is biased. As a possible solution, multiple authors could collaborate on the same task/article and only approve labels that are unanimously accepted.Post-process your labelling result with the least amount of effort. One particular aspect you will appreciate is the ease with which you can handle the labelled data. In my experience, the JSON format is the easiest to work with when I am working on labelling projects for clients. It would be great if the tool could support multiple types of formats for importing and exporting data.Provide a user-friendly interface to your human annotators. Developing a good data labelling tool for me is based primarily on this factor. Not only was I responsible for preparing the client documentation, but I also had to train the human annotations on how to use the labelling tool with as little human error as possible. You can therefore save yourself from a great deal of hassle if you use an easy-to-use labelling tool.Code your labelling interface to suit your needs. I’m sure, as a programmer, you’d like your tool to be controlled by code. Coding to make the interface customized would allow the time to be dedicated to other important tasks.
Track the labelling quality, on-premises or in the cloud, at any time. The annotation staff can be informed if they are not following the instructions before the entire labelling project is completed.
Keep track of the progress of every annotator. The deadline is given to you, so it is imperative that every annotator be given a specific deadline for finishing their labelling. As a project leader, you should be able to track the progress to ensure everyone stays on track.
Allow multiple annotations to work together. Bias is one of the most problematic topics in machine learning. As a data scientist, you do not want annotation bias to affect your model after spending several days or weeks training your model, only to find out that it is biased. As a possible solution, multiple authors could collaborate on the same task/article and only approve labels that are unanimously accepted.
Post-process your labelling result with the least amount of effort. One particular aspect you will appreciate is the ease with which you can handle the labelled data. In my experience, the JSON format is the easiest to work with when I am working on labelling projects for clients. It would be great if the tool could support multiple types of formats for importing and exporting data.
Provide a user-friendly interface to your human annotators. Developing a good data labelling tool for me is based primarily on this factor. Not only was I responsible for preparing the client documentation, but I also had to train the human annotations on how to use the labelling tool with as little human error as possible. You can therefore save yourself from a great deal of hassle if you use an easy-to-use labelling tool.
Code your labelling interface to suit your needs. I’m sure, as a programmer, you’d like your tool to be controlled by code. Coding to make the interface customized would allow the time to be dedicated to other important tasks.
These are the features I would at least like my labelling tool to have. A tool like this could cost you thousands of dollars and countless hours of labour to develop. What is the best way to find such an off-the-shelf tool ... for free?
Before I begin, let me disclaim the following: I do not work for Label Studio and I am not affiliated with Label Studio. It is simply my personal experience from working on a client’s project.
github.com
As I was developing a system to label data on a client’s behalf, I ran into this tool. In light of the fact that it is an open-source and free data labelling tool, I am quite surprised at its flexibility and functionality. Using a few simple steps, I will show you how you can construct a simple NER labelling interface.
You can easily set up Label Studio by following the instructions in the Github repository. It supports both installations on the local machine and deployment in the cloud. As part of my work for a client, I built and deployed the tool using Docker. It allows him to store the data locally since credentials are the main requirement for his business. To demonstrate the tool, I am going to use Heroku Buttons. You may deploy it in any manner you deem acceptable for your business.
You will be able to see the project page after you log in. The process of creating a project is illustrated in the gif above. For this project, I call it NER.
We will prepare a sample project with only two articles (in Label Studio, they call these "tasks"). You are free add more if you want to.
The sample articles are copied from these two articles:
https://www.reuters.com/world/asia-pacific/japans-mount-aso-erupts-alert-level-raised-2021-10-20/
https://www.reuters.com/technology/bitcoin-sits-below-all-time-high-after-us-etf-debut-2021-10-20/
https://www.reuters.com/world/asia-pacific/japans-mount-aso-erupts-alert-level-raised-2021-10-20/
https://www.reuters.com/technology/bitcoin-sits-below-all-time-high-after-us-etf-debut-2021-10-20/
import requests
from bs4 import BeautifulSoup
import json
from google.colab import files
Using Beautifulsoup to crawl the article body automatically
%time
task_texts = []
task_links = ["https://www.reuters.com/world/asia-pacific/japans-mount-aso-erupts-alert-level-raised-2021-10-20/",
"https://www.reuters.com/technology/bitcoin-sits-below-all-time-high-after-us-etf-debut-2021-10-20/"]
for task_link in task_links:
page = requests.get(task_link)
if page.status_code == 200:
soup = BeautifulSoup(page.content, 'html.parser')
task_texts.append(''.join([p.getText() for p in soup.find_all('p', {'data-testid': lambda value: value and "paragraph" in value})]))
else:
print('Website returns non-parsable content')
raise
CPU times: user 2 μs, sys: 0 ns, total: 2 μs
Wall time: 5.48 μs
Populate the crawled articles into a list format accepted by label studio
%time
label_studio_input = []
for task_text in task_texts:
label_studio_input.append({"data":{"text":task_text}})
CPU times: user 3 μs, sys: 0 ns, total: 3 μs
Wall time: 7.39 μs
print(json.dumps(label_studio_input[0], indent=4, sort_keys=True, ensure_ascii=False))
{
"data": {
"text": "TOKYO, Oct 20 (Reuters) - A volcano erupted in Japan on Wednesday, blasting ash several miles into the sky and prompting officials to warn against the threat of lava flows and falling rocks, but there were no immediate reports of casualties or damage.Mount Aso, a tourist destination on the main southern island of Kyushu, sent plumes of ash 3.5 km (2.2 miles) high when it erupted at about 11:43 a.m. (0243 GMT), the Japan Meteorological Agency said.It raised the alert level for the volcano to 3 on a scale of 5, telling people not to approach, and warned of a risk of large falling rocks and pyroclastic flows within a radius of about 1 km (0.6 mile) around the mountain's Nakadake crater.The government is checking to determine the status of a number of climbers on the mountain at the time, Chief Cabinet Secretary Hirokazu Matsuno told reporters, but added that there were no reports of casualties.Television networks broadcast images of a dark cloud of ash looming over the volcano that swiftly obscured large swathes of the mountain.Ash falls from the 1,592-metre (5,222-foot) mountain in the prefecture of Kumamoto are expected to shower nearby towns until late afternoon, the weather agency added.Mount Aso had a small eruption in 2019, while Japan's worst volcanic disaster in nearly 90 years killed 63 people on Mount Ontake in September 2014."
}
}
Save file to temporary folder and automatically download the file
with open("label_studio_input.json",'w') as j:
json.dump(label_studio_input, j)
files.download("label_studio_input.json")
Our next step is to upload our own data to prepare for labelling. For your convenience, I have created a script to help you get started. As a starting point, I used two articles from Reuters.com. Run the script above in Colab, and you should be able to view a list of tasks in JSON format like this:
[ { “data”: { “text”: “TOKYO, Oct 20 (Reuters) - A volcano ...” } }, { “data”: { “text”: “HONG KONG, Oct 20 (Reuters) - Bitcoin ...” } }]
You can import data by uploading the label_studio_input.json file. After that, you may select from a large variety of templates to customize your labelling interface in the last tab. The default NER template can be used to start off our first NER project. Here are the steps to show you the first project page.
Label Studio is by far the simplest tool I have ever used. This tool’s user interface makes it very easy for me to use. As you can see in the above video, you simply select the label button and highlight the word associated with it. It is possible to activate the label button with the hotkeys if you want to do it more quickly. By pressing the “3” key, you can activate the label button for the “LOC” label. You can confirm your labelling by clicking “Submit” on the right panel after you have finished. Simply edit the text, then update it as needed.
You can see how intuitive the entire labelling process is. What about exporting your result to future processing?
Once you have completed labelling, export it in a different format so you can post-process the result. In this demo, I will export it in JSON format and further clean the result into a Panda Dataframe.
Here is a script that shows you a very simple step to clean the label studio results:
I have stored the label studio result in my google drive.
For demo purpose, I will download it from the google drive and use it to do simple post-processing.
import pandas as pd
import json
from IPython import display
!wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=1IqO4-bTCa12IW5paSfQsNoTziCXY304e' -O label_studio_output.json
--2021-10-20 11:54:30-- https://docs.google.com/uc?export=download&id=1IqO4-bTCa12IW5paSfQsNoTziCXY304e
Resolving docs.google.com (docs.google.com)... 172.217.15.110, 2607:f8b0:4004:811::200e
Connecting to docs.google.com (docs.google.com)|172.217.15.110|:443... connected.
HTTP request sent, awaiting response... 302 Moved Temporarily
Location: https://doc-0o-bg-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/8ct4776jhmqlnu6o2lt742603fr01lqr/1634730825000/05232633842228891353/*/1IqO4-bTCa12IW5paSfQsNoTziCXY304e?e=download [following]
Warning: wildcards not supported in HTTP.
--2021-10-20 11:54:30-- https://doc-0o-bg-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/8ct4776jhmqlnu6o2lt742603fr01lqr/1634730825000/05232633842228891353/*/1IqO4-bTCa12IW5paSfQsNoTziCXY304e?e=download
Resolving doc-0o-bg-docs.googleusercontent.com (doc-0o-bg-docs.googleusercontent.com)... 142.251.33.193, 2607:f8b0:4004:837::2001
Connecting to doc-0o-bg-docs.googleusercontent.com (doc-0o-bg-docs.googleusercontent.com)|142.251.33.193|:443... connected.
HTTP request sent, awaiting response... 200 OK
Length: 5949 (5.8K) [application/json]
Saving to: ‘label_studio_output.json’
label_studio_output 100%[===================>] 5.81K --.-KB/s in 0s
2021-10-20 11:54:30 (36.0 MB/s) - ‘label_studio_output.json’ saved [5949/5949]
with open("label_studio_output.json",'r') as j:
raw_result = json.load(j)
print(json.dumps(raw_result[0], indent=4, sort_keys=True))
{
"annotations": [
{
"completed_by": {
"email": "[email protected]",
"first_name": "",
"id": 1,
"last_name": ""
},
"created_at": "2021-10-20T08:08:52.329065Z",
"ground_truth": false,
"id": 1,
"lead_time": 101.718,
"parent_annotation": null,
"parent_prediction": null,
"prediction": {},
"result": [
{
"from_name": "label",
"id": "2c-MOFaI_1",
"origin": "manual",
"to_name": "text",
"type": "labels",
"value": {
"end": 5,
"labels": [
"PER"
],
"start": 0,
"text": "TOKYO"
}
},
{
"from_name": "label",
"id": "CQuF--hNqt",
"origin": "manual",
"to_name": "text",
"type": "labels",
"value": {
"end": 52,
"labels": [
"LOC"
],
"start": 47,
"text": "Japan"
}
},
{
"from_name": "label",
"id": "SsOEHB7pb8",
"origin": "manual",
"to_name": "text",
"type": "labels",
"value": {
"end": 321,
"labels": [
"LOC"
],
"start": 315,
"text": "Kyushu"
}
},
{
"from_name": "label",
"id": "7eWePA7S4O",
"origin": "manual",
"to_name": "text",
"type": "labels",
"value": {
"end": 445,
"labels": [
"ORG"
],
"start": 418,
"text": "Japan Meteorological Agency"
}
},
{
"from_name": "label",
"id": "hLIKJlIXzN",
"origin": "manual",
"to_name": "text",
"type": "labels",
"value": {
"end": 837,
"labels": [
"PER"
],
"start": 821,
"text": "Hirokazu Matsuno"
}
}
],
"result_count": 0,
"task": 1,
"updated_at": "2021-10-20T08:09:19.767039Z",
"was_cancelled": false
}
],
"created_at": "2021-10-20T08:08:06.826941Z",
"data": {
"text": "TOKYO, Oct 20 (Reuters) - A volcano erupted in Japan on Wednesday, blasting ash several miles into the sky and prompting officials to warn against the threat of lava flows and falling rocks, but there were no immediate reports of casualties or damage.Mount Aso, a tourist destination on the main southern island of Kyushu, sent plumes of ash 3.5 km (2.2 miles) high when it erupted at about 11:43 a.m. (0243 GMT), the Japan Meteorological Agency said.It raised the alert level for the volcano to 3 on a scale of 5, telling people not to approach, and warned of a risk of large falling rocks and pyroclastic flows within a radius of about 1 km (0.6 mile) around the mountain's Nakadake crater.The government is checking to determine the status of a number of climbers on the mountain at the time, Chief Cabinet Secretary Hirokazu Matsuno told reporters, but added that there were no reports of casualties.Television networks broadcast images of a dark cloud of ash looming over the volcano that swiftly obscured large swathes of the mountain.Ash falls from the 1,592-metre (5,222-foot) mountain in the prefecture of Kumamoto are expected to shower nearby towns until late afternoon, the weather agency added.Mount Aso had a small eruption in 2019, while Japan's worst volcanic disaster in nearly 90 years killed 63 people on Mount Ontake in September 2014."
},
"file_upload": "80025440-label_studio_input.json",
"id": 1,
"meta": {},
"predictions": [],
"project": 1,
"updated_at": "2021-10-20T08:09:19.734419Z"
}
Now we have the JSON formatted result, what we will do next is to convert it into panda format. Feel free to convert it to any format you like. The important point here is to show you how easy it is to work with the label studio output.
post_processed_result = []
for task in raw_result:
for label in task['annotations'][0]['result']:
task_row = {}
task_row['task_id'] = task['annotations'][0]['id']
task_row['token'] = label['value']['text']
task_row['token_start'] = label['value']['start']
task_row['token_end'] = label['value']['end']
task_row['label'] = label['value']['labels'][0]
post_processed_result.append(task_row)
pd.DataFrame(post_processed_result)
Certainly not! Earlier in the article, we discussed the defining characteristics of a good data labelling tool. Let’s go over some of the cool features you can customize for different business scenarios.
# Code for the default NER template<View> <Labels name=”label” toName=”text”> <Label value=”PER” background=”red”/> <Label value=”ORG” background=”darkorange”/> <Label value=”LOC” background=”orange”/> <Label value=”MISC” background=”green”/> </Labels> <Text name=”text” value=”$text”/></View>
I showed you only how to start NER projects using the freely available template in the case study above. Additionally, Label Studio gives you access to a code editor that you can use to customize your labelling templates. Code is in XML format, so you can add custom label configurations to your dataset using tags. The following are two examples to allow you to further customize your dataset.
NER’s default template assigns ORG and LOC labels very similar colours. It can cause confusion when annotations are checked after labelling. By changing the colour of the LOC label to blue, we can avoid this human error. To make the task more complete, we will also add more labels.
# Modify the LOC background color to blue<View> <Labels name=”label” toName=”text”> <Label value=”PER” background=”red”/> <Label value=”ORG” background=”darkorange”/> <Label value=”LOC” background=”blue”/> <Label value=”MISC” background=”green”/> <Label value=”BRAND” background=”yellow”/> <Label value=”TIME” background=”purple”/> </Labels> <Text name=”text” value=”$text”/></View>
At the time of setting up the project, we only had the option of choosing one template. Even in the case of a single project, you may need to perform multi-task inference. In one of my client’s projects, I was required to design a multi-label classification model that also performed NER. Adding a new labelling job to our existing tasks is simply a matter of adding a few lines to the script.
<View> <Labels name=”label” toName=”text”> <Label value=”PER” background=”red”/> <Label value=”ORG” background=”darkorange”/> <Label value=”LOC” background=”blue”/> <Label value=”MISC” background=”green”/> <Label value=”BRAND” background=”yellow”/> <Label value=”TIME” background=”purple”/> </Labels> <Text name=”text” value=”$text”/> <Taxonomy name=”article_class” toName=”text”> <Choice value=”world”> <Choice value=”africa”/> <Choice value=”america”/> </Choice> <Choice value=”business”> <Choice value=”environment”/> <Choice value=”finance”/> </Choice> </Taxonomy></View>
We can see that adding a new tag called Taxonomy generates a multi-label classification job right away for the existing task.
Now that you know how easy Label Studio is to use, you can now use it on your next labelling project. In closing, I’d like to point out one more important feature.
There is no doubt that labelling jobs are labour-intensive, which means that we need to spread the tasks among multiple annotators to complete them as quickly as possible. To reduce human bias, we should assign more than one human to each labelling task. The good news is that Label Studio allows annotators to sign up and they can work on the same task if needed.
To start annotating the same articles as the existing annotator, all they need to do is create a new tab under their account:
Our goal in this article is to show you how to build a labelling tool to support your next labelling project. In addition to its array of free features, Label Studio also allows you to customize your labelling interface with just a few lines of code. The platform supports not only natural language processing task but also computer vision and speech recognition tasks. The team edition would be ideal if you intend to use this tool for a long time.
Label Studio really did a great job of making this labelling tool as easy to use as possible. No matter if you are a startup or a small business, labelling can sometimes be a problem when you are developing a new machine learning project. Costs and time can add up when designing a new labelling tool. In this regard, Label Studio is a viable option.
https://labelstud.io/
https://labelstud.io/
Woen Yon is a Data Scientist based in Singapore. His experience includes developing advanced artificial intelligence products for several multinational enterprises.
Woen Yon works with a handful of smart people to offer web solutions including web crawling services and website development for local and international start-up business owners. They are well aware of the challenges of building quality software. Please do not hesitate to drop him an email at [email protected] if you need assistance.
He loves making friends! Feel free to connect with him on LinkedIn and Medium
|
[
{
"code": null,
"e": 379,
"s": 172,
"text": "As a data scientist, you will definitely need to train models to meet your organization’s needs. Most of the time, you require labelled data from within your company in order to build a customized solution."
},
{
"code": null,
"e": 684,
"s": 379,
"text": "You’re approached by a product manager one day who wants you to build a named entity recognition model to improve the quality of the downstream data science product. Due to the short time frame this product needs to be launched, he hired a bunch of human labellers to assist you. What should you do next?"
},
{
"code": null,
"e": 734,
"s": 684,
"text": "“ Give us the tools, and we will finish the job “"
},
{
"code": null,
"e": 755,
"s": 734,
"text": "by Winston Churchill"
},
{
"code": null,
"e": 992,
"s": 755,
"text": "The task objective is clear, manpower is ample, and a deadline is set. What’s next? A useful labelling tool. Please note the emphasis on “useful”. But what is it that I mean by “useful”? The tool should at least give you the ability to:"
},
{
"code": null,
"e": 2920,
"s": 992,
"text": "Track the labelling quality, on-premises or in the cloud, at any time. The annotation staff can be informed if they are not following the instructions before the entire labelling project is completed.Keep track of the progress of every annotator. The deadline is given to you, so it is imperative that every annotator be given a specific deadline for finishing their labelling. As a project leader, you should be able to track the progress to ensure everyone stays on track.Allow multiple annotations to work together. Bias is one of the most problematic topics in machine learning. As a data scientist, you do not want annotation bias to affect your model after spending several days or weeks training your model, only to find out that it is biased. As a possible solution, multiple authors could collaborate on the same task/article and only approve labels that are unanimously accepted.Post-process your labelling result with the least amount of effort. One particular aspect you will appreciate is the ease with which you can handle the labelled data. In my experience, the JSON format is the easiest to work with when I am working on labelling projects for clients. It would be great if the tool could support multiple types of formats for importing and exporting data.Provide a user-friendly interface to your human annotators. Developing a good data labelling tool for me is based primarily on this factor. Not only was I responsible for preparing the client documentation, but I also had to train the human annotations on how to use the labelling tool with as little human error as possible. You can therefore save yourself from a great deal of hassle if you use an easy-to-use labelling tool.Code your labelling interface to suit your needs. I’m sure, as a programmer, you’d like your tool to be controlled by code. Coding to make the interface customized would allow the time to be dedicated to other important tasks."
},
{
"code": null,
"e": 3121,
"s": 2920,
"text": "Track the labelling quality, on-premises or in the cloud, at any time. The annotation staff can be informed if they are not following the instructions before the entire labelling project is completed."
},
{
"code": null,
"e": 3396,
"s": 3121,
"text": "Keep track of the progress of every annotator. The deadline is given to you, so it is imperative that every annotator be given a specific deadline for finishing their labelling. As a project leader, you should be able to track the progress to ensure everyone stays on track."
},
{
"code": null,
"e": 3812,
"s": 3396,
"text": "Allow multiple annotations to work together. Bias is one of the most problematic topics in machine learning. As a data scientist, you do not want annotation bias to affect your model after spending several days or weeks training your model, only to find out that it is biased. As a possible solution, multiple authors could collaborate on the same task/article and only approve labels that are unanimously accepted."
},
{
"code": null,
"e": 4198,
"s": 3812,
"text": "Post-process your labelling result with the least amount of effort. One particular aspect you will appreciate is the ease with which you can handle the labelled data. In my experience, the JSON format is the easiest to work with when I am working on labelling projects for clients. It would be great if the tool could support multiple types of formats for importing and exporting data."
},
{
"code": null,
"e": 4626,
"s": 4198,
"text": "Provide a user-friendly interface to your human annotators. Developing a good data labelling tool for me is based primarily on this factor. Not only was I responsible for preparing the client documentation, but I also had to train the human annotations on how to use the labelling tool with as little human error as possible. You can therefore save yourself from a great deal of hassle if you use an easy-to-use labelling tool."
},
{
"code": null,
"e": 4853,
"s": 4626,
"text": "Code your labelling interface to suit your needs. I’m sure, as a programmer, you’d like your tool to be controlled by code. Coding to make the interface customized would allow the time to be dedicated to other important tasks."
},
{
"code": null,
"e": 5090,
"s": 4853,
"text": "These are the features I would at least like my labelling tool to have. A tool like this could cost you thousands of dollars and countless hours of labour to develop. What is the best way to find such an off-the-shelf tool ... for free?"
},
{
"code": null,
"e": 5283,
"s": 5090,
"text": "Before I begin, let me disclaim the following: I do not work for Label Studio and I am not affiliated with Label Studio. It is simply my personal experience from working on a client’s project."
},
{
"code": null,
"e": 5294,
"s": 5283,
"text": "github.com"
},
{
"code": null,
"e": 5615,
"s": 5294,
"text": "As I was developing a system to label data on a client’s behalf, I ran into this tool. In light of the fact that it is an open-source and free data labelling tool, I am quite surprised at its flexibility and functionality. Using a few simple steps, I will show you how you can construct a simple NER labelling interface."
},
{
"code": null,
"e": 6095,
"s": 5615,
"text": "You can easily set up Label Studio by following the instructions in the Github repository. It supports both installations on the local machine and deployment in the cloud. As part of my work for a client, I built and deployed the tool using Docker. It allows him to store the data locally since credentials are the main requirement for his business. To demonstrate the tool, I am going to use Heroku Buttons. You may deploy it in any manner you deem acceptable for your business."
},
{
"code": null,
"e": 6254,
"s": 6095,
"text": "You will be able to see the project page after you log in. The process of creating a project is illustrated in the gif above. For this project, I call it NER."
},
{
"code": null,
"e": 6392,
"s": 6254,
"text": "We will prepare a sample project with only two articles (in Label Studio, they call these \"tasks\"). You are free add more if you want to."
},
{
"code": null,
"e": 6448,
"s": 6392,
"text": "The sample articles are copied from these two articles:"
},
{
"code": null,
"e": 6647,
"s": 6448,
"text": "\nhttps://www.reuters.com/world/asia-pacific/japans-mount-aso-erupts-alert-level-raised-2021-10-20/\nhttps://www.reuters.com/technology/bitcoin-sits-below-all-time-high-after-us-etf-debut-2021-10-20/\n"
},
{
"code": null,
"e": 6745,
"s": 6647,
"text": "https://www.reuters.com/world/asia-pacific/japans-mount-aso-erupts-alert-level-raised-2021-10-20/"
},
{
"code": null,
"e": 6844,
"s": 6745,
"text": "https://www.reuters.com/technology/bitcoin-sits-below-all-time-high-after-us-etf-debut-2021-10-20/"
},
{
"code": null,
"e": 6934,
"s": 6844,
"text": "import requests\nfrom bs4 import BeautifulSoup\nimport json\nfrom google.colab import files\n"
},
{
"code": null,
"e": 6994,
"s": 6934,
"text": "Using Beautifulsoup to crawl the article body automatically"
},
{
"code": null,
"e": 7624,
"s": 6994,
"text": "%time\ntask_texts = []\n\ntask_links = [\"https://www.reuters.com/world/asia-pacific/japans-mount-aso-erupts-alert-level-raised-2021-10-20/\", \n \"https://www.reuters.com/technology/bitcoin-sits-below-all-time-high-after-us-etf-debut-2021-10-20/\"]\n\nfor task_link in task_links:\n page = requests.get(task_link)\n if page.status_code == 200:\n soup = BeautifulSoup(page.content, 'html.parser')\n task_texts.append(''.join([p.getText() for p in soup.find_all('p', {'data-testid': lambda value: value and \"paragraph\" in value})]))\n else:\n print('Website returns non-parsable content')\n raise\n"
},
{
"code": null,
"e": 7689,
"s": 7624,
"text": "CPU times: user 2 μs, sys: 0 ns, total: 2 μs\nWall time: 5.48 μs\n"
},
{
"code": null,
"e": 7763,
"s": 7689,
"text": "Populate the crawled articles into a list format accepted by label studio"
},
{
"code": null,
"e": 7883,
"s": 7763,
"text": "%time\nlabel_studio_input = []\n\nfor task_text in task_texts:\n label_studio_input.append({\"data\":{\"text\":task_text}})\n"
},
{
"code": null,
"e": 7948,
"s": 7883,
"text": "CPU times: user 3 μs, sys: 0 ns, total: 3 μs\nWall time: 7.39 μs\n"
},
{
"code": null,
"e": 8036,
"s": 7948,
"text": "print(json.dumps(label_studio_input[0], indent=4, sort_keys=True, ensure_ascii=False))\n"
},
{
"code": null,
"e": 9436,
"s": 8036,
"text": "{\n \"data\": {\n \"text\": \"TOKYO, Oct 20 (Reuters) - A volcano erupted in Japan on Wednesday, blasting ash several miles into the sky and prompting officials to warn against the threat of lava flows and falling rocks, but there were no immediate reports of casualties or damage.Mount Aso, a tourist destination on the main southern island of Kyushu, sent plumes of ash 3.5 km (2.2 miles) high when it erupted at about 11:43 a.m. (0243 GMT), the Japan Meteorological Agency said.It raised the alert level for the volcano to 3 on a scale of 5, telling people not to approach, and warned of a risk of large falling rocks and pyroclastic flows within a radius of about 1 km (0.6 mile) around the mountain's Nakadake crater.The government is checking to determine the status of a number of climbers on the mountain at the time, Chief Cabinet Secretary Hirokazu Matsuno told reporters, but added that there were no reports of casualties.Television networks broadcast images of a dark cloud of ash looming over the volcano that swiftly obscured large swathes of the mountain.Ash falls from the 1,592-metre (5,222-foot) mountain in the prefecture of Kumamoto are expected to shower nearby towns until late afternoon, the weather agency added.Mount Aso had a small eruption in 2019, while Japan's worst volcanic disaster in nearly 90 years killed 63 people on Mount Ontake in September 2014.\"\n }\n}\n"
},
{
"code": null,
"e": 9502,
"s": 9436,
"text": "Save file to temporary folder and automatically download the file"
},
{
"code": null,
"e": 9587,
"s": 9502,
"text": "with open(\"label_studio_input.json\",'w') as j:\n json.dump(label_studio_input, j)\n"
},
{
"code": null,
"e": 9630,
"s": 9587,
"text": "files.download(\"label_studio_input.json\")\n"
},
{
"code": null,
"e": 9930,
"s": 9630,
"text": "Our next step is to upload our own data to prepare for labelling. For your convenience, I have created a script to help you get started. As a starting point, I used two articles from Reuters.com. Run the script above in Colab, and you should be able to view a list of tasks in JSON format like this:"
},
{
"code": null,
"e": 10096,
"s": 9930,
"text": "[ { “data”: { “text”: “TOKYO, Oct 20 (Reuters) - A volcano ...” } }, { “data”: { “text”: “HONG KONG, Oct 20 (Reuters) - Bitcoin ...” } }]"
},
{
"code": null,
"e": 10407,
"s": 10096,
"text": "You can import data by uploading the label_studio_input.json file. After that, you may select from a large variety of templates to customize your labelling interface in the last tab. The default NER template can be used to start off our first NER project. Here are the steps to show you the first project page."
},
{
"code": null,
"e": 10960,
"s": 10407,
"text": "Label Studio is by far the simplest tool I have ever used. This tool’s user interface makes it very easy for me to use. As you can see in the above video, you simply select the label button and highlight the word associated with it. It is possible to activate the label button with the hotkeys if you want to do it more quickly. By pressing the “3” key, you can activate the label button for the “LOC” label. You can confirm your labelling by clicking “Submit” on the right panel after you have finished. Simply edit the text, then update it as needed."
},
{
"code": null,
"e": 11074,
"s": 10960,
"text": "You can see how intuitive the entire labelling process is. What about exporting your result to future processing?"
},
{
"code": null,
"e": 11276,
"s": 11074,
"text": "Once you have completed labelling, export it in a different format so you can post-process the result. In this demo, I will export it in JSON format and further clean the result into a Panda Dataframe."
},
{
"code": null,
"e": 11362,
"s": 11276,
"text": "Here is a script that shows you a very simple step to clean the label studio results:"
},
{
"code": null,
"e": 11520,
"s": 11362,
"text": "I have stored the label studio result in my google drive.\nFor demo purpose, I will download it from the google drive and use it to do simple post-processing."
},
{
"code": null,
"e": 11581,
"s": 11520,
"text": "import pandas as pd\nimport json\nfrom IPython import display\n"
},
{
"code": null,
"e": 11721,
"s": 11581,
"text": "!wget --no-check-certificate 'https://docs.google.com/uc?export=download&id=1IqO4-bTCa12IW5paSfQsNoTziCXY304e' -O label_studio_output.json\n"
},
{
"code": null,
"e": 13102,
"s": 11721,
"text": "--2021-10-20 11:54:30-- https://docs.google.com/uc?export=download&id=1IqO4-bTCa12IW5paSfQsNoTziCXY304e\nResolving docs.google.com (docs.google.com)... 172.217.15.110, 2607:f8b0:4004:811::200e\nConnecting to docs.google.com (docs.google.com)|172.217.15.110|:443... connected.\nHTTP request sent, awaiting response... 302 Moved Temporarily\nLocation: https://doc-0o-bg-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/8ct4776jhmqlnu6o2lt742603fr01lqr/1634730825000/05232633842228891353/*/1IqO4-bTCa12IW5paSfQsNoTziCXY304e?e=download [following]\nWarning: wildcards not supported in HTTP.\n--2021-10-20 11:54:30-- https://doc-0o-bg-docs.googleusercontent.com/docs/securesc/ha0ro937gcuc7l7deffksulhg5h7mbp1/8ct4776jhmqlnu6o2lt742603fr01lqr/1634730825000/05232633842228891353/*/1IqO4-bTCa12IW5paSfQsNoTziCXY304e?e=download\nResolving doc-0o-bg-docs.googleusercontent.com (doc-0o-bg-docs.googleusercontent.com)... 142.251.33.193, 2607:f8b0:4004:837::2001\nConnecting to doc-0o-bg-docs.googleusercontent.com (doc-0o-bg-docs.googleusercontent.com)|142.251.33.193|:443... connected.\nHTTP request sent, awaiting response... 200 OK\nLength: 5949 (5.8K) [application/json]\nSaving to: ‘label_studio_output.json’\n\nlabel_studio_output 100%[===================>] 5.81K --.-KB/s in 0s \n\n2021-10-20 11:54:30 (36.0 MB/s) - ‘label_studio_output.json’ saved [5949/5949]\n\n"
},
{
"code": null,
"e": 13181,
"s": 13102,
"text": "with open(\"label_studio_output.json\",'r') as j:\n raw_result = json.load(j)\n"
},
{
"code": null,
"e": 13241,
"s": 13181,
"text": "print(json.dumps(raw_result[0], indent=4, sort_keys=True))\n"
},
{
"code": null,
"e": 18070,
"s": 13241,
"text": "{\n \"annotations\": [\n {\n \"completed_by\": {\n \"email\": \"[email protected]\",\n \"first_name\": \"\",\n \"id\": 1,\n \"last_name\": \"\"\n },\n \"created_at\": \"2021-10-20T08:08:52.329065Z\",\n \"ground_truth\": false,\n \"id\": 1,\n \"lead_time\": 101.718,\n \"parent_annotation\": null,\n \"parent_prediction\": null,\n \"prediction\": {},\n \"result\": [\n {\n \"from_name\": \"label\",\n \"id\": \"2c-MOFaI_1\",\n \"origin\": \"manual\",\n \"to_name\": \"text\",\n \"type\": \"labels\",\n \"value\": {\n \"end\": 5,\n \"labels\": [\n \"PER\"\n ],\n \"start\": 0,\n \"text\": \"TOKYO\"\n }\n },\n {\n \"from_name\": \"label\",\n \"id\": \"CQuF--hNqt\",\n \"origin\": \"manual\",\n \"to_name\": \"text\",\n \"type\": \"labels\",\n \"value\": {\n \"end\": 52,\n \"labels\": [\n \"LOC\"\n ],\n \"start\": 47,\n \"text\": \"Japan\"\n }\n },\n {\n \"from_name\": \"label\",\n \"id\": \"SsOEHB7pb8\",\n \"origin\": \"manual\",\n \"to_name\": \"text\",\n \"type\": \"labels\",\n \"value\": {\n \"end\": 321,\n \"labels\": [\n \"LOC\"\n ],\n \"start\": 315,\n \"text\": \"Kyushu\"\n }\n },\n {\n \"from_name\": \"label\",\n \"id\": \"7eWePA7S4O\",\n \"origin\": \"manual\",\n \"to_name\": \"text\",\n \"type\": \"labels\",\n \"value\": {\n \"end\": 445,\n \"labels\": [\n \"ORG\"\n ],\n \"start\": 418,\n \"text\": \"Japan Meteorological Agency\"\n }\n },\n {\n \"from_name\": \"label\",\n \"id\": \"hLIKJlIXzN\",\n \"origin\": \"manual\",\n \"to_name\": \"text\",\n \"type\": \"labels\",\n \"value\": {\n \"end\": 837,\n \"labels\": [\n \"PER\"\n ],\n \"start\": 821,\n \"text\": \"Hirokazu Matsuno\"\n }\n }\n ],\n \"result_count\": 0,\n \"task\": 1,\n \"updated_at\": \"2021-10-20T08:09:19.767039Z\",\n \"was_cancelled\": false\n }\n ],\n \"created_at\": \"2021-10-20T08:08:06.826941Z\",\n \"data\": {\n \"text\": \"TOKYO, Oct 20 (Reuters) - A volcano erupted in Japan on Wednesday, blasting ash several miles into the sky and prompting officials to warn against the threat of lava flows and falling rocks, but there were no immediate reports of casualties or damage.Mount Aso, a tourist destination on the main southern island of Kyushu, sent plumes of ash 3.5 km (2.2 miles) high when it erupted at about 11:43 a.m. (0243 GMT), the Japan Meteorological Agency said.It raised the alert level for the volcano to 3 on a scale of 5, telling people not to approach, and warned of a risk of large falling rocks and pyroclastic flows within a radius of about 1 km (0.6 mile) around the mountain's Nakadake crater.The government is checking to determine the status of a number of climbers on the mountain at the time, Chief Cabinet Secretary Hirokazu Matsuno told reporters, but added that there were no reports of casualties.Television networks broadcast images of a dark cloud of ash looming over the volcano that swiftly obscured large swathes of the mountain.Ash falls from the 1,592-metre (5,222-foot) mountain in the prefecture of Kumamoto are expected to shower nearby towns until late afternoon, the weather agency added.Mount Aso had a small eruption in 2019, while Japan's worst volcanic disaster in nearly 90 years killed 63 people on Mount Ontake in September 2014.\"\n },\n \"file_upload\": \"80025440-label_studio_input.json\",\n \"id\": 1,\n \"meta\": {},\n \"predictions\": [],\n \"project\": 1,\n \"updated_at\": \"2021-10-20T08:09:19.734419Z\"\n}\n"
},
{
"code": null,
"e": 18307,
"s": 18070,
"text": "Now we have the JSON formatted result, what we will do next is to convert it into panda format. Feel free to convert it to any format you like. The important point here is to show you how easy it is to work with the label studio output."
},
{
"code": null,
"e": 18776,
"s": 18307,
"text": "post_processed_result = []\n\nfor task in raw_result:\n for label in task['annotations'][0]['result']:\n task_row = {}\n task_row['task_id'] = task['annotations'][0]['id']\n task_row['token'] = label['value']['text']\n task_row['token_start'] = label['value']['start']\n task_row['token_end'] = label['value']['end']\n task_row['label'] = label['value']['labels'][0]\n post_processed_result.append(task_row)\n"
},
{
"code": null,
"e": 18813,
"s": 18776,
"text": "pd.DataFrame(post_processed_result)\n"
},
{
"code": null,
"e": 19019,
"s": 18815,
"text": "Certainly not! Earlier in the article, we discussed the defining characteristics of a good data labelling tool. Let’s go over some of the cool features you can customize for different business scenarios."
},
{
"code": null,
"e": 19350,
"s": 19019,
"text": "# Code for the default NER template<View> <Labels name=”label” toName=”text”> <Label value=”PER” background=”red”/> <Label value=”ORG” background=”darkorange”/> <Label value=”LOC” background=”orange”/> <Label value=”MISC” background=”green”/> </Labels> <Text name=”text” value=”$text”/></View>"
},
{
"code": null,
"e": 19745,
"s": 19350,
"text": "I showed you only how to start NER projects using the freely available template in the case study above. Additionally, Label Studio gives you access to a code editor that you can use to customize your labelling templates. Code is in XML format, so you can add custom label configurations to your dataset using tags. The following are two examples to allow you to further customize your dataset."
},
{
"code": null,
"e": 20028,
"s": 19745,
"text": "NER’s default template assigns ORG and LOC labels very similar colours. It can cause confusion when annotations are checked after labelling. By changing the colour of the LOC label to blue, we can avoid this human error. To make the task more complete, we will also add more labels."
},
{
"code": null,
"e": 20462,
"s": 20028,
"text": "# Modify the LOC background color to blue<View> <Labels name=”label” toName=”text”> <Label value=”PER” background=”red”/> <Label value=”ORG” background=”darkorange”/> <Label value=”LOC” background=”blue”/> <Label value=”MISC” background=”green”/> <Label value=”BRAND” background=”yellow”/> <Label value=”TIME” background=”purple”/> </Labels> <Text name=”text” value=”$text”/></View>"
},
{
"code": null,
"e": 20856,
"s": 20462,
"text": "At the time of setting up the project, we only had the option of choosing one template. Even in the case of a single project, you may need to perform multi-task inference. In one of my client’s projects, I was required to design a multi-label classification model that also performed NER. Adding a new labelling job to our existing tasks is simply a matter of adding a few lines to the script."
},
{
"code": null,
"e": 21561,
"s": 20856,
"text": "<View> <Labels name=”label” toName=”text”> <Label value=”PER” background=”red”/> <Label value=”ORG” background=”darkorange”/> <Label value=”LOC” background=”blue”/> <Label value=”MISC” background=”green”/> <Label value=”BRAND” background=”yellow”/> <Label value=”TIME” background=”purple”/> </Labels> <Text name=”text” value=”$text”/> <Taxonomy name=”article_class” toName=”text”> <Choice value=”world”> <Choice value=”africa”/> <Choice value=”america”/> </Choice> <Choice value=”business”> <Choice value=”environment”/> <Choice value=”finance”/> </Choice> </Taxonomy></View>"
},
{
"code": null,
"e": 21687,
"s": 21561,
"text": "We can see that adding a new tag called Taxonomy generates a multi-label classification job right away for the existing task."
},
{
"code": null,
"e": 21851,
"s": 21687,
"text": "Now that you know how easy Label Studio is to use, you can now use it on your next labelling project. In closing, I’d like to point out one more important feature."
},
{
"code": null,
"e": 22216,
"s": 21851,
"text": "There is no doubt that labelling jobs are labour-intensive, which means that we need to spread the tasks among multiple annotators to complete them as quickly as possible. To reduce human bias, we should assign more than one human to each labelling task. The good news is that Label Studio allows annotators to sign up and they can work on the same task if needed."
},
{
"code": null,
"e": 22342,
"s": 22216,
"text": "To start annotating the same articles as the existing annotator, all they need to do is create a new tab under their account:"
},
{
"code": null,
"e": 22792,
"s": 22342,
"text": "Our goal in this article is to show you how to build a labelling tool to support your next labelling project. In addition to its array of free features, Label Studio also allows you to customize your labelling interface with just a few lines of code. The platform supports not only natural language processing task but also computer vision and speech recognition tasks. The team edition would be ideal if you intend to use this tool for a long time."
},
{
"code": null,
"e": 23143,
"s": 22792,
"text": "Label Studio really did a great job of making this labelling tool as easy to use as possible. No matter if you are a startup or a small business, labelling can sometimes be a problem when you are developing a new machine learning project. Costs and time can add up when designing a new labelling tool. In this regard, Label Studio is a viable option."
},
{
"code": null,
"e": 23165,
"s": 23143,
"text": "https://labelstud.io/"
},
{
"code": null,
"e": 23187,
"s": 23165,
"text": "https://labelstud.io/"
},
{
"code": null,
"e": 23352,
"s": 23187,
"text": "Woen Yon is a Data Scientist based in Singapore. His experience includes developing advanced artificial intelligence products for several multinational enterprises."
},
{
"code": null,
"e": 23688,
"s": 23352,
"text": "Woen Yon works with a handful of smart people to offer web solutions including web crawling services and website development for local and international start-up business owners. They are well aware of the challenges of building quality software. Please do not hesitate to drop him an email at [email protected] if you need assistance."
}
] |
Java String codePointAt() Method
|
❮ String Methods
Return the Unicode of the first character in a string (the Unicode value
of "H" is 72):
String myStr = "Hello";
int result = myStr.codePointAt(0);
System.out.println(result);
Try it Yourself »
The codePointAt() method returns the Unicode
value of the character at the specified index in a string.
The index of the first character is 0, the second character is 1, and so on.
public int codePointAt(int index)
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 19,
"s": 0,
"text": "\n❮ String Methods\n"
},
{
"code": null,
"e": 110,
"s": 19,
"text": "Return the Unicode of the first character in a string (the Unicode value \n of \"H\" is 72):"
},
{
"code": null,
"e": 197,
"s": 110,
"text": "String myStr = \"Hello\";\nint result = myStr.codePointAt(0);\nSystem.out.println(result);"
},
{
"code": null,
"e": 217,
"s": 197,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 322,
"s": 217,
"text": "The codePointAt() method returns the Unicode \nvalue of the character at the specified index in a string."
},
{
"code": null,
"e": 399,
"s": 322,
"text": "The index of the first character is 0, the second character is 1, and so on."
},
{
"code": null,
"e": 434,
"s": 399,
"text": "public int codePointAt(int index)\n"
},
{
"code": null,
"e": 467,
"s": 434,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 509,
"s": 467,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 616,
"s": 509,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 635,
"s": 616,
"text": "[email protected]"
}
] |
Getting started with Vim and Tmux for Python | by Denis Gontcharov | Towards Data Science
|
If you write code in multiple languages you may have found it tiresome to maintain an IDE for each. After some experimentation I found the combination of Vim and Tmux to be the ideal solution for my case. The main benefits are:
✓ One environment with support for any language
✓ Efficient keyboard-only file editing
✓ Easy installation in any new environment
However, being a text editor and not an IDE, this solution lacks some important features out of the box. Fortunately, both Vim and Tmux are highly configurable.
This article shows how to configure Vim and Tmux to support a list of critical features for Python development. Although Tmux plays an important part, most of the configuration concerns Vim.
This workflow is designed to run on a Unix system like Linux or MacOS. To start, create a .vimrc file in the home/ directory as well as an empty folder .vim/. Install Vim, Tmux and (optionally) IPython. Some familiarity with Vim and its configuration through the .vimrc file is assumed. If you don’t know how to install Vim plugins take a look at this article.
Below is an opinionated list of features that make Python development in Vim more sensible:
1. One environment for multiple languages
2. Easy access to the terminal
3. Smooth directory browsing
4. Sending lines of code to a Python console
5. Running a Python file in the terminal
6. Interactive debugging
Vim can be configured for each file type independently. For example, Vim can be configured to use four spaces for a tab when it opens a Python file but two spaces when it opens an R file. To enable file-specific settings put the following line in the .vimrc file:
filetype plugin indent on
The indent part enables file specific indentation.
Create the directory .vim/after/ftplugin. Files in ftplugin are named after the language (e.g. python, json, r, sh) and have the .vim extension. Below is an example for JSON, Python, R and Bash:
.vim/└── after └── ftplugin ├── json.vim ├── python.vim ├── r.vim └── sh.vim
The idea is to put any .vimrc configuration that only applies to a particular language into the corresponding file in ftplugin. In that sense, files in ftplugin can be viewed as “language-specific .vimrc” files. These files are sourced after .vimrc and overwrite any general settings.
For example, Python-specific indentation should be put in the python.vim file:
setlocal tabstop=4setlocal shiftwidth=4setlocal softtabstop=4setlocal expandtab
Notice the use of setlocal so that these settings only overwrite the general settings from the .vimrc file for the current buffer only.
The next chapters in this article follow the convention of putting language-specific settings in ftplugin and general Vim settings in .vimrc.
Keep your vimrc clean
This feature only works if Vim runs inside the terminal. In that case, Vim can be suspended by running the Ex command:
:stop<CR>
This moves Vim to the background and switches the screen back to the terminal from which Vim was called. Running fg in the terminal moves Vim back to the foreground.
Switching between Vim and a full-screen terminal is so convenient that it’s worth creating a mapping in .vimrc:
nnoremap <leader>t :stop<CR>
Terminal Vim versus GUI
IDEs generally provide a file explorer built as a project drawer. This approach doesn’t mix well with Vim’s window style workflow. After all, how does Vim know in which window you want to open a file you selected from the project drawer?
Vim already comes with a built-in plugin called netrw. To understand this plugin, imagine Vim windows as flipping cards: on one side you have your file and on the other side the netrw file explorer.
It’s useful to map two key bindings for file browsing in .vimrc. The first one opens netrw at the current file’s directory. The second key binding opens netrw at the current working directory.
nmap <leader>f :Explore<CR>nmap <leader><s-f> :edit.<CR>
Netrw has some annoying defaults though. It’s recommended to put these two additional netrw settings in .vimrc. The first setting allows to open a file in a right split. The second setting suppresses netrw from saving .netrwhist files in the .vim folder.
let g:netrw_altv = 1let g:netrw_dirhistmax = 0
Finally, a minimal plugin called vim-vinegar makes netrw more sensible and comes with several useful shortcuts:
Press - in any buffer to hop up to the directory listing and seek to the file you just came from.
Press . on a file to pre-populate it at the end of a : command line. There’s also !, which starts the line off with a bang.
Press y. to yank an absolute path for the file under the cursor.
You don’t need NERDTREE or (maybe) netrw
Oil and vinegar — split windows and the project drawer
vim-vinegar
Tmux allows to split the screen horizontally into two terminal windows: the upper one for Vim (possible with multiple vertical split windows) and the bottom one containing a IPython console. If you dislike IPython the above procedure will work just as well with the regular Python console.
Next, the plugin vim-slime is used to send selected code from Vim to the IPython console. The following to configuration in the .vimrc file enables this behavior:
let g:slime_target = "tmux"let g:slime_default_config = {"socket_name": get(split($TMUX, ","), 0), "target_pane": ":.1"}
Pressing C-c, C-c (holding Ctrl and double-tapping C) sends the paragraph beneath the cursor to the IPython console. (The first time vim-slime will prompt the target pane. Press Enter twice.)
The above procedure is language agnostic: the same procedure allows to send lines of R code to an R console or lines from a Bash script to the terminal.
vim-slime
The Tao of Tmux
It’s convenient to have a shortcut to run the current script in the terminal. Generally, this is done by calling the interpreter followed by the file name:
python filename.py
The following mapping in defined in python.vim runs two consecutive Ex-commands:
nmap <buffer> <leader>r <Esc>:w<CR>:!clear;python %<CR>
Here’s what it does:
The first Ex-command :w<CR> saves the file.The second Ex-command starts with :! indicating it’s meant meant for the terminal, clears the terminal with :clear and finally calls the interpreter python %<CR> on the current file whose path is given by %.
The first Ex-command :w<CR> saves the file.
The second Ex-command starts with :! indicating it’s meant meant for the terminal, clears the terminal with :clear and finally calls the interpreter python %<CR> on the current file whose path is given by %.
Notice that this mapping is language-specific. A similar mapping to run a bash script can be defined as follows:
nnoremap <buffer> <leader>r <Esc>:w<CR>:!clear;sh %<CR>
Running Python code in Vim
Debugging is an area where IDEs really shine. Nonetheless, by installing the Python ipdb a satisfactory debugging experience can be obtained in Vim.
The module ipdb is similar to pdb but designed for IPython. It doesn’t have to be installed as it comes with IPython. It allows to define a breakpoint with set_trace() which will pause the program at that point and drop start the debugger where the program’s state can be inspected using IPython.
The following Vim mapping in python.vim puts a breakpoint below the current line:
nmap <buffer> <leader>b oimport ipdb;ipdb.set_trace(context=5)<ESC>
The context argument specifies the number of lines shown by the debugger.
A nice feature if IPython is embed which launches a separate IPython session during debugging. Changes made in this session will not affect objects in the original debugging session.
ipdb> from IPython import embedipdb> embed()
A further review of the debugger commands is beyond the scope of the article. They are nicely documented in the documentation in the referenced below.
pdb documentation
The configurations in this article will help you get started with Vim and Tmux for your Python development. Other useful features such as linting, code completion and jumping to definitions were not covered. Take a look at my personal Vim configuration for a more complete example of what’s possible.
|
[
{
"code": null,
"e": 400,
"s": 172,
"text": "If you write code in multiple languages you may have found it tiresome to maintain an IDE for each. After some experimentation I found the combination of Vim and Tmux to be the ideal solution for my case. The main benefits are:"
},
{
"code": null,
"e": 448,
"s": 400,
"text": "✓ One environment with support for any language"
},
{
"code": null,
"e": 487,
"s": 448,
"text": "✓ Efficient keyboard-only file editing"
},
{
"code": null,
"e": 530,
"s": 487,
"text": "✓ Easy installation in any new environment"
},
{
"code": null,
"e": 691,
"s": 530,
"text": "However, being a text editor and not an IDE, this solution lacks some important features out of the box. Fortunately, both Vim and Tmux are highly configurable."
},
{
"code": null,
"e": 882,
"s": 691,
"text": "This article shows how to configure Vim and Tmux to support a list of critical features for Python development. Although Tmux plays an important part, most of the configuration concerns Vim."
},
{
"code": null,
"e": 1243,
"s": 882,
"text": "This workflow is designed to run on a Unix system like Linux or MacOS. To start, create a .vimrc file in the home/ directory as well as an empty folder .vim/. Install Vim, Tmux and (optionally) IPython. Some familiarity with Vim and its configuration through the .vimrc file is assumed. If you don’t know how to install Vim plugins take a look at this article."
},
{
"code": null,
"e": 1335,
"s": 1243,
"text": "Below is an opinionated list of features that make Python development in Vim more sensible:"
},
{
"code": null,
"e": 1377,
"s": 1335,
"text": "1. One environment for multiple languages"
},
{
"code": null,
"e": 1408,
"s": 1377,
"text": "2. Easy access to the terminal"
},
{
"code": null,
"e": 1437,
"s": 1408,
"text": "3. Smooth directory browsing"
},
{
"code": null,
"e": 1482,
"s": 1437,
"text": "4. Sending lines of code to a Python console"
},
{
"code": null,
"e": 1523,
"s": 1482,
"text": "5. Running a Python file in the terminal"
},
{
"code": null,
"e": 1548,
"s": 1523,
"text": "6. Interactive debugging"
},
{
"code": null,
"e": 1812,
"s": 1548,
"text": "Vim can be configured for each file type independently. For example, Vim can be configured to use four spaces for a tab when it opens a Python file but two spaces when it opens an R file. To enable file-specific settings put the following line in the .vimrc file:"
},
{
"code": null,
"e": 1838,
"s": 1812,
"text": "filetype plugin indent on"
},
{
"code": null,
"e": 1889,
"s": 1838,
"text": "The indent part enables file specific indentation."
},
{
"code": null,
"e": 2084,
"s": 1889,
"text": "Create the directory .vim/after/ftplugin. Files in ftplugin are named after the language (e.g. python, json, r, sh) and have the .vim extension. Below is an example for JSON, Python, R and Bash:"
},
{
"code": null,
"e": 2192,
"s": 2084,
"text": ".vim/└── after └── ftplugin ├── json.vim ├── python.vim ├── r.vim └── sh.vim"
},
{
"code": null,
"e": 2477,
"s": 2192,
"text": "The idea is to put any .vimrc configuration that only applies to a particular language into the corresponding file in ftplugin. In that sense, files in ftplugin can be viewed as “language-specific .vimrc” files. These files are sourced after .vimrc and overwrite any general settings."
},
{
"code": null,
"e": 2556,
"s": 2477,
"text": "For example, Python-specific indentation should be put in the python.vim file:"
},
{
"code": null,
"e": 2636,
"s": 2556,
"text": "setlocal tabstop=4setlocal shiftwidth=4setlocal softtabstop=4setlocal expandtab"
},
{
"code": null,
"e": 2772,
"s": 2636,
"text": "Notice the use of setlocal so that these settings only overwrite the general settings from the .vimrc file for the current buffer only."
},
{
"code": null,
"e": 2914,
"s": 2772,
"text": "The next chapters in this article follow the convention of putting language-specific settings in ftplugin and general Vim settings in .vimrc."
},
{
"code": null,
"e": 2936,
"s": 2914,
"text": "Keep your vimrc clean"
},
{
"code": null,
"e": 3055,
"s": 2936,
"text": "This feature only works if Vim runs inside the terminal. In that case, Vim can be suspended by running the Ex command:"
},
{
"code": null,
"e": 3065,
"s": 3055,
"text": ":stop<CR>"
},
{
"code": null,
"e": 3231,
"s": 3065,
"text": "This moves Vim to the background and switches the screen back to the terminal from which Vim was called. Running fg in the terminal moves Vim back to the foreground."
},
{
"code": null,
"e": 3343,
"s": 3231,
"text": "Switching between Vim and a full-screen terminal is so convenient that it’s worth creating a mapping in .vimrc:"
},
{
"code": null,
"e": 3372,
"s": 3343,
"text": "nnoremap <leader>t :stop<CR>"
},
{
"code": null,
"e": 3396,
"s": 3372,
"text": "Terminal Vim versus GUI"
},
{
"code": null,
"e": 3634,
"s": 3396,
"text": "IDEs generally provide a file explorer built as a project drawer. This approach doesn’t mix well with Vim’s window style workflow. After all, how does Vim know in which window you want to open a file you selected from the project drawer?"
},
{
"code": null,
"e": 3833,
"s": 3634,
"text": "Vim already comes with a built-in plugin called netrw. To understand this plugin, imagine Vim windows as flipping cards: on one side you have your file and on the other side the netrw file explorer."
},
{
"code": null,
"e": 4026,
"s": 3833,
"text": "It’s useful to map two key bindings for file browsing in .vimrc. The first one opens netrw at the current file’s directory. The second key binding opens netrw at the current working directory."
},
{
"code": null,
"e": 4083,
"s": 4026,
"text": "nmap <leader>f :Explore<CR>nmap <leader><s-f> :edit.<CR>"
},
{
"code": null,
"e": 4338,
"s": 4083,
"text": "Netrw has some annoying defaults though. It’s recommended to put these two additional netrw settings in .vimrc. The first setting allows to open a file in a right split. The second setting suppresses netrw from saving .netrwhist files in the .vim folder."
},
{
"code": null,
"e": 4385,
"s": 4338,
"text": "let g:netrw_altv = 1let g:netrw_dirhistmax = 0"
},
{
"code": null,
"e": 4497,
"s": 4385,
"text": "Finally, a minimal plugin called vim-vinegar makes netrw more sensible and comes with several useful shortcuts:"
},
{
"code": null,
"e": 4595,
"s": 4497,
"text": "Press - in any buffer to hop up to the directory listing and seek to the file you just came from."
},
{
"code": null,
"e": 4719,
"s": 4595,
"text": "Press . on a file to pre-populate it at the end of a : command line. There’s also !, which starts the line off with a bang."
},
{
"code": null,
"e": 4784,
"s": 4719,
"text": "Press y. to yank an absolute path for the file under the cursor."
},
{
"code": null,
"e": 4825,
"s": 4784,
"text": "You don’t need NERDTREE or (maybe) netrw"
},
{
"code": null,
"e": 4880,
"s": 4825,
"text": "Oil and vinegar — split windows and the project drawer"
},
{
"code": null,
"e": 4892,
"s": 4880,
"text": "vim-vinegar"
},
{
"code": null,
"e": 5182,
"s": 4892,
"text": "Tmux allows to split the screen horizontally into two terminal windows: the upper one for Vim (possible with multiple vertical split windows) and the bottom one containing a IPython console. If you dislike IPython the above procedure will work just as well with the regular Python console."
},
{
"code": null,
"e": 5345,
"s": 5182,
"text": "Next, the plugin vim-slime is used to send selected code from Vim to the IPython console. The following to configuration in the .vimrc file enables this behavior:"
},
{
"code": null,
"e": 5466,
"s": 5345,
"text": "let g:slime_target = \"tmux\"let g:slime_default_config = {\"socket_name\": get(split($TMUX, \",\"), 0), \"target_pane\": \":.1\"}"
},
{
"code": null,
"e": 5658,
"s": 5466,
"text": "Pressing C-c, C-c (holding Ctrl and double-tapping C) sends the paragraph beneath the cursor to the IPython console. (The first time vim-slime will prompt the target pane. Press Enter twice.)"
},
{
"code": null,
"e": 5811,
"s": 5658,
"text": "The above procedure is language agnostic: the same procedure allows to send lines of R code to an R console or lines from a Bash script to the terminal."
},
{
"code": null,
"e": 5821,
"s": 5811,
"text": "vim-slime"
},
{
"code": null,
"e": 5837,
"s": 5821,
"text": "The Tao of Tmux"
},
{
"code": null,
"e": 5993,
"s": 5837,
"text": "It’s convenient to have a shortcut to run the current script in the terminal. Generally, this is done by calling the interpreter followed by the file name:"
},
{
"code": null,
"e": 6012,
"s": 5993,
"text": "python filename.py"
},
{
"code": null,
"e": 6093,
"s": 6012,
"text": "The following mapping in defined in python.vim runs two consecutive Ex-commands:"
},
{
"code": null,
"e": 6149,
"s": 6093,
"text": "nmap <buffer> <leader>r <Esc>:w<CR>:!clear;python %<CR>"
},
{
"code": null,
"e": 6170,
"s": 6149,
"text": "Here’s what it does:"
},
{
"code": null,
"e": 6421,
"s": 6170,
"text": "The first Ex-command :w<CR> saves the file.The second Ex-command starts with :! indicating it’s meant meant for the terminal, clears the terminal with :clear and finally calls the interpreter python %<CR> on the current file whose path is given by %."
},
{
"code": null,
"e": 6465,
"s": 6421,
"text": "The first Ex-command :w<CR> saves the file."
},
{
"code": null,
"e": 6673,
"s": 6465,
"text": "The second Ex-command starts with :! indicating it’s meant meant for the terminal, clears the terminal with :clear and finally calls the interpreter python %<CR> on the current file whose path is given by %."
},
{
"code": null,
"e": 6786,
"s": 6673,
"text": "Notice that this mapping is language-specific. A similar mapping to run a bash script can be defined as follows:"
},
{
"code": null,
"e": 6842,
"s": 6786,
"text": "nnoremap <buffer> <leader>r <Esc>:w<CR>:!clear;sh %<CR>"
},
{
"code": null,
"e": 6869,
"s": 6842,
"text": "Running Python code in Vim"
},
{
"code": null,
"e": 7018,
"s": 6869,
"text": "Debugging is an area where IDEs really shine. Nonetheless, by installing the Python ipdb a satisfactory debugging experience can be obtained in Vim."
},
{
"code": null,
"e": 7315,
"s": 7018,
"text": "The module ipdb is similar to pdb but designed for IPython. It doesn’t have to be installed as it comes with IPython. It allows to define a breakpoint with set_trace() which will pause the program at that point and drop start the debugger where the program’s state can be inspected using IPython."
},
{
"code": null,
"e": 7397,
"s": 7315,
"text": "The following Vim mapping in python.vim puts a breakpoint below the current line:"
},
{
"code": null,
"e": 7465,
"s": 7397,
"text": "nmap <buffer> <leader>b oimport ipdb;ipdb.set_trace(context=5)<ESC>"
},
{
"code": null,
"e": 7539,
"s": 7465,
"text": "The context argument specifies the number of lines shown by the debugger."
},
{
"code": null,
"e": 7722,
"s": 7539,
"text": "A nice feature if IPython is embed which launches a separate IPython session during debugging. Changes made in this session will not affect objects in the original debugging session."
},
{
"code": null,
"e": 7767,
"s": 7722,
"text": "ipdb> from IPython import embedipdb> embed()"
},
{
"code": null,
"e": 7918,
"s": 7767,
"text": "A further review of the debugger commands is beyond the scope of the article. They are nicely documented in the documentation in the referenced below."
},
{
"code": null,
"e": 7936,
"s": 7918,
"text": "pdb documentation"
}
] |
How can I remove the same element in the list by Python
|
Just remove return statement outside for block. It will work. Also last print statement should have remove_same instead of remaove_new
def remove_same(L1, L2):
L1_copy = L1[:]
for e in L1_copy:
if e in L2:
L1.remove(e)
return L1
L1 = [1,2,3,4]
L2 = [1,2,5,6]
print(remove_same(L1, L2))
The result:
[3, 4]
|
[
{
"code": null,
"e": 1197,
"s": 1062,
"text": "Just remove return statement outside for block. It will work. Also last print statement should have remove_same instead of remaove_new"
},
{
"code": null,
"e": 1382,
"s": 1197,
"text": "def remove_same(L1, L2):\n L1_copy = L1[:]\n for e in L1_copy:\n if e in L2:\n L1.remove(e)\n return L1\n\nL1 = [1,2,3,4]\nL2 = [1,2,5,6]\nprint(remove_same(L1, L2))"
},
{
"code": null,
"e": 1394,
"s": 1382,
"text": "The result:"
},
{
"code": null,
"e": 1401,
"s": 1394,
"text": "[3, 4]"
}
] |
Given a sequence of words, print all anagrams together using STL - GeeksforGeeks
|
10 Jun, 2021
Given an array of words, print all anagrams together.
For example,
Input: array = {“cat”, “dog”, “tac”, “god”, “act”}
output: cat tac act, dog god
Explanation: cat tac and act are anagrams
and dog and god are anagrams as
they have the same set of characters.
Input: array = {“abc”, “def”, “ghi”}
output: abc, def, ghi
Explanation: There are no anagrams in the array.
Other approaches are discussed herein these posts:
given-a-sequence-of-words-print-all-anagrams-together
given-a-sequence-of-words-print-all-anagrams-together-set-2
Approach: This is a HashMap solution using C++ Standard Template Library which stores the Key-Value Pair. In the hashmap, the key will be the sorted set of characters and value will be the output string. Two anagrams will be similar when their characters are sorted. Now,
Store the vector elements in HashMap with key as the sorted string.If the key is same, then add the string to the value of HashMap(string vector).Traverse the HashMap and print the anagram strings.
Store the vector elements in HashMap with key as the sorted string.
If the key is same, then add the string to the value of HashMap(string vector).
Traverse the HashMap and print the anagram strings.
C++
Python3
// C++ program for finding all anagram// pairs in the given array#include <algorithm>#include <iostream>#include <unordered_map>#include <vector>using namespace std; // Utility function for// printing anagram listvoid printAnagram(unordered_map<string,vector<string> >& store){ for (auto it:store) { vector<string> temp_vec(it.second); int size = temp_vec.size(); for (int i = 0; i < size; i++) cout << temp_vec[i] << " "; cout << "\n"; }} // Utility function for storing// the vector of strings into HashMapvoid storeInMap(vector<string>& vec){ unordered_map<string,vector<string> > store; for (int i = 0; i < vec.size(); i++) { string tempString(vec[i]); // sort the string sort(tempString.begin(),tempString.end()); // make hash of a sorted string store[tempString].push_back(vec[i]); } // print utility function for printing // all the anagrams printAnagram(store);} // Driver codeint main(){ // initialize vector of strings vector<string> arr; arr.push_back("geeksquiz"); arr.push_back("geeksforgeeks"); arr.push_back("abcd"); arr.push_back("forgeeksgeeks"); arr.push_back("zuiqkeegs"); arr.push_back("cat"); arr.push_back("act"); arr.push_back("tca"); // utility function for storing // strings into hashmap storeInMap(arr); return 0;}
# Python3 program for finding all anagram# pairs in the given arrayfrom collections import defaultdict # Utility function for# printing anagram listdef printAnagram(store: dict) -> None: for (k, v) in store.items(): temp_vec = v size = len(temp_vec) if (size > 1): for i in range(size): print(temp_vec[i], end = " ") print() # Utility function for storing# the vector of strings into HashMapdef storeInMap(vec: list) -> None: store = defaultdict(lambda: list) for i in range(len(vec)): tempString = vec[i] tempString = ''.join(sorted(tempString)) # Check for sorted string # if it already exists if (tempString not in store): temp_vec = [] temp_vec.append(vec[i]) store[tempString] = temp_vec else: # Push new string to # already existing key temp_vec = store[tempString] temp_vec.append(vec[i]) store[tempString] = temp_vec # Print utility function for # printing all the anagrams printAnagram(store) # Driver codeif __name__ == "__main__": # Initialize vector of strings arr = [] arr.append("geeksquiz") arr.append("geeksforgeeks") arr.append("abcd") arr.append("forgeeksgeeks") arr.append("zuiqkeegs") arr.append("cat") arr.append("act") arr.append("tca") # Utility function for storing # strings into hashmap storeInMap(arr) # This code is contributed by sanjeev2552
Note: Compile above program with -std=c++11 flag in g++
Output:
cat act tca
geeksforgeeks forgeeksgeeks
geeksquiz zuiqkeegs
Complexity Analysis:
Time Complexity: O(n * m(log m)), where m is the length of a word.A single traversal through the array is needed.
Space Complexity: O(n). There are n words in a string. The map requires O(n) space to store the strings.
This article is contributed by Mandeep 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.
andrew1234
ssharan3112
sanjeev2552
nareshsaharan1
amitazadi
Amazon
anagram
Snapdeal
STL
Hash
Strings
Amazon
Snapdeal
Hash
Strings
STL
anagram
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Hashing | Set 2 (Separate Chaining)
Counting frequencies of array elements
Most frequent element in an array
Double Hashing
Check if two arrays are equal or not
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
C++ Data Types
Write a program to print all permutations of a given string
|
[
{
"code": null,
"e": 24682,
"s": 24654,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 24737,
"s": 24682,
"text": "Given an array of words, print all anagrams together. "
},
{
"code": null,
"e": 24751,
"s": 24737,
"text": "For example, "
},
{
"code": null,
"e": 25054,
"s": 24751,
"text": "Input: array = {“cat”, “dog”, “tac”, “god”, “act”}\noutput: cat tac act, dog god\nExplanation: cat tac and act are anagrams \nand dog and god are anagrams as \nthey have the same set of characters.\n\nInput: array = {“abc”, “def”, “ghi”}\noutput: abc, def, ghi\nExplanation: There are no anagrams in the array."
},
{
"code": null,
"e": 25107,
"s": 25054,
"text": "Other approaches are discussed herein these posts: "
},
{
"code": null,
"e": 25161,
"s": 25107,
"text": "given-a-sequence-of-words-print-all-anagrams-together"
},
{
"code": null,
"e": 25221,
"s": 25161,
"text": "given-a-sequence-of-words-print-all-anagrams-together-set-2"
},
{
"code": null,
"e": 25495,
"s": 25221,
"text": "Approach: This is a HashMap solution using C++ Standard Template Library which stores the Key-Value Pair. In the hashmap, the key will be the sorted set of characters and value will be the output string. Two anagrams will be similar when their characters are sorted. Now, "
},
{
"code": null,
"e": 25693,
"s": 25495,
"text": "Store the vector elements in HashMap with key as the sorted string.If the key is same, then add the string to the value of HashMap(string vector).Traverse the HashMap and print the anagram strings."
},
{
"code": null,
"e": 25761,
"s": 25693,
"text": "Store the vector elements in HashMap with key as the sorted string."
},
{
"code": null,
"e": 25841,
"s": 25761,
"text": "If the key is same, then add the string to the value of HashMap(string vector)."
},
{
"code": null,
"e": 25893,
"s": 25841,
"text": "Traverse the HashMap and print the anagram strings."
},
{
"code": null,
"e": 25897,
"s": 25893,
"text": "C++"
},
{
"code": null,
"e": 25905,
"s": 25897,
"text": "Python3"
},
{
"code": "// C++ program for finding all anagram// pairs in the given array#include <algorithm>#include <iostream>#include <unordered_map>#include <vector>using namespace std; // Utility function for// printing anagram listvoid printAnagram(unordered_map<string,vector<string> >& store){ for (auto it:store) { vector<string> temp_vec(it.second); int size = temp_vec.size(); for (int i = 0; i < size; i++) cout << temp_vec[i] << \" \"; cout << \"\\n\"; }} // Utility function for storing// the vector of strings into HashMapvoid storeInMap(vector<string>& vec){ unordered_map<string,vector<string> > store; for (int i = 0; i < vec.size(); i++) { string tempString(vec[i]); // sort the string sort(tempString.begin(),tempString.end()); // make hash of a sorted string store[tempString].push_back(vec[i]); } // print utility function for printing // all the anagrams printAnagram(store);} // Driver codeint main(){ // initialize vector of strings vector<string> arr; arr.push_back(\"geeksquiz\"); arr.push_back(\"geeksforgeeks\"); arr.push_back(\"abcd\"); arr.push_back(\"forgeeksgeeks\"); arr.push_back(\"zuiqkeegs\"); arr.push_back(\"cat\"); arr.push_back(\"act\"); arr.push_back(\"tca\"); // utility function for storing // strings into hashmap storeInMap(arr); return 0;}",
"e": 27330,
"s": 25905,
"text": null
},
{
"code": "# Python3 program for finding all anagram# pairs in the given arrayfrom collections import defaultdict # Utility function for# printing anagram listdef printAnagram(store: dict) -> None: for (k, v) in store.items(): temp_vec = v size = len(temp_vec) if (size > 1): for i in range(size): print(temp_vec[i], end = \" \") print() # Utility function for storing# the vector of strings into HashMapdef storeInMap(vec: list) -> None: store = defaultdict(lambda: list) for i in range(len(vec)): tempString = vec[i] tempString = ''.join(sorted(tempString)) # Check for sorted string # if it already exists if (tempString not in store): temp_vec = [] temp_vec.append(vec[i]) store[tempString] = temp_vec else: # Push new string to # already existing key temp_vec = store[tempString] temp_vec.append(vec[i]) store[tempString] = temp_vec # Print utility function for # printing all the anagrams printAnagram(store) # Driver codeif __name__ == \"__main__\": # Initialize vector of strings arr = [] arr.append(\"geeksquiz\") arr.append(\"geeksforgeeks\") arr.append(\"abcd\") arr.append(\"forgeeksgeeks\") arr.append(\"zuiqkeegs\") arr.append(\"cat\") arr.append(\"act\") arr.append(\"tca\") # Utility function for storing # strings into hashmap storeInMap(arr) # This code is contributed by sanjeev2552",
"e": 28901,
"s": 27330,
"text": null
},
{
"code": null,
"e": 28958,
"s": 28901,
"text": "Note: Compile above program with -std=c++11 flag in g++ "
},
{
"code": null,
"e": 28967,
"s": 28958,
"text": "Output: "
},
{
"code": null,
"e": 29030,
"s": 28967,
"text": "cat act tca \ngeeksforgeeks forgeeksgeeks \ngeeksquiz zuiqkeegs "
},
{
"code": null,
"e": 29052,
"s": 29030,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 29167,
"s": 29052,
"text": "Time Complexity: O(n * m(log m)), where m is the length of a word.A single traversal through the array is needed."
},
{
"code": null,
"e": 29272,
"s": 29167,
"text": "Space Complexity: O(n). There are n words in a string. The map requires O(n) space to store the strings."
},
{
"code": null,
"e": 29694,
"s": 29272,
"text": "This article is contributed by Mandeep 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": 29705,
"s": 29694,
"text": "andrew1234"
},
{
"code": null,
"e": 29717,
"s": 29705,
"text": "ssharan3112"
},
{
"code": null,
"e": 29729,
"s": 29717,
"text": "sanjeev2552"
},
{
"code": null,
"e": 29744,
"s": 29729,
"text": "nareshsaharan1"
},
{
"code": null,
"e": 29754,
"s": 29744,
"text": "amitazadi"
},
{
"code": null,
"e": 29761,
"s": 29754,
"text": "Amazon"
},
{
"code": null,
"e": 29769,
"s": 29761,
"text": "anagram"
},
{
"code": null,
"e": 29778,
"s": 29769,
"text": "Snapdeal"
},
{
"code": null,
"e": 29782,
"s": 29778,
"text": "STL"
},
{
"code": null,
"e": 29787,
"s": 29782,
"text": "Hash"
},
{
"code": null,
"e": 29795,
"s": 29787,
"text": "Strings"
},
{
"code": null,
"e": 29802,
"s": 29795,
"text": "Amazon"
},
{
"code": null,
"e": 29811,
"s": 29802,
"text": "Snapdeal"
},
{
"code": null,
"e": 29816,
"s": 29811,
"text": "Hash"
},
{
"code": null,
"e": 29824,
"s": 29816,
"text": "Strings"
},
{
"code": null,
"e": 29828,
"s": 29824,
"text": "STL"
},
{
"code": null,
"e": 29836,
"s": 29828,
"text": "anagram"
},
{
"code": null,
"e": 29934,
"s": 29836,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29943,
"s": 29934,
"text": "Comments"
},
{
"code": null,
"e": 29956,
"s": 29943,
"text": "Old Comments"
},
{
"code": null,
"e": 29992,
"s": 29956,
"text": "Hashing | Set 2 (Separate Chaining)"
},
{
"code": null,
"e": 30031,
"s": 29992,
"text": "Counting frequencies of array elements"
},
{
"code": null,
"e": 30065,
"s": 30031,
"text": "Most frequent element in an array"
},
{
"code": null,
"e": 30080,
"s": 30065,
"text": "Double Hashing"
},
{
"code": null,
"e": 30117,
"s": 30080,
"text": "Check if two arrays are equal or not"
},
{
"code": null,
"e": 30142,
"s": 30117,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30188,
"s": 30142,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 30222,
"s": 30188,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 30237,
"s": 30222,
"text": "C++ Data Types"
}
] |
Check if both halves of the string have same set of characters in Python
|
We can split a long string from the middle and check if the two halves are equal or not. The input string may have an odd or even number of characters. If it has an even number of characters, we divide the two halves by taking half of the length. But if the number of characters is odd then we ignore the middlemost character and then compare the remaining two halves.
In the below program we create the two halves of the input string with above logic and then
from collections import Counter
def comparehalves(input_string):
str_len = len(input_string)
# If number of characyes is odd
# ignore the middle character
if (str_len % 2 != 0):
left = input_string[0:int(str_len / 2)]
right = input_string[(int(str_len / 2)) + 1:]
else:
left = input_string[0:int(str_len / 2)]
right = input_string[int(str_len / 2):]
# Convert the halves into lists
# and sort them
l1 = list(left)
l1.sort()
l2 = list(right)
l2.sort()
if l1 == l2:
print ("Same character in both halves")
else:
print ("Both halves are different ")
in_string = input("Enter String: ")
comparehalves(in_string)
Running the above code gives us the following result −
# Run1
Enter String: Tutorials
Both halves are different
# Run2
Enter String: TutTut
Same character in both halves
|
[
{
"code": null,
"e": 1431,
"s": 1062,
"text": "We can split a long string from the middle and check if the two halves are equal or not. The input string may have an odd or even number of characters. If it has an even number of characters, we divide the two halves by taking half of the length. But if the number of characters is odd then we ignore the middlemost character and then compare the remaining two halves."
},
{
"code": null,
"e": 1523,
"s": 1431,
"text": "In the below program we create the two halves of the input string with above logic and then"
},
{
"code": null,
"e": 2194,
"s": 1523,
"text": "from collections import Counter\ndef comparehalves(input_string):\n str_len = len(input_string)\n# If number of characyes is odd\n# ignore the middle character\n if (str_len % 2 != 0):\n left = input_string[0:int(str_len / 2)]\n right = input_string[(int(str_len / 2)) + 1:]\n else:\n left = input_string[0:int(str_len / 2)]\n right = input_string[int(str_len / 2):]\n# Convert the halves into lists\n# and sort them\n l1 = list(left)\n l1.sort()\n l2 = list(right)\n l2.sort()\n if l1 == l2:\n print (\"Same character in both halves\")\n else:\n print (\"Both halves are different \")\nin_string = input(\"Enter String: \")\ncomparehalves(in_string)"
},
{
"code": null,
"e": 2249,
"s": 2194,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2364,
"s": 2249,
"text": "# Run1\nEnter String: Tutorials\nBoth halves are different\n# Run2\nEnter String: TutTut\nSame character in both halves"
}
] |
Minimize deletions from either end to remove Minimum and Maximum from Array - GeeksforGeeks
|
15 Dec, 2021
Given array of integers arr[] of size N, the task is to find the count of minimum number of deletion operations to remove minimum and the maximum element from the array. The elements can only be deleted from either end of the array.
Examples:
Input: arr = [2, 10, 7, 5, 4, 1, 8, 6]Output: 5Explanation: The minimum element is 1 and the maximum element is 10. We can visualise the deletion operations as below:[2, 10, 7, 5, 4, 1, 8, 6][2, 10, 7, 5, 4, 1, 8][2, 10, 7, 5, 4, 1][2, 10, 7, 5, 4][10, 7, 5, 4][7, 5, 4]
Total 5 deletion operations performed. There is no other sequence with less deleitions in which the minimum and maximum can be deleted.
Input: arr = [56]Output: 1Explanation: Because the array only has one entry, it serves as both the lowest and maximum value. With a single delete, we can eliminate it.
Input: arr = [2, 5, 8, 3, 6, 4]Output: 3Explanation: The minimum element is 2 and the maximum element is 8. We can visualise the deletion operations as below:[2, 5, 8, 3, 6, 4][5, 8, 3, 6, 4][8, 3, 6, 4][3, 6, 4]
Total 3 deletions are performed. It is the minimum possible number of deletions.
Approach: The above problem can be solved using below observation:
Suppose the max and min elements exists at index i and j, or vice versa, as shown below:
[ _ _ _ _ _ min/max _ _ _ _ _ _ max/min _ _ _ _ _ _ ]
<-- a --> (i) <--- b ---> (j) <---- c ---->
<-----------------------N ------------------------->
where,
i, j: index of either max or min element of the array
a: distance of the minimum (or maximum) element from starting
b: distance between minimum and maximum element
c: distance between maximum( or minimum) element from ending
N: length of array
Now let’s look at different possible ways of deletion:
For removing one from start and the other from end:
No. of deletion = (a + c) = ( (i + 1) + (n – j) )
For removing both of them from starting of the array:
No. of deletion = (a + b) = (j + 1)
For removing both of them from the end of the array:
No. of deletion = (b + c) = (n – i)
Using the above equations we can now easily get distances using the index of min and max element. The answer is minimum of these 3 cases
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ code to implement the above approach #include <bits/stdc++.h>using namespace std; // Function to return// the minimum number of deletionsint minDeletions(vector<int>& nums){ int n = nums.size(); // Index of minimum element int minindex = min_element(nums.begin(), nums.end()) - nums.begin(); // Index of maximum element int maxindex = max_element(nums.begin(), nums.end()) - nums.begin(); // Assume that minimum element // always occur before maximum element. // If not, then swap its index. if (minindex > maxindex) swap(minindex, maxindex); // Deletion operations for case-1 int bothend = (minindex + 1) + (n - maxindex); // Deletion operations for case-2 int frontend = (maxindex + 1); // Deletion operations for case-3 int backend = (n - minindex); // Least number of deletions is the answer int ans = min(bothend, min(frontend, backend)); return ans;} // Driver codeint main(){ vector<int> arr{ 2, 10, 7, 5, 4, 1, 8, 6 }; cout << minDeletions(arr) << endl; vector<int> arr2{ 56 }; cout << minDeletions(arr2); return 0;}
// Java code to implement the above approachimport java.util.Arrays;import java.util.stream.IntStream; class GFG{ // Function to return the// minimum number of deletionsint minDeletions(int[] nums){ int n = nums.length; // Index of minimum element int minindex = findIndex(nums, Arrays.stream(nums).min().getAsInt()); // Index of maximum element int maxindex = findIndex( nums, Arrays.stream(nums).max().getAsInt()); // Assume that minimum element // always occur before maximum element. // If not, then swap its index. if (minindex > maxindex) { minindex = minindex + maxindex; maxindex = minindex - maxindex; minindex = minindex - maxindex; } // Deletion operations for case-1 int bothend = (minindex + 1) + (n - maxindex); // Deletion operations for case-2 int frontend = (maxindex + 1); // Deletion operations for case-3 int backend = (n - minindex); // Least number of deletions is the answer int ans = Math.min( bothend, Math.min(frontend, backend)); return ans;} // Function to find the index of an elementpublic static int findIndex(int arr[], int t){ int len = arr.length; return IntStream.range(0, len) .filter(i -> t == arr[i]) .findFirst() // first occurrence .orElse(-1); // No element found} // Driver codepublic static void main(String[] args){ int[] arr = { 2, 10, 7, 5, 4, 1, 8, 6 }; System.out.print(new GFG().minDeletions(arr) + "\n"); int []arr2 = { 56 }; System.out.print(new GFG().minDeletions(arr2));}} // This code is contributed by 29AjayKumar
# Python 3 code to implement the above approach # Function to return# the minimum number of deletionsdef minDeletions(nums): n = len(nums) # Index of minimum element minindex = nums.index(min(nums)) # Index of maximum element maxindex = nums.index(max(nums)) # Assume that minimum element # always occur before maximum element. # If not, then swap its index. if (minindex > maxindex): minindex, maxindex = maxindex, minindex # Deletion operations for case-1 bothend = (minindex + 1) + (n - maxindex) # Deletion operations for case-2 frontend = (maxindex + 1) # Deletion operations for case-3 backend = (n - minindex) # Least number of deletions is the answer ans = min(bothend, min(frontend, backend)) return ans # Driver codeif __name__ == "__main__": arr = [2, 10, 7, 5, 4, 1, 8, 6] print(minDeletions(arr)) arr2 = [56] print(minDeletions(arr2)) # This code is contributed by ukasp.
// C# code to implement the above approachusing System;using System.Linq; public class GFG{ // Function to return the// minimum number of deletionsint minDeletions(int[] nums){ int n = nums.Length; // Index of minimum element int minindex = findIndex(nums, nums.Min()); // Index of maximum element int maxindex = findIndex( nums, nums.Max()); // Assume that minimum element // always occur before maximum element. // If not, then swap its index. if (minindex > maxindex) { minindex = minindex + maxindex; maxindex = minindex - maxindex; minindex = minindex - maxindex; } // Deletion operations for case-1 int bothend = (minindex + 1) + (n - maxindex); // Deletion operations for case-2 int frontend = (maxindex + 1); // Deletion operations for case-3 int backend = (n - minindex); // Least number of deletions is the answer int ans = Math.Min( bothend, Math.Min(frontend, backend)); return ans;} // Function to find the index of an elementpublic static int findIndex(int []arr, int t){ int len = arr.Length; return Array.IndexOf(arr, t);} // Driver codepublic static void Main(String[] args){ int[] arr = { 2, 10, 7, 5, 4, 1, 8, 6 }; Console.Write(new GFG().minDeletions(arr) + "\n"); int []arr2 = { 56 }; Console.Write(new GFG().minDeletions(arr2));}} // This code is contributed by 29AjayKumar
<script> // JavaScript code to implement the above approach // Function to return // the minimum number of deletions const minDeletions = (nums) => { let n = nums.length; // Index of minimum element let minindex = nums.indexOf(Math.min(...nums)); // Index of maximum element let maxindex = nums.indexOf(Math.max(...nums)); // Assume that minimum element // always occur before maximum element. // If not, then swap its index. if (minindex > maxindex) { let temp = minindex; minindex = maxindex; maxindex = temp; } // Deletion operations for case-1 let bothend = (minindex + 1) + (n - maxindex); // Deletion operations for case-2 let frontend = (maxindex + 1); // Deletion operations for case-3 let backend = (n - minindex); // Least number of deletions is the answer let ans = Math.min(bothend, Math.min(frontend, backend)); return ans; } // Driver code let arr = [2, 10, 7, 5, 4, 1, 8, 6]; document.write(`${minDeletions(arr)}<br/>`); let arr2 = [56]; document.write(minDeletions(arr2)); // This code is contributed by rakeshsahni </script>
5
1
Time Complexity: O(N)Auxiliary Space: O(1)
29AjayKumar
ukasp
rakeshsahni
Arrays
Greedy
Mathematical
Arrays
Greedy
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find sum of elements in a given array
Building Heap from Array
Window Sliding Technique
1's and 2's complement of a Binary Number
Reversal algorithm for array rotation
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Write a program to print all permutations of a given string
Huffman Coding | Greedy Algo-3
|
[
{
"code": null,
"e": 24405,
"s": 24377,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 24638,
"s": 24405,
"text": "Given array of integers arr[] of size N, the task is to find the count of minimum number of deletion operations to remove minimum and the maximum element from the array. The elements can only be deleted from either end of the array."
},
{
"code": null,
"e": 24648,
"s": 24638,
"text": "Examples:"
},
{
"code": null,
"e": 24919,
"s": 24648,
"text": "Input: arr = [2, 10, 7, 5, 4, 1, 8, 6]Output: 5Explanation: The minimum element is 1 and the maximum element is 10. We can visualise the deletion operations as below:[2, 10, 7, 5, 4, 1, 8, 6][2, 10, 7, 5, 4, 1, 8][2, 10, 7, 5, 4, 1][2, 10, 7, 5, 4][10, 7, 5, 4][7, 5, 4]"
},
{
"code": null,
"e": 25055,
"s": 24919,
"text": "Total 5 deletion operations performed. There is no other sequence with less deleitions in which the minimum and maximum can be deleted."
},
{
"code": null,
"e": 25223,
"s": 25055,
"text": "Input: arr = [56]Output: 1Explanation: Because the array only has one entry, it serves as both the lowest and maximum value. With a single delete, we can eliminate it."
},
{
"code": null,
"e": 25436,
"s": 25223,
"text": "Input: arr = [2, 5, 8, 3, 6, 4]Output: 3Explanation: The minimum element is 2 and the maximum element is 8. We can visualise the deletion operations as below:[2, 5, 8, 3, 6, 4][5, 8, 3, 6, 4][8, 3, 6, 4][3, 6, 4]"
},
{
"code": null,
"e": 25517,
"s": 25436,
"text": "Total 3 deletions are performed. It is the minimum possible number of deletions."
},
{
"code": null,
"e": 25584,
"s": 25517,
"text": "Approach: The above problem can be solved using below observation:"
},
{
"code": null,
"e": 25674,
"s": 25584,
"text": "Suppose the max and min elements exists at index i and j, or vice versa, as shown below: "
},
{
"code": null,
"e": 25834,
"s": 25674,
"text": "[ _ _ _ _ _ min/max _ _ _ _ _ _ max/min _ _ _ _ _ _ ]\n <-- a --> (i) <--- b ---> (j) <---- c ---->\n<-----------------------N ------------------------->"
},
{
"code": null,
"e": 25841,
"s": 25834,
"text": "where,"
},
{
"code": null,
"e": 25895,
"s": 25841,
"text": "i, j: index of either max or min element of the array"
},
{
"code": null,
"e": 25957,
"s": 25895,
"text": "a: distance of the minimum (or maximum) element from starting"
},
{
"code": null,
"e": 26005,
"s": 25957,
"text": "b: distance between minimum and maximum element"
},
{
"code": null,
"e": 26066,
"s": 26005,
"text": "c: distance between maximum( or minimum) element from ending"
},
{
"code": null,
"e": 26085,
"s": 26066,
"text": "N: length of array"
},
{
"code": null,
"e": 26140,
"s": 26085,
"text": "Now let’s look at different possible ways of deletion:"
},
{
"code": null,
"e": 26192,
"s": 26140,
"text": "For removing one from start and the other from end:"
},
{
"code": null,
"e": 26242,
"s": 26192,
"text": "No. of deletion = (a + c) = ( (i + 1) + (n – j) )"
},
{
"code": null,
"e": 26296,
"s": 26242,
"text": "For removing both of them from starting of the array:"
},
{
"code": null,
"e": 26332,
"s": 26296,
"text": "No. of deletion = (a + b) = (j + 1)"
},
{
"code": null,
"e": 26385,
"s": 26332,
"text": "For removing both of them from the end of the array:"
},
{
"code": null,
"e": 26421,
"s": 26385,
"text": "No. of deletion = (b + c) = (n – i)"
},
{
"code": null,
"e": 26558,
"s": 26421,
"text": "Using the above equations we can now easily get distances using the index of min and max element. The answer is minimum of these 3 cases"
},
{
"code": null,
"e": 26609,
"s": 26558,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 26613,
"s": 26609,
"text": "C++"
},
{
"code": null,
"e": 26618,
"s": 26613,
"text": "Java"
},
{
"code": null,
"e": 26626,
"s": 26618,
"text": "Python3"
},
{
"code": null,
"e": 26629,
"s": 26626,
"text": "C#"
},
{
"code": null,
"e": 26640,
"s": 26629,
"text": "Javascript"
},
{
"code": "// C++ code to implement the above approach #include <bits/stdc++.h>using namespace std; // Function to return// the minimum number of deletionsint minDeletions(vector<int>& nums){ int n = nums.size(); // Index of minimum element int minindex = min_element(nums.begin(), nums.end()) - nums.begin(); // Index of maximum element int maxindex = max_element(nums.begin(), nums.end()) - nums.begin(); // Assume that minimum element // always occur before maximum element. // If not, then swap its index. if (minindex > maxindex) swap(minindex, maxindex); // Deletion operations for case-1 int bothend = (minindex + 1) + (n - maxindex); // Deletion operations for case-2 int frontend = (maxindex + 1); // Deletion operations for case-3 int backend = (n - minindex); // Least number of deletions is the answer int ans = min(bothend, min(frontend, backend)); return ans;} // Driver codeint main(){ vector<int> arr{ 2, 10, 7, 5, 4, 1, 8, 6 }; cout << minDeletions(arr) << endl; vector<int> arr2{ 56 }; cout << minDeletions(arr2); return 0;}",
"e": 27826,
"s": 26640,
"text": null
},
{
"code": "// Java code to implement the above approachimport java.util.Arrays;import java.util.stream.IntStream; class GFG{ // Function to return the// minimum number of deletionsint minDeletions(int[] nums){ int n = nums.length; // Index of minimum element int minindex = findIndex(nums, Arrays.stream(nums).min().getAsInt()); // Index of maximum element int maxindex = findIndex( nums, Arrays.stream(nums).max().getAsInt()); // Assume that minimum element // always occur before maximum element. // If not, then swap its index. if (minindex > maxindex) { minindex = minindex + maxindex; maxindex = minindex - maxindex; minindex = minindex - maxindex; } // Deletion operations for case-1 int bothend = (minindex + 1) + (n - maxindex); // Deletion operations for case-2 int frontend = (maxindex + 1); // Deletion operations for case-3 int backend = (n - minindex); // Least number of deletions is the answer int ans = Math.min( bothend, Math.min(frontend, backend)); return ans;} // Function to find the index of an elementpublic static int findIndex(int arr[], int t){ int len = arr.length; return IntStream.range(0, len) .filter(i -> t == arr[i]) .findFirst() // first occurrence .orElse(-1); // No element found} // Driver codepublic static void main(String[] args){ int[] arr = { 2, 10, 7, 5, 4, 1, 8, 6 }; System.out.print(new GFG().minDeletions(arr) + \"\\n\"); int []arr2 = { 56 }; System.out.print(new GFG().minDeletions(arr2));}} // This code is contributed by 29AjayKumar",
"e": 29445,
"s": 27826,
"text": null
},
{
"code": "# Python 3 code to implement the above approach # Function to return# the minimum number of deletionsdef minDeletions(nums): n = len(nums) # Index of minimum element minindex = nums.index(min(nums)) # Index of maximum element maxindex = nums.index(max(nums)) # Assume that minimum element # always occur before maximum element. # If not, then swap its index. if (minindex > maxindex): minindex, maxindex = maxindex, minindex # Deletion operations for case-1 bothend = (minindex + 1) + (n - maxindex) # Deletion operations for case-2 frontend = (maxindex + 1) # Deletion operations for case-3 backend = (n - minindex) # Least number of deletions is the answer ans = min(bothend, min(frontend, backend)) return ans # Driver codeif __name__ == \"__main__\": arr = [2, 10, 7, 5, 4, 1, 8, 6] print(minDeletions(arr)) arr2 = [56] print(minDeletions(arr2)) # This code is contributed by ukasp.",
"e": 30431,
"s": 29445,
"text": null
},
{
"code": "// C# code to implement the above approachusing System;using System.Linq; public class GFG{ // Function to return the// minimum number of deletionsint minDeletions(int[] nums){ int n = nums.Length; // Index of minimum element int minindex = findIndex(nums, nums.Min()); // Index of maximum element int maxindex = findIndex( nums, nums.Max()); // Assume that minimum element // always occur before maximum element. // If not, then swap its index. if (minindex > maxindex) { minindex = minindex + maxindex; maxindex = minindex - maxindex; minindex = minindex - maxindex; } // Deletion operations for case-1 int bothend = (minindex + 1) + (n - maxindex); // Deletion operations for case-2 int frontend = (maxindex + 1); // Deletion operations for case-3 int backend = (n - minindex); // Least number of deletions is the answer int ans = Math.Min( bothend, Math.Min(frontend, backend)); return ans;} // Function to find the index of an elementpublic static int findIndex(int []arr, int t){ int len = arr.Length; return Array.IndexOf(arr, t);} // Driver codepublic static void Main(String[] args){ int[] arr = { 2, 10, 7, 5, 4, 1, 8, 6 }; Console.Write(new GFG().minDeletions(arr) + \"\\n\"); int []arr2 = { 56 }; Console.Write(new GFG().minDeletions(arr2));}} // This code is contributed by 29AjayKumar",
"e": 31857,
"s": 30431,
"text": null
},
{
"code": "<script> // JavaScript code to implement the above approach // Function to return // the minimum number of deletions const minDeletions = (nums) => { let n = nums.length; // Index of minimum element let minindex = nums.indexOf(Math.min(...nums)); // Index of maximum element let maxindex = nums.indexOf(Math.max(...nums)); // Assume that minimum element // always occur before maximum element. // If not, then swap its index. if (minindex > maxindex) { let temp = minindex; minindex = maxindex; maxindex = temp; } // Deletion operations for case-1 let bothend = (minindex + 1) + (n - maxindex); // Deletion operations for case-2 let frontend = (maxindex + 1); // Deletion operations for case-3 let backend = (n - minindex); // Least number of deletions is the answer let ans = Math.min(bothend, Math.min(frontend, backend)); return ans; } // Driver code let arr = [2, 10, 7, 5, 4, 1, 8, 6]; document.write(`${minDeletions(arr)}<br/>`); let arr2 = [56]; document.write(minDeletions(arr2)); // This code is contributed by rakeshsahni </script>",
"e": 33111,
"s": 31857,
"text": null
},
{
"code": null,
"e": 33115,
"s": 33111,
"text": "5\n1"
},
{
"code": null,
"e": 33158,
"s": 33115,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 33172,
"s": 33160,
"text": "29AjayKumar"
},
{
"code": null,
"e": 33178,
"s": 33172,
"text": "ukasp"
},
{
"code": null,
"e": 33190,
"s": 33178,
"text": "rakeshsahni"
},
{
"code": null,
"e": 33197,
"s": 33190,
"text": "Arrays"
},
{
"code": null,
"e": 33204,
"s": 33197,
"text": "Greedy"
},
{
"code": null,
"e": 33217,
"s": 33204,
"text": "Mathematical"
},
{
"code": null,
"e": 33224,
"s": 33217,
"text": "Arrays"
},
{
"code": null,
"e": 33231,
"s": 33224,
"text": "Greedy"
},
{
"code": null,
"e": 33244,
"s": 33231,
"text": "Mathematical"
},
{
"code": null,
"e": 33342,
"s": 33244,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33351,
"s": 33342,
"text": "Comments"
},
{
"code": null,
"e": 33364,
"s": 33351,
"text": "Old Comments"
},
{
"code": null,
"e": 33413,
"s": 33364,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33438,
"s": 33413,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 33463,
"s": 33438,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33505,
"s": 33463,
"text": "1's and 2's complement of a Binary Number"
},
{
"code": null,
"e": 33543,
"s": 33505,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 33594,
"s": 33543,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 33645,
"s": 33594,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 33703,
"s": 33645,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 33763,
"s": 33703,
"text": "Write a program to print all permutations of a given string"
}
] |
Edit Distance | Practice | GeeksforGeeks
|
Given two strings s and t. Return the minimum number of operations required to convert s to t.
The possible operations are permitted:
Insert a character at any position of the string.
Remove any character from the string.
Replace any character from the string with any other character.
Insert a character at any position of the string.
Remove any character from the string.
Replace any character from the string with any other character.
Example 1:
Input:
s = "geek", t = "gesek"
Output: 1
Explanation: One operation is required
inserting 's' between two 'e's of str1.
Example 2:
Input :
s = "gfg", t = "gfg"
Output:
0
Explanation: Both strings are same.
Your Task:
You don't need to read or print anything. Your task is to complete the function editDistance() which takes strings s and t as input parameters and returns the minimum number of operation to convert the string s to string t.
Expected Time Complexity: O(|s|*|t|)
Expected Space Complexity: O(|s|*|t|)
Constraints:
1 ≤ Length of both strings ≤ 100
Both the strings are in lowercase.
0
santoshkumar15novmth1 day ago
private: int helper(int i, int j, string s1, string s2, vector<vector<int>> &dp) { //base case if(i < 0) return j+1; if(j < 0) return i+1; if(dp[i][j]!=-1) return dp[i][j]; if(s1[i] == s2[j]) return dp[i][j]=helper(i-1, j-1, s1, s2, dp); return dp[i][j]=1 + min(helper(i-1, j, s1, s2, dp), min(helper(i, j-1, s1, s2, dp), helper(i-1, j-1, s1,s2,dp))); } public: int editDistance(string s, string t) { int n=s.size(); int m=t.size(); vector<vector<int>> dp(n, vector<int>(m, -1)); return helper(n-1, m-1, s, t, dp); }
0
aniketsaraswat1122 weeks ago
int editDistance(string s, string t){
int n = s.size(), m = t.size();
int dp[n+1][m+1] = {};
for(int i = 0; i<=n; i++) dp[i][0] = i;
for(int i = 0; i<=m; i++) dp[0][i] = i;
for(int i = 1; i<=n; i++){
for(int j = 1; j<=m; j++){
if(s[i-1] != t[j-1])
dp[i][j] = min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1])) + 1;
else
dp[i][j] = dp[i-1][j-1];
}
}
return dp[n][m];
}
+1
kshitij14102 weeks ago
int editDistance(string s, string t) { int n=s.size(); int m= t.size(); vector<int>prev(m+1),curr(m+1); for(int j=0;j<=m;j++) prev[j]=j; for(int i=1;i<=n;i++) { curr[0]=i; for(int j=1;j<=m;j++) { if(s[i-1]==t[j-1]) curr[j]=prev[j-1]; else{ curr[j]=1+min(curr[j-1],min(prev[j],prev[j-1])); } } prev=curr; } int ans=prev[m]; prev.clear(); curr.clear(); return ans; }
0
joeldcostaec193 weeks ago
class Solution { public int editDistance(String s, String t) { int x=t.length(); int y=s.length(); int[][] dp=new int[x+1][y+1]; dp[0][y]=x; dp[x][0]=y; for(int i=1;i<=x;i++){ dp[i][y]=dp[i-1][y]-1; } for(int i=1;i<=y;i++){ dp[x][i]=dp[x][i-1]-1; } for(int i=x-1;i>=0;i--){ for(int j=y-1;j>=0;j--){ if(t.charAt(i)!=s.charAt(j)){ dp[i][j]=1+Math.min(dp[i+1][j],dp[i][j+1]); dp[i][j]=Math.min(dp[i][j],1+dp[i+1][j+1]); } else dp[i][j]=dp[i+1][j+1]; } } return dp[0][0]; // Code here }}
0
robbinhackk3 weeks ago
int memo[101][101]; int fun(string s1, string s2, int m, int n){ if (m == 0) return n; if (n == 0) return m; if (memo[m][n] != -1) return memo[m][n]; else { if (s1[m - 1] == s2[n - 1]) memo[m][n]= fun(s1, s2, m - 1, n - 1); else { // memo[m][n]= 1 +min(fun(s1, s2, m, n - 1),fun(s1, s2, m - 1, n),fun(s1, s2, m - 1, n - 1)); memo[m][n]= 1 + min(fun(s1, s2, m, n - 1), min(fun(s1, s2, m - 1, n), fun(s1, s2, m - 1, n - 1))); } } return memo[m][n];} int editDistance(string s, string t) { int m = s.length(), n = t.length(); memset(memo,-1,sizeof(memo)); return fun(s, t, m, n); }
0
jainmuskan5654 weeks ago
int editDistance(string s, string t) { int len1= s.length(); int len2= t.length(); int dp[len1+1][len2+1]; for(int i=0;i<len1+1;i++){ for(int j=0;j<len2+1;j++){ //Base case when S len is 0 if(i==0){ dp[i][j]= j; } // if t len is 0 else if(j==0){ dp[i][j]=i; } } } for(int i=1;i<len1+1;i++){ for(int j=1;j<len2+1;j++){ //same char so we just took the diagonal element if(s[i-1]==t[j-1]){ dp[i][j]= dp[i-1][j-1]; } // different then 3 case insert, replace, remove else{ dp[i][j]= 1+min(dp[i][j-1], min(dp[i-1][j-1], dp[i-1][j])); } } } return dp[len1][len2]; }
0
adityagagtiwari1 month ago
Easy java solution.
class Solution { public int editDistance(String s, String t) { // Code here int[][] dp = new int[s.length()+1][t.length()+1]; for(int i=0;i<s.length()+1;i++) { for(int j=0;j<t.length()+1;j++) { if(i==0) dp[i][j] = j; if(j==0) dp[i][j] = i; } } for(int i=1;i<dp.length;i++) { for(int j=1;j<dp[0].length;j++) { //if the character are already equal then it will check for its i-1 and j-1 //characters as for ith character no extra moves will be required if(s.charAt(i-1)==t.charAt(j-1)) { dp[i][j] = dp[i-1][j-1]; } //from all three states i.e. dp[i-1][j-1],dp[i-1][j],dp[i][j-1] its possible // to reach dp[i][j] by performing the three operations hence we will take the //smallest among the three and add 1 to it for the current operation //as the two chracters arent equal else { dp[i][j] = 1 + Math.min(dp[i-1][j-1],Math.min(dp[i-1][j],dp[i][j-1])); } } } return dp[dp.length-1][dp[0].length-1]; }}
0
pujagulhane20011 month ago
int editDistance(string s, string t) { // Code here int x=s.length(); int y=t.length(); int m[x+1][y+1]; for(int i=0;i<x+1;i++) { for(int j=0;j<y+1;j++) { if(i==0) m[0][j]=j; else if(j==0) m[i][0]=i; } } for(int i=1;i<x+1;i++) { for(int j=1;j<y+1;j++) { if(s[i-1]==t[j-1]) { m[i][j] = m[i-1][j-1]; }else{ m[i][j] = 1+min(m[i-1][j] , min(m[i-1][j-1],m[i][j-1])); } } } return m[x][y];
+1
anandkumarsatapathy1 month ago
int longestCommonSubsequence(string s, string t) { int n = s.length(); int m = t.length(); vector<vector<int>>dp(n+1,vector<int>(m+1,0)); // making the diagonal the of the zero ; for(int i = 0;i<=n;i++)dp[i][0]=i; for(int j =0;j<=m;j++)dp[0][j]=j; // this line for the string matching for(int i = 1;i<=n;i++){ for(int j = 1;j<=m;j++){ if(s[i-1]==t[j-1]) { dp[i][j]=dp[i-1][j-1]; } else { dp[i][j]=1+min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1])); } } } return dp[n][m]; } int editDistance(string s, string t) { return longestCommonSubsequence(s,t); }
0
sandeep55211 month ago
1-D array space optimized C++ Solution.
int minDistance(string a, string b) {
int m=a.size(),n=b.size();
vector<int> f(n+1),s(n+1);
for(int i=0;i<=n;i++) f[i]=i;
for(int i=1;i<=m;i++){
s[0]=i;
for(int j=1;j<=n;j++){
if(a[i-1]==b[j-1]) s[j]=f[j-1];
else s[j]=1+min(min(f[j-1],f[j]),s[j-1]);
}
f=s;
}
return f[n];
}
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": 372,
"s": 238,
"text": "Given two strings s and t. Return the minimum number of operations required to convert s to t.\nThe possible operations are permitted:"
},
{
"code": null,
"e": 526,
"s": 372,
"text": "\nInsert a character at any position of the string.\nRemove any character from the string.\nReplace any character from the string with any other character.\n"
},
{
"code": null,
"e": 576,
"s": 526,
"text": "Insert a character at any position of the string."
},
{
"code": null,
"e": 614,
"s": 576,
"text": "Remove any character from the string."
},
{
"code": null,
"e": 678,
"s": 614,
"text": "Replace any character from the string with any other character."
},
{
"code": null,
"e": 691,
"s": 680,
"text": "Example 1:"
},
{
"code": null,
"e": 814,
"s": 691,
"text": "Input: \ns = \"geek\", t = \"gesek\"\nOutput: 1\nExplanation: One operation is required \ninserting 's' between two 'e's of str1.\n"
},
{
"code": null,
"e": 825,
"s": 814,
"text": "Example 2:"
},
{
"code": null,
"e": 903,
"s": 825,
"text": "Input : \ns = \"gfg\", t = \"gfg\"\nOutput: \n0\nExplanation: Both strings are same.\n"
},
{
"code": null,
"e": 1141,
"s": 905,
"text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function editDistance() which takes strings s and t as input parameters and returns the minimum number of operation to convert the string s to string t. "
},
{
"code": null,
"e": 1217,
"s": 1141,
"text": "\nExpected Time Complexity: O(|s|*|t|)\nExpected Space Complexity: O(|s|*|t|)"
},
{
"code": null,
"e": 1299,
"s": 1217,
"text": "\nConstraints:\n1 ≤ Length of both strings ≤ 100\nBoth the strings are in lowercase."
},
{
"code": null,
"e": 1301,
"s": 1299,
"text": "0"
},
{
"code": null,
"e": 1331,
"s": 1301,
"text": "santoshkumar15novmth1 day ago"
},
{
"code": null,
"e": 1977,
"s": 1331,
"text": "private: int helper(int i, int j, string s1, string s2, vector<vector<int>> &dp) { //base case if(i < 0) return j+1; if(j < 0) return i+1; if(dp[i][j]!=-1) return dp[i][j]; if(s1[i] == s2[j]) return dp[i][j]=helper(i-1, j-1, s1, s2, dp); return dp[i][j]=1 + min(helper(i-1, j, s1, s2, dp), min(helper(i, j-1, s1, s2, dp), helper(i-1, j-1, s1,s2,dp))); } public: int editDistance(string s, string t) { int n=s.size(); int m=t.size(); vector<vector<int>> dp(n, vector<int>(m, -1)); return helper(n-1, m-1, s, t, dp); }"
},
{
"code": null,
"e": 1979,
"s": 1977,
"text": "0"
},
{
"code": null,
"e": 2008,
"s": 1979,
"text": "aniketsaraswat1122 weeks ago"
},
{
"code": null,
"e": 2526,
"s": 2008,
"text": "int editDistance(string s, string t){\n int n = s.size(), m = t.size();\n int dp[n+1][m+1] = {};\n for(int i = 0; i<=n; i++) dp[i][0] = i;\n for(int i = 0; i<=m; i++) dp[0][i] = i;\n for(int i = 1; i<=n; i++){\n for(int j = 1; j<=m; j++){\n if(s[i-1] != t[j-1])\n dp[i][j] = min(dp[i-1][j-1],min(dp[i-1][j],dp[i][j-1])) + 1;\n else\n dp[i][j] = dp[i-1][j-1];\n }\n }\n return dp[n][m];\n }"
},
{
"code": null,
"e": 2529,
"s": 2526,
"text": "+1"
},
{
"code": null,
"e": 2552,
"s": 2529,
"text": "kshitij14102 weeks ago"
},
{
"code": null,
"e": 3073,
"s": 2552,
"text": "int editDistance(string s, string t) { int n=s.size(); int m= t.size(); vector<int>prev(m+1),curr(m+1); for(int j=0;j<=m;j++) prev[j]=j; for(int i=1;i<=n;i++) { curr[0]=i; for(int j=1;j<=m;j++) { if(s[i-1]==t[j-1]) curr[j]=prev[j-1]; else{ curr[j]=1+min(curr[j-1],min(prev[j],prev[j-1])); } } prev=curr; } int ans=prev[m]; prev.clear(); curr.clear(); return ans; }"
},
{
"code": null,
"e": 3075,
"s": 3073,
"text": "0"
},
{
"code": null,
"e": 3101,
"s": 3075,
"text": "joeldcostaec193 weeks ago"
},
{
"code": null,
"e": 3791,
"s": 3101,
"text": "class Solution { public int editDistance(String s, String t) { int x=t.length(); int y=s.length(); int[][] dp=new int[x+1][y+1]; dp[0][y]=x; dp[x][0]=y; for(int i=1;i<=x;i++){ dp[i][y]=dp[i-1][y]-1; } for(int i=1;i<=y;i++){ dp[x][i]=dp[x][i-1]-1; } for(int i=x-1;i>=0;i--){ for(int j=y-1;j>=0;j--){ if(t.charAt(i)!=s.charAt(j)){ dp[i][j]=1+Math.min(dp[i+1][j],dp[i][j+1]); dp[i][j]=Math.min(dp[i][j],1+dp[i+1][j+1]); } else dp[i][j]=dp[i+1][j+1]; } } return dp[0][0]; // Code here }}"
},
{
"code": null,
"e": 3793,
"s": 3791,
"text": "0"
},
{
"code": null,
"e": 3816,
"s": 3793,
"text": "robbinhackk3 weeks ago"
},
{
"code": null,
"e": 4513,
"s": 3816,
"text": "int memo[101][101]; int fun(string s1, string s2, int m, int n){ if (m == 0) return n; if (n == 0) return m; if (memo[m][n] != -1) return memo[m][n]; else { if (s1[m - 1] == s2[n - 1]) memo[m][n]= fun(s1, s2, m - 1, n - 1); else { // memo[m][n]= 1 +min(fun(s1, s2, m, n - 1),fun(s1, s2, m - 1, n),fun(s1, s2, m - 1, n - 1)); memo[m][n]= 1 + min(fun(s1, s2, m, n - 1), min(fun(s1, s2, m - 1, n), fun(s1, s2, m - 1, n - 1))); } } return memo[m][n];} int editDistance(string s, string t) { int m = s.length(), n = t.length(); memset(memo,-1,sizeof(memo)); return fun(s, t, m, n); }"
},
{
"code": null,
"e": 4515,
"s": 4513,
"text": "0"
},
{
"code": null,
"e": 4540,
"s": 4515,
"text": "jainmuskan5654 weeks ago"
},
{
"code": null,
"e": 5588,
"s": 4540,
"text": "int editDistance(string s, string t) { int len1= s.length(); int len2= t.length(); int dp[len1+1][len2+1]; for(int i=0;i<len1+1;i++){ for(int j=0;j<len2+1;j++){ //Base case when S len is 0 if(i==0){ dp[i][j]= j; } // if t len is 0 else if(j==0){ dp[i][j]=i; } } } for(int i=1;i<len1+1;i++){ for(int j=1;j<len2+1;j++){ //same char so we just took the diagonal element if(s[i-1]==t[j-1]){ dp[i][j]= dp[i-1][j-1]; } // different then 3 case insert, replace, remove else{ dp[i][j]= 1+min(dp[i][j-1], min(dp[i-1][j-1], dp[i-1][j])); } } } return dp[len1][len2]; }"
},
{
"code": null,
"e": 5590,
"s": 5588,
"text": "0"
},
{
"code": null,
"e": 5617,
"s": 5590,
"text": "adityagagtiwari1 month ago"
},
{
"code": null,
"e": 5637,
"s": 5617,
"text": "Easy java solution."
},
{
"code": null,
"e": 6885,
"s": 5637,
"text": "class Solution { public int editDistance(String s, String t) { // Code here int[][] dp = new int[s.length()+1][t.length()+1]; for(int i=0;i<s.length()+1;i++) { for(int j=0;j<t.length()+1;j++) { if(i==0) dp[i][j] = j; if(j==0) dp[i][j] = i; } } for(int i=1;i<dp.length;i++) { for(int j=1;j<dp[0].length;j++) { //if the character are already equal then it will check for its i-1 and j-1 //characters as for ith character no extra moves will be required if(s.charAt(i-1)==t.charAt(j-1)) { dp[i][j] = dp[i-1][j-1]; } //from all three states i.e. dp[i-1][j-1],dp[i-1][j],dp[i][j-1] its possible // to reach dp[i][j] by performing the three operations hence we will take the //smallest among the three and add 1 to it for the current operation //as the two chracters arent equal else { dp[i][j] = 1 + Math.min(dp[i-1][j-1],Math.min(dp[i-1][j],dp[i][j-1])); } } } return dp[dp.length-1][dp[0].length-1]; }}"
},
{
"code": null,
"e": 6887,
"s": 6885,
"text": "0"
},
{
"code": null,
"e": 6914,
"s": 6887,
"text": "pujagulhane20011 month ago"
},
{
"code": null,
"e": 7470,
"s": 6914,
"text": "int editDistance(string s, string t) { // Code here int x=s.length(); int y=t.length(); int m[x+1][y+1]; for(int i=0;i<x+1;i++) { for(int j=0;j<y+1;j++) { if(i==0) m[0][j]=j; else if(j==0) m[i][0]=i; } } for(int i=1;i<x+1;i++) { for(int j=1;j<y+1;j++) { if(s[i-1]==t[j-1]) { m[i][j] = m[i-1][j-1]; }else{ m[i][j] = 1+min(m[i-1][j] , min(m[i-1][j-1],m[i][j-1])); } } } return m[x][y]; "
},
{
"code": null,
"e": 7473,
"s": 7470,
"text": "+1"
},
{
"code": null,
"e": 7504,
"s": 7473,
"text": "anandkumarsatapathy1 month ago"
},
{
"code": null,
"e": 8397,
"s": 7504,
"text": "int longestCommonSubsequence(string s, string t) { int n = s.length(); int m = t.length(); vector<vector<int>>dp(n+1,vector<int>(m+1,0)); // making the diagonal the of the zero ; for(int i = 0;i<=n;i++)dp[i][0]=i; for(int j =0;j<=m;j++)dp[0][j]=j; // this line for the string matching for(int i = 1;i<=n;i++){ for(int j = 1;j<=m;j++){ if(s[i-1]==t[j-1]) { dp[i][j]=dp[i-1][j-1]; } else { dp[i][j]=1+min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1])); } } } return dp[n][m]; } int editDistance(string s, string t) { return longestCommonSubsequence(s,t); }"
},
{
"code": null,
"e": 8401,
"s": 8399,
"text": "0"
},
{
"code": null,
"e": 8424,
"s": 8401,
"text": "sandeep55211 month ago"
},
{
"code": null,
"e": 8466,
"s": 8424,
"text": " 1-D array space optimized C++ Solution."
},
{
"code": null,
"e": 8859,
"s": 8466,
"text": "int minDistance(string a, string b) {\n int m=a.size(),n=b.size();\n vector<int> f(n+1),s(n+1);\n for(int i=0;i<=n;i++) f[i]=i;\n for(int i=1;i<=m;i++){\n s[0]=i;\n for(int j=1;j<=n;j++){\n if(a[i-1]==b[j-1]) s[j]=f[j-1];\n else s[j]=1+min(min(f[j-1],f[j]),s[j-1]);\n }\n f=s;\n }\n return f[n];\n }"
},
{
"code": null,
"e": 9005,
"s": 8859,
"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": 9041,
"s": 9005,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 9051,
"s": 9041,
"text": "\nProblem\n"
},
{
"code": null,
"e": 9061,
"s": 9051,
"text": "\nContest\n"
},
{
"code": null,
"e": 9124,
"s": 9061,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 9272,
"s": 9124,
"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": 9480,
"s": 9272,
"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": 9586,
"s": 9480,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
What is the purpose of a self-executing function in JavaScript?
|
The purpose of a self-executing is that those variables declared in the self-executing function are only available inside the self-executing function.
Variables declared in the self-executing function are, by default, only available to code within the self-executing function.
It is an immediately invoked function expression (IIFE). It is a function, which executes on creation.
Here is the syntax −
(function() {
// code
})();
As you can see above, the following pair of parentheses converts the code inside the parentheses into an expression:
function(){...}
In addition, the next pair, i.e. the second pair of parentheses continues the operation. It calls the function, which resulted from the expression above.
|
[
{
"code": null,
"e": 1213,
"s": 1062,
"text": "The purpose of a self-executing is that those variables declared in the self-executing function are only available inside the self-executing function."
},
{
"code": null,
"e": 1339,
"s": 1213,
"text": "Variables declared in the self-executing function are, by default, only available to code within the self-executing function."
},
{
"code": null,
"e": 1442,
"s": 1339,
"text": "It is an immediately invoked function expression (IIFE). It is a function, which executes on creation."
},
{
"code": null,
"e": 1463,
"s": 1442,
"text": "Here is the syntax −"
},
{
"code": null,
"e": 1494,
"s": 1463,
"text": "(function() {\n // code\n})();"
},
{
"code": null,
"e": 1611,
"s": 1494,
"text": "As you can see above, the following pair of parentheses converts the code inside the parentheses into an expression:"
},
{
"code": null,
"e": 1627,
"s": 1611,
"text": "function(){...}"
},
{
"code": null,
"e": 1781,
"s": 1627,
"text": "In addition, the next pair, i.e. the second pair of parentheses continues the operation. It calls the function, which resulted from the expression above."
}
] |
DateTime.FromFileTime() Method in C# - GeeksforGeeks
|
28 Jan, 2019
DateTime.FromFileTime(Int64) Method is used to converts the specified Windows file time to an equivalent local time.
Syntax: public static DateTime FromFileTime (long fileTime);Here, it takes a Windows file time expressed in ticks.
Return Value: This method returns an object that represents the local time equivalent of the date and time represented by the fileTime parameter.
Exception: This method will give ArgumentOutOfRangeException if the fileTime is less than 0 or represents a time greater than MaxValue.
Below programs illustrate the use of DateTime.FromFileTime(Int64) Method:
Example 1:
// C# program to demonstrate the// DateTime.FromFileTime(Int64) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date1 = new DateTime(2010, 3, 14, 2, 30, 00); // converting 2500000000000 file // time represented in ticks // into DateTime format // using FromBinary() method DateTime date2 = DateTime.FromFileTime(2500000000000); // Display the date1 System.Console.WriteLine("DateTime before " + "operation: {0:y} {0:dd}", date1); // Display the date2 System.Console.WriteLine("\nDateTime after" + " operation: {0:y} {0:dd}", date2); } catch (ArgumentOutOfRangeException e) { Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
DateTime before operation: 2010 March 14
DateTime after operation: 1601 January 03
Example 2: For ArgumentOutOfRangeException
// C# program to demonstrate the// DateTime.FromFileTime() Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date1 = new DateTime(2010, 3, 14, 2, 30, 00); // converting -1 file time // represented in ticks // into DateTime format // using FromBinary() method DateTime date2 = DateTime.FromFileTime(-1); // Display the date1 System.Console.WriteLine("DateTime before " + "operation: {0:y} {0:dd}",date1); // Display the date2 System.Console.WriteLine("\nDateTime after" + " operation: {0:y} {0:dd}", date2); } catch (ArgumentOutOfRangeException e) { Console.WriteLine("fileTime is less than 0 "); Console.Write("Exception Thrown: "); Console.Write("{0}", e.GetType(), e.Message); } }}
fileTime is less than 0
Exception Thrown: System.ArgumentOutOfRangeException
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.datetime.fromfiletime?view=netframework-4.7.2
CSharp DateTime Struct
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to calculate Electricity Bill
Linked List Implementation in C#
C# | How to insert an element in an Array?
HashSet in C# with Examples
Lambda Expressions in C#
Main Method in C#
Difference between Hashtable and Dictionary in C#
C# | Dictionary.Add() Method
Collections in C#
Different Ways to Convert Char Array to String in C#
|
[
{
"code": null,
"e": 23911,
"s": 23883,
"text": "\n28 Jan, 2019"
},
{
"code": null,
"e": 24028,
"s": 23911,
"text": "DateTime.FromFileTime(Int64) Method is used to converts the specified Windows file time to an equivalent local time."
},
{
"code": null,
"e": 24143,
"s": 24028,
"text": "Syntax: public static DateTime FromFileTime (long fileTime);Here, it takes a Windows file time expressed in ticks."
},
{
"code": null,
"e": 24289,
"s": 24143,
"text": "Return Value: This method returns an object that represents the local time equivalent of the date and time represented by the fileTime parameter."
},
{
"code": null,
"e": 24425,
"s": 24289,
"text": "Exception: This method will give ArgumentOutOfRangeException if the fileTime is less than 0 or represents a time greater than MaxValue."
},
{
"code": null,
"e": 24499,
"s": 24425,
"text": "Below programs illustrate the use of DateTime.FromFileTime(Int64) Method:"
},
{
"code": null,
"e": 24510,
"s": 24499,
"text": "Example 1:"
},
{
"code": "// C# program to demonstrate the// DateTime.FromFileTime(Int64) Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date1 = new DateTime(2010, 3, 14, 2, 30, 00); // converting 2500000000000 file // time represented in ticks // into DateTime format // using FromBinary() method DateTime date2 = DateTime.FromFileTime(2500000000000); // Display the date1 System.Console.WriteLine(\"DateTime before \" + \"operation: {0:y} {0:dd}\", date1); // Display the date2 System.Console.WriteLine(\"\\nDateTime after\" + \" operation: {0:y} {0:dd}\", date2); } catch (ArgumentOutOfRangeException e) { Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 25590,
"s": 24510,
"text": null
},
{
"code": null,
"e": 25675,
"s": 25590,
"text": "DateTime before operation: 2010 March 14\n\nDateTime after operation: 1601 January 03\n"
},
{
"code": null,
"e": 25718,
"s": 25675,
"text": "Example 2: For ArgumentOutOfRangeException"
},
{
"code": "// C# program to demonstrate the// DateTime.FromFileTime() Methodusing System;using System.Globalization; class GFG { // Main Method public static void Main() { try { // creating object of DateTime DateTime date1 = new DateTime(2010, 3, 14, 2, 30, 00); // converting -1 file time // represented in ticks // into DateTime format // using FromBinary() method DateTime date2 = DateTime.FromFileTime(-1); // Display the date1 System.Console.WriteLine(\"DateTime before \" + \"operation: {0:y} {0:dd}\",date1); // Display the date2 System.Console.WriteLine(\"\\nDateTime after\" + \" operation: {0:y} {0:dd}\", date2); } catch (ArgumentOutOfRangeException e) { Console.WriteLine(\"fileTime is less than 0 \"); Console.Write(\"Exception Thrown: \"); Console.Write(\"{0}\", e.GetType(), e.Message); } }}",
"e": 26859,
"s": 25718,
"text": null
},
{
"code": null,
"e": 26938,
"s": 26859,
"text": "fileTime is less than 0 \nException Thrown: System.ArgumentOutOfRangeException\n"
},
{
"code": null,
"e": 26949,
"s": 26938,
"text": "Reference:"
},
{
"code": null,
"e": 27046,
"s": 26949,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.datetime.fromfiletime?view=netframework-4.7.2"
},
{
"code": null,
"e": 27069,
"s": 27046,
"text": "CSharp DateTime Struct"
},
{
"code": null,
"e": 27083,
"s": 27069,
"text": "CSharp-method"
},
{
"code": null,
"e": 27086,
"s": 27083,
"text": "C#"
},
{
"code": null,
"e": 27184,
"s": 27086,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27193,
"s": 27184,
"text": "Comments"
},
{
"code": null,
"e": 27206,
"s": 27193,
"text": "Old Comments"
},
{
"code": null,
"e": 27244,
"s": 27206,
"text": "Program to calculate Electricity Bill"
},
{
"code": null,
"e": 27277,
"s": 27244,
"text": "Linked List Implementation in C#"
},
{
"code": null,
"e": 27320,
"s": 27277,
"text": "C# | How to insert an element in an Array?"
},
{
"code": null,
"e": 27348,
"s": 27320,
"text": "HashSet in C# with Examples"
},
{
"code": null,
"e": 27373,
"s": 27348,
"text": "Lambda Expressions in C#"
},
{
"code": null,
"e": 27391,
"s": 27373,
"text": "Main Method in C#"
},
{
"code": null,
"e": 27441,
"s": 27391,
"text": "Difference between Hashtable and Dictionary in C#"
},
{
"code": null,
"e": 27470,
"s": 27441,
"text": "C# | Dictionary.Add() Method"
},
{
"code": null,
"e": 27488,
"s": 27470,
"text": "Collections in C#"
}
] |
Denoising Noisy Documents. Computer Vision Techniques | by Chinmay Wyawahare | Towards Data Science
|
Numerous scientific papers, historical documentaries/artifacts, recipes, books are stored as papers be it handwritten/typewritten. With time, the paper/notes tend to accumulate noise/dirt through fingerprints, weakening of paper fibers, dirt, coffee/tea stains, abrasions, wrinkling, etc. There are several surface cleaning methods used for both preserving and cleaning, but they have certain limits, the major one being: that the original document might get altered during the process.
I along with Michael Lally and Kartikeya Shukla worked on the data set of noisy documents if from the UC Irvine NoisyOffice Data Set. Denoising dirty documents enables the creation of higher fidelity digital recreations of original documents. Several methods for denoising documents like — Median Filtering, Edge Detection, Dilation & Erosion, Adaptive Filtering, Autoencoding, and Linear Regression are applied to a test dataset and their results are evaluated, discussed, and compared.
Median filtering is the simplest denoising technique and it follows two basic steps: first, obtain the “background” of an image using Median Filtering with a kernel size of 23 x 23, then subtract the background from the image. Only the “foreground” will remain, clear of any noise that existed in the background. In this context, “foreground” is the text or significant details of the document and “background” is the noise, the white space between document elements.
Edge detection methods identify the points where the image brightness changes sharply, to organize them into edges.
Canny edge detection is particularly helpful to extract edges
Before using the techniques, the images were processed to be cleaned away from the edges of noise. First apply dilation, which makes lines thicker by adding pixels to boundaries. Notice this results in “filling in” the text, while edges surrounding stains remain hollow. Then, by applying the reverse operation, erosion, one can completely remove thin lines while preserving the thicker lines.
Another characteristic of the dirty images is that the text tends to be darker than the noise. Within dark noises, the text inside is even darker.
Thus the objective is to preserve pixels that are the darkest locally
Thresholding sets all pixels whose intensity is above a threshold to 1 (background), and the remaining pixels to 0 (foreground). During adaptive thresholding, there is no single global threshold: the threshold value is computed for each pixel. To determine the threshold, we use Gaussian Thresholding. The threshold value is the weighted sum of neighboring pixel intensities, where the weights are a gaussian window
Instead of modelling the entire image at once, we tried predicting the cleaned-up intensity for each pixel within the image and constructed a cleaned image by combining together a set of predicted pixel intensities using linear regression. After creating a vector of y values, and a matrix of x values, the simplest data set is where the x values are just the pixel intensities of the dirty image.
Except at the extremes, there is a linear relationship between the brightness of the dirty images and the cleaned images. There is a broad spread of x values as y approaches 1, and these pixels probably represent stains that need to be removed. The linear model has done a brightness and contrast correction. That’s quite good performance for a simple least squares linear regression!
Autoencoders are neural networks composed of an encoder and a decoder. The encoder compresses the input data into a lower-dimensional representation. The decoder reconstructs the representation to obtain an output that mimics the input as closely as possible. In doing so, the autoencoder learns the most salient features of the input data.
Autoencoders are closely related to principal component analysis (PCA). If the activation function used within the autoencoder is linear within each layer, the latent variables present at the bottleneck (the smallest layer in the network, aka. code) directly correspond to the principal components from PCA
The network is composed of 5 convolutional layers to extract meaningful features from images. In the first four convolutions, we use 64 kernels. Each kernel has different weights, perform different convolutions on the input layer, and produce a different feature map. Each output of the convolution, therefore, is composed of 64 channels.
The encoder uses max-pooling for compression. A sliding filter runs over the input image, to construct a smaller image where each pixel is the max of a region represented by the filter in the original image. The decoder uses up-sampling to restore the image to its original dimensions, by simply repeating the rows and columns of the layer input before feeding it to a convolutional layer.
Batch normalization reduces covariance shift, that is the difference in the distribution of the activations between layers, and allows each layer of the model to learn more independently of other layers.
Model: "model_1"_________________________________________________________________Layer (type) Output Shape Param # =================================================================image_input (InputLayer) (None, 420, 540, 1) 0 _________________________________________________________________Conv1 (Conv2D) (None, 420, 540, 32) 320 _________________________________________________________________pool1 (MaxPooling2D) (None, 210, 270, 32) 0 _________________________________________________________________Conv2 (Conv2D) (None, 210, 270, 64) 18496 _________________________________________________________________pool2 (MaxPooling2D) (None, 105, 135, 64) 0 _________________________________________________________________Conv3 (Conv2D) (None, 105, 135, 64) 36928 _________________________________________________________________upsample1 (UpSampling2D) (None, 210, 270, 64) 0 _________________________________________________________________Conv4 (Conv2D) (None, 210, 270, 32) 18464 _________________________________________________________________upsample2 (UpSampling2D) (None, 420, 540, 32) 0 _________________________________________________________________Conv5 (Conv2D) (None, 420, 540, 1) 289 =================================================================Total params: 74,497Trainable params: 74,497Non-trainable params: 0_________________________________________________________________
After observing the results of various computer vision, machine learning and neural nets, we thought of deploying it as a software tool — “Denoizer” which is hosted on AWS
Here’s the complete code for the comparative study along with the application hosted on AWS:
github.com
[1] F. Zamora-Martinez, S. Espan ̃a-Boquera and M. J. Castro-Bleda,Behaviour-based Clustering of Neural Networks applied to Document Enhancement, in: Computational and Ambient Intelligence, pages 144- 151, Springer, 2007.
[2] Z. Wang, A. C. Bovik “A Universal Image Quality Index” IEEE Signal Processing Letters, Volume 9, Issue 3, Pages 81–84, August 2002
[3] UC Irvine NoisyOffice Data Set: https://archive.ics.uci.edu/ml/datasets/NoisyOffice
|
[
{
"code": null,
"e": 658,
"s": 171,
"text": "Numerous scientific papers, historical documentaries/artifacts, recipes, books are stored as papers be it handwritten/typewritten. With time, the paper/notes tend to accumulate noise/dirt through fingerprints, weakening of paper fibers, dirt, coffee/tea stains, abrasions, wrinkling, etc. There are several surface cleaning methods used for both preserving and cleaning, but they have certain limits, the major one being: that the original document might get altered during the process."
},
{
"code": null,
"e": 1146,
"s": 658,
"text": "I along with Michael Lally and Kartikeya Shukla worked on the data set of noisy documents if from the UC Irvine NoisyOffice Data Set. Denoising dirty documents enables the creation of higher fidelity digital recreations of original documents. Several methods for denoising documents like — Median Filtering, Edge Detection, Dilation & Erosion, Adaptive Filtering, Autoencoding, and Linear Regression are applied to a test dataset and their results are evaluated, discussed, and compared."
},
{
"code": null,
"e": 1614,
"s": 1146,
"text": "Median filtering is the simplest denoising technique and it follows two basic steps: first, obtain the “background” of an image using Median Filtering with a kernel size of 23 x 23, then subtract the background from the image. Only the “foreground” will remain, clear of any noise that existed in the background. In this context, “foreground” is the text or significant details of the document and “background” is the noise, the white space between document elements."
},
{
"code": null,
"e": 1730,
"s": 1614,
"text": "Edge detection methods identify the points where the image brightness changes sharply, to organize them into edges."
},
{
"code": null,
"e": 1792,
"s": 1730,
"text": "Canny edge detection is particularly helpful to extract edges"
},
{
"code": null,
"e": 2186,
"s": 1792,
"text": "Before using the techniques, the images were processed to be cleaned away from the edges of noise. First apply dilation, which makes lines thicker by adding pixels to boundaries. Notice this results in “filling in” the text, while edges surrounding stains remain hollow. Then, by applying the reverse operation, erosion, one can completely remove thin lines while preserving the thicker lines."
},
{
"code": null,
"e": 2333,
"s": 2186,
"text": "Another characteristic of the dirty images is that the text tends to be darker than the noise. Within dark noises, the text inside is even darker."
},
{
"code": null,
"e": 2403,
"s": 2333,
"text": "Thus the objective is to preserve pixels that are the darkest locally"
},
{
"code": null,
"e": 2819,
"s": 2403,
"text": "Thresholding sets all pixels whose intensity is above a threshold to 1 (background), and the remaining pixels to 0 (foreground). During adaptive thresholding, there is no single global threshold: the threshold value is computed for each pixel. To determine the threshold, we use Gaussian Thresholding. The threshold value is the weighted sum of neighboring pixel intensities, where the weights are a gaussian window"
},
{
"code": null,
"e": 3217,
"s": 2819,
"text": "Instead of modelling the entire image at once, we tried predicting the cleaned-up intensity for each pixel within the image and constructed a cleaned image by combining together a set of predicted pixel intensities using linear regression. After creating a vector of y values, and a matrix of x values, the simplest data set is where the x values are just the pixel intensities of the dirty image."
},
{
"code": null,
"e": 3602,
"s": 3217,
"text": "Except at the extremes, there is a linear relationship between the brightness of the dirty images and the cleaned images. There is a broad spread of x values as y approaches 1, and these pixels probably represent stains that need to be removed. The linear model has done a brightness and contrast correction. That’s quite good performance for a simple least squares linear regression!"
},
{
"code": null,
"e": 3943,
"s": 3602,
"text": "Autoencoders are neural networks composed of an encoder and a decoder. The encoder compresses the input data into a lower-dimensional representation. The decoder reconstructs the representation to obtain an output that mimics the input as closely as possible. In doing so, the autoencoder learns the most salient features of the input data."
},
{
"code": null,
"e": 4250,
"s": 3943,
"text": "Autoencoders are closely related to principal component analysis (PCA). If the activation function used within the autoencoder is linear within each layer, the latent variables present at the bottleneck (the smallest layer in the network, aka. code) directly correspond to the principal components from PCA"
},
{
"code": null,
"e": 4589,
"s": 4250,
"text": "The network is composed of 5 convolutional layers to extract meaningful features from images. In the first four convolutions, we use 64 kernels. Each kernel has different weights, perform different convolutions on the input layer, and produce a different feature map. Each output of the convolution, therefore, is composed of 64 channels."
},
{
"code": null,
"e": 4979,
"s": 4589,
"text": "The encoder uses max-pooling for compression. A sliding filter runs over the input image, to construct a smaller image where each pixel is the max of a region represented by the filter in the original image. The decoder uses up-sampling to restore the image to its original dimensions, by simply repeating the rows and columns of the layer input before feeding it to a convolutional layer."
},
{
"code": null,
"e": 5183,
"s": 4979,
"text": "Batch normalization reduces covariance shift, that is the difference in the distribution of the activations between layers, and allows each layer of the model to learn more independently of other layers."
},
{
"code": null,
"e": 6827,
"s": 5183,
"text": "Model: \"model_1\"_________________________________________________________________Layer (type) Output Shape Param # =================================================================image_input (InputLayer) (None, 420, 540, 1) 0 _________________________________________________________________Conv1 (Conv2D) (None, 420, 540, 32) 320 _________________________________________________________________pool1 (MaxPooling2D) (None, 210, 270, 32) 0 _________________________________________________________________Conv2 (Conv2D) (None, 210, 270, 64) 18496 _________________________________________________________________pool2 (MaxPooling2D) (None, 105, 135, 64) 0 _________________________________________________________________Conv3 (Conv2D) (None, 105, 135, 64) 36928 _________________________________________________________________upsample1 (UpSampling2D) (None, 210, 270, 64) 0 _________________________________________________________________Conv4 (Conv2D) (None, 210, 270, 32) 18464 _________________________________________________________________upsample2 (UpSampling2D) (None, 420, 540, 32) 0 _________________________________________________________________Conv5 (Conv2D) (None, 420, 540, 1) 289 =================================================================Total params: 74,497Trainable params: 74,497Non-trainable params: 0_________________________________________________________________"
},
{
"code": null,
"e": 6999,
"s": 6827,
"text": "After observing the results of various computer vision, machine learning and neural nets, we thought of deploying it as a software tool — “Denoizer” which is hosted on AWS"
},
{
"code": null,
"e": 7092,
"s": 6999,
"text": "Here’s the complete code for the comparative study along with the application hosted on AWS:"
},
{
"code": null,
"e": 7103,
"s": 7092,
"text": "github.com"
},
{
"code": null,
"e": 7325,
"s": 7103,
"text": "[1] F. Zamora-Martinez, S. Espan ̃a-Boquera and M. J. Castro-Bleda,Behaviour-based Clustering of Neural Networks applied to Document Enhancement, in: Computational and Ambient Intelligence, pages 144- 151, Springer, 2007."
},
{
"code": null,
"e": 7460,
"s": 7325,
"text": "[2] Z. Wang, A. C. Bovik “A Universal Image Quality Index” IEEE Signal Processing Letters, Volume 9, Issue 3, Pages 81–84, August 2002"
}
] |
A Simple Guide to Automate Your Excel Reporting with Python | by Frank Andrade | Towards Data Science
|
Let’s face it; no matter what our job is, sooner or later, we will have to deal with repetitive tasks like updating a daily report in Excel. Things could get worse if you work for a company that doesn’t work with Python because you wouldn't be able to solve this problem by using only Python.
But don’t worry, you still can use your Python skills to automate your excel reporting without having to convince your boss to migrate to Python! You only have to use the Python module openpyxl to tell Excel what you want to do through Python. Unlike a previous article I wrote that encourages you to move from Excel to Python, with openpyxl you would be able to stick to Excel while creating your reports with Python.
Table of Contents1. The Dataset2. Make a Pivot Table with Pandas - Importing libraries - Reading the Excel file - Making a pivot table - Exporting pivot table to Excel file3. Make The Report with Openpyxl - Creating row and column reference - Adding Excel charts through Python - Applying Excel formulas through Python - Formatting the report sheet4. Automating the Report with a Python Function (Full code) - Applying the function to a single Excel file - Applying the function to multiple Excel files5. Schedule the Python Script to Run Monthly, Weekly, or Daily
In this guide, we’ll use an Excel file with sales data that is similar to those files you have as inputs to make reports at work. You can download this file on Kaggle; however, it has a .csv format, so you should change the extension to .xlsx or just download it from this Google Drive link (I also changed the file name to supermarket_sales.xlsx)
Before writing any code, take look at the file on Google Drive and familiarize yourself with it. That file is going to be the input to create the following report through Python.
Now let’s make that report and automate it with Python!
Now that you downloaded the Excel file, let’s import the libraries we’ll use in this guide.
import pandas as pdimport openpyxlfrom openpyxl import load_workbookfrom openpyxl.styles import Fontfrom openpyxl.chart import BarChart, Referenceimport string
We’ll use Pandas to read the Excel file, create a pivot table, and export it to Excel. Then we’ll use the Openpyxl library to write Excel formulas, make charts and format the spreadsheet through Python. Finally, we’ll create a Python function to automate this process.
Note: If you don’t have those libraries installed in Python, you can easily install them by writing pip install pandas and pip install openpyxl on your terminal or command prompt.
Before we read the Excel file, make sure the file is in the same place where your Python script is located. Then, read the Excel file with pd.read_excel() like in the following code.
excel_file = pd.read_excel('supermarket_sales.xlsx')excel_file[['Gender', 'Product line', 'Total']]
The file has many columns but we’ll only use the Gender, Product line, and Total columns for the report we’re going to create. To show you how they look like, I selected them using double brackets. If we print this on Jupyter Notebooks, you’ll see the following dataframe that looks like an Excel spreadsheet.
We can easily create a pivot table from the excel_file dataframe previously created. We just need to use the .pivot_table() method. Let’s say we want to create a pivot table that shows the total money spent by males and females on the different product lines. To do so, we write the following code.
report_table = excel_file.pivot_table(index='Gender', columns='Product line', values='Total', aggfunc='sum').round(0)
The report_table should look something like this.
To export the previous pivot table created we use the .to_excel() method. Inside parentheses, we have to write the name of the output Excel file. In this case, I’ll name this file as report_2021.xlsx
We can also specify the name of the sheet we want to create and in which cell the pivot table should be located.
report_table.to_excel('report_2021.xlsx', sheet_name='Report', startrow=4)
Now the Excel file is exported in the same folder your Python script is located.
Every time we want to access a workbook we’ll use the load_workbook imported from openpyxl and then save it with the .save() method. In the following sections, I’ll be loading and saving the workbook every time we modify the workbook; however, you only need to do this once (like in the full code shown at the end of this guide)
To automate the report, we need to take the minimum and maximum active column/row, so the code we’re going to write keeps working even if we add more data.
To obtain the references in the workbook, we first load the workbook with load_workbook() and locate the sheet we want to work with using wb[‘name_of_sheet’]. Then we access the active cells with .active
wb = load_workbook('report_2021.xlsx')sheet = wb['Report']# cell references (original spreadsheet) min_column = wb.active.min_columnmax_column = wb.active.max_columnmin_row = wb.active.min_rowmax_row = wb.active.max_row
You can print the variables created to get an idea of what they mean. For this example, we obtain these numbers.
Min Columns: 1Max Columns: 7Min Rows: 5Max Rows: 7
Open thereport_2021.xlsx we exported before to verify this.
As you can in the picture above, the minimum row is 5 and the maximum row is 7. Also, the minimum row is A (1) and the maximum row is G (7). These references will be extremely useful for the following sections.
To create an Excel chart from the pivot table we created we need to use the Barchart module we imported before. To identify the position of the data and category values, we use the Reference module from openpyxl (we imported Reference in the beginning of this article)
wb = load_workbook('report_2021.xlsx')sheet = wb['Report']# barchartbarchart = BarChart()#locate data and categoriesdata = Reference(sheet, min_col=min_column+1, max_col=max_column, min_row=min_row, max_row=max_row) #including headerscategories = Reference(sheet, min_col=min_column, max_col=min_column, min_row=min_row+1, max_row=max_row) #not including headers# adding data and categoriesbarchart.add_data(data, titles_from_data=True)barchart.set_categories(categories)#location chartsheet.add_chart(barchart, "B12")barchart.title = 'Sales by Product line'barchart.style = 5 #choose the chart stylewb.save('report_2021.xlsx')
After writing that code, the report_2021.xlsx file should look like this.
Breaking down the code:
barchart = BarChart() initializes a barchart variable from the Barchart class
data and categories are variables that represent where that information is located. We’re using the column and row references we defined above to automate this. Also, keep in mind that I’m including the headers in data but not in categories
We use add_data and set_categories to add the necessary data to the barchart. Inside add_data I’m adding the titles_from_data=True because I included the headers for data
We use sheet.add_chart to specify what we want to add to the “Report” sheet and in which cell we want to add it
We can modify the default title and chart style using barchart.title and barchart.style
We save all the changes with wb.save()
You can write Excel formulas through Python the same way you’d write in an Excel sheet. For example, let’s say we wish to sum the data in cells B5 and B6 and show it on cell B7 with the currency style.
sheet['B7'] = '=SUM(B5:B6)'sheet['B7'].style = 'Currency'
That’s pretty simple, right? We can repeat that from column B to G or use a for loop to automate it. But first, we need to get the alphabet to have it as a reference for the names that columns have in Excel (A, B, C, ...) To do so, we use the string library and write the following code.
import stringalphabet = list(string.ascii_uppercase)excel_alphabet = alphabet[0:max_column] print(excel_alphabet)
If we print this we’ll obtain a list from A to G.
This happens because first, we created an alphabet list from A to Z, but then we took a slice [0:max_column] to match the length of this list (7) with the first 7 letters of the alphabet (A-G).
Note: Python lists start on 0, so A=0, B=1, C=2, and so on. Also, the [a:b] slice notation takes b-a elements (starting with “a” and ending with “b-1”)
After this, we can make a loop through the columns and apply the sum formula but now with column references, so instead of writing this,
sheet['B7'] = '=SUM(B5:B6)'sheet['B7'].style = 'Currency'
now we include reference and put it inside a for loop.
wb = load_workbook('report_2021.xlsx')sheet = wb['Report']# sum in columns B-Gfor i in excel_alphabet: if i!='A': sheet[f'{i}{max_row+1}'] = f'=SUM({i}{min_row+1}:{i}{max_row})' sheet[f'{i}{max_row+1}'].style = 'Currency'# adding total labelsheet[f'{excel_alphabet[0]}{max_row+1}'] = 'Total'wb.save('report_2021.xlsx')
After running the code, we get the =SUM formula in the “Total” row for columns between B to G.
Breaking down the code:
for i in excel_alphabet loops through all the active columns, but then we excluded the A column with if i!='A' because the A column doesn’t contain numeric data
sheet[f'{i}{max_row+1}'] = f'=SUM({i}{min_row+1}:{i}{max_row}' is the same as writing sheet['B7'] = '=SUM(B5:B6)' but now we do that for columns A to G
sheet[f'{i}{max_row+1}'].style = 'Currency' gives the currency style to cells below the maximum row.
We add the ‘Total’ label to the A column below the maximum row withsheet[f'{excel_alphabet[0]}{max_row+1}'] = 'Total'
To finish the report, we can add a title, subtitle and also customize their font.
wb = load_workbook('report_2021.xlsx')sheet = wb['Report']sheet['A1'] = 'Sales Report'sheet['A2'] = '2021'sheet['A1'].font = Font('Arial', bold=True, size=20)sheet['A2'].font = Font('Arial', bold=True, size=10)wb.save('report_2021.xlsx')
You can add other parameters inside Font(). On this website, you can find a list of styles available.
The final report should look like the following picture.
Now that the report is ready, we can put all the code we’ve written so far inside a function that automates the report, so the next time we want to make this report we only have to introduce the file name and run it.
Notes: For this function to work, the file name should have the structure “sales_month.xlsx” Also, I added a few lines of code that use the name of the month/year of the sales file as a variable, so we can reuse it in the output file and subtitle of the report.
The code below might look intimidating, but it’s only what we’ve written so far plus the new variables file_name, month_name, and month_and_extension.
Let’s imagine the original file we downloaded has the name “sales_2021.xlsx” instead of “supermarket_sales.xlsx” With this we can apply the formula to the report by writing the following
automate_excel('sales_2021.xlsx')
After running this code, you’ll see an Excel file named “report_2021.xlsx” in the same folder your Python script is located.
Let’s imagine now we have only monthly Excel files “sales_january.xlsx” “sales_february.xlsx” and “sales_march.xlsx” (You can find those files on my Github to test them)
You can either apply the formula one by one to get 3 reports
automate_excel('sales_january.xlsx')automate_excel('sales_february.xlsx')automate_excel('sales_march.xlsx')
or you could concatenate them first using pd.concat() and then apply the function only once.
# read excel filesexcel_file_1 = pd.read_excel('sales_january.xlsx')excel_file_2 = pd.read_excel('sales_february.xlsx')excel_file_3 = pd.read_excel('sales_march.xlsx')# concatenate filesnew_file = pd.concat([excel_file_1, excel_file_2, excel_file_3], ignore_index=True)# export filenew_file.to_excel('sales_2021.xlsx')# apply functionautomate_excel('sales_2021.xlsx')
You can schedule the Python script we’ve written in this guide to run whenever you want on your computer. You just need to use the task scheduler or crontab on Windows and Mac respectively.
If you don’t know how to schedule a job, click on the guide below to learn how to do it.
towardsdatascience.com
That’s it! In this article, you learned how to automate a basic Excel report; however, you can do even more on your own once you master the Pandas library. In the link below, you can find a complete guide of Pandas I wrote especially for Excel users.
towardsdatascience.com
I also made a guide to help you build your first machine learning model with Python.
towardsdatascience.com
You can find the code behind this analysis on my Github.
Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials (Free PDF)
|
[
{
"code": null,
"e": 464,
"s": 171,
"text": "Let’s face it; no matter what our job is, sooner or later, we will have to deal with repetitive tasks like updating a daily report in Excel. Things could get worse if you work for a company that doesn’t work with Python because you wouldn't be able to solve this problem by using only Python."
},
{
"code": null,
"e": 883,
"s": 464,
"text": "But don’t worry, you still can use your Python skills to automate your excel reporting without having to convince your boss to migrate to Python! You only have to use the Python module openpyxl to tell Excel what you want to do through Python. Unlike a previous article I wrote that encourages you to move from Excel to Python, with openpyxl you would be able to stick to Excel while creating your reports with Python."
},
{
"code": null,
"e": 1448,
"s": 883,
"text": "Table of Contents1. The Dataset2. Make a Pivot Table with Pandas - Importing libraries - Reading the Excel file - Making a pivot table - Exporting pivot table to Excel file3. Make The Report with Openpyxl - Creating row and column reference - Adding Excel charts through Python - Applying Excel formulas through Python - Formatting the report sheet4. Automating the Report with a Python Function (Full code) - Applying the function to a single Excel file - Applying the function to multiple Excel files5. Schedule the Python Script to Run Monthly, Weekly, or Daily"
},
{
"code": null,
"e": 1796,
"s": 1448,
"text": "In this guide, we’ll use an Excel file with sales data that is similar to those files you have as inputs to make reports at work. You can download this file on Kaggle; however, it has a .csv format, so you should change the extension to .xlsx or just download it from this Google Drive link (I also changed the file name to supermarket_sales.xlsx)"
},
{
"code": null,
"e": 1975,
"s": 1796,
"text": "Before writing any code, take look at the file on Google Drive and familiarize yourself with it. That file is going to be the input to create the following report through Python."
},
{
"code": null,
"e": 2031,
"s": 1975,
"text": "Now let’s make that report and automate it with Python!"
},
{
"code": null,
"e": 2123,
"s": 2031,
"text": "Now that you downloaded the Excel file, let’s import the libraries we’ll use in this guide."
},
{
"code": null,
"e": 2283,
"s": 2123,
"text": "import pandas as pdimport openpyxlfrom openpyxl import load_workbookfrom openpyxl.styles import Fontfrom openpyxl.chart import BarChart, Referenceimport string"
},
{
"code": null,
"e": 2552,
"s": 2283,
"text": "We’ll use Pandas to read the Excel file, create a pivot table, and export it to Excel. Then we’ll use the Openpyxl library to write Excel formulas, make charts and format the spreadsheet through Python. Finally, we’ll create a Python function to automate this process."
},
{
"code": null,
"e": 2732,
"s": 2552,
"text": "Note: If you don’t have those libraries installed in Python, you can easily install them by writing pip install pandas and pip install openpyxl on your terminal or command prompt."
},
{
"code": null,
"e": 2915,
"s": 2732,
"text": "Before we read the Excel file, make sure the file is in the same place where your Python script is located. Then, read the Excel file with pd.read_excel() like in the following code."
},
{
"code": null,
"e": 3015,
"s": 2915,
"text": "excel_file = pd.read_excel('supermarket_sales.xlsx')excel_file[['Gender', 'Product line', 'Total']]"
},
{
"code": null,
"e": 3325,
"s": 3015,
"text": "The file has many columns but we’ll only use the Gender, Product line, and Total columns for the report we’re going to create. To show you how they look like, I selected them using double brackets. If we print this on Jupyter Notebooks, you’ll see the following dataframe that looks like an Excel spreadsheet."
},
{
"code": null,
"e": 3624,
"s": 3325,
"text": "We can easily create a pivot table from the excel_file dataframe previously created. We just need to use the .pivot_table() method. Let’s say we want to create a pivot table that shows the total money spent by males and females on the different product lines. To do so, we write the following code."
},
{
"code": null,
"e": 3853,
"s": 3624,
"text": "report_table = excel_file.pivot_table(index='Gender', columns='Product line', values='Total', aggfunc='sum').round(0)"
},
{
"code": null,
"e": 3903,
"s": 3853,
"text": "The report_table should look something like this."
},
{
"code": null,
"e": 4103,
"s": 3903,
"text": "To export the previous pivot table created we use the .to_excel() method. Inside parentheses, we have to write the name of the output Excel file. In this case, I’ll name this file as report_2021.xlsx"
},
{
"code": null,
"e": 4216,
"s": 4103,
"text": "We can also specify the name of the sheet we want to create and in which cell the pivot table should be located."
},
{
"code": null,
"e": 4333,
"s": 4216,
"text": "report_table.to_excel('report_2021.xlsx', sheet_name='Report', startrow=4)"
},
{
"code": null,
"e": 4414,
"s": 4333,
"text": "Now the Excel file is exported in the same folder your Python script is located."
},
{
"code": null,
"e": 4743,
"s": 4414,
"text": "Every time we want to access a workbook we’ll use the load_workbook imported from openpyxl and then save it with the .save() method. In the following sections, I’ll be loading and saving the workbook every time we modify the workbook; however, you only need to do this once (like in the full code shown at the end of this guide)"
},
{
"code": null,
"e": 4899,
"s": 4743,
"text": "To automate the report, we need to take the minimum and maximum active column/row, so the code we’re going to write keeps working even if we add more data."
},
{
"code": null,
"e": 5103,
"s": 4899,
"text": "To obtain the references in the workbook, we first load the workbook with load_workbook() and locate the sheet we want to work with using wb[‘name_of_sheet’]. Then we access the active cells with .active"
},
{
"code": null,
"e": 5323,
"s": 5103,
"text": "wb = load_workbook('report_2021.xlsx')sheet = wb['Report']# cell references (original spreadsheet) min_column = wb.active.min_columnmax_column = wb.active.max_columnmin_row = wb.active.min_rowmax_row = wb.active.max_row"
},
{
"code": null,
"e": 5436,
"s": 5323,
"text": "You can print the variables created to get an idea of what they mean. For this example, we obtain these numbers."
},
{
"code": null,
"e": 5487,
"s": 5436,
"text": "Min Columns: 1Max Columns: 7Min Rows: 5Max Rows: 7"
},
{
"code": null,
"e": 5547,
"s": 5487,
"text": "Open thereport_2021.xlsx we exported before to verify this."
},
{
"code": null,
"e": 5758,
"s": 5547,
"text": "As you can in the picture above, the minimum row is 5 and the maximum row is 7. Also, the minimum row is A (1) and the maximum row is G (7). These references will be extremely useful for the following sections."
},
{
"code": null,
"e": 6027,
"s": 5758,
"text": "To create an Excel chart from the pivot table we created we need to use the Barchart module we imported before. To identify the position of the data and category values, we use the Reference module from openpyxl (we imported Reference in the beginning of this article)"
},
{
"code": null,
"e": 6807,
"s": 6027,
"text": "wb = load_workbook('report_2021.xlsx')sheet = wb['Report']# barchartbarchart = BarChart()#locate data and categoriesdata = Reference(sheet, min_col=min_column+1, max_col=max_column, min_row=min_row, max_row=max_row) #including headerscategories = Reference(sheet, min_col=min_column, max_col=min_column, min_row=min_row+1, max_row=max_row) #not including headers# adding data and categoriesbarchart.add_data(data, titles_from_data=True)barchart.set_categories(categories)#location chartsheet.add_chart(barchart, \"B12\")barchart.title = 'Sales by Product line'barchart.style = 5 #choose the chart stylewb.save('report_2021.xlsx')"
},
{
"code": null,
"e": 6881,
"s": 6807,
"text": "After writing that code, the report_2021.xlsx file should look like this."
},
{
"code": null,
"e": 6905,
"s": 6881,
"text": "Breaking down the code:"
},
{
"code": null,
"e": 6983,
"s": 6905,
"text": "barchart = BarChart() initializes a barchart variable from the Barchart class"
},
{
"code": null,
"e": 7224,
"s": 6983,
"text": "data and categories are variables that represent where that information is located. We’re using the column and row references we defined above to automate this. Also, keep in mind that I’m including the headers in data but not in categories"
},
{
"code": null,
"e": 7395,
"s": 7224,
"text": "We use add_data and set_categories to add the necessary data to the barchart. Inside add_data I’m adding the titles_from_data=True because I included the headers for data"
},
{
"code": null,
"e": 7507,
"s": 7395,
"text": "We use sheet.add_chart to specify what we want to add to the “Report” sheet and in which cell we want to add it"
},
{
"code": null,
"e": 7595,
"s": 7507,
"text": "We can modify the default title and chart style using barchart.title and barchart.style"
},
{
"code": null,
"e": 7634,
"s": 7595,
"text": "We save all the changes with wb.save()"
},
{
"code": null,
"e": 7836,
"s": 7634,
"text": "You can write Excel formulas through Python the same way you’d write in an Excel sheet. For example, let’s say we wish to sum the data in cells B5 and B6 and show it on cell B7 with the currency style."
},
{
"code": null,
"e": 7894,
"s": 7836,
"text": "sheet['B7'] = '=SUM(B5:B6)'sheet['B7'].style = 'Currency'"
},
{
"code": null,
"e": 8182,
"s": 7894,
"text": "That’s pretty simple, right? We can repeat that from column B to G or use a for loop to automate it. But first, we need to get the alphabet to have it as a reference for the names that columns have in Excel (A, B, C, ...) To do so, we use the string library and write the following code."
},
{
"code": null,
"e": 8296,
"s": 8182,
"text": "import stringalphabet = list(string.ascii_uppercase)excel_alphabet = alphabet[0:max_column] print(excel_alphabet)"
},
{
"code": null,
"e": 8346,
"s": 8296,
"text": "If we print this we’ll obtain a list from A to G."
},
{
"code": null,
"e": 8540,
"s": 8346,
"text": "This happens because first, we created an alphabet list from A to Z, but then we took a slice [0:max_column] to match the length of this list (7) with the first 7 letters of the alphabet (A-G)."
},
{
"code": null,
"e": 8692,
"s": 8540,
"text": "Note: Python lists start on 0, so A=0, B=1, C=2, and so on. Also, the [a:b] slice notation takes b-a elements (starting with “a” and ending with “b-1”)"
},
{
"code": null,
"e": 8829,
"s": 8692,
"text": "After this, we can make a loop through the columns and apply the sum formula but now with column references, so instead of writing this,"
},
{
"code": null,
"e": 8887,
"s": 8829,
"text": "sheet['B7'] = '=SUM(B5:B6)'sheet['B7'].style = 'Currency'"
},
{
"code": null,
"e": 8942,
"s": 8887,
"text": "now we include reference and put it inside a for loop."
},
{
"code": null,
"e": 9278,
"s": 8942,
"text": "wb = load_workbook('report_2021.xlsx')sheet = wb['Report']# sum in columns B-Gfor i in excel_alphabet: if i!='A': sheet[f'{i}{max_row+1}'] = f'=SUM({i}{min_row+1}:{i}{max_row})' sheet[f'{i}{max_row+1}'].style = 'Currency'# adding total labelsheet[f'{excel_alphabet[0]}{max_row+1}'] = 'Total'wb.save('report_2021.xlsx')"
},
{
"code": null,
"e": 9373,
"s": 9278,
"text": "After running the code, we get the =SUM formula in the “Total” row for columns between B to G."
},
{
"code": null,
"e": 9397,
"s": 9373,
"text": "Breaking down the code:"
},
{
"code": null,
"e": 9558,
"s": 9397,
"text": "for i in excel_alphabet loops through all the active columns, but then we excluded the A column with if i!='A' because the A column doesn’t contain numeric data"
},
{
"code": null,
"e": 9710,
"s": 9558,
"text": "sheet[f'{i}{max_row+1}'] = f'=SUM({i}{min_row+1}:{i}{max_row}' is the same as writing sheet['B7'] = '=SUM(B5:B6)' but now we do that for columns A to G"
},
{
"code": null,
"e": 9811,
"s": 9710,
"text": "sheet[f'{i}{max_row+1}'].style = 'Currency' gives the currency style to cells below the maximum row."
},
{
"code": null,
"e": 9929,
"s": 9811,
"text": "We add the ‘Total’ label to the A column below the maximum row withsheet[f'{excel_alphabet[0]}{max_row+1}'] = 'Total'"
},
{
"code": null,
"e": 10011,
"s": 9929,
"text": "To finish the report, we can add a title, subtitle and also customize their font."
},
{
"code": null,
"e": 10249,
"s": 10011,
"text": "wb = load_workbook('report_2021.xlsx')sheet = wb['Report']sheet['A1'] = 'Sales Report'sheet['A2'] = '2021'sheet['A1'].font = Font('Arial', bold=True, size=20)sheet['A2'].font = Font('Arial', bold=True, size=10)wb.save('report_2021.xlsx')"
},
{
"code": null,
"e": 10351,
"s": 10249,
"text": "You can add other parameters inside Font(). On this website, you can find a list of styles available."
},
{
"code": null,
"e": 10408,
"s": 10351,
"text": "The final report should look like the following picture."
},
{
"code": null,
"e": 10625,
"s": 10408,
"text": "Now that the report is ready, we can put all the code we’ve written so far inside a function that automates the report, so the next time we want to make this report we only have to introduce the file name and run it."
},
{
"code": null,
"e": 10887,
"s": 10625,
"text": "Notes: For this function to work, the file name should have the structure “sales_month.xlsx” Also, I added a few lines of code that use the name of the month/year of the sales file as a variable, so we can reuse it in the output file and subtitle of the report."
},
{
"code": null,
"e": 11038,
"s": 10887,
"text": "The code below might look intimidating, but it’s only what we’ve written so far plus the new variables file_name, month_name, and month_and_extension."
},
{
"code": null,
"e": 11225,
"s": 11038,
"text": "Let’s imagine the original file we downloaded has the name “sales_2021.xlsx” instead of “supermarket_sales.xlsx” With this we can apply the formula to the report by writing the following"
},
{
"code": null,
"e": 11259,
"s": 11225,
"text": "automate_excel('sales_2021.xlsx')"
},
{
"code": null,
"e": 11384,
"s": 11259,
"text": "After running this code, you’ll see an Excel file named “report_2021.xlsx” in the same folder your Python script is located."
},
{
"code": null,
"e": 11554,
"s": 11384,
"text": "Let’s imagine now we have only monthly Excel files “sales_january.xlsx” “sales_february.xlsx” and “sales_march.xlsx” (You can find those files on my Github to test them)"
},
{
"code": null,
"e": 11615,
"s": 11554,
"text": "You can either apply the formula one by one to get 3 reports"
},
{
"code": null,
"e": 11723,
"s": 11615,
"text": "automate_excel('sales_january.xlsx')automate_excel('sales_february.xlsx')automate_excel('sales_march.xlsx')"
},
{
"code": null,
"e": 11816,
"s": 11723,
"text": "or you could concatenate them first using pd.concat() and then apply the function only once."
},
{
"code": null,
"e": 12226,
"s": 11816,
"text": "# read excel filesexcel_file_1 = pd.read_excel('sales_january.xlsx')excel_file_2 = pd.read_excel('sales_february.xlsx')excel_file_3 = pd.read_excel('sales_march.xlsx')# concatenate filesnew_file = pd.concat([excel_file_1, excel_file_2, excel_file_3], ignore_index=True)# export filenew_file.to_excel('sales_2021.xlsx')# apply functionautomate_excel('sales_2021.xlsx')"
},
{
"code": null,
"e": 12416,
"s": 12226,
"text": "You can schedule the Python script we’ve written in this guide to run whenever you want on your computer. You just need to use the task scheduler or crontab on Windows and Mac respectively."
},
{
"code": null,
"e": 12505,
"s": 12416,
"text": "If you don’t know how to schedule a job, click on the guide below to learn how to do it."
},
{
"code": null,
"e": 12528,
"s": 12505,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12779,
"s": 12528,
"text": "That’s it! In this article, you learned how to automate a basic Excel report; however, you can do even more on your own once you master the Pandas library. In the link below, you can find a complete guide of Pandas I wrote especially for Excel users."
},
{
"code": null,
"e": 12802,
"s": 12779,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12887,
"s": 12802,
"text": "I also made a guide to help you build your first machine learning model with Python."
},
{
"code": null,
"e": 12910,
"s": 12887,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12967,
"s": 12910,
"text": "You can find the code behind this analysis on my Github."
}
] |
MySQL query to get the count of distinct records in a column
|
To get the count of distinct records, use DISTINCT along with COUNT(). Following is the syntax −
select count(DISTINCT yourColumnName) from yourTableName;
Let us first create a table −
mysql> create table DemoTable
-> (
-> Name varchar(20),
-> Score int
-> );
Query OK, 0 rows affected (0.67 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('John',56);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values('Sam',89);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('John',56);
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Carol',60);
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable values('Sam',89);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('Carol',60);
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable
This will produce the following output −
+-------+-------+
| Name | Score |
+-------+-------+
| John | 56 |
| Sam | 89 |
| John | 56 |
| Carol | 60 |
| Sam | 89 |
| Carol | 60 |
+-------+-------+
6 rows in set (0.00 sec)
Here is the query to get to get the count of distinct records in a column −
mysql> select count(DISTINCT Score) from DemoTable;
This will produce the following output −
+-----------------------+
| count(DISTINCT Score) |
+-----------------------+
| 3 |
+-----------------------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To get the count of distinct records, use DISTINCT along with COUNT(). Following is the syntax −"
},
{
"code": null,
"e": 1217,
"s": 1159,
"text": "select count(DISTINCT yourColumnName) from yourTableName;"
},
{
"code": null,
"e": 1247,
"s": 1217,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1359,
"s": 1247,
"text": "mysql> create table DemoTable\n-> (\n-> Name varchar(20),\n-> Score int\n-> );\nQuery OK, 0 rows affected (0.67 sec)"
},
{
"code": null,
"e": 1415,
"s": 1359,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1924,
"s": 1415,
"text": "mysql> insert into DemoTable values('John',56);\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into DemoTable values('Sam',89);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into DemoTable values('John',56);\nQuery OK, 1 row affected (0.17 sec)\n\nmysql> insert into DemoTable values('Carol',60);\nQuery OK, 1 row affected (0.20 sec)\n\nmysql> insert into DemoTable values('Sam',89);\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable values('Carol',60);\nQuery OK, 1 row affected (0.20 sec)"
},
{
"code": null,
"e": 1984,
"s": 1924,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2014,
"s": 1984,
"text": "mysql> select *from DemoTable"
},
{
"code": null,
"e": 2055,
"s": 2014,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2260,
"s": 2055,
"text": "+-------+-------+\n| Name | Score |\n+-------+-------+\n| John | 56 |\n| Sam | 89 |\n| John | 56 |\n| Carol | 60 |\n| Sam | 89 |\n| Carol | 60 |\n+-------+-------+\n6 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2336,
"s": 2260,
"text": "Here is the query to get to get the count of distinct records in a column −"
},
{
"code": null,
"e": 2388,
"s": 2336,
"text": "mysql> select count(DISTINCT Score) from DemoTable;"
},
{
"code": null,
"e": 2429,
"s": 2388,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2583,
"s": 2429,
"text": "+-----------------------+\n| count(DISTINCT Score) |\n+-----------------------+\n| 3 |\n+-----------------------+\n1 row in set (0.00 sec)"
}
] |
PHP Object Cloning
|
Creating copy of an object by simple assignment merely creates another reference to the one in memory. Hence, changes in attribute reflect both in original and duplicate object. PHP has clone keyword that creates a shallow copy of the object. However, if original object has other embedded object as one of its properties, the copied object still refers to the same. To create a eep copy of object, the magic method __clone() needs to be defined in the class/
In following code, myclass has one of attributes as object of address class. An object of myclass is duplicated by assignment. Change in value of its prroperty is reflected in both objects
Live Demo
<?php
class address{
var $city="Nanded";
var $pin="431601";
function setaddr($arg1, $arg2){
$this->city=$arg1;
$this->pin=$arg2;
}
}
class myclass{
var $name="Raja";
var $obj;
function setname($arg){
$this->name=$arg;
}
}
$obj1=new myclass();
$obj1->obj=new address();
echo "original object\n";
print_r($obj1);
$obj2=$obj1;
$obj1->setname("Ravi");
echo "after change:\n";
print_r($obj1);
print_r($obj2);
?>
This code shows following output
original object
myclass Object(
[name] => Raja
[obj] => address Object(
[city] => Nanded
[pin] => 431601
)
)
after change:
original object
myclass Object(
[name] => Ravi
[obj] => address Object(
[city] => Nanded
[pin] => 431601
)
)
copied object
myclass Object(
[name] => Ravi
[obj] => address Object(
[city] => Nanded
[pin] => 431601
)
)
The clone keyword creates a shallow copy. Change in value of property doesn't reflect in cloned object. However, if embedded object is modified, changes are reflected in original and cloned object
Live Demo
<?php
class address{
var $city="Nanded";
var $pin="431601";
function setaddr($arg1, $arg2){
$this->city=$arg1;
$this->pin=$arg2;
}
}
class myclass{
var $name="Raja";
var $obj;
function setname($arg){
$this->name=$arg;
}
}
$obj1=new myclass();
$obj1->obj=new address();
echo "original object:\n";
print_r($obj1);
$obj2=clone $obj1;
$obj1->setname("Ravi");
$obj1->obj->setaddr("Mumbai", "400001");
echo "after change:\n";
echo "original object:\n";
print_r($obj1);
echo "cloned object:\n";
print_r($obj2);
?>
Output shows following result
original object:
myclass Object(
[name] => Raja
[obj] => address Object(
[city] => Nanded
[pin] => 431601
)
)
after change:
original object:
myclass Object(
[name] => Ravi
[obj] => address Object(
[city] => Mumbai
[pin] => 400001
)
)
cloned object:
myclass Object(
[name] => Raja
[obj] => address Object(
[city] => Mumbai
[pin] => 400001
)
)
The __clone() method creates a deep copy by creating lone of embedded object too
<?php
class address{
var $city="Nanded";
var $pin="431601";
function setaddr($arg1, $arg2){
$this->city=$arg1;
$this->pin=$arg2;
}
}
class myclass{
var $name="Raja";
var $obj;
function setname($arg){
$this->name=$arg;
}
public function __clone() {
$this->obj = clone $this->obj ;
}
}
$obj1=new myclass();
$obj1->obj=new address();
echo "original object:\n";
print_r($obj1);
$obj2=clone $obj1;
$obj1->setname("Ravi");
$obj1->obj->setaddr("Mumbai", "400001");
echo "after change:\n";
echo "original object:\n";
print_r($obj1);
echo "cloned object:\n";
print_r($obj2);
?>
Output shows following result
original object:
myclass Object(
[name] => Raja
[obj] => address Object(
[city] => Nanded
[pin] => 431601
)
)
after change:
original object:
myclass Object(
[name] => Ravi
[obj] => address Object(
[city] => Mumbai
[pin] => 400001
)
)
cloned object:
myclass Object(
[name] => Raja
[obj] => address Object(
[city] => Nanded
[pin] => 431601
)
)
|
[
{
"code": null,
"e": 1522,
"s": 1062,
"text": "Creating copy of an object by simple assignment merely creates another reference to the one in memory. Hence, changes in attribute reflect both in original and duplicate object. PHP has clone keyword that creates a shallow copy of the object. However, if original object has other embedded object as one of its properties, the copied object still refers to the same. To create a eep copy of object, the magic method __clone() needs to be defined in the class/"
},
{
"code": null,
"e": 1711,
"s": 1522,
"text": "In following code, myclass has one of attributes as object of address class. An object of myclass is duplicated by assignment. Change in value of its prroperty is reflected in both objects"
},
{
"code": null,
"e": 1722,
"s": 1711,
"text": " Live Demo"
},
{
"code": null,
"e": 2171,
"s": 1722,
"text": "<?php\nclass address{\n var $city=\"Nanded\";\n var $pin=\"431601\";\n function setaddr($arg1, $arg2){\n $this->city=$arg1;\n $this->pin=$arg2;\n }\n}\nclass myclass{\n var $name=\"Raja\";\n var $obj;\n function setname($arg){\n $this->name=$arg;\n }\n}\n$obj1=new myclass();\n$obj1->obj=new address();\necho \"original object\\n\";\nprint_r($obj1);\n$obj2=$obj1;\n$obj1->setname(\"Ravi\");\necho \"after change:\\n\";\nprint_r($obj1);\nprint_r($obj2);\n?>"
},
{
"code": null,
"e": 2204,
"s": 2171,
"text": "This code shows following output"
},
{
"code": null,
"e": 2607,
"s": 2204,
"text": "original object\nmyclass Object(\n [name] => Raja\n [obj] => address Object(\n [city] => Nanded\n [pin] => 431601\n )\n)\nafter change:\noriginal object\nmyclass Object(\n [name] => Ravi\n [obj] => address Object(\n [city] => Nanded\n [pin] => 431601\n )\n)\ncopied object\nmyclass Object(\n [name] => Ravi\n [obj] => address Object(\n [city] => Nanded\n [pin] => 431601\n )\n\n)"
},
{
"code": null,
"e": 2804,
"s": 2607,
"text": "The clone keyword creates a shallow copy. Change in value of property doesn't reflect in cloned object. However, if embedded object is modified, changes are reflected in original and cloned object"
},
{
"code": null,
"e": 2815,
"s": 2804,
"text": " Live Demo"
},
{
"code": null,
"e": 3364,
"s": 2815,
"text": "<?php\nclass address{\n var $city=\"Nanded\";\n var $pin=\"431601\";\n function setaddr($arg1, $arg2){\n $this->city=$arg1;\n $this->pin=$arg2;\n }\n}\nclass myclass{\n var $name=\"Raja\";\n var $obj;\n function setname($arg){\n $this->name=$arg;\n }\n}\n$obj1=new myclass();\n$obj1->obj=new address();\necho \"original object:\\n\";\nprint_r($obj1);\n$obj2=clone $obj1;\n$obj1->setname(\"Ravi\");\n$obj1->obj->setaddr(\"Mumbai\", \"400001\");\necho \"after change:\\n\";\necho \"original object:\\n\";\nprint_r($obj1);\necho \"cloned object:\\n\";\nprint_r($obj2);\n?>"
},
{
"code": null,
"e": 3394,
"s": 3364,
"text": "Output shows following result"
},
{
"code": null,
"e": 3802,
"s": 3394,
"text": "original object:\nmyclass Object(\n [name] => Raja\n [obj] => address Object(\n [city] => Nanded\n [pin] => 431601\n )\n\n)\nafter change:\noriginal object:\nmyclass Object(\n [name] => Ravi\n [obj] => address Object(\n [city] => Mumbai\n [pin] => 400001\n )\n\n)\ncloned object:\nmyclass Object(\n [name] => Raja\n [obj] => address Object(\n [city] => Mumbai\n [pin] => 400001\n )\n\n)"
},
{
"code": null,
"e": 3883,
"s": 3802,
"text": "The __clone() method creates a deep copy by creating lone of embedded object too"
},
{
"code": null,
"e": 4506,
"s": 3883,
"text": "<?php\nclass address{\n var $city=\"Nanded\";\n var $pin=\"431601\";\n function setaddr($arg1, $arg2){\n $this->city=$arg1;\n $this->pin=$arg2;\n }\n}\nclass myclass{\n var $name=\"Raja\";\n var $obj;\n function setname($arg){\n $this->name=$arg;\n }\n public function __clone() {\n $this->obj = clone $this->obj ;\n }\n}\n$obj1=new myclass();\n$obj1->obj=new address();\necho \"original object:\\n\";\nprint_r($obj1);\n$obj2=clone $obj1;\n$obj1->setname(\"Ravi\");\n$obj1->obj->setaddr(\"Mumbai\", \"400001\");\necho \"after change:\\n\";\necho \"original object:\\n\";\nprint_r($obj1);\necho \"cloned object:\\n\";\nprint_r($obj2);\n?>"
},
{
"code": null,
"e": 4536,
"s": 4506,
"text": "Output shows following result"
},
{
"code": null,
"e": 4944,
"s": 4536,
"text": "original object:\nmyclass Object(\n [name] => Raja\n [obj] => address Object(\n [city] => Nanded\n [pin] => 431601\n )\n\n)\nafter change:\noriginal object:\nmyclass Object(\n [name] => Ravi\n [obj] => address Object(\n [city] => Mumbai\n [pin] => 400001\n )\n\n)\ncloned object:\nmyclass Object(\n [name] => Raja\n [obj] => address Object(\n [city] => Nanded\n [pin] => 431601\n )\n\n)"
}
] |
Write a C program of library management system using switch case
|
How to store the books-related information of library using C programming.
Step 1: Declare a structure which holds data members
Step 2: declare variables which are used for loop
Step 3: use switch case to work on each module
Step 4: case 1- for Adding book information
Case 2- for Display book information
Case 3- for Finding number for books in library
Case 4- for EXIT
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<string.h>
struct library{
char bookname[50];
char author[50];
int noofpages;
float price;
};
int main(){
struct library lib[100];
char bookname[30];
int i,j, keepcount;
i=j=keepcount = 0;
while(j!=6){
printf("\n1. Add book information\n");
printf("2.Display book information\n");
printf("3. no of books in the library\n");
printf("4. Exit");
printf ("\n\nEnter one of the above : ");
scanf("%d",&j);
switch (j){
/* Add book */
case 1:
printf ("Enter book name = ");
scanf ("%s",lib[i].bookname);
printf ("Enter author name = ");
scanf ("%s",lib[i].author);
printf ("Enter pages = ");
scanf ("%d",&lib[i].noofpages);
printf ("Enter price = ");
scanf ("%f",&lib[i].price);
keepcount++;
i++;
break;
case 2:
printf("you have entered the following information\n");
for(i=0; i<keepcount; i++){
printf ("book name = %s\n",lib[i].bookname);
printf ("\t author name = %s\n",lib[i].author);
printf ("\t pages = %d\n",lib[i].noofpages);
printf ("\t price = %f\n",lib[i].price);
}
break;
case 3:
printf("\n No of books in library : %d", keepcount);
break;
case 4:
exit (0);
}
}
return 0;
}
1. Add book information
2.Display book information
3. no of books in the library
4. Exit
Enter one of the above : 1
Enter book name = HarryPotter
Enter author name = hp
Enter pages = 250
Enter price = 350.6
1. Add book information
2.Display book information
3. no of books in the library
4. Exit
Enter one of the above : 2
you have entered the following information
book name = HarryPotter
author name = hp
pages = 250
price = 350.600006
1. Add book information
2.Display book information
3. no of books in the library
4. Exit
Enter one of the above : 3
No of books in library : 1
1. Add book information
2.Display book information
3. no of books in the library
4. Exit
Enter one of the above : 4
|
[
{
"code": null,
"e": 1137,
"s": 1062,
"text": "How to store the books-related information of library using C programming."
},
{
"code": null,
"e": 1457,
"s": 1137,
"text": "Step 1: Declare a structure which holds data members\nStep 2: declare variables which are used for loop\nStep 3: use switch case to work on each module\nStep 4: case 1- for Adding book information\n Case 2- for Display book information\n Case 3- for Finding number for books in library\n Case 4- for EXIT"
},
{
"code": null,
"e": 3001,
"s": 1457,
"text": "#include<stdio.h>\n#include<conio.h>\n#include<stdlib.h>\n#include<string.h>\nstruct library{\n char bookname[50];\n char author[50];\n int noofpages;\n float price;\n};\nint main(){\n struct library lib[100];\n char bookname[30];\n int i,j, keepcount;\n i=j=keepcount = 0;\n while(j!=6){\n printf(\"\\n1. Add book information\\n\");\n printf(\"2.Display book information\\n\");\n printf(\"3. no of books in the library\\n\");\n printf(\"4. Exit\");\n printf (\"\\n\\nEnter one of the above : \");\n scanf(\"%d\",&j);\n switch (j){\n /* Add book */\n case 1:\n printf (\"Enter book name = \");\n scanf (\"%s\",lib[i].bookname);\n printf (\"Enter author name = \");\n scanf (\"%s\",lib[i].author);\n printf (\"Enter pages = \");\n scanf (\"%d\",&lib[i].noofpages);\n printf (\"Enter price = \");\n scanf (\"%f\",&lib[i].price);\n keepcount++;\n i++;\n break;\n case 2:\n printf(\"you have entered the following information\\n\");\n for(i=0; i<keepcount; i++){\n printf (\"book name = %s\\n\",lib[i].bookname);\n printf (\"\\t author name = %s\\n\",lib[i].author);\n printf (\"\\t pages = %d\\n\",lib[i].noofpages);\n printf (\"\\t price = %f\\n\",lib[i].price);\n }\n break;\n case 3:\n printf(\"\\n No of books in library : %d\", keepcount);\n break;\n case 4:\n exit (0);\n }\n }\n return 0;\n}"
},
{
"code": null,
"e": 3732,
"s": 3001,
"text": "1. Add book information\n2.Display book information\n3. no of books in the library\n4. Exit\n\nEnter one of the above : 1\nEnter book name = HarryPotter\nEnter author name = hp\nEnter pages = 250\nEnter price = 350.6\n\n1. Add book information\n2.Display book information\n3. no of books in the library\n4. Exit\n\nEnter one of the above : 2\nyou have entered the following information\nbook name = HarryPotter\n author name = hp\n pages = 250\n price = 350.600006\n\n1. Add book information\n2.Display book information\n3. no of books in the library\n4. Exit\n\nEnter one of the above : 3\n\nNo of books in library : 1\n1. Add book information\n2.Display book information\n3. no of books in the library\n4. Exit\n\nEnter one of the above : 4"
}
] |
GAVRO — Managed Big Data Schema Evolution | by Gary Strange | Towards Data Science
|
Managing schema changes has always proved troublesome for architects and software engineers. Building a big-data platform is no different and managing schema evolution is still a challenge that needs solving. NoSQL, Hadoop and the schema-on-read mantra have gone some way towards alleviating the trappings of strict schema enforcement. However, integration developers, analysts and data scientists are still hindered by the amount of data wrangling they need to perform when extracting accurate insights from big-data.
Successful business’ grow and evolve at pace accelerating and amplifying the volatility of known data schemas. Datasets are not static and constantly evolving, so knowing what business-fact data represents in the current and historical periods of the business is crucial to making confident information insights.
Through this article and accompanying GitHub repo, I’ll demonstrate how you can manage schema evolution in a big-data platform using Microsoft Azure technologies.
This is an area that tends to be overlooked in practice until you run into your first production issues. Without thinking through data management and schema evolution carefully, people often pay a much higher cost later on.
Confluent.io (29th April 2020), Schema Evolution and Compatibility. https://docs.confluent.io/current/schema-registry/avro.html#schema-evolution-and-compatibility
As a writer, it's difficult to decide how to tell your story. Do I jump straight into the technical solution to satisfy the engineers looking for succinct examples or do I start with the why’s and motivations? So I’ll leave it up to the reader. If you want to jump straight into the technical example head to the GitHub repo. If you want the finer details, read on...
Serializing data to be stored in files to be analysed later, is fairly straight forward if consumers understand the schema that was used to write the data and the schema never changes.
But what happens if the schema evolves over time? It becomes a little more complicated.
When the write-schema evolves due to a new business requirement, consumers (readers) must understand when the new schema was introduced and the definition of the new schema to successfully de-serialize the data. Failure to comprehend the schema-change event will impact data processing pipelines and services will error as they fail to de-serialize the data.
There are a few solutions to this problem... (this is by no means an exhaustive list).
Release Co-ordination
The writer and the reader coordinate their backlogs and software releases. This may work well when the writer and the reader applications are developed and maintained by the same engineering team. However, it’s often the case that the writer and reader are working to different objectives and priorities across the enterprise. Temporally coupling independent team backlogs through strict interface dependencies is to be avoided as it inhibits agility and delivery velocity.
Schema Version Management
Versioning write-schemas enables forward and backwards compatibility management. Providing forward and backward compatibility de-couples backlogs and priorities, allowing engineering teams independent progression of their goals.
Versioning is generally discussed in the context of two distinct sub-topics.
Major — A major version change typically breaks interfaces and contracts between systems. A major schema change would typically inhibit readers from reading the data written by the new schema version. Forward and backward compatibility is difficult or impossible.
Minor — A minor version change is typically considered to be a low impact change. Forward and backward compatibility is often possible. Readers typically continue to operate as they previously did, successfully de-serialising data without progressing to the newest version of the schema.
Wouldn’t it be nice to build a data ingestion architecture that had some resilience to change? More specifically, resilience to schema evolution.
Below is the Azure architecture I’ll use to describe how schema evolution can be managed successfully.
Kafka’s Schema Registry provides a great example of managing schema evolution over streaming architecture. Azure Event Hubs, Microsoft’s Kafka like product, doesn’t currently have a schema registry feature. Events published to Event Hubs are serialised into a binary blob nested in the body of Event Hubs Avro schema (Fig.1). We will get into the details shortly, but essentially the published event data is schema-less, any down-stream readers need to de-serialise the binary blob by asserting a schema at read time. There are some clever-work-arounds1 that utilise Confluent’s schema-registry alongside Event Hubs. I will build on these suggestions and provide an alternative approach to schema evolution resilience. In my previous story (Evolving into a Big-Data Driven Business in the Azure Cloud: Data Ingestion), I described a Data Lake ingestion architecture that utilises Event Hubs and Event Hub Capture to form a batch layer for big data analytics. I’ll use this architecture as reference for handling schema evolution.
Figure 1.
{"type":"record", "name":"EventData", "namespace":"Microsoft.ServiceBus.Messaging", "fields":[ {"name":"SequenceNumber","type":"long"}, {"name":"Offset","type":"string"}, {"name":"EnqueuedTimeUtc","type":"string"}, {"name":"SystemProperties","type":{"type":"map","values":["long","double","string","bytes"]}}, {"name":"Properties","type":{"type":"map","values":["long","double","string","bytes"]}}, {"name":"Body","type":["null","bytes"]} ]}
Event Hubs
How many? How many Event Hubs should I have? Or to put it another way, should I have one big pipe for all my data or many smaller pipes for each message type? The same question has been asked regarding Kafka topics and there is no definitive answer2. One thing is highly probably, different use cases will favour different approaches. If your concern is just to get messages from A to B or you’re integrating with architecture outside of your control, messages might flow through one Event Hub, one big pipe. If some of your data is highly sensitive and you only want certain subscribers to read and process that data or you may need specific partition strategies which would lead to the adoption of many event hubs within a namespace, many smaller pipes.
Big Pipe
If an Event Hub contains many message types with varying schemas how would we identify and deserialize the various messages correctly?
Small Pipe
When an Event Hub contains just one message type and that message type evolves over time how do consumers deserialize the new versions of the message?
At first glance, these issues may seem to be unrelated. However, they are manifestations of the same core problem. How to manage the de-serialisation of data.
All messages on Event Hubs are anonymous blobs of binary. One option would be for consumers to infer the schema. However, this approach is non-deterministic and based on sampling, so the inferred schema can only be an approximation. Another approach might be to assert the schema on consumption. However, this means that engineering teams consuming messages are temporarily coupled to the evolution of the schema, even for minor changes. Event Hub Capture offers us an opportunity to break the temporal coupling and allow consumers to consume data from t0** at their own pace. However, if a consumer wants to read and make use of all the AVRO files, produced by the Event Hub Capture process, they will also need to know which write schemas were used to write the binary messages over the period that the events were captured. This could be many months or even years of data. As a consumer, I would need to know the schema evolution time-line or I will struggle to make use of the data.
** well at least from the begging of the Event Hub capture configuration.
Early impressions of Event Hub Capture might lead you to believe that AVRO was being used to help address the concerns detailed above. However, after reading the AVRO specification it would seem that only minor version changes are possible. So breaking changes cannot be managed and AVRO files with multiple message types would be impossible.
Event Hubs allow us to add additional metadata when we publish messages. This metadata is the key to managing schema evolution.
There are two possible options.
1) The write-schema is stored with each message in the Event Hub client properties dictionary. This would severely inflate the storage costs.
2) A message type identifier is stored in the Event Hub client properties dictionary. The identifier is then used to lookup the schema from a central store.
With both of these solutions, the schema is always directly or indirectly stored with the data. The files produced by Event Hub Capture will always have a means of identifying the write schema. Moreover, each file can contain x number of message types and y number of message versions.
Let’s take a look at an Azure Function that publishes messages to Event Hub using the client SDK.
The schema identifier is always stored alongside the data (line 17).
In the example above, the function uses a timer trigger to execute new instances of the function every 5 seconds. The function trigger is irrelevant, and it could easily be a CosmosDB Change Feed Processing binding or any other bindings that produce data to be processed. Moreover, using a function app is also irrelevant, what matters is what you publish to the Event Hub. The function app lends itself to a succinct example.
It's important to note the schema version of the message is being persisted alongside the message by adding a reference to eventData.Properties. This metadata attribution is critical when it comes to reading the data at a later date. When events are published to Event Hub the schema identifier is always stored alongside the data.
I configure Event Hub Capture to produce a new AVRO file every minute or every 500mb, whichever comes first. So, we now have the schema identifier and data captured in neatly partitioned AVRO files, but how do we process it in our big data pipelines. In my previous story, I covered the subject of maintaining a schema repository to capture a truthful account of all the enterprise's schemas. This repo is used to create an artefact that will be consumed in the data processing pipeline. The artefact is a simple key-value store connecting versioned schema identifiers with the write schema used. For the purpose of this document, I’ll use a simple Databrick Python notebook to process the AVRO data.
I won’t go into a full description of the complete notebook but focus on the most important cells (the complete notebook is in the GitHub repo).
The first is the reading of the Event Hub Data Capture AVRO. Spark’s AVRO dataframeReader is used to read AVRO files from storage and de-serialise them into a data-frame. We can allow Spark to infer the schema at this point as we know it to be non-volatile (i.e. the Azure Event Hub schema). The properties attribute holds the information about the schema version that was used to write the data in the binary field ‘Body’. A simple projection is run over the data to process a refined data-frame with three columns. The schema version is extracted from the properties object (the stored value from the serialised properties dictionary is stored in the child attribute member2). The ‘Body’ attribute is cast to a string as we want to use spark’s JSON de-serialiser on it later in the notebook.
from pyspark.sql.functions import colrawAvroDf = spark.read.format("avro").load("wasbs://" + containerName + "@" + storageAccName + ".blob.core.windows.net/gavroehnamespace/gavroeh/*/2020/*/*/*/*/*.avro")avroDf = rawAvroDf.select(col("Properties.SchemaVersion.member2").alias('SchemaVersion'), col("Body").cast("string"))display(avroDf)
The second is the schema lookup object. For the purpose of simplifying the example, I’m manually creating some schemas that will be used to deserialise the AVRO data. However, in practice, these schema’s will be generated from a schema repository and be stored as runtime artefacts. Note to self, need to write this up as a follow-up article.
The schemas, stored in a one-dimensional array, represent an entity that has evolved. In this theoretical example, the business has grown and started trading overseas in new currencies. Transactions now need currency identifiers, so a new attribute ‘Currency’ was added to the sales-order data schema. As readers, we need to be able to de-serialise the new data successfully.
from pyspark.sql.types import StructType, StructField, LongType, StringType, ArrayType, DoubleTypesalesOrderV1 =StructType([StructField('OrderId',StringType(),True),StructField('OrderAmount',DoubleType(),True),StructField('OrderCreatedUTC',StringType(),True)])salesOrderV2 =StructType([StructField('OrderId',StringType(),True),StructField('OrderAmount',DoubleType(),True),StructField('Currency',StringType(),False),StructField('OrderCreatedUTC',StringType(),True)])salesOrderSchemaDictionary = { "v1.0":salesOrderV1, "v2.0":salesOrderV2 }salesOrderSchemaDictionary
The third cell I’d like to focus on is the cell that actually reads and de-serialises the data. The Event Hub Data Capture output that was read into a data-frame previously is used to determine a distinct list of schema versions present in the data. For each schema version, a new temporary SparkSQL table will be created to access the de-serialised data. The original AVRO data-frame is filtered on each iteration of the ‘for’ loop, grouping records by distinct schema-version to produce subsets of data. Each subset is then de-serialised using the corresponding schema in the salesOrderSchemaDictionary. A number of new temporary tables will be created and the output of this cell will display a list of created objects.
from pyspark.sql.functions import concat, lit, regexp_replacedistinctSchemaVersions = avroDf.select('SchemaVersion').distinct()objectToCreate = distinctSchemaVersions.withColumn('TableName', concat(lit('SalesOrder'),regexp_replace(col('SchemaVersion'), '[.]', '_'))).collect()display(objectToCreate)for record in objectToCreate:schemaVersion = record.SchemaVersionjsonRdd = avroDf.filter(col("SchemaVersion") == schemaVersion).select(avroDf.Body)objectJson = jsonRdd.rdd.map(lambda x: x[0])dataExtract = spark.read.schema(salesOrderSchemaDictionary[schemaVersion]).json(objectJson)dataExtract.registerTempTable(record.TableName)
Finally, SparkSQL can be used to explore the successful deserialised data in the temporary tables.
%sqlselect * from SalesOrderv1_0%sqlselect * from SalesOrderv2_0
I should have started by clearing up what GAVRO is. Sorry to disappoint, but it’s not some new Apache incubator project that you wasn’t aware of. It’s an endearing name that my colleagues gave to the method I described in this article. I believe it’s a combination of my first initial and AVRO, at first I found their nickname for the method to be a product of the team's camaraderie, but then it stuck.
I don’t believe in designing and prescribing methods that are completely exact and should be unconditionally applied to every enterprise because every enterprise is different. So if you take anything away from reading this then I hope it’s the motivation to think about the connotations of badly managed schema evolution within your big data pipe-lines. We hear time and time again about the struggles organisation’s have with extracting information and actionable insight from big-data and how expensive data-scientists are wasting 80% of their time wrestling with data preparation. Schema management is a weapon when applied properly, that can be used to accelerate data understanding and reduce time to insight. So take the time to invest in it and you will reap healthy returns.
[1] Volkan Civelek, Schema validation with Event Hubs (1st April 2019), https://azure.microsoft.com/en-gb/blog/schema-validation-with-event-hubs/
[2] Martin Kleppman, Should you put several event types in the same Kafka topic?(18th Jan 2018), https://martin.kleppmann.com/2018/01/18/event-types-in-kafka-topic.html
Yahoo’s Apache Pulsar System: https://pulsar.apache.org/docs/en/schema-evolution-compatibility/
Confluent.io’s Schema-Registry: https://docs.confluent.io/current/schema-registry/index.html
Jay Kreps, The Log: What every software engineer should know about real-time data’s unifying abstraction (16th Dec 2013), https://engineering.linkedin.com/distributed-systems/log-what-every-software-engineer-should-know-about-real-time-datas-unifying
|
[
{
"code": null,
"e": 691,
"s": 172,
"text": "Managing schema changes has always proved troublesome for architects and software engineers. Building a big-data platform is no different and managing schema evolution is still a challenge that needs solving. NoSQL, Hadoop and the schema-on-read mantra have gone some way towards alleviating the trappings of strict schema enforcement. However, integration developers, analysts and data scientists are still hindered by the amount of data wrangling they need to perform when extracting accurate insights from big-data."
},
{
"code": null,
"e": 1004,
"s": 691,
"text": "Successful business’ grow and evolve at pace accelerating and amplifying the volatility of known data schemas. Datasets are not static and constantly evolving, so knowing what business-fact data represents in the current and historical periods of the business is crucial to making confident information insights."
},
{
"code": null,
"e": 1167,
"s": 1004,
"text": "Through this article and accompanying GitHub repo, I’ll demonstrate how you can manage schema evolution in a big-data platform using Microsoft Azure technologies."
},
{
"code": null,
"e": 1391,
"s": 1167,
"text": "This is an area that tends to be overlooked in practice until you run into your first production issues. Without thinking through data management and schema evolution carefully, people often pay a much higher cost later on."
},
{
"code": null,
"e": 1554,
"s": 1391,
"text": "Confluent.io (29th April 2020), Schema Evolution and Compatibility. https://docs.confluent.io/current/schema-registry/avro.html#schema-evolution-and-compatibility"
},
{
"code": null,
"e": 1922,
"s": 1554,
"text": "As a writer, it's difficult to decide how to tell your story. Do I jump straight into the technical solution to satisfy the engineers looking for succinct examples or do I start with the why’s and motivations? So I’ll leave it up to the reader. If you want to jump straight into the technical example head to the GitHub repo. If you want the finer details, read on..."
},
{
"code": null,
"e": 2107,
"s": 1922,
"text": "Serializing data to be stored in files to be analysed later, is fairly straight forward if consumers understand the schema that was used to write the data and the schema never changes."
},
{
"code": null,
"e": 2195,
"s": 2107,
"text": "But what happens if the schema evolves over time? It becomes a little more complicated."
},
{
"code": null,
"e": 2554,
"s": 2195,
"text": "When the write-schema evolves due to a new business requirement, consumers (readers) must understand when the new schema was introduced and the definition of the new schema to successfully de-serialize the data. Failure to comprehend the schema-change event will impact data processing pipelines and services will error as they fail to de-serialize the data."
},
{
"code": null,
"e": 2641,
"s": 2554,
"text": "There are a few solutions to this problem... (this is by no means an exhaustive list)."
},
{
"code": null,
"e": 2663,
"s": 2641,
"text": "Release Co-ordination"
},
{
"code": null,
"e": 3137,
"s": 2663,
"text": "The writer and the reader coordinate their backlogs and software releases. This may work well when the writer and the reader applications are developed and maintained by the same engineering team. However, it’s often the case that the writer and reader are working to different objectives and priorities across the enterprise. Temporally coupling independent team backlogs through strict interface dependencies is to be avoided as it inhibits agility and delivery velocity."
},
{
"code": null,
"e": 3163,
"s": 3137,
"text": "Schema Version Management"
},
{
"code": null,
"e": 3392,
"s": 3163,
"text": "Versioning write-schemas enables forward and backwards compatibility management. Providing forward and backward compatibility de-couples backlogs and priorities, allowing engineering teams independent progression of their goals."
},
{
"code": null,
"e": 3469,
"s": 3392,
"text": "Versioning is generally discussed in the context of two distinct sub-topics."
},
{
"code": null,
"e": 3733,
"s": 3469,
"text": "Major — A major version change typically breaks interfaces and contracts between systems. A major schema change would typically inhibit readers from reading the data written by the new schema version. Forward and backward compatibility is difficult or impossible."
},
{
"code": null,
"e": 4021,
"s": 3733,
"text": "Minor — A minor version change is typically considered to be a low impact change. Forward and backward compatibility is often possible. Readers typically continue to operate as they previously did, successfully de-serialising data without progressing to the newest version of the schema."
},
{
"code": null,
"e": 4167,
"s": 4021,
"text": "Wouldn’t it be nice to build a data ingestion architecture that had some resilience to change? More specifically, resilience to schema evolution."
},
{
"code": null,
"e": 4270,
"s": 4167,
"text": "Below is the Azure architecture I’ll use to describe how schema evolution can be managed successfully."
},
{
"code": null,
"e": 5300,
"s": 4270,
"text": "Kafka’s Schema Registry provides a great example of managing schema evolution over streaming architecture. Azure Event Hubs, Microsoft’s Kafka like product, doesn’t currently have a schema registry feature. Events published to Event Hubs are serialised into a binary blob nested in the body of Event Hubs Avro schema (Fig.1). We will get into the details shortly, but essentially the published event data is schema-less, any down-stream readers need to de-serialise the binary blob by asserting a schema at read time. There are some clever-work-arounds1 that utilise Confluent’s schema-registry alongside Event Hubs. I will build on these suggestions and provide an alternative approach to schema evolution resilience. In my previous story (Evolving into a Big-Data Driven Business in the Azure Cloud: Data Ingestion), I described a Data Lake ingestion architecture that utilises Event Hubs and Event Hub Capture to form a batch layer for big data analytics. I’ll use this architecture as reference for handling schema evolution."
},
{
"code": null,
"e": 5310,
"s": 5300,
"text": "Figure 1."
},
{
"code": null,
"e": 5869,
"s": 5310,
"text": "{\"type\":\"record\", \"name\":\"EventData\", \"namespace\":\"Microsoft.ServiceBus.Messaging\", \"fields\":[ {\"name\":\"SequenceNumber\",\"type\":\"long\"}, {\"name\":\"Offset\",\"type\":\"string\"}, {\"name\":\"EnqueuedTimeUtc\",\"type\":\"string\"}, {\"name\":\"SystemProperties\",\"type\":{\"type\":\"map\",\"values\":[\"long\",\"double\",\"string\",\"bytes\"]}}, {\"name\":\"Properties\",\"type\":{\"type\":\"map\",\"values\":[\"long\",\"double\",\"string\",\"bytes\"]}}, {\"name\":\"Body\",\"type\":[\"null\",\"bytes\"]} ]}"
},
{
"code": null,
"e": 5880,
"s": 5869,
"text": "Event Hubs"
},
{
"code": null,
"e": 6636,
"s": 5880,
"text": "How many? How many Event Hubs should I have? Or to put it another way, should I have one big pipe for all my data or many smaller pipes for each message type? The same question has been asked regarding Kafka topics and there is no definitive answer2. One thing is highly probably, different use cases will favour different approaches. If your concern is just to get messages from A to B or you’re integrating with architecture outside of your control, messages might flow through one Event Hub, one big pipe. If some of your data is highly sensitive and you only want certain subscribers to read and process that data or you may need specific partition strategies which would lead to the adoption of many event hubs within a namespace, many smaller pipes."
},
{
"code": null,
"e": 6645,
"s": 6636,
"text": "Big Pipe"
},
{
"code": null,
"e": 6780,
"s": 6645,
"text": "If an Event Hub contains many message types with varying schemas how would we identify and deserialize the various messages correctly?"
},
{
"code": null,
"e": 6791,
"s": 6780,
"text": "Small Pipe"
},
{
"code": null,
"e": 6942,
"s": 6791,
"text": "When an Event Hub contains just one message type and that message type evolves over time how do consumers deserialize the new versions of the message?"
},
{
"code": null,
"e": 7101,
"s": 6942,
"text": "At first glance, these issues may seem to be unrelated. However, they are manifestations of the same core problem. How to manage the de-serialisation of data."
},
{
"code": null,
"e": 8088,
"s": 7101,
"text": "All messages on Event Hubs are anonymous blobs of binary. One option would be for consumers to infer the schema. However, this approach is non-deterministic and based on sampling, so the inferred schema can only be an approximation. Another approach might be to assert the schema on consumption. However, this means that engineering teams consuming messages are temporarily coupled to the evolution of the schema, even for minor changes. Event Hub Capture offers us an opportunity to break the temporal coupling and allow consumers to consume data from t0** at their own pace. However, if a consumer wants to read and make use of all the AVRO files, produced by the Event Hub Capture process, they will also need to know which write schemas were used to write the binary messages over the period that the events were captured. This could be many months or even years of data. As a consumer, I would need to know the schema evolution time-line or I will struggle to make use of the data."
},
{
"code": null,
"e": 8162,
"s": 8088,
"text": "** well at least from the begging of the Event Hub capture configuration."
},
{
"code": null,
"e": 8505,
"s": 8162,
"text": "Early impressions of Event Hub Capture might lead you to believe that AVRO was being used to help address the concerns detailed above. However, after reading the AVRO specification it would seem that only minor version changes are possible. So breaking changes cannot be managed and AVRO files with multiple message types would be impossible."
},
{
"code": null,
"e": 8633,
"s": 8505,
"text": "Event Hubs allow us to add additional metadata when we publish messages. This metadata is the key to managing schema evolution."
},
{
"code": null,
"e": 8665,
"s": 8633,
"text": "There are two possible options."
},
{
"code": null,
"e": 8807,
"s": 8665,
"text": "1) The write-schema is stored with each message in the Event Hub client properties dictionary. This would severely inflate the storage costs."
},
{
"code": null,
"e": 8964,
"s": 8807,
"text": "2) A message type identifier is stored in the Event Hub client properties dictionary. The identifier is then used to lookup the schema from a central store."
},
{
"code": null,
"e": 9250,
"s": 8964,
"text": "With both of these solutions, the schema is always directly or indirectly stored with the data. The files produced by Event Hub Capture will always have a means of identifying the write schema. Moreover, each file can contain x number of message types and y number of message versions."
},
{
"code": null,
"e": 9348,
"s": 9250,
"text": "Let’s take a look at an Azure Function that publishes messages to Event Hub using the client SDK."
},
{
"code": null,
"e": 9417,
"s": 9348,
"text": "The schema identifier is always stored alongside the data (line 17)."
},
{
"code": null,
"e": 9844,
"s": 9417,
"text": "In the example above, the function uses a timer trigger to execute new instances of the function every 5 seconds. The function trigger is irrelevant, and it could easily be a CosmosDB Change Feed Processing binding or any other bindings that produce data to be processed. Moreover, using a function app is also irrelevant, what matters is what you publish to the Event Hub. The function app lends itself to a succinct example."
},
{
"code": null,
"e": 10176,
"s": 9844,
"text": "It's important to note the schema version of the message is being persisted alongside the message by adding a reference to eventData.Properties. This metadata attribution is critical when it comes to reading the data at a later date. When events are published to Event Hub the schema identifier is always stored alongside the data."
},
{
"code": null,
"e": 10877,
"s": 10176,
"text": "I configure Event Hub Capture to produce a new AVRO file every minute or every 500mb, whichever comes first. So, we now have the schema identifier and data captured in neatly partitioned AVRO files, but how do we process it in our big data pipelines. In my previous story, I covered the subject of maintaining a schema repository to capture a truthful account of all the enterprise's schemas. This repo is used to create an artefact that will be consumed in the data processing pipeline. The artefact is a simple key-value store connecting versioned schema identifiers with the write schema used. For the purpose of this document, I’ll use a simple Databrick Python notebook to process the AVRO data."
},
{
"code": null,
"e": 11022,
"s": 10877,
"text": "I won’t go into a full description of the complete notebook but focus on the most important cells (the complete notebook is in the GitHub repo)."
},
{
"code": null,
"e": 11816,
"s": 11022,
"text": "The first is the reading of the Event Hub Data Capture AVRO. Spark’s AVRO dataframeReader is used to read AVRO files from storage and de-serialise them into a data-frame. We can allow Spark to infer the schema at this point as we know it to be non-volatile (i.e. the Azure Event Hub schema). The properties attribute holds the information about the schema version that was used to write the data in the binary field ‘Body’. A simple projection is run over the data to process a refined data-frame with three columns. The schema version is extracted from the properties object (the stored value from the serialised properties dictionary is stored in the child attribute member2). The ‘Body’ attribute is cast to a string as we want to use spark’s JSON de-serialiser on it later in the notebook."
},
{
"code": null,
"e": 12153,
"s": 11816,
"text": "from pyspark.sql.functions import colrawAvroDf = spark.read.format(\"avro\").load(\"wasbs://\" + containerName + \"@\" + storageAccName + \".blob.core.windows.net/gavroehnamespace/gavroeh/*/2020/*/*/*/*/*.avro\")avroDf = rawAvroDf.select(col(\"Properties.SchemaVersion.member2\").alias('SchemaVersion'), col(\"Body\").cast(\"string\"))display(avroDf)"
},
{
"code": null,
"e": 12496,
"s": 12153,
"text": "The second is the schema lookup object. For the purpose of simplifying the example, I’m manually creating some schemas that will be used to deserialise the AVRO data. However, in practice, these schema’s will be generated from a schema repository and be stored as runtime artefacts. Note to self, need to write this up as a follow-up article."
},
{
"code": null,
"e": 12872,
"s": 12496,
"text": "The schemas, stored in a one-dimensional array, represent an entity that has evolved. In this theoretical example, the business has grown and started trading overseas in new currencies. Transactions now need currency identifiers, so a new attribute ‘Currency’ was added to the sales-order data schema. As readers, we need to be able to de-serialise the new data successfully."
},
{
"code": null,
"e": 13437,
"s": 12872,
"text": "from pyspark.sql.types import StructType, StructField, LongType, StringType, ArrayType, DoubleTypesalesOrderV1 =StructType([StructField('OrderId',StringType(),True),StructField('OrderAmount',DoubleType(),True),StructField('OrderCreatedUTC',StringType(),True)])salesOrderV2 =StructType([StructField('OrderId',StringType(),True),StructField('OrderAmount',DoubleType(),True),StructField('Currency',StringType(),False),StructField('OrderCreatedUTC',StringType(),True)])salesOrderSchemaDictionary = { \"v1.0\":salesOrderV1, \"v2.0\":salesOrderV2 }salesOrderSchemaDictionary"
},
{
"code": null,
"e": 14160,
"s": 13437,
"text": "The third cell I’d like to focus on is the cell that actually reads and de-serialises the data. The Event Hub Data Capture output that was read into a data-frame previously is used to determine a distinct list of schema versions present in the data. For each schema version, a new temporary SparkSQL table will be created to access the de-serialised data. The original AVRO data-frame is filtered on each iteration of the ‘for’ loop, grouping records by distinct schema-version to produce subsets of data. Each subset is then de-serialised using the corresponding schema in the salesOrderSchemaDictionary. A number of new temporary tables will be created and the output of this cell will display a list of created objects."
},
{
"code": null,
"e": 14789,
"s": 14160,
"text": "from pyspark.sql.functions import concat, lit, regexp_replacedistinctSchemaVersions = avroDf.select('SchemaVersion').distinct()objectToCreate = distinctSchemaVersions.withColumn('TableName', concat(lit('SalesOrder'),regexp_replace(col('SchemaVersion'), '[.]', '_'))).collect()display(objectToCreate)for record in objectToCreate:schemaVersion = record.SchemaVersionjsonRdd = avroDf.filter(col(\"SchemaVersion\") == schemaVersion).select(avroDf.Body)objectJson = jsonRdd.rdd.map(lambda x: x[0])dataExtract = spark.read.schema(salesOrderSchemaDictionary[schemaVersion]).json(objectJson)dataExtract.registerTempTable(record.TableName)"
},
{
"code": null,
"e": 14888,
"s": 14789,
"text": "Finally, SparkSQL can be used to explore the successful deserialised data in the temporary tables."
},
{
"code": null,
"e": 14953,
"s": 14888,
"text": "%sqlselect * from SalesOrderv1_0%sqlselect * from SalesOrderv2_0"
},
{
"code": null,
"e": 15357,
"s": 14953,
"text": "I should have started by clearing up what GAVRO is. Sorry to disappoint, but it’s not some new Apache incubator project that you wasn’t aware of. It’s an endearing name that my colleagues gave to the method I described in this article. I believe it’s a combination of my first initial and AVRO, at first I found their nickname for the method to be a product of the team's camaraderie, but then it stuck."
},
{
"code": null,
"e": 16140,
"s": 15357,
"text": "I don’t believe in designing and prescribing methods that are completely exact and should be unconditionally applied to every enterprise because every enterprise is different. So if you take anything away from reading this then I hope it’s the motivation to think about the connotations of badly managed schema evolution within your big data pipe-lines. We hear time and time again about the struggles organisation’s have with extracting information and actionable insight from big-data and how expensive data-scientists are wasting 80% of their time wrestling with data preparation. Schema management is a weapon when applied properly, that can be used to accelerate data understanding and reduce time to insight. So take the time to invest in it and you will reap healthy returns."
},
{
"code": null,
"e": 16286,
"s": 16140,
"text": "[1] Volkan Civelek, Schema validation with Event Hubs (1st April 2019), https://azure.microsoft.com/en-gb/blog/schema-validation-with-event-hubs/"
},
{
"code": null,
"e": 16455,
"s": 16286,
"text": "[2] Martin Kleppman, Should you put several event types in the same Kafka topic?(18th Jan 2018), https://martin.kleppmann.com/2018/01/18/event-types-in-kafka-topic.html"
},
{
"code": null,
"e": 16551,
"s": 16455,
"text": "Yahoo’s Apache Pulsar System: https://pulsar.apache.org/docs/en/schema-evolution-compatibility/"
},
{
"code": null,
"e": 16644,
"s": 16551,
"text": "Confluent.io’s Schema-Registry: https://docs.confluent.io/current/schema-registry/index.html"
}
] |
How to use substring () in Android textview?
|
This example demonstrate about How to use substring () in Android textview.
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"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center"
tools:context=".MainActivity">
<EditText
android:id="@+id/name"
android:layout_width="match_parent"
android:hint="Enter name"
android:layout_height="wrap_content" />
<Button
android:id="@+id/click"
android:text="Click"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/textview"
android:layout_width="wrap_content"
android:textSize="25sp"
android:layout_height="wrap_content" />
</LinearLayout>
In the above code, we have taken name as Edit text, when user click on button it will take data and return substring value.
Step 3 − Add the following code to src/MainActivity.java
package com.example.myapplication;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
EditText name;
Button button;
TextView text;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
name = findViewById(R.id.name);
button = findViewById(R.id.click);
text = findViewById(R.id.textview);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!name.getText().toString().isEmpty()) {
if (name.getText().toString().length() >= 0) {
String substring = name.getText().toString().substring(0,5);
text.setText(String.valueOf(substring));
}
} else {
name.setError("Plz enter name");
}
}
});
}
}
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 −
In the above result, enter the string as “sairamkrishnaprasadkrishnamm” and it returned sub string value from 0th index to 5th index as saira
Click here to download the project code
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "This example demonstrate about How to use substring () in Android textview."
},
{
"code": null,
"e": 1267,
"s": 1138,
"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": 1332,
"s": 1267,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2222,
"s": 1332,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:gravity=\"center\"\n tools:context=\".MainActivity\">\n <EditText\n android:id=\"@+id/name\"\n android:layout_width=\"match_parent\"\n android:hint=\"Enter name\"\n android:layout_height=\"wrap_content\" />\n <Button\n android:id=\"@+id/click\"\n android:text=\"Click\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\" />\n <TextView\n android:id=\"@+id/textview\"\n android:layout_width=\"wrap_content\"\n android:textSize=\"25sp\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>"
},
{
"code": null,
"e": 2346,
"s": 2222,
"text": "In the above code, we have taken name as Edit text, when user click on button it will take data and return substring value."
},
{
"code": null,
"e": 2403,
"s": 2346,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 3525,
"s": 2403,
"text": "package com.example.myapplication;\n\nimport android.os.Bundle;\nimport android.support.v7.app.AppCompatActivity;\nimport android.view.View;\nimport android.widget.Button;\nimport android.widget.EditText;\nimport android.widget.TextView;\n\npublic class MainActivity extends AppCompatActivity {\n EditText name;\n Button button;\n TextView text;\n\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n name = findViewById(R.id.name);\n button = findViewById(R.id.click);\n text = findViewById(R.id.textview);\n button.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n if (!name.getText().toString().isEmpty()) {\n if (name.getText().toString().length() >= 0) {\n String substring = name.getText().toString().substring(0,5);\n text.setText(String.valueOf(substring));\n }\n } else {\n name.setError(\"Plz enter name\");\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 3872,
"s": 3525,
"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": 4014,
"s": 3872,
"text": "In the above result, enter the string as “sairamkrishnaprasadkrishnamm” and it returned sub string value from 0th index to 5th index as saira"
},
{
"code": null,
"e": 4054,
"s": 4014,
"text": "Click here to download the project code"
}
] |
Banker's Algorithm in Operating System - GeeksforGeeks
|
28 Dec, 2021
The banker’s algorithm is a resource allocation and deadlock avoidance algorithm that tests for safety by simulating the allocation for predetermined maximum possible amounts of all resources, then makes an “s-state” check to test for possible activities, before deciding whether allocation should be allowed to continue.Why Banker’s algorithm is named so? Banker’s algorithm is named so because it is used in banking system to check whether loan can be sanctioned to a person or not. Suppose there are n number of account holders in a bank and the total sum of their money is S. If a person applies for a loan then the bank first subtracts the loan amount from the total money that bank has and if the remaining amount is greater than S then only the loan is sanctioned. It is done because if all the account holders comes to withdraw their money then the bank can easily do it.In other words, the bank would never allocate its money in such a way that it can no longer satisfy the needs of all its customers. The bank would try to be in safe state always.Following Data structures are used to implement the Banker’s Algorithm:Let ‘n’ be the number of processes in the system and ‘m’ be the number of resources types.Available :
It is a 1-d array of size ‘m’ indicating the number of available resources of each type.
Available[ j ] = k means there are ‘k’ instances of resource type Rj
Max :
It is a 2-d array of size ‘n*m’ that defines the maximum demand of each process in a system.
Max[ i, j ] = k means process Pi may request at most ‘k’ instances of resource type Rj.
Allocation :
It is a 2-d array of size ‘n*m’ that defines the number of resources of each type currently allocated to each process.
Allocation[ i, j ] = k means process Pi is currently allocated ‘k’ instances of resource type Rj
Need :
It is a 2-d array of size ‘n*m’ that indicates the remaining resource need of each process.
Need [ i, j ] = k means process Pi currently need ‘k’ instances of resource type Rj
Need [ i, j ] = Max [ i, j ] – Allocation [ i, j ]
Allocationi specifies the resources currently allocated to process Pi and Needi specifies the additional resources that process Pi may still request to complete its task.Banker’s algorithm consists of Safety algorithm and Resource request algorithmSafety AlgorithmThe algorithm for finding out whether or not a system is in a safe state can be described as follows:
1) Let Work and Finish be vectors of length ‘m’ and ‘n’ respectively. Initialize: Work = Available Finish[i] = false; for i=1, 2, 3, 4....n2) Find an i such that both a) Finish[i] = false b) Needi <= Work if no such i exists goto step (4)3) Work = Work + Allocation[i] Finish[i] = true goto step (2)4) if Finish [i] = true for all i then the system is in a safe state
Resource-Request AlgorithmLet Requesti be the request array for process Pi. Requesti [j] = k means process Pi wants k instances of resource type Rj. When a request for resources is made by process Pi, the following actions are taken:
1) If Requesti <= Needi Goto step (2) ; otherwise, raise an error condition, since the process has exceeded its maximum claim.2) If Requesti <= Available Goto step (3); otherwise, Pi must wait, since the resources are not available.3) Have the system pretend to have allocated the requested resources to process Pi by modifying the state as follows: Available = Available – Requesti Allocationi = Allocationi + Requesti Needi = Needi– Requesti
Example:Considering a system with five processes P0 through P4 and three resources of type A, B, C. Resource type A has 10 instances, B has 5 instances and type C has 7 instances. Suppose at time t0 following snapshot of the system has been taken:
Question1. What will be the content of the Need matrix?Need [i, j] = Max [i, j] – Allocation [i, j]So, the content of Need Matrix is:
Question2. Is the system in a safe state? If Yes, then what is the safe sequence?Applying the Safety algorithm on the given system,
Question3. What will happen if process P1 requests one additional instance of resource type A and two instances of resource type C?
We must determine whether this new system state is safe. To do so, we again execute Safety algorithm on the above data structures.
Hence the new system state is safe, so we can immediately grant the request for process P1 .Code for Banker’s Algorithm
C
C++
Java
Python3
C#
Javascript
// Banker's Algorithm#include <stdio.h>int main(){ // P0, P1, P2, P3, P4 are the Process names here int n, m, i, j, k; n = 5; // Number of processes m = 3; // Number of resources int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix { 2, 0, 0 }, // P1 { 3, 0, 2 }, // P2 { 2, 1, 1 }, // P3 { 0, 0, 2 } }; // P4 int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix { 3, 2, 2 }, // P1 { 9, 0, 2 }, // P2 { 2, 2, 2 }, // P3 { 4, 3, 3 } }; // P4 int avail[3] = { 3, 3, 2 }; // Available Resources int f[n], ans[n], ind = 0; for (k = 0; k < n; k++) { f[k] = 0; } int need[n][m]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) need[i][j] = max[i][j] - alloc[i][j]; } int y = 0; for (k = 0; k < 5; k++) { for (i = 0; i < n; i++) { if (f[i] == 0) { int flag = 0; for (j = 0; j < m; j++) { if (need[i][j] > avail[j]){ flag = 1; break; } } if (flag == 0) { ans[ind++] = i; for (y = 0; y < m; y++) avail[y] += alloc[i][y]; f[i] = 1; } } } } int flag = 1; for(int i=0;i<n;i++) { if(f[i]==0) { flag=0; printf("The following system is not safe"); break; } } if(flag==1) { printf("Following is the SAFE Sequence\n"); for (i = 0; i < n - 1; i++) printf(" P%d ->", ans[i]); printf(" P%d", ans[n - 1]); } return (0); // This code is contributed by Deep Baldha (CandyZack)}
// Banker's Algorithm#include <iostream>using namespace std; int main(){ // P0, P1, P2, P3, P4 are the Process names here int n, m, i, j, k; n = 5; // Number of processes m = 3; // Number of resources int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix { 2, 0, 0 }, // P1 { 3, 0, 2 }, // P2 { 2, 1, 1 }, // P3 { 0, 0, 2 } }; // P4 int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix { 3, 2, 2 }, // P1 { 9, 0, 2 }, // P2 { 2, 2, 2 }, // P3 { 4, 3, 3 } }; // P4 int avail[3] = { 3, 3, 2 }; // Available Resources int f[n], ans[n], ind = 0; for (k = 0; k < n; k++) { f[k] = 0; } int need[n][m]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) need[i][j] = max[i][j] - alloc[i][j]; } int y = 0; for (k = 0; k < 5; k++) { for (i = 0; i < n; i++) { if (f[i] == 0) { int flag = 0; for (j = 0; j < m; j++) { if (need[i][j] > avail[j]){ flag = 1; break; } } if (flag == 0) { ans[ind++] = i; for (y = 0; y < m; y++) avail[y] += alloc[i][y]; f[i] = 1; } } } } int flag = 1; // To check if sequence is safe or not for(int i = 0;i<n;i++) { if(f[i]==0) { flag = 0; cout << "The given sequence is not safe"; break; } } if(flag==1) { cout << "Following is the SAFE Sequence" << endl; for (i = 0; i < n - 1; i++) cout << " P" << ans[i] << " ->"; cout << " P" << ans[n - 1] <<endl; } return (0);}
//Java Program for Bankers Algorithmpublic class GfGBankers{ int n = 5; // Number of processes int m = 3; // Number of resources int need[][] = new int[n][m]; int [][]max; int [][]alloc; int []avail; int safeSequence[] = new int[n]; void initializeValues() { // P0, P1, P2, P3, P4 are the Process names here // Allocation Matrix alloc = new int[][] { { 0, 1, 0 }, //P0 { 2, 0, 0 }, //P1 { 3, 0, 2 }, //P2 { 2, 1, 1 }, //P3 { 0, 0, 2 } }; //P4 // MAX Matrix max = new int[][] { { 7, 5, 3 }, //P0 { 3, 2, 2 }, //P1 { 9, 0, 2 }, //P2 { 2, 2, 2 }, //P3 { 4, 3, 3 } }; //P4 // Available Resources avail = new int[] { 3, 3, 2 }; } void isSafe() { int count=0; //visited array to find the already allocated process boolean visited[] = new boolean[n]; for (int i = 0;i < n; i++) { visited[i] = false; } //work array to store the copy of available resources int work[] = new int[m]; for (int i = 0;i < m; i++) { work[i] = avail[i]; } while (count<n) { boolean flag = false; for (int i = 0;i < n; i++) { if (visited[i] == false) { int j; for (j = 0;j < m; j++) { if (need[i][j] > work[j]) break; } if (j == m) { safeSequence[count++]=i; visited[i]=true; flag=true; for (j = 0;j < m; j++) { work[j] = work[j]+alloc[i][j]; } } } } if (flag == false) { break; } } if (count < n) { System.out.println("The System is UnSafe!"); } else { //System.out.println("The given System is Safe"); System.out.println("Following is the SAFE Sequence"); for (int i = 0;i < n; i++) { System.out.print("P" + safeSequence[i]); if (i != n-1) System.out.print(" -> "); } } } void calculateNeed() { for (int i = 0;i < n; i++) { for (int j = 0;j < m; j++) { need[i][j] = max[i][j]-alloc[i][j]; } } } public static void main(String[] args) { int i, j, k; GfGBankers gfg = new GfGBankers(); gfg.initializeValues(); //Calculate the Need Matrix gfg.calculateNeed(); // Check whether system is in safe state or not gfg.isSafe(); }}
# Banker's Algorithm # Driver code:if __name__=="__main__": # P0, P1, P2, P3, P4 are the Process names here n = 5 # Number of processes m = 3 # Number of resources # Allocation Matrix alloc = [[0, 1, 0 ],[ 2, 0, 0 ], [3, 0, 2 ],[2, 1, 1] ,[ 0, 0, 2]] # MAX Matrix max = [[7, 5, 3 ],[3, 2, 2 ], [ 9, 0, 2 ],[2, 2, 2],[4, 3, 3]] avail = [3, 3, 2] # Available Resources f = [0]*n ans = [0]*n ind = 0 for k in range(n): f[k] = 0 need = [[ 0 for i in range(m)]for i in range(n)] for i in range(n): for j in range(m): need[i][j] = max[i][j] - alloc[i][j] y = 0 for k in range(5): for i in range(n): if (f[i] == 0): flag = 0 for j in range(m): if (need[i][j] > avail[j]): flag = 1 break if (flag == 0): ans[ind] = i ind += 1 for y in range(m): avail[y] += alloc[i][y] f[i] = 1 print("Following is the SAFE Sequence") for i in range(n - 1): print(" P", ans[i], " ->", sep="", end="") print(" P", ans[n - 1], sep="") # This code is contributed by SHUBHAMSINGH10
// C# Program for Bankers Algorithmusing System;using System.Collections.Generic; class GFG{static int n = 5; // Number of processesstatic int m = 3; // Number of resourcesint [,]need = new int[n, m];int [,]max;int [,]alloc;int []avail;int []safeSequence = new int[n]; void initializeValues(){ // P0, P1, P2, P3, P4 are the Process // names here Allocation Matrix alloc = new int[,] {{ 0, 1, 0 }, //P0 { 2, 0, 0 }, //P1 { 3, 0, 2 }, //P2 { 2, 1, 1 }, //P3 { 0, 0, 2 }};//P4 // MAX Matrix max = new int[,] {{ 7, 5, 3 }, //P0 { 3, 2, 2 }, //P1 { 9, 0, 2 }, //P2 { 2, 2, 2 }, //P3 { 4, 3, 3 }};//P4 // Available Resources avail = new int[] { 3, 3, 2 };} void isSafe(){ int count = 0; // visited array to find the // already allocated process Boolean []visited = new Boolean[n]; for (int i = 0; i < n; i++) { visited[i] = false; } // work array to store the copy of // available resources int []work = new int[m]; for (int i = 0; i < m; i++) { work[i] = avail[i]; } while (count<n) { Boolean flag = false; for (int i = 0; i < n; i++) { if (visited[i] == false) { int j; for (j = 0; j < m; j++) { if (need[i, j] > work[j]) break; } if (j == m) { safeSequence[count++] = i; visited[i] = true; flag = true; for (j = 0; j < m; j++) { work[j] = work[j] + alloc[i, j]; } } } } if (flag == false) { break; } } if (count < n) { Console.WriteLine("The System is UnSafe!"); } else { //System.out.println("The given System is Safe"); Console.WriteLine("Following is the SAFE Sequence"); for (int i = 0; i < n; i++) { Console.Write("P" + safeSequence[i]); if (i != n - 1) Console.Write(" -> "); } }} void calculateNeed(){ for (int i = 0;i < n; i++) { for (int j = 0;j < m; j++) { need[i, j] = max[i, j] - alloc[i, j]; } } } // Driver Codepublic static void Main(String[] args){ GFG gfg = new GFG(); gfg.initializeValues(); // Calculate the Need Matrix gfg.calculateNeed(); // Check whether system is in // safe state or not gfg.isSafe(); }} // This code is contributed by Rajput-Ji
<script> let n, m, i, j, k; n = 5; // Number of processes m = 3; // Number of resources let alloc = [ [ 0, 1, 0 ], // P0 // Allocation Matrix [ 2, 0, 0 ], // P1 [ 3, 0, 2 ], // P2 [ 2, 1, 1 ], // P3 [ 0, 0, 2 ] ]; // P4 let max = [ [ 7, 5, 3 ], // P0 // MAX Matrix [ 3, 2, 2 ], // P1 [ 9, 0, 2 ], // P2 [ 2, 2, 2 ], // P3 [ 4, 3, 3 ] ]; // P4 let avail = [ 3, 3, 2 ]; // Available Resources let f = [], ans = [], ind = 0; for (k = 0; k < n; k++) { f[k] = 0; } let need = []; for (i = 0; i < n; i++) { let need1 = []; for (j = 0; j < m; j++) need1.push(max[i][j] - alloc[i][j]); need.push(need1); } let y = 0; for (k = 0; k < 5; k++) { for (i = 0; i < n; i++) { if (f[i] == 0) { let flag = 0; for (j = 0; j < m; j++) { if (need[i][j] > avail[j]){ flag = 1; break; } } if (flag == 0) { ans[ind++] = i; for (y = 0; y < m; y++) avail[y] += alloc[i][y]; f[i] = 1; } } } } document.write("Following is the SAFE Sequence" + "<br>"); for (i = 0; i < n - 1; i++) document.write(" P" + ans[i] + " ->"); document.write( " P" + ans[n - 1] + "<br>");</script>
Following is the SAFE Sequence
P1 -> P3 -> P4 -> P0 -> P2
As the processes enter the system, they must predict the maximum number of resources needed which is not impractical to determine.
In this algorithm, the number of processes remain fixed which is not possible in interactive systems.
This algorithm requires that there should be a fixed number of resources to allocate. If a device breaks and becomes suddenly unavailable the algorithm would not work.
Overhead cost incurred by the algorithm can be high when there are many processes and resources because it has to be invoked for every processes.
Deepanshu8391
CandyZack
ShJos
tarlisonbrito
Rajput-Ji
muskan02
SHUBHAMSINGH10
dharanendralv23
itskawal2000
hrithik2108
Process Synchronization
Operating Systems
Operating Systems
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
LRU Cache Implementation
Cache Memory in Computer Organization
'crontab' in Linux with Examples
Memory Management in Operating System
Mutex lock for Linux Thread Synchronization
Difference between Internal and External fragmentation
Program for Least Recently Used (LRU) Page Replacement algorithm
Random Access Memory (RAM) and Read Only Memory (ROM)
Last Minute Notes – Operating Systems
Introduction of System Call
|
[
{
"code": null,
"e": 27733,
"s": 27705,
"text": "\n28 Dec, 2021"
},
{
"code": null,
"e": 28966,
"s": 27733,
"text": "The banker’s algorithm is a resource allocation and deadlock avoidance algorithm that tests for safety by simulating the allocation for predetermined maximum possible amounts of all resources, then makes an “s-state” check to test for possible activities, before deciding whether allocation should be allowed to continue.Why Banker’s algorithm is named so? Banker’s algorithm is named so because it is used in banking system to check whether loan can be sanctioned to a person or not. Suppose there are n number of account holders in a bank and the total sum of their money is S. If a person applies for a loan then the bank first subtracts the loan amount from the total money that bank has and if the remaining amount is greater than S then only the loan is sanctioned. It is done because if all the account holders comes to withdraw their money then the bank can easily do it.In other words, the bank would never allocate its money in such a way that it can no longer satisfy the needs of all its customers. The bank would try to be in safe state always.Following Data structures are used to implement the Banker’s Algorithm:Let ‘n’ be the number of processes in the system and ‘m’ be the number of resources types.Available : "
},
{
"code": null,
"e": 29055,
"s": 28966,
"text": "It is a 1-d array of size ‘m’ indicating the number of available resources of each type."
},
{
"code": null,
"e": 29124,
"s": 29055,
"text": "Available[ j ] = k means there are ‘k’ instances of resource type Rj"
},
{
"code": null,
"e": 29132,
"s": 29124,
"text": "Max : "
},
{
"code": null,
"e": 29225,
"s": 29132,
"text": "It is a 2-d array of size ‘n*m’ that defines the maximum demand of each process in a system."
},
{
"code": null,
"e": 29313,
"s": 29225,
"text": "Max[ i, j ] = k means process Pi may request at most ‘k’ instances of resource type Rj."
},
{
"code": null,
"e": 29328,
"s": 29313,
"text": "Allocation : "
},
{
"code": null,
"e": 29447,
"s": 29328,
"text": "It is a 2-d array of size ‘n*m’ that defines the number of resources of each type currently allocated to each process."
},
{
"code": null,
"e": 29544,
"s": 29447,
"text": "Allocation[ i, j ] = k means process Pi is currently allocated ‘k’ instances of resource type Rj"
},
{
"code": null,
"e": 29553,
"s": 29544,
"text": "Need : "
},
{
"code": null,
"e": 29645,
"s": 29553,
"text": "It is a 2-d array of size ‘n*m’ that indicates the remaining resource need of each process."
},
{
"code": null,
"e": 29731,
"s": 29645,
"text": "Need [ i, j ] = k means process Pi currently need ‘k’ instances of resource type Rj"
},
{
"code": null,
"e": 29788,
"s": 29731,
"text": "Need [ i, j ] = Max [ i, j ] – Allocation [ i, j ]"
},
{
"code": null,
"e": 30158,
"s": 29790,
"text": "Allocationi specifies the resources currently allocated to process Pi and Needi specifies the additional resources that process Pi may still request to complete its task.Banker’s algorithm consists of Safety algorithm and Resource request algorithmSafety AlgorithmThe algorithm for finding out whether or not a system is in a safe state can be described as follows: "
},
{
"code": null,
"e": 30528,
"s": 30158,
"text": "1) Let Work and Finish be vectors of length ‘m’ and ‘n’ respectively. Initialize: Work = Available Finish[i] = false; for i=1, 2, 3, 4....n2) Find an i such that both a) Finish[i] = false b) Needi <= Work if no such i exists goto step (4)3) Work = Work + Allocation[i] Finish[i] = true goto step (2)4) if Finish [i] = true for all i then the system is in a safe state "
},
{
"code": null,
"e": 30763,
"s": 30528,
"text": "Resource-Request AlgorithmLet Requesti be the request array for process Pi. Requesti [j] = k means process Pi wants k instances of resource type Rj. When a request for resources is made by process Pi, the following actions are taken: "
},
{
"code": null,
"e": 31208,
"s": 30763,
"text": "1) If Requesti <= Needi Goto step (2) ; otherwise, raise an error condition, since the process has exceeded its maximum claim.2) If Requesti <= Available Goto step (3); otherwise, Pi must wait, since the resources are not available.3) Have the system pretend to have allocated the requested resources to process Pi by modifying the state as follows: Available = Available – Requesti Allocationi = Allocationi + Requesti Needi = Needi– Requesti "
},
{
"code": null,
"e": 31457,
"s": 31208,
"text": "Example:Considering a system with five processes P0 through P4 and three resources of type A, B, C. Resource type A has 10 instances, B has 5 instances and type C has 7 instances. Suppose at time t0 following snapshot of the system has been taken: "
},
{
"code": null,
"e": 31592,
"s": 31457,
"text": "Question1. What will be the content of the Need matrix?Need [i, j] = Max [i, j] – Allocation [i, j]So, the content of Need Matrix is: "
},
{
"code": null,
"e": 31726,
"s": 31592,
"text": "Question2. Is the system in a safe state? If Yes, then what is the safe sequence?Applying the Safety algorithm on the given system, "
},
{
"code": null,
"e": 31859,
"s": 31726,
"text": "Question3. What will happen if process P1 requests one additional instance of resource type A and two instances of resource type C? "
},
{
"code": null,
"e": 31991,
"s": 31859,
"text": "We must determine whether this new system state is safe. To do so, we again execute Safety algorithm on the above data structures. "
},
{
"code": null,
"e": 32113,
"s": 31991,
"text": "Hence the new system state is safe, so we can immediately grant the request for process P1 .Code for Banker’s Algorithm "
},
{
"code": null,
"e": 32115,
"s": 32113,
"text": "C"
},
{
"code": null,
"e": 32119,
"s": 32115,
"text": "C++"
},
{
"code": null,
"e": 32124,
"s": 32119,
"text": "Java"
},
{
"code": null,
"e": 32132,
"s": 32124,
"text": "Python3"
},
{
"code": null,
"e": 32135,
"s": 32132,
"text": "C#"
},
{
"code": null,
"e": 32146,
"s": 32135,
"text": "Javascript"
},
{
"code": "// Banker's Algorithm#include <stdio.h>int main(){ // P0, P1, P2, P3, P4 are the Process names here int n, m, i, j, k; n = 5; // Number of processes m = 3; // Number of resources int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix { 2, 0, 0 }, // P1 { 3, 0, 2 }, // P2 { 2, 1, 1 }, // P3 { 0, 0, 2 } }; // P4 int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix { 3, 2, 2 }, // P1 { 9, 0, 2 }, // P2 { 2, 2, 2 }, // P3 { 4, 3, 3 } }; // P4 int avail[3] = { 3, 3, 2 }; // Available Resources int f[n], ans[n], ind = 0; for (k = 0; k < n; k++) { f[k] = 0; } int need[n][m]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) need[i][j] = max[i][j] - alloc[i][j]; } int y = 0; for (k = 0; k < 5; k++) { for (i = 0; i < n; i++) { if (f[i] == 0) { int flag = 0; for (j = 0; j < m; j++) { if (need[i][j] > avail[j]){ flag = 1; break; } } if (flag == 0) { ans[ind++] = i; for (y = 0; y < m; y++) avail[y] += alloc[i][y]; f[i] = 1; } } } } int flag = 1; for(int i=0;i<n;i++) { if(f[i]==0) { flag=0; printf(\"The following system is not safe\"); break; } } if(flag==1) { printf(\"Following is the SAFE Sequence\\n\"); for (i = 0; i < n - 1; i++) printf(\" P%d ->\", ans[i]); printf(\" P%d\", ans[n - 1]); } return (0); // This code is contributed by Deep Baldha (CandyZack)}",
"e": 34059,
"s": 32146,
"text": null
},
{
"code": "// Banker's Algorithm#include <iostream>using namespace std; int main(){ // P0, P1, P2, P3, P4 are the Process names here int n, m, i, j, k; n = 5; // Number of processes m = 3; // Number of resources int alloc[5][3] = { { 0, 1, 0 }, // P0 // Allocation Matrix { 2, 0, 0 }, // P1 { 3, 0, 2 }, // P2 { 2, 1, 1 }, // P3 { 0, 0, 2 } }; // P4 int max[5][3] = { { 7, 5, 3 }, // P0 // MAX Matrix { 3, 2, 2 }, // P1 { 9, 0, 2 }, // P2 { 2, 2, 2 }, // P3 { 4, 3, 3 } }; // P4 int avail[3] = { 3, 3, 2 }; // Available Resources int f[n], ans[n], ind = 0; for (k = 0; k < n; k++) { f[k] = 0; } int need[n][m]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) need[i][j] = max[i][j] - alloc[i][j]; } int y = 0; for (k = 0; k < 5; k++) { for (i = 0; i < n; i++) { if (f[i] == 0) { int flag = 0; for (j = 0; j < m; j++) { if (need[i][j] > avail[j]){ flag = 1; break; } } if (flag == 0) { ans[ind++] = i; for (y = 0; y < m; y++) avail[y] += alloc[i][y]; f[i] = 1; } } } } int flag = 1; // To check if sequence is safe or not for(int i = 0;i<n;i++) { if(f[i]==0) { flag = 0; cout << \"The given sequence is not safe\"; break; } } if(flag==1) { cout << \"Following is the SAFE Sequence\" << endl; for (i = 0; i < n - 1; i++) cout << \" P\" << ans[i] << \" ->\"; cout << \" P\" << ans[n - 1] <<endl; } return (0);}",
"e": 35741,
"s": 34059,
"text": null
},
{
"code": "//Java Program for Bankers Algorithmpublic class GfGBankers{ int n = 5; // Number of processes int m = 3; // Number of resources int need[][] = new int[n][m]; int [][]max; int [][]alloc; int []avail; int safeSequence[] = new int[n]; void initializeValues() { // P0, P1, P2, P3, P4 are the Process names here // Allocation Matrix alloc = new int[][] { { 0, 1, 0 }, //P0 { 2, 0, 0 }, //P1 { 3, 0, 2 }, //P2 { 2, 1, 1 }, //P3 { 0, 0, 2 } }; //P4 // MAX Matrix max = new int[][] { { 7, 5, 3 }, //P0 { 3, 2, 2 }, //P1 { 9, 0, 2 }, //P2 { 2, 2, 2 }, //P3 { 4, 3, 3 } }; //P4 // Available Resources avail = new int[] { 3, 3, 2 }; } void isSafe() { int count=0; //visited array to find the already allocated process boolean visited[] = new boolean[n]; for (int i = 0;i < n; i++) { visited[i] = false; } //work array to store the copy of available resources int work[] = new int[m]; for (int i = 0;i < m; i++) { work[i] = avail[i]; } while (count<n) { boolean flag = false; for (int i = 0;i < n; i++) { if (visited[i] == false) { int j; for (j = 0;j < m; j++) { if (need[i][j] > work[j]) break; } if (j == m) { safeSequence[count++]=i; visited[i]=true; flag=true; for (j = 0;j < m; j++) { work[j] = work[j]+alloc[i][j]; } } } } if (flag == false) { break; } } if (count < n) { System.out.println(\"The System is UnSafe!\"); } else { //System.out.println(\"The given System is Safe\"); System.out.println(\"Following is the SAFE Sequence\"); for (int i = 0;i < n; i++) { System.out.print(\"P\" + safeSequence[i]); if (i != n-1) System.out.print(\" -> \"); } } } void calculateNeed() { for (int i = 0;i < n; i++) { for (int j = 0;j < m; j++) { need[i][j] = max[i][j]-alloc[i][j]; } } } public static void main(String[] args) { int i, j, k; GfGBankers gfg = new GfGBankers(); gfg.initializeValues(); //Calculate the Need Matrix gfg.calculateNeed(); // Check whether system is in safe state or not gfg.isSafe(); }}",
"e": 38496,
"s": 35741,
"text": null
},
{
"code": "# Banker's Algorithm # Driver code:if __name__==\"__main__\": # P0, P1, P2, P3, P4 are the Process names here n = 5 # Number of processes m = 3 # Number of resources # Allocation Matrix alloc = [[0, 1, 0 ],[ 2, 0, 0 ], [3, 0, 2 ],[2, 1, 1] ,[ 0, 0, 2]] # MAX Matrix max = [[7, 5, 3 ],[3, 2, 2 ], [ 9, 0, 2 ],[2, 2, 2],[4, 3, 3]] avail = [3, 3, 2] # Available Resources f = [0]*n ans = [0]*n ind = 0 for k in range(n): f[k] = 0 need = [[ 0 for i in range(m)]for i in range(n)] for i in range(n): for j in range(m): need[i][j] = max[i][j] - alloc[i][j] y = 0 for k in range(5): for i in range(n): if (f[i] == 0): flag = 0 for j in range(m): if (need[i][j] > avail[j]): flag = 1 break if (flag == 0): ans[ind] = i ind += 1 for y in range(m): avail[y] += alloc[i][y] f[i] = 1 print(\"Following is the SAFE Sequence\") for i in range(n - 1): print(\" P\", ans[i], \" ->\", sep=\"\", end=\"\") print(\" P\", ans[n - 1], sep=\"\") # This code is contributed by SHUBHAMSINGH10",
"e": 39864,
"s": 38496,
"text": null
},
{
"code": "// C# Program for Bankers Algorithmusing System;using System.Collections.Generic; class GFG{static int n = 5; // Number of processesstatic int m = 3; // Number of resourcesint [,]need = new int[n, m];int [,]max;int [,]alloc;int []avail;int []safeSequence = new int[n]; void initializeValues(){ // P0, P1, P2, P3, P4 are the Process // names here Allocation Matrix alloc = new int[,] {{ 0, 1, 0 }, //P0 { 2, 0, 0 }, //P1 { 3, 0, 2 }, //P2 { 2, 1, 1 }, //P3 { 0, 0, 2 }};//P4 // MAX Matrix max = new int[,] {{ 7, 5, 3 }, //P0 { 3, 2, 2 }, //P1 { 9, 0, 2 }, //P2 { 2, 2, 2 }, //P3 { 4, 3, 3 }};//P4 // Available Resources avail = new int[] { 3, 3, 2 };} void isSafe(){ int count = 0; // visited array to find the // already allocated process Boolean []visited = new Boolean[n]; for (int i = 0; i < n; i++) { visited[i] = false; } // work array to store the copy of // available resources int []work = new int[m]; for (int i = 0; i < m; i++) { work[i] = avail[i]; } while (count<n) { Boolean flag = false; for (int i = 0; i < n; i++) { if (visited[i] == false) { int j; for (j = 0; j < m; j++) { if (need[i, j] > work[j]) break; } if (j == m) { safeSequence[count++] = i; visited[i] = true; flag = true; for (j = 0; j < m; j++) { work[j] = work[j] + alloc[i, j]; } } } } if (flag == false) { break; } } if (count < n) { Console.WriteLine(\"The System is UnSafe!\"); } else { //System.out.println(\"The given System is Safe\"); Console.WriteLine(\"Following is the SAFE Sequence\"); for (int i = 0; i < n; i++) { Console.Write(\"P\" + safeSequence[i]); if (i != n - 1) Console.Write(\" -> \"); } }} void calculateNeed(){ for (int i = 0;i < n; i++) { for (int j = 0;j < m; j++) { need[i, j] = max[i, j] - alloc[i, j]; } } } // Driver Codepublic static void Main(String[] args){ GFG gfg = new GFG(); gfg.initializeValues(); // Calculate the Need Matrix gfg.calculateNeed(); // Check whether system is in // safe state or not gfg.isSafe(); }} // This code is contributed by Rajput-Ji",
"e": 42705,
"s": 39864,
"text": null
},
{
"code": "<script> let n, m, i, j, k; n = 5; // Number of processes m = 3; // Number of resources let alloc = [ [ 0, 1, 0 ], // P0 // Allocation Matrix [ 2, 0, 0 ], // P1 [ 3, 0, 2 ], // P2 [ 2, 1, 1 ], // P3 [ 0, 0, 2 ] ]; // P4 let max = [ [ 7, 5, 3 ], // P0 // MAX Matrix [ 3, 2, 2 ], // P1 [ 9, 0, 2 ], // P2 [ 2, 2, 2 ], // P3 [ 4, 3, 3 ] ]; // P4 let avail = [ 3, 3, 2 ]; // Available Resources let f = [], ans = [], ind = 0; for (k = 0; k < n; k++) { f[k] = 0; } let need = []; for (i = 0; i < n; i++) { let need1 = []; for (j = 0; j < m; j++) need1.push(max[i][j] - alloc[i][j]); need.push(need1); } let y = 0; for (k = 0; k < 5; k++) { for (i = 0; i < n; i++) { if (f[i] == 0) { let flag = 0; for (j = 0; j < m; j++) { if (need[i][j] > avail[j]){ flag = 1; break; } } if (flag == 0) { ans[ind++] = i; for (y = 0; y < m; y++) avail[y] += alloc[i][y]; f[i] = 1; } } } } document.write(\"Following is the SAFE Sequence\" + \"<br>\"); for (i = 0; i < n - 1; i++) document.write(\" P\" + ans[i] + \" ->\"); document.write( \" P\" + ans[n - 1] + \"<br>\");</script>",
"e": 44046,
"s": 42705,
"text": null
},
{
"code": null,
"e": 44105,
"s": 44046,
"text": "Following is the SAFE Sequence\n P1 -> P3 -> P4 -> P0 -> P2"
},
{
"code": null,
"e": 44236,
"s": 44105,
"text": "As the processes enter the system, they must predict the maximum number of resources needed which is not impractical to determine."
},
{
"code": null,
"e": 44338,
"s": 44236,
"text": "In this algorithm, the number of processes remain fixed which is not possible in interactive systems."
},
{
"code": null,
"e": 44506,
"s": 44338,
"text": "This algorithm requires that there should be a fixed number of resources to allocate. If a device breaks and becomes suddenly unavailable the algorithm would not work."
},
{
"code": null,
"e": 44652,
"s": 44506,
"text": "Overhead cost incurred by the algorithm can be high when there are many processes and resources because it has to be invoked for every processes."
},
{
"code": null,
"e": 44666,
"s": 44652,
"text": "Deepanshu8391"
},
{
"code": null,
"e": 44676,
"s": 44666,
"text": "CandyZack"
},
{
"code": null,
"e": 44682,
"s": 44676,
"text": "ShJos"
},
{
"code": null,
"e": 44696,
"s": 44682,
"text": "tarlisonbrito"
},
{
"code": null,
"e": 44706,
"s": 44696,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 44715,
"s": 44706,
"text": "muskan02"
},
{
"code": null,
"e": 44730,
"s": 44715,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 44746,
"s": 44730,
"text": "dharanendralv23"
},
{
"code": null,
"e": 44759,
"s": 44746,
"text": "itskawal2000"
},
{
"code": null,
"e": 44771,
"s": 44759,
"text": "hrithik2108"
},
{
"code": null,
"e": 44795,
"s": 44771,
"text": "Process Synchronization"
},
{
"code": null,
"e": 44813,
"s": 44795,
"text": "Operating Systems"
},
{
"code": null,
"e": 44831,
"s": 44813,
"text": "Operating Systems"
},
{
"code": null,
"e": 44929,
"s": 44831,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44938,
"s": 44929,
"text": "Comments"
},
{
"code": null,
"e": 44951,
"s": 44938,
"text": "Old Comments"
},
{
"code": null,
"e": 44976,
"s": 44951,
"text": "LRU Cache Implementation"
},
{
"code": null,
"e": 45014,
"s": 44976,
"text": "Cache Memory in Computer Organization"
},
{
"code": null,
"e": 45047,
"s": 45014,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 45085,
"s": 45047,
"text": "Memory Management in Operating System"
},
{
"code": null,
"e": 45129,
"s": 45085,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 45184,
"s": 45129,
"text": "Difference between Internal and External fragmentation"
},
{
"code": null,
"e": 45249,
"s": 45184,
"text": "Program for Least Recently Used (LRU) Page Replacement algorithm"
},
{
"code": null,
"e": 45303,
"s": 45249,
"text": "Random Access Memory (RAM) and Read Only Memory (ROM)"
},
{
"code": null,
"e": 45341,
"s": 45303,
"text": "Last Minute Notes – Operating Systems"
}
] |
C++ Iterator Library - prev
|
It returns an iterator pointing to the element that it would be pointing to if advanced -n positions.
Following is the declaration for std::prev.
template <class BidirectionalIterator>
BidirectionalIterator prev (BidirectionalIterator it,
typename iterator_traits<BidirectionalIterator>::difference_type n = 1);
it − It is a base postion in iterator.
it − It is a base postion in iterator.
n − It indicates about number of postion.
n − It indicates about number of postion.
It returned an iterator to the element n positions before it.
If any of the arithmetical operations performed on the iterator throws.
constant for random-access iterators.
The following example shows the usage of std::prev.
#include <iostream>
#include <iterator>
#include <list>
#include <algorithm>
int main () {
std::list<int> mylist;
for (int i = 0; i < 10; i++) mylist.push_back (i*1);
std::cout << "The last element is " << *std::prev(mylist.begin()) << '\n';
return 0;
}
Let us compile and run the above program, this will produce the following result −
The last element is 10
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2705,
"s": 2603,
"text": "It returns an iterator pointing to the element that it would be pointing to if advanced -n positions."
},
{
"code": null,
"e": 2749,
"s": 2705,
"text": "Following is the declaration for std::prev."
},
{
"code": null,
"e": 2925,
"s": 2749,
"text": "template <class BidirectionalIterator>\n BidirectionalIterator prev (BidirectionalIterator it,\n typename iterator_traits<BidirectionalIterator>::difference_type n = 1);\n"
},
{
"code": null,
"e": 2964,
"s": 2925,
"text": "it − It is a base postion in iterator."
},
{
"code": null,
"e": 3003,
"s": 2964,
"text": "it − It is a base postion in iterator."
},
{
"code": null,
"e": 3045,
"s": 3003,
"text": "n − It indicates about number of postion."
},
{
"code": null,
"e": 3087,
"s": 3045,
"text": "n − It indicates about number of postion."
},
{
"code": null,
"e": 3149,
"s": 3087,
"text": "It returned an iterator to the element n positions before it."
},
{
"code": null,
"e": 3221,
"s": 3149,
"text": "If any of the arithmetical operations performed on the iterator throws."
},
{
"code": null,
"e": 3259,
"s": 3221,
"text": "constant for random-access iterators."
},
{
"code": null,
"e": 3311,
"s": 3259,
"text": "The following example shows the usage of std::prev."
},
{
"code": null,
"e": 3603,
"s": 3311,
"text": "#include <iostream> \n#include <iterator> \n#include <list> \n#include <algorithm> \n\nint main () {\n std::list<int> mylist;\n for (int i = 0; i < 10; i++) mylist.push_back (i*1);\n\n std::cout << \"The last element is \" << *std::prev(mylist.begin()) << '\\n';\n\n return 0;\n}"
},
{
"code": null,
"e": 3686,
"s": 3603,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3710,
"s": 3686,
"text": "The last element is 10\n"
},
{
"code": null,
"e": 3717,
"s": 3710,
"text": " Print"
},
{
"code": null,
"e": 3728,
"s": 3717,
"text": " Add Notes"
}
] |
How to set an Android App's background image repeated?
|
This example demonstrates about How to set an Android App's background image repeated
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/drawable/app_background.xml.
<?xml version="1.0" encoding="utf-8"?>
<bitmap xmlns:android="http://schemas.android.com/apk/res/android" android:src="@drawable/image1" android:tileMode="repeat" />
Step 2 − Add the following code to res/values/styles.xml.
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="android:windowBackground">@drawable/app_background</item>
</style>
</resources>
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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="16dp" />
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import android.os.Bundle;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
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">
<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": 1148,
"s": 1062,
"text": "This example demonstrates about How to set an Android App's background image repeated"
},
{
"code": null,
"e": 1277,
"s": 1148,
"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": 1345,
"s": 1277,
"text": "Step 2 − Add the following code to res/drawable/app_background.xml."
},
{
"code": null,
"e": 1511,
"s": 1345,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<bitmap xmlns:android=\"http://schemas.android.com/apk/res/android\" android:src=\"@drawable/image1\" android:tileMode=\"repeat\" />"
},
{
"code": null,
"e": 1569,
"s": 1511,
"text": "Step 2 − Add the following code to res/values/styles.xml."
},
{
"code": null,
"e": 1935,
"s": 1569,
"text": "<resources>\n <style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n <item name=\"colorPrimary\">@color/colorPrimary</item>\n <item name=\"colorPrimaryDark\">@color/colorPrimaryDark</item>\n <item name=\"colorAccent\">@color/colorAccent</item>\n <item name=\"android:windowBackground\">@drawable/app_background</item>\n </style>\n</resources>"
},
{
"code": null,
"e": 2000,
"s": 1935,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2228,
"s": 2000,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\" />"
},
{
"code": null,
"e": 2285,
"s": 2228,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2602,
"s": 2285,
"text": "package app.com.sample;\nimport android.os.Bundle;\nimport androidx.appcompat.app.AppCompatActivity;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}"
},
{
"code": null,
"e": 2657,
"s": 2602,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3327,
"s": 2657,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3674,
"s": 3327,
"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": 3715,
"s": 3674,
"text": "Click here to download the project code."
}
] |
Array.Find() Method in C#
|
The Array.Find() method in C# is used to search for an element that matches the conditions defined by the specified predicate and returns the first occurrence within the entire Array.
Following is the syntax −
public static T Find<T> (T[] array, Predicate<T> match);
Above, the array is the one-dimensional, zero-based array to search, whereas match is the predicate that defines the conditions of the element to search for.
Let us now see an example to implement the Array.Find() method −
using System;
public class Demo{
public static void Main(){
Console.WriteLine("Array elements...");
string[] arr = { "car", "bike", "truck", "bus"};
for (int i = 0; i < arr.Length; i++){
Console.Write("{0} ", arr[i]);
}
Console.WriteLine();
string res = Array.Find(arr, ele => ele.StartsWith("t",
StringComparison.Ordinal));
Console.Write("Searched element...");
Console.Write("{0}", res);
}
}
This will produce the following output −
Array elements...
car bike truck bus
Searched element...truck
|
[
{
"code": null,
"e": 1246,
"s": 1062,
"text": "The Array.Find() method in C# is used to search for an element that matches the conditions defined by the specified predicate and returns the first occurrence within the entire Array."
},
{
"code": null,
"e": 1272,
"s": 1246,
"text": "Following is the syntax −"
},
{
"code": null,
"e": 1329,
"s": 1272,
"text": "public static T Find<T> (T[] array, Predicate<T> match);"
},
{
"code": null,
"e": 1487,
"s": 1329,
"text": "Above, the array is the one-dimensional, zero-based array to search, whereas match is the predicate that defines the conditions of the element to search for."
},
{
"code": null,
"e": 1552,
"s": 1487,
"text": "Let us now see an example to implement the Array.Find() method −"
},
{
"code": null,
"e": 2015,
"s": 1552,
"text": "using System;\npublic class Demo{\n public static void Main(){\n Console.WriteLine(\"Array elements...\");\n string[] arr = { \"car\", \"bike\", \"truck\", \"bus\"};\n for (int i = 0; i < arr.Length; i++){\n Console.Write(\"{0} \", arr[i]);\n }\n Console.WriteLine();\n string res = Array.Find(arr, ele => ele.StartsWith(\"t\",\n StringComparison.Ordinal));\n Console.Write(\"Searched element...\");\n Console.Write(\"{0}\", res);\n }\n}"
},
{
"code": null,
"e": 2056,
"s": 2015,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2118,
"s": 2056,
"text": "Array elements...\ncar bike truck bus\nSearched element...truck"
}
] |
Sort in C++ Standard Template Library (STL) - GeeksforGeeks
|
11 May, 2022
Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort(). This function internally uses IntroSort. In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By default, it uses QuickSort but if QuickSort is doing unfair partitioning and taking more than N*logN time, it switches to HeapSort and when the array size becomes really small, it switches to InsertionSort.
The prototype for sort is :
sort(startaddress, endaddress)
startaddress: the address of the first
element of the array
endaddress: the address of the next
contiguous location of the
last element of the array.
So actually sort() sorts in the
range of [startaddress,endaddress)
C++
// C++ program to sort an array#include <algorithm>#include <iostream> using namespace std; void show(int a[], int array_size){ for (int i = 0; i < array_size; ++i) cout << a[i] << " ";} // Driver codeint main(){ int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; // size of the array int asize = sizeof(a) / sizeof(a[0]); cout << "The array before sorting is : \n"; // print the array show(a, asize); // sort the array sort(a, a + asize); cout << "\n\nThe array after sorting is :\n"; // print the array after sorting show(a, asize); return 0;}
The array before sorting is :
1 5 8 9 6 7 3 4 2 0
The array after sorting is :
0 1 2 3 4 5 6 7 8 9
Refer std::sort() for more details.
manish095
harshitmuhal
PrashunJha
hrithikmaheshwari42
kk9826225
cpp-algorithm-library
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Virtual Function in C++
Constructors in C++
Templates in C++ with Examples
Operator Overloading in C++
Socket Programming in C/C++
Polymorphism in C++
Copy Constructor in C++
Friend class and function in C++
C++ Data Types
Left Shift and Right Shift Operators in C/C++
|
[
{
"code": null,
"e": 26182,
"s": 26154,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 26736,
"s": 26182,
"text": "Sorting is one of the most basic functions applied to data. It means arranging the data in a particular fashion, which can be increasing or decreasing. There is a builtin function in C++ STL by the name of sort(). This function internally uses IntroSort. In more details it is implemented using hybrid of QuickSort, HeapSort and InsertionSort.By default, it uses QuickSort but if QuickSort is doing unfair partitioning and taking more than N*logN time, it switches to HeapSort and when the array size becomes really small, it switches to InsertionSort. "
},
{
"code": null,
"e": 26765,
"s": 26736,
"text": "The prototype for sort is : "
},
{
"code": null,
"e": 27056,
"s": 26765,
"text": "sort(startaddress, endaddress)\n\nstartaddress: the address of the first \n element of the array\nendaddress: the address of the next \n contiguous location of the \n last element of the array.\nSo actually sort() sorts in the \nrange of [startaddress,endaddress)"
},
{
"code": null,
"e": 27060,
"s": 27056,
"text": "C++"
},
{
"code": "// C++ program to sort an array#include <algorithm>#include <iostream> using namespace std; void show(int a[], int array_size){ for (int i = 0; i < array_size; ++i) cout << a[i] << \" \";} // Driver codeint main(){ int a[] = { 1, 5, 8, 9, 6, 7, 3, 4, 2, 0 }; // size of the array int asize = sizeof(a) / sizeof(a[0]); cout << \"The array before sorting is : \\n\"; // print the array show(a, asize); // sort the array sort(a, a + asize); cout << \"\\n\\nThe array after sorting is :\\n\"; // print the array after sorting show(a, asize); return 0;}",
"e": 27668,
"s": 27060,
"text": null
},
{
"code": null,
"e": 27771,
"s": 27668,
"text": "The array before sorting is : \n1 5 8 9 6 7 3 4 2 0 \n\nThe array after sorting is :\n0 1 2 3 4 5 6 7 8 9 "
},
{
"code": null,
"e": 27807,
"s": 27771,
"text": "Refer std::sort() for more details."
},
{
"code": null,
"e": 27817,
"s": 27807,
"text": "manish095"
},
{
"code": null,
"e": 27830,
"s": 27817,
"text": "harshitmuhal"
},
{
"code": null,
"e": 27841,
"s": 27830,
"text": "PrashunJha"
},
{
"code": null,
"e": 27861,
"s": 27841,
"text": "hrithikmaheshwari42"
},
{
"code": null,
"e": 27871,
"s": 27861,
"text": "kk9826225"
},
{
"code": null,
"e": 27893,
"s": 27871,
"text": "cpp-algorithm-library"
},
{
"code": null,
"e": 27897,
"s": 27893,
"text": "STL"
},
{
"code": null,
"e": 27901,
"s": 27897,
"text": "C++"
},
{
"code": null,
"e": 27905,
"s": 27901,
"text": "STL"
},
{
"code": null,
"e": 27909,
"s": 27905,
"text": "CPP"
},
{
"code": null,
"e": 28007,
"s": 27909,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28031,
"s": 28007,
"text": "Virtual Function in C++"
},
{
"code": null,
"e": 28051,
"s": 28031,
"text": "Constructors in C++"
},
{
"code": null,
"e": 28082,
"s": 28051,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 28110,
"s": 28082,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 28138,
"s": 28110,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 28158,
"s": 28138,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 28182,
"s": 28158,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 28215,
"s": 28182,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 28230,
"s": 28215,
"text": "C++ Data Types"
}
] |
How to add table row in a table using jQuery? - GeeksforGeeks
|
23 Apr, 2019
jQuery can be used to add table rows dynamically. This can be used in web applications where the user may need to add more rows if required.
Steps to add table row:
The required markup for the row is constructed.markup = "<tr><td> + information + </td></tr>"
markup = "<tr><td> + information + </td></tr>"
The table body is selected to which the table rows to be added.tableBody = $("table tbody")
tableBody = $("table tbody")
Finally the markup is added to the table body.tableBody.append(markup)
tableBody.append(markup)
Example:
<!DOCTYPE html><html> <head> <title> How to add table row in jQuery? </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <style> table { margin: 25px 0; width: 200px; } table th, table td { padding: 10px; text-align: center; } table, th, td { border: 1px solid; } </style></head> <body> <h1 style="color: green"> GeeksForGeeks </h1> <b>How to add table row in jQuery?</b> <p> Click on the button below to add a row to the table </p> <button class="add-row"> Add row </button> <table> <thead> <tr> <th>Rows</th> </tr> </thead> <tbody> <tr> <td>This is row 0</td> </tr> </tbody> </table> <!-- Script to add table row --> <script> let lineNo = 1; $(document).ready(function () { $(".add-row").click(function () { markup = "<tr><td>This is row " + lineNo + "</td></tr>"; tableBody = $("table tbody"); tableBody.append(markup); lineNo++; }); }); </script></body></html>
Output:
Before clicking the button:
After clicking the button 4 times:
jQuery-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
Difference between var, let and const keywords in JavaScript
Set the value of an input field in JavaScript
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 24680,
"s": 24652,
"text": "\n23 Apr, 2019"
},
{
"code": null,
"e": 24821,
"s": 24680,
"text": "jQuery can be used to add table rows dynamically. This can be used in web applications where the user may need to add more rows if required."
},
{
"code": null,
"e": 24845,
"s": 24821,
"text": "Steps to add table row:"
},
{
"code": null,
"e": 24939,
"s": 24845,
"text": "The required markup for the row is constructed.markup = \"<tr><td> + information + </td></tr>\""
},
{
"code": "markup = \"<tr><td> + information + </td></tr>\"",
"e": 24986,
"s": 24939,
"text": null
},
{
"code": null,
"e": 25078,
"s": 24986,
"text": "The table body is selected to which the table rows to be added.tableBody = $(\"table tbody\")"
},
{
"code": "tableBody = $(\"table tbody\")",
"e": 25107,
"s": 25078,
"text": null
},
{
"code": null,
"e": 25178,
"s": 25107,
"text": "Finally the markup is added to the table body.tableBody.append(markup)"
},
{
"code": "tableBody.append(markup)",
"e": 25203,
"s": 25178,
"text": null
},
{
"code": null,
"e": 25212,
"s": 25203,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title> How to add table row in jQuery? </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <style> table { margin: 25px 0; width: 200px; } table th, table td { padding: 10px; text-align: center; } table, th, td { border: 1px solid; } </style></head> <body> <h1 style=\"color: green\"> GeeksForGeeks </h1> <b>How to add table row in jQuery?</b> <p> Click on the button below to add a row to the table </p> <button class=\"add-row\"> Add row </button> <table> <thead> <tr> <th>Rows</th> </tr> </thead> <tbody> <tr> <td>This is row 0</td> </tr> </tbody> </table> <!-- Script to add table row --> <script> let lineNo = 1; $(document).ready(function () { $(\".add-row\").click(function () { markup = \"<tr><td>This is row \" + lineNo + \"</td></tr>\"; tableBody = $(\"table tbody\"); tableBody.append(markup); lineNo++; }); }); </script></body></html> ",
"e": 26604,
"s": 25212,
"text": null
},
{
"code": null,
"e": 26612,
"s": 26604,
"text": "Output:"
},
{
"code": null,
"e": 26640,
"s": 26612,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 26675,
"s": 26640,
"text": "After clicking the button 4 times:"
},
{
"code": null,
"e": 26687,
"s": 26675,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 26694,
"s": 26687,
"text": "Picked"
},
{
"code": null,
"e": 26705,
"s": 26694,
"text": "JavaScript"
},
{
"code": null,
"e": 26722,
"s": 26705,
"text": "Web Technologies"
},
{
"code": null,
"e": 26749,
"s": 26722,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 26847,
"s": 26749,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26856,
"s": 26847,
"text": "Comments"
},
{
"code": null,
"e": 26869,
"s": 26856,
"text": "Old Comments"
},
{
"code": null,
"e": 26914,
"s": 26869,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26986,
"s": 26914,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27047,
"s": 26986,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27093,
"s": 27047,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 27134,
"s": 27093,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27176,
"s": 27134,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27209,
"s": 27176,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 27271,
"s": 27209,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 27314,
"s": 27271,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
C/C++ program to implement CHECKSUM - GeeksforGeeks
|
03 Dec, 2021
The Checksum is an error detection method that detected errors in data/message while it is transmitted from sender to receiver. This method is used by the higher layer protocols and makes use of the Checksum Generator on the Sender side and Checksum Checker on the Receiver side.
Examples:
Input: sent_message = “10101111”, rec_message = “10101101”, block_size = 8Output: ErrorExplaination: Since the 7th bit in the sent_message and the rec_message is different, the final checksum value is not equal to zero denoting that some error has occurred during transmission.
Input: sent_message = “10000101011000111001010011101101”, rec_message = “10000101011000111001010011101101”, block_size = 8Output: No Error
Approach: The given problem can be divided into two following parts:
Generating the Checksum value of the sender’s message can be done using the following steps:Divide the message into the binary strings of the given block size.All the binary strings are added together to get the sum.The One’s Complement of the binary string representing the sum is the required checksum value.
Divide the message into the binary strings of the given block size.
All the binary strings are added together to get the sum.
The One’s Complement of the binary string representing the sum is the required checksum value.
Check if the value of the received message (i.e, rec_message + senders_checksum) is equal to 0.The checksum of the received message can be calculated similarly to the checksum calculated in the above process.If the checksum value is 0, the message is transmitted properly with no errors otherwise, some error has occurred during the transmission.
The checksum of the received message can be calculated similarly to the checksum calculated in the above process.
If the checksum value is 0, the message is transmitted properly with no errors otherwise, some error has occurred during the transmission.
Below is the implementation of the above approach:
C++
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find the One's complement// of the given binary stringstring Ones_complement(string data){ for (int i = 0; i < data.length(); i++) { if (data[i] == '0') data[i] = '1'; else data[i] = '0'; } return data;} // Function to return the checksum value of// the give string when divided in K size blocksstring checkSum(string data, int block_size){ // Check data size is divisible by block_size // Otherwise add '0' front of the data int n = data.length(); if (n % block_size != 0) { int pad_size = block_size - (n % block_size); for (int i = 0; i < pad_size; i++) { data = '0' + data; } } // Binary addition of all blocks with carry string result = ""; // First block of data stored in result variable for (int i = 0; i < block_size; i++) { result += data[i]; } // Loop to calculate the block // wise addition of data for (int i = block_size; i < n; i += block_size) { // Stores the data of the next bloack string next_block = ""; for (int j = i; j < i + block_size; j++) { next_block += data[j]; } // Stores the binary addition of two blocks string additions = ""; int sum = 0, carry = 0; // Loop to calculate the binary addition of // the current two blocls of k size for (int k = block_size - 1; k >= 0; k--) { sum += (next_block[k] - '0') + (result[k] - '0'); carry = sum / 2; if (sum == 0) { additions = '0' + additions; sum = carry; } else if (sum == 1) { additions = '1' + additions; sum = carry; } else if (sum == 2) { additions = '0' + additions; sum = carry; } else { additions = '1' + additions; sum = carry; } } // After binary add of two blocks with carry, // if carry is 1 then apply binary addition string final = ""; if (carry == 1) { for (int l = additions.length() - 1; l >= 0; l--) { if (carry == 0) { final = additions[l] + final; } else if (((additions[l] - '0') + carry) % 2 == 0) { final = "0" + final; carry = 1; } else { final = "1" + final; carry = 0; } } result = final; } else { result = additions; } } // Return One's complements of result value // which represents the required checksum value return Ones_complement(result);} // Function to check if the received message// is same as the senders messagebool checker(string sent_message, string rec_message, int block_size){ // Checksum Value of the senders message string sender_checksum = checkSum(sent_message, block_size); // Checksum value for the receivers message string receiver_checksum = checkSum( rec_message + sender_checksum, block_size); // If receivers checksum value is 0 if (count(receiver_checksum.begin(), receiver_checksum.end(), '0') == block_size) { return true; } else { return false; }} // Driver Codeint main(){ string sent_message = "10000101011000111001010011101101"; string recv_message = "10000101011000111001010011101101"; int block_size = 8; if (checker(sent_message, recv_message, block_size)) { cout << "No Error"; } else { cout << "Error"; } return 0;}
No Error
Time Complexity: O(N)Auxiliary Space: O(block_size)
surinderdawra388
C Programs
C++ Programs
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C Program to read contents of Whole File
Producer Consumer Problem in C
Exit codes in C/C++ with Examples
C program to find the length of a string
Handling multiple clients on server with multithreading using Socket Programming in C/C++
C++ Program for QuickSort
Sorting a Map by value in C++ STL
Shallow Copy and Deep Copy in C++
delete keyword in C++
Passing a function as a parameter in C++
|
[
{
"code": null,
"e": 26726,
"s": 26698,
"text": "\n03 Dec, 2021"
},
{
"code": null,
"e": 27006,
"s": 26726,
"text": "The Checksum is an error detection method that detected errors in data/message while it is transmitted from sender to receiver. This method is used by the higher layer protocols and makes use of the Checksum Generator on the Sender side and Checksum Checker on the Receiver side."
},
{
"code": null,
"e": 27016,
"s": 27006,
"text": "Examples:"
},
{
"code": null,
"e": 27294,
"s": 27016,
"text": "Input: sent_message = “10101111”, rec_message = “10101101”, block_size = 8Output: ErrorExplaination: Since the 7th bit in the sent_message and the rec_message is different, the final checksum value is not equal to zero denoting that some error has occurred during transmission."
},
{
"code": null,
"e": 27433,
"s": 27294,
"text": "Input: sent_message = “10000101011000111001010011101101”, rec_message = “10000101011000111001010011101101”, block_size = 8Output: No Error"
},
{
"code": null,
"e": 27502,
"s": 27433,
"text": "Approach: The given problem can be divided into two following parts:"
},
{
"code": null,
"e": 27813,
"s": 27502,
"text": "Generating the Checksum value of the sender’s message can be done using the following steps:Divide the message into the binary strings of the given block size.All the binary strings are added together to get the sum.The One’s Complement of the binary string representing the sum is the required checksum value."
},
{
"code": null,
"e": 27881,
"s": 27813,
"text": "Divide the message into the binary strings of the given block size."
},
{
"code": null,
"e": 27939,
"s": 27881,
"text": "All the binary strings are added together to get the sum."
},
{
"code": null,
"e": 28034,
"s": 27939,
"text": "The One’s Complement of the binary string representing the sum is the required checksum value."
},
{
"code": null,
"e": 28381,
"s": 28034,
"text": "Check if the value of the received message (i.e, rec_message + senders_checksum) is equal to 0.The checksum of the received message can be calculated similarly to the checksum calculated in the above process.If the checksum value is 0, the message is transmitted properly with no errors otherwise, some error has occurred during the transmission."
},
{
"code": null,
"e": 28495,
"s": 28381,
"text": "The checksum of the received message can be calculated similarly to the checksum calculated in the above process."
},
{
"code": null,
"e": 28634,
"s": 28495,
"text": "If the checksum value is 0, the message is transmitted properly with no errors otherwise, some error has occurred during the transmission."
},
{
"code": null,
"e": 28686,
"s": 28634,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28690,
"s": 28686,
"text": "C++"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to find the One's complement// of the given binary stringstring Ones_complement(string data){ for (int i = 0; i < data.length(); i++) { if (data[i] == '0') data[i] = '1'; else data[i] = '0'; } return data;} // Function to return the checksum value of// the give string when divided in K size blocksstring checkSum(string data, int block_size){ // Check data size is divisible by block_size // Otherwise add '0' front of the data int n = data.length(); if (n % block_size != 0) { int pad_size = block_size - (n % block_size); for (int i = 0; i < pad_size; i++) { data = '0' + data; } } // Binary addition of all blocks with carry string result = \"\"; // First block of data stored in result variable for (int i = 0; i < block_size; i++) { result += data[i]; } // Loop to calculate the block // wise addition of data for (int i = block_size; i < n; i += block_size) { // Stores the data of the next bloack string next_block = \"\"; for (int j = i; j < i + block_size; j++) { next_block += data[j]; } // Stores the binary addition of two blocks string additions = \"\"; int sum = 0, carry = 0; // Loop to calculate the binary addition of // the current two blocls of k size for (int k = block_size - 1; k >= 0; k--) { sum += (next_block[k] - '0') + (result[k] - '0'); carry = sum / 2; if (sum == 0) { additions = '0' + additions; sum = carry; } else if (sum == 1) { additions = '1' + additions; sum = carry; } else if (sum == 2) { additions = '0' + additions; sum = carry; } else { additions = '1' + additions; sum = carry; } } // After binary add of two blocks with carry, // if carry is 1 then apply binary addition string final = \"\"; if (carry == 1) { for (int l = additions.length() - 1; l >= 0; l--) { if (carry == 0) { final = additions[l] + final; } else if (((additions[l] - '0') + carry) % 2 == 0) { final = \"0\" + final; carry = 1; } else { final = \"1\" + final; carry = 0; } } result = final; } else { result = additions; } } // Return One's complements of result value // which represents the required checksum value return Ones_complement(result);} // Function to check if the received message// is same as the senders messagebool checker(string sent_message, string rec_message, int block_size){ // Checksum Value of the senders message string sender_checksum = checkSum(sent_message, block_size); // Checksum value for the receivers message string receiver_checksum = checkSum( rec_message + sender_checksum, block_size); // If receivers checksum value is 0 if (count(receiver_checksum.begin(), receiver_checksum.end(), '0') == block_size) { return true; } else { return false; }} // Driver Codeint main(){ string sent_message = \"10000101011000111001010011101101\"; string recv_message = \"10000101011000111001010011101101\"; int block_size = 8; if (checker(sent_message, recv_message, block_size)) { cout << \"No Error\"; } else { cout << \"Error\"; } return 0;}",
"e": 32639,
"s": 28690,
"text": null
},
{
"code": null,
"e": 32648,
"s": 32639,
"text": "No Error"
},
{
"code": null,
"e": 32700,
"s": 32648,
"text": "Time Complexity: O(N)Auxiliary Space: O(block_size)"
},
{
"code": null,
"e": 32717,
"s": 32700,
"text": "surinderdawra388"
},
{
"code": null,
"e": 32728,
"s": 32717,
"text": "C Programs"
},
{
"code": null,
"e": 32741,
"s": 32728,
"text": "C++ Programs"
},
{
"code": null,
"e": 32759,
"s": 32741,
"text": "Computer Networks"
},
{
"code": null,
"e": 32777,
"s": 32759,
"text": "Computer Networks"
},
{
"code": null,
"e": 32875,
"s": 32777,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32916,
"s": 32875,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 32947,
"s": 32916,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 32981,
"s": 32947,
"text": "Exit codes in C/C++ with Examples"
},
{
"code": null,
"e": 33022,
"s": 32981,
"text": "C program to find the length of a string"
},
{
"code": null,
"e": 33112,
"s": 33022,
"text": "Handling multiple clients on server with multithreading using Socket Programming in C/C++"
},
{
"code": null,
"e": 33138,
"s": 33112,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 33172,
"s": 33138,
"text": "Sorting a Map by value in C++ STL"
},
{
"code": null,
"e": 33206,
"s": 33172,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 33228,
"s": 33206,
"text": "delete keyword in C++"
}
] |
Deep Linking in Android with Example - GeeksforGeeks
|
04 Feb, 2021
Deep Linking is one of the most important features that is used by various apps to gather data inside their apps in the form of a URL link. So it becomes helpful for the users from other apps to easily share the data with different apps. In this article, we will take a look at the implementation of deep links in our Android App.
A deep link is a URL link that is generated, when anyone clicks on that link our app will be open with a specific activity or a screen. Using this URL we can send a message to our app with parameters. In WhatsApp, we can generate a deep link to send a message to a phone number with some message in it. Deep links are used to open your app’s specific screen with a URL link.
We will be building a simple application in which we will be creating a deep link and on clicking on that link we will be passing our message to our app and display that message in a text view. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the 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: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code 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" android:orientation="vertical" android:weightSum="5" tools:context=".MainActivity"> <!--text view for displaying welcome message--> <TextView android:id="@+id/idTVWelcome" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_centerInParent="true" android:padding="10dp" android:text="Welcome to " android:textAlignment="center" android:textAllCaps="false" android:textColor="@color/purple_500" android:textSize="30sp" /> <!--text view for displaying the organization name from the link which we have generated--> <TextView android:id="@+id/idTVMessage" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_below="@id/idTVWelcome" android:text="Organization Name" android:textAlignment="center" android:textAllCaps="false" android:textColor="@color/purple_500" android:textSize="30sp" android:textStyle="bold" /> </RelativeLayout>
Step 3: Working with the AndroidManifest.xml file
Navigate to the app > AndroidManifest.xml and add the below code to it. As we are creating a deep link for our MainActivity.java file so we have to add this code in the MainActivity part. Below is the code which is to be added in the AndroidManifext.xml file. Comments are added in the code to get to know in more detail.
XML
<!--as we want to open main activity from our link so we are specifying only in main activity or we can specify that in different activity as well on below line we are adding intent filter to our MainActivity--><intent-filter> <!--below line is to set the action to our intent to view--> <action android:name="android.intent.action.VIEW" /> <!--on below line we are adding a default category to our intent--> <category android:name="android.intent.category.DEFAULT" /> <!--on below line we are adding a category to make our app browsable--> <category android:name="android.intent.category.BROWSABLE" /> <!--on below line we are specifying the host name and the scheme type from which we will be calling our app--> <data android:host="www.chaitanyamunje.com" android:scheme="https" /></intent-filter> <!--below is the same filter as above just the scheme is changed to http --><!--so we can open our app with the url starting with https and http as well--><intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:host="www.chaitanyamunje.com" android:scheme="http" /></intent-filter>
Below is the complete code for the AndroidManifest.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.deeplinks"> <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/Theme.DeepLinks"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <!--as we want to open main activity from our link so we are specifying only in main activity or we can specify that in different activity as well--> <!--on below line we are adding intent filter to our MainActivity--> <intent-filter> <!--below line is to set the action to our intent to view--> <action android:name="android.intent.action.VIEW" /> <!--on below line we are adding a default category to our intent--> <category android:name="android.intent.category.DEFAULT" /> <!--on below line we are adding a category to make our app browsable--> <category android:name="android.intent.category.BROWSABLE" /> <!--on below line we are specifying the host name and the scheme type from which we will be calling our app--> <data android:host="www.chaitanyamunje.com" android:scheme="https" /> </intent-filter> <!--below is the same filter as above just the scheme is changed to http --> <!--so we can open our app with the url starting with https and http as well--> <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" /> <category android:name="android.intent.category.BROWSABLE" /> <data android:host="www.chaitanyamunje.com" android:scheme="http" /> </intent-filter> </activity> </application></manifest>
Step 4: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
package com.example.deeplinks; import android.net.Uri;import android.os.Bundle;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.util.List; public class MainActivity extends AppCompatActivity { // creating a variable for our text view private TextView messageTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variable messageTV = findViewById(R.id.idTVMessage); // getting the data from our // intent in our uri. Uri uri = getIntent().getData(); // checking if the uri is null or not. if (uri != null) { // if the uri is not null then we are getting the // path segments and storing it in list. List<String> parameters = uri.getPathSegments(); // after that we are extracting string from that parameters. String param = parameters.get(parameters.size() - 1); // on below line we are setting // that string to our text view // which we got as params. messageTV.setText(param); } }}
Now we have added the URL in our AndroidManifest file as https://www.chaitanyamunje.com/hello/GeeksForGeeks. The URL from which we will send messages to our MainActivity.java file. In the above URL the “https” is our scheme, “www.chaitanyamunje.com” is our hostname and “hello” is our first parameter and “GeeksForGeeks” is a second parameter which we are going to show in our app as an organization name. You can change your parameters according to your requirement. Now run your app and see the output of the app.
As you have run your app you will get to see the text as Organization name, now close the application and click on the link which is shown above from the device in which your application is installed. After clicking on that link a pop-up message will be displayed to select the application. Inside that pop-up message select, your application, and your app will be open. We are passing a message as “GeeksForGeeks” which will be displayed in the place of the Organization name.
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?
Broadcast Receiver in Android With Example
Resource Raw Folder in Android Studio
CardView in Android With Example
Android RecyclerView in Kotlin
Arrays in Java
Split() String method in Java with examples
For-each loop in Java
Stream In Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 25871,
"s": 25843,
"text": "\n04 Feb, 2021"
},
{
"code": null,
"e": 26203,
"s": 25871,
"text": "Deep Linking is one of the most important features that is used by various apps to gather data inside their apps in the form of a URL link. So it becomes helpful for the users from other apps to easily share the data with different apps. In this article, we will take a look at the implementation of deep links in our Android App. "
},
{
"code": null,
"e": 26581,
"s": 26203,
"text": "A deep link is a URL link that is generated, when anyone clicks on that link our app will be open with a specific activity or a screen. Using this URL we can send a message to our app with parameters. In WhatsApp, we can generate a deep link to send a message to a phone number with some message in it. Deep links are used to open your app’s specific screen with a URL link. "
},
{
"code": null,
"e": 26942,
"s": 26581,
"text": "We will be building a simple application in which we will be creating a deep link and on clicking on that link we will be passing our message to our app and display that message in a text view. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 26971,
"s": 26942,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 27133,
"s": 26971,
"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": 27181,
"s": 27133,
"text": "Step 2: Working with the activity_main.xml file"
},
{
"code": null,
"e": 27324,
"s": 27181,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 27328,
"s": 27324,
"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\" android:orientation=\"vertical\" android:weightSum=\"5\" tools:context=\".MainActivity\"> <!--text view for displaying welcome message--> <TextView android:id=\"@+id/idTVWelcome\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_centerInParent=\"true\" android:padding=\"10dp\" android:text=\"Welcome to \" android:textAlignment=\"center\" android:textAllCaps=\"false\" android:textColor=\"@color/purple_500\" android:textSize=\"30sp\" /> <!--text view for displaying the organization name from the link which we have generated--> <TextView android:id=\"@+id/idTVMessage\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/idTVWelcome\" android:text=\"Organization Name\" android:textAlignment=\"center\" android:textAllCaps=\"false\" android:textColor=\"@color/purple_500\" android:textSize=\"30sp\" android:textStyle=\"bold\" /> </RelativeLayout>",
"e": 28651,
"s": 27328,
"text": null
},
{
"code": null,
"e": 28701,
"s": 28651,
"text": "Step 3: Working with the AndroidManifest.xml file"
},
{
"code": null,
"e": 29024,
"s": 28701,
"text": "Navigate to the app > AndroidManifest.xml and add the below code to it. As we are creating a deep link for our MainActivity.java file so we have to add this code in the MainActivity part. Below is the code which is to be added in the AndroidManifext.xml file. Comments are added in the code to get to know in more detail. "
},
{
"code": null,
"e": 29028,
"s": 29024,
"text": "XML"
},
{
"code": "<!--as we want to open main activity from our link so we are specifying only in main activity or we can specify that in different activity as well on below line we are adding intent filter to our MainActivity--><intent-filter> <!--below line is to set the action to our intent to view--> <action android:name=\"android.intent.action.VIEW\" /> <!--on below line we are adding a default category to our intent--> <category android:name=\"android.intent.category.DEFAULT\" /> <!--on below line we are adding a category to make our app browsable--> <category android:name=\"android.intent.category.BROWSABLE\" /> <!--on below line we are specifying the host name and the scheme type from which we will be calling our app--> <data android:host=\"www.chaitanyamunje.com\" android:scheme=\"https\" /></intent-filter> <!--below is the same filter as above just the scheme is changed to http --><!--so we can open our app with the url starting with https and http as well--><intent-filter> <action android:name=\"android.intent.action.VIEW\" /> <category android:name=\"android.intent.category.DEFAULT\" /> <category android:name=\"android.intent.category.BROWSABLE\" /> <data android:host=\"www.chaitanyamunje.com\" android:scheme=\"http\" /></intent-filter>",
"e": 30320,
"s": 29028,
"text": null
},
{
"code": null,
"e": 30381,
"s": 30320,
"text": "Below is the complete code for the AndroidManifest.xml file."
},
{
"code": null,
"e": 30385,
"s": 30381,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.deeplinks\"> <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/Theme.DeepLinks\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> <!--as we want to open main activity from our link so we are specifying only in main activity or we can specify that in different activity as well--> <!--on below line we are adding intent filter to our MainActivity--> <intent-filter> <!--below line is to set the action to our intent to view--> <action android:name=\"android.intent.action.VIEW\" /> <!--on below line we are adding a default category to our intent--> <category android:name=\"android.intent.category.DEFAULT\" /> <!--on below line we are adding a category to make our app browsable--> <category android:name=\"android.intent.category.BROWSABLE\" /> <!--on below line we are specifying the host name and the scheme type from which we will be calling our app--> <data android:host=\"www.chaitanyamunje.com\" android:scheme=\"https\" /> </intent-filter> <!--below is the same filter as above just the scheme is changed to http --> <!--so we can open our app with the url starting with https and http as well--> <intent-filter> <action android:name=\"android.intent.action.VIEW\" /> <category android:name=\"android.intent.category.DEFAULT\" /> <category android:name=\"android.intent.category.BROWSABLE\" /> <data android:host=\"www.chaitanyamunje.com\" android:scheme=\"http\" /> </intent-filter> </activity> </application></manifest>",
"e": 32723,
"s": 30385,
"text": null
},
{
"code": null,
"e": 32771,
"s": 32723,
"text": "Step 4: Working with the MainActivity.java file"
},
{
"code": null,
"e": 32961,
"s": 32771,
"text": "Go to the MainActivity.java file and refer to the following code. 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": 32966,
"s": 32961,
"text": "Java"
},
{
"code": "package com.example.deeplinks; import android.net.Uri;import android.os.Bundle;import android.widget.TextView; import androidx.appcompat.app.AppCompatActivity; import java.util.List; public class MainActivity extends AppCompatActivity { // creating a variable for our text view private TextView messageTV; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variable messageTV = findViewById(R.id.idTVMessage); // getting the data from our // intent in our uri. Uri uri = getIntent().getData(); // checking if the uri is null or not. if (uri != null) { // if the uri is not null then we are getting the // path segments and storing it in list. List<String> parameters = uri.getPathSegments(); // after that we are extracting string from that parameters. String param = parameters.get(parameters.size() - 1); // on below line we are setting // that string to our text view // which we got as params. messageTV.setText(param); } }}",
"e": 34254,
"s": 32966,
"text": null
},
{
"code": null,
"e": 34770,
"s": 34254,
"text": "Now we have added the URL in our AndroidManifest file as https://www.chaitanyamunje.com/hello/GeeksForGeeks. The URL from which we will send messages to our MainActivity.java file. In the above URL the “https” is our scheme, “www.chaitanyamunje.com” is our hostname and “hello” is our first parameter and “GeeksForGeeks” is a second parameter which we are going to show in our app as an organization name. You can change your parameters according to your requirement. Now run your app and see the output of the app."
},
{
"code": null,
"e": 35248,
"s": 34770,
"text": "As you have run your app you will get to see the text as Organization name, now close the application and click on the link which is shown above from the device in which your application is installed. After clicking on that link a pop-up message will be displayed to select the application. Inside that pop-up message select, your application, and your app will be open. We are passing a message as “GeeksForGeeks” which will be displayed in the place of the Organization name."
},
{
"code": null,
"e": 35256,
"s": 35248,
"text": "android"
},
{
"code": null,
"e": 35280,
"s": 35256,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 35288,
"s": 35280,
"text": "Android"
},
{
"code": null,
"e": 35293,
"s": 35288,
"text": "Java"
},
{
"code": null,
"e": 35312,
"s": 35293,
"text": "Technical Scripter"
},
{
"code": null,
"e": 35317,
"s": 35312,
"text": "Java"
},
{
"code": null,
"e": 35325,
"s": 35317,
"text": "Android"
},
{
"code": null,
"e": 35423,
"s": 35325,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35481,
"s": 35423,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 35524,
"s": 35481,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 35562,
"s": 35524,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 35595,
"s": 35562,
"text": "CardView in Android With Example"
},
{
"code": null,
"e": 35626,
"s": 35595,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 35641,
"s": 35626,
"text": "Arrays in Java"
},
{
"code": null,
"e": 35685,
"s": 35641,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 35707,
"s": 35685,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 35722,
"s": 35707,
"text": "Stream In Java"
}
] |
Build an Application for Screen Rotation Using Python - GeeksforGeeks
|
30 Sep, 2021
In this article, we are going to write a python script for screen rotation and implement it with GUI.
The display can be modified to four orientations using some methods from the rotatescreen module, it is a small Python package for rotating the screen in a system.
pip install rotate-screen
Step 1) Import the required module in the python script.
Python3
# Import required moduleimport rotatescreen
Step 2) Create an object of rotatescreen.get_primary_display() to access the main screen of the system.
Python3
# Accessing the main screenrotate_screen = rotatescreen.get_primary_display()
Step 3) Now use various methods to rotate the screen.
set_landscape(), Rotate Up
set_portrait_flipped(), Rotate Left
set_landscape_flipped(), Rotate Down
set_portrait(), Rotate Right
Python3
# Methods to change orientation # for landscaperotate_screen.set_landscape() # portrait at leftrotate_screen.set_portrait_flipped() # landscape at downrotate_screen.set_landscape_flipped() # portrait at rightrotate_screen.set_portrait()
Below is the complete program of the above approach along with GUI implementation.
Python3
# Import required modulesfrom tkinter import *import rotatescreen # User defined function# for rotating screendef Screen_rotation(temp): screen = rotatescreen.get_primary_display() if temp == "up": screen.set_landscape() elif temp == "right": screen.set_portrait_flipped() elif temp == "down": screen.set_landscape_flipped() elif temp == "left": screen.set_portrait() # Creating tkinter objectmaster = Tk()master.geometry("100x100")master.title("Screen Rotation")master.configure(bg='light grey') # Variable classes in tkinterresult = StringVar() # Creating buttons to change orientationButton(master, text="Up", command=lambda: Screen_rotation( "up"), bg="white").grid(row=0, column=3)Button(master, text="Right", command=lambda: Screen_rotation( "right"), bg="white").grid(row=1, column=6)Button(master, text="Left", command=lambda: Screen_rotation( "left"), bg="white").grid(row=1, column=2)Button(master, text="Down", command=lambda: Screen_rotation( "down"), bg="white").grid(row=3, column=3) mainloop() # this code belongs to Satyam kumar (ksatyam858)
Output:
abhigoya
saurabh1990aror
Python Tkinter-exercises
Python-tkinter
python-utility
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 Convert Python Dictionary To JSON?
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n30 Sep, 2021"
},
{
"code": null,
"e": 25750,
"s": 25647,
"text": "In this article, we are going to write a python script for screen rotation and implement it with GUI. "
},
{
"code": null,
"e": 25914,
"s": 25750,
"text": "The display can be modified to four orientations using some methods from the rotatescreen module, it is a small Python package for rotating the screen in a system."
},
{
"code": null,
"e": 25940,
"s": 25914,
"text": "pip install rotate-screen"
},
{
"code": null,
"e": 25997,
"s": 25940,
"text": "Step 1) Import the required module in the python script."
},
{
"code": null,
"e": 26005,
"s": 25997,
"text": "Python3"
},
{
"code": "# Import required moduleimport rotatescreen",
"e": 26049,
"s": 26005,
"text": null
},
{
"code": null,
"e": 26155,
"s": 26049,
"text": " Step 2) Create an object of rotatescreen.get_primary_display() to access the main screen of the system. "
},
{
"code": null,
"e": 26163,
"s": 26155,
"text": "Python3"
},
{
"code": "# Accessing the main screenrotate_screen = rotatescreen.get_primary_display()",
"e": 26241,
"s": 26163,
"text": null
},
{
"code": null,
"e": 26296,
"s": 26241,
"text": " Step 3) Now use various methods to rotate the screen."
},
{
"code": null,
"e": 26323,
"s": 26296,
"text": "set_landscape(), Rotate Up"
},
{
"code": null,
"e": 26359,
"s": 26323,
"text": "set_portrait_flipped(), Rotate Left"
},
{
"code": null,
"e": 26396,
"s": 26359,
"text": "set_landscape_flipped(), Rotate Down"
},
{
"code": null,
"e": 26425,
"s": 26396,
"text": "set_portrait(), Rotate Right"
},
{
"code": null,
"e": 26433,
"s": 26425,
"text": "Python3"
},
{
"code": "# Methods to change orientation # for landscaperotate_screen.set_landscape() # portrait at leftrotate_screen.set_portrait_flipped() # landscape at downrotate_screen.set_landscape_flipped() # portrait at rightrotate_screen.set_portrait()",
"e": 26670,
"s": 26433,
"text": null
},
{
"code": null,
"e": 26754,
"s": 26670,
"text": " Below is the complete program of the above approach along with GUI implementation."
},
{
"code": null,
"e": 26762,
"s": 26754,
"text": "Python3"
},
{
"code": "# Import required modulesfrom tkinter import *import rotatescreen # User defined function# for rotating screendef Screen_rotation(temp): screen = rotatescreen.get_primary_display() if temp == \"up\": screen.set_landscape() elif temp == \"right\": screen.set_portrait_flipped() elif temp == \"down\": screen.set_landscape_flipped() elif temp == \"left\": screen.set_portrait() # Creating tkinter objectmaster = Tk()master.geometry(\"100x100\")master.title(\"Screen Rotation\")master.configure(bg='light grey') # Variable classes in tkinterresult = StringVar() # Creating buttons to change orientationButton(master, text=\"Up\", command=lambda: Screen_rotation( \"up\"), bg=\"white\").grid(row=0, column=3)Button(master, text=\"Right\", command=lambda: Screen_rotation( \"right\"), bg=\"white\").grid(row=1, column=6)Button(master, text=\"Left\", command=lambda: Screen_rotation( \"left\"), bg=\"white\").grid(row=1, column=2)Button(master, text=\"Down\", command=lambda: Screen_rotation( \"down\"), bg=\"white\").grid(row=3, column=3) mainloop() # this code belongs to Satyam kumar (ksatyam858)",
"e": 27880,
"s": 26762,
"text": null
},
{
"code": null,
"e": 27888,
"s": 27880,
"text": "Output:"
},
{
"code": null,
"e": 27897,
"s": 27888,
"text": "abhigoya"
},
{
"code": null,
"e": 27913,
"s": 27897,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 27938,
"s": 27913,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 27953,
"s": 27938,
"text": "Python-tkinter"
},
{
"code": null,
"e": 27968,
"s": 27953,
"text": "python-utility"
},
{
"code": null,
"e": 27975,
"s": 27968,
"text": "Python"
},
{
"code": null,
"e": 28073,
"s": 27975,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28105,
"s": 28073,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28147,
"s": 28105,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28189,
"s": 28147,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28245,
"s": 28189,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28272,
"s": 28245,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28303,
"s": 28272,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28332,
"s": 28303,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28354,
"s": 28332,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 28390,
"s": 28354,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Compute Log Normal Probability Density in R Programming - dlnorm() Function - GeeksforGeeks
|
25 Jun, 2020
dlnorm() function in R Language is used to compute the log normal value of the probability density function. It also creates a plot of the log normal density.
Syntax: dlnorm(vec)
Parameters:vec: x-values for normal density
Example 1:
# R program to compute# log normal probability density # Creating x-values for densityx <- seq(1, 10, by = 1) # Calling dlnorm() functiony <- dlnorm(x)y
Output:
[1] 0.398942280 0.156874019 0.072728256 0.038153457 0.021850715 0.013354538
[7] 0.008581626 0.005739296 0.003965747 0.002815902
Example 2:
# R program to compute# log normal probability density # Creating x-values for densityx <- seq(1, 10, by = 0.1) # Calling dlnorm() functiony <- dlnorm(x) # Plot a graphplot(y)
Output:
R-Statistics
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 ?
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
How to change Row Names of DataFrame in R ?
Printing Output of an R Program
Remove rows with NA in one column of R DataFrame
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?
|
[
{
"code": null,
"e": 25394,
"s": 25366,
"text": "\n25 Jun, 2020"
},
{
"code": null,
"e": 25553,
"s": 25394,
"text": "dlnorm() function in R Language is used to compute the log normal value of the probability density function. It also creates a plot of the log normal density."
},
{
"code": null,
"e": 25573,
"s": 25553,
"text": "Syntax: dlnorm(vec)"
},
{
"code": null,
"e": 25617,
"s": 25573,
"text": "Parameters:vec: x-values for normal density"
},
{
"code": null,
"e": 25628,
"s": 25617,
"text": "Example 1:"
},
{
"code": "# R program to compute# log normal probability density # Creating x-values for densityx <- seq(1, 10, by = 1) # Calling dlnorm() functiony <- dlnorm(x)y",
"e": 25783,
"s": 25628,
"text": null
},
{
"code": null,
"e": 25791,
"s": 25783,
"text": "Output:"
},
{
"code": null,
"e": 25922,
"s": 25791,
"text": " [1] 0.398942280 0.156874019 0.072728256 0.038153457 0.021850715 0.013354538\n [7] 0.008581626 0.005739296 0.003965747 0.002815902\n"
},
{
"code": null,
"e": 25933,
"s": 25922,
"text": "Example 2:"
},
{
"code": "# R program to compute# log normal probability density # Creating x-values for densityx <- seq(1, 10, by = 0.1) # Calling dlnorm() functiony <- dlnorm(x) # Plot a graphplot(y)",
"e": 26112,
"s": 25933,
"text": null
},
{
"code": null,
"e": 26120,
"s": 26112,
"text": "Output:"
},
{
"code": null,
"e": 26133,
"s": 26120,
"text": "R-Statistics"
},
{
"code": null,
"e": 26144,
"s": 26133,
"text": "R Language"
},
{
"code": null,
"e": 26242,
"s": 26144,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26251,
"s": 26242,
"text": "Comments"
},
{
"code": null,
"e": 26264,
"s": 26251,
"text": "Old Comments"
},
{
"code": null,
"e": 26322,
"s": 26264,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 26374,
"s": 26322,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 26406,
"s": 26374,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 26458,
"s": 26406,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26502,
"s": 26458,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 26534,
"s": 26502,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 26583,
"s": 26534,
"text": "Remove rows with NA in one column of R DataFrame"
},
{
"code": null,
"e": 26621,
"s": 26583,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26656,
"s": 26621,
"text": "Group by function in R using Dplyr"
}
] |
Boundary Root to Leaf Path traversal of a Binary Tree - GeeksforGeeks
|
15 Feb, 2022
Given a Binary Tree, the task is to print all Root to Leaf path of this tree in Boundary Root to Leaf path traversal.
Boundary Root to Leaf Path Traversal: In this traversal, the first Root to Leaf path(Left boundary) is printed first, followed by the last Root to Leaf path (Right boundary) in Reverse order. Then the process is repeated for the second and second-last Root to Leaf path, till the all Root to Leaf path has been printed.
Examples:
Input:
1
/ \
15 13
/ / \
11 7 29
\ /
2 3
Output: 1 15 11
3 29 13 1
1 13 7 2
Explanation:
First of all print first path from Root to the Leaf
which is 1 15 11
Then, print the last path from the Leaf to Root
which is 3 29 13 1
Then, print the second path from Root to Leaf
which is 1 13 7 2
Input:
7
/ \
23 41
/ \ \
31 16 3
/ \ \ /
2 5 17 11
/
23
Output: 7 23 31 2
11 3 41 7
7 23 31 5
23 17 16 23 7
Approach: In order to print paths in Boundary Root to Leaf Path Traversal,
We first need to make Preorder Traversal of the binary tree to get the all node values of particular path.
Here an array is used to store the path of the tree while doing the Preorder traversal then store this path into matrix.
Then for each path, print the matrix in first row (Left to Right) then last row (Right to Left) and so on.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to print the// path in Boundary Root to Leaf// Path Traversal. #include <bits/stdc++.h>using namespace std; // Structure of tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to// create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);}// Function to calculate the length// of longest path of the treeint lengthOfLongestPath(struct Node* node){ // Base Case if (node == NULL) return 0; // Recursive call to calculate the length // of longest path int left = lengthOfLongestPath(node->left); int right = lengthOfLongestPath(node->right); return 1 + (left > right ? left : right);} // Function to copy the complete// path in a matrixvoid copyPath(int* path, int index, int** mtrx, int row){ // Loop to copy the path for (int i = 0; i < index; i++) { mtrx[row][i] = path[i]; }} // Function to store all path// one by one in matrixvoid storePath(struct Node* node, int* path, int index, int** mtrx, int& row){ // Base condition if (node == NULL) { return; } // Inserting the current node // into the current path path[index] = node->key; // Recursive call for // the left sub tree storePath(node->left, path, index + 1, mtrx, row); // Recursive call for // the right sub tree storePath(node->right, path, index + 1, mtrx, row); // Condition to check that current // node is a leaf node or not if (node->left == NULL && node->right == NULL) { // Incrementation for changing // row row = row + 1; // Function call for copying // the path copyPath(path, index + 1, mtrx, row); }} // Function to calculate// total pathint totalPath(Node* node){ static int count = 0; if (node == NULL) { return count; } if (node->left == NULL && node->right == NULL) { return count + 1; } count = totalPath(node->left); return totalPath(node->right);} // Function for Clockwise Spiral Traversal// of Binary Treevoid traverse_matrix(int** mtrx, int height, int width){ int j = 0, k1 = 0, k2 = 0; int k3 = height - 1; int k4 = width - 1; for (int round = 0; round < height/2; round++) { for (j = k2; j < width; j++) { // Only print those values which // are not MAX_INTEGER if (mtrx[k1][j] != INT_MAX) { cout << mtrx[k1][j] << " "; } } cout << endl; k2 = 0; k1++; for (j = k4; j >= 0; j--) { // Only print those values which // are not MAX_INTEGER if (mtrx[k3][j] != INT_MAX) { cout << mtrx[k3][j] << " "; } } cout << endl; k4 = width - 1; k3--; } // Condition (one row may be left // traversing) // If number of rows in matrix are odd if (height % 2 != 0) { for (j = k2; j < width; j++) { // Only print those values which are // not MAX_INTEGER if (mtrx[k1][j] != INT_MAX) { cout << mtrx[k1][j] << " "; } } }} // Function to print all the paths// in Boundary Root to Leaf// Path Traversalvoid PrintPath(Node* node){ // Calculate the length of // longest path of the tree int max_len = lengthOfLongestPath(node); // Calculate total path int total_path = totalPath(node); // Array to store path int* path = new int[max_len]; memset(path, 0, sizeof(path)); // Use double pointer to create // 2D array which will contain // all path of the tree int** mtrx = new int*[total_path]; // Initialize width for each row // of matrix for (int i = 0; i < total_path; i++) { mtrx[i] = new int[max_len]; } // Initialize complete matrix with // MAX INTEGER(purpose garbage) for (int i = 0; i < total_path; i++) { for (int j = 0; j < max_len; j++) { mtrx[i][j] = INT_MAX; } } int row = -1; storePath(node, path, 0, mtrx, row); // Print the circular clockwise spiral // traversal of the tree traverse_matrix(mtrx, total_path, max_len); // Release extra memory // allocated for matrix free(mtrx);} // Driver Codeint main(){ /* 10 / \ 13 11 / \ 19 23 / \ / \ 21 29 43 15 / 7 */ // Create Binary Tree as shown Node* root = newNode(10); root->left = newNode(13); root->right = newNode(11); root->right->left = newNode(19); root->right->right = newNode(23); root->right->left->left = newNode(21); root->right->left->right = newNode(29); root->right->right->left = newNode(43); root->right->right->right = newNode(15); root->right->right->right->left = newNode(7); // Function Call PrintPath(root); return 0;}
// Java implementation to print the // path in Boundary Root to Leaf // Path Traversal.import java.util.*; class GFG{ static int row;static int count = 0; // Structure of tree nodestatic class Node{ int key; Node left, right;}; // Utility function to// create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function to calculate the length// of longest path of the treestatic int lengthOfLongestPath(Node node){ // Base Case if (node == null) return 0; // Recursive call to calculate the // length of longest path int left = lengthOfLongestPath(node.left); int right = lengthOfLongestPath(node.right); return 1 + (left > right ? left : right);} // Function to copy the complete// path in a matrixstatic void copyPath(int[] path, int index, int[][] mtrx, int r){ // Loop to copy the path for(int i = 0; i < index; i++) { mtrx[r][i] = path[i]; }} // Function to store all path// one by one in matrixstatic void storePath(Node node, int[] path, int index, int[][] mtrx){ // Base condition if (node == null) { return; } // Inserting the current node // into the current path path[index] = node.key; // Recursive call for // the left sub tree storePath(node.left, path, index + 1, mtrx); // Recursive call for // the right sub tree storePath(node.right, path, index + 1, mtrx); // Condition to check that current // node is a leaf node or not if (node.left == null && node.right == null) { // Incrementation for changing // row row = row + 1; // Function call for copying // the path copyPath(path, index + 1, mtrx, row); }} // Function to calculate// total pathstatic int totalPath(Node node){ if (node == null) { return count; } if (node.left == null && node.right == null) { return count + 1; } count = totalPath(node.left); return totalPath(node.right);} // Function for Clockwise Spiral Traversal// of Binary Treestatic void traverse_matrix(int[][] mtrx, int height, int width){ int j = 0, k1 = 0, k2 = 0; int k3 = height - 1; int k4 = width - 1; for(int round = 0; round < height / 2; round++) { for(j = k2; j < width; j++) { // Only print those values which // are not MAX_INTEGER if (mtrx[k1][j] != Integer.MAX_VALUE) { System.out.print(mtrx[k1][j] + " "); } } System.out.println(); k2 = 0; k1++; for(j = k4; j >= 0; j--) { // Only print those values which // are not MAX_INTEGER if (mtrx[k3][j] != Integer.MAX_VALUE) { System.out.print(mtrx[k3][j] + " "); } } System.out.println(); k4 = width - 1; k3--; } // Condition (one row may be left // traversing) // If number of rows in matrix are odd if (height % 2 != 0) { for(j = k2; j < width; j++) { // Only print those values which are // not MAX_INTEGER if (mtrx[k1][j] != Integer.MAX_VALUE) { System.out.print(mtrx[k1][j] + " "); } } }} // Function to print all the paths// in Boundary Root to Leaf// Path Traversalstatic void PrintPath(Node node){ // Calculate the length of // longest path of the tree int max_len = lengthOfLongestPath(node); // Calculate total path int total_path = totalPath(node); // Array to store path int[] path = new int[max_len]; Arrays.fill(path, 0); // Use double pointer to create // 2D array which will contain // all path of the tree int[][] mtrx = new int[total_path][max_len]; // Initialize complete matrix with // MAX INTEGER(purpose garbage) for(int i = 0; i < total_path; i++) { for(int j = 0; j < max_len; j++) { mtrx[i][j] = Integer.MAX_VALUE; } } row = -1; storePath(node, path, 0, mtrx); // Print the circular clockwise spiral // traversal of the tree traverse_matrix(mtrx, total_path, max_len);} // Driver Codepublic static void main(String[] args){ /* 10 / \ 13 11 / \ 19 23 / \ / \ 21 29 43 15 / 7 */ // Create Binary Tree as shown Node root = newNode(10); root.left = newNode(13); root.right = newNode(11); root.right.left = newNode(19); root.right.right = newNode(23); root.right.left.left = newNode(21); root.right.left.right = newNode(29); root.right.right.left = newNode(43); root.right.right.right = newNode(15); root.right.right.right.left = newNode(7); // Function Call PrintPath(root);}} // This code is contributed by sanjeev2552
# Python3 implementation to print the# path in Boundary Root to Leaf# Path Traversal. # Structure of tree nodeclass Node: def __init__(self, key): self.key = key self.left = None self.right = None row = 0count = 0 # Utility function to# create a new nodedef newNode(key): temp = Node(key) return temp # Function to calculate the length# of longest path of the treedef lengthOfLongestPath(node): # Base Case if (node == None): return 0; # Recursive call to calculate the length # of longest path left = lengthOfLongestPath(node.left); right = lengthOfLongestPath(node.right); return 1 + (left if left > right else right); # Function to copy the complete# path in a matrixdef copyPath(path, index, mtrx, r): # Loop to copy the path for i in range(index): mtrx[r][i] = path[i]; # Function to store all path# one by one in matrixdef storePath(node, path, index, mtrx): global row # Base condition if (node == None): return; # Inserting the current node # into the current path path[index] = node.key; # Recursive call for # the left sub tree storePath(node.left, path, index + 1, mtrx); # Recursive call for # the right sub tree storePath(node.right, path, index + 1, mtrx); # Condition to check that current # node is a leaf node or not if (node.left == None and node.right == None): # Incrementation for changing # row row = row + 1; # Function call for copying # the path copyPath(path, index + 1, mtrx, row); # Function to calculate# total pathdef totalPath(node): global count if (node == None): return count; if (node.left == None and node.right == None): return count + 1; count = totalPath(node.left); return totalPath(node.right); # Function for Clockwise Spiral Traversal# of Binary Treedef traverse_matrix( mtrx, height, width): j = 0 k1 = 0 k2 = 0; k3 = height - 1; k4 = width - 1; for round in range(height//2): for j in range(k2, width): # Only print those values which # are not MAX_INTEGER if (mtrx[k1][j] != 1000000): print(mtrx[k1][j], end=' ') print() k2 = 0; k1 += 1 for j in range(k4, -1, -1): # Only print those values which # are not MAX_INTEGER if (mtrx[k3][j] != 1000000): print(mtrx[k3][j], end=' ') print() k4 = width - 1; k3 -= 1 # Condition (one row may be left # traversing) # If number of rows in matrix are odd if (height % 2 != 0): for j in range(k2, width): # Only print those values which are # not MAX_INTEGER if (mtrx[k1][j] != 1000000): print(mtrx[k1][j], end=' ') # Function to print all the paths# in Boundary Root to Leaf# Path Traversaldef PrintPath(node): global row # Calculate the length of # longest path of the tree max_len = lengthOfLongestPath(node); # Calculate total path total_path = totalPath(node); # Array to store path path = [0 for i in range(max_len)] # Use double pointer to create # 2D array which will contain # all path of the tree mtrx = [[1000000 for j in range(max_len)] for i in range(total_path)] row = -1; storePath(node, path, 0, mtrx); # Print the circular clockwise spiral # traversal of the tree traverse_matrix(mtrx, total_path, max_len); # Driver Codeif __name__=='__main__': ''' 10 / \ 13 11 / \ 19 23 / \ / \ 21 29 43 15 / 7 ''' # Create Binary Tree as shown root = newNode(10); root.left = newNode(13); root.right = newNode(11); root.right.left = newNode(19); root.right.right = newNode(23); root.right.left.left = newNode(21); root.right.left.right = newNode(29); root.right.right.left = newNode(43); root.right.right.right = newNode(15); root.right.right.right.left = newNode(7); # Function Call PrintPath(root); # This code is contributed by pratham76
// C# implementation to print the // path in Boundary Root to Leaf // Path Traversal. using System;using System.Collections; class GFG{ static int row;static int count = 0; // Structure of tree nodepublic class Node{ public int key; public Node left, right;}; // Utility function to// create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function to calculate the length// of longest path of the treestatic int lengthOfLongestPath(Node node){ // Base Case if (node == null) return 0; // Recursive call to calculate the // length of longest path int left = lengthOfLongestPath(node.left); int right = lengthOfLongestPath(node.right); return 1 + (left > right ? left : right);} // Function to copy the complete// path in a matrixstatic void copyPath(int[] path, int index, int[,] mtrx, int r){ // Loop to copy the path for(int i = 0; i < index; i++) { mtrx[r, i] = path[i]; }} // Function to store all path// one by one in matrixstatic void storePath(Node node, int[] path, int index, int[,] mtrx){ // Base condition if (node == null) { return; } // Inserting the current node // into the current path path[index] = node.key; // Recursive call for // the left sub tree storePath(node.left, path, index + 1, mtrx); // Recursive call for // the right sub tree storePath(node.right, path, index + 1, mtrx); // Condition to check that current // node is a leaf node or not if (node.left == null && node.right == null) { // Incrementation for changing // row row = row + 1; // Function call for copying // the path copyPath(path, index + 1, mtrx, row); }} // Function to calculate// total pathstatic int totalPath(Node node){ if (node == null) { return count; } if (node.left == null && node.right == null) { return count + 1; } count = totalPath(node.left); return totalPath(node.right);} // Function for Clockwise Spiral Traversal// of Binary Treestatic void traverse_matrix(int[,] mtrx, int height, int width){ int j = 0, k1 = 0, k2 = 0; int k3 = height - 1; int k4 = width - 1; for(int round = 0; round < height / 2; round++) { for(j = k2; j < width; j++) { // Only print those values which // are not MAX_INTEGER if (mtrx[k1, j] != 10000000) { Console.Write(mtrx[k1, j] + " "); } } Console.WriteLine(); k2 = 0; k1++; for(j = k4; j >= 0; j--) { // Only print those values which // are not MAX_INTEGER if (mtrx[k3, j] != 10000000) { Console.Write(mtrx[k3, j] + " "); } } Console.WriteLine(); k4 = width - 1; k3--; } // Condition (one row may be left // traversing) // If number of rows in matrix are odd if (height % 2 != 0) { for(j = k2; j < width; j++) { // Only print those values which are // not MAX_INTEGER if (mtrx[k1, j] != 10000000) { Console.Write(mtrx[k1, j] + " "); } } }} // Function to print all the paths// in Boundary Root to Leaf// Path Traversalstatic void PrintPath(Node node){ // Calculate the length of // longest path of the tree int max_len = lengthOfLongestPath(node); // Calculate total path int total_path = totalPath(node); // Array to store path int[] path = new int[max_len]; Array.Fill(path, 0); // Use double pointer to create // 2D array which will contain // all path of the tree int[,] mtrx = new int[total_path, max_len]; // Initialize complete matrix with // MAX INTEGER(purpose garbage) for(int i = 0; i < total_path; i++) { for(int j = 0; j < max_len; j++) { mtrx[i, j] = 10000000; } } row = -1; storePath(node, path, 0, mtrx); // Print the circular clockwise spiral // traversal of the tree traverse_matrix(mtrx, total_path, max_len);} // Driver Codepublic static void Main(string[] args){ /* 10 / \ 13 11 / \ 19 23 / \ / \ 21 29 43 15 / 7 */ // Create Binary Tree as shown Node root = newNode(10); root.left = newNode(13); root.right = newNode(11); root.right.left = newNode(19); root.right.right = newNode(23); root.right.left.left = newNode(21); root.right.left.right = newNode(29); root.right.right.left = newNode(43); root.right.right.right = newNode(15); root.right.right.right.left = newNode(7); // Function Call PrintPath(root);}} // This code is contributed by rutvik_56
<script> // JavaScript implementation to print the // path in Boundary Root to Leaf // Path Traversal. let row; let count = 0; // Structure of tree node class Node { constructor(key) { this.left = null; this.right = null; this.key = key; } } // Utility function to // create a new node function newNode(key) { let temp = new Node(key); return (temp); } // Function to calculate the length // of longest path of the tree function lengthOfLongestPath(node) { // Base Case if (node == null) return 0; // Recursive call to calculate the // length of longest path let left = lengthOfLongestPath(node.left); let right = lengthOfLongestPath(node.right); return 1 + (left > right ? left : right); } // Function to copy the complete // path in a matrix function copyPath(path, index, mtrx, r) { // Loop to copy the path for(let i = 0; i < index; i++) { mtrx[r][i] = path[i]; } } // Function to store all path // one by one in matrix function storePath(node, path, index, mtrx) { // Base condition if (node == null) { return; } // Inserting the current node // into the current path path[index] = node.key; // Recursive call for // the left sub tree storePath(node.left, path, index + 1, mtrx); // Recursive call for // the right sub tree storePath(node.right, path, index + 1, mtrx); // Condition to check that current // node is a leaf node or not if (node.left == null && node.right == null) { // Incrementation for changing // row row = row + 1; // Function call for copying // the path copyPath(path, index + 1, mtrx, row); } } // Function to calculate // total path function totalPath(node) { if (node == null) { return count; } if (node.left == null && node.right == null) { return count + 1; } count = totalPath(node.left); return totalPath(node.right); } // Function for Clockwise Spiral Traversal // of Binary Tree function traverse_matrix(mtrx, height, width) { let j = 0, k1 = 0, k2 = 0; let k3 = height - 1; let k4 = width - 1; for(let round = 0; round < parseInt(height / 2, 10); round++) { for(j = k2; j < width; j++) { // Only print those values which // are not MAX_INTEGER if (mtrx[k1][j] != Number.MAX_VALUE) { document.write(mtrx[k1][j] + " "); } } document.write("</br>"); k2 = 0; k1++; for(j = k4; j >= 0; j--) { // Only print those values which // are not MAX_INTEGER if (mtrx[k3][j] != Number.MAX_VALUE) { document.write(mtrx[k3][j] + " "); } } document.write("</br>"); k4 = width - 1; k3--; } // Condition (one row may be left // traversing) // If number of rows in matrix are odd if (height % 2 != 0) { for(j = k2; j < width; j++) { // Only print those values which are // not MAX_INTEGER if (mtrx[k1][j] != Number.MAX_VALUE) { document.write(mtrx[k1][j] + " "); } } } } // Function to print all the paths // in Boundary Root to Leaf // Path Traversal function PrintPath(node) { // Calculate the length of // longest path of the tree let max_len = lengthOfLongestPath(node); // Calculate total path let total_path = totalPath(node); // Array to store path let path = new Array(max_len); path.fill(0); // Use double pointer to create // 2D array which will contain // all path of the tree let mtrx = new Array(total_path); // Initialize complete matrix with // MAX INTEGER(purpose garbage) for(let i = 0; i < total_path; i++) { mtrx[i] = new Array(max_len); for(let j = 0; j < max_len; j++) { mtrx[i][j] = Number.MAX_VALUE; } } row = -1; storePath(node, path, 0, mtrx); // Print the circular clockwise spiral // traversal of the tree traverse_matrix(mtrx, total_path, max_len); } /* 10 / \ 13 11 / \ 19 23 / \ / \ 21 29 43 15 / 7 */ // Create Binary Tree as shown let root = newNode(10); root.left = newNode(13); root.right = newNode(11); root.right.left = newNode(19); root.right.right = newNode(23); root.right.left.left = newNode(21); root.right.left.right = newNode(29); root.right.right.left = newNode(43); root.right.right.right = newNode(15); root.right.right.right.left = newNode(7); // Function Call PrintPath(root); </script>
10 13
7 15 23 11 10
10 11 19 21
43 23 11 10
10 11 19 29
sanjeev2552
rutvik_56
pratham76
nidhi_biet
divyesh072019
khushboogoyal499
ankita_saini
simmytarika5
Binary Tree
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Introduction to Tree Data Structure
DFS traversal of a tree using recursion
Threaded Binary Tree
Find the node with minimum value in a Binary Search Tree
Find maximum (or minimum) in Binary Tree
Iterative Postorder Traversal | Set 2 (Using One Stack)
Top 50 Tree Coding Problems for Interviews
Iterative Preorder Traversal
Construct Complete Binary Tree from its Linked List Representation
Difference between Min Heap and Max Heap
|
[
{
"code": null,
"e": 24938,
"s": 24910,
"text": "\n15 Feb, 2022"
},
{
"code": null,
"e": 25057,
"s": 24938,
"text": "Given a Binary Tree, the task is to print all Root to Leaf path of this tree in Boundary Root to Leaf path traversal. "
},
{
"code": null,
"e": 25379,
"s": 25057,
"text": "Boundary Root to Leaf Path Traversal: In this traversal, the first Root to Leaf path(Left boundary) is printed first, followed by the last Root to Leaf path (Right boundary) in Reverse order. Then the process is repeated for the second and second-last Root to Leaf path, till the all Root to Leaf path has been printed. "
},
{
"code": null,
"e": 25391,
"s": 25379,
"text": "Examples: "
},
{
"code": null,
"e": 26151,
"s": 25391,
"text": "Input: \n 1\n / \\ \n 15 13 \n / / \\ \n 11 7 29 \n \\ / \n 2 3 \nOutput: 1 15 11\n 3 29 13 1\n 1 13 7 2\n\nExplanation:\nFirst of all print first path from Root to the Leaf \nwhich is 1 15 11\nThen, print the last path from the Leaf to Root\nwhich is 3 29 13 1\nThen, print the second path from Root to Leaf \nwhich is 1 13 7 2\n\nInput:\n 7\n / \\ \n 23 41 \n / \\ \\\n 31 16 3 \n / \\ \\ / \n 2 5 17 11 \n /\n 23 \n\nOutput: 7 23 31 2\n 11 3 41 7\n 7 23 31 5\n 23 17 16 23 7"
},
{
"code": null,
"e": 26228,
"s": 26151,
"text": "Approach: In order to print paths in Boundary Root to Leaf Path Traversal, "
},
{
"code": null,
"e": 26335,
"s": 26228,
"text": "We first need to make Preorder Traversal of the binary tree to get the all node values of particular path."
},
{
"code": null,
"e": 26456,
"s": 26335,
"text": "Here an array is used to store the path of the tree while doing the Preorder traversal then store this path into matrix."
},
{
"code": null,
"e": 26563,
"s": 26456,
"text": "Then for each path, print the matrix in first row (Left to Right) then last row (Right to Left) and so on."
},
{
"code": null,
"e": 26616,
"s": 26563,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26620,
"s": 26616,
"text": "C++"
},
{
"code": null,
"e": 26625,
"s": 26620,
"text": "Java"
},
{
"code": null,
"e": 26633,
"s": 26625,
"text": "Python3"
},
{
"code": null,
"e": 26636,
"s": 26633,
"text": "C#"
},
{
"code": null,
"e": 26647,
"s": 26636,
"text": "Javascript"
},
{
"code": "// C++ implementation to print the// path in Boundary Root to Leaf// Path Traversal. #include <bits/stdc++.h>using namespace std; // Structure of tree nodestruct Node { int key; struct Node *left, *right;}; // Utility function to// create a new nodeNode* newNode(int key){ Node* temp = new Node; temp->key = key; temp->left = temp->right = NULL; return (temp);}// Function to calculate the length// of longest path of the treeint lengthOfLongestPath(struct Node* node){ // Base Case if (node == NULL) return 0; // Recursive call to calculate the length // of longest path int left = lengthOfLongestPath(node->left); int right = lengthOfLongestPath(node->right); return 1 + (left > right ? left : right);} // Function to copy the complete// path in a matrixvoid copyPath(int* path, int index, int** mtrx, int row){ // Loop to copy the path for (int i = 0; i < index; i++) { mtrx[row][i] = path[i]; }} // Function to store all path// one by one in matrixvoid storePath(struct Node* node, int* path, int index, int** mtrx, int& row){ // Base condition if (node == NULL) { return; } // Inserting the current node // into the current path path[index] = node->key; // Recursive call for // the left sub tree storePath(node->left, path, index + 1, mtrx, row); // Recursive call for // the right sub tree storePath(node->right, path, index + 1, mtrx, row); // Condition to check that current // node is a leaf node or not if (node->left == NULL && node->right == NULL) { // Incrementation for changing // row row = row + 1; // Function call for copying // the path copyPath(path, index + 1, mtrx, row); }} // Function to calculate// total pathint totalPath(Node* node){ static int count = 0; if (node == NULL) { return count; } if (node->left == NULL && node->right == NULL) { return count + 1; } count = totalPath(node->left); return totalPath(node->right);} // Function for Clockwise Spiral Traversal// of Binary Treevoid traverse_matrix(int** mtrx, int height, int width){ int j = 0, k1 = 0, k2 = 0; int k3 = height - 1; int k4 = width - 1; for (int round = 0; round < height/2; round++) { for (j = k2; j < width; j++) { // Only print those values which // are not MAX_INTEGER if (mtrx[k1][j] != INT_MAX) { cout << mtrx[k1][j] << \" \"; } } cout << endl; k2 = 0; k1++; for (j = k4; j >= 0; j--) { // Only print those values which // are not MAX_INTEGER if (mtrx[k3][j] != INT_MAX) { cout << mtrx[k3][j] << \" \"; } } cout << endl; k4 = width - 1; k3--; } // Condition (one row may be left // traversing) // If number of rows in matrix are odd if (height % 2 != 0) { for (j = k2; j < width; j++) { // Only print those values which are // not MAX_INTEGER if (mtrx[k1][j] != INT_MAX) { cout << mtrx[k1][j] << \" \"; } } }} // Function to print all the paths// in Boundary Root to Leaf// Path Traversalvoid PrintPath(Node* node){ // Calculate the length of // longest path of the tree int max_len = lengthOfLongestPath(node); // Calculate total path int total_path = totalPath(node); // Array to store path int* path = new int[max_len]; memset(path, 0, sizeof(path)); // Use double pointer to create // 2D array which will contain // all path of the tree int** mtrx = new int*[total_path]; // Initialize width for each row // of matrix for (int i = 0; i < total_path; i++) { mtrx[i] = new int[max_len]; } // Initialize complete matrix with // MAX INTEGER(purpose garbage) for (int i = 0; i < total_path; i++) { for (int j = 0; j < max_len; j++) { mtrx[i][j] = INT_MAX; } } int row = -1; storePath(node, path, 0, mtrx, row); // Print the circular clockwise spiral // traversal of the tree traverse_matrix(mtrx, total_path, max_len); // Release extra memory // allocated for matrix free(mtrx);} // Driver Codeint main(){ /* 10 / \\ 13 11 / \\ 19 23 / \\ / \\ 21 29 43 15 / 7 */ // Create Binary Tree as shown Node* root = newNode(10); root->left = newNode(13); root->right = newNode(11); root->right->left = newNode(19); root->right->right = newNode(23); root->right->left->left = newNode(21); root->right->left->right = newNode(29); root->right->right->left = newNode(43); root->right->right->right = newNode(15); root->right->right->right->left = newNode(7); // Function Call PrintPath(root); return 0;}",
"e": 31805,
"s": 26647,
"text": null
},
{
"code": "// Java implementation to print the // path in Boundary Root to Leaf // Path Traversal.import java.util.*; class GFG{ static int row;static int count = 0; // Structure of tree nodestatic class Node{ int key; Node left, right;}; // Utility function to// create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function to calculate the length// of longest path of the treestatic int lengthOfLongestPath(Node node){ // Base Case if (node == null) return 0; // Recursive call to calculate the // length of longest path int left = lengthOfLongestPath(node.left); int right = lengthOfLongestPath(node.right); return 1 + (left > right ? left : right);} // Function to copy the complete// path in a matrixstatic void copyPath(int[] path, int index, int[][] mtrx, int r){ // Loop to copy the path for(int i = 0; i < index; i++) { mtrx[r][i] = path[i]; }} // Function to store all path// one by one in matrixstatic void storePath(Node node, int[] path, int index, int[][] mtrx){ // Base condition if (node == null) { return; } // Inserting the current node // into the current path path[index] = node.key; // Recursive call for // the left sub tree storePath(node.left, path, index + 1, mtrx); // Recursive call for // the right sub tree storePath(node.right, path, index + 1, mtrx); // Condition to check that current // node is a leaf node or not if (node.left == null && node.right == null) { // Incrementation for changing // row row = row + 1; // Function call for copying // the path copyPath(path, index + 1, mtrx, row); }} // Function to calculate// total pathstatic int totalPath(Node node){ if (node == null) { return count; } if (node.left == null && node.right == null) { return count + 1; } count = totalPath(node.left); return totalPath(node.right);} // Function for Clockwise Spiral Traversal// of Binary Treestatic void traverse_matrix(int[][] mtrx, int height, int width){ int j = 0, k1 = 0, k2 = 0; int k3 = height - 1; int k4 = width - 1; for(int round = 0; round < height / 2; round++) { for(j = k2; j < width; j++) { // Only print those values which // are not MAX_INTEGER if (mtrx[k1][j] != Integer.MAX_VALUE) { System.out.print(mtrx[k1][j] + \" \"); } } System.out.println(); k2 = 0; k1++; for(j = k4; j >= 0; j--) { // Only print those values which // are not MAX_INTEGER if (mtrx[k3][j] != Integer.MAX_VALUE) { System.out.print(mtrx[k3][j] + \" \"); } } System.out.println(); k4 = width - 1; k3--; } // Condition (one row may be left // traversing) // If number of rows in matrix are odd if (height % 2 != 0) { for(j = k2; j < width; j++) { // Only print those values which are // not MAX_INTEGER if (mtrx[k1][j] != Integer.MAX_VALUE) { System.out.print(mtrx[k1][j] + \" \"); } } }} // Function to print all the paths// in Boundary Root to Leaf// Path Traversalstatic void PrintPath(Node node){ // Calculate the length of // longest path of the tree int max_len = lengthOfLongestPath(node); // Calculate total path int total_path = totalPath(node); // Array to store path int[] path = new int[max_len]; Arrays.fill(path, 0); // Use double pointer to create // 2D array which will contain // all path of the tree int[][] mtrx = new int[total_path][max_len]; // Initialize complete matrix with // MAX INTEGER(purpose garbage) for(int i = 0; i < total_path; i++) { for(int j = 0; j < max_len; j++) { mtrx[i][j] = Integer.MAX_VALUE; } } row = -1; storePath(node, path, 0, mtrx); // Print the circular clockwise spiral // traversal of the tree traverse_matrix(mtrx, total_path, max_len);} // Driver Codepublic static void main(String[] args){ /* 10 / \\ 13 11 / \\ 19 23 / \\ / \\ 21 29 43 15 / 7 */ // Create Binary Tree as shown Node root = newNode(10); root.left = newNode(13); root.right = newNode(11); root.right.left = newNode(19); root.right.right = newNode(23); root.right.left.left = newNode(21); root.right.left.right = newNode(29); root.right.right.left = newNode(43); root.right.right.right = newNode(15); root.right.right.right.left = newNode(7); // Function Call PrintPath(root);}} // This code is contributed by sanjeev2552",
"e": 36924,
"s": 31805,
"text": null
},
{
"code": "# Python3 implementation to print the# path in Boundary Root to Leaf# Path Traversal. # Structure of tree nodeclass Node: def __init__(self, key): self.key = key self.left = None self.right = None row = 0count = 0 # Utility function to# create a new nodedef newNode(key): temp = Node(key) return temp # Function to calculate the length# of longest path of the treedef lengthOfLongestPath(node): # Base Case if (node == None): return 0; # Recursive call to calculate the length # of longest path left = lengthOfLongestPath(node.left); right = lengthOfLongestPath(node.right); return 1 + (left if left > right else right); # Function to copy the complete# path in a matrixdef copyPath(path, index, mtrx, r): # Loop to copy the path for i in range(index): mtrx[r][i] = path[i]; # Function to store all path# one by one in matrixdef storePath(node, path, index, mtrx): global row # Base condition if (node == None): return; # Inserting the current node # into the current path path[index] = node.key; # Recursive call for # the left sub tree storePath(node.left, path, index + 1, mtrx); # Recursive call for # the right sub tree storePath(node.right, path, index + 1, mtrx); # Condition to check that current # node is a leaf node or not if (node.left == None and node.right == None): # Incrementation for changing # row row = row + 1; # Function call for copying # the path copyPath(path, index + 1, mtrx, row); # Function to calculate# total pathdef totalPath(node): global count if (node == None): return count; if (node.left == None and node.right == None): return count + 1; count = totalPath(node.left); return totalPath(node.right); # Function for Clockwise Spiral Traversal# of Binary Treedef traverse_matrix( mtrx, height, width): j = 0 k1 = 0 k2 = 0; k3 = height - 1; k4 = width - 1; for round in range(height//2): for j in range(k2, width): # Only print those values which # are not MAX_INTEGER if (mtrx[k1][j] != 1000000): print(mtrx[k1][j], end=' ') print() k2 = 0; k1 += 1 for j in range(k4, -1, -1): # Only print those values which # are not MAX_INTEGER if (mtrx[k3][j] != 1000000): print(mtrx[k3][j], end=' ') print() k4 = width - 1; k3 -= 1 # Condition (one row may be left # traversing) # If number of rows in matrix are odd if (height % 2 != 0): for j in range(k2, width): # Only print those values which are # not MAX_INTEGER if (mtrx[k1][j] != 1000000): print(mtrx[k1][j], end=' ') # Function to print all the paths# in Boundary Root to Leaf# Path Traversaldef PrintPath(node): global row # Calculate the length of # longest path of the tree max_len = lengthOfLongestPath(node); # Calculate total path total_path = totalPath(node); # Array to store path path = [0 for i in range(max_len)] # Use double pointer to create # 2D array which will contain # all path of the tree mtrx = [[1000000 for j in range(max_len)] for i in range(total_path)] row = -1; storePath(node, path, 0, mtrx); # Print the circular clockwise spiral # traversal of the tree traverse_matrix(mtrx, total_path, max_len); # Driver Codeif __name__=='__main__': ''' 10 / \\ 13 11 / \\ 19 23 / \\ / \\ 21 29 43 15 / 7 ''' # Create Binary Tree as shown root = newNode(10); root.left = newNode(13); root.right = newNode(11); root.right.left = newNode(19); root.right.right = newNode(23); root.right.left.left = newNode(21); root.right.left.right = newNode(29); root.right.right.left = newNode(43); root.right.right.right = newNode(15); root.right.right.right.left = newNode(7); # Function Call PrintPath(root); # This code is contributed by pratham76",
"e": 41372,
"s": 36924,
"text": null
},
{
"code": "// C# implementation to print the // path in Boundary Root to Leaf // Path Traversal. using System;using System.Collections; class GFG{ static int row;static int count = 0; // Structure of tree nodepublic class Node{ public int key; public Node left, right;}; // Utility function to// create a new nodestatic Node newNode(int key){ Node temp = new Node(); temp.key = key; temp.left = temp.right = null; return (temp);} // Function to calculate the length// of longest path of the treestatic int lengthOfLongestPath(Node node){ // Base Case if (node == null) return 0; // Recursive call to calculate the // length of longest path int left = lengthOfLongestPath(node.left); int right = lengthOfLongestPath(node.right); return 1 + (left > right ? left : right);} // Function to copy the complete// path in a matrixstatic void copyPath(int[] path, int index, int[,] mtrx, int r){ // Loop to copy the path for(int i = 0; i < index; i++) { mtrx[r, i] = path[i]; }} // Function to store all path// one by one in matrixstatic void storePath(Node node, int[] path, int index, int[,] mtrx){ // Base condition if (node == null) { return; } // Inserting the current node // into the current path path[index] = node.key; // Recursive call for // the left sub tree storePath(node.left, path, index + 1, mtrx); // Recursive call for // the right sub tree storePath(node.right, path, index + 1, mtrx); // Condition to check that current // node is a leaf node or not if (node.left == null && node.right == null) { // Incrementation for changing // row row = row + 1; // Function call for copying // the path copyPath(path, index + 1, mtrx, row); }} // Function to calculate// total pathstatic int totalPath(Node node){ if (node == null) { return count; } if (node.left == null && node.right == null) { return count + 1; } count = totalPath(node.left); return totalPath(node.right);} // Function for Clockwise Spiral Traversal// of Binary Treestatic void traverse_matrix(int[,] mtrx, int height, int width){ int j = 0, k1 = 0, k2 = 0; int k3 = height - 1; int k4 = width - 1; for(int round = 0; round < height / 2; round++) { for(j = k2; j < width; j++) { // Only print those values which // are not MAX_INTEGER if (mtrx[k1, j] != 10000000) { Console.Write(mtrx[k1, j] + \" \"); } } Console.WriteLine(); k2 = 0; k1++; for(j = k4; j >= 0; j--) { // Only print those values which // are not MAX_INTEGER if (mtrx[k3, j] != 10000000) { Console.Write(mtrx[k3, j] + \" \"); } } Console.WriteLine(); k4 = width - 1; k3--; } // Condition (one row may be left // traversing) // If number of rows in matrix are odd if (height % 2 != 0) { for(j = k2; j < width; j++) { // Only print those values which are // not MAX_INTEGER if (mtrx[k1, j] != 10000000) { Console.Write(mtrx[k1, j] + \" \"); } } }} // Function to print all the paths// in Boundary Root to Leaf// Path Traversalstatic void PrintPath(Node node){ // Calculate the length of // longest path of the tree int max_len = lengthOfLongestPath(node); // Calculate total path int total_path = totalPath(node); // Array to store path int[] path = new int[max_len]; Array.Fill(path, 0); // Use double pointer to create // 2D array which will contain // all path of the tree int[,] mtrx = new int[total_path, max_len]; // Initialize complete matrix with // MAX INTEGER(purpose garbage) for(int i = 0; i < total_path; i++) { for(int j = 0; j < max_len; j++) { mtrx[i, j] = 10000000; } } row = -1; storePath(node, path, 0, mtrx); // Print the circular clockwise spiral // traversal of the tree traverse_matrix(mtrx, total_path, max_len);} // Driver Codepublic static void Main(string[] args){ /* 10 / \\ 13 11 / \\ 19 23 / \\ / \\ 21 29 43 15 / 7 */ // Create Binary Tree as shown Node root = newNode(10); root.left = newNode(13); root.right = newNode(11); root.right.left = newNode(19); root.right.right = newNode(23); root.right.left.left = newNode(21); root.right.left.right = newNode(29); root.right.right.left = newNode(43); root.right.right.right = newNode(15); root.right.right.right.left = newNode(7); // Function Call PrintPath(root);}} // This code is contributed by rutvik_56",
"e": 46511,
"s": 41372,
"text": null
},
{
"code": "<script> // JavaScript implementation to print the // path in Boundary Root to Leaf // Path Traversal. let row; let count = 0; // Structure of tree node class Node { constructor(key) { this.left = null; this.right = null; this.key = key; } } // Utility function to // create a new node function newNode(key) { let temp = new Node(key); return (temp); } // Function to calculate the length // of longest path of the tree function lengthOfLongestPath(node) { // Base Case if (node == null) return 0; // Recursive call to calculate the // length of longest path let left = lengthOfLongestPath(node.left); let right = lengthOfLongestPath(node.right); return 1 + (left > right ? left : right); } // Function to copy the complete // path in a matrix function copyPath(path, index, mtrx, r) { // Loop to copy the path for(let i = 0; i < index; i++) { mtrx[r][i] = path[i]; } } // Function to store all path // one by one in matrix function storePath(node, path, index, mtrx) { // Base condition if (node == null) { return; } // Inserting the current node // into the current path path[index] = node.key; // Recursive call for // the left sub tree storePath(node.left, path, index + 1, mtrx); // Recursive call for // the right sub tree storePath(node.right, path, index + 1, mtrx); // Condition to check that current // node is a leaf node or not if (node.left == null && node.right == null) { // Incrementation for changing // row row = row + 1; // Function call for copying // the path copyPath(path, index + 1, mtrx, row); } } // Function to calculate // total path function totalPath(node) { if (node == null) { return count; } if (node.left == null && node.right == null) { return count + 1; } count = totalPath(node.left); return totalPath(node.right); } // Function for Clockwise Spiral Traversal // of Binary Tree function traverse_matrix(mtrx, height, width) { let j = 0, k1 = 0, k2 = 0; let k3 = height - 1; let k4 = width - 1; for(let round = 0; round < parseInt(height / 2, 10); round++) { for(j = k2; j < width; j++) { // Only print those values which // are not MAX_INTEGER if (mtrx[k1][j] != Number.MAX_VALUE) { document.write(mtrx[k1][j] + \" \"); } } document.write(\"</br>\"); k2 = 0; k1++; for(j = k4; j >= 0; j--) { // Only print those values which // are not MAX_INTEGER if (mtrx[k3][j] != Number.MAX_VALUE) { document.write(mtrx[k3][j] + \" \"); } } document.write(\"</br>\"); k4 = width - 1; k3--; } // Condition (one row may be left // traversing) // If number of rows in matrix are odd if (height % 2 != 0) { for(j = k2; j < width; j++) { // Only print those values which are // not MAX_INTEGER if (mtrx[k1][j] != Number.MAX_VALUE) { document.write(mtrx[k1][j] + \" \"); } } } } // Function to print all the paths // in Boundary Root to Leaf // Path Traversal function PrintPath(node) { // Calculate the length of // longest path of the tree let max_len = lengthOfLongestPath(node); // Calculate total path let total_path = totalPath(node); // Array to store path let path = new Array(max_len); path.fill(0); // Use double pointer to create // 2D array which will contain // all path of the tree let mtrx = new Array(total_path); // Initialize complete matrix with // MAX INTEGER(purpose garbage) for(let i = 0; i < total_path; i++) { mtrx[i] = new Array(max_len); for(let j = 0; j < max_len; j++) { mtrx[i][j] = Number.MAX_VALUE; } } row = -1; storePath(node, path, 0, mtrx); // Print the circular clockwise spiral // traversal of the tree traverse_matrix(mtrx, total_path, max_len); } /* 10 / \\ 13 11 / \\ 19 23 / \\ / \\ 21 29 43 15 / 7 */ // Create Binary Tree as shown let root = newNode(10); root.left = newNode(13); root.right = newNode(11); root.right.left = newNode(19); root.right.right = newNode(23); root.right.left.left = newNode(21); root.right.left.right = newNode(29); root.right.right.left = newNode(43); root.right.right.right = newNode(15); root.right.right.right.left = newNode(7); // Function Call PrintPath(root); </script>",
"e": 52014,
"s": 46511,
"text": null
},
{
"code": null,
"e": 52074,
"s": 52014,
"text": "10 13 \n7 15 23 11 10 \n10 11 19 21 \n43 23 11 10 \n10 11 19 29"
},
{
"code": null,
"e": 52088,
"s": 52076,
"text": "sanjeev2552"
},
{
"code": null,
"e": 52098,
"s": 52088,
"text": "rutvik_56"
},
{
"code": null,
"e": 52108,
"s": 52098,
"text": "pratham76"
},
{
"code": null,
"e": 52119,
"s": 52108,
"text": "nidhi_biet"
},
{
"code": null,
"e": 52133,
"s": 52119,
"text": "divyesh072019"
},
{
"code": null,
"e": 52150,
"s": 52133,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 52163,
"s": 52150,
"text": "ankita_saini"
},
{
"code": null,
"e": 52176,
"s": 52163,
"text": "simmytarika5"
},
{
"code": null,
"e": 52188,
"s": 52176,
"text": "Binary Tree"
},
{
"code": null,
"e": 52193,
"s": 52188,
"text": "Tree"
},
{
"code": null,
"e": 52198,
"s": 52193,
"text": "Tree"
},
{
"code": null,
"e": 52296,
"s": 52198,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 52305,
"s": 52296,
"text": "Comments"
},
{
"code": null,
"e": 52318,
"s": 52305,
"text": "Old Comments"
},
{
"code": null,
"e": 52354,
"s": 52318,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 52394,
"s": 52354,
"text": "DFS traversal of a tree using recursion"
},
{
"code": null,
"e": 52415,
"s": 52394,
"text": "Threaded Binary Tree"
},
{
"code": null,
"e": 52472,
"s": 52415,
"text": "Find the node with minimum value in a Binary Search Tree"
},
{
"code": null,
"e": 52513,
"s": 52472,
"text": "Find maximum (or minimum) in Binary Tree"
},
{
"code": null,
"e": 52569,
"s": 52513,
"text": "Iterative Postorder Traversal | Set 2 (Using One Stack)"
},
{
"code": null,
"e": 52612,
"s": 52569,
"text": "Top 50 Tree Coding Problems for Interviews"
},
{
"code": null,
"e": 52641,
"s": 52612,
"text": "Iterative Preorder Traversal"
},
{
"code": null,
"e": 52708,
"s": 52641,
"text": "Construct Complete Binary Tree from its Linked List Representation"
}
] |
Getting Started with Snowflake ❄️ | by Emile Gill | Towards Data Science
|
Whether you’ve heard of Snowflake Inc. from its record-breaking IPO this September, or from its ever-growing presence in data job ads, there is definitely a lot of hype around this company at the moment. In this article, we explore why, and how we can get started with its free trial.
A data warehouse is essential for any company that wants to be data-driven, and all companies should aspire to be data-driven; having business data at the fingertips of analysts and decision-makers has never been more important. That said, it is no easy feat to architect an on-premise data warehouse.
Requiring heavy IT support to set up and maintain the necessary hardware and software, on-premise data-warehouses have traditionally only been viable for large companies, and have often proved a source of friction between IT and analytics teams. This is humorously demonstrated by Snowflake in their ad:
Snowflake elegantly solves the problem of data warehousing. A cloud-based solution, Snowflake requires none of the heavy infrastructure set-up or up-front costs that are associated with traditional on-premise data-warehouses. It also allows users to scale up and down easily, whilst only paying for the storage and compute that they use. This makes it a great option for startups, where it may not be feasible to raise the up-front costs needed for a traditional data warehouse. Or for companies moving up the data hierarchy of needs, that need to start small, but scale up as their company progresses towards a more data-driven culture.
Its unique selling point comes in its layered architecture. At the base we have the “Database Storage” layer, this is where Snowflake stores and efficiently organises data loaded into the platform. Above this sits the “Compute” layer, where our virtual warehouses live. Each of these is an independent compute cluster that has access to the storage layer. Being independent, these virtual warehouses do not compete for any of the same resources; hence, we can scale the computational power to run queries on our storage layer indefinitely. On top of all of this sits Snowflake’s “Cloud Services” layer. This is the layer that we directly interact with, coordinating the way we interact with Snowflake’s underlying architecture, all through the universal language of SQL.
The separations of these layers and independent ability to scale each is what marks Snowflake out from the crowd. Giving the flexibility to organisations to pay only for the storage and compute they need, as well as scaling indefinitely to meet their needs.
One of the great things about cloud tech, is that there’s almost always a free trial that you can try out, without having to pay anything upfront. This makes learning the platform accessible, not just to those privileged enough to work for a company willing to try out new tech, or invest in learning and development, but also to individuals who are curious and trying to upskill themselves for the job market.
In a recent article, I detailed how one could set up a cloud PostgreSQL instance on AWS, Google Cloud Platform, or Heroku. Similarly, here, we will see that Snowflake offers a generous free-trial option that will allow us to explore what the platform has to offer.
To get started, we simply need to register here. Upon registration, an email will shortly arrive in our inbox with a link to our newly created Snowflake instance, for which we can set a username and password. From this point onwards we have $400 of Snowflake credits at our disposal to get a feel for the platform and explore the power of the features it has to offer.
Let’s begin by taking a look at the user interface of our newly set up instance. At the top of the console, we can see a taskbar comprising ‘Databases’, ‘Shares’, ‘Data Marketplace’, ‘Warehouses’, ‘Worksheets’, ‘History’. We’ll go through these one by one to get a feel for some of the fundamental concepts and features of Snowflake.
Here we can see a list of all the databases we have access to. We can also use the user interface to create, clone, drop or transfer ownership of a database. You will see that in our free trial we have already been provided with several databases. The database SNOWFLAKE_SAMPLE_DATA is of particular use, as this is pre-loaded with several datasets that we can immediately get started with.
Clicking on a database, we can see its comprising Tables, Views, Schemas, Stages, File Formats, Sequences and Pipes. The first three of these will be familiar to anyone with a working knowledge of SQL, the latter are powerful additions that help us with loading data into Snowflake, some of which we will explore later.
The “Shares” tab demonstrates another feature unique to Snowflake, allowing us to easily share Tables and Views between different accounts. Owing to its layered architecture, data stored on a provider’s account may be queried by a consumer, without the need for any replication or transfer of data. The top-level “Services” layer simply manages access to the stored data, such that the consumer incurs charges only for the compute resources they use to query the data, but no additional storage resources.
This all sounds simple, but is quite revolutionary when it comes to sharing data between third-party vendors, or between independent business functions within an organisation. It eliminates the need for any archaic form of data transfer like SFTP, or any replication of the data. The services layer from the consumer account simply reaches over to the provider’s storage layer and can see the data as it is, using its own compute resources to perform any queries.
As well as the direct sharing of data from providers to consumers we saw in the previous section, Snowflake also offers a “Data Marketplace” feature. This is an “app-store” of data, if you will. Various companies offer datasets, some available instantly for us to import and query, others being “Personalised” options which can be requested and purchased from the company under specific commercial terms agreed with the consumer. Again, something so simple, but entirely unique, that Snowflake has brought to the game, creating an entire industry in itself of companies providing and purchasing data in a seamless manner.
As discussed previously, “virtual warehouses” provide the computational element of the Snowflake platform, powering the queries and data loading tasks we perform. In the “Warehouses” tab we see a list of the warehouses we have available, as well as- analogous to what we saw in the “Tables” tab- the ability to create, drop and transfer ownership of warehouses.
We also have the option to configure the properties of a warehouse and to suspend or resume a warehouse. Remember, each warehouse is an independent compute cluster with specified size. This size determines the computational power we have available to make a query, but also the number of credits that we will be billed. We can provision compute resources to meet our individual needs and suspend or resume these as required so that we are not billed while they are not in use. The “Auto Suspend” property of a warehouse means that we do not have to resume/suspend manually; after a specified period of inactivity, the warehouse will be suspended automatically, resuming once a new query is executed.
The “Worksheets” tab provides a neat editor where we can write and execute SQL commands. The sidebar on the left visualises database objects: databases, schemas, tables, views. The tabbed layout at the top of the page allows us to create multiple “worksheets”, which are saved by Snowflake, so we don’t need to worry about losing our work. We can also load a SQL script in a .sql file, stored locally, to a worksheet. We see the result of any queries we execute at the bottom of the UI, and have the option of exporting this data to a CSV, or even copying it to our clipboard.
Here we can see all queries that have been executed on our Snowflake instance, going back 14 days. We can also see various metadata about these executions, including the status of the execution, warehouse used and duration the command took to run. We can even see the results of historic queries that have been run in the last 24 hours. This is useful if we want to retrieve information about queries that we have run or to check up on the status of any queries that might be currently executing.
Now that we have a feel for the concepts behind the Snowflake platform and the user interface that it provides, let’s consider a simple use case. Say we have a CSV dataset that we want to interrogate in Snowflake, how would one go about this task?
When it comes to connecting to Snowflake, we have several options to choose from.
We have seen that the web UI provides us with a “Worksheets” tab, where we can execute SQL commands and that we can use the UI itself to create objects. In addition to this, we can also connect to Snowflake using the SnowSQL command-line interface, or through its various connectors to common languages/frameworks. Here we will stay language agnostic by exploring the Snowflake CLI.
The installation process for SnowSQL CLI is covered here in the official documentation. Once it has been installed, connecting is easy. We simply, provide our connection parameters (the full list of which may be found here) and we’re in:
snowsql -a <account-name> -u <username>
Before we load any data, we must first set up the required database objects in Snowflake to house our CSV data, as well as provisioning the resources required for the load process.
Let’s first provision the compute resources we will use for our loading of data. To do this we need to create a new “virtual warehouse”, specifying the properties we want it to have. In this case, since our task will require minimal compute power, we provision an “X-SMALL” warehouse, which will only consume 1 Snowflake Credit per hour. We will also set an autosuspend of 3 minutes, so that our warehouse will automatically shut down after 3 minutes of inactivity, conserving the credits we use.
Next, we will need a database to house the tables and views for our project. We can do this simply by running:
Now that we have our warehouse and database set up, we can check the context we are working in, with:
If we correctly executed the above commands, then this should return the following:
All that remains is to create a table and then we can go ahead and start learning how to load in our data. For comparison, I’ll use the same data as my “A Practical Guide to Getting Set-up with PostgreSQL” post, which used the Covid-19 Geographic Case Distribution dataset provided by the European Centre for Disease Prevention and Control. You can get the latest version of this dataset here as a CSV.
When it comes to loading data into Snowflake, we must first create a “Stage”. This is simply a reference to a cloud storage location, from which Snowflake can pull our data. There are two forms of data stage that we might use: external stages, which reference cloud storage outside of Snowflake (i.e. Amazon S3, Google Cloud Storage, or Microsoft Azure) and internal stages, cloud storage hosted within the Snowflake platform.
To create an external stage we would- in keeping with the above syntax for creating database objects- simply need to run:
The parameters will vary slightly depending on the cloud service provider (AWS, GCP, Azure) we are connecting to. The example I have given here is for AWS, but the documentation here provides examples for all three, as well as the full list of optional parameters that can be supplied when creating a stage.
For the purposes of this tutorial, though, I will assume that we don’t have access to cloud storage already and will leverage the internal data storage provided by Snowflake. To create an internal stage is even simpler, running the above without specifying a URL or credentials parameter will create our stage within Snowflake:
Once we have our internal Snowflake stage set up, we can load in our CSV using the SnowSQL CLI put command from our local machine.
put file://C:\Users\emile\OneDrive\Documents\GitHub\snowflake-basics\ecdc_covid_cases.csv @test_db.public.test_stage;
If all went well, our file will now be stored in our Snowflake cloud storage, ready to be loaded into our table. We can quickly check the contents of a Snowflake data stage by running the command:
This will return a list of the files stored in our stage. In our case, we should see only one file, named ecdc_covid_cases.csv.gz . The .gz suffix shows that Snowflake has implicitly compressed our file, reducing the cloud storage required to host it.
Now that we have our data staged in the cloud, loading it into our target table couldn’t be easier. We simply run a COPY INTO command, specifying our table and the data stage we wish to load from.
As well as defining the table we seek to populate, and stage to gather data from, we also specify the FILE_FORMAT parameter. In this case, letting Snowflake know that we are loading CSV data, we want to skip the first row which contains headers, ignore missing columns and ignore commas contained within strings enclosed by double-quotes. There are many other options we could have specified here, and Snowflake even allows us to execute the create file_format command to create a named format, should we want to persist this for later use. In this case, though, specifying it in our COPY INTO command will suffice.
Following the execution of this command, we will be greeted with a line confirming the success of our execution. If not we will see a red error message, suggesting we need to tweak our load command to ensure that the file format is correctly specified and the data within is corresponding to the table we configured previously. Assuming our command has indeed executed correctly, we can now test the data we have loaded by selecting the first few lines by query:
select * from worldwide_caseslimit 5;
The results should return the first 5 lines of our dataset, indicating that our data is loaded correctly. We can now query away to our heart’s content!
We now have a basic feel for the fundamentals of the Snowflake Data Platform, can create database objects, stage and load data, and query data, both from the web-UI, and SnowSQL command-line interface. We have also explored why- in my opinion, at least- Snowflake is worthy of the hype that surrounds it.
In my next post on Snowflake, I hope to take this further and explore a more complex use case where we need to continuously load data into a Snowflake database from cloud storage. But for now...
Thanks for reading!
If you enjoyed this post, feel free to check out some of my other articles:
|
[
{
"code": null,
"e": 456,
"s": 171,
"text": "Whether you’ve heard of Snowflake Inc. from its record-breaking IPO this September, or from its ever-growing presence in data job ads, there is definitely a lot of hype around this company at the moment. In this article, we explore why, and how we can get started with its free trial."
},
{
"code": null,
"e": 758,
"s": 456,
"text": "A data warehouse is essential for any company that wants to be data-driven, and all companies should aspire to be data-driven; having business data at the fingertips of analysts and decision-makers has never been more important. That said, it is no easy feat to architect an on-premise data warehouse."
},
{
"code": null,
"e": 1062,
"s": 758,
"text": "Requiring heavy IT support to set up and maintain the necessary hardware and software, on-premise data-warehouses have traditionally only been viable for large companies, and have often proved a source of friction between IT and analytics teams. This is humorously demonstrated by Snowflake in their ad:"
},
{
"code": null,
"e": 1700,
"s": 1062,
"text": "Snowflake elegantly solves the problem of data warehousing. A cloud-based solution, Snowflake requires none of the heavy infrastructure set-up or up-front costs that are associated with traditional on-premise data-warehouses. It also allows users to scale up and down easily, whilst only paying for the storage and compute that they use. This makes it a great option for startups, where it may not be feasible to raise the up-front costs needed for a traditional data warehouse. Or for companies moving up the data hierarchy of needs, that need to start small, but scale up as their company progresses towards a more data-driven culture."
},
{
"code": null,
"e": 2471,
"s": 1700,
"text": "Its unique selling point comes in its layered architecture. At the base we have the “Database Storage” layer, this is where Snowflake stores and efficiently organises data loaded into the platform. Above this sits the “Compute” layer, where our virtual warehouses live. Each of these is an independent compute cluster that has access to the storage layer. Being independent, these virtual warehouses do not compete for any of the same resources; hence, we can scale the computational power to run queries on our storage layer indefinitely. On top of all of this sits Snowflake’s “Cloud Services” layer. This is the layer that we directly interact with, coordinating the way we interact with Snowflake’s underlying architecture, all through the universal language of SQL."
},
{
"code": null,
"e": 2729,
"s": 2471,
"text": "The separations of these layers and independent ability to scale each is what marks Snowflake out from the crowd. Giving the flexibility to organisations to pay only for the storage and compute they need, as well as scaling indefinitely to meet their needs."
},
{
"code": null,
"e": 3140,
"s": 2729,
"text": "One of the great things about cloud tech, is that there’s almost always a free trial that you can try out, without having to pay anything upfront. This makes learning the platform accessible, not just to those privileged enough to work for a company willing to try out new tech, or invest in learning and development, but also to individuals who are curious and trying to upskill themselves for the job market."
},
{
"code": null,
"e": 3405,
"s": 3140,
"text": "In a recent article, I detailed how one could set up a cloud PostgreSQL instance on AWS, Google Cloud Platform, or Heroku. Similarly, here, we will see that Snowflake offers a generous free-trial option that will allow us to explore what the platform has to offer."
},
{
"code": null,
"e": 3774,
"s": 3405,
"text": "To get started, we simply need to register here. Upon registration, an email will shortly arrive in our inbox with a link to our newly created Snowflake instance, for which we can set a username and password. From this point onwards we have $400 of Snowflake credits at our disposal to get a feel for the platform and explore the power of the features it has to offer."
},
{
"code": null,
"e": 4108,
"s": 3774,
"text": "Let’s begin by taking a look at the user interface of our newly set up instance. At the top of the console, we can see a taskbar comprising ‘Databases’, ‘Shares’, ‘Data Marketplace’, ‘Warehouses’, ‘Worksheets’, ‘History’. We’ll go through these one by one to get a feel for some of the fundamental concepts and features of Snowflake."
},
{
"code": null,
"e": 4499,
"s": 4108,
"text": "Here we can see a list of all the databases we have access to. We can also use the user interface to create, clone, drop or transfer ownership of a database. You will see that in our free trial we have already been provided with several databases. The database SNOWFLAKE_SAMPLE_DATA is of particular use, as this is pre-loaded with several datasets that we can immediately get started with."
},
{
"code": null,
"e": 4819,
"s": 4499,
"text": "Clicking on a database, we can see its comprising Tables, Views, Schemas, Stages, File Formats, Sequences and Pipes. The first three of these will be familiar to anyone with a working knowledge of SQL, the latter are powerful additions that help us with loading data into Snowflake, some of which we will explore later."
},
{
"code": null,
"e": 5325,
"s": 4819,
"text": "The “Shares” tab demonstrates another feature unique to Snowflake, allowing us to easily share Tables and Views between different accounts. Owing to its layered architecture, data stored on a provider’s account may be queried by a consumer, without the need for any replication or transfer of data. The top-level “Services” layer simply manages access to the stored data, such that the consumer incurs charges only for the compute resources they use to query the data, but no additional storage resources."
},
{
"code": null,
"e": 5789,
"s": 5325,
"text": "This all sounds simple, but is quite revolutionary when it comes to sharing data between third-party vendors, or between independent business functions within an organisation. It eliminates the need for any archaic form of data transfer like SFTP, or any replication of the data. The services layer from the consumer account simply reaches over to the provider’s storage layer and can see the data as it is, using its own compute resources to perform any queries."
},
{
"code": null,
"e": 6411,
"s": 5789,
"text": "As well as the direct sharing of data from providers to consumers we saw in the previous section, Snowflake also offers a “Data Marketplace” feature. This is an “app-store” of data, if you will. Various companies offer datasets, some available instantly for us to import and query, others being “Personalised” options which can be requested and purchased from the company under specific commercial terms agreed with the consumer. Again, something so simple, but entirely unique, that Snowflake has brought to the game, creating an entire industry in itself of companies providing and purchasing data in a seamless manner."
},
{
"code": null,
"e": 6773,
"s": 6411,
"text": "As discussed previously, “virtual warehouses” provide the computational element of the Snowflake platform, powering the queries and data loading tasks we perform. In the “Warehouses” tab we see a list of the warehouses we have available, as well as- analogous to what we saw in the “Tables” tab- the ability to create, drop and transfer ownership of warehouses."
},
{
"code": null,
"e": 7473,
"s": 6773,
"text": "We also have the option to configure the properties of a warehouse and to suspend or resume a warehouse. Remember, each warehouse is an independent compute cluster with specified size. This size determines the computational power we have available to make a query, but also the number of credits that we will be billed. We can provision compute resources to meet our individual needs and suspend or resume these as required so that we are not billed while they are not in use. The “Auto Suspend” property of a warehouse means that we do not have to resume/suspend manually; after a specified period of inactivity, the warehouse will be suspended automatically, resuming once a new query is executed."
},
{
"code": null,
"e": 8050,
"s": 7473,
"text": "The “Worksheets” tab provides a neat editor where we can write and execute SQL commands. The sidebar on the left visualises database objects: databases, schemas, tables, views. The tabbed layout at the top of the page allows us to create multiple “worksheets”, which are saved by Snowflake, so we don’t need to worry about losing our work. We can also load a SQL script in a .sql file, stored locally, to a worksheet. We see the result of any queries we execute at the bottom of the UI, and have the option of exporting this data to a CSV, or even copying it to our clipboard."
},
{
"code": null,
"e": 8547,
"s": 8050,
"text": "Here we can see all queries that have been executed on our Snowflake instance, going back 14 days. We can also see various metadata about these executions, including the status of the execution, warehouse used and duration the command took to run. We can even see the results of historic queries that have been run in the last 24 hours. This is useful if we want to retrieve information about queries that we have run or to check up on the status of any queries that might be currently executing."
},
{
"code": null,
"e": 8795,
"s": 8547,
"text": "Now that we have a feel for the concepts behind the Snowflake platform and the user interface that it provides, let’s consider a simple use case. Say we have a CSV dataset that we want to interrogate in Snowflake, how would one go about this task?"
},
{
"code": null,
"e": 8877,
"s": 8795,
"text": "When it comes to connecting to Snowflake, we have several options to choose from."
},
{
"code": null,
"e": 9260,
"s": 8877,
"text": "We have seen that the web UI provides us with a “Worksheets” tab, where we can execute SQL commands and that we can use the UI itself to create objects. In addition to this, we can also connect to Snowflake using the SnowSQL command-line interface, or through its various connectors to common languages/frameworks. Here we will stay language agnostic by exploring the Snowflake CLI."
},
{
"code": null,
"e": 9498,
"s": 9260,
"text": "The installation process for SnowSQL CLI is covered here in the official documentation. Once it has been installed, connecting is easy. We simply, provide our connection parameters (the full list of which may be found here) and we’re in:"
},
{
"code": null,
"e": 9538,
"s": 9498,
"text": "snowsql -a <account-name> -u <username>"
},
{
"code": null,
"e": 9719,
"s": 9538,
"text": "Before we load any data, we must first set up the required database objects in Snowflake to house our CSV data, as well as provisioning the resources required for the load process."
},
{
"code": null,
"e": 10216,
"s": 9719,
"text": "Let’s first provision the compute resources we will use for our loading of data. To do this we need to create a new “virtual warehouse”, specifying the properties we want it to have. In this case, since our task will require minimal compute power, we provision an “X-SMALL” warehouse, which will only consume 1 Snowflake Credit per hour. We will also set an autosuspend of 3 minutes, so that our warehouse will automatically shut down after 3 minutes of inactivity, conserving the credits we use."
},
{
"code": null,
"e": 10327,
"s": 10216,
"text": "Next, we will need a database to house the tables and views for our project. We can do this simply by running:"
},
{
"code": null,
"e": 10429,
"s": 10327,
"text": "Now that we have our warehouse and database set up, we can check the context we are working in, with:"
},
{
"code": null,
"e": 10513,
"s": 10429,
"text": "If we correctly executed the above commands, then this should return the following:"
},
{
"code": null,
"e": 10916,
"s": 10513,
"text": "All that remains is to create a table and then we can go ahead and start learning how to load in our data. For comparison, I’ll use the same data as my “A Practical Guide to Getting Set-up with PostgreSQL” post, which used the Covid-19 Geographic Case Distribution dataset provided by the European Centre for Disease Prevention and Control. You can get the latest version of this dataset here as a CSV."
},
{
"code": null,
"e": 11343,
"s": 10916,
"text": "When it comes to loading data into Snowflake, we must first create a “Stage”. This is simply a reference to a cloud storage location, from which Snowflake can pull our data. There are two forms of data stage that we might use: external stages, which reference cloud storage outside of Snowflake (i.e. Amazon S3, Google Cloud Storage, or Microsoft Azure) and internal stages, cloud storage hosted within the Snowflake platform."
},
{
"code": null,
"e": 11465,
"s": 11343,
"text": "To create an external stage we would- in keeping with the above syntax for creating database objects- simply need to run:"
},
{
"code": null,
"e": 11773,
"s": 11465,
"text": "The parameters will vary slightly depending on the cloud service provider (AWS, GCP, Azure) we are connecting to. The example I have given here is for AWS, but the documentation here provides examples for all three, as well as the full list of optional parameters that can be supplied when creating a stage."
},
{
"code": null,
"e": 12101,
"s": 11773,
"text": "For the purposes of this tutorial, though, I will assume that we don’t have access to cloud storage already and will leverage the internal data storage provided by Snowflake. To create an internal stage is even simpler, running the above without specifying a URL or credentials parameter will create our stage within Snowflake:"
},
{
"code": null,
"e": 12232,
"s": 12101,
"text": "Once we have our internal Snowflake stage set up, we can load in our CSV using the SnowSQL CLI put command from our local machine."
},
{
"code": null,
"e": 12350,
"s": 12232,
"text": "put file://C:\\Users\\emile\\OneDrive\\Documents\\GitHub\\snowflake-basics\\ecdc_covid_cases.csv @test_db.public.test_stage;"
},
{
"code": null,
"e": 12547,
"s": 12350,
"text": "If all went well, our file will now be stored in our Snowflake cloud storage, ready to be loaded into our table. We can quickly check the contents of a Snowflake data stage by running the command:"
},
{
"code": null,
"e": 12799,
"s": 12547,
"text": "This will return a list of the files stored in our stage. In our case, we should see only one file, named ecdc_covid_cases.csv.gz . The .gz suffix shows that Snowflake has implicitly compressed our file, reducing the cloud storage required to host it."
},
{
"code": null,
"e": 12996,
"s": 12799,
"text": "Now that we have our data staged in the cloud, loading it into our target table couldn’t be easier. We simply run a COPY INTO command, specifying our table and the data stage we wish to load from."
},
{
"code": null,
"e": 13612,
"s": 12996,
"text": "As well as defining the table we seek to populate, and stage to gather data from, we also specify the FILE_FORMAT parameter. In this case, letting Snowflake know that we are loading CSV data, we want to skip the first row which contains headers, ignore missing columns and ignore commas contained within strings enclosed by double-quotes. There are many other options we could have specified here, and Snowflake even allows us to execute the create file_format command to create a named format, should we want to persist this for later use. In this case, though, specifying it in our COPY INTO command will suffice."
},
{
"code": null,
"e": 14075,
"s": 13612,
"text": "Following the execution of this command, we will be greeted with a line confirming the success of our execution. If not we will see a red error message, suggesting we need to tweak our load command to ensure that the file format is correctly specified and the data within is corresponding to the table we configured previously. Assuming our command has indeed executed correctly, we can now test the data we have loaded by selecting the first few lines by query:"
},
{
"code": null,
"e": 14113,
"s": 14075,
"text": "select * from worldwide_caseslimit 5;"
},
{
"code": null,
"e": 14265,
"s": 14113,
"text": "The results should return the first 5 lines of our dataset, indicating that our data is loaded correctly. We can now query away to our heart’s content!"
},
{
"code": null,
"e": 14570,
"s": 14265,
"text": "We now have a basic feel for the fundamentals of the Snowflake Data Platform, can create database objects, stage and load data, and query data, both from the web-UI, and SnowSQL command-line interface. We have also explored why- in my opinion, at least- Snowflake is worthy of the hype that surrounds it."
},
{
"code": null,
"e": 14765,
"s": 14570,
"text": "In my next post on Snowflake, I hope to take this further and explore a more complex use case where we need to continuously load data into a Snowflake database from cloud storage. But for now..."
},
{
"code": null,
"e": 14785,
"s": 14765,
"text": "Thanks for reading!"
}
] |
Java 16 - Environment Setup
|
We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.
Try the following example using Live Demo option available at the top right corner of the below sample code box −
public class MyFirstJavaProgram {
public static void main(String []args) {
System.out.println("Hello World");
}
}
Hello World
For most of the examples given in this tutorial, you will find a Live Demo option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning.
If you want to set up your own environment for Java programming language, then this section guides you through the whole process.Please follow the steps given below to set up your Java environment.
Java SE is available for download for free.To download click here, please download a version compatible with your operating system.
Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Right-click on 'My Computer' and select 'Properties'.
Right-click on 'My Computer' and select 'Properties'.
Click on the 'Environment variables' button under the 'Advanced' tab.
Click on the 'Environment variables' button under the 'Advanced' tab.
Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way
C:\Windows\System32;c:\Program Files\java\jdk\bin.
Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way
C:\Windows\System32;c:\Program Files\java\jdk\bin.
Assuming you have installed Java in c:\Program Files\java\jdk directory −
Edit the 'C:\autoexec.bat' file and add the following line at the end −
SET PATH=%PATH%;C:\Program Files\java\jdk\bin
Edit the 'C:\autoexec.bat' file and add the following line at the end −
SET PATH=%PATH%;C:\Program Files\java\jdk\bin
Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.
For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc −
export PATH=/path/to/java:$PATH'
export PATH=/path/to/java:$PATH'
To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −
Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.
Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.
Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org/.
Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org/.
IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc.
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": 2383,
"s": 2090,
"text": "We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online."
},
{
"code": null,
"e": 2497,
"s": 2383,
"text": "Try the following example using Live Demo option available at the top right corner of the below sample code box −"
},
{
"code": null,
"e": 2623,
"s": 2497,
"text": "public class MyFirstJavaProgram {\n public static void main(String []args) {\n System.out.println(\"Hello World\");\n }\n}"
},
{
"code": null,
"e": 2636,
"s": 2623,
"text": "Hello World\n"
},
{
"code": null,
"e": 2862,
"s": 2636,
"text": "For most of the examples given in this tutorial, you will find a Live Demo option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning."
},
{
"code": null,
"e": 3060,
"s": 2862,
"text": "If you want to set up your own environment for Java programming language, then this section guides you through the whole process.Please follow the steps given below to set up your Java environment."
},
{
"code": null,
"e": 3192,
"s": 3060,
"text": "Java SE is available for download for free.To download click here, please download a version compatible with your operating system."
},
{
"code": null,
"e": 3420,
"s": 3192,
"text": "Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories."
},
{
"code": null,
"e": 3494,
"s": 3420,
"text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory −"
},
{
"code": null,
"e": 3548,
"s": 3494,
"text": "Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 3602,
"s": 3548,
"text": "Right-click on 'My Computer' and select 'Properties'."
},
{
"code": null,
"e": 3672,
"s": 3602,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 3742,
"s": 3672,
"text": "Click on the 'Environment variables' button under the 'Advanced' tab."
},
{
"code": null,
"e": 3989,
"s": 3742,
"text": "Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\\Windows\\System32, then edit it the following way\nC:\\Windows\\System32;c:\\Program Files\\java\\jdk\\bin.\n"
},
{
"code": null,
"e": 4184,
"s": 3989,
"text": "Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\\Windows\\System32, then edit it the following way"
},
{
"code": null,
"e": 4235,
"s": 4184,
"text": "C:\\Windows\\System32;c:\\Program Files\\java\\jdk\\bin."
},
{
"code": null,
"e": 4309,
"s": 4235,
"text": "Assuming you have installed Java in c:\\Program Files\\java\\jdk directory −"
},
{
"code": null,
"e": 4428,
"s": 4309,
"text": "\nEdit the 'C:\\autoexec.bat' file and add the following line at the end −\nSET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin"
},
{
"code": null,
"e": 4500,
"s": 4428,
"text": "Edit the 'C:\\autoexec.bat' file and add the following line at the end −"
},
{
"code": null,
"e": 4546,
"s": 4500,
"text": "SET PATH=%PATH%;C:\\Program Files\\java\\jdk\\bin"
},
{
"code": null,
"e": 4709,
"s": 4546,
"text": "Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this."
},
{
"code": null,
"e": 4820,
"s": 4709,
"text": "For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc −"
},
{
"code": null,
"e": 4853,
"s": 4820,
"text": "export PATH=/path/to/java:$PATH'"
},
{
"code": null,
"e": 4886,
"s": 4853,
"text": "export PATH=/path/to/java:$PATH'"
},
{
"code": null,
"e": 5050,
"s": 4886,
"text": "To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −"
},
{
"code": null,
"e": 5236,
"s": 5050,
"text": "Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities."
},
{
"code": null,
"e": 5422,
"s": 5236,
"text": "Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities."
},
{
"code": null,
"e": 5537,
"s": 5422,
"text": "Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html."
},
{
"code": null,
"e": 5652,
"s": 5537,
"text": "Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html."
},
{
"code": null,
"e": 5777,
"s": 5652,
"text": "Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org/."
},
{
"code": null,
"e": 5902,
"s": 5777,
"text": "Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org/."
},
{
"code": null,
"e": 6068,
"s": 5902,
"text": "IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc."
},
{
"code": null,
"e": 6101,
"s": 6068,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6117,
"s": 6101,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6150,
"s": 6117,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6166,
"s": 6150,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6201,
"s": 6166,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6215,
"s": 6201,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6249,
"s": 6215,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6263,
"s": 6249,
"text": " Tushar Kale"
},
{
"code": null,
"e": 6300,
"s": 6263,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 6315,
"s": 6300,
"text": " Monica Mittal"
},
{
"code": null,
"e": 6348,
"s": 6315,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 6367,
"s": 6348,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6374,
"s": 6367,
"text": " Print"
},
{
"code": null,
"e": 6385,
"s": 6374,
"text": " Add Notes"
}
] |
InterpretML: Analysis of SVM and XGBoost models | by Michael Grogan | Towards Data Science
|
InterpretML by Microsoft is designed with the aim of expanding interpretability of machine learning models. In other words, make those models easier to understand and ultimately facilitate human interpretation.
Microsoft’s Interpret-Community is an extension of this repository, which includes additional interpretability techniques.
In particular, one useful feature is what is called the MimicExplainer. This is a type of global surrogate model that allows for interpretability of any black box model.
In this example, the MimicExplainer is used in interpreting regression models built using SVM (support vector machines) and XGBRegressor (XGBoost for regression problems).
Specifically, these two models are used as follows:
SVM is used for predicting the average daily rate of a customer using specified features, such as their country of origin, market segment, among others. Original findings are available here.XGBRegressor is used as a time series regression model to predict the number of weekly cancellations by regressing a lagged series against the actual, i.e. 5 lagged series with sequential lags of up to t-5 are used as features in the model to predict the cancellation value at time t. Original findings are available here.
SVM is used for predicting the average daily rate of a customer using specified features, such as their country of origin, market segment, among others. Original findings are available here.
XGBRegressor is used as a time series regression model to predict the number of weekly cancellations by regressing a lagged series against the actual, i.e. 5 lagged series with sequential lags of up to t-5 are used as features in the model to predict the cancellation value at time t. Original findings are available here.
The original data is available from Antonio, Almeida and Nunes (2019): Hotel booking demand datasets.
For the purposes of demonstrating how MimicExplainer works, the original models and results are illustrated — with further information on how MimicExplainer can make such results more interpretable.
In order to predict the average daily rate (or rate that a customer pays on average per day) for a hotel booking, an SVM model is constructed with the following features:
Cancellation (whether a customer cancels their booking or not)
Country of Origin
Market Segment
Deposit Type
Customer Type
Required Car Parking Spaces
Week of Arrival
The model is trained as follows:
>>> from sklearn.svm import LinearSVR>>> svm_reg = LinearSVR(epsilon=1.5)>>> svm_reg.fit(X_train, y_train)LinearSVR(C=1.0, dual=True, epsilon=1.5, fit_intercept=True,intercept_scaling=1.0, loss='epsilon_insensitive', max_iter=1000, random_state=None, tol=0.0001, verbose=0)>>> predictions = svm_reg.predict(X_val)>>> predictionsarray([100.75090575, 109.08222631, 79.81544167, ..., 94.50700112, 55.65495607, 65.5248653 ])
When this model was validated against a test set, an RMSE (root mean squared error) of 44.6 was obtained, along with an MAE (mean absolute error) of 29.5. With a mean ADR of 105, the model does show a degree of predictive power in estimating ADR values by customer.
Here is how we can use MimicExplainer for further interpretability of these results.
from interpret.ext.blackbox import MimicExplainerfrom interpret.ext.glassbox import LinearExplainableModelexplainer = MimicExplainer(svm_reg, X_train, LinearExplainableModel)
The MimicExplainer is the black box model, while the LinearExplainableModel is being used as the global surrogate to this black box model.
Note that when running the model, it is possible to set augment_data = True if dealing with high-dimensional data, i.e. a situation where the number of columns exceeds the number of rows. This allows for oversampling of initialization samples.
However, given that this is not the case here, i.e. the dataset has many more rows than columns (features) — this will not be invoked.
Next, a global explanation is printed out which features the top K features and their values indicating importance:
global_explanation = explainer.explain_global(X_val)sorted_global_importance_values = global_explanation.get_ranked_global_values()sorted_global_importance_names = global_explanation.get_ranked_global_names()dict(zip(sorted_global_importance_names, sorted_global_importance_values))global_explanation.get_feature_importance_dict()
Here is the output:
{3: 8.81513709127725, 7: 4.9616362270740995, 1: 4.959263897550327, 6: 2.593931464493208, 2: 0.9707145503848649, 5: 0.8455564214901589, 4: 0.505321879369921, 0: 0.0}
From the above, feature number 3 (market segment), 7 (week of arrival), and 1 (booking cancellation) are indicated as the most important features in influencing customer ADR.
That said, what if we wish to isolate certain observations in the validation data? e.g. suppose that we only wish to determine feature importance for a select few customers?
Here is an example.
From the validation set, features of importance and their values are determined for customers ordered 10 to 15.
local_explanation = explainer.explain_local(X_val[10:15])sorted_local_importance_names = local_explanation.get_ranked_local_names()sorted_local_importance_values = local_explanation.get_ranked_local_values()
Here are the identified features of importance and their values:
>>> sorted_local_importance_names[[1, 3, 2, 6, 5, 4, 0, 7], [7, 3, 2, 6, 5, 4, 1, 0], [6, 5, 4, 1, 0, 2, 7, 3], [6, 3, 5, 4, 1, 0, 2, 7], [3, 7, 6, 5, 4, 1, 0, 2]]>>> sorted_local_importance_values[[17.833762274315003, 9.1394041860457, 1.1694515257954607, 0.0, -0.0, -0.0, 0.0, -1.707920714865971], [9.955928069584559, 9.1394041860457, 1.1694515257954607, 0.0, -0.0, -0.0, 0.0, 0.0], [0.0, -0.0, -0.0, 0.0, 0.0, -0.5708037209239748, -11.288939359236048, -13.709106279068548], [19.017733248096473, 9.1394041860457, -0.0, -0.0, 0.0, 0.0, -0.7448292455959183, -5.040448938994693], [9.1394041860457, 6.623399845455836, 0.0, -0.0, -0.0, 0.0, 0.0, -0.9884649801366393]]
This allows for isolation of feature importance by customer. For instance, feature 1 (booking cancellation) was the most influencing factor for customer 10, whereas feature 7 (week of arrival) was the most influencing factor for customer 11.
As mentioned, an XGBRegressor model was originally used in order to predict the number of weekly cancellations for the hotel in question.
The model was defined as follows:
from xgboost import XGBRegressormodel = XGBRegressor(objective='reg:squarederror', n_estimators=1000)model.fit(X_train, Y_train)
Here are the defined model parameters:
As we can see from the above, there are numerous model parameters that could be modified in training the XGBRegressor. However, n_estimators is set to 1000 in this instance. This defines the number of trees in the XGBoost model.The objective is set to ‘reg:squarederror’, i.e. a regression with squared loss which penalizes errors on extreme values more heavily.
The RMSE yielded across the validation set was 50.14 along with an MAE of 38.63, which was lower than the mean value of 109 yielded across this set.
Using MimicExplainer, the interpretability of the model results can now be generated in a similar manner to the previous example:
from interpret.ext.blackbox import MimicExplainerfrom interpret.ext.glassbox import LinearExplainableModelexplainer = MimicExplainer(model, X_train, LinearExplainableModel)
For this purpose, we can identify the features that are the most important in determining the weekly hotel cancellation value at time t. However, given that this is a time series — the model is effectively indicating which lag value is most informative in predicting the cancellation for a particular week, e.g. is a 1-week lag, or a 3-week lag of most importance in influencing cancellations at time t?
global_explanation = explainer.explain_global(X_val)sorted_global_importance_values = global_explanation.get_ranked_global_values()sorted_global_importance_names = global_explanation.get_ranked_global_names()dict(zip(sorted_global_importance_names, sorted_global_importance_values))global_explanation.get_feature_importance_dict()
Here are the results:
{3: 10.580821439553645, 2: 7.795196757642633, 1: 4.973377270096975, 4: 2.329894438847138, 0: 1.382442979985477}
From the above, it is indicated that a lag for feature 3 (t-4) is of most importance when forecasting weekly hotel cancellations at time t.
However, what if we wish to isolate certain weeks?
Taking the validation set, let us isolate the weeks across observations 8 to 13 (which corresponds to the year 2017, weeks 13 to 18).
local_explanation = explainer.explain_local(X_val[8:13])sorted_local_importance_names = local_explanation.get_ranked_local_names()sorted_local_importance_values = local_explanation.get_ranked_local_values()
Here are the findings:
>>> sorted_local_importance_names[[4, 0, 2, 1, 3], [3, 4, 1, 0, 2], [3, 4, 1, 2, 0], [3, 2, 0, 4, 1], [2, 3, 4, 0, 1]]>>> sorted_local_importance_values[[1.2079747395122986, 0.655418467841234, -2.068988871651338, -5.677678197831921, -16.414222669030814], [5.880283637250306, 1.524120206263528, 1.157876862894971, -1.807324914948728, -11.282397723111108], [7.472748373413244, 7.056665874410039, 6.562734352772048, 3.8926286204696896, 0.353858053622055], [35.340881256264645, 4.976559073582604, 2.0627004008640695, 1.1289383728244913, -2.3393838658490202], [23.945342003058602, 5.4821674532095725, 1.287011106200106, -0.7518634651816014, -2.975249452893382]]
Identifying the features of importance across the time series in this manner can potentially yield useful insights as to the importance of lagged values in predicting cancellations across different weeks. For instance, we can see that in predicting cancellations for week 13, the lag at t-5 (feature 4) was identified as the most important feature.
However, when predicting cancellations for week 18, the lag at t-3 (feature 2) was identified as most important.
As opposed to using a one size fits all forecasting model, interpretability can allow for identification of suitable forecasting methods for a particular point in time, and in turn allow for customisation of time series forecasting methods across different periods.
In this example, we have seen how interpretability can yield valuable insights when analysing machine learning output — which would be much more difficult when simply using black box ML models in their own right.
Specifically, we have seen:
How MimicExplainer can be used as a global surrogate model to allow for interpretability of any black box model
Use of MimicExplainer across regression problems
How to interpret the results from MimicExplainer and gauge feature importance
Many thanks for your time, and any questions or feedback are greatly appreciated. The relevant Jupyter Notebooks for the above examples can be found here.
Disclaimer: This article is written on an “as is” basis and without warranty. It was written with the intention of providing an overview of data science concepts, and should not be interpreted as any sort of professional advice. The findings are that of the author, and are not affiliated with any third-party mentioned above.
|
[
{
"code": null,
"e": 383,
"s": 172,
"text": "InterpretML by Microsoft is designed with the aim of expanding interpretability of machine learning models. In other words, make those models easier to understand and ultimately facilitate human interpretation."
},
{
"code": null,
"e": 506,
"s": 383,
"text": "Microsoft’s Interpret-Community is an extension of this repository, which includes additional interpretability techniques."
},
{
"code": null,
"e": 676,
"s": 506,
"text": "In particular, one useful feature is what is called the MimicExplainer. This is a type of global surrogate model that allows for interpretability of any black box model."
},
{
"code": null,
"e": 848,
"s": 676,
"text": "In this example, the MimicExplainer is used in interpreting regression models built using SVM (support vector machines) and XGBRegressor (XGBoost for regression problems)."
},
{
"code": null,
"e": 900,
"s": 848,
"text": "Specifically, these two models are used as follows:"
},
{
"code": null,
"e": 1413,
"s": 900,
"text": "SVM is used for predicting the average daily rate of a customer using specified features, such as their country of origin, market segment, among others. Original findings are available here.XGBRegressor is used as a time series regression model to predict the number of weekly cancellations by regressing a lagged series against the actual, i.e. 5 lagged series with sequential lags of up to t-5 are used as features in the model to predict the cancellation value at time t. Original findings are available here."
},
{
"code": null,
"e": 1604,
"s": 1413,
"text": "SVM is used for predicting the average daily rate of a customer using specified features, such as their country of origin, market segment, among others. Original findings are available here."
},
{
"code": null,
"e": 1927,
"s": 1604,
"text": "XGBRegressor is used as a time series regression model to predict the number of weekly cancellations by regressing a lagged series against the actual, i.e. 5 lagged series with sequential lags of up to t-5 are used as features in the model to predict the cancellation value at time t. Original findings are available here."
},
{
"code": null,
"e": 2029,
"s": 1927,
"text": "The original data is available from Antonio, Almeida and Nunes (2019): Hotel booking demand datasets."
},
{
"code": null,
"e": 2228,
"s": 2029,
"text": "For the purposes of demonstrating how MimicExplainer works, the original models and results are illustrated — with further information on how MimicExplainer can make such results more interpretable."
},
{
"code": null,
"e": 2399,
"s": 2228,
"text": "In order to predict the average daily rate (or rate that a customer pays on average per day) for a hotel booking, an SVM model is constructed with the following features:"
},
{
"code": null,
"e": 2462,
"s": 2399,
"text": "Cancellation (whether a customer cancels their booking or not)"
},
{
"code": null,
"e": 2480,
"s": 2462,
"text": "Country of Origin"
},
{
"code": null,
"e": 2495,
"s": 2480,
"text": "Market Segment"
},
{
"code": null,
"e": 2508,
"s": 2495,
"text": "Deposit Type"
},
{
"code": null,
"e": 2522,
"s": 2508,
"text": "Customer Type"
},
{
"code": null,
"e": 2550,
"s": 2522,
"text": "Required Car Parking Spaces"
},
{
"code": null,
"e": 2566,
"s": 2550,
"text": "Week of Arrival"
},
{
"code": null,
"e": 2599,
"s": 2566,
"text": "The model is trained as follows:"
},
{
"code": null,
"e": 3030,
"s": 2599,
"text": ">>> from sklearn.svm import LinearSVR>>> svm_reg = LinearSVR(epsilon=1.5)>>> svm_reg.fit(X_train, y_train)LinearSVR(C=1.0, dual=True, epsilon=1.5, fit_intercept=True,intercept_scaling=1.0, loss='epsilon_insensitive', max_iter=1000, random_state=None, tol=0.0001, verbose=0)>>> predictions = svm_reg.predict(X_val)>>> predictionsarray([100.75090575, 109.08222631, 79.81544167, ..., 94.50700112, 55.65495607, 65.5248653 ])"
},
{
"code": null,
"e": 3296,
"s": 3030,
"text": "When this model was validated against a test set, an RMSE (root mean squared error) of 44.6 was obtained, along with an MAE (mean absolute error) of 29.5. With a mean ADR of 105, the model does show a degree of predictive power in estimating ADR values by customer."
},
{
"code": null,
"e": 3381,
"s": 3296,
"text": "Here is how we can use MimicExplainer for further interpretability of these results."
},
{
"code": null,
"e": 3610,
"s": 3381,
"text": "from interpret.ext.blackbox import MimicExplainerfrom interpret.ext.glassbox import LinearExplainableModelexplainer = MimicExplainer(svm_reg, X_train, LinearExplainableModel)"
},
{
"code": null,
"e": 3749,
"s": 3610,
"text": "The MimicExplainer is the black box model, while the LinearExplainableModel is being used as the global surrogate to this black box model."
},
{
"code": null,
"e": 3993,
"s": 3749,
"text": "Note that when running the model, it is possible to set augment_data = True if dealing with high-dimensional data, i.e. a situation where the number of columns exceeds the number of rows. This allows for oversampling of initialization samples."
},
{
"code": null,
"e": 4128,
"s": 3993,
"text": "However, given that this is not the case here, i.e. the dataset has many more rows than columns (features) — this will not be invoked."
},
{
"code": null,
"e": 4244,
"s": 4128,
"text": "Next, a global explanation is printed out which features the top K features and their values indicating importance:"
},
{
"code": null,
"e": 4575,
"s": 4244,
"text": "global_explanation = explainer.explain_global(X_val)sorted_global_importance_values = global_explanation.get_ranked_global_values()sorted_global_importance_names = global_explanation.get_ranked_global_names()dict(zip(sorted_global_importance_names, sorted_global_importance_values))global_explanation.get_feature_importance_dict()"
},
{
"code": null,
"e": 4595,
"s": 4575,
"text": "Here is the output:"
},
{
"code": null,
"e": 4760,
"s": 4595,
"text": "{3: 8.81513709127725, 7: 4.9616362270740995, 1: 4.959263897550327, 6: 2.593931464493208, 2: 0.9707145503848649, 5: 0.8455564214901589, 4: 0.505321879369921, 0: 0.0}"
},
{
"code": null,
"e": 4935,
"s": 4760,
"text": "From the above, feature number 3 (market segment), 7 (week of arrival), and 1 (booking cancellation) are indicated as the most important features in influencing customer ADR."
},
{
"code": null,
"e": 5109,
"s": 4935,
"text": "That said, what if we wish to isolate certain observations in the validation data? e.g. suppose that we only wish to determine feature importance for a select few customers?"
},
{
"code": null,
"e": 5129,
"s": 5109,
"text": "Here is an example."
},
{
"code": null,
"e": 5241,
"s": 5129,
"text": "From the validation set, features of importance and their values are determined for customers ordered 10 to 15."
},
{
"code": null,
"e": 5449,
"s": 5241,
"text": "local_explanation = explainer.explain_local(X_val[10:15])sorted_local_importance_names = local_explanation.get_ranked_local_names()sorted_local_importance_values = local_explanation.get_ranked_local_values()"
},
{
"code": null,
"e": 5514,
"s": 5449,
"text": "Here are the identified features of importance and their values:"
},
{
"code": null,
"e": 6187,
"s": 5514,
"text": ">>> sorted_local_importance_names[[1, 3, 2, 6, 5, 4, 0, 7], [7, 3, 2, 6, 5, 4, 1, 0], [6, 5, 4, 1, 0, 2, 7, 3], [6, 3, 5, 4, 1, 0, 2, 7], [3, 7, 6, 5, 4, 1, 0, 2]]>>> sorted_local_importance_values[[17.833762274315003, 9.1394041860457, 1.1694515257954607, 0.0, -0.0, -0.0, 0.0, -1.707920714865971], [9.955928069584559, 9.1394041860457, 1.1694515257954607, 0.0, -0.0, -0.0, 0.0, 0.0], [0.0, -0.0, -0.0, 0.0, 0.0, -0.5708037209239748, -11.288939359236048, -13.709106279068548], [19.017733248096473, 9.1394041860457, -0.0, -0.0, 0.0, 0.0, -0.7448292455959183, -5.040448938994693], [9.1394041860457, 6.623399845455836, 0.0, -0.0, -0.0, 0.0, 0.0, -0.9884649801366393]]"
},
{
"code": null,
"e": 6429,
"s": 6187,
"text": "This allows for isolation of feature importance by customer. For instance, feature 1 (booking cancellation) was the most influencing factor for customer 10, whereas feature 7 (week of arrival) was the most influencing factor for customer 11."
},
{
"code": null,
"e": 6567,
"s": 6429,
"text": "As mentioned, an XGBRegressor model was originally used in order to predict the number of weekly cancellations for the hotel in question."
},
{
"code": null,
"e": 6601,
"s": 6567,
"text": "The model was defined as follows:"
},
{
"code": null,
"e": 6730,
"s": 6601,
"text": "from xgboost import XGBRegressormodel = XGBRegressor(objective='reg:squarederror', n_estimators=1000)model.fit(X_train, Y_train)"
},
{
"code": null,
"e": 6769,
"s": 6730,
"text": "Here are the defined model parameters:"
},
{
"code": null,
"e": 7132,
"s": 6769,
"text": "As we can see from the above, there are numerous model parameters that could be modified in training the XGBRegressor. However, n_estimators is set to 1000 in this instance. This defines the number of trees in the XGBoost model.The objective is set to ‘reg:squarederror’, i.e. a regression with squared loss which penalizes errors on extreme values more heavily."
},
{
"code": null,
"e": 7281,
"s": 7132,
"text": "The RMSE yielded across the validation set was 50.14 along with an MAE of 38.63, which was lower than the mean value of 109 yielded across this set."
},
{
"code": null,
"e": 7411,
"s": 7281,
"text": "Using MimicExplainer, the interpretability of the model results can now be generated in a similar manner to the previous example:"
},
{
"code": null,
"e": 7638,
"s": 7411,
"text": "from interpret.ext.blackbox import MimicExplainerfrom interpret.ext.glassbox import LinearExplainableModelexplainer = MimicExplainer(model, X_train, LinearExplainableModel)"
},
{
"code": null,
"e": 8042,
"s": 7638,
"text": "For this purpose, we can identify the features that are the most important in determining the weekly hotel cancellation value at time t. However, given that this is a time series — the model is effectively indicating which lag value is most informative in predicting the cancellation for a particular week, e.g. is a 1-week lag, or a 3-week lag of most importance in influencing cancellations at time t?"
},
{
"code": null,
"e": 8373,
"s": 8042,
"text": "global_explanation = explainer.explain_global(X_val)sorted_global_importance_values = global_explanation.get_ranked_global_values()sorted_global_importance_names = global_explanation.get_ranked_global_names()dict(zip(sorted_global_importance_names, sorted_global_importance_values))global_explanation.get_feature_importance_dict()"
},
{
"code": null,
"e": 8395,
"s": 8373,
"text": "Here are the results:"
},
{
"code": null,
"e": 8507,
"s": 8395,
"text": "{3: 10.580821439553645, 2: 7.795196757642633, 1: 4.973377270096975, 4: 2.329894438847138, 0: 1.382442979985477}"
},
{
"code": null,
"e": 8647,
"s": 8507,
"text": "From the above, it is indicated that a lag for feature 3 (t-4) is of most importance when forecasting weekly hotel cancellations at time t."
},
{
"code": null,
"e": 8698,
"s": 8647,
"text": "However, what if we wish to isolate certain weeks?"
},
{
"code": null,
"e": 8832,
"s": 8698,
"text": "Taking the validation set, let us isolate the weeks across observations 8 to 13 (which corresponds to the year 2017, weeks 13 to 18)."
},
{
"code": null,
"e": 9039,
"s": 8832,
"text": "local_explanation = explainer.explain_local(X_val[8:13])sorted_local_importance_names = local_explanation.get_ranked_local_names()sorted_local_importance_values = local_explanation.get_ranked_local_values()"
},
{
"code": null,
"e": 9062,
"s": 9039,
"text": "Here are the findings:"
},
{
"code": null,
"e": 9727,
"s": 9062,
"text": ">>> sorted_local_importance_names[[4, 0, 2, 1, 3], [3, 4, 1, 0, 2], [3, 4, 1, 2, 0], [3, 2, 0, 4, 1], [2, 3, 4, 0, 1]]>>> sorted_local_importance_values[[1.2079747395122986, 0.655418467841234, -2.068988871651338, -5.677678197831921, -16.414222669030814], [5.880283637250306, 1.524120206263528, 1.157876862894971, -1.807324914948728, -11.282397723111108], [7.472748373413244, 7.056665874410039, 6.562734352772048, 3.8926286204696896, 0.353858053622055], [35.340881256264645, 4.976559073582604, 2.0627004008640695, 1.1289383728244913, -2.3393838658490202], [23.945342003058602, 5.4821674532095725, 1.287011106200106, -0.7518634651816014, -2.975249452893382]]"
},
{
"code": null,
"e": 10076,
"s": 9727,
"text": "Identifying the features of importance across the time series in this manner can potentially yield useful insights as to the importance of lagged values in predicting cancellations across different weeks. For instance, we can see that in predicting cancellations for week 13, the lag at t-5 (feature 4) was identified as the most important feature."
},
{
"code": null,
"e": 10189,
"s": 10076,
"text": "However, when predicting cancellations for week 18, the lag at t-3 (feature 2) was identified as most important."
},
{
"code": null,
"e": 10455,
"s": 10189,
"text": "As opposed to using a one size fits all forecasting model, interpretability can allow for identification of suitable forecasting methods for a particular point in time, and in turn allow for customisation of time series forecasting methods across different periods."
},
{
"code": null,
"e": 10668,
"s": 10455,
"text": "In this example, we have seen how interpretability can yield valuable insights when analysing machine learning output — which would be much more difficult when simply using black box ML models in their own right."
},
{
"code": null,
"e": 10696,
"s": 10668,
"text": "Specifically, we have seen:"
},
{
"code": null,
"e": 10808,
"s": 10696,
"text": "How MimicExplainer can be used as a global surrogate model to allow for interpretability of any black box model"
},
{
"code": null,
"e": 10857,
"s": 10808,
"text": "Use of MimicExplainer across regression problems"
},
{
"code": null,
"e": 10935,
"s": 10857,
"text": "How to interpret the results from MimicExplainer and gauge feature importance"
},
{
"code": null,
"e": 11090,
"s": 10935,
"text": "Many thanks for your time, and any questions or feedback are greatly appreciated. The relevant Jupyter Notebooks for the above examples can be found here."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.