title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
WSDL - <binding> Element | The <binding> element provides specific details on how a portType operation will actually be transmitted over the wire.
The bindings can be made available via multiple transports including HTTP GET, HTTP POST, or SOAP.
The bindings can be made available via multiple transports including HTTP GET, HTTP POST, or SOAP.
The bindings provide concrete information on what protocol is being used to transfer portType operations.
The bindings provide concrete information on what protocol is being used to transfer portType operations.
The bindings provide information where the service is located.
The bindings provide information where the service is located.
For SOAP protocol, the binding is <soap:binding>, and the transport is SOAP messages on top of HTTP protocol.
For SOAP protocol, the binding is <soap:binding>, and the transport is SOAP messages on top of HTTP protocol.
You can specify multiple bindings for a single portType.
You can specify multiple bindings for a single portType.
The binding element has two attributes : name and type attribute.
<binding name = "Hello_Binding" type = "tns:Hello_PortType">
The name attribute defines the name of the binding, and the type attribute points to the port for the binding, in this case the "tns:Hello_PortType" port.
WSDL 1.1 includes built-in extensions for SOAP 1.1. It allows you to specify SOAP specific details including SOAP headers, SOAP encoding styles, and the SOAPAction HTTP header. The SOAP extension elements include the following −
soap:binding
soap:operation
soap:body
This element indicates that the binding will be made available via SOAP. The style attribute indicates the overall style of the SOAP message format. A style value of rpc specifies an RPC format.
The transport attribute indicates the transport of the SOAP messages. The value http://schemas.xmlsoap.org/soap/http indicates the SOAP HTTP transport, whereas http://schemas.xmlsoap.org/soap/smtp indicates the SOAP SMTP transport.
This element indicates the binding of a specific operation to a specific SOAP implementation. The soapAction attribute specifies that the SOAPAction HTTP header be used for identifying the service.
This element enables you to specify the details of the input and output messages. In the case of HelloWorld, the body element specifies the SOAP encoding style and the namespace URN associated with the specified service.
Here is the piece of code from the Example chapter −
<binding name = "Hello_Binding" type = "tns:Hello_PortType">
<soap:binding style = "rpc" transport = "http://schemas.xmlsoap.org/soap/http"/>
<operation name = "sayHello">
<soap:operation soapAction = "sayHello"/>
<input>
<soap:body
encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/"
namespace = "urn:examples:helloservice" use = "encoded"/>
</input>
<output>
<soap:body
encodingStyle = "http://schemas.xmlsoap.org/soap/encoding/"
namespace = "urn:examples:helloservice" use = "encoded"/> | [
{
"code": null,
"e": 2058,
"s": 1938,
"text": "The <binding> element provides specific details on how a portType operation will actually be transmitted over the wire."
},
{
"code": null,
"e": 2157,
"s": 2058,
"text": "The bindings can be made available via multiple transports including HTTP GET, HTTP POST, or SOAP."
},
{
"code": null,
"e": 2256,
"s": 2157,
"text": "The bindings can be made available via multiple transports including HTTP GET, HTTP POST, or SOAP."
},
{
"code": null,
"e": 2362,
"s": 2256,
"text": "The bindings provide concrete information on what protocol is being used to transfer portType operations."
},
{
"code": null,
"e": 2468,
"s": 2362,
"text": "The bindings provide concrete information on what protocol is being used to transfer portType operations."
},
{
"code": null,
"e": 2531,
"s": 2468,
"text": "The bindings provide information where the service is located."
},
{
"code": null,
"e": 2594,
"s": 2531,
"text": "The bindings provide information where the service is located."
},
{
"code": null,
"e": 2704,
"s": 2594,
"text": "For SOAP protocol, the binding is <soap:binding>, and the transport is SOAP messages on top of HTTP protocol."
},
{
"code": null,
"e": 2814,
"s": 2704,
"text": "For SOAP protocol, the binding is <soap:binding>, and the transport is SOAP messages on top of HTTP protocol."
},
{
"code": null,
"e": 2871,
"s": 2814,
"text": "You can specify multiple bindings for a single portType."
},
{
"code": null,
"e": 2928,
"s": 2871,
"text": "You can specify multiple bindings for a single portType."
},
{
"code": null,
"e": 2994,
"s": 2928,
"text": "The binding element has two attributes : name and type attribute."
},
{
"code": null,
"e": 3056,
"s": 2994,
"text": "<binding name = \"Hello_Binding\" type = \"tns:Hello_PortType\">\n"
},
{
"code": null,
"e": 3211,
"s": 3056,
"text": "The name attribute defines the name of the binding, and the type attribute points to the port for the binding, in this case the \"tns:Hello_PortType\" port."
},
{
"code": null,
"e": 3440,
"s": 3211,
"text": "WSDL 1.1 includes built-in extensions for SOAP 1.1. It allows you to specify SOAP specific details including SOAP headers, SOAP encoding styles, and the SOAPAction HTTP header. The SOAP extension elements include the following −"
},
{
"code": null,
"e": 3453,
"s": 3440,
"text": "soap:binding"
},
{
"code": null,
"e": 3468,
"s": 3453,
"text": "soap:operation"
},
{
"code": null,
"e": 3478,
"s": 3468,
"text": "soap:body"
},
{
"code": null,
"e": 3673,
"s": 3478,
"text": "This element indicates that the binding will be made available via SOAP. The style attribute indicates the overall style of the SOAP message format. A style value of rpc specifies an RPC format."
},
{
"code": null,
"e": 3905,
"s": 3673,
"text": "The transport attribute indicates the transport of the SOAP messages. The value http://schemas.xmlsoap.org/soap/http indicates the SOAP HTTP transport, whereas http://schemas.xmlsoap.org/soap/smtp indicates the SOAP SMTP transport."
},
{
"code": null,
"e": 4103,
"s": 3905,
"text": "This element indicates the binding of a specific operation to a specific SOAP implementation. The soapAction attribute specifies that the SOAPAction HTTP header be used for identifying the service."
},
{
"code": null,
"e": 4324,
"s": 4103,
"text": "This element enables you to specify the details of the input and output messages. In the case of HelloWorld, the body element specifies the SOAP encoding style and the namespace URN associated with the specified service."
},
{
"code": null,
"e": 4377,
"s": 4324,
"text": "Here is the piece of code from the Example chapter −"
}
] |
Number of groups formed in a graph of friends | 31 Aug, 2021
Given n friends and their friendship relations, find the total number of groups that exist. And the number of ways of new groups that can be formed consisting of people from every existing group. If no relation is given for any person then that person has no group and singularly forms a group. If a is a friend of b and b is a friend of c, then a b and c form a group.
Examples:
Input : Number of people = 6
Relations : 1 - 2, 3 - 4
and 5 - 6
Output: Number of existing Groups = 3
Number of new groups that can
be formed = 8
Explanation: The existing groups are
(1, 2), (3, 4), (5, 6). The new 8 groups
that can be formed by considering a
member of every group are (1, 3, 5),
(1, 3, 6), (1, 4, 5), (1, 4, 6), (2,
3, 5), (2, 3, 6), (2, 4, 5) and (2, 4,
6).
Input: Number of people = 4
Relations : 1 - 2 and 2 - 3
Output: Number of existing Groups = 2
Number of new groups that can
be formed = 3
Explanation: The existing groups are
(1, 2, 3) and (4). The new groups that
can be formed by considering a member
of every group are (1, 4), (2, 4), (3, 4).
To count number of groups, we need to simply count connected components in the given undirected graph. Counting connected components can be easily done using DFS or BFS. Since this is an undirected graph, the number of times a Depth First Search starts from an unvisited vertex for every friend is equal to the number of groups formed.
To count number of ways in which we form new groups can be done using simply formula which is (N1)*(N2)*....(Nn) where Ni is the no of people in i-th group.
C++
Java
Python3
// C++ program to count number of existing// groups and number of new groups that can// be formed.#include <bits/stdc++.h>using namespace std; class Graph { int V; // No. of vertices // Pointer to an array containing // adjacency lists list<int>* adj; int countUtil(int v, bool visited[]);public: Graph(int V); // Constructor // function to add an edge to graph void addRelation(int v, int w); void countGroups();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} // Adds a relation as a two way edge of// undirected graph.void Graph::addRelation(int v, int w){ // Since indexing is 0 based, reducing // edge numbers by 1. v--; w--; adj[v].push_back(w); adj[w].push_back(v);} // Returns count of not visited nodes reachable// from v using DFS.int Graph::countUtil(int v, bool visited[]){ int count = 1; visited[v] = true; for (auto i=adj[v].begin(); i!=adj[v].end(); ++i) if (!visited[*i]) count = count + countUtil(*i, visited); return count; } // A DFS based function to Count number of// existing groups and number of new groups// that can be formed using a member of// every group.void Graph::countGroups(){ // Mark all the vertices as not visited bool* visited = new bool[V]; memset(visited, 0, V*sizeof(int)); int existing_groups = 0, new_groups = 1; for (int i = 0; i < V; i++) { // If not in any group. if (visited[i] == false) { existing_groups++; // Number of new groups that // can be formed. new_groups = new_groups * countUtil(i, visited); } } if (existing_groups == 1) new_groups = 0; cout << "No. of existing groups are " << existing_groups << endl; cout << "No. of new groups that can be" " formed are " << new_groups << endl;} // Driver codeint main(){ int n = 6; // Create a graph given in the above diagram Graph g(n); // total 6 people g.addRelation(1, 2); // 1 and 2 are friends g.addRelation(3, 4); // 3 and 4 are friends g.addRelation(5, 6); // 5 and 6 are friends g.countGroups(); return 0;}
// Java program to count number of// existing groups and number of// new groups that can be formed.import java.util.*;import java.io.*; class Graph{ // No. of verticesprivate int V; // Array of lists for Adjacency// List Representationprivate LinkedList<Integer> adj[]; // Constructor@SuppressWarnings("unchecked") Graph(int v){ V = v; adj = new LinkedList[V]; for(int i = 0; i < V; i++) { adj[i] = new LinkedList(); }} // Adds a relation as a two way edge of// undirected graph.public void addRelation(int v, int w){ // Since indexing is 0 based, reducing // edge numbers by 1. v--; w--; adj[v].add(w); adj[w].add(v);} // Returns count of not visited nodes// reachable from v using DFS.int countUtil(int v, boolean visited[]){ int count = 1; visited[v] = true; // 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]) count = count + countUtil(n, visited); } return count;} // A DFS based function to Count number of// existing groups and number of new groups// that can be formed using a member of// every group.void countGroups(){ // Mark all the vertices as not // visited(set as false by default // in java) boolean visited[] = new boolean[V]; int existing_groups = 0, new_groups = 1; for(int i = 0; i < V; i++) { // If not in any group. if (visited[i] == false) { existing_groups++; // Number of new groups that // can be formed. new_groups = new_groups * countUtil(i, visited); } } if (existing_groups == 1) new_groups = 0; System.out.println("No. of existing groups are " + existing_groups); System.out.println("No. of new groups that " + "can be formed are " + new_groups);} // Driver codepublic static void main(String[] args){ int n = 6; // Create a graph given in // the above diagram Graph g = new Graph(n); // total 6 people g.addRelation(1, 2); // 1 and 2 are friends g.addRelation(3, 4); // 3 and 4 are friends g.addRelation(5, 6); // 5 and 6 are friends g.countGroups();}} // This code is contributed by MuskanKalra1
# Python3 program to count number of# existing groups and number of new# groups that can be formed.class Graph: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] # Adds a relation as a two way # edge of undirected graph. def addRelation(self, v, w): # Since indexing is 0 based, # reducing edge numbers by 1. v -= 1 w -= 1 self.adj[v].append(w) self.adj[w].append(v) # Returns count of not visited # nodes reachable from v using DFS. def countUtil(self, v, visited): count = 1 visited[v] = True i = 0 while i != len(self.adj[v]): if (not visited[self.adj[v][i]]): count = count + self.countUtil(self.adj[v][i], visited) i += 1 return count # A DFS based function to Count number # of existing groups and number of new # groups that can be formed using a # member of every group. def countGroups(self): # Mark all the vertices as # not visited visited = [0] * self.V existing_groups = 0 new_groups = 1 for i in range(self.V): # If not in any group. if (visited[i] == False): existing_groups += 1 # Number of new groups that # can be formed. new_groups = (new_groups * self.countUtil(i, visited)) if (existing_groups == 1): new_groups = 0 print("No. of existing groups are", existing_groups) print("No. of new groups that", "can be formed are", new_groups) # Driver codeif __name__ == '__main__': n = 6 # Create a graph given in the above diagram g = Graph(n) # total 6 people g.addRelation(1, 2) # 1 and 2 are friends g.addRelation(3, 4) # 3 and 4 are friends g.addRelation(5, 6) # 5 and 6 are friends g.countGroups() # This code is contributed by PranchalK
Output:
No. of existing groups are 3
No. of new groups that can be formed are 8
Time complexity: O(N + R) where N is the number of people and R is the number of relations.
This article is contributed by Raj. 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
Akanksha_Rai
MuskanKalra1
nishchhal125
DFS
graph-connectivity
Graph
DFS
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 424,
"s": 54,
"text": "Given n friends and their friendship relations, find the total number of groups that exist. And the number of ways of new groups that can be formed consisting of people from every existing group. If no relation is given for any person then that person has no group and singularly forms a group. If a is a friend of b and b is a friend of c, then a b and c form a group."
},
{
"code": null,
"e": 436,
"s": 424,
"text": "Examples: "
},
{
"code": null,
"e": 1191,
"s": 436,
"text": "Input : Number of people = 6 \n Relations : 1 - 2, 3 - 4 \n and 5 - 6 \nOutput: Number of existing Groups = 3\n Number of new groups that can\n be formed = 8\nExplanation: The existing groups are \n(1, 2), (3, 4), (5, 6). The new 8 groups \nthat can be formed by considering a \nmember of every group are (1, 3, 5), \n(1, 3, 6), (1, 4, 5), (1, 4, 6), (2, \n3, 5), (2, 3, 6), (2, 4, 5) and (2, 4,\n6). \n\nInput: Number of people = 4 \n Relations : 1 - 2 and 2 - 3 \nOutput: Number of existing Groups = 2\n Number of new groups that can\n be formed = 3\nExplanation: The existing groups are \n(1, 2, 3) and (4). The new groups that \ncan be formed by considering a member\nof every group are (1, 4), (2, 4), (3, 4)."
},
{
"code": null,
"e": 1528,
"s": 1191,
"text": "To count number of groups, we need to simply count connected components in the given undirected graph. Counting connected components can be easily done using DFS or BFS. Since this is an undirected graph, the number of times a Depth First Search starts from an unvisited vertex for every friend is equal to the number of groups formed. "
},
{
"code": null,
"e": 1686,
"s": 1528,
"text": "To count number of ways in which we form new groups can be done using simply formula which is (N1)*(N2)*....(Nn) where Ni is the no of people in i-th group. "
},
{
"code": null,
"e": 1690,
"s": 1686,
"text": "C++"
},
{
"code": null,
"e": 1695,
"s": 1690,
"text": "Java"
},
{
"code": null,
"e": 1703,
"s": 1695,
"text": "Python3"
},
{
"code": "// C++ program to count number of existing// groups and number of new groups that can// be formed.#include <bits/stdc++.h>using namespace std; class Graph { int V; // No. of vertices // Pointer to an array containing // adjacency lists list<int>* adj; int countUtil(int v, bool visited[]);public: Graph(int V); // Constructor // function to add an edge to graph void addRelation(int v, int w); void countGroups();}; Graph::Graph(int V){ this->V = V; adj = new list<int>[V];} // Adds a relation as a two way edge of// undirected graph.void Graph::addRelation(int v, int w){ // Since indexing is 0 based, reducing // edge numbers by 1. v--; w--; adj[v].push_back(w); adj[w].push_back(v);} // Returns count of not visited nodes reachable// from v using DFS.int Graph::countUtil(int v, bool visited[]){ int count = 1; visited[v] = true; for (auto i=adj[v].begin(); i!=adj[v].end(); ++i) if (!visited[*i]) count = count + countUtil(*i, visited); return count; } // A DFS based function to Count number of// existing groups and number of new groups// that can be formed using a member of// every group.void Graph::countGroups(){ // Mark all the vertices as not visited bool* visited = new bool[V]; memset(visited, 0, V*sizeof(int)); int existing_groups = 0, new_groups = 1; for (int i = 0; i < V; i++) { // If not in any group. if (visited[i] == false) { existing_groups++; // Number of new groups that // can be formed. new_groups = new_groups * countUtil(i, visited); } } if (existing_groups == 1) new_groups = 0; cout << \"No. of existing groups are \" << existing_groups << endl; cout << \"No. of new groups that can be\" \" formed are \" << new_groups << endl;} // Driver codeint main(){ int n = 6; // Create a graph given in the above diagram Graph g(n); // total 6 people g.addRelation(1, 2); // 1 and 2 are friends g.addRelation(3, 4); // 3 and 4 are friends g.addRelation(5, 6); // 5 and 6 are friends g.countGroups(); return 0;}",
"e": 3939,
"s": 1703,
"text": null
},
{
"code": "// Java program to count number of// existing groups and number of// new groups that can be formed.import java.util.*;import java.io.*; class Graph{ // No. of verticesprivate int V; // Array of lists for Adjacency// List Representationprivate LinkedList<Integer> adj[]; // Constructor@SuppressWarnings(\"unchecked\") Graph(int v){ V = v; adj = new LinkedList[V]; for(int i = 0; i < V; i++) { adj[i] = new LinkedList(); }} // Adds a relation as a two way edge of// undirected graph.public void addRelation(int v, int w){ // Since indexing is 0 based, reducing // edge numbers by 1. v--; w--; adj[v].add(w); adj[w].add(v);} // Returns count of not visited nodes// reachable from v using DFS.int countUtil(int v, boolean visited[]){ int count = 1; visited[v] = true; // 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]) count = count + countUtil(n, visited); } return count;} // A DFS based function to Count number of// existing groups and number of new groups// that can be formed using a member of// every group.void countGroups(){ // Mark all the vertices as not // visited(set as false by default // in java) boolean visited[] = new boolean[V]; int existing_groups = 0, new_groups = 1; for(int i = 0; i < V; i++) { // If not in any group. if (visited[i] == false) { existing_groups++; // Number of new groups that // can be formed. new_groups = new_groups * countUtil(i, visited); } } if (existing_groups == 1) new_groups = 0; System.out.println(\"No. of existing groups are \" + existing_groups); System.out.println(\"No. of new groups that \" + \"can be formed are \" + new_groups);} // Driver codepublic static void main(String[] args){ int n = 6; // Create a graph given in // the above diagram Graph g = new Graph(n); // total 6 people g.addRelation(1, 2); // 1 and 2 are friends g.addRelation(3, 4); // 3 and 4 are friends g.addRelation(5, 6); // 5 and 6 are friends g.countGroups();}} // This code is contributed by MuskanKalra1",
"e": 6341,
"s": 3939,
"text": null
},
{
"code": "# Python3 program to count number of# existing groups and number of new# groups that can be formed.class Graph: def __init__(self, V): self.V = V self.adj = [[] for i in range(V)] # Adds a relation as a two way # edge of undirected graph. def addRelation(self, v, w): # Since indexing is 0 based, # reducing edge numbers by 1. v -= 1 w -= 1 self.adj[v].append(w) self.adj[w].append(v) # Returns count of not visited # nodes reachable from v using DFS. def countUtil(self, v, visited): count = 1 visited[v] = True i = 0 while i != len(self.adj[v]): if (not visited[self.adj[v][i]]): count = count + self.countUtil(self.adj[v][i], visited) i += 1 return count # A DFS based function to Count number # of existing groups and number of new # groups that can be formed using a # member of every group. def countGroups(self): # Mark all the vertices as # not visited visited = [0] * self.V existing_groups = 0 new_groups = 1 for i in range(self.V): # If not in any group. if (visited[i] == False): existing_groups += 1 # Number of new groups that # can be formed. new_groups = (new_groups * self.countUtil(i, visited)) if (existing_groups == 1): new_groups = 0 print(\"No. of existing groups are\", existing_groups) print(\"No. of new groups that\", \"can be formed are\", new_groups) # Driver codeif __name__ == '__main__': n = 6 # Create a graph given in the above diagram g = Graph(n) # total 6 people g.addRelation(1, 2) # 1 and 2 are friends g.addRelation(3, 4) # 3 and 4 are friends g.addRelation(5, 6) # 5 and 6 are friends g.countGroups() # This code is contributed by PranchalK",
"e": 8467,
"s": 6341,
"text": null
},
{
"code": null,
"e": 8476,
"s": 8467,
"text": "Output: "
},
{
"code": null,
"e": 8548,
"s": 8476,
"text": "No. of existing groups are 3\nNo. of new groups that can be formed are 8"
},
{
"code": null,
"e": 8640,
"s": 8548,
"text": "Time complexity: O(N + R) where N is the number of people and R is the number of relations."
},
{
"code": null,
"e": 9052,
"s": 8640,
"text": "This article is contributed by Raj. 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": 9068,
"s": 9052,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 9081,
"s": 9068,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 9094,
"s": 9081,
"text": "MuskanKalra1"
},
{
"code": null,
"e": 9107,
"s": 9094,
"text": "nishchhal125"
},
{
"code": null,
"e": 9111,
"s": 9107,
"text": "DFS"
},
{
"code": null,
"e": 9130,
"s": 9111,
"text": "graph-connectivity"
},
{
"code": null,
"e": 9136,
"s": 9130,
"text": "Graph"
},
{
"code": null,
"e": 9140,
"s": 9136,
"text": "DFS"
},
{
"code": null,
"e": 9146,
"s": 9140,
"text": "Graph"
}
] |
How to round elements of the NumPy array to the nearest integer? | 08 Jun, 2022
Prerequisites: Python NumPy
In this article, let’s discuss how to round elements of the NumPy array to the nearest integer. numpy.rint() function of Python that can convert the elements of an array to the nearest integer.
Syntax: numpy.rint(x, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj]) = <ufunc ‘rint’>
Example 1:
Python3
import numpy as n # create arrayy = n.array([0.2, 0.3, 0.4, 0.5, 0.6, 0.7])print("Original array:", end=" ")print(y) # round to nearest integery = n.rint(y)print("After rounding off:", end=" ")print(y)
Output:
Example 2:
Python3
import numpy as n # create arrayy = n.array([-0.2, 0.7, -1.4, -4.5, -7.6, -19.7])print("Original array:", end=" ")print(y) # round to nearest integery = n.rint(y)print("After rounding off:", end=" ")print(y)
Output:
simmytarika5
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 56,
"s": 28,
"text": "Prerequisites: Python NumPy"
},
{
"code": null,
"e": 250,
"s": 56,
"text": "In this article, let’s discuss how to round elements of the NumPy array to the nearest integer. numpy.rint() function of Python that can convert the elements of an array to the nearest integer."
},
{
"code": null,
"e": 394,
"s": 250,
"text": "Syntax: numpy.rint(x, /, out=None, *, where=True, casting=’same_kind’, order=’K’, dtype=None, subok=True[, signature, extobj]) = <ufunc ‘rint’>"
},
{
"code": null,
"e": 405,
"s": 394,
"text": "Example 1:"
},
{
"code": null,
"e": 413,
"s": 405,
"text": "Python3"
},
{
"code": "import numpy as n # create arrayy = n.array([0.2, 0.3, 0.4, 0.5, 0.6, 0.7])print(\"Original array:\", end=\" \")print(y) # round to nearest integery = n.rint(y)print(\"After rounding off:\", end=\" \")print(y)",
"e": 615,
"s": 413,
"text": null
},
{
"code": null,
"e": 623,
"s": 615,
"text": "Output:"
},
{
"code": null,
"e": 634,
"s": 623,
"text": "Example 2:"
},
{
"code": null,
"e": 642,
"s": 634,
"text": "Python3"
},
{
"code": "import numpy as n # create arrayy = n.array([-0.2, 0.7, -1.4, -4.5, -7.6, -19.7])print(\"Original array:\", end=\" \")print(y) # round to nearest integery = n.rint(y)print(\"After rounding off:\", end=\" \")print(y)",
"e": 850,
"s": 642,
"text": null
},
{
"code": null,
"e": 858,
"s": 850,
"text": "Output:"
},
{
"code": null,
"e": 871,
"s": 858,
"text": "simmytarika5"
},
{
"code": null,
"e": 906,
"s": 871,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 919,
"s": 906,
"text": "Python-numpy"
},
{
"code": null,
"e": 926,
"s": 919,
"text": "Python"
},
{
"code": null,
"e": 1024,
"s": 926,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1056,
"s": 1024,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1083,
"s": 1056,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1104,
"s": 1083,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1127,
"s": 1104,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1158,
"s": 1127,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1214,
"s": 1158,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1256,
"s": 1214,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1298,
"s": 1256,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1337,
"s": 1298,
"text": "Python | Get unique values from a list"
}
] |
Smallest number to make Array sum at most K by dividing each element | 05 Nov, 2021
Given an array arr[] of size N and a number K, the task is to find the smallest number M such that the sum of the array becomes lesser than or equal to the number K when every element of that array is divided by the number M.Note: Each result of the division is rounded to the nearest integer greater than or equal to that element. For example: 10/3 = 4 and 6/2 = 3
Examples:
Input: arr[] = {2, 3, 4, 9}, K = 6 Output: 4 Explanation: When every element is divided by 4- 2/4 + 3/4 + 4/4 + 9/4 = 1 + 1 + 1 + 3 = 6 When every element is divided by 3- 2/3 + 3/3 + 4/3 + 9/3 = 1 + 1 + 2 + 3 = 7 which is greater than K. Hence, the smallest integer which makes the sum less than or equal to K = 6 is 4. Input: arr[] = {5, 6, 7, 8}, K = 4 Output: 8
Naive Approach: The naive approach for this problem is to start from 1 and for every number, divide every element in the array and check if the sum is less than or equal to K. The first number at which this condition satisfies is the required answer. Time complexity: O(N * M), where M is the number to be found and N is the size of the array.
Efficient Approach: The idea is to use the concept of Binary Search.
Input the array.On assuming that the maximum possible answer is 109, initialize the max as 109 and the min as 1.Perform the Binary Search on this range and for every number, check if the sum is less than or equal to K.If the sum is less than K, then an answer might exist for a number that is smaller than this. So, continue and check for the numbers less than that counter.If the sum is greater than K, then the number M is greater than the current counter. So, continue and check for the numbers greater than that counter.
Input the array.
On assuming that the maximum possible answer is 109, initialize the max as 109 and the min as 1.
Perform the Binary Search on this range and for every number, check if the sum is less than or equal to K.
If the sum is less than K, then an answer might exist for a number that is smaller than this. So, continue and check for the numbers less than that counter.
If the sum is greater than K, then the number M is greater than the current counter. So, continue and check for the numbers greater than that counter.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that number #include <bits/stdc++.h>using namespace std; // Function to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that numberint findMinDivisor(int arr[], int n, int limit){ // Binary search between 1 and 10^9 int low = 0, high = 1e9; while (low < high) { int mid = (low + high) / 2; int sum = 0; // Calculating the new sum after // dividing every element by mid for (int i = 0; i < n; i++) { sum += ceil((double)arr[i] / (double)mid); } // If after dividing by mid, // if the new sum is less than or // equal to limit move low to mid+1 if (sum <= limit) high = mid; else // Else, move mid + 1 to high low = mid + 1; } // Returning the minimum number return low;} // Driver codeint main(){ int arr[] = { 2, 3, 4, 9 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 6; cout << findMinDivisor(arr, N, K);}
// Java program to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that numberimport java.util.*; class GFG{ // Function to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that numberstatic int findMinDivisor(int arr[], int n, int limit){ // Binary search between 1 and 10^9 int low = 0, high = 1000000000; while (low < high) { int mid = (low + high) / 2; int sum = 0; // Calculating the new sum after // dividing every element by mid for(int i = 0; i < n; i++) { sum += Math.ceil((double) arr[i] / (double) mid); } // If after dividing by mid, // if the new sum is less than or // equal to limit move low to mid+1 if (sum <= limit) high = mid; else // Else, move mid + 1 to high low = mid + 1; } // Returning the minimum number return low;} // Driver Codepublic static void main(String args[]){ int arr[] = { 2, 3, 4, 9 }; int N = arr.length; int K = 6; System.out.println( findMinDivisor(arr, N, K));}} // This code is contributed by rutvik_56
# Python3 program to find the smallest# number such that the sum of the# array becomes less than or equal# to K when every element of the# array is divided by that numberfrom math import ceil # Function to find the smallest# number such that the sum of the# array becomes less than or equal# to K when every element of the# array is divided by that numberdef findMinDivisor(arr, n, limit): # Binary search between 1 and 10^9 low = 0 high = 10 ** 9 while (low < high): mid = (low + high) // 2 sum = 0 # Calculating the new sum after # dividing every element by mid for i in range(n): sum += ceil(arr[i] / mid) # If after dividing by mid, # if the new sum is less than or # equal to limit move low to mid+1 if (sum <= limit): high = mid else: # Else, move mid + 1 to high low = mid + 1 # Returning the minimum number return low # Driver codeif __name__ == '__main__': arr= [ 2, 3, 4, 9 ] N = len(arr) K = 6 print(findMinDivisor(arr, N, K)) # This code is contributed by mohit kumar 29
// C# program to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that numberusing System; class GFG{ // Function to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that numberstatic int findMinDivisor(int []arr, int n, int limit){ // Binary search between 1 and 10^9 int low = 0, high = 1000000000; while (low < high) { int mid = (low + high) / 2; int sum = 0; // Calculating the new sum after // dividing every element by mid for(int i = 0; i < n; i++) { sum += (int)Math.Ceiling((double) arr[i] / (double) mid); } // If after dividing by mid, // if the new sum is less than or // equal to limit move low to mid+1 if (sum <= limit) { high = mid; } else { // Else, move mid + 1 to high low = mid + 1; } } // Returning the minimum number return low;} // Driver Codepublic static void Main(String []args){ int []arr = { 2, 3, 4, 9 }; int N = arr.Length; int K = 6; Console.WriteLine(findMinDivisor(arr, N, K));}} // This code is contributed by 29AjayKumar
<script>// Program program to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that number // Function to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that numberfunction findMinDivisor(arr, n, limit){ // Binary search between 1 and 10^9 let low = 0, high = 1000000000; while (low < high) { let mid = Math.floor((low + high) / 2); let sum = 0; // Calculating the new sum after // dividing every element by mid for(let i = 0; i < n; i++) { sum += Math.ceil( arr[i] / mid); } // If after dividing by mid, // if the new sum is less than or // equal to limit move low to mid+1 if (sum <= limit) high = mid; else // Else, move mid + 1 to high low = mid + 1; } // Returning the minimum number return low;} // Driver Code let arr = [ 2, 3, 4, 9 ]; let N = arr.length; let K = 6; document.write( findMinDivisor(arr, N, K)); </script>
4
Time Complexity: O(N * 30), where N is the size of the array because finding any number between 1 and 109 takes at most 30 operations in binary search. Auxiliary Space: O(1)
mohit kumar 29
rutvik_56
29AjayKumar
target_2
rishavmahato348
Binary Search
divisors
Arrays
Mathematical
Arrays
Mathematical
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Coin Change | DP-7 | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n05 Nov, 2021"
},
{
"code": null,
"e": 420,
"s": 54,
"text": "Given an array arr[] of size N and a number K, the task is to find the smallest number M such that the sum of the array becomes lesser than or equal to the number K when every element of that array is divided by the number M.Note: Each result of the division is rounded to the nearest integer greater than or equal to that element. For example: 10/3 = 4 and 6/2 = 3"
},
{
"code": null,
"e": 430,
"s": 420,
"text": "Examples:"
},
{
"code": null,
"e": 798,
"s": 430,
"text": "Input: arr[] = {2, 3, 4, 9}, K = 6 Output: 4 Explanation: When every element is divided by 4- 2/4 + 3/4 + 4/4 + 9/4 = 1 + 1 + 1 + 3 = 6 When every element is divided by 3- 2/3 + 3/3 + 4/3 + 9/3 = 1 + 1 + 2 + 3 = 7 which is greater than K. Hence, the smallest integer which makes the sum less than or equal to K = 6 is 4. Input: arr[] = {5, 6, 7, 8}, K = 4 Output: 8 "
},
{
"code": null,
"e": 1143,
"s": 798,
"text": "Naive Approach: The naive approach for this problem is to start from 1 and for every number, divide every element in the array and check if the sum is less than or equal to K. The first number at which this condition satisfies is the required answer. Time complexity: O(N * M), where M is the number to be found and N is the size of the array. "
},
{
"code": null,
"e": 1214,
"s": 1143,
"text": "Efficient Approach: The idea is to use the concept of Binary Search. "
},
{
"code": null,
"e": 1739,
"s": 1214,
"text": "Input the array.On assuming that the maximum possible answer is 109, initialize the max as 109 and the min as 1.Perform the Binary Search on this range and for every number, check if the sum is less than or equal to K.If the sum is less than K, then an answer might exist for a number that is smaller than this. So, continue and check for the numbers less than that counter.If the sum is greater than K, then the number M is greater than the current counter. So, continue and check for the numbers greater than that counter."
},
{
"code": null,
"e": 1756,
"s": 1739,
"text": "Input the array."
},
{
"code": null,
"e": 1853,
"s": 1756,
"text": "On assuming that the maximum possible answer is 109, initialize the max as 109 and the min as 1."
},
{
"code": null,
"e": 1960,
"s": 1853,
"text": "Perform the Binary Search on this range and for every number, check if the sum is less than or equal to K."
},
{
"code": null,
"e": 2117,
"s": 1960,
"text": "If the sum is less than K, then an answer might exist for a number that is smaller than this. So, continue and check for the numbers less than that counter."
},
{
"code": null,
"e": 2268,
"s": 2117,
"text": "If the sum is greater than K, then the number M is greater than the current counter. So, continue and check for the numbers greater than that counter."
},
{
"code": null,
"e": 2321,
"s": 2268,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 2325,
"s": 2321,
"text": "C++"
},
{
"code": null,
"e": 2330,
"s": 2325,
"text": "Java"
},
{
"code": null,
"e": 2338,
"s": 2330,
"text": "Python3"
},
{
"code": null,
"e": 2341,
"s": 2338,
"text": "C#"
},
{
"code": null,
"e": 2352,
"s": 2341,
"text": "Javascript"
},
{
"code": "// C++ program to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that number #include <bits/stdc++.h>using namespace std; // Function to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that numberint findMinDivisor(int arr[], int n, int limit){ // Binary search between 1 and 10^9 int low = 0, high = 1e9; while (low < high) { int mid = (low + high) / 2; int sum = 0; // Calculating the new sum after // dividing every element by mid for (int i = 0; i < n; i++) { sum += ceil((double)arr[i] / (double)mid); } // If after dividing by mid, // if the new sum is less than or // equal to limit move low to mid+1 if (sum <= limit) high = mid; else // Else, move mid + 1 to high low = mid + 1; } // Returning the minimum number return low;} // Driver codeint main(){ int arr[] = { 2, 3, 4, 9 }; int N = sizeof(arr) / sizeof(arr[0]); int K = 6; cout << findMinDivisor(arr, N, K);}",
"e": 3595,
"s": 2352,
"text": null
},
{
"code": "// Java program to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that numberimport java.util.*; class GFG{ // Function to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that numberstatic int findMinDivisor(int arr[], int n, int limit){ // Binary search between 1 and 10^9 int low = 0, high = 1000000000; while (low < high) { int mid = (low + high) / 2; int sum = 0; // Calculating the new sum after // dividing every element by mid for(int i = 0; i < n; i++) { sum += Math.ceil((double) arr[i] / (double) mid); } // If after dividing by mid, // if the new sum is less than or // equal to limit move low to mid+1 if (sum <= limit) high = mid; else // Else, move mid + 1 to high low = mid + 1; } // Returning the minimum number return low;} // Driver Codepublic static void main(String args[]){ int arr[] = { 2, 3, 4, 9 }; int N = arr.length; int K = 6; System.out.println( findMinDivisor(arr, N, K));}} // This code is contributed by rutvik_56",
"e": 4982,
"s": 3595,
"text": null
},
{
"code": "# Python3 program to find the smallest# number such that the sum of the# array becomes less than or equal# to K when every element of the# array is divided by that numberfrom math import ceil # Function to find the smallest# number such that the sum of the# array becomes less than or equal# to K when every element of the# array is divided by that numberdef findMinDivisor(arr, n, limit): # Binary search between 1 and 10^9 low = 0 high = 10 ** 9 while (low < high): mid = (low + high) // 2 sum = 0 # Calculating the new sum after # dividing every element by mid for i in range(n): sum += ceil(arr[i] / mid) # If after dividing by mid, # if the new sum is less than or # equal to limit move low to mid+1 if (sum <= limit): high = mid else: # Else, move mid + 1 to high low = mid + 1 # Returning the minimum number return low # Driver codeif __name__ == '__main__': arr= [ 2, 3, 4, 9 ] N = len(arr) K = 6 print(findMinDivisor(arr, N, K)) # This code is contributed by mohit kumar 29",
"e": 6133,
"s": 4982,
"text": null
},
{
"code": "// C# program to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that numberusing System; class GFG{ // Function to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that numberstatic int findMinDivisor(int []arr, int n, int limit){ // Binary search between 1 and 10^9 int low = 0, high = 1000000000; while (low < high) { int mid = (low + high) / 2; int sum = 0; // Calculating the new sum after // dividing every element by mid for(int i = 0; i < n; i++) { sum += (int)Math.Ceiling((double) arr[i] / (double) mid); } // If after dividing by mid, // if the new sum is less than or // equal to limit move low to mid+1 if (sum <= limit) { high = mid; } else { // Else, move mid + 1 to high low = mid + 1; } } // Returning the minimum number return low;} // Driver Codepublic static void Main(String []args){ int []arr = { 2, 3, 4, 9 }; int N = arr.Length; int K = 6; Console.WriteLine(findMinDivisor(arr, N, K));}} // This code is contributed by 29AjayKumar",
"e": 7554,
"s": 6133,
"text": null
},
{
"code": "<script>// Program program to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that number // Function to find the smallest// number such that the sum of the// array becomes less than or equal// to K when every element of the// array is divided by that numberfunction findMinDivisor(arr, n, limit){ // Binary search between 1 and 10^9 let low = 0, high = 1000000000; while (low < high) { let mid = Math.floor((low + high) / 2); let sum = 0; // Calculating the new sum after // dividing every element by mid for(let i = 0; i < n; i++) { sum += Math.ceil( arr[i] / mid); } // If after dividing by mid, // if the new sum is less than or // equal to limit move low to mid+1 if (sum <= limit) high = mid; else // Else, move mid + 1 to high low = mid + 1; } // Returning the minimum number return low;} // Driver Code let arr = [ 2, 3, 4, 9 ]; let N = arr.length; let K = 6; document.write( findMinDivisor(arr, N, K)); </script>",
"e": 8805,
"s": 7554,
"text": null
},
{
"code": null,
"e": 8807,
"s": 8805,
"text": "4"
},
{
"code": null,
"e": 8983,
"s": 8809,
"text": "Time Complexity: O(N * 30), where N is the size of the array because finding any number between 1 and 109 takes at most 30 operations in binary search. Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8998,
"s": 8983,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 9008,
"s": 8998,
"text": "rutvik_56"
},
{
"code": null,
"e": 9020,
"s": 9008,
"text": "29AjayKumar"
},
{
"code": null,
"e": 9029,
"s": 9020,
"text": "target_2"
},
{
"code": null,
"e": 9045,
"s": 9029,
"text": "rishavmahato348"
},
{
"code": null,
"e": 9059,
"s": 9045,
"text": "Binary Search"
},
{
"code": null,
"e": 9068,
"s": 9059,
"text": "divisors"
},
{
"code": null,
"e": 9075,
"s": 9068,
"text": "Arrays"
},
{
"code": null,
"e": 9088,
"s": 9075,
"text": "Mathematical"
},
{
"code": null,
"e": 9095,
"s": 9088,
"text": "Arrays"
},
{
"code": null,
"e": 9108,
"s": 9095,
"text": "Mathematical"
},
{
"code": null,
"e": 9122,
"s": 9108,
"text": "Binary Search"
},
{
"code": null,
"e": 9220,
"s": 9122,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 9252,
"s": 9220,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 9277,
"s": 9252,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 9324,
"s": 9277,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 9388,
"s": 9324,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9419,
"s": 9388,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 9449,
"s": 9419,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 9492,
"s": 9449,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 9552,
"s": 9492,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 9567,
"s": 9552,
"text": "C++ Data Types"
}
] |
How to run two async functions forever – Python | 17 May, 2021
Asynchronous programming is a type of programming in which we can execute more than one task without blocking the Main task (function). In Python, there are many ways to execute more than one function concurrently, one of the ways is by using asyncio. Async programming allows you to write concurrent code that runs in a single thread.
Note: Asyncio doesn’t use threads or multiprocessing to make the program Asynchronous.
Coroutine: Coroutines are a general control structure whereby flow control is cooperatively passed between two different routines without returning. In asyncio Coroutine can be created by using async keyword before def.
async def speak_async():
for i in range(100):
print("Hello I'm Abhishek, writer on GFG")
If you try to run an async function directly you will get a runtime warning:
RuntimeWarning: coroutine ‘speak_async’ was never awaited
speak_async()
To run an async function (coroutine) you have to call it using an Event Loop.
Event Loops: You can think of Event Loop as functions to run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses.
Example 1: Event Loop example to run async Function to run a single async function:
Python3
import asyncio async def function_asyc(): for i in range(5): print("Hello, I'm Abhishek") print("GFG is Great") return 0 # to run the above function we'll # use Event Loops these are low # level functions to run async functionsloop = asyncio.get_event_loop()loop.run_until_complete(function_asyc())loop.close()print("HELLO WORLD")print("HELLO WORLD") # You can also use High Level functions Like:# asyncio.run(function_asyc())
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
HELLO WORLD
HELLO WORLD
Example 2: Execute more than one function at a time. To do so we have to create a new async function (main) and call all the async functions (which we want to run at the same time) in that new function (main). And then call the new (main) function using Event Loops...
Code:
Python3
import asyncio async def function_asyc(): for i in range(100000): if i % 50000 == 0: print("Hello, I'm Abhishek") print("GFG is Great") return 0 async def function_2(): print("\n HELLO WORLD \n") return 0 async def main(): f1 = loop.create_task(function_asyc()) f2 = loop.create_task(function_2()) await asyncio.wait([f1, f2]) # to run the above function we'll # use Event Loops these are low # level functions to run async functionsloop = asyncio.get_event_loop()loop.run_until_complete(main())loop.close() # You can also use High Level functions Like:# asyncio.run(function_asyc())
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
HELLO WORLD
Note: .create_task() is used to run multiple async functions at a time.
Example 3: Here you can see function_async() and function_2() are not running concurrently, the output of function_async() is displayed first and then the output of function_2() is displayed, that means function_2() is being executed after the execution of function_async().
But we don’t want that! we want both functions to make progress concurrently, so to achieve that in python we have to explicitly tell the computer when to shift from one function to another.
Code:
Python3
import asyncio async def function_asyc(): for i in range(100000): if i % 50000 == 0: print("Hello, I'm Abhishek") print("GFG is Great") # New Line Added await asyncio.sleep(0.01) return 0 async def function_2(): print("\n HELLO WORLD \n") return 0 async def main(): f1 = loop.create_task(function_asyc()) f2 = loop.create_task(function_2()) await asyncio.wait([f1, f2]) # to run the above function we'll # use Event Loops these are low level# functions to run async functionsloop = asyncio.get_event_loop()loop.run_until_complete(main())loop.close() # You can also use High Level functions Like:# asyncio.run(function_asyc())
Hello, I'm Abhishek
GFG is Great
HELLO WORLD
Hello, I'm Abhishek
GFG is Great
Now as you can see, the second function is executed during the execution of the running function (function_async()). So these were the basics now let’s see how to run two async functions forever.
Method 1: Just use the while True loop in the main function:
Python3
import asyncio async def function_asyc(): i = 0 while i < 1000000: i += 1 if i % 50000 == 0: print("Hello, I'm Abhishek") print("GFG is Great") await asyncio.sleep(0.01) async def function_2(): print("\n HELLO WORLD \n") async def main(): # New Line Added while True: f1 = loop.create_task(function_asyc()) f2 = loop.create_task(function_2()) await asyncio.wait([f1, f2]) # to run the above function we'll # use Event Loops these are low# level functions to run async functionsloop = asyncio.get_event_loop()loop.run_until_complete(main())loop.close()
Output:
Hello, I'm Abhishek
GFG is Great
HELLO WORLD
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
.
.
.
.
Method 2: Using while True loops for both functions and calling them using asyncio.ensure_future() and loop.run_forever()
Note: ensure_future lets us execute a coroutine in the background, without explicitly waiting for it to finish.
Python3
import asyncio async def function_asyc(): i = 0 while True: i += 1 if i % 50000 == 0: print("Hello, I'm Abhishek") print("GFG is Great") await asyncio.sleep(0.01) async def function_2(): while True: await asyncio.sleep(0.01) print("\n HELLO WORLD \n") loop = asyncio.get_event_loop()asyncio.ensure_future(function_asyc())asyncio.ensure_future(function_2())loop.run_forever()
Output:
Hello, I'm Abhishek
GFG is Great
Hello, I'm Abhishek
GFG is Great
HELLO WORLD
Hello, I'm Abhishek
GFG is Great
.
.
.
Picked
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 May, 2021"
},
{
"code": null,
"e": 388,
"s": 52,
"text": "Asynchronous programming is a type of programming in which we can execute more than one task without blocking the Main task (function). In Python, there are many ways to execute more than one function concurrently, one of the ways is by using asyncio. Async programming allows you to write concurrent code that runs in a single thread."
},
{
"code": null,
"e": 475,
"s": 388,
"text": "Note: Asyncio doesn’t use threads or multiprocessing to make the program Asynchronous."
},
{
"code": null,
"e": 715,
"s": 475,
"text": "Coroutine: Coroutines are a general control structure whereby flow control is cooperatively passed between two different routines without returning. In asyncio Coroutine can be created by using async keyword before def. "
},
{
"code": null,
"e": 814,
"s": 715,
"text": "async def speak_async():\n for i in range(100):\n print(\"Hello I'm Abhishek, writer on GFG\")"
},
{
"code": null,
"e": 891,
"s": 814,
"text": "If you try to run an async function directly you will get a runtime warning:"
},
{
"code": null,
"e": 949,
"s": 891,
"text": "RuntimeWarning: coroutine ‘speak_async’ was never awaited"
},
{
"code": null,
"e": 963,
"s": 949,
"text": "speak_async()"
},
{
"code": null,
"e": 1041,
"s": 963,
"text": "To run an async function (coroutine) you have to call it using an Event Loop."
},
{
"code": null,
"e": 1190,
"s": 1041,
"text": "Event Loops: You can think of Event Loop as functions to run asynchronous tasks and callbacks, perform network IO operations, and run subprocesses. "
},
{
"code": null,
"e": 1274,
"s": 1190,
"text": "Example 1: Event Loop example to run async Function to run a single async function:"
},
{
"code": null,
"e": 1282,
"s": 1274,
"text": "Python3"
},
{
"code": "import asyncio async def function_asyc(): for i in range(5): print(\"Hello, I'm Abhishek\") print(\"GFG is Great\") return 0 # to run the above function we'll # use Event Loops these are low # level functions to run async functionsloop = asyncio.get_event_loop()loop.run_until_complete(function_asyc())loop.close()print(\"HELLO WORLD\")print(\"HELLO WORLD\") # You can also use High Level functions Like:# asyncio.run(function_asyc())",
"e": 1734,
"s": 1282,
"text": null
},
{
"code": null,
"e": 1923,
"s": 1734,
"text": "Hello, I'm Abhishek\nGFG is Great\nHello, I'm Abhishek\nGFG is Great\nHello, I'm Abhishek\nGFG is Great\nHello, I'm Abhishek\nGFG is Great\nHello, I'm Abhishek\nGFG is Great\nHELLO WORLD\nHELLO WORLD"
},
{
"code": null,
"e": 2192,
"s": 1923,
"text": "Example 2: Execute more than one function at a time. To do so we have to create a new async function (main) and call all the async functions (which we want to run at the same time) in that new function (main). And then call the new (main) function using Event Loops..."
},
{
"code": null,
"e": 2198,
"s": 2192,
"text": "Code:"
},
{
"code": null,
"e": 2206,
"s": 2198,
"text": "Python3"
},
{
"code": "import asyncio async def function_asyc(): for i in range(100000): if i % 50000 == 0: print(\"Hello, I'm Abhishek\") print(\"GFG is Great\") return 0 async def function_2(): print(\"\\n HELLO WORLD \\n\") return 0 async def main(): f1 = loop.create_task(function_asyc()) f2 = loop.create_task(function_2()) await asyncio.wait([f1, f2]) # to run the above function we'll # use Event Loops these are low # level functions to run async functionsloop = asyncio.get_event_loop()loop.run_until_complete(main())loop.close() # You can also use High Level functions Like:# asyncio.run(function_asyc())",
"e": 2847,
"s": 2206,
"text": null
},
{
"code": null,
"e": 2928,
"s": 2847,
"text": "Hello, I'm Abhishek\nGFG is Great\nHello, I'm Abhishek\nGFG is Great\n\n HELLO WORLD "
},
{
"code": null,
"e": 3000,
"s": 2928,
"text": "Note: .create_task() is used to run multiple async functions at a time."
},
{
"code": null,
"e": 3275,
"s": 3000,
"text": "Example 3: Here you can see function_async() and function_2() are not running concurrently, the output of function_async() is displayed first and then the output of function_2() is displayed, that means function_2() is being executed after the execution of function_async()."
},
{
"code": null,
"e": 3466,
"s": 3275,
"text": "But we don’t want that! we want both functions to make progress concurrently, so to achieve that in python we have to explicitly tell the computer when to shift from one function to another."
},
{
"code": null,
"e": 3472,
"s": 3466,
"text": "Code:"
},
{
"code": null,
"e": 3480,
"s": 3472,
"text": "Python3"
},
{
"code": "import asyncio async def function_asyc(): for i in range(100000): if i % 50000 == 0: print(\"Hello, I'm Abhishek\") print(\"GFG is Great\") # New Line Added await asyncio.sleep(0.01) return 0 async def function_2(): print(\"\\n HELLO WORLD \\n\") return 0 async def main(): f1 = loop.create_task(function_asyc()) f2 = loop.create_task(function_2()) await asyncio.wait([f1, f2]) # to run the above function we'll # use Event Loops these are low level# functions to run async functionsloop = asyncio.get_event_loop()loop.run_until_complete(main())loop.close() # You can also use High Level functions Like:# asyncio.run(function_asyc())",
"e": 4203,
"s": 3480,
"text": null
},
{
"code": null,
"e": 4285,
"s": 4203,
"text": "Hello, I'm Abhishek\nGFG is Great\n\n HELLO WORLD \n\nHello, I'm Abhishek\nGFG is Great"
},
{
"code": null,
"e": 4481,
"s": 4285,
"text": "Now as you can see, the second function is executed during the execution of the running function (function_async()). So these were the basics now let’s see how to run two async functions forever."
},
{
"code": null,
"e": 4542,
"s": 4481,
"text": "Method 1: Just use the while True loop in the main function:"
},
{
"code": null,
"e": 4550,
"s": 4542,
"text": "Python3"
},
{
"code": "import asyncio async def function_asyc(): i = 0 while i < 1000000: i += 1 if i % 50000 == 0: print(\"Hello, I'm Abhishek\") print(\"GFG is Great\") await asyncio.sleep(0.01) async def function_2(): print(\"\\n HELLO WORLD \\n\") async def main(): # New Line Added while True: f1 = loop.create_task(function_asyc()) f2 = loop.create_task(function_2()) await asyncio.wait([f1, f2]) # to run the above function we'll # use Event Loops these are low# level functions to run async functionsloop = asyncio.get_event_loop()loop.run_until_complete(main())loop.close()",
"e": 5197,
"s": 4550,
"text": null
},
{
"code": null,
"e": 5205,
"s": 5197,
"text": "Output:"
},
{
"code": null,
"e": 5493,
"s": 5205,
"text": "Hello, I'm Abhishek\nGFG is Great\n\n HELLO WORLD \n\nHello, I'm Abhishek\nGFG is Great\nHello, I'm Abhishek\nGFG is Great\nHello, I'm Abhishek\nGFG is Great\nHello, I'm Abhishek\nGFG is Great\nHello, I'm Abhishek\nGFG is Great\nHello, I'm Abhishek\nGFG is Great\nHello, I'm Abhishek\nGFG is Great\n.\n.\n.\n."
},
{
"code": null,
"e": 5616,
"s": 5493,
"text": "Method 2: Using while True loops for both functions and calling them using asyncio.ensure_future() and loop.run_forever() "
},
{
"code": null,
"e": 5728,
"s": 5616,
"text": "Note: ensure_future lets us execute a coroutine in the background, without explicitly waiting for it to finish."
},
{
"code": null,
"e": 5736,
"s": 5728,
"text": "Python3"
},
{
"code": "import asyncio async def function_asyc(): i = 0 while True: i += 1 if i % 50000 == 0: print(\"Hello, I'm Abhishek\") print(\"GFG is Great\") await asyncio.sleep(0.01) async def function_2(): while True: await asyncio.sleep(0.01) print(\"\\n HELLO WORLD \\n\") loop = asyncio.get_event_loop()asyncio.ensure_future(function_asyc())asyncio.ensure_future(function_2())loop.run_forever()",
"e": 6192,
"s": 5736,
"text": null
},
{
"code": null,
"e": 6200,
"s": 6192,
"text": "Output:"
},
{
"code": null,
"e": 6321,
"s": 6200,
"text": "Hello, I'm Abhishek\nGFG is Great\nHello, I'm Abhishek\nGFG is Great\n\n HELLO WORLD \n\nHello, I'm Abhishek\nGFG is Great\n.\n.\n."
},
{
"code": null,
"e": 6328,
"s": 6321,
"text": "Picked"
},
{
"code": null,
"e": 6345,
"s": 6328,
"text": "Python-Functions"
},
{
"code": null,
"e": 6352,
"s": 6345,
"text": "Python"
},
{
"code": null,
"e": 6450,
"s": 6352,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6482,
"s": 6450,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 6509,
"s": 6482,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 6530,
"s": 6509,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 6553,
"s": 6530,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 6584,
"s": 6553,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 6640,
"s": 6584,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 6682,
"s": 6640,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 6724,
"s": 6682,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 6763,
"s": 6724,
"text": "Python | Get unique values from a list"
}
] |
GATE | GATE-CS-2015 (Set 1) | Question 19 | 28 Jun, 2021
The following two functions P1 and P2 that share a variable B with an initial value of 2 execute concurrently.
P1()
{
C = B – 1;
B = 2*C;
}
P2()
{
D = 2 * B;
B = D - 1;
}
The number of distinct values that B can possibly take after the execution is(A) 3(B) 2(C) 5(D) 4Answer: (A)Explanation: There are following ways that concurrent processes can follow.
C = B – 1; // C = 1
B = 2*C; // B = 2
D = 2 * B; // D = 4
B = D - 1; // B = 3
C = B – 1; // C = 1
D = 2 * B; // D = 4
B = D - 1; // B = 3
B = 2*C; // B = 2
C = B – 1; // C = 1
D = 2 * B; // D = 4
B = 2*C; // B = 2
B = D - 1; // B = 3
D = 2 * B; // D = 4
C = B – 1; // C = 1
B = 2*C; // B = 2
B = D - 1; // B = 3
D = 2 * B; // D = 4
B = D - 1; // B = 3
C = B – 1; // C = 2
B = 2*C; // B = 4
There are 3 different possible values of B: 2, 3 and 4.Quiz of this Question
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 139,
"s": 28,
"text": "The following two functions P1 and P2 that share a variable B with an initial value of 2 execute concurrently."
},
{
"code": null,
"e": 218,
"s": 139,
"text": "P1() \n{ \n C = B – 1; \n B = 2*C; \n}\n\nP2()\n{\n D = 2 * B;\n B = D - 1; \n}"
},
{
"code": null,
"e": 402,
"s": 218,
"text": "The number of distinct values that B can possibly take after the execution is(A) 3(B) 2(C) 5(D) 4Answer: (A)Explanation: There are following ways that concurrent processes can follow."
},
{
"code": null,
"e": 850,
"s": 402,
"text": " C = B – 1; // C = 1\n B = 2*C; // B = 2\n D = 2 * B; // D = 4\n B = D - 1; // B = 3\n\n\n C = B – 1; // C = 1\n D = 2 * B; // D = 4\n B = D - 1; // B = 3\n B = 2*C; // B = 2\n\n C = B – 1; // C = 1\n D = 2 * B; // D = 4\n B = 2*C; // B = 2\n B = D - 1; // B = 3\n\n D = 2 * B; // D = 4\n C = B – 1; // C = 1\n B = 2*C; // B = 2\n B = D - 1; // B = 3\n\n D = 2 * B; // D = 4\n B = D - 1; // B = 3\n C = B – 1; // C = 2\n B = 2*C; // B = 4 "
},
{
"code": null,
"e": 927,
"s": 850,
"text": "There are 3 different possible values of B: 2, 3 and 4.Quiz of this Question"
},
{
"code": null,
"e": 948,
"s": 927,
"text": "GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 974,
"s": 948,
"text": "GATE-GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 979,
"s": 974,
"text": "GATE"
}
] |
GATE | GATE-CS-2015 (Set 2) | Question 65 | 28 Jun, 2021
A Computer system implements 8 kilobyte pages and a 32-bit physical address space. Each page table entry contains a valid bit, a dirty bit three permission bits, and the translation. If the maximum size of the page table of a process is 24 megabytes, the length of the virtual address supported by the system is _______________ bits(A) 36(B) 32(C) 28(D) 40Answer: (A)Explanation:
Max size of virtual address can be calculated by
calculating maximum number of page table entries.
Maximum Number of page table entries can be calculated
using given maximum page table size and size of a page
table entry.
Given maximum page table size = 24 MB
Let us calculate size of a page table entry.
A page table entry has following number of bits.
1 (valid bit) +
1 (dirty bit) +
3 (permission bits) +
x bits to store physical address space of a page.
Value of x = (Total bits in physical address) -
(Total bits for addressing within a page)
Since size of a page is 8 kilobytes, total bits needed within
a page is 13.
So value of x = 32 - 13 = 19
Putting value of x, we get size of a page table entry =
1 + 1 + 3 + 19 = 24bits.
Number of page table entries
= (Page Table Size) / (An entry size)
= (24 megabytes / 24 bits)
= 223
Vrtual address Size
= (Number of page table entries) * (Page Size)
= 223 * 8 kilobits
= 236
Therefore, length of virtual address space = 36
Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 432,
"s": 52,
"text": "A Computer system implements 8 kilobyte pages and a 32-bit physical address space. Each page table entry contains a valid bit, a dirty bit three permission bits, and the translation. If the maximum size of the page table of a process is 24 megabytes, the length of the virtual address supported by the system is _______________ bits(A) 36(B) 32(C) 28(D) 40Answer: (A)Explanation:"
},
{
"code": null,
"e": 1578,
"s": 432,
"text": "Max size of virtual address can be calculated by \ncalculating maximum number of page table entries.\n\nMaximum Number of page table entries can be calculated \nusing given maximum page table size and size of a page \ntable entry.\n\nGiven maximum page table size = 24 MB\n\nLet us calculate size of a page table entry.\n\nA page table entry has following number of bits.\n1 (valid bit) + \n1 (dirty bit) + \n3 (permission bits) + \nx bits to store physical address space of a page.\n\nValue of x = (Total bits in physical address) - \n (Total bits for addressing within a page)\nSince size of a page is 8 kilobytes, total bits needed within\na page is 13.\nSo value of x = 32 - 13 = 19\n\nPutting value of x, we get size of a page table entry =\n 1 + 1 + 3 + 19 = 24bits.\n\nNumber of page table entries \n = (Page Table Size) / (An entry size)\n = (24 megabytes / 24 bits) \n = 223\n\nVrtual address Size \n = (Number of page table entries) * (Page Size)\n = 223 * 8 kilobits\n = 236 \nTherefore, length of virtual address space = 36"
},
{
"code": null,
"e": 1600,
"s": 1578,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 1621,
"s": 1600,
"text": "GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 1647,
"s": 1621,
"text": "GATE-GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 1652,
"s": 1647,
"text": "GATE"
}
] |
VB.Net - Continue Statement | The Continue statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. It works somewhat like the Exit statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between.
For the For...Next loop, Continue statement causes the conditional test and increment portions of the loop to execute. For the While and Do...While loops, continue statement causes the program control to pass to the conditional tests.
The syntax for a Continue statement is as follows −
Continue { Do | For | While }
Module loops
Sub Main()
' local variable definition
Dim a As Integer = 10
Do
If (a = 15) Then
' skip the iteration '
a = a + 1
Continue Do
End If
Console.WriteLine("value of a: {0}", a)
a = a + 1
Loop While (a < 20)
Console.ReadLine()
End Sub
End Module
When the above code is compiled and executed, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19 | [
{
"code": null,
"e": 2727,
"s": 2434,
"text": "The Continue statement causes the loop to skip the remainder of its body and immediately retest its condition prior to reiterating. It works somewhat like the Exit statement. Instead of forcing termination, it forces the next iteration of the loop to take place, skipping any code in between."
},
{
"code": null,
"e": 2962,
"s": 2727,
"text": "For the For...Next loop, Continue statement causes the conditional test and increment portions of the loop to execute. For the While and Do...While loops, continue statement causes the program control to pass to the conditional tests."
},
{
"code": null,
"e": 3014,
"s": 2962,
"text": "The syntax for a Continue statement is as follows −"
},
{
"code": null,
"e": 3045,
"s": 3014,
"text": "Continue { Do | For | While }\n"
},
{
"code": null,
"e": 3408,
"s": 3045,
"text": "Module loops\n Sub Main()\n ' local variable definition \n Dim a As Integer = 10\n Do\n If (a = 15) Then\n ' skip the iteration '\n a = a + 1\n Continue Do\n End If\n Console.WriteLine(\"value of a: {0}\", a)\n a = a + 1\n Loop While (a < 20)\n Console.ReadLine()\n End Sub\nEnd Module"
},
{
"code": null,
"e": 3489,
"s": 3408,
"text": "When the above code is compiled and executed, it produces the following result −"
}
] |
Timers of 8051 | In Intel 8051, there are two 16-bit timer registers. These registers are known as Timer0 andTimer1. The timer registers can be used in two modes. These modes areTimer mode and the Counter mode. The only difference between these two modes is the source for incrementing the timer registers.
In the timer mode, the internal machine cycles are counted. So this register is incremented in each machine cycle. So when the clock frequency is 12MHz, then the timer register is incremented in each millisecond. In this mode it ignores the external timer input pin.
In the counter mode, the external events are counted. In this mode, the timer register is incremented for each 1 to 0 transition of the external input pin. This type of transitions is treated as events. The external input pins are sampled once in each machine cycle, and to determine the 1or 0 transitions, another machine cycle will be needed. So in this mode, at least two machine cycles are needed. When the frequency is12MHz, then the maximum count frequency will be 12MHz/24 = 500KHz. So for event counting the time duration is 2 μs.
There are four different modes of the Timer or Counter. The Mode 0 to Mode 2 are for both of the Timer/Counter. Mode 3 has a different meaning for each timer register. There is a register called TMOD. This register can be programmed to configure these timers or counters.
The Serial port is used for serial communication in mode 1 and 3. Timer1 is used for generating the baud rate. So only Timer0 is available for timer or counter operations.
TMOD(Timer Mode) is an SFR. The address of this register is 89H. This is not bit-addressable.
Now, let us see the circuit that controls the running of the timers.
In the following table, we will see the bit details and their different operations for high or low value.
The Gate bit will be high when the timer or counter is in mode 0 to 2.
To configure the Timer0 as 16-bit event counter and Timer1 as 8-bit auto reload counter, we can use the bit pattern 0 0 1 0 0 1 0 1. It is equivalent to 25H. If we want to program the TMOD register with this bit pattern, we can use this instruction:
MOVTMOD, #25H
The above instruction is executed, then the timer/counter will be controlled by the software. To configure the system as hardware controlled mode, then the gate bits will be 1. So the bit patterns will be 1 0 1 0 1 1 0 1 = ADH
we can use this instruction:
MOVTMOD, #0ADH
The Mode 0 operation is the 8-bit timer or counter with a 5-bit pre-scaler. So it is a 13-bit timer/counter. It uses 5 bits of TL0 or TL1 and all of the 8-bits of TH0 or TH1.
In this example the Timer1is selected, in this case, every 32 (25)event for counter operations or 32 machine cycles for timer operation, the TH1 register will be incremented by 1. When the TH1overflows from FFH to 00H, then the TF1 of TCON register will be high, and it stops the timer/counter. So for an example, we can say that if the TH1 is holding F0H, and it is in timer mode, then TF1will be high after 10H * 32 = 512 machine cycles.
MOVTMOD, #00H
MOVTH1, #0F0H
MOVIE, #88H
SETB TR1
In the above program, the Timer1 is configured as timer mode 0. In this case Gate = 0. Then the TH1 will be loaded with F0H, then enable the Timer1 interrupt. At last set the TR1 of TCON register, and start the timer.
The Mode 1 operation is the 16-bit timer or counter. In the following diagram, we are using Mode 1 for Timer0.
In this case every event for counter operations or machine cycles for timer operation, the TH0– TL0 register-pair will be incremented by 1. When the register pair overflows from FFFFH to 0000H, then the TF0 of TCON register will be high, and it stops the timer/counter. So for an example, we can say that if the TH0 – TL0 register pair is holding FFF0H, and it is in timer mode, then TF0 will be high after 10H = 16 machine cycles. When the clock frequency is 12MHz, then the following instructions generate an interrupt 16 μs after Timer0 starts running.
MOVTMOD, #01H
MOVTL0, #0F0H
MOVTH0, #0FFH
MOVIE, #82H
SETB TR0
In the above program, the Timer0 is configured as timer mode 1. In this case Gate = 0. Then the TL0 will be loaded with F0H and TH0 is loaded with FFH, then enable the Timer0 interrupt. At last set the TR0 of TCON register, and start the timer.
The Mode 2 operation is the 8-bit auto reload timer or counter. In the following diagram, we are using Mode 2 for Timer1.
In this case every event for counter operations or machine cycles for timer operation, the TL1register will be incremented by 1. When the register pair overflows from FFH to 00H, then the TF1 of TCON register will be high, also theTL1 will be reloaded with the content of TH1 and starts the operation again.
So for an example, we can say that if the TH1 and TL1 register both are holding F0H and it is in timer mode, then TF1 will be high after 10H= 16 machine cycles. When the clock frequency is 12MHz this happens after 16 μs, then the following instructions generate an interrupt once every 16 μs after Timer1 starts running.
MOVTMOD, #20H
MOVTL1, #0F0H
MOVTH1, #0F0H
MOVIE, #88H
SETBTR1
In the above program, the Timer1 is configured as timer mode 2. In this case Gate = 0. Then the TL1 and TH1 are loaded with F0H. then enable the Timer1 interrupt. At last set the TR1 of TCON register, and start the timer.
Timer1 in mode 2 generates the desired baud rate when the serial port is working on Mode 1 or 3.
Mode 3 is different for Timer0 and Timer1. When the Timer0 is working in mode 3, the TL0 will be used as an 8-bit timer/counter. It will be controlled by the standard Timer0 control bits, T0 and INT0 inputs. The TH0 is used as an 8-bit timer but not the counter. This is controlled by Timer1 Control bit TR1. When the TH0 overflows from FFH to 00H, then TF1 is set to 1. In the following diagram, we can Timer0 in Mode 3.
When the Timer1 is working in Mode 3, it simply holds the count but does not run. When Timer0 is in mode 3, the Timer1 is configured in one of the mode 0, 1 and 2. In this case, the Timer1 cannot interrupt the microcontroller. When the TF1 is used by TH0 timer, the Timer1 is used as Baud Rate Generator.
The meaning of gate bit in Timer0 and Timer1 for mode 3 is as follows
It controls the running of 8-bit timer/counter TL0 as like Mode 0, 1, or 2. The running of TH0 is controlled by TR1 bit only. So the gate bit in this mode for Timer0 has no specific role.
The mode 3 is present for applications requiring an extra 8-bit timer/counter. In Mode 3 of Timer0, the 8051 has three timers. One 8-bit timer by TH0, another8-bit timer/counter by TL0, and one 16-bit timer/counter by Timer1.
If the Timer0 is in mode3, and Timer1 is working on either 0, 1 or 2, then the gun control of the Timer1 is activated when the gate bit is low or INT1 is high. The run control is deactivated when the gate is high and INT1 is low. | [
{
"code": null,
"e": 1478,
"s": 1187,
"text": "In Intel 8051, there are two 16-bit timer registers. These registers are known as Timer0 andTimer1. The timer registers can be used in two modes. These modes areTimer mode and the Counter mode. The only difference between these two modes is the source for incrementing the timer registers. "
},
{
"code": null,
"e": 1745,
"s": 1478,
"text": "In the timer mode, the internal machine cycles are counted. So this register is incremented in each machine cycle. So when the clock frequency is 12MHz, then the timer register is incremented in each millisecond. In this mode it ignores the external timer input pin."
},
{
"code": null,
"e": 2284,
"s": 1745,
"text": "In the counter mode, the external events are counted. In this mode, the timer register is incremented for each 1 to 0 transition of the external input pin. This type of transitions is treated as events. The external input pins are sampled once in each machine cycle, and to determine the 1or 0 transitions, another machine cycle will be needed. So in this mode, at least two machine cycles are needed. When the frequency is12MHz, then the maximum count frequency will be 12MHz/24 = 500KHz. So for event counting the time duration is 2 μs."
},
{
"code": null,
"e": 2556,
"s": 2284,
"text": "There are four different modes of the Timer or Counter. The Mode 0 to Mode 2 are for both of the Timer/Counter. Mode 3 has a different meaning for each timer register. There is a register called TMOD. This register can be programmed to configure these timers or counters."
},
{
"code": null,
"e": 2728,
"s": 2556,
"text": "The Serial port is used for serial communication in mode 1 and 3. Timer1 is used for generating the baud rate. So only Timer0 is available for timer or counter operations."
},
{
"code": null,
"e": 2822,
"s": 2728,
"text": "TMOD(Timer Mode) is an SFR. The address of this register is 89H. This is not bit-addressable."
},
{
"code": null,
"e": 2891,
"s": 2822,
"text": "Now, let us see the circuit that controls the running of the timers."
},
{
"code": null,
"e": 2997,
"s": 2891,
"text": "In the following table, we will see the bit details and their different operations for high or low value."
},
{
"code": null,
"e": 3068,
"s": 2997,
"text": "The Gate bit will be high when the timer or counter is in mode 0 to 2."
},
{
"code": null,
"e": 3318,
"s": 3068,
"text": "To configure the Timer0 as 16-bit event counter and Timer1 as 8-bit auto reload counter, we can use the bit pattern 0 0 1 0 0 1 0 1. It is equivalent to 25H. If we want to program the TMOD register with this bit pattern, we can use this instruction:"
},
{
"code": null,
"e": 3332,
"s": 3318,
"text": "MOVTMOD, #25H"
},
{
"code": null,
"e": 3559,
"s": 3332,
"text": "The above instruction is executed, then the timer/counter will be controlled by the software. To configure the system as hardware controlled mode, then the gate bits will be 1. So the bit patterns will be 1 0 1 0 1 1 0 1 = ADH"
},
{
"code": null,
"e": 3588,
"s": 3559,
"text": "we can use this instruction:"
},
{
"code": null,
"e": 3603,
"s": 3588,
"text": "MOVTMOD, #0ADH"
},
{
"code": null,
"e": 3778,
"s": 3603,
"text": "The Mode 0 operation is the 8-bit timer or counter with a 5-bit pre-scaler. So it is a 13-bit timer/counter. It uses 5 bits of TL0 or TL1 and all of the 8-bits of TH0 or TH1."
},
{
"code": null,
"e": 4218,
"s": 3778,
"text": "In this example the Timer1is selected, in this case, every 32 (25)event for counter operations or 32 machine cycles for timer operation, the TH1 register will be incremented by 1. When the TH1overflows from FFH to 00H, then the TF1 of TCON register will be high, and it stops the timer/counter. So for an example, we can say that if the TH1 is holding F0H, and it is in timer mode, then TF1will be high after 10H * 32 = 512 machine cycles."
},
{
"code": null,
"e": 4267,
"s": 4218,
"text": "MOVTMOD, #00H\nMOVTH1, #0F0H\nMOVIE, #88H\nSETB TR1"
},
{
"code": null,
"e": 4485,
"s": 4267,
"text": "In the above program, the Timer1 is configured as timer mode 0. In this case Gate = 0. Then the TH1 will be loaded with F0H, then enable the Timer1 interrupt. At last set the TR1 of TCON register, and start the timer."
},
{
"code": null,
"e": 4596,
"s": 4485,
"text": "The Mode 1 operation is the 16-bit timer or counter. In the following diagram, we are using Mode 1 for Timer0."
},
{
"code": null,
"e": 5152,
"s": 4596,
"text": "In this case every event for counter operations or machine cycles for timer operation, the TH0– TL0 register-pair will be incremented by 1. When the register pair overflows from FFFFH to 0000H, then the TF0 of TCON register will be high, and it stops the timer/counter. So for an example, we can say that if the TH0 – TL0 register pair is holding FFF0H, and it is in timer mode, then TF0 will be high after 10H = 16 machine cycles. When the clock frequency is 12MHz, then the following instructions generate an interrupt 16 μs after Timer0 starts running."
},
{
"code": null,
"e": 5215,
"s": 5152,
"text": "MOVTMOD, #01H\nMOVTL0, #0F0H\nMOVTH0, #0FFH\nMOVIE, #82H\nSETB TR0"
},
{
"code": null,
"e": 5460,
"s": 5215,
"text": "In the above program, the Timer0 is configured as timer mode 1. In this case Gate = 0. Then the TL0 will be loaded with F0H and TH0 is loaded with FFH, then enable the Timer0 interrupt. At last set the TR0 of TCON register, and start the timer."
},
{
"code": null,
"e": 5582,
"s": 5460,
"text": "The Mode 2 operation is the 8-bit auto reload timer or counter. In the following diagram, we are using Mode 2 for Timer1."
},
{
"code": null,
"e": 5891,
"s": 5582,
"text": "In this case every event for counter operations or machine cycles for timer operation, the TL1register will be incremented by 1. When the register pair overflows from FFH to 00H, then the TF1 of TCON register will be high, also theTL1 will be reloaded with the content of TH1 and starts the operation again. "
},
{
"code": null,
"e": 6212,
"s": 5891,
"text": "So for an example, we can say that if the TH1 and TL1 register both are holding F0H and it is in timer mode, then TF1 will be high after 10H= 16 machine cycles. When the clock frequency is 12MHz this happens after 16 μs, then the following instructions generate an interrupt once every 16 μs after Timer1 starts running."
},
{
"code": null,
"e": 6274,
"s": 6212,
"text": "MOVTMOD, #20H\nMOVTL1, #0F0H\nMOVTH1, #0F0H\nMOVIE, #88H\nSETBTR1"
},
{
"code": null,
"e": 6496,
"s": 6274,
"text": "In the above program, the Timer1 is configured as timer mode 2. In this case Gate = 0. Then the TL1 and TH1 are loaded with F0H. then enable the Timer1 interrupt. At last set the TR1 of TCON register, and start the timer."
},
{
"code": null,
"e": 6593,
"s": 6496,
"text": "Timer1 in mode 2 generates the desired baud rate when the serial port is working on Mode 1 or 3."
},
{
"code": null,
"e": 7015,
"s": 6593,
"text": "Mode 3 is different for Timer0 and Timer1. When the Timer0 is working in mode 3, the TL0 will be used as an 8-bit timer/counter. It will be controlled by the standard Timer0 control bits, T0 and INT0 inputs. The TH0 is used as an 8-bit timer but not the counter. This is controlled by Timer1 Control bit TR1. When the TH0 overflows from FFH to 00H, then TF1 is set to 1. In the following diagram, we can Timer0 in Mode 3."
},
{
"code": null,
"e": 7320,
"s": 7015,
"text": "When the Timer1 is working in Mode 3, it simply holds the count but does not run. When Timer0 is in mode 3, the Timer1 is configured in one of the mode 0, 1 and 2. In this case, the Timer1 cannot interrupt the microcontroller. When the TF1 is used by TH0 timer, the Timer1 is used as Baud Rate Generator."
},
{
"code": null,
"e": 7390,
"s": 7320,
"text": "The meaning of gate bit in Timer0 and Timer1 for mode 3 is as follows"
},
{
"code": null,
"e": 7579,
"s": 7390,
"text": "It controls the running of 8-bit timer/counter TL0 as like Mode 0, 1, or 2. The running of TH0 is controlled by TR1 bit only. So the gate bit in this mode for Timer0 has no specific role. "
},
{
"code": null,
"e": 7806,
"s": 7579,
"text": "The mode 3 is present for applications requiring an extra 8-bit timer/counter. In Mode 3 of Timer0, the 8051 has three timers. One 8-bit timer by TH0, another8-bit timer/counter by TL0, and one 16-bit timer/counter by Timer1."
},
{
"code": null,
"e": 8037,
"s": 7806,
"text": "If the Timer0 is in mode3, and Timer1 is working on either 0, 1 or 2, then the gun control of the Timer1 is activated when the gate bit is low or INT1 is high. The run control is deactivated when the gate is high and INT1 is low. "
}
] |
R - Histograms | A histogram represents the frequencies of values of a variable bucketed into ranges. Histogram is similar to bar chat but the difference is it groups the values into continuous ranges. Each bar in histogram represents the height of the number of values present in that range.
R creates histogram using hist() function. This function takes a vector as an input and uses some more parameters to plot histograms.
The basic syntax for creating a histogram using R is −
hist(v,main,xlab,xlim,ylim,breaks,col,border)
Following is the description of the parameters used −
v is a vector containing numeric values used in histogram.
v is a vector containing numeric values used in histogram.
main indicates title of the chart.
main indicates title of the chart.
col is used to set color of the bars.
col is used to set color of the bars.
border is used to set border color of each bar.
border is used to set border color of each bar.
xlab is used to give description of x-axis.
xlab is used to give description of x-axis.
xlim is used to specify the range of values on the x-axis.
xlim is used to specify the range of values on the x-axis.
ylim is used to specify the range of values on the y-axis.
ylim is used to specify the range of values on the y-axis.
breaks is used to mention the width of each bar.
breaks is used to mention the width of each bar.
A simple histogram is created using input vector, label, col and border parameters.
The script given below will create and save the histogram in the current R working directory.
# Create data for the graph.
v <- c(9,13,21,8,36,22,12,41,31,33,19)
# Give the chart file a name.
png(file = "histogram.png")
# Create the histogram.
hist(v,xlab = "Weight",col = "yellow",border = "blue")
# Save the file.
dev.off()
When we execute the above code, it produces the following result −
To specify the range of values allowed in X axis and Y axis, we can use the xlim and ylim parameters.
The width of each of the bar can be decided by using breaks.
# Create data for the graph.
v <- c(9,13,21,8,36,22,12,41,31,33,19)
# Give the chart file a name.
png(file = "histogram_lim_breaks.png")
# Create the histogram.
hist(v,xlab = "Weight",col = "green",border = "red", xlim = c(0,40), ylim = c(0,5),
breaks = 5)
# Save the file.
dev.off()
When we execute the above code, it produces the following result − | [
{
"code": null,
"e": 2812,
"s": 2536,
"text": "A histogram represents the frequencies of values of a variable bucketed into ranges. Histogram is similar to bar chat but the difference is it groups the values into continuous ranges. Each bar in histogram represents the height of the number of values present in that range."
},
{
"code": null,
"e": 2946,
"s": 2812,
"text": "R creates histogram using hist() function. This function takes a vector as an input and uses some more parameters to plot histograms."
},
{
"code": null,
"e": 3001,
"s": 2946,
"text": "The basic syntax for creating a histogram using R is −"
},
{
"code": null,
"e": 3048,
"s": 3001,
"text": "hist(v,main,xlab,xlim,ylim,breaks,col,border)\n"
},
{
"code": null,
"e": 3102,
"s": 3048,
"text": "Following is the description of the parameters used −"
},
{
"code": null,
"e": 3161,
"s": 3102,
"text": "v is a vector containing numeric values used in histogram."
},
{
"code": null,
"e": 3220,
"s": 3161,
"text": "v is a vector containing numeric values used in histogram."
},
{
"code": null,
"e": 3255,
"s": 3220,
"text": "main indicates title of the chart."
},
{
"code": null,
"e": 3290,
"s": 3255,
"text": "main indicates title of the chart."
},
{
"code": null,
"e": 3328,
"s": 3290,
"text": "col is used to set color of the bars."
},
{
"code": null,
"e": 3366,
"s": 3328,
"text": "col is used to set color of the bars."
},
{
"code": null,
"e": 3414,
"s": 3366,
"text": "border is used to set border color of each bar."
},
{
"code": null,
"e": 3462,
"s": 3414,
"text": "border is used to set border color of each bar."
},
{
"code": null,
"e": 3506,
"s": 3462,
"text": "xlab is used to give description of x-axis."
},
{
"code": null,
"e": 3550,
"s": 3506,
"text": "xlab is used to give description of x-axis."
},
{
"code": null,
"e": 3609,
"s": 3550,
"text": "xlim is used to specify the range of values on the x-axis."
},
{
"code": null,
"e": 3668,
"s": 3609,
"text": "xlim is used to specify the range of values on the x-axis."
},
{
"code": null,
"e": 3727,
"s": 3668,
"text": "ylim is used to specify the range of values on the y-axis."
},
{
"code": null,
"e": 3786,
"s": 3727,
"text": "ylim is used to specify the range of values on the y-axis."
},
{
"code": null,
"e": 3835,
"s": 3786,
"text": "breaks is used to mention the width of each bar."
},
{
"code": null,
"e": 3884,
"s": 3835,
"text": "breaks is used to mention the width of each bar."
},
{
"code": null,
"e": 3968,
"s": 3884,
"text": "A simple histogram is created using input vector, label, col and border parameters."
},
{
"code": null,
"e": 4062,
"s": 3968,
"text": "The script given below will create and save the histogram in the current R working directory."
},
{
"code": null,
"e": 4298,
"s": 4062,
"text": "# Create data for the graph.\nv <- c(9,13,21,8,36,22,12,41,31,33,19)\n\n# Give the chart file a name.\npng(file = \"histogram.png\")\n\n# Create the histogram.\nhist(v,xlab = \"Weight\",col = \"yellow\",border = \"blue\")\n\n# Save the file.\ndev.off()"
},
{
"code": null,
"e": 4365,
"s": 4298,
"text": "When we execute the above code, it produces the following result −"
},
{
"code": null,
"e": 4467,
"s": 4365,
"text": "To specify the range of values allowed in X axis and Y axis, we can use the xlim and ylim parameters."
},
{
"code": null,
"e": 4528,
"s": 4467,
"text": "The width of each of the bar can be decided by using breaks."
},
{
"code": null,
"e": 4818,
"s": 4528,
"text": "# Create data for the graph.\nv <- c(9,13,21,8,36,22,12,41,31,33,19)\n\n# Give the chart file a name.\npng(file = \"histogram_lim_breaks.png\")\n\n# Create the histogram.\nhist(v,xlab = \"Weight\",col = \"green\",border = \"red\", xlim = c(0,40), ylim = c(0,5),\n breaks = 5)\n\n# Save the file.\ndev.off()"
}
] |
Boolean equals() method in Java with examples | 09 Oct, 2018
The equals() method of Boolean class is a built in method of Java which is used check equality of two Boolean object.
Syntax:
BooleanObject.equals(Object ob)
Parameter: It take a parameter ob of type Object as input which is the instance to be compared.
Return Type: The return type is boolean. It returns true if the specified Object ‘ob’ has same value as the ‘BooleanObject’, else it returns false.
Below are programs to illustrate the equals() method of Boolean class:
Program 1:
// Java code to implement// equals() method of Boolean class class GeeksforGeeks { // Driver method public static void main(String[] args) { // Boolean object Boolean a = new Boolean(true); // Boolean object Boolean b = new Boolean(true); // compare method System.out.println(a + " comparing with " + b + " = " + a.equals(b)); }}
true comparing with true = true
Program 2:
// Java code to implement// equals() method of Java class class GeeksforGeeks { // Driver method public static void main(String[] args) { // Boolean object Boolean a = new Boolean(true); // Boolean object Boolean b = new Boolean(false); // compare method System.out.println(a + " comparing with " + b + " = " + a.equals(b)); }}
true comparing with false = false
Program 3:
// Java code to implement// equals() method of Java class class GeeksforGeeks { // Driver method public static void main(String[] args) { // Boolean object Boolean a = new Boolean(false); // Boolean object Boolean b = new Boolean(true); // compare method System.out.println(a + " comparing with " + b + " = " + a.equals(b)); }}
false comparing with true = false
Java - util package
Java-Boolean
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Oct, 2018"
},
{
"code": null,
"e": 146,
"s": 28,
"text": "The equals() method of Boolean class is a built in method of Java which is used check equality of two Boolean object."
},
{
"code": null,
"e": 154,
"s": 146,
"text": "Syntax:"
},
{
"code": null,
"e": 186,
"s": 154,
"text": "BooleanObject.equals(Object ob)"
},
{
"code": null,
"e": 282,
"s": 186,
"text": "Parameter: It take a parameter ob of type Object as input which is the instance to be compared."
},
{
"code": null,
"e": 430,
"s": 282,
"text": "Return Type: The return type is boolean. It returns true if the specified Object ‘ob’ has same value as the ‘BooleanObject’, else it returns false."
},
{
"code": null,
"e": 501,
"s": 430,
"text": "Below are programs to illustrate the equals() method of Boolean class:"
},
{
"code": null,
"e": 512,
"s": 501,
"text": "Program 1:"
},
{
"code": "// Java code to implement// equals() method of Boolean class class GeeksforGeeks { // Driver method public static void main(String[] args) { // Boolean object Boolean a = new Boolean(true); // Boolean object Boolean b = new Boolean(true); // compare method System.out.println(a + \" comparing with \" + b + \" = \" + a.equals(b)); }}",
"e": 931,
"s": 512,
"text": null
},
{
"code": null,
"e": 964,
"s": 931,
"text": "true comparing with true = true\n"
},
{
"code": null,
"e": 975,
"s": 964,
"text": "Program 2:"
},
{
"code": "// Java code to implement// equals() method of Java class class GeeksforGeeks { // Driver method public static void main(String[] args) { // Boolean object Boolean a = new Boolean(true); // Boolean object Boolean b = new Boolean(false); // compare method System.out.println(a + \" comparing with \" + b + \" = \" + a.equals(b)); }}",
"e": 1392,
"s": 975,
"text": null
},
{
"code": null,
"e": 1427,
"s": 1392,
"text": "true comparing with false = false\n"
},
{
"code": null,
"e": 1438,
"s": 1427,
"text": "Program 3:"
},
{
"code": "// Java code to implement// equals() method of Java class class GeeksforGeeks { // Driver method public static void main(String[] args) { // Boolean object Boolean a = new Boolean(false); // Boolean object Boolean b = new Boolean(true); // compare method System.out.println(a + \" comparing with \" + b + \" = \" + a.equals(b)); }}",
"e": 1855,
"s": 1438,
"text": null
},
{
"code": null,
"e": 1890,
"s": 1855,
"text": "false comparing with true = false\n"
},
{
"code": null,
"e": 1910,
"s": 1890,
"text": "Java - util package"
},
{
"code": null,
"e": 1923,
"s": 1910,
"text": "Java-Boolean"
},
{
"code": null,
"e": 1938,
"s": 1923,
"text": "Java-Functions"
},
{
"code": null,
"e": 1943,
"s": 1938,
"text": "Java"
},
{
"code": null,
"e": 1948,
"s": 1943,
"text": "Java"
}
] |
Java Program to Print a New Line in String | 06 Jun, 2021
Java is the most powerful programming language, by which we can perform many tasks and Java is an industry preferable language. So it is filled with a huge amount of features. Here we are going to discuss one of the best features of Java, that is how to print a new line in a string using Java.
Methods:
There are many ways to print new line in string been illustrated as below:
Using System.lineSeparator() methodUsing platform-dependent newline characterUsing System.getProperty() method Using %n newline characterUsing System.out.println() method
Using System.lineSeparator() method
Using platform-dependent newline character
Using System.getProperty() method
Using %n newline character
Using System.out.println() method
Let us discuss them individually in detail.
Method 1: Using System.lineSeparator() method
Example
Java
// Java program to print a new line in string// Using System.lineSeparator() method // Main classclass GFG { // Main Driver Code public static void main(String[] args) { // Calling the System.lineSeparator() function to // print newline in between some specified strings String newline = System.lineSeparator(); // Printing new line System.out.println("GFG" + newline + "gfg"); }}
GFG
gfg
Method 2: Using platform-dependent newline character.
Note: Here the new line character is “\n” for Unix and “\r\n” for Windows OS.
Example
Java
// Java program to print a new line in string// Using platform-dependent Newline Character // Main classclass GFG { // Main Driver Code public static void main(String[] args) { // Using new line Character '\n' to print // new line in between strings System.out.println("GFG" + '\n' + "gfg"); }}
GFG
gfg
Method 3: Using System.getProperty() method. Here this function uses the value of the system property “line.separator”, which returns the system-dependent line separator string.
Example
Java
// Java program to print a new line in string class GFG{ // Main Driver Code public static void main(String[] args) { // Calling System.getProperty() function Over The // parameter for the value of the system property "line.separator", // which returns the system-dependent line separator string. String newline = System.getProperty("line.separator"); // Printing new line between two strings System.out.println("GFG" + newline + "gfg"); }}
Output:
GFG
gfg
Method 4: Using %n newline character
Note: Here this newline character is used along with the printf() function.
Example
Java
// Java program to print a new line in string// Using %n Newline Character // Importing input output classesimport java.io.*; // Main classclass GFG { // Main Driver Code public static void main(String[] args) { // Printing new line using new line // Character "%n" with the printf() method System.out.printf("GFG%ngfg"); }}
GFG
gfg
Method-5: Using System.out.println() method.
Example
Java
// Java program to print a new line in string// Using System.out.println() method // Main classclass GFG { // Main driver method public static void main(String[] args) { // Printing new line using // System.out.println() function // over custom string inputs System.out.println("GFG"); System.out.println("gfg"); }}
GFG
gfg
Java-String-Programs
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2021"
},
{
"code": null,
"e": 323,
"s": 28,
"text": "Java is the most powerful programming language, by which we can perform many tasks and Java is an industry preferable language. So it is filled with a huge amount of features. Here we are going to discuss one of the best features of Java, that is how to print a new line in a string using Java."
},
{
"code": null,
"e": 333,
"s": 323,
"text": "Methods: "
},
{
"code": null,
"e": 408,
"s": 333,
"text": "There are many ways to print new line in string been illustrated as below:"
},
{
"code": null,
"e": 580,
"s": 408,
"text": "Using System.lineSeparator() methodUsing platform-dependent newline characterUsing System.getProperty() method Using %n newline characterUsing System.out.println() method "
},
{
"code": null,
"e": 616,
"s": 580,
"text": "Using System.lineSeparator() method"
},
{
"code": null,
"e": 659,
"s": 616,
"text": "Using platform-dependent newline character"
},
{
"code": null,
"e": 693,
"s": 659,
"text": "Using System.getProperty() method"
},
{
"code": null,
"e": 721,
"s": 693,
"text": " Using %n newline character"
},
{
"code": null,
"e": 756,
"s": 721,
"text": "Using System.out.println() method "
},
{
"code": null,
"e": 800,
"s": 756,
"text": "Let us discuss them individually in detail."
},
{
"code": null,
"e": 846,
"s": 800,
"text": "Method 1: Using System.lineSeparator() method"
},
{
"code": null,
"e": 854,
"s": 846,
"text": "Example"
},
{
"code": null,
"e": 859,
"s": 854,
"text": "Java"
},
{
"code": "// Java program to print a new line in string// Using System.lineSeparator() method // Main classclass GFG { // Main Driver Code public static void main(String[] args) { // Calling the System.lineSeparator() function to // print newline in between some specified strings String newline = System.lineSeparator(); // Printing new line System.out.println(\"GFG\" + newline + \"gfg\"); }}",
"e": 1290,
"s": 859,
"text": null
},
{
"code": null,
"e": 1299,
"s": 1290,
"text": "GFG\ngfg\n"
},
{
"code": null,
"e": 1354,
"s": 1299,
"text": "Method 2: Using platform-dependent newline character. "
},
{
"code": null,
"e": 1432,
"s": 1354,
"text": "Note: Here the new line character is “\\n” for Unix and “\\r\\n” for Windows OS."
},
{
"code": null,
"e": 1441,
"s": 1432,
"text": "Example "
},
{
"code": null,
"e": 1446,
"s": 1441,
"text": "Java"
},
{
"code": "// Java program to print a new line in string// Using platform-dependent Newline Character // Main classclass GFG { // Main Driver Code public static void main(String[] args) { // Using new line Character '\\n' to print // new line in between strings System.out.println(\"GFG\" + '\\n' + \"gfg\"); }}",
"e": 1779,
"s": 1446,
"text": null
},
{
"code": null,
"e": 1788,
"s": 1779,
"text": "GFG\ngfg\n"
},
{
"code": null,
"e": 1967,
"s": 1788,
"text": "Method 3: Using System.getProperty() method. Here this function uses the value of the system property “line.separator”, which returns the system-dependent line separator string. "
},
{
"code": null,
"e": 1976,
"s": 1967,
"text": "Example "
},
{
"code": null,
"e": 1981,
"s": 1976,
"text": "Java"
},
{
"code": "// Java program to print a new line in string class GFG{ // Main Driver Code public static void main(String[] args) { // Calling System.getProperty() function Over The // parameter for the value of the system property \"line.separator\", // which returns the system-dependent line separator string. String newline = System.getProperty(\"line.separator\"); // Printing new line between two strings System.out.println(\"GFG\" + newline + \"gfg\"); }}",
"e": 2499,
"s": 1981,
"text": null
},
{
"code": null,
"e": 2508,
"s": 2499,
"text": "Output: "
},
{
"code": null,
"e": 2516,
"s": 2508,
"text": "GFG\ngfg"
},
{
"code": null,
"e": 2553,
"s": 2516,
"text": "Method 4: Using %n newline character"
},
{
"code": null,
"e": 2629,
"s": 2553,
"text": "Note: Here this newline character is used along with the printf() function."
},
{
"code": null,
"e": 2638,
"s": 2629,
"text": "Example "
},
{
"code": null,
"e": 2643,
"s": 2638,
"text": "Java"
},
{
"code": "// Java program to print a new line in string// Using %n Newline Character // Importing input output classesimport java.io.*; // Main classclass GFG { // Main Driver Code public static void main(String[] args) { // Printing new line using new line // Character \"%n\" with the printf() method System.out.printf(\"GFG%ngfg\"); }}",
"e": 3005,
"s": 2643,
"text": null
},
{
"code": null,
"e": 3013,
"s": 3005,
"text": "GFG\ngfg"
},
{
"code": null,
"e": 3058,
"s": 3013,
"text": "Method-5: Using System.out.println() method."
},
{
"code": null,
"e": 3067,
"s": 3058,
"text": "Example "
},
{
"code": null,
"e": 3072,
"s": 3067,
"text": "Java"
},
{
"code": "// Java program to print a new line in string// Using System.out.println() method // Main classclass GFG { // Main driver method public static void main(String[] args) { // Printing new line using // System.out.println() function // over custom string inputs System.out.println(\"GFG\"); System.out.println(\"gfg\"); }}",
"e": 3440,
"s": 3072,
"text": null
},
{
"code": null,
"e": 3449,
"s": 3440,
"text": "GFG\ngfg\n"
},
{
"code": null,
"e": 3470,
"s": 3449,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 3477,
"s": 3470,
"text": "Picked"
},
{
"code": null,
"e": 3482,
"s": 3477,
"text": "Java"
},
{
"code": null,
"e": 3496,
"s": 3482,
"text": "Java Programs"
},
{
"code": null,
"e": 3501,
"s": 3496,
"text": "Java"
},
{
"code": null,
"e": 3599,
"s": 3501,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3650,
"s": 3599,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3681,
"s": 3650,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3711,
"s": 3681,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3726,
"s": 3711,
"text": "Stream In Java"
},
{
"code": null,
"e": 3744,
"s": 3726,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3772,
"s": 3744,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 3798,
"s": 3772,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3842,
"s": 3798,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 3876,
"s": 3842,
"text": "Convert Double to Integer in Java"
}
] |
Ways to convert string to dictionary | 30 May, 2022
Dictionary is an unordered collection in Python which store data values like a map i.e., key:value pair. In order to convert a String into a dictionary, the stored string must be in such a way that key:value pair can be generated from it. This article demonstrates several ways of converting a string into a dictionary. Method 1: Splitting a string to generate key:value pair of the dictionary In this approach, the given string will be analysed and with the use of split() method, the string will be split in such a way that it generates the key:value pair for the creation of a dictionary. Below is the implementation of the approach.
Python3
# Python implementation of converting# a string into a dictionary # initialising stringstr = " Jan = January; Feb = February; Mar = March" # At first the string will be splitted# at the occurrence of ';' to divide items# for the dictionaryand then again splitting# will be done at occurrence of '=' which# generates key:value pair for each itemdictionary = dict(subString.split("=") for subString in str.split(";")) # printing the generated dictionaryprint(dictionary)
{' Feb ': ' February', ' Mar ': ' March', ' Jan ': ' January'}
Method 2: Using 2 strings to generate the key:value pair for the dictionary In this approach, 2 different strings will be considered and one of them will be used to generate keys and another one will be used to generate values for the dictionary. After manipulating both the strings the dictionary items will be created using those key:value pair. Below is the implementation of the approach.
Python3
# Python implementation of converting# a string into a dictionary # initialising first stringstr1 = "Jan, Feb, March"str2 = "January | February | March" # splitting first string# in order to get keyskeys = str1.split(", ") # splitting second string# in order to get valuesvalues = str2.split("|") # declaring the dictionarydictionary = {} # Assigning keys and its# corresponding values in# the dictionaryfor i in range(len(keys)): dictionary[keys[i]] = values[i] # printing the generated dictionaryprint(dictionary)
{'Jan': 'January ', 'Feb': ' February ', 'March': ' March'}
Method 3: Using zip() method to combine the key:value pair extracted from 2 string In this approach, again 2 strings will be used, one for generating keys and another for generating values for the dictionary. When all the keys and values are stored, zip() method will be used to create key:value pair and thus generating the complete dictionary. Below is the implementation of the approach.
Python3
# Python implementation of converting# a string into a dictionary # initialising first stringstr1 = "Jan, Feb, March"str2 = "January | February | March" # splitting first string# in order to get keyskeys = str1.split(", ") # splitting second string# in order to get valuesvalues = str2.split("|") # declaring the dictionarydictionary = {} # Merging all keys and values# to generate items for# the dictionarydictionary = dict(zip(keys, values)) # printing the generated dictionaryprint(dictionary)
{' March': ' March', 'Jan': 'January ', ' Feb': ' February '}
Method 4: If the string is itself in the form of string dictionary In this approach, a string which is already in the form of string dictionary i.e., the string has a dictionary expression is converted into a dictionary using ast.literal_eval() method. Below is the implementation of the approach.
Python3
# Python implementation of converting# a string into a dictionary # importing ast moduleimport ast # initialising string dictionarystr = '{"Jan" : "January", "Feb" : "February", "Mar" : "March"}' # converting string into dictionarydictionary = ast.literal_eval(str) # printing the generated dictionaryprint(dictionary)
{'Feb': 'February', 'Jan': 'January', 'Mar': 'March'}
nikhatkhan11
Python dictionary-programs
Python string-programs
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 May, 2022"
},
{
"code": null,
"e": 692,
"s": 54,
"text": "Dictionary is an unordered collection in Python which store data values like a map i.e., key:value pair. In order to convert a String into a dictionary, the stored string must be in such a way that key:value pair can be generated from it. This article demonstrates several ways of converting a string into a dictionary. Method 1: Splitting a string to generate key:value pair of the dictionary In this approach, the given string will be analysed and with the use of split() method, the string will be split in such a way that it generates the key:value pair for the creation of a dictionary. Below is the implementation of the approach. "
},
{
"code": null,
"e": 700,
"s": 692,
"text": "Python3"
},
{
"code": "# Python implementation of converting# a string into a dictionary # initialising stringstr = \" Jan = January; Feb = February; Mar = March\" # At first the string will be splitted# at the occurrence of ';' to divide items# for the dictionaryand then again splitting# will be done at occurrence of '=' which# generates key:value pair for each itemdictionary = dict(subString.split(\"=\") for subString in str.split(\";\")) # printing the generated dictionaryprint(dictionary)",
"e": 1169,
"s": 700,
"text": null
},
{
"code": null,
"e": 1232,
"s": 1169,
"text": "{' Feb ': ' February', ' Mar ': ' March', ' Jan ': ' January'}"
},
{
"code": null,
"e": 1626,
"s": 1232,
"text": "Method 2: Using 2 strings to generate the key:value pair for the dictionary In this approach, 2 different strings will be considered and one of them will be used to generate keys and another one will be used to generate values for the dictionary. After manipulating both the strings the dictionary items will be created using those key:value pair. Below is the implementation of the approach. "
},
{
"code": null,
"e": 1634,
"s": 1626,
"text": "Python3"
},
{
"code": "# Python implementation of converting# a string into a dictionary # initialising first stringstr1 = \"Jan, Feb, March\"str2 = \"January | February | March\" # splitting first string# in order to get keyskeys = str1.split(\", \") # splitting second string# in order to get valuesvalues = str2.split(\"|\") # declaring the dictionarydictionary = {} # Assigning keys and its# corresponding values in# the dictionaryfor i in range(len(keys)): dictionary[keys[i]] = values[i] # printing the generated dictionaryprint(dictionary)",
"e": 2153,
"s": 1634,
"text": null
},
{
"code": null,
"e": 2213,
"s": 2153,
"text": "{'Jan': 'January ', 'Feb': ' February ', 'March': ' March'}"
},
{
"code": null,
"e": 2605,
"s": 2213,
"text": "Method 3: Using zip() method to combine the key:value pair extracted from 2 string In this approach, again 2 strings will be used, one for generating keys and another for generating values for the dictionary. When all the keys and values are stored, zip() method will be used to create key:value pair and thus generating the complete dictionary. Below is the implementation of the approach. "
},
{
"code": null,
"e": 2613,
"s": 2605,
"text": "Python3"
},
{
"code": "# Python implementation of converting# a string into a dictionary # initialising first stringstr1 = \"Jan, Feb, March\"str2 = \"January | February | March\" # splitting first string# in order to get keyskeys = str1.split(\", \") # splitting second string# in order to get valuesvalues = str2.split(\"|\") # declaring the dictionarydictionary = {} # Merging all keys and values# to generate items for# the dictionarydictionary = dict(zip(keys, values)) # printing the generated dictionaryprint(dictionary)",
"e": 3111,
"s": 2613,
"text": null
},
{
"code": null,
"e": 3173,
"s": 3111,
"text": "{' March': ' March', 'Jan': 'January ', ' Feb': ' February '}"
},
{
"code": null,
"e": 3472,
"s": 3173,
"text": "Method 4: If the string is itself in the form of string dictionary In this approach, a string which is already in the form of string dictionary i.e., the string has a dictionary expression is converted into a dictionary using ast.literal_eval() method. Below is the implementation of the approach. "
},
{
"code": null,
"e": 3480,
"s": 3472,
"text": "Python3"
},
{
"code": "# Python implementation of converting# a string into a dictionary # importing ast moduleimport ast # initialising string dictionarystr = '{\"Jan\" : \"January\", \"Feb\" : \"February\", \"Mar\" : \"March\"}' # converting string into dictionarydictionary = ast.literal_eval(str) # printing the generated dictionaryprint(dictionary)",
"e": 3800,
"s": 3480,
"text": null
},
{
"code": null,
"e": 3854,
"s": 3800,
"text": "{'Feb': 'February', 'Jan': 'January', 'Mar': 'March'}"
},
{
"code": null,
"e": 3867,
"s": 3854,
"text": "nikhatkhan11"
},
{
"code": null,
"e": 3894,
"s": 3867,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 3917,
"s": 3894,
"text": "Python string-programs"
},
{
"code": null,
"e": 3924,
"s": 3917,
"text": "Python"
}
] |
Commonly used file formats in Data Science | 04 Feb, 2022
What is a File Format File formats are designed to store specific types of information, such as CSV, XLSX etc. The file format also tells the computer how to display or process its content. Common file formats, such as CSV, XLSX, ZIP, TXT etc.If you see your future as a data scientist so you must understand the different types of file format. Because data science is all about the data and it’s processing and if you don’t understand the file format so may be it’s quite complicated for you. Thus, it is mandatory for you to be aware of different file formats.Different type of file formats: CSV: the CSV is stand for Comma-separated values. as-well-as this name CSV file is use comma to separated values. In CSV file each line is a data record and Each record consists of one or more then one data fields, the field is separated by commas.Code: Python code to read csv file in pandas
python3
import pandas as pddf = pd.read_csv("file_path / file_name.csv")print(df)
XLSX: The XLSX file is Microsoft Excel Open XML Format Spreadsheet file. This is used to store any type of data but it’s mainly used to store financial data and to create mathematical models etc. Code: Python code to read xlsx file in pandas
python3
import pandas as pddf = pd.read_excel (r'file_path\\name.xlsx')print (df)
Note:
install xlrd before reading excel file in python for avoid the error. You can install xlrd using following command.pip install xlrd
ZIP: ZIP files are used an data containers, they store one or more then one files in the compressed form. it widely used in internet After you downloaded ZIP file, you need to unpack its contents in order to use it.Code: Python code to read zip file in pandas
python3
import pandas as pddf = pd.read_csv(' File_Path \\ File_Name .zip')print(df)
TXT: TXT files are useful for storing information in plain text with no special formatting beyond basic fonts and font styles. It is recognized by any text editing and other software programs.Code: Python code to read txt file in pandas
python3
import pandas as pddf = pd.read_csv('File_Path \\ File_Name .txt')print(df)
JSON: JSON is stand for JavaScript Object Notation. JSON is a standard text-based format for representing structured data based on JavaScript object syntaxCode: Python code to read json file in pandas
python3
import pandas as pddf = pd.read_json('File_path \\ File_Name .json')print(df)
HTML: HTML is stand for stands for Hyper Text Markup Language is use for creating web pages. we can read html table in python pandas using read_html() function.Code: Python code to read html file in pandas
python3
import pandas as pddf = pd.read_html('File_Path \\File_Name.html')print(df)
Note:
You need to install a package named “lxml & html5lib” which can handle the file with ‘.html’ extension.pip install html5lib pip install lxml
PDF: pdf stands for Portable Document Format (PDF) this file format is use when we need to save files that cannot be modified but still need to be easily available.Code: Python code to read pdf in pandas
python3
pip install tabula-pypip install pandasdf = tabula.read_pdf(file_path \\ file_name .pdf)print(df)
Note:
You need to install a package named “tabula-py” which can handle the file with ‘.pdf’ extension. pip install tabula-py
simmytarika5
data-science
Python pandas-basics
Python pandas-datatypes
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Feb, 2022"
},
{
"code": null,
"e": 941,
"s": 52,
"text": "What is a File Format File formats are designed to store specific types of information, such as CSV, XLSX etc. The file format also tells the computer how to display or process its content. Common file formats, such as CSV, XLSX, ZIP, TXT etc.If you see your future as a data scientist so you must understand the different types of file format. Because data science is all about the data and it’s processing and if you don’t understand the file format so may be it’s quite complicated for you. Thus, it is mandatory for you to be aware of different file formats.Different type of file formats: CSV: the CSV is stand for Comma-separated values. as-well-as this name CSV file is use comma to separated values. In CSV file each line is a data record and Each record consists of one or more then one data fields, the field is separated by commas.Code: Python code to read csv file in pandas "
},
{
"code": null,
"e": 949,
"s": 941,
"text": "python3"
},
{
"code": "import pandas as pddf = pd.read_csv(\"file_path / file_name.csv\")print(df)",
"e": 1023,
"s": 949,
"text": null
},
{
"code": null,
"e": 1266,
"s": 1023,
"text": "XLSX: The XLSX file is Microsoft Excel Open XML Format Spreadsheet file. This is used to store any type of data but it’s mainly used to store financial data and to create mathematical models etc. Code: Python code to read xlsx file in pandas "
},
{
"code": null,
"e": 1274,
"s": 1266,
"text": "python3"
},
{
"code": "import pandas as pddf = pd.read_excel (r'file_path\\\\name.xlsx')print (df)",
"e": 1348,
"s": 1274,
"text": null
},
{
"code": null,
"e": 1356,
"s": 1348,
"text": "Note: "
},
{
"code": null,
"e": 1490,
"s": 1356,
"text": "install xlrd before reading excel file in python for avoid the error. You can install xlrd using following command.pip install xlrd "
},
{
"code": null,
"e": 1751,
"s": 1490,
"text": "ZIP: ZIP files are used an data containers, they store one or more then one files in the compressed form. it widely used in internet After you downloaded ZIP file, you need to unpack its contents in order to use it.Code: Python code to read zip file in pandas "
},
{
"code": null,
"e": 1759,
"s": 1751,
"text": "python3"
},
{
"code": "import pandas as pddf = pd.read_csv(' File_Path \\\\ File_Name .zip')print(df)",
"e": 1836,
"s": 1759,
"text": null
},
{
"code": null,
"e": 2074,
"s": 1836,
"text": "TXT: TXT files are useful for storing information in plain text with no special formatting beyond basic fonts and font styles. It is recognized by any text editing and other software programs.Code: Python code to read txt file in pandas "
},
{
"code": null,
"e": 2082,
"s": 2074,
"text": "python3"
},
{
"code": "import pandas as pddf = pd.read_csv('File_Path \\\\ File_Name .txt')print(df)",
"e": 2158,
"s": 2082,
"text": null
},
{
"code": null,
"e": 2360,
"s": 2158,
"text": "JSON: JSON is stand for JavaScript Object Notation. JSON is a standard text-based format for representing structured data based on JavaScript object syntaxCode: Python code to read json file in pandas "
},
{
"code": null,
"e": 2368,
"s": 2360,
"text": "python3"
},
{
"code": "import pandas as pddf = pd.read_json('File_path \\\\ File_Name .json')print(df)",
"e": 2446,
"s": 2368,
"text": null
},
{
"code": null,
"e": 2653,
"s": 2446,
"text": "HTML: HTML is stand for stands for Hyper Text Markup Language is use for creating web pages. we can read html table in python pandas using read_html() function.Code: Python code to read html file in pandas "
},
{
"code": null,
"e": 2661,
"s": 2653,
"text": "python3"
},
{
"code": "import pandas as pddf = pd.read_html('File_Path \\\\File_Name.html')print(df)",
"e": 2737,
"s": 2661,
"text": null
},
{
"code": null,
"e": 2745,
"s": 2737,
"text": "Note: "
},
{
"code": null,
"e": 2888,
"s": 2745,
"text": "You need to install a package named “lxml & html5lib” which can handle the file with ‘.html’ extension.pip install html5lib pip install lxml "
},
{
"code": null,
"e": 3093,
"s": 2888,
"text": "PDF: pdf stands for Portable Document Format (PDF) this file format is use when we need to save files that cannot be modified but still need to be easily available.Code: Python code to read pdf in pandas "
},
{
"code": null,
"e": 3101,
"s": 3093,
"text": "python3"
},
{
"code": "pip install tabula-pypip install pandasdf = tabula.read_pdf(file_path \\\\ file_name .pdf)print(df)",
"e": 3199,
"s": 3101,
"text": null
},
{
"code": null,
"e": 3207,
"s": 3199,
"text": "Note: "
},
{
"code": null,
"e": 3328,
"s": 3207,
"text": "You need to install a package named “tabula-py” which can handle the file with ‘.pdf’ extension. pip install tabula-py "
},
{
"code": null,
"e": 3343,
"s": 3330,
"text": "simmytarika5"
},
{
"code": null,
"e": 3356,
"s": 3343,
"text": "data-science"
},
{
"code": null,
"e": 3377,
"s": 3356,
"text": "Python pandas-basics"
},
{
"code": null,
"e": 3401,
"s": 3377,
"text": "Python pandas-datatypes"
},
{
"code": null,
"e": 3408,
"s": 3401,
"text": "Python"
},
{
"code": null,
"e": 3506,
"s": 3408,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3538,
"s": 3506,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3565,
"s": 3538,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3586,
"s": 3565,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3609,
"s": 3586,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3640,
"s": 3609,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3696,
"s": 3640,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3738,
"s": 3696,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3780,
"s": 3738,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3819,
"s": 3780,
"text": "Python | Get unique values from a list"
}
] |
JCL - EXEC Statement | Each JCL can be made of many job steps. Each job step can execute a program directly or can call a procedure, which in turn executes one or more programs (job steps). The statement, which holds the job step program/procedure information is the EXEC statement.
The purpose of the EXEC statement is to provide required information for the program/procedure executed in the job step. Parameters coded in this statement can pass data to the program in execution, can override certain parameters of JOB statement and can pass parameters to the procedure if the EXEC statement calls a procedure instead of directly executing a program.
Following is the basic syntax of a JCL EXEC statement:
//Step-name EXEC Positional-param, Keyword-param
Let us see the description of the terms used in above EXEC statement syntax.
This identifies the job step within the JCL. It can be of length 1 to 8 with alphanumeric characters.
This is the keyword to identify it as an EXEC statement.
These are positional parameters, which can be of two types:
Following are the various keyword parameters for EXEC statement. You can use one or more parameters based on requirements and they are separated by comma:
Used to provide parametrized data to the program that is being executed in the job step. This is a program dependant field and do not have definite rules, except that the PARM value has to be included within quotation in the event of having special characters.
For example given below, the value "CUST1000" is passed as an alphanumeric value to the program. If the program is in COBOL, the value passed through a PARM parameter in a JCL is received in the LINKAGE SECTION of the program.
This is used to specify whether the job step require virtual or real storage for execution. Virtual storage is pageable whereas real storage is not and is placed in the main memory for execution. Job steps, which require faster execution can be placed in real storage. Following is the syntax:
ADDRSPC=VIRT | REAL
When an ADDRSPC is not coded, VIRT is the default one.
This specifies the accounting information of the job step. Following is the syntax:
ACCT=(userid)
This is similar to the positional parameter accounting information in the JOB statement. If it is coded both in JOB and EXEC statement, then the accounting information in JOB statement applies to all job steps where an ACCT parameter is not coded. The ACCT parameter in an EXEC statement will override the one present in the JOB statement for that job step only.
If REGION is coded in an EXEC statement, then it applies to that job step only.
REGION coded in JOB statement overrides the REGION coded in EXEC statement of any job step.
Used to control the job step execution based on the return-code of the previous step.
If a COND parameter is coded in an EXEC statement of a job step, then the COND parameter of the JOB statement (if present) is ignored. The various tests that can be performed using a COND parameter is explained in conditional Processing.
Following is a simple example of JCL script along with JOB and EXEC statements:
//TTYYSAMP JOB 'TUTO',CLASS=6,MSGCLASS=X,REGION=8K,
// NOTIFY=&SYSUID
//*
//STEP010 EXEC PGM=MYCOBOL,PARAM=CUST1000, | [
{
"code": null,
"e": 2258,
"s": 1998,
"text": "Each JCL can be made of many job steps. Each job step can execute a program directly or can call a procedure, which in turn executes one or more programs (job steps). The statement, which holds the job step program/procedure information is the EXEC statement."
},
{
"code": null,
"e": 2628,
"s": 2258,
"text": "The purpose of the EXEC statement is to provide required information for the program/procedure executed in the job step. Parameters coded in this statement can pass data to the program in execution, can override certain parameters of JOB statement and can pass parameters to the procedure if the EXEC statement calls a procedure instead of directly executing a program."
},
{
"code": null,
"e": 2683,
"s": 2628,
"text": "Following is the basic syntax of a JCL EXEC statement:"
},
{
"code": null,
"e": 2733,
"s": 2683,
"text": "//Step-name EXEC Positional-param, Keyword-param "
},
{
"code": null,
"e": 2810,
"s": 2733,
"text": "Let us see the description of the terms used in above EXEC statement syntax."
},
{
"code": null,
"e": 2912,
"s": 2810,
"text": "This identifies the job step within the JCL. It can be of length 1 to 8 with alphanumeric characters."
},
{
"code": null,
"e": 2969,
"s": 2912,
"text": "This is the keyword to identify it as an EXEC statement."
},
{
"code": null,
"e": 3029,
"s": 2969,
"text": "These are positional parameters, which can be of two types:"
},
{
"code": null,
"e": 3184,
"s": 3029,
"text": "Following are the various keyword parameters for EXEC statement. You can use one or more parameters based on requirements and they are separated by comma:"
},
{
"code": null,
"e": 3445,
"s": 3184,
"text": "Used to provide parametrized data to the program that is being executed in the job step. This is a program dependant field and do not have definite rules, except that the PARM value has to be included within quotation in the event of having special characters."
},
{
"code": null,
"e": 3672,
"s": 3445,
"text": "For example given below, the value \"CUST1000\" is passed as an alphanumeric value to the program. If the program is in COBOL, the value passed through a PARM parameter in a JCL is received in the LINKAGE SECTION of the program."
},
{
"code": null,
"e": 3966,
"s": 3672,
"text": "This is used to specify whether the job step require virtual or real storage for execution. Virtual storage is pageable whereas real storage is not and is placed in the main memory for execution. Job steps, which require faster execution can be placed in real storage. Following is the syntax:"
},
{
"code": null,
"e": 3986,
"s": 3966,
"text": "ADDRSPC=VIRT | REAL"
},
{
"code": null,
"e": 4041,
"s": 3986,
"text": "When an ADDRSPC is not coded, VIRT is the default one."
},
{
"code": null,
"e": 4125,
"s": 4041,
"text": "This specifies the accounting information of the job step. Following is the syntax:"
},
{
"code": null,
"e": 4139,
"s": 4125,
"text": "ACCT=(userid)"
},
{
"code": null,
"e": 4502,
"s": 4139,
"text": "This is similar to the positional parameter accounting information in the JOB statement. If it is coded both in JOB and EXEC statement, then the accounting information in JOB statement applies to all job steps where an ACCT parameter is not coded. The ACCT parameter in an EXEC statement will override the one present in the JOB statement for that job step only."
},
{
"code": null,
"e": 4582,
"s": 4502,
"text": "If REGION is coded in an EXEC statement, then it applies to that job step only."
},
{
"code": null,
"e": 4674,
"s": 4582,
"text": "REGION coded in JOB statement overrides the REGION coded in EXEC statement of any job step."
},
{
"code": null,
"e": 4760,
"s": 4674,
"text": "Used to control the job step execution based on the return-code of the previous step."
},
{
"code": null,
"e": 4998,
"s": 4760,
"text": "If a COND parameter is coded in an EXEC statement of a job step, then the COND parameter of the JOB statement (if present) is ignored. The various tests that can be performed using a COND parameter is explained in conditional Processing."
},
{
"code": null,
"e": 5078,
"s": 4998,
"text": "Following is a simple example of JCL script along with JOB and EXEC statements:"
}
] |
PHP Check if two arrays contain same elements | 03 Dec, 2021
In this article, we will see how to compare the elements of arrays in PHP, & will know how to apply to get the result after comparison through the examples. In PHP, there are two types of arrays, Indexed array and Associative array. In an Indexed array, the array elements are index numerically starting from 0 while in an Associative array, the array elements have named keys associated with them.
Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important. When the order of the array elements is not important, two methods can be applied to check the array equality which is listed below:
Use the sort() function to sort an array element and then use the equality operator.
Use array operator ( == ) in case of Associative array.
We will understand both the ways to compare the elements in arrays.
Equality checking in an indexed array:
This can be applied in the numeric array where string integer indexing is done. Here, use the sort() function to sort array elements and then use the equality operator for checking the index of those two arrays using the array operator. Here is the order of the array elements are not important, so sorting will make all the array element in a sequential manner, thus if two arrays are equal the values corresponding to the same index of both the arrays will be the same.
Example: PHP example to check equality of two arrays using the sorting technique and equal operator.
PHP
<?php $arr1 = array(4, 5, 'hello', 2.45, 3.56); $arr2 = array(5, 2.45, 'hello', 3.56, 4); // Sort the array elements sort($arr1); sort($arr2); // Check for equality if ($arr1 == $arr2) echo "Both arrays are same\n"; else echo "Both arrays are not same\n"; $arr3 = array(5, 'car', 'hello', 2.45, 3.56); $arr4 = array(4, 2.45, 'hello', 3.56, 'geeks'); // Sort the array elements sort($arr3); sort($arr4); // Check for equality if ($arr3 == $arr4) echo "Both arrays are same"; else echo "Both arrays are not same";?>
Both arrays are same
Both arrays are not same
Equality checking in Associative array: In the case of an associative array, all the elements have an index associated with them so, there is no need for sorting, the equality operator can be directly applied to check for equality. Basically, the equality operator compares the values corresponding to an index in both the arrays if all the index values are the same then they are equal otherwise they are not.
Syntax:
bool $arr1 == $arr2
In the case of the indexed array, the sorting is done to arrange the elements sequentially whereas in the case of the associative array the elements are already indexed so sorting is not necessary anymore.
Example: PHP example to check the equality of two associative arrays.
PHP
<?php $arr1 = array( 'first' => 'geeks', 'second' => 'for', 'last' => 'ide' ); $arr2 = array( 'first' => 'geeks', 'last' =>'ide', 'second' =>'for' ); // Check for equality if ($arr1 == $arr2) echo "Both arrays are same\n"; else echo "Both arrays are not same\n"; $arr3 = array( 'first' => 'geeks', 'second' => 'for', 'last' => 'ide' ); $arr4 = array( 'first' => 'geek', 'second' =>'for', 'last' =>'geeks' ); // Check for equality if ($arr3 == $arr4) echo "Both arrays are same"; else echo "Both arrays are not same";?>
Both arrays are same
Both arrays are not same
bhaskargeeksforgeeks
PHP-array
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to delete an array element based on key in PHP?
How to convert array to string in PHP ?
How to pop an alert message box using PHP ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Dec, 2021"
},
{
"code": null,
"e": 428,
"s": 28,
"text": "In this article, we will see how to compare the elements of arrays in PHP, & will know how to apply to get the result after comparison through the examples. In PHP, there are two types of arrays, Indexed array and Associative array. In an Indexed array, the array elements are index numerically starting from 0 while in an Associative array, the array elements have named keys associated with them. "
},
{
"code": null,
"e": 875,
"s": 428,
"text": "Now, to check whether two arrays are equal or not, an iteration can be done over the arrays and check whether for each index the value associated with the index in both the arrays is the same or not. PHP has an inbuilt array operator( === ) to check the same but here the order of array elements is not important. When the order of the array elements is not important, two methods can be applied to check the array equality which is listed below:"
},
{
"code": null,
"e": 960,
"s": 875,
"text": "Use the sort() function to sort an array element and then use the equality operator."
},
{
"code": null,
"e": 1016,
"s": 960,
"text": "Use array operator ( == ) in case of Associative array."
},
{
"code": null,
"e": 1084,
"s": 1016,
"text": "We will understand both the ways to compare the elements in arrays."
},
{
"code": null,
"e": 1124,
"s": 1084,
"text": "Equality checking in an indexed array: "
},
{
"code": null,
"e": 1596,
"s": 1124,
"text": "This can be applied in the numeric array where string integer indexing is done. Here, use the sort() function to sort array elements and then use the equality operator for checking the index of those two arrays using the array operator. Here is the order of the array elements are not important, so sorting will make all the array element in a sequential manner, thus if two arrays are equal the values corresponding to the same index of both the arrays will be the same."
},
{
"code": null,
"e": 1697,
"s": 1596,
"text": "Example: PHP example to check equality of two arrays using the sorting technique and equal operator."
},
{
"code": null,
"e": 1701,
"s": 1697,
"text": "PHP"
},
{
"code": "<?php $arr1 = array(4, 5, 'hello', 2.45, 3.56); $arr2 = array(5, 2.45, 'hello', 3.56, 4); // Sort the array elements sort($arr1); sort($arr2); // Check for equality if ($arr1 == $arr2) echo \"Both arrays are same\\n\"; else echo \"Both arrays are not same\\n\"; $arr3 = array(5, 'car', 'hello', 2.45, 3.56); $arr4 = array(4, 2.45, 'hello', 3.56, 'geeks'); // Sort the array elements sort($arr3); sort($arr4); // Check for equality if ($arr3 == $arr4) echo \"Both arrays are same\"; else echo \"Both arrays are not same\";?>",
"e": 2256,
"s": 1701,
"text": null
},
{
"code": null,
"e": 2302,
"s": 2256,
"text": "Both arrays are same\nBoth arrays are not same"
},
{
"code": null,
"e": 2715,
"s": 2304,
"text": "Equality checking in Associative array: In the case of an associative array, all the elements have an index associated with them so, there is no need for sorting, the equality operator can be directly applied to check for equality. Basically, the equality operator compares the values corresponding to an index in both the arrays if all the index values are the same then they are equal otherwise they are not."
},
{
"code": null,
"e": 2723,
"s": 2715,
"text": "Syntax:"
},
{
"code": null,
"e": 2743,
"s": 2723,
"text": "bool $arr1 == $arr2"
},
{
"code": null,
"e": 2949,
"s": 2743,
"text": "In the case of the indexed array, the sorting is done to arrange the elements sequentially whereas in the case of the associative array the elements are already indexed so sorting is not necessary anymore."
},
{
"code": null,
"e": 3019,
"s": 2949,
"text": "Example: PHP example to check the equality of two associative arrays."
},
{
"code": null,
"e": 3023,
"s": 3019,
"text": "PHP"
},
{
"code": "<?php $arr1 = array( 'first' => 'geeks', 'second' => 'for', 'last' => 'ide' ); $arr2 = array( 'first' => 'geeks', 'last' =>'ide', 'second' =>'for' ); // Check for equality if ($arr1 == $arr2) echo \"Both arrays are same\\n\"; else echo \"Both arrays are not same\\n\"; $arr3 = array( 'first' => 'geeks', 'second' => 'for', 'last' => 'ide' ); $arr4 = array( 'first' => 'geek', 'second' =>'for', 'last' =>'geeks' ); // Check for equality if ($arr3 == $arr4) echo \"Both arrays are same\"; else echo \"Both arrays are not same\";?>",
"e": 3739,
"s": 3023,
"text": null
},
{
"code": null,
"e": 3785,
"s": 3739,
"text": "Both arrays are same\nBoth arrays are not same"
},
{
"code": null,
"e": 3808,
"s": 3787,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 3818,
"s": 3808,
"text": "PHP-array"
},
{
"code": null,
"e": 3825,
"s": 3818,
"text": "Picked"
},
{
"code": null,
"e": 3829,
"s": 3825,
"text": "PHP"
},
{
"code": null,
"e": 3842,
"s": 3829,
"text": "PHP Programs"
},
{
"code": null,
"e": 3859,
"s": 3842,
"text": "Web Technologies"
},
{
"code": null,
"e": 3863,
"s": 3859,
"text": "PHP"
},
{
"code": null,
"e": 3961,
"s": 3863,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4006,
"s": 3961,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 4056,
"s": 4006,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 4080,
"s": 4056,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 4132,
"s": 4080,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 4172,
"s": 4132,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 4217,
"s": 4172,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 4267,
"s": 4217,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 4319,
"s": 4267,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 4359,
"s": 4319,
"text": "How to convert array to string in PHP ?"
}
] |
Horn Clauses in Deductive Databases | 01 Jul, 2020
Horn clause is clause (a disjunction of literals) with at most one positive, i.e. unnegated, literal. A clause with at most one positive (unnegated) literal is called a Horn Clause.
Deductive Database:A type of database which can make conclusions based on sets of well-defined rules, stored in database. RDBMS and logic programming are combined using this. Deductive database designing is done with help of pure declarative programming language known as Datalog.
Types of Horn Clauses :
Definite clause / Strict Horn clause –It has exactly one positive literal.
Unit clause –Definite clause with no negative literals.
Goal clause –Horn clause without a positive literal.
In Datalog, rules are expressed as a restricted form of clauses called Horn clauses, in which a clause can contain at most one positive literal.
A formula can have following quantifiers:
Universal quantifier –It can be understood as – “For all x, P(x) holds”, meaning P(x) is true for every object x in universe. For example, all trucks has wheels.
Existential quantifier –It can be understood as – “There exists an x such that P(x)”, meaning P(x) is true for at least one object x of universe. For example, someone cares for you.
Forms of a Horn Clause :
NOT(P1) OR NOT(P2) OR ... OR NOT(Pn) OR QNOT(P1) OR NOT(P2) OR ... OR NOT (Pn)
NOT(P1) OR NOT(P2) OR ... OR NOT(Pn) OR Q
NOT(P1) OR NOT(P2) OR ... OR NOT(Pn) OR Q
NOT(P1) OR NOT(P2) OR ... OR NOT (Pn)
NOT(P1) OR NOT(P2) OR ... OR NOT (Pn)
Transformation of Horn Clause :The Horn clause in (1) can be transformed into clause –
P1 AND P2 AND ... AND Pn → Q
which is written in Datalog as following rules
Q :- P1, P2, ..., Pn
The above Datalog Rule, is hence a Horn clause.
If predicates P1 AND P2 AND ... AND Pn, are all true for a particular binding to their variable arguments, then Q is also true and can hence be inferred.
The Horn clause in (2) can be transformed into –
P1 AND P2 AND ... AND Pn →
which is written in Datalog as follows:
P1, P2, ..., Pn
The above Datalog expression can be considered as an integrity constraint, where all predicates must be true to satisfy query.
A query in Datalog consists of two components:
A Datalog program, which is a finite set of rules.
A literal P(X1, X2, X3, ... Xn), where each X is a variable or a constant.
DBMS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Jul, 2020"
},
{
"code": null,
"e": 210,
"s": 28,
"text": "Horn clause is clause (a disjunction of literals) with at most one positive, i.e. unnegated, literal. A clause with at most one positive (unnegated) literal is called a Horn Clause."
},
{
"code": null,
"e": 491,
"s": 210,
"text": "Deductive Database:A type of database which can make conclusions based on sets of well-defined rules, stored in database. RDBMS and logic programming are combined using this. Deductive database designing is done with help of pure declarative programming language known as Datalog."
},
{
"code": null,
"e": 515,
"s": 491,
"text": "Types of Horn Clauses :"
},
{
"code": null,
"e": 590,
"s": 515,
"text": "Definite clause / Strict Horn clause –It has exactly one positive literal."
},
{
"code": null,
"e": 646,
"s": 590,
"text": "Unit clause –Definite clause with no negative literals."
},
{
"code": null,
"e": 699,
"s": 646,
"text": "Goal clause –Horn clause without a positive literal."
},
{
"code": null,
"e": 844,
"s": 699,
"text": "In Datalog, rules are expressed as a restricted form of clauses called Horn clauses, in which a clause can contain at most one positive literal."
},
{
"code": null,
"e": 886,
"s": 844,
"text": "A formula can have following quantifiers:"
},
{
"code": null,
"e": 1048,
"s": 886,
"text": "Universal quantifier –It can be understood as – “For all x, P(x) holds”, meaning P(x) is true for every object x in universe. For example, all trucks has wheels."
},
{
"code": null,
"e": 1230,
"s": 1048,
"text": "Existential quantifier –It can be understood as – “There exists an x such that P(x)”, meaning P(x) is true for at least one object x of universe. For example, someone cares for you."
},
{
"code": null,
"e": 1255,
"s": 1230,
"text": "Forms of a Horn Clause :"
},
{
"code": null,
"e": 1334,
"s": 1255,
"text": "NOT(P1) OR NOT(P2) OR ... OR NOT(Pn) OR QNOT(P1) OR NOT(P2) OR ... OR NOT (Pn)"
},
{
"code": null,
"e": 1376,
"s": 1334,
"text": "NOT(P1) OR NOT(P2) OR ... OR NOT(Pn) OR Q"
},
{
"code": null,
"e": 1418,
"s": 1376,
"text": "NOT(P1) OR NOT(P2) OR ... OR NOT(Pn) OR Q"
},
{
"code": null,
"e": 1456,
"s": 1418,
"text": "NOT(P1) OR NOT(P2) OR ... OR NOT (Pn)"
},
{
"code": null,
"e": 1494,
"s": 1456,
"text": "NOT(P1) OR NOT(P2) OR ... OR NOT (Pn)"
},
{
"code": null,
"e": 1581,
"s": 1494,
"text": "Transformation of Horn Clause :The Horn clause in (1) can be transformed into clause –"
},
{
"code": null,
"e": 1611,
"s": 1581,
"text": "P1 AND P2 AND ... AND Pn → Q "
},
{
"code": null,
"e": 1658,
"s": 1611,
"text": "which is written in Datalog as following rules"
},
{
"code": null,
"e": 1680,
"s": 1658,
"text": "Q :- P1, P2, ..., Pn "
},
{
"code": null,
"e": 1728,
"s": 1680,
"text": "The above Datalog Rule, is hence a Horn clause."
},
{
"code": null,
"e": 1882,
"s": 1728,
"text": "If predicates P1 AND P2 AND ... AND Pn, are all true for a particular binding to their variable arguments, then Q is also true and can hence be inferred."
},
{
"code": null,
"e": 1931,
"s": 1882,
"text": "The Horn clause in (2) can be transformed into –"
},
{
"code": null,
"e": 1959,
"s": 1931,
"text": "P1 AND P2 AND ... AND Pn → "
},
{
"code": null,
"e": 1999,
"s": 1959,
"text": "which is written in Datalog as follows:"
},
{
"code": null,
"e": 2016,
"s": 1999,
"text": "P1, P2, ..., Pn "
},
{
"code": null,
"e": 2143,
"s": 2016,
"text": "The above Datalog expression can be considered as an integrity constraint, where all predicates must be true to satisfy query."
},
{
"code": null,
"e": 2190,
"s": 2143,
"text": "A query in Datalog consists of two components:"
},
{
"code": null,
"e": 2241,
"s": 2190,
"text": "A Datalog program, which is a finite set of rules."
},
{
"code": null,
"e": 2316,
"s": 2241,
"text": "A literal P(X1, X2, X3, ... Xn), where each X is a variable or a constant."
},
{
"code": null,
"e": 2321,
"s": 2316,
"text": "DBMS"
},
{
"code": null,
"e": 2326,
"s": 2321,
"text": "DBMS"
}
] |
Python | Pandas Series.plot() method | 17 Sep, 2019
With the help of Series.plot() method, we can get the plot of pandas series by using Series.plot() method.
Syntax : Series.plot()Return : Return the plot of series.
# import Series and matplotlibimport pandas as pdimport matplotlib.pyplot as plt # using Series.plot() methodgfg = pd.Series([0.1, 0.4, 0.16, 0.3, 0.9, 0.81]) gfg.plot()plt.show()
Output :
Example #2 :
# import Series and matplotlibimport pandas as pdimport matplotlib.pyplot as plt # using Series.plot() methodgfg = pd.Series([10, 9.9, 9.8, 7.8, 6.7, 19, 5.5]) gfg.plot()plt.show()
Output :
Python pandas-series
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 161,
"s": 54,
"text": "With the help of Series.plot() method, we can get the plot of pandas series by using Series.plot() method."
},
{
"code": null,
"e": 219,
"s": 161,
"text": "Syntax : Series.plot()Return : Return the plot of series."
},
{
"code": "# import Series and matplotlibimport pandas as pdimport matplotlib.pyplot as plt # using Series.plot() methodgfg = pd.Series([0.1, 0.4, 0.16, 0.3, 0.9, 0.81]) gfg.plot()plt.show()",
"e": 401,
"s": 219,
"text": null
},
{
"code": null,
"e": 410,
"s": 401,
"text": "Output :"
},
{
"code": null,
"e": 423,
"s": 410,
"text": "Example #2 :"
},
{
"code": "# import Series and matplotlibimport pandas as pdimport matplotlib.pyplot as plt # using Series.plot() methodgfg = pd.Series([10, 9.9, 9.8, 7.8, 6.7, 19, 5.5]) gfg.plot()plt.show()",
"e": 606,
"s": 423,
"text": null
},
{
"code": null,
"e": 615,
"s": 606,
"text": "Output :"
},
{
"code": null,
"e": 636,
"s": 615,
"text": "Python pandas-series"
},
{
"code": null,
"e": 650,
"s": 636,
"text": "Python-pandas"
},
{
"code": null,
"e": 657,
"s": 650,
"text": "Python"
},
{
"code": null,
"e": 755,
"s": 657,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 787,
"s": 755,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 814,
"s": 787,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 835,
"s": 814,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 858,
"s": 835,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 914,
"s": 858,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 945,
"s": 914,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 987,
"s": 945,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1029,
"s": 987,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1068,
"s": 1029,
"text": "Python | Get unique values from a list"
}
] |
Check if the String ends with specified suffix in Golang | 26 Aug, 2019
In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In Go strings, you can check whether the string ends with the specified suffix or not with the help of HasSuffix() function. This function returns true if the given string ends with the specified suffix and return false if the given string does not end with the specified suffix. It is defined under the strings package so, you have to import strings package in your program for accessing HasSuffix function.
Syntax:
func HasSuffix(str, suf string) bool
Here, str is the original string and suf is a string which represents the suffix. The return type of this function is of the bool type.
Example:
// Go program to illustrate how to check the// given string start with the specified prefixpackage main import ( "fmt" "strings") // Main functionfunc main() { // Creating and initializing strings // Using shorthand declaration s1 := "I am working as a Technical content writer in GeeksforGeeks!" s2 := "I am currently writing articles on Go language!" // Checking the given strings // starts with the specified prefix // Using HasSuffix() function res1 := strings.HasSuffix(s1, "GeeksforGeeks!") res2 := strings.HasSuffix(s1, "!") res3 := strings.HasSuffix(s1, "Apple") res4 := strings.HasSuffix(s2, "language!") res5 := strings.HasSuffix(s2, "dog") res6 := strings.HasSuffix("GeeksforGeeks, Geeks", "Geeks") res7 := strings.HasSuffix("Welcome to GeeksforGeeks", "Welcome") // Displaying results fmt.Println("Result 1: ", res1) fmt.Println("Result 2: ", res2) fmt.Println("Result 3: ", res3) fmt.Println("Result 4: ", res4) fmt.Println("Result 5: ", res5) fmt.Println("Result 6: ", res6) fmt.Println("Result 7: ", res7)}
Output:
Result 1: true
Result 2: true
Result 3: false
Result 4: true
Result 5: false
Result 6: true
Result 7: false
Golang
Golang-String
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Parse JSON in Golang?
Constants- Go Language
Structures in Golang
Loops in Go Language
Time Durations in Golang
How to iterate over an Array using for loop in Golang?
Strings in Golang
Go Variables
time.Parse() Function in Golang With Examples
Class and Object in Golang | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 659,
"s": 28,
"text": "In Go language, strings are different from other languages like Java, C++, Python, etc. It is a sequence of variable-width characters where each and every character is represented by one or more bytes using UTF-8 Encoding.In Go strings, you can check whether the string ends with the specified suffix or not with the help of HasSuffix() function. This function returns true if the given string ends with the specified suffix and return false if the given string does not end with the specified suffix. It is defined under the strings package so, you have to import strings package in your program for accessing HasSuffix function."
},
{
"code": null,
"e": 667,
"s": 659,
"text": "Syntax:"
},
{
"code": null,
"e": 704,
"s": 667,
"text": "func HasSuffix(str, suf string) bool"
},
{
"code": null,
"e": 840,
"s": 704,
"text": "Here, str is the original string and suf is a string which represents the suffix. The return type of this function is of the bool type."
},
{
"code": null,
"e": 849,
"s": 840,
"text": "Example:"
},
{
"code": "// Go program to illustrate how to check the// given string start with the specified prefixpackage main import ( \"fmt\" \"strings\") // Main functionfunc main() { // Creating and initializing strings // Using shorthand declaration s1 := \"I am working as a Technical content writer in GeeksforGeeks!\" s2 := \"I am currently writing articles on Go language!\" // Checking the given strings // starts with the specified prefix // Using HasSuffix() function res1 := strings.HasSuffix(s1, \"GeeksforGeeks!\") res2 := strings.HasSuffix(s1, \"!\") res3 := strings.HasSuffix(s1, \"Apple\") res4 := strings.HasSuffix(s2, \"language!\") res5 := strings.HasSuffix(s2, \"dog\") res6 := strings.HasSuffix(\"GeeksforGeeks, Geeks\", \"Geeks\") res7 := strings.HasSuffix(\"Welcome to GeeksforGeeks\", \"Welcome\") // Displaying results fmt.Println(\"Result 1: \", res1) fmt.Println(\"Result 2: \", res2) fmt.Println(\"Result 3: \", res3) fmt.Println(\"Result 4: \", res4) fmt.Println(\"Result 5: \", res5) fmt.Println(\"Result 6: \", res6) fmt.Println(\"Result 7: \", res7)}",
"e": 1952,
"s": 849,
"text": null
},
{
"code": null,
"e": 1960,
"s": 1952,
"text": "Output:"
},
{
"code": null,
"e": 2076,
"s": 1960,
"text": "Result 1: true\nResult 2: true\nResult 3: false\nResult 4: true\nResult 5: false\nResult 6: true\nResult 7: false\n"
},
{
"code": null,
"e": 2083,
"s": 2076,
"text": "Golang"
},
{
"code": null,
"e": 2097,
"s": 2083,
"text": "Golang-String"
},
{
"code": null,
"e": 2109,
"s": 2097,
"text": "Go Language"
},
{
"code": null,
"e": 2207,
"s": 2109,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2236,
"s": 2207,
"text": "How to Parse JSON in Golang?"
},
{
"code": null,
"e": 2259,
"s": 2236,
"text": "Constants- Go Language"
},
{
"code": null,
"e": 2280,
"s": 2259,
"text": "Structures in Golang"
},
{
"code": null,
"e": 2301,
"s": 2280,
"text": "Loops in Go Language"
},
{
"code": null,
"e": 2326,
"s": 2301,
"text": "Time Durations in Golang"
},
{
"code": null,
"e": 2381,
"s": 2326,
"text": "How to iterate over an Array using for loop in Golang?"
},
{
"code": null,
"e": 2399,
"s": 2381,
"text": "Strings in Golang"
},
{
"code": null,
"e": 2412,
"s": 2399,
"text": "Go Variables"
},
{
"code": null,
"e": 2458,
"s": 2412,
"text": "time.Parse() Function in Golang With Examples"
}
] |
Find the first, second and third minimum elements in an array | 12 Jun, 2022
Find the first, second and third minimum elements in an array in O(n).Examples:
Input : 9 4 12 6
Output : First min = 4
Second min = 6
Third min = 9
Input : 4 9 1 32 12
Output : First min = 1
Second min = 4
Third min = 9
First approach : First we can use normal method that is sort the array and then print first, second and third element of the array. Time complexity of this solution is O(n Log n).Second approach : Time complexity of this solution is O(n).Algorithm-
First take an element
then if array[index] < Firstelement
Thirdelement = Secondelement
Secondelement = Firstelement
Firstelement = array[index]
else if array[index] < Secondelement
Thirdelement = Secondelement
Secondelement = array[index]
else if array[index] < Thirdelement
Thirdelement = array[index]
then print all the element
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find the first, second// and third minimum element in an array#include<bits/stdc++.h>#define MAX 100000using namespace std; int Print3Smallest(int array[], int n){ int firstmin = MAX, secmin = MAX, thirdmin = MAX; for (int i = 0; i < n; i++) { /* Check if current element is less than firstmin, then update first, second and third */ if (array[i] < firstmin) { thirdmin = secmin; secmin = firstmin; firstmin = array[i]; } /* Check if current element is less than secmin then update second and third */ else if (array[i] < secmin) { thirdmin = secmin; secmin = array[i]; } /* Check if current element is less than then update third */ else if (array[i] < thirdmin) thirdmin = array[i]; } cout << "First min = " << firstmin << "\n"; cout << "Second min = " << secmin << "\n"; cout << "Third min = " << thirdmin << "\n";} // Driver codeint main(){ int array[] = {4, 9, 1, 32, 12}; int n = sizeof(array) / sizeof(array[0]); Print3Smallest(array, n); return 0;}
// Java program to find the first, second// and third minimum element in an arrayimport java.util.*; public class GFG{ static void Print3Smallest(int array[], int n) { int firstmin = Integer.MAX_VALUE; int secmin = Integer.MAX_VALUE; int thirdmin = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { /* Check if current element is less than firstmin, then update first, second and third */ if (array[i] < firstmin) { thirdmin = secmin; secmin = firstmin; firstmin = array[i]; } /* Check if current element is less than secmin then update second and third */ else if (array[i] < secmin) { thirdmin = secmin; secmin = array[i]; } /* Check if current element is less than then update third */ else if (array[i] < thirdmin) thirdmin = array[i]; } System.out.println("First min = " + firstmin ); System.out.println("Second min = " + secmin ); System.out.println("Third min = " + thirdmin ); } // Driver code public static void main(String[] args) { int array[] = {4, 9, 1, 32, 12}; int n = array.length; Print3Smallest(array, n); } } // This code is contributed by// Sam007
# A Python program to find the first,# second and third minimum element# in an array MAX = 100000 def Print3Smallest(arr, n): firstmin = MAX secmin = MAX thirdmin = MAX for i in range(0, n): # Check if current element # is less than firstmin, # then update first,second # and third if arr[i] < firstmin: thirdmin = secmin secmin = firstmin firstmin = arr[i] # Check if current element is # less than secmin then update # second and third elif arr[i] < secmin: thirdmin = secmin secmin = arr[i] # Check if current element is # less than,then update third elif arr[i] < thirdmin: thirdmin = arr[i] print("First min = ", firstmin) print("Second min = ", secmin) print("Third min = ", thirdmin) # driver programarr = [4, 9, 1, 32, 12]n = len(arr)Print3Smallest(arr, n) # This code is contributed by Shrikant13.
// C# program to find the first, second// and third minimum element in an arrayusing System; class GFG{static void Print3Smallest(int []array, int n) { int firstmin = int.MaxValue; int secmin = int.MaxValue; int thirdmin = int.MaxValue; for (int i = 0; i < n; i++) { /* Check if current element is less than firstmin, then update first, second and third */ if (array[i] < firstmin) { thirdmin = secmin; secmin = firstmin; firstmin = array[i]; } /* Check if current element is less than secmin then update second and third */ else if (array[i] < secmin) { thirdmin = secmin; secmin = array[i]; } /* Check if current element is less than then update third */ else if (array[i] < thirdmin) thirdmin = array[i]; } Console.WriteLine("First min = " + firstmin ); Console.WriteLine("Second min = " + secmin ); Console.WriteLine("Third min = " + thirdmin ); } // Driver code static void Main() { int []array = new int[]{4, 9, 1, 32, 12}; int n = array.Length; Print3Smallest(array, n); }} // This code is contributed by Sam007
<?php// php program to find the first, second// and third minimum element in an array function Print3Smallest($array, $n){ $MAX = 100000; $firstmin = $MAX; $secmin = $MAX; $thirdmin = $MAX; for ($i = 0; $i < $n; $i++) { /* Check if current element is less than firstmin, then update first, second and third */ if ($array[$i] < $firstmin) { $thirdmin = $secmin; $secmin = $firstmin; $firstmin = $array[$i]; } /* Check if current element is less than secmin then update second and third */ else if ($array[$i] < $secmin) { $thirdmin = $secmin; $secmin = $array[$i]; } /* Check if current element is less than then update third */ else if ($array[$i] < $thirdmin) $thirdmin = $array[$i]; } echo "First min = ".$firstmin."\n"; echo "Second min = ".$secmin."\n"; echo "Third min = ".$thirdmin."\n";} // Driver code $array= array(4, 9, 1, 32, 12); $n = sizeof($array) / sizeof($array[0]); Print3Smallest($array, $n); // This code is contributed by mits?>
<script> // Javascript program to find the first, second// and third minimum element in an array let MAX = 100000 function Print3Smallest( array, n){ let firstmin = MAX, secmin = MAX, thirdmin = MAX; for (let i = 0; i < n; i++) { /* Check if current element is less than firstmin, then update first, second and third */ if (array[i] < firstmin) { thirdmin = secmin; secmin = firstmin; firstmin = array[i]; } /* Check if current element is less than secmin then update second and third */ else if (array[i] < secmin) { thirdmin = secmin; secmin = array[i]; } /* Check if current element is less than then update third */ else if (array[i] < thirdmin) thirdmin = array[i]; } document.write("First min = " + firstmin + "</br>"); document.write("Second min = " + secmin + "</br>"); document.write("Third min = " + thirdmin + "</br>");} // Driver program let array = [4, 9, 1, 32, 12]; let n = array.length; Print3Smallest(array, n); </script>
Output:
First min = 1
Second min = 4
Third min = 9
Time Complexity: O(n)Auxiliary Space: O(1)
shrikanth13
Mithun Kumar
jana_sayantan
sagartomar9927
codewithrathi
Arrays
School Programming
Searching
Arrays
Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
What is Data Structure: Types, Classifications and Applications
Chocolate Distribution Problem
Python Dictionary
Reverse a string in Java
Introduction To PYTHON
Interfaces in Java
Inheritance in C++ | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n12 Jun, 2022"
},
{
"code": null,
"e": 135,
"s": 53,
"text": "Find the first, second and third minimum elements in an array in O(n).Examples: "
},
{
"code": null,
"e": 313,
"s": 135,
"text": "Input : 9 4 12 6\nOutput : First min = 4\n Second min = 6\n Third min = 9\n\nInput : 4 9 1 32 12\nOutput : First min = 1\n Second min = 4\n Third min = 9"
},
{
"code": null,
"e": 566,
"s": 315,
"text": "First approach : First we can use normal method that is sort the array and then print first, second and third element of the array. Time complexity of this solution is O(n Log n).Second approach : Time complexity of this solution is O(n).Algorithm- "
},
{
"code": null,
"e": 956,
"s": 566,
"text": "First take an element\nthen if array[index] < Firstelement\n Thirdelement = Secondelement\n Secondelement = Firstelement\n Firstelement = array[index]\n else if array[index] < Secondelement\n Thirdelement = Secondelement\n Secondelement = array[index]\n else if array[index] < Thirdelement\n Thirdelement = array[index]\n\nthen print all the element "
},
{
"code": null,
"e": 962,
"s": 958,
"text": "C++"
},
{
"code": null,
"e": 967,
"s": 962,
"text": "Java"
},
{
"code": null,
"e": 975,
"s": 967,
"text": "Python3"
},
{
"code": null,
"e": 978,
"s": 975,
"text": "C#"
},
{
"code": null,
"e": 982,
"s": 978,
"text": "PHP"
},
{
"code": null,
"e": 993,
"s": 982,
"text": "Javascript"
},
{
"code": "// CPP program to find the first, second// and third minimum element in an array#include<bits/stdc++.h>#define MAX 100000using namespace std; int Print3Smallest(int array[], int n){ int firstmin = MAX, secmin = MAX, thirdmin = MAX; for (int i = 0; i < n; i++) { /* Check if current element is less than firstmin, then update first, second and third */ if (array[i] < firstmin) { thirdmin = secmin; secmin = firstmin; firstmin = array[i]; } /* Check if current element is less than secmin then update second and third */ else if (array[i] < secmin) { thirdmin = secmin; secmin = array[i]; } /* Check if current element is less than then update third */ else if (array[i] < thirdmin) thirdmin = array[i]; } cout << \"First min = \" << firstmin << \"\\n\"; cout << \"Second min = \" << secmin << \"\\n\"; cout << \"Third min = \" << thirdmin << \"\\n\";} // Driver codeint main(){ int array[] = {4, 9, 1, 32, 12}; int n = sizeof(array) / sizeof(array[0]); Print3Smallest(array, n); return 0;}",
"e": 2174,
"s": 993,
"text": null
},
{
"code": "// Java program to find the first, second// and third minimum element in an arrayimport java.util.*; public class GFG{ static void Print3Smallest(int array[], int n) { int firstmin = Integer.MAX_VALUE; int secmin = Integer.MAX_VALUE; int thirdmin = Integer.MAX_VALUE; for (int i = 0; i < n; i++) { /* Check if current element is less than firstmin, then update first, second and third */ if (array[i] < firstmin) { thirdmin = secmin; secmin = firstmin; firstmin = array[i]; } /* Check if current element is less than secmin then update second and third */ else if (array[i] < secmin) { thirdmin = secmin; secmin = array[i]; } /* Check if current element is less than then update third */ else if (array[i] < thirdmin) thirdmin = array[i]; } System.out.println(\"First min = \" + firstmin ); System.out.println(\"Second min = \" + secmin ); System.out.println(\"Third min = \" + thirdmin ); } // Driver code public static void main(String[] args) { int array[] = {4, 9, 1, 32, 12}; int n = array.length; Print3Smallest(array, n); } } // This code is contributed by// Sam007",
"e": 3754,
"s": 2174,
"text": null
},
{
"code": "# A Python program to find the first,# second and third minimum element# in an array MAX = 100000 def Print3Smallest(arr, n): firstmin = MAX secmin = MAX thirdmin = MAX for i in range(0, n): # Check if current element # is less than firstmin, # then update first,second # and third if arr[i] < firstmin: thirdmin = secmin secmin = firstmin firstmin = arr[i] # Check if current element is # less than secmin then update # second and third elif arr[i] < secmin: thirdmin = secmin secmin = arr[i] # Check if current element is # less than,then update third elif arr[i] < thirdmin: thirdmin = arr[i] print(\"First min = \", firstmin) print(\"Second min = \", secmin) print(\"Third min = \", thirdmin) # driver programarr = [4, 9, 1, 32, 12]n = len(arr)Print3Smallest(arr, n) # This code is contributed by Shrikant13.",
"e": 4747,
"s": 3754,
"text": null
},
{
"code": "// C# program to find the first, second// and third minimum element in an arrayusing System; class GFG{static void Print3Smallest(int []array, int n) { int firstmin = int.MaxValue; int secmin = int.MaxValue; int thirdmin = int.MaxValue; for (int i = 0; i < n; i++) { /* Check if current element is less than firstmin, then update first, second and third */ if (array[i] < firstmin) { thirdmin = secmin; secmin = firstmin; firstmin = array[i]; } /* Check if current element is less than secmin then update second and third */ else if (array[i] < secmin) { thirdmin = secmin; secmin = array[i]; } /* Check if current element is less than then update third */ else if (array[i] < thirdmin) thirdmin = array[i]; } Console.WriteLine(\"First min = \" + firstmin ); Console.WriteLine(\"Second min = \" + secmin ); Console.WriteLine(\"Third min = \" + thirdmin ); } // Driver code static void Main() { int []array = new int[]{4, 9, 1, 32, 12}; int n = array.Length; Print3Smallest(array, n); }} // This code is contributed by Sam007",
"e": 6270,
"s": 4747,
"text": null
},
{
"code": "<?php// php program to find the first, second// and third minimum element in an array function Print3Smallest($array, $n){ $MAX = 100000; $firstmin = $MAX; $secmin = $MAX; $thirdmin = $MAX; for ($i = 0; $i < $n; $i++) { /* Check if current element is less than firstmin, then update first, second and third */ if ($array[$i] < $firstmin) { $thirdmin = $secmin; $secmin = $firstmin; $firstmin = $array[$i]; } /* Check if current element is less than secmin then update second and third */ else if ($array[$i] < $secmin) { $thirdmin = $secmin; $secmin = $array[$i]; } /* Check if current element is less than then update third */ else if ($array[$i] < $thirdmin) $thirdmin = $array[$i]; } echo \"First min = \".$firstmin.\"\\n\"; echo \"Second min = \".$secmin.\"\\n\"; echo \"Third min = \".$thirdmin.\"\\n\";} // Driver code $array= array(4, 9, 1, 32, 12); $n = sizeof($array) / sizeof($array[0]); Print3Smallest($array, $n); // This code is contributed by mits?>",
"e": 7434,
"s": 6270,
"text": null
},
{
"code": "<script> // Javascript program to find the first, second// and third minimum element in an array let MAX = 100000 function Print3Smallest( array, n){ let firstmin = MAX, secmin = MAX, thirdmin = MAX; for (let i = 0; i < n; i++) { /* Check if current element is less than firstmin, then update first, second and third */ if (array[i] < firstmin) { thirdmin = secmin; secmin = firstmin; firstmin = array[i]; } /* Check if current element is less than secmin then update second and third */ else if (array[i] < secmin) { thirdmin = secmin; secmin = array[i]; } /* Check if current element is less than then update third */ else if (array[i] < thirdmin) thirdmin = array[i]; } document.write(\"First min = \" + firstmin + \"</br>\"); document.write(\"Second min = \" + secmin + \"</br>\"); document.write(\"Third min = \" + thirdmin + \"</br>\");} // Driver program let array = [4, 9, 1, 32, 12]; let n = array.length; Print3Smallest(array, n); </script>",
"e": 8595,
"s": 7434,
"text": null
},
{
"code": null,
"e": 8605,
"s": 8595,
"text": "Output: "
},
{
"code": null,
"e": 8648,
"s": 8605,
"text": "First min = 1\nSecond min = 4\nThird min = 9"
},
{
"code": null,
"e": 8691,
"s": 8648,
"text": "Time Complexity: O(n)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 8703,
"s": 8691,
"text": "shrikanth13"
},
{
"code": null,
"e": 8716,
"s": 8703,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 8730,
"s": 8716,
"text": "jana_sayantan"
},
{
"code": null,
"e": 8745,
"s": 8730,
"text": "sagartomar9927"
},
{
"code": null,
"e": 8759,
"s": 8745,
"text": "codewithrathi"
},
{
"code": null,
"e": 8766,
"s": 8759,
"text": "Arrays"
},
{
"code": null,
"e": 8785,
"s": 8766,
"text": "School Programming"
},
{
"code": null,
"e": 8795,
"s": 8785,
"text": "Searching"
},
{
"code": null,
"e": 8802,
"s": 8795,
"text": "Arrays"
},
{
"code": null,
"e": 8812,
"s": 8802,
"text": "Searching"
},
{
"code": null,
"e": 8910,
"s": 8812,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8942,
"s": 8910,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 8967,
"s": 8942,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 9014,
"s": 8967,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 9078,
"s": 9014,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 9109,
"s": 9078,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 9127,
"s": 9109,
"text": "Python Dictionary"
},
{
"code": null,
"e": 9152,
"s": 9127,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 9175,
"s": 9152,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 9194,
"s": 9175,
"text": "Interfaces in Java"
}
] |
KeyFactory getInstance() method in Java with Examples | 09 Jun, 2020
The getInstance() method of java.security.KeyFactory class returns a object of KeyFactory type that applys the assigned KeyFactory algorithm.
Syntax:
public static KeyFactory
getInstance(String algorithm)
throws NoSuchAlgorithmException
Parameters: This method seeks the standard Algorithm as a parameter whose instance is to be created to this KeyFactory instance.
Return Value: This method returns a new key factory object.
Exception: This method throws following exception:
NoSuchAlgorithmException: if no provider is available to support an key factory spi application for the particular algorithm.
NullPointerException: if algorithm is null.
Below are the examples to illustrate the getInstance() method:
Example 1:
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of KeyFactory // and getting instance // By using getInstance() method KeyFactory sr = KeyFactory.getInstance("DSA"); // getting the algorithm of KeyFactory object String str = sr.getAlgorithm(); // printing the status System.out.println("algorithm : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }}
algorithm : DSA
Example 2: To show NoSuchAlgorithmException
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of KeyFactory // and getting instance // By using getInstance() method KeyFactory sr = KeyFactory.getInstance("GEEKS"); // getting the algorithm of KeyFactory object String str = sr.getAlgorithm(); // printing the status System.out.println("algorithm : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } }}
Exception thrown :
java.security.NoSuchAlgorithmException:
GEEKS KeyFactory not available
The getInstance() method of java.security.KeyFactory class returns a object of KeyFactory type that applys the assigned KeyFactory algorithm and assigned provider object.
Syntax:
public static KeyFactory
getInstance(String algorithm, String provider)
throws NoSuchAlgorithmException
Parameters: This method seeks the following arguments as a parameters:
algorithm: which is the name of the algorithm specified to get the instance.
provider: which is the name of the provider to be specified
Return Value: This method returns an new key factory object.
Exception: This method throws following exceptions:
NoSuchAlgorithmException:– if no provider is available to support an key factory spi application for the particular algorithm.
IllegalArgumentException:– if the provider is null.
NullPointerException:– if algorithm is null
Below are the examples to illustrate the getInstance() method:
Example 1:
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of KeyFactory // and getting instance // By using getInstance() method KeyFactory sr = KeyFactory.getInstance( "DSA", "SUN"); // getting the algorithm of KeyFactory object String str = sr.getAlgorithm(); // printing the status System.out.println("algorithm : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } catch (NoSuchProviderException e) { System.out.println("Exception thrown : " + e); } }}
algorithm : DSA
Example 2: To show NoSuchAlgorithmException
// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of KeyFactory // and getting instance // By using getInstance() method KeyFactory sr = KeyFactory.getInstance( "RSA", "SUN"); // getting the algorithm of KeyFactory object String str = sr.getAlgorithm(); // printing the status System.out.println("algorithm : " + str); } catch (NoSuchAlgorithmException e) { System.out.println("Exception thrown : " + e); } catch (NullPointerException e) { System.out.println("Exception thrown : " + e); } catch (NoSuchProviderException e) { System.out.println("Exception thrown : " + e); } }}
Exception thrown :
java.security.NoSuchAlgorithmException:
no such algorithm: RSA for provider SUN
Reference: https://docs.oracle.com/javase/9/docs/api/java/security/KeyFactory.html#getInstance-java.lang.String-
Akanksha_Rai
Java-Functions
Java-KeyFactory
Java-security package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jun, 2020"
},
{
"code": null,
"e": 170,
"s": 28,
"text": "The getInstance() method of java.security.KeyFactory class returns a object of KeyFactory type that applys the assigned KeyFactory algorithm."
},
{
"code": null,
"e": 178,
"s": 170,
"text": "Syntax:"
},
{
"code": null,
"e": 269,
"s": 178,
"text": "public static KeyFactory\n getInstance(String algorithm)\n throws NoSuchAlgorithmException"
},
{
"code": null,
"e": 398,
"s": 269,
"text": "Parameters: This method seeks the standard Algorithm as a parameter whose instance is to be created to this KeyFactory instance."
},
{
"code": null,
"e": 458,
"s": 398,
"text": "Return Value: This method returns a new key factory object."
},
{
"code": null,
"e": 509,
"s": 458,
"text": "Exception: This method throws following exception:"
},
{
"code": null,
"e": 635,
"s": 509,
"text": "NoSuchAlgorithmException: if no provider is available to support an key factory spi application for the particular algorithm."
},
{
"code": null,
"e": 679,
"s": 635,
"text": "NullPointerException: if algorithm is null."
},
{
"code": null,
"e": 742,
"s": 679,
"text": "Below are the examples to illustrate the getInstance() method:"
},
{
"code": null,
"e": 753,
"s": 742,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of KeyFactory // and getting instance // By using getInstance() method KeyFactory sr = KeyFactory.getInstance(\"DSA\"); // getting the algorithm of KeyFactory object String str = sr.getAlgorithm(); // printing the status System.out.println(\"algorithm : \" + str); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 1566,
"s": 753,
"text": null
},
{
"code": null,
"e": 1583,
"s": 1566,
"text": "algorithm : DSA\n"
},
{
"code": null,
"e": 1627,
"s": 1583,
"text": "Example 2: To show NoSuchAlgorithmException"
},
{
"code": "// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of KeyFactory // and getting instance // By using getInstance() method KeyFactory sr = KeyFactory.getInstance(\"GEEKS\"); // getting the algorithm of KeyFactory object String str = sr.getAlgorithm(); // printing the status System.out.println(\"algorithm : \" + str); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 2427,
"s": 1627,
"text": null
},
{
"code": null,
"e": 2520,
"s": 2427,
"text": "Exception thrown :\n java.security.NoSuchAlgorithmException:\n GEEKS KeyFactory not available\n"
},
{
"code": null,
"e": 2691,
"s": 2520,
"text": "The getInstance() method of java.security.KeyFactory class returns a object of KeyFactory type that applys the assigned KeyFactory algorithm and assigned provider object."
},
{
"code": null,
"e": 2699,
"s": 2691,
"text": "Syntax:"
},
{
"code": null,
"e": 2807,
"s": 2699,
"text": "public static KeyFactory\n getInstance(String algorithm, String provider)\n throws NoSuchAlgorithmException"
},
{
"code": null,
"e": 2878,
"s": 2807,
"text": "Parameters: This method seeks the following arguments as a parameters:"
},
{
"code": null,
"e": 2955,
"s": 2878,
"text": "algorithm: which is the name of the algorithm specified to get the instance."
},
{
"code": null,
"e": 3015,
"s": 2955,
"text": "provider: which is the name of the provider to be specified"
},
{
"code": null,
"e": 3076,
"s": 3015,
"text": "Return Value: This method returns an new key factory object."
},
{
"code": null,
"e": 3128,
"s": 3076,
"text": "Exception: This method throws following exceptions:"
},
{
"code": null,
"e": 3255,
"s": 3128,
"text": "NoSuchAlgorithmException:– if no provider is available to support an key factory spi application for the particular algorithm."
},
{
"code": null,
"e": 3307,
"s": 3255,
"text": "IllegalArgumentException:– if the provider is null."
},
{
"code": null,
"e": 3351,
"s": 3307,
"text": "NullPointerException:– if algorithm is null"
},
{
"code": null,
"e": 3414,
"s": 3351,
"text": "Below are the examples to illustrate the getInstance() method:"
},
{
"code": null,
"e": 3425,
"s": 3414,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of KeyFactory // and getting instance // By using getInstance() method KeyFactory sr = KeyFactory.getInstance( \"DSA\", \"SUN\"); // getting the algorithm of KeyFactory object String str = sr.getAlgorithm(); // printing the status System.out.println(\"algorithm : \" + str); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } catch (NoSuchProviderException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 4373,
"s": 3425,
"text": null
},
{
"code": null,
"e": 4390,
"s": 4373,
"text": "algorithm : DSA\n"
},
{
"code": null,
"e": 4434,
"s": 4390,
"text": "Example 2: To show NoSuchAlgorithmException"
},
{
"code": "// Java program to demonstrate// getInstance() method import java.security.*;import java.util.*; public class GFG1 { public static void main(String[] argv) { try { // creating the object of KeyFactory // and getting instance // By using getInstance() method KeyFactory sr = KeyFactory.getInstance( \"RSA\", \"SUN\"); // getting the algorithm of KeyFactory object String str = sr.getAlgorithm(); // printing the status System.out.println(\"algorithm : \" + str); } catch (NoSuchAlgorithmException e) { System.out.println(\"Exception thrown : \" + e); } catch (NullPointerException e) { System.out.println(\"Exception thrown : \" + e); } catch (NoSuchProviderException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 5382,
"s": 4434,
"text": null
},
{
"code": null,
"e": 5484,
"s": 5382,
"text": "Exception thrown :\n java.security.NoSuchAlgorithmException:\n no such algorithm: RSA for provider SUN\n"
},
{
"code": null,
"e": 5597,
"s": 5484,
"text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/security/KeyFactory.html#getInstance-java.lang.String-"
},
{
"code": null,
"e": 5610,
"s": 5597,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5625,
"s": 5610,
"text": "Java-Functions"
},
{
"code": null,
"e": 5641,
"s": 5625,
"text": "Java-KeyFactory"
},
{
"code": null,
"e": 5663,
"s": 5641,
"text": "Java-security package"
},
{
"code": null,
"e": 5668,
"s": 5663,
"text": "Java"
},
{
"code": null,
"e": 5673,
"s": 5668,
"text": "Java"
},
{
"code": null,
"e": 5771,
"s": 5673,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5822,
"s": 5771,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 5853,
"s": 5822,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 5872,
"s": 5853,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 5902,
"s": 5872,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 5917,
"s": 5902,
"text": "Stream In Java"
},
{
"code": null,
"e": 5935,
"s": 5917,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 5955,
"s": 5935,
"text": "Collections in Java"
},
{
"code": null,
"e": 5979,
"s": 5955,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 6011,
"s": 5979,
"text": "Multidimensional Arrays in Java"
}
] |
Seaborn – Coloring Boxplots with Palettes | 27 Sep, 2021
Adding the right set of color with your data visualization makes it more impressive and readable, seaborn color palettes make it easy to use colors with your visualization. In this article, we will see how to color boxplot with seaborn color palettes also learn the uses of seaborn color palettes and it can be applied to other plots as well.
Step-by-step Approach:
Step 1: Load the python packages and libraries required to color a boxplot.
Python3
# import librariesimport seaborn as sns import matplotlib.pyplot as plt
Step 2: Load the dataset to generate a boxplot.
Python3
# loading datasetds = sns.load_dataset('iris')
Step 3: Generate a boxplot using the boxplot() method.
Python3
# create boxplot objectax = sns.boxplot(data=tips, orient="h")
Step 4: Seaborn boxplot() function has palette argument, in this example we have set palette=”Set1′′, it uses a qualitative color paletter Set3 to color the boxes in boxpolot. So add palette parameter in boxplot method.
Python3
# use palette methodax = sns.boxplot(data=ds, orient="h", palette="Set1")
Below is the complete program based on the above approach:
Python3
# import librariesimport seaborn as snsimport matplotlib.pyplot as plt # load datasetds = sns.load_dataset("tips") plt.figure(figsize=(8, 6)) # use palette methodax = sns.boxplot(data=ds, orient="h", palette="Set1")
Coloring Boxplots with Seaborn Palettes
abhishek0719kadiyan
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace() | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Sep, 2021"
},
{
"code": null,
"e": 398,
"s": 54,
"text": "Adding the right set of color with your data visualization makes it more impressive and readable, seaborn color palettes make it easy to use colors with your visualization. In this article, we will see how to color boxplot with seaborn color palettes also learn the uses of seaborn color palettes and it can be applied to other plots as well. "
},
{
"code": null,
"e": 421,
"s": 398,
"text": "Step-by-step Approach:"
},
{
"code": null,
"e": 497,
"s": 421,
"text": "Step 1: Load the python packages and libraries required to color a boxplot."
},
{
"code": null,
"e": 505,
"s": 497,
"text": "Python3"
},
{
"code": "# import librariesimport seaborn as sns import matplotlib.pyplot as plt",
"e": 577,
"s": 505,
"text": null
},
{
"code": null,
"e": 625,
"s": 577,
"text": "Step 2: Load the dataset to generate a boxplot."
},
{
"code": null,
"e": 633,
"s": 625,
"text": "Python3"
},
{
"code": "# loading datasetds = sns.load_dataset('iris')",
"e": 680,
"s": 633,
"text": null
},
{
"code": null,
"e": 736,
"s": 680,
"text": "Step 3: Generate a boxplot using the boxplot() method. "
},
{
"code": null,
"e": 744,
"s": 736,
"text": "Python3"
},
{
"code": "# create boxplot objectax = sns.boxplot(data=tips, orient=\"h\")",
"e": 807,
"s": 744,
"text": null
},
{
"code": null,
"e": 1027,
"s": 807,
"text": "Step 4: Seaborn boxplot() function has palette argument, in this example we have set palette=”Set1′′, it uses a qualitative color paletter Set3 to color the boxes in boxpolot. So add palette parameter in boxplot method."
},
{
"code": null,
"e": 1035,
"s": 1027,
"text": "Python3"
},
{
"code": "# use palette methodax = sns.boxplot(data=ds, orient=\"h\", palette=\"Set1\")",
"e": 1109,
"s": 1035,
"text": null
},
{
"code": null,
"e": 1168,
"s": 1109,
"text": "Below is the complete program based on the above approach:"
},
{
"code": null,
"e": 1176,
"s": 1168,
"text": "Python3"
},
{
"code": "# import librariesimport seaborn as snsimport matplotlib.pyplot as plt # load datasetds = sns.load_dataset(\"tips\") plt.figure(figsize=(8, 6)) # use palette methodax = sns.boxplot(data=ds, orient=\"h\", palette=\"Set1\")",
"e": 1392,
"s": 1176,
"text": null
},
{
"code": null,
"e": 1432,
"s": 1392,
"text": "Coloring Boxplots with Seaborn Palettes"
},
{
"code": null,
"e": 1452,
"s": 1432,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 1467,
"s": 1452,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 1474,
"s": 1467,
"text": "Python"
},
{
"code": null,
"e": 1572,
"s": 1474,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1600,
"s": 1572,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1650,
"s": 1600,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 1672,
"s": 1650,
"text": "Python map() function"
},
{
"code": null,
"e": 1716,
"s": 1672,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 1734,
"s": 1716,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1776,
"s": 1734,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1799,
"s": 1776,
"text": "Taking input in Python"
},
{
"code": null,
"e": 1821,
"s": 1799,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1856,
"s": 1821,
"text": "Read a file line by line in Python"
}
] |
Modulo Operator (%) in C/C++ with Examples | 17 Jun, 2022
The modulo operator, denoted by %, is an arithmetic operator. The modulo division operator produces the remainder of an integer division.
Syntax: If x and y are integers, then the expression:
x % y
produces the remainder when x is divided by y.
Return Value:
If y completely divides x, the result of the expression is 0.
If x is not completely divisible by y, then the result will be the remainder in the range [1, x-1].
If y is 0, then division by zero is a compile-time error.
For example: Consider the following code:
C++
C
Java
Python3
C#
Javascript
// Program to illustrate the// working of modulo operator#include <iostream>using namespace std; int main(void){ // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = 3; y = 4; result = x % y; cout << result << endl; result = y % x; cout << result << endl; x = 4; y = 2; result = x % y; cout<<result; return 0;} // This code is contributed by Mayank Tyagi
// Program to illustrate the// working of modulo operator #include <stdio.h> int main(void){ // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = 3; y = 4; result = x % y; printf("%d", result); result = y % x; printf("\n%d", result); x = 4; y = 2; result = x % y; printf("\n%d", result); return 0;}
// Java Program to illustrate the// working of modulo operatorimport java.io.*; class GFG { // Driver Code public static void main (String[] args) { // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = 3; y = 4; result = x % y; System.out.println(result); result = y % x; System.out.println(result); x = 4; y = 2; result = x % y; System.out.println(result); }} // This code is contributed by Shubham Singh
# Python Program to illustrate the# working of modulo operator # To store two integer valuesx = 0y = 0 # To store the result of# the modulo expressionresult = 0 x = 3y = 4result = x % yprint(result) result = y % xprint(result) x = 4y = 2result = x % yprint(result) # This code is contributed by Shubham Singh
// C# Program to illustrate the// working of modulo operatorusing System;public class GFG{ // Driver Code static public void Main () { // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = 3; y = 4; result = x % y; Console.WriteLine(result); result = y % x; Console.WriteLine(result); x = 4; y = 2; result = x % y; Console.WriteLine(result); }} // This code is contributed by Shubham Singh
<script> // Program to illustrate the// working of modulo operator // To store two integer valuesvar x, y; // To store the result of// the modulo expressionvar result; x = 3;y = 4;result = x % y;document.write(result +"<br>"); result = y % x;document.write(result +"<br>"); x = 4;y = 2;result = x % y;document.write(result +"<br>"); // This code is contributed by Shubham Singh</script>
3
1
0
Restrictions of the modulo operator: The modulo operator has quite some restrictions or limitations.
The % operator cannot be applied to floating-point numbers i.e float or double. If you try to use the modulo operator with floating-point constants or variables, the compiler will produce an error:
C++
C
Java
Python3
C#
Javascript
// Program to illustrate the// working of modulo operator#include <iostream>using namespace std; int main(){ // To store two integer values float x, y; // To store the result of // the modulo expression float result; x = 2.3; y = 1.5; result = x % y; cout << result; return 0;} // This code is contributed by Harshit Srivastava
// Program to illustrate the// working of modulo operator #include <stdio.h> int main(void){ // To store two integer values float x, y; // To store the result of // the modulo expression float result; x = 2.3; y = 1.5; result = x % y; printf("%f", result); return 0;}
// Java implementation of the above approachimport java.io.*;import java.util.*; class GFG { public static void main (String[] args) { // To store two integer values float x, y; // To store the result of // the modulo expression float result; x = 2.3; y = 1.5; result = x % y; System.out.println(result); }} // This code is contributed by Shubham Singh
# Program to illustrate the# working of modulo operator # To store two integer valuesx, y = 0, 0 # To store the result of# the modulo expressionresult = 0 x = 2.3y = 1.5result = x % yprint(result) # This code is contribute by Shubham Singh
using System; public class GFG{ static public void Main () { // To store two integer values float x, y; // To store the result of // the modulo expression float result; x = 2.3; y = 1.5; result = x % y; Console.Write(result); }} // This code is contributed by Shubham Singh
<script> // Program to illustrate the// working of modulo operator // To store two integer valuesvar x, y; // To store the result of// the modulo expressionvar result; x = 2.3;y = 1.5;result = x % y;document.write(result +"<br>"); // This code is contributed by Shubham Singh</script>
Compilation Error:
Compilation Error in C code :- prog.c: In function 'main':
prog.c:19:16: error:
invalid operands to binary % (have 'float' and 'float')
result = x % y;
^
The sign of the result for modulo operator is machine-dependent for negative operands, as the action takes as a result of underflow or overflow.
C++
C
Java
C#
// Program to illustrate the// working of the modulo operator#include <iostream>using namespace std; int main(void){ // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = -3; y = 4; result = x % y; cout << result << endl; x = 4; y = -2; result = x % y; cout << result << endl; x = -3; y = -4; result = x % y; cout << result; return 0;} // This code is contributed by Harshit Srivastava
// Program to illustrate the// working of the modulo operator #include <stdio.h> int main(void){ // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = -3; y = 4; result = x % y; printf("%d", result); x = 4; y = -2; result = x % y; printf("\n%d", result); x = -3; y = -4; result = x % y; printf("\n%d", result); return 0;}
import java.io.*; class GFG { public static void main (String[] args) { // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = -3; y = 4; result = x % y; System.out.println(result); x = 4; y = -2; result = x % y; System.out.println(result); x = -3; y = -4; result = x % y; System.out.println(result); }} // This code is contributed by sarajadhav12052009
using System; public class GFG{ static public void Main () { // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = -3; y = 4; result = x % y; Console.WriteLine(result); x = 4; y = -2; result = x % y; Console.WriteLine(result); x = -3; y = -4; result = x % y; Console.WriteLine(result); }} // This code is contributed by sarajadhav12052009
-3
0
-3
Note: Some compilers may show the result of the expression as 1 and other may show -1. It depends on the compiler.
shubhamkumarlhh
mayanktyagi1709
srivastavaharshit848
alexandrebinninger
SHUBHAMSINGH10
avtarkumar719
harendrakumar123
sarajadhav12052009
C-Operators
cpp-operator
C Language
C++
Mathematical
Programming Language
cpp-operator
Mathematical
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Initialize a vector in C++ (7 different ways)
Templates in C++ with Examples
Operator Overloading in C++
Inheritance in C++ | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 192,
"s": 53,
"text": "The modulo operator, denoted by %, is an arithmetic operator. The modulo division operator produces the remainder of an integer division. "
},
{
"code": null,
"e": 247,
"s": 192,
"text": "Syntax: If x and y are integers, then the expression: "
},
{
"code": null,
"e": 253,
"s": 247,
"text": "x % y"
},
{
"code": null,
"e": 301,
"s": 253,
"text": "produces the remainder when x is divided by y. "
},
{
"code": null,
"e": 316,
"s": 301,
"text": "Return Value: "
},
{
"code": null,
"e": 378,
"s": 316,
"text": "If y completely divides x, the result of the expression is 0."
},
{
"code": null,
"e": 478,
"s": 378,
"text": "If x is not completely divisible by y, then the result will be the remainder in the range [1, x-1]."
},
{
"code": null,
"e": 536,
"s": 478,
"text": "If y is 0, then division by zero is a compile-time error."
},
{
"code": null,
"e": 578,
"s": 536,
"text": "For example: Consider the following code:"
},
{
"code": null,
"e": 582,
"s": 578,
"text": "C++"
},
{
"code": null,
"e": 584,
"s": 582,
"text": "C"
},
{
"code": null,
"e": 589,
"s": 584,
"text": "Java"
},
{
"code": null,
"e": 597,
"s": 589,
"text": "Python3"
},
{
"code": null,
"e": 600,
"s": 597,
"text": "C#"
},
{
"code": null,
"e": 611,
"s": 600,
"text": "Javascript"
},
{
"code": "// Program to illustrate the// working of modulo operator#include <iostream>using namespace std; int main(void){ // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = 3; y = 4; result = x % y; cout << result << endl; result = y % x; cout << result << endl; x = 4; y = 2; result = x % y; cout<<result; return 0;} // This code is contributed by Mayank Tyagi",
"e": 1075,
"s": 611,
"text": null
},
{
"code": "// Program to illustrate the// working of modulo operator #include <stdio.h> int main(void){ // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = 3; y = 4; result = x % y; printf(\"%d\", result); result = y % x; printf(\"\\n%d\", result); x = 4; y = 2; result = x % y; printf(\"\\n%d\", result); return 0;}",
"e": 1483,
"s": 1075,
"text": null
},
{
"code": "// Java Program to illustrate the// working of modulo operatorimport java.io.*; class GFG { // Driver Code public static void main (String[] args) { // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = 3; y = 4; result = x % y; System.out.println(result); result = y % x; System.out.println(result); x = 4; y = 2; result = x % y; System.out.println(result); }} // This code is contributed by Shubham Singh",
"e": 1999,
"s": 1483,
"text": null
},
{
"code": "# Python Program to illustrate the# working of modulo operator # To store two integer valuesx = 0y = 0 # To store the result of# the modulo expressionresult = 0 x = 3y = 4result = x % yprint(result) result = y % xprint(result) x = 4y = 2result = x % yprint(result) # This code is contributed by Shubham Singh",
"e": 2308,
"s": 1999,
"text": null
},
{
"code": "// C# Program to illustrate the// working of modulo operatorusing System;public class GFG{ // Driver Code static public void Main () { // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = 3; y = 4; result = x % y; Console.WriteLine(result); result = y % x; Console.WriteLine(result); x = 4; y = 2; result = x % y; Console.WriteLine(result); }} // This code is contributed by Shubham Singh",
"e": 2807,
"s": 2308,
"text": null
},
{
"code": "<script> // Program to illustrate the// working of modulo operator // To store two integer valuesvar x, y; // To store the result of// the modulo expressionvar result; x = 3;y = 4;result = x % y;document.write(result +\"<br>\"); result = y % x;document.write(result +\"<br>\"); x = 4;y = 2;result = x % y;document.write(result +\"<br>\"); // This code is contributed by Shubham Singh</script>",
"e": 3194,
"s": 2807,
"text": null
},
{
"code": null,
"e": 3200,
"s": 3194,
"text": "3\n1\n0"
},
{
"code": null,
"e": 3301,
"s": 3200,
"text": "Restrictions of the modulo operator: The modulo operator has quite some restrictions or limitations."
},
{
"code": null,
"e": 3499,
"s": 3301,
"text": "The % operator cannot be applied to floating-point numbers i.e float or double. If you try to use the modulo operator with floating-point constants or variables, the compiler will produce an error:"
},
{
"code": null,
"e": 3503,
"s": 3499,
"text": "C++"
},
{
"code": null,
"e": 3505,
"s": 3503,
"text": "C"
},
{
"code": null,
"e": 3510,
"s": 3505,
"text": "Java"
},
{
"code": null,
"e": 3518,
"s": 3510,
"text": "Python3"
},
{
"code": null,
"e": 3521,
"s": 3518,
"text": "C#"
},
{
"code": null,
"e": 3532,
"s": 3521,
"text": "Javascript"
},
{
"code": "// Program to illustrate the// working of modulo operator#include <iostream>using namespace std; int main(){ // To store two integer values float x, y; // To store the result of // the modulo expression float result; x = 2.3; y = 1.5; result = x % y; cout << result; return 0;} // This code is contributed by Harshit Srivastava",
"e": 3898,
"s": 3532,
"text": null
},
{
"code": "// Program to illustrate the// working of modulo operator #include <stdio.h> int main(void){ // To store two integer values float x, y; // To store the result of // the modulo expression float result; x = 2.3; y = 1.5; result = x % y; printf(\"%f\", result); return 0;}",
"e": 4200,
"s": 3898,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.io.*;import java.util.*; class GFG { public static void main (String[] args) { // To store two integer values float x, y; // To store the result of // the modulo expression float result; x = 2.3; y = 1.5; result = x % y; System.out.println(result); }} // This code is contributed by Shubham Singh",
"e": 4645,
"s": 4200,
"text": null
},
{
"code": "# Program to illustrate the# working of modulo operator # To store two integer valuesx, y = 0, 0 # To store the result of# the modulo expressionresult = 0 x = 2.3y = 1.5result = x % yprint(result) # This code is contribute by Shubham Singh",
"e": 4885,
"s": 4645,
"text": null
},
{
"code": "using System; public class GFG{ static public void Main () { // To store two integer values float x, y; // To store the result of // the modulo expression float result; x = 2.3; y = 1.5; result = x % y; Console.Write(result); }} // This code is contributed by Shubham Singh",
"e": 5251,
"s": 4885,
"text": null
},
{
"code": "<script> // Program to illustrate the// working of modulo operator // To store two integer valuesvar x, y; // To store the result of// the modulo expressionvar result; x = 2.3;y = 1.5;result = x % y;document.write(result +\"<br>\"); // This code is contributed by Shubham Singh</script>",
"e": 5536,
"s": 5251,
"text": null
},
{
"code": null,
"e": 5556,
"s": 5536,
"text": "Compilation Error: "
},
{
"code": null,
"e": 5743,
"s": 5556,
"text": "Compilation Error in C code :- prog.c: In function 'main':\nprog.c:19:16: error:\n invalid operands to binary % (have 'float' and 'float')\n result = x % y;\n ^ "
},
{
"code": null,
"e": 5889,
"s": 5743,
"text": "The sign of the result for modulo operator is machine-dependent for negative operands, as the action takes as a result of underflow or overflow. "
},
{
"code": null,
"e": 5893,
"s": 5889,
"text": "C++"
},
{
"code": null,
"e": 5895,
"s": 5893,
"text": "C"
},
{
"code": null,
"e": 5900,
"s": 5895,
"text": "Java"
},
{
"code": null,
"e": 5903,
"s": 5900,
"text": "C#"
},
{
"code": "// Program to illustrate the// working of the modulo operator#include <iostream>using namespace std; int main(void){ // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = -3; y = 4; result = x % y; cout << result << endl; x = 4; y = -2; result = x % y; cout << result << endl; x = -3; y = -4; result = x % y; cout << result; return 0;} // This code is contributed by Harshit Srivastava",
"e": 6407,
"s": 5903,
"text": null
},
{
"code": "// Program to illustrate the// working of the modulo operator #include <stdio.h> int main(void){ // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = -3; y = 4; result = x % y; printf(\"%d\", result); x = 4; y = -2; result = x % y; printf(\"\\n%d\", result); x = -3; y = -4; result = x % y; printf(\"\\n%d\", result); return 0;}",
"e": 6843,
"s": 6407,
"text": null
},
{
"code": "import java.io.*; class GFG { public static void main (String[] args) { // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = -3; y = 4; result = x % y; System.out.println(result); x = 4; y = -2; result = x % y; System.out.println(result); x = -3; y = -4; result = x % y; System.out.println(result); }} // This code is contributed by sarajadhav12052009",
"e": 7382,
"s": 6843,
"text": null
},
{
"code": "using System; public class GFG{ static public void Main () { // To store two integer values int x, y; // To store the result of // the modulo expression int result; x = -3; y = 4; result = x % y; Console.WriteLine(result); x = 4; y = -2; result = x % y; Console.WriteLine(result); x = -3; y = -4; result = x % y; Console.WriteLine(result); }} // This code is contributed by sarajadhav12052009",
"e": 7910,
"s": 7382,
"text": null
},
{
"code": null,
"e": 7918,
"s": 7910,
"text": "-3\n0\n-3"
},
{
"code": null,
"e": 8033,
"s": 7918,
"text": "Note: Some compilers may show the result of the expression as 1 and other may show -1. It depends on the compiler."
},
{
"code": null,
"e": 8049,
"s": 8033,
"text": "shubhamkumarlhh"
},
{
"code": null,
"e": 8065,
"s": 8049,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 8086,
"s": 8065,
"text": "srivastavaharshit848"
},
{
"code": null,
"e": 8105,
"s": 8086,
"text": "alexandrebinninger"
},
{
"code": null,
"e": 8120,
"s": 8105,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 8134,
"s": 8120,
"text": "avtarkumar719"
},
{
"code": null,
"e": 8151,
"s": 8134,
"text": "harendrakumar123"
},
{
"code": null,
"e": 8170,
"s": 8151,
"text": "sarajadhav12052009"
},
{
"code": null,
"e": 8182,
"s": 8170,
"text": "C-Operators"
},
{
"code": null,
"e": 8195,
"s": 8182,
"text": "cpp-operator"
},
{
"code": null,
"e": 8206,
"s": 8195,
"text": "C Language"
},
{
"code": null,
"e": 8210,
"s": 8206,
"text": "C++"
},
{
"code": null,
"e": 8223,
"s": 8210,
"text": "Mathematical"
},
{
"code": null,
"e": 8244,
"s": 8223,
"text": "Programming Language"
},
{
"code": null,
"e": 8257,
"s": 8244,
"text": "cpp-operator"
},
{
"code": null,
"e": 8270,
"s": 8257,
"text": "Mathematical"
},
{
"code": null,
"e": 8274,
"s": 8270,
"text": "CPP"
},
{
"code": null,
"e": 8372,
"s": 8274,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 8389,
"s": 8372,
"text": "Substring in C++"
},
{
"code": null,
"e": 8424,
"s": 8389,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 8446,
"s": 8424,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 8492,
"s": 8446,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 8537,
"s": 8492,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 8555,
"s": 8537,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 8601,
"s": 8555,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 8632,
"s": 8601,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 8660,
"s": 8632,
"text": "Operator Overloading in C++"
}
] |
Exceptions – Selenium Python | 30 Apr, 2020
Exceptions in Selenium Python are the errors that occur when one of method fails or an unexpected event occurs. All instances in Python must be instances of a class that derives from BaseException. Two exception classes that are not related via subclassing are never equivalent, even if they have the same name. The built-in exceptions can be generated by the interpreter or built-in functions. This article revolves around multiple exceptions that can occur during the run of a Selenium program.
Let’s demonstrate Exception by trying to find an element that doesn’t exist and click it at geeksforgeeks.org
# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get("https://www.geeksforgeeks.org/") # get element element = driver.find_element_by_link_text("abrakadabra") # click the itemprint(element.click())
Now, let’s run this program, it first open geeksforgeeks.org and then raise exception – selenium.common.exceptions.NoSuchElementException, which means that element doesn’t exists on the website.
Exceptions are of primary use when you are writing development ready code especially which is at a high risk of causing certain type of exception. So here is list of all exceptions in Selenium Python.
Python-selenium
selenium
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Iterate over a list in Python
Read JSON file using Python
Python map() function
How to iterate through Excel rows in Python?
Enumerate() in Python
Adding new column to existing DataFrame in Pandas
Python OOPs Concepts
Different ways to create Pandas Dataframe
How to get column names in Pandas dataframe
Stack in Python | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n30 Apr, 2020"
},
{
"code": null,
"e": 549,
"s": 52,
"text": "Exceptions in Selenium Python are the errors that occur when one of method fails or an unexpected event occurs. All instances in Python must be instances of a class that derives from BaseException. Two exception classes that are not related via subclassing are never equivalent, even if they have the same name. The built-in exceptions can be generated by the interpreter or built-in functions. This article revolves around multiple exceptions that can occur during the run of a Selenium program."
},
{
"code": null,
"e": 659,
"s": 549,
"text": "Let’s demonstrate Exception by trying to find an element that doesn’t exist and click it at geeksforgeeks.org"
},
{
"code": "# import webdriverfrom selenium import webdriver # create webdriver objectdriver = webdriver.Firefox() # get geeksforgeeks.orgdriver.get(\"https://www.geeksforgeeks.org/\") # get element element = driver.find_element_by_link_text(\"abrakadabra\") # click the itemprint(element.click())",
"e": 945,
"s": 659,
"text": null
},
{
"code": null,
"e": 1140,
"s": 945,
"text": "Now, let’s run this program, it first open geeksforgeeks.org and then raise exception – selenium.common.exceptions.NoSuchElementException, which means that element doesn’t exists on the website."
},
{
"code": null,
"e": 1341,
"s": 1140,
"text": "Exceptions are of primary use when you are writing development ready code especially which is at a high risk of causing certain type of exception. So here is list of all exceptions in Selenium Python."
},
{
"code": null,
"e": 1357,
"s": 1341,
"text": "Python-selenium"
},
{
"code": null,
"e": 1366,
"s": 1357,
"text": "selenium"
},
{
"code": null,
"e": 1373,
"s": 1366,
"text": "Python"
},
{
"code": null,
"e": 1471,
"s": 1373,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1501,
"s": 1471,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1529,
"s": 1501,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 1551,
"s": 1529,
"text": "Python map() function"
},
{
"code": null,
"e": 1596,
"s": 1551,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 1618,
"s": 1596,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1668,
"s": 1618,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 1689,
"s": 1668,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1731,
"s": 1689,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1775,
"s": 1731,
"text": "How to get column names in Pandas dataframe"
}
] |
Scatterplot using Seaborn in Python | 05 Nov, 2020
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas.
Scatterplot can be used with several semantic groupings which can help to understand well in a graph. They can plot two-dimensional graphics that can be enhanced by mapping up to three additional variables while using the semantics of hue, size, and style parameters. All the parameter control visual semantic which are used to identify the different subsets. Using redundant semantics can be helpful for making graphics more accessible.
Syntax: seaborn.scatterplot(x=None, y=None, hue=None, style=None, size=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, markers=True, style_order=None, x_bins=None, y_bins=None, units=None, estimator=None, ci=95, n_boot=1000, alpha=’auto’, x_jitter=None, y_jitter=None, legend=’brief’, ax=None, **kwargs)Parameters:x, y: Input data variables that should be numeric.
data: Dataframe where each column is a variable and each row is an observation.
size: Grouping variable that will produce points with different sizes.
style: Grouping variable that will produce points with different markers.
palette: Grouping variable that will produce points with different markers.
markers: Object determining how to draw the markers for different levels.
alpha: Proportional opacity of the points.
Returns: This method returns the Axes object with the plot drawn onto it.
Let’s visualize of “fmri” dataset using seaborn.scatterplot() function. We will only use the x, y parameters of the function.
Code:
Python3
import seaborn seaborn.set(style='whitegrid')fmri = seaborn.load_dataset("fmri") seaborn.scatterplot(x="timepoint", y="signal", data=fmri)
Output:
Grouping data points on the basis of category, here as region and event.
Python3
import seaborn seaborn.set(style='whitegrid')fmri = seaborn.load_dataset("fmri") seaborn.scatterplot(x="timepoint", y="signal", hue="region", style="event", data=fmri)
Output:
Basic visualization of “tips” dataset using Scatterplot.
Python3
import seaborn seaborn.set(style='whitegrid')tip = seaborn.load_dataset('tips') seaborn.scatterplot(x='day', y='tip', data=tip)
Output:
1. Adding the marker attributes
The circle is used to represent the data point and the default marker here is a blue circle. In the above output, we are seeing the default output for the marker, but we can customize this blue circle with marker attributes.
Python3
seaborn.scatterplot(x='day', y='tip', data= tip, marker = '+')
Output:
2. Adding the hue attributes.
It will produce data points with different colors. Hue can be used to group to multiple data variable and show the dependency of the passed data values are to be plotted.
Syntax: seaborn.scatterplot( x, y, data, hue)
Python3
seaborn.scatterplot(x='day', y='tip', data=tip, hue='time')
Output:
In the above example, we can see how the tip and day bill is related to whether it was lunchtime or dinner time. The blue color has represented the Dinner and the orange color represents the Lunch.
Let’s check for a hue = ” day “
Python3
seaborn.scatterplot(x='day', y='tip', data=tip, hue='day')
3. Adding the style attributes.
Grouping variable that will produce points with different markers. Using style we can generate the scatter grouping variable that will produce points with different markers.
Syntax:
seaborn.scatterplot( x, y, data, style)
Python3
seaborn.scatterplot(x='day', y='tip', data=tip, hue="time", style="time")
Output:
4. Adding the palette attributes.
Using the palette we can generate the point with different colors. In this below example we can see the palette can be responsible for a generate the scatter plot with different colormap values.
Syntax:
seaborn.scatterplot( x, y, data, palette=”color_name”)
Python3
seaborn.scatterplot(x='day', y='tip', data=tip, hue='time', palette='pastel')
Output:
5. Adding size attributes.
Using size we can generate the point and we can produce points with different sizes.
Syntax:
seaborn.scatterplot( x, y, data, size)
Python3
seaborn.scatterplot(x='day', y='tip', data=tip ,hue='size', size = "size")
Output:
6. Adding legend attributes.
.Using the legend parameter we can turn on (legend=full) and we can also turn off the legend using (legend = False).
If the legend is “brief”, numeric hue and size variables will be represented with a sample of evenly spaced values.
If the legend is “full”, every group will get an entry in the legend.
If False, no legend data is added and no legend is drawn.
Syntax: seaborn.scatterplot( x, y, data, legend=”brief)
Python3
seaborn.scatterplot(x='day', y='tip', data=tip, hue='day', sizes=(30, 200), legend='brief')
Output:
7. Adding alpha attributes.
Using alpha we can control proportional opacity of the points. We can decrease and increase the opacity.
Syntax: seaborn.scatterplot( x, y, data, alpha=”0.2′′)
Python3
seaborn.scatterplot(x='day', y='tip', data=tip, alpha = 0.1)
Output:
kumar_satyam
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Python Dictionary
Different ways to create Pandas Dataframe
Taking input in Python
Enumerate() in Python
Read a file line by line in Python
Python String | replace() | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Nov, 2020"
},
{
"code": null,
"e": 353,
"s": 53,
"text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides beautiful default styles and color palettes to make statistical plots more attractive. It is built on the top of matplotlib library and also closely integrated into the data structures from pandas. "
},
{
"code": null,
"e": 792,
"s": 353,
"text": "Scatterplot can be used with several semantic groupings which can help to understand well in a graph. They can plot two-dimensional graphics that can be enhanced by mapping up to three additional variables while using the semantics of hue, size, and style parameters. All the parameter control visual semantic which are used to identify the different subsets. Using redundant semantics can be helpful for making graphics more accessible. "
},
{
"code": null,
"e": 1216,
"s": 792,
"text": "Syntax: seaborn.scatterplot(x=None, y=None, hue=None, style=None, size=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, markers=True, style_order=None, x_bins=None, y_bins=None, units=None, estimator=None, ci=95, n_boot=1000, alpha=’auto’, x_jitter=None, y_jitter=None, legend=’brief’, ax=None, **kwargs)Parameters:x, y: Input data variables that should be numeric."
},
{
"code": null,
"e": 1296,
"s": 1216,
"text": "data: Dataframe where each column is a variable and each row is an observation."
},
{
"code": null,
"e": 1367,
"s": 1296,
"text": "size: Grouping variable that will produce points with different sizes."
},
{
"code": null,
"e": 1443,
"s": 1367,
"text": "style: Grouping variable that will produce points with different markers. "
},
{
"code": null,
"e": 1521,
"s": 1443,
"text": "palette: Grouping variable that will produce points with different markers. "
},
{
"code": null,
"e": 1595,
"s": 1521,
"text": "markers: Object determining how to draw the markers for different levels."
},
{
"code": null,
"e": 1638,
"s": 1595,
"text": "alpha: Proportional opacity of the points."
},
{
"code": null,
"e": 1713,
"s": 1638,
"text": "Returns: This method returns the Axes object with the plot drawn onto it. "
},
{
"code": null,
"e": 1839,
"s": 1713,
"text": "Let’s visualize of “fmri” dataset using seaborn.scatterplot() function. We will only use the x, y parameters of the function."
},
{
"code": null,
"e": 1845,
"s": 1839,
"text": "Code:"
},
{
"code": null,
"e": 1853,
"s": 1845,
"text": "Python3"
},
{
"code": "import seaborn seaborn.set(style='whitegrid')fmri = seaborn.load_dataset(\"fmri\") seaborn.scatterplot(x=\"timepoint\", y=\"signal\", data=fmri)",
"e": 2031,
"s": 1853,
"text": null
},
{
"code": null,
"e": 2040,
"s": 2031,
"text": "Output: "
},
{
"code": null,
"e": 2113,
"s": 2040,
"text": "Grouping data points on the basis of category, here as region and event."
},
{
"code": null,
"e": 2121,
"s": 2113,
"text": "Python3"
},
{
"code": "import seaborn seaborn.set(style='whitegrid')fmri = seaborn.load_dataset(\"fmri\") seaborn.scatterplot(x=\"timepoint\", y=\"signal\", hue=\"region\", style=\"event\", data=fmri)",
"e": 2366,
"s": 2121,
"text": null
},
{
"code": null,
"e": 2374,
"s": 2366,
"text": "Output:"
},
{
"code": null,
"e": 2431,
"s": 2374,
"text": "Basic visualization of “tips” dataset using Scatterplot."
},
{
"code": null,
"e": 2439,
"s": 2431,
"text": "Python3"
},
{
"code": "import seaborn seaborn.set(style='whitegrid')tip = seaborn.load_dataset('tips') seaborn.scatterplot(x='day', y='tip', data=tip)",
"e": 2568,
"s": 2439,
"text": null
},
{
"code": null,
"e": 2576,
"s": 2568,
"text": "Output:"
},
{
"code": null,
"e": 2608,
"s": 2576,
"text": "1. Adding the marker attributes"
},
{
"code": null,
"e": 2833,
"s": 2608,
"text": "The circle is used to represent the data point and the default marker here is a blue circle. In the above output, we are seeing the default output for the marker, but we can customize this blue circle with marker attributes."
},
{
"code": null,
"e": 2841,
"s": 2833,
"text": "Python3"
},
{
"code": "seaborn.scatterplot(x='day', y='tip', data= tip, marker = '+')",
"e": 2904,
"s": 2841,
"text": null
},
{
"code": null,
"e": 2912,
"s": 2904,
"text": "Output:"
},
{
"code": null,
"e": 2943,
"s": 2912,
"text": "2. Adding the hue attributes. "
},
{
"code": null,
"e": 3114,
"s": 2943,
"text": "It will produce data points with different colors. Hue can be used to group to multiple data variable and show the dependency of the passed data values are to be plotted."
},
{
"code": null,
"e": 3160,
"s": 3114,
"text": "Syntax: seaborn.scatterplot( x, y, data, hue)"
},
{
"code": null,
"e": 3168,
"s": 3160,
"text": "Python3"
},
{
"code": "seaborn.scatterplot(x='day', y='tip', data=tip, hue='time')",
"e": 3228,
"s": 3168,
"text": null
},
{
"code": null,
"e": 3236,
"s": 3228,
"text": "Output:"
},
{
"code": null,
"e": 3434,
"s": 3236,
"text": "In the above example, we can see how the tip and day bill is related to whether it was lunchtime or dinner time. The blue color has represented the Dinner and the orange color represents the Lunch."
},
{
"code": null,
"e": 3466,
"s": 3434,
"text": "Let’s check for a hue = ” day “"
},
{
"code": null,
"e": 3474,
"s": 3466,
"text": "Python3"
},
{
"code": "seaborn.scatterplot(x='day', y='tip', data=tip, hue='day')",
"e": 3533,
"s": 3474,
"text": null
},
{
"code": null,
"e": 3565,
"s": 3533,
"text": "3. Adding the style attributes."
},
{
"code": null,
"e": 3739,
"s": 3565,
"text": "Grouping variable that will produce points with different markers. Using style we can generate the scatter grouping variable that will produce points with different markers."
},
{
"code": null,
"e": 3747,
"s": 3739,
"text": "Syntax:"
},
{
"code": null,
"e": 3787,
"s": 3747,
"text": "seaborn.scatterplot( x, y, data, style)"
},
{
"code": null,
"e": 3795,
"s": 3787,
"text": "Python3"
},
{
"code": "seaborn.scatterplot(x='day', y='tip', data=tip, hue=\"time\", style=\"time\")",
"e": 3869,
"s": 3795,
"text": null
},
{
"code": null,
"e": 3877,
"s": 3869,
"text": "Output:"
},
{
"code": null,
"e": 3911,
"s": 3877,
"text": "4. Adding the palette attributes."
},
{
"code": null,
"e": 4106,
"s": 3911,
"text": "Using the palette we can generate the point with different colors. In this below example we can see the palette can be responsible for a generate the scatter plot with different colormap values."
},
{
"code": null,
"e": 4114,
"s": 4106,
"text": "Syntax:"
},
{
"code": null,
"e": 4169,
"s": 4114,
"text": "seaborn.scatterplot( x, y, data, palette=”color_name”)"
},
{
"code": null,
"e": 4177,
"s": 4169,
"text": "Python3"
},
{
"code": "seaborn.scatterplot(x='day', y='tip', data=tip, hue='time', palette='pastel')",
"e": 4255,
"s": 4177,
"text": null
},
{
"code": null,
"e": 4263,
"s": 4255,
"text": "Output:"
},
{
"code": null,
"e": 4290,
"s": 4263,
"text": "5. Adding size attributes."
},
{
"code": null,
"e": 4375,
"s": 4290,
"text": "Using size we can generate the point and we can produce points with different sizes."
},
{
"code": null,
"e": 4383,
"s": 4375,
"text": "Syntax:"
},
{
"code": null,
"e": 4422,
"s": 4383,
"text": "seaborn.scatterplot( x, y, data, size)"
},
{
"code": null,
"e": 4430,
"s": 4422,
"text": "Python3"
},
{
"code": "seaborn.scatterplot(x='day', y='tip', data=tip ,hue='size', size = \"size\")",
"e": 4505,
"s": 4430,
"text": null
},
{
"code": null,
"e": 4513,
"s": 4505,
"text": "Output:"
},
{
"code": null,
"e": 4542,
"s": 4513,
"text": "6. Adding legend attributes."
},
{
"code": null,
"e": 4659,
"s": 4542,
"text": ".Using the legend parameter we can turn on (legend=full) and we can also turn off the legend using (legend = False)."
},
{
"code": null,
"e": 4775,
"s": 4659,
"text": "If the legend is “brief”, numeric hue and size variables will be represented with a sample of evenly spaced values."
},
{
"code": null,
"e": 4845,
"s": 4775,
"text": "If the legend is “full”, every group will get an entry in the legend."
},
{
"code": null,
"e": 4903,
"s": 4845,
"text": "If False, no legend data is added and no legend is drawn."
},
{
"code": null,
"e": 4959,
"s": 4903,
"text": "Syntax: seaborn.scatterplot( x, y, data, legend=”brief)"
},
{
"code": null,
"e": 4967,
"s": 4959,
"text": "Python3"
},
{
"code": "seaborn.scatterplot(x='day', y='tip', data=tip, hue='day', sizes=(30, 200), legend='brief')",
"e": 5078,
"s": 4967,
"text": null
},
{
"code": null,
"e": 5086,
"s": 5078,
"text": "Output:"
},
{
"code": null,
"e": 5114,
"s": 5086,
"text": "7. Adding alpha attributes."
},
{
"code": null,
"e": 5219,
"s": 5114,
"text": "Using alpha we can control proportional opacity of the points. We can decrease and increase the opacity."
},
{
"code": null,
"e": 5274,
"s": 5219,
"text": "Syntax: seaborn.scatterplot( x, y, data, alpha=”0.2′′)"
},
{
"code": null,
"e": 5282,
"s": 5274,
"text": "Python3"
},
{
"code": "seaborn.scatterplot(x='day', y='tip', data=tip, alpha = 0.1)",
"e": 5343,
"s": 5282,
"text": null
},
{
"code": null,
"e": 5351,
"s": 5343,
"text": "Output:"
},
{
"code": null,
"e": 5366,
"s": 5353,
"text": "kumar_satyam"
},
{
"code": null,
"e": 5381,
"s": 5366,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 5388,
"s": 5381,
"text": "Python"
},
{
"code": null,
"e": 5486,
"s": 5388,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5514,
"s": 5486,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 5564,
"s": 5514,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 5586,
"s": 5564,
"text": "Python map() function"
},
{
"code": null,
"e": 5630,
"s": 5586,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 5648,
"s": 5630,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5690,
"s": 5648,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5713,
"s": 5690,
"text": "Taking input in Python"
},
{
"code": null,
"e": 5735,
"s": 5713,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5770,
"s": 5735,
"text": "Read a file line by line in Python"
}
] |
How to test the shared location path from the remote computer in PowerShell? | Many times we need to test the NAS path or shared path location from the remote server. Meaning we need to check if the shared path is accessible from the remote location and we use the Test-Path that time but we get an error of PermissionDenied or UnauthorizedAccessExcept.
Our sample code is shown below and in this example, we are using the Invoke-Command to connect to another computer and from there we are checking if the shared path is accessible.
Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock {
Test-Path -Path "\\ad\Shared\Temp"
}
This script throws an exception.
Access is denied
+ CategoryInfo : PermissionDenied: (\\ad\Shared\Temp:String) [Test-Path], UnauthorizedAccessException
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.TestPathCommand
+ PSComputerName : LabMachine2k16
False
This is not the permission issue but this is a PowerShell remoting issue. By default PowerShell remoting supports one layer of remoting, here we are connecting to a remote machine and again checking the shared path from it so it becomes the 2 stages of remoting and PowerShell doesn't support it.
To get this issue solved, we can use the Map drive to test if we can connect to it successfully or not. If yes then the remote server has connectivity to that path. For example,
Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{
if(New-PSDrive -Name X -PSProvider FileSystem `
-Root "\\Ad\Shared\Temp" -EA Ignore){
Write-Output "Path is accessible"
}
}
Path is accessible | [
{
"code": null,
"e": 1462,
"s": 1187,
"text": "Many times we need to test the NAS path or shared path location from the remote server. Meaning we need to check if the shared path is accessible from the remote location and we use the Test-Path that time but we get an error of PermissionDenied or UnauthorizedAccessExcept."
},
{
"code": null,
"e": 1642,
"s": 1462,
"text": "Our sample code is shown below and in this example, we are using the Invoke-Command to connect to another computer and from there we are checking if the shared path is accessible."
},
{
"code": null,
"e": 1741,
"s": 1642,
"text": "Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock {\n Test-Path -Path \"\\\\ad\\Shared\\Temp\"\n}"
},
{
"code": null,
"e": 1774,
"s": 1741,
"text": "This script throws an exception."
},
{
"code": null,
"e": 2067,
"s": 1774,
"text": "Access is denied\n + CategoryInfo : PermissionDenied: (\\\\ad\\Shared\\Temp:String) [Test-Path], UnauthorizedAccessException\n + FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.TestPathCommand\n + PSComputerName : LabMachine2k16\nFalse"
},
{
"code": null,
"e": 2364,
"s": 2067,
"text": "This is not the permission issue but this is a PowerShell remoting issue. By default PowerShell remoting supports one layer of remoting, here we are connecting to a remote machine and again checking the shared path from it so it becomes the 2 stages of remoting and PowerShell doesn't support it."
},
{
"code": null,
"e": 2542,
"s": 2364,
"text": "To get this issue solved, we can use the Map drive to test if we can connect to it successfully or not. If yes then the remote server has connectivity to that path. For example,"
},
{
"code": null,
"e": 2743,
"s": 2542,
"text": "Invoke-Command -ComputerName LabMachine2k16 -ScriptBlock{\n if(New-PSDrive -Name X -PSProvider FileSystem `\n -Root \"\\\\Ad\\Shared\\Temp\" -EA Ignore){\n Write-Output \"Path is accessible\"\n }\n}"
},
{
"code": null,
"e": 2762,
"s": 2743,
"text": "Path is accessible"
}
] |
How to find SubString in R programming? - GeeksforGeeks | 21 Oct, 2021
In this article, we are going to see how to find substring in R programming language.
R provides different ways to find substrings. These are:
Using substr() method
Using str_detect() method
Using grep() method
Find substring in R using substr() method in R Programming is used to find the sub-string from starting index to the ending index values in a string.
Syntax: substr(string_name, start, end)
Return: Returns the sub string from a given string using indexes.
Example 1:
R
# Given Stringgfg < - "Geeks For Geeks" # Using substr() methodanswer < - substr(gfg, 0, 5) print(answer)
Output:
[1] "Geeks"
Example 2:
R
# Given Stringgfg < - "The quick brown fox jumps over the lazy dog" # Using substr() methodanswer < - substr(gfg, 20, 30) print(answer)
Output:
[1] " jumps over"
str_detect() Function in R Language is used to check if the specified match of the substring exists in the original string. It will return TRUE for a match found otherwise FALSE against each of the elements of the Vector or matrix.
Syntax: str_detect(string, pattern)
Parameter:
string: specified string
pattern: Pattern to be matched
Example:
R
# R Program to illustrate# the use of str_detect function # Loading librarylibrary(stringr) # Creating vectorx <- c("Geeks", "Hello", "Welcome", "For") # Pattern to be matchedpat <- "Geeks" # Calling str_detect() functionstr_detect(x, pat)
Output:
[1] TRUE FALSE FALSE FALSE
grep() function returns the index at which the pattern is found in the vector. If there are multiple occurrences of the pattern, it returns a list of indices of the occurrences. This is very useful as it not only tells us about the occurrence of the pattern but also of its location in the vector.
Syntax: grep(pattern, string, ignore.case=FALSE)
Parameters:
pattern: A regular expressions pattern.
string: The character vector to be searched.
ignore.case: Whether to ignore case in the search. Here ignore.case is an optional parameter as is set to FALSE by default.
Example:
R
str <- c("Hello", "hello", "hi", "hey")grep('he', str)
Output:
[1] 2 4
kumar_satyam
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
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?
Data Visualization in R
Logistic Regression in R Programming
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
How to import an Excel File into R ?
How to filter R DataFrame by values in a column? | [
{
"code": null,
"e": 25162,
"s": 25134,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 25249,
"s": 25162,
"text": "In this article, we are going to see how to find substring in R programming language. "
},
{
"code": null,
"e": 25306,
"s": 25249,
"text": "R provides different ways to find substrings. These are:"
},
{
"code": null,
"e": 25328,
"s": 25306,
"text": "Using substr() method"
},
{
"code": null,
"e": 25354,
"s": 25328,
"text": "Using str_detect() method"
},
{
"code": null,
"e": 25374,
"s": 25354,
"text": "Using grep() method"
},
{
"code": null,
"e": 25524,
"s": 25374,
"text": "Find substring in R using substr() method in R Programming is used to find the sub-string from starting index to the ending index values in a string."
},
{
"code": null,
"e": 25564,
"s": 25524,
"text": "Syntax: substr(string_name, start, end)"
},
{
"code": null,
"e": 25631,
"s": 25564,
"text": "Return: Returns the sub string from a given string using indexes. "
},
{
"code": null,
"e": 25642,
"s": 25631,
"text": "Example 1:"
},
{
"code": null,
"e": 25644,
"s": 25642,
"text": "R"
},
{
"code": "# Given Stringgfg < - \"Geeks For Geeks\" # Using substr() methodanswer < - substr(gfg, 0, 5) print(answer)",
"e": 25752,
"s": 25644,
"text": null
},
{
"code": null,
"e": 25760,
"s": 25752,
"text": "Output:"
},
{
"code": null,
"e": 25772,
"s": 25760,
"text": "[1] \"Geeks\""
},
{
"code": null,
"e": 25783,
"s": 25772,
"text": "Example 2:"
},
{
"code": null,
"e": 25785,
"s": 25783,
"text": "R"
},
{
"code": "# Given Stringgfg < - \"The quick brown fox jumps over the lazy dog\" # Using substr() methodanswer < - substr(gfg, 20, 30) print(answer)",
"e": 25923,
"s": 25785,
"text": null
},
{
"code": null,
"e": 25932,
"s": 25923,
"text": "Output: "
},
{
"code": null,
"e": 25950,
"s": 25932,
"text": "[1] \" jumps over\""
},
{
"code": null,
"e": 26182,
"s": 25950,
"text": "str_detect() Function in R Language is used to check if the specified match of the substring exists in the original string. It will return TRUE for a match found otherwise FALSE against each of the elements of the Vector or matrix."
},
{
"code": null,
"e": 26218,
"s": 26182,
"text": "Syntax: str_detect(string, pattern)"
},
{
"code": null,
"e": 26229,
"s": 26218,
"text": "Parameter:"
},
{
"code": null,
"e": 26254,
"s": 26229,
"text": "string: specified string"
},
{
"code": null,
"e": 26285,
"s": 26254,
"text": "pattern: Pattern to be matched"
},
{
"code": null,
"e": 26294,
"s": 26285,
"text": "Example:"
},
{
"code": null,
"e": 26296,
"s": 26294,
"text": "R"
},
{
"code": "# R Program to illustrate# the use of str_detect function # Loading librarylibrary(stringr) # Creating vectorx <- c(\"Geeks\", \"Hello\", \"Welcome\", \"For\") # Pattern to be matchedpat <- \"Geeks\" # Calling str_detect() functionstr_detect(x, pat)",
"e": 26540,
"s": 26296,
"text": null
},
{
"code": null,
"e": 26548,
"s": 26540,
"text": "Output:"
},
{
"code": null,
"e": 26576,
"s": 26548,
"text": "[1] TRUE FALSE FALSE FALSE"
},
{
"code": null,
"e": 26874,
"s": 26576,
"text": "grep() function returns the index at which the pattern is found in the vector. If there are multiple occurrences of the pattern, it returns a list of indices of the occurrences. This is very useful as it not only tells us about the occurrence of the pattern but also of its location in the vector."
},
{
"code": null,
"e": 26923,
"s": 26874,
"text": "Syntax: grep(pattern, string, ignore.case=FALSE)"
},
{
"code": null,
"e": 26935,
"s": 26923,
"text": "Parameters:"
},
{
"code": null,
"e": 26975,
"s": 26935,
"text": "pattern: A regular expressions pattern."
},
{
"code": null,
"e": 27020,
"s": 26975,
"text": "string: The character vector to be searched."
},
{
"code": null,
"e": 27144,
"s": 27020,
"text": "ignore.case: Whether to ignore case in the search. Here ignore.case is an optional parameter as is set to FALSE by default."
},
{
"code": null,
"e": 27153,
"s": 27144,
"text": "Example:"
},
{
"code": null,
"e": 27155,
"s": 27153,
"text": "R"
},
{
"code": "str <- c(\"Hello\", \"hello\", \"hi\", \"hey\")grep('he', str)",
"e": 27210,
"s": 27155,
"text": null
},
{
"code": null,
"e": 27218,
"s": 27210,
"text": "Output:"
},
{
"code": null,
"e": 27226,
"s": 27218,
"text": "[1] 2 4"
},
{
"code": null,
"e": 27239,
"s": 27226,
"text": "kumar_satyam"
},
{
"code": null,
"e": 27250,
"s": 27239,
"text": "R Language"
},
{
"code": null,
"e": 27348,
"s": 27250,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27357,
"s": 27348,
"text": "Comments"
},
{
"code": null,
"e": 27370,
"s": 27357,
"text": "Old Comments"
},
{
"code": null,
"e": 27422,
"s": 27370,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27460,
"s": 27422,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27495,
"s": 27460,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27553,
"s": 27495,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27577,
"s": 27553,
"text": "Data Visualization in R"
},
{
"code": null,
"e": 27614,
"s": 27577,
"text": "Logistic Regression in R Programming"
},
{
"code": null,
"e": 27657,
"s": 27614,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27707,
"s": 27657,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27744,
"s": 27707,
"text": "How to import an Excel File into R ?"
}
] |
Adjusting Prices for Inflation in Python with Pandas Merge | by Jake Huneycutt | Towards Data Science | For several years, I managed a small, start-up investment fund. While Wall Street analysts typically look back only a year or two when analyzing companies, I’d often dig back 20 or 30 years. I’d even occasionally scour through economic and price data going back to the 1950’s, ‘20s, or in rare cases 19th Century, to get a better understanding of market cycles. When you do this type of deep long-term historical analysis, however, one issue you will run into: nominal prices can be very deceiving.
Take for instance, the price of grains. We have Producer Price Index values for grains running back to January 1926 when the index was at 37.9 during the 1920’s boom. In April 2018, that same index was at 151.5. Hence, prices increased 4-fold for grains in the during that 92 year time frame. If we were to measure it from the bottom of the Great Depression in 1933 (when the index was at 11.0), prices have increased 15-fold!
This is a very misleading picture and it’s difficult to know this simply from looking at the chart above. Once we adjust for inflation, we get the radically different looking chart below.
Not only have grain prices not been rising over time, they’ve actually been falling in real terms. Adjusted for CPI inflation, grain prices today are 71% lower than they were in 1926. Today’s prices are even 24% below the Great Depression lows.
Grains have become more affordable over time and falling real agriculture prices have alleviated poverty in much of the world. You may have never gained that insight by simply looking at the nominal prices in the top chart. You have to adjust for inflation to gain that perspective.
Inflation in the US
Inflation has cycled dramatically in the US over the past century. In World War II, inflation shot-up to 10.5%. By 1953, inflation had fallen all the way to 0.8%. In 1980, inflation was sky-high at 13.5% before the Federal Reserve cracked down on it. In 2005, official CPI inflation was at 3.4%, but housing prices in the 20 largest US metro areas rose 14%! In 2017, inflation was relatively tame at 2.0% (but it’s starting to push back up again as labor and input costs continue to rise).
Inflation-adjustment gives you a much better understanding of real prices. This analysis can be very insightful. Indeed, one of my most successful investment theses revolved around examining inflation-adjusted copper-prices during the Japanese Asset Bubble and making comparisons to the late 00’s / early 10’s copper price bubble.
Nevertheless, inflation adjustment might seem like a tricky issue to handle in Python if you’re working in a Pandas DataFrame. You may have thousands of rows of “data points” with dates scattered all across the spectrum in your data frame. Whereas, inflation data tends to be in the form of sequential monthly data. How do you bridge the two?
Finding Your Sources
The first thing to talk about is sources. What data do you use to adjust for inflation? Where do you find inflation data?
There’s not always one “right” answer, but if you live in the US or are dealing with American pricing data, the Federal Reserve Economic Data (commonly known by the acronym “FRED”) should be one of your go-to sources. There are dozens of inflation measures out there, but the one I most frequently use is called “CPIAUCNS”. This inflation data set goes all the way back to 1913, which is why it tends to be my favorite for long-term analysis.
There are many other data sets, as well. If you’re looking at housing price data in Minneapolis, for example, you might prefer to look at a housing price index, such as the All-Transactions House Price Index or the Case-Shiller Minneapolis Home Price Index. Normally, however, some variant of CPI is what you’ll use as your index.
Set Your Index
CPI inflation and housing price indices are already indexed in a certain manner, but you’ll likely need to re-index the data to suit your own purposes. For instance, if your inflation data is indexed to 100 in January 1982, while your data set deals with data running from 2004 to 2017, you’ll likely either want to index your data based on either 2004 prices (beginning) or 2017 prices (end).
We can do this in Excel or Python. Admittedly, I find it’s normally easier to adjust the data in Excel, but if we had a particularly large data set, Python might be a superior option.
In Python, we could do this by loading our inflation data in and creating a new column for the ‘Index Multiplier’. Then we’d simply multiply the nominal prices by the ‘Index Multiplier.’
# load inflation datainflation = pd.read_excel(‘inflation_data.xls’, sheetname=’Data’)# create index multiplierinflation[‘CPI_Multiplier’] = inflation[‘CPI’].iloc[-1] / inflation[‘CPI’]
Note in this example, I’m using the last data value to create the index, so that prices will be indexed to today’s prices. If we used the first data point to index based on the beginning start point, we’d select the first value instead of the last.
Now we have an index to adjust our prices. We need to merge the two data sets to perform the operation.
Matching Up Dates
Before we can merge, however, we have to deal with the trickiest aspect of this exercise: dates. Dates can be a major pain in programming. There are several ways to handle them.
In a recent data set, I found months and years in separate columns, such as in the example below.
Month Year01 200804 201209 2016
Meanwhile, the dates on my inflation data were recognized in yyyy/mm/dd format, that looked like this:
Date CPI_Multiplier2008/01/01 1.0002008/02/01 1.0032008/03/01 1.0052008/04/01 1.011
How to align the two?
There are numerous answers, but I created a ‘day’ column and assigned it a value of 1 (to match the dates in the inflation data) and used pd.to_datetime to create a ‘Date’ column in the original data set.
# load data setdf = pd.read_excel('training_data.xlsx')# create new day column for 'day'df['day'] = 1#create new dataframe to store date infonew_df = df[['year', 'month', 'day']]# create new column 'Date' in original data w/ datetime conversiondf['Date'] = pd.to_datetime(new_df)
In Pandas, pd.to_datetime() is a powerful tool, but you do have to get your data just-right to make it work.
Merging the Data
Finally, we load the inflation data and use pd.merge to merge the two data frames. The ‘how’ argument specifies the type of join. In this instance, I set ‘df’ (my main data set) as the 1st argument and ‘inflation’ (the inflation data) as the second and used a ‘left’ join to merge on ‘Date’.
# merge dataframedf = pd.merge(df, inflation, how='left', on='Date')
Now, with the merged dataframe, it’s easy to create an index.
df[‘CPIAdjPrice’] = df[‘SalePrice’] * df[‘CPI_Multiplier’]
Viola! We can now see prices in real terms!
Conclusions
On long-term data series, inflation adjustments can be vital in understanding your data. By using nominal prices, it can also make prediction trickier.
Inflation adjustment can be useful for looking at things such as commodity prices or retail prices, but also can be used with housing price indices to adjust housing prices in volatile markets. This way, we can strip out ‘market volatility’ and ‘inflation’ as part of our prediction models. | [
{
"code": null,
"e": 671,
"s": 172,
"text": "For several years, I managed a small, start-up investment fund. While Wall Street analysts typically look back only a year or two when analyzing companies, I’d often dig back 20 or 30 years. I’d even occasionally scour through economic and price data going back to the 1950’s, ‘20s, or in rare cases 19th Century, to get a better understanding of market cycles. When you do this type of deep long-term historical analysis, however, one issue you will run into: nominal prices can be very deceiving."
},
{
"code": null,
"e": 1098,
"s": 671,
"text": "Take for instance, the price of grains. We have Producer Price Index values for grains running back to January 1926 when the index was at 37.9 during the 1920’s boom. In April 2018, that same index was at 151.5. Hence, prices increased 4-fold for grains in the during that 92 year time frame. If we were to measure it from the bottom of the Great Depression in 1933 (when the index was at 11.0), prices have increased 15-fold!"
},
{
"code": null,
"e": 1286,
"s": 1098,
"text": "This is a very misleading picture and it’s difficult to know this simply from looking at the chart above. Once we adjust for inflation, we get the radically different looking chart below."
},
{
"code": null,
"e": 1531,
"s": 1286,
"text": "Not only have grain prices not been rising over time, they’ve actually been falling in real terms. Adjusted for CPI inflation, grain prices today are 71% lower than they were in 1926. Today’s prices are even 24% below the Great Depression lows."
},
{
"code": null,
"e": 1814,
"s": 1531,
"text": "Grains have become more affordable over time and falling real agriculture prices have alleviated poverty in much of the world. You may have never gained that insight by simply looking at the nominal prices in the top chart. You have to adjust for inflation to gain that perspective."
},
{
"code": null,
"e": 1834,
"s": 1814,
"text": "Inflation in the US"
},
{
"code": null,
"e": 2324,
"s": 1834,
"text": "Inflation has cycled dramatically in the US over the past century. In World War II, inflation shot-up to 10.5%. By 1953, inflation had fallen all the way to 0.8%. In 1980, inflation was sky-high at 13.5% before the Federal Reserve cracked down on it. In 2005, official CPI inflation was at 3.4%, but housing prices in the 20 largest US metro areas rose 14%! In 2017, inflation was relatively tame at 2.0% (but it’s starting to push back up again as labor and input costs continue to rise)."
},
{
"code": null,
"e": 2655,
"s": 2324,
"text": "Inflation-adjustment gives you a much better understanding of real prices. This analysis can be very insightful. Indeed, one of my most successful investment theses revolved around examining inflation-adjusted copper-prices during the Japanese Asset Bubble and making comparisons to the late 00’s / early 10’s copper price bubble."
},
{
"code": null,
"e": 2998,
"s": 2655,
"text": "Nevertheless, inflation adjustment might seem like a tricky issue to handle in Python if you’re working in a Pandas DataFrame. You may have thousands of rows of “data points” with dates scattered all across the spectrum in your data frame. Whereas, inflation data tends to be in the form of sequential monthly data. How do you bridge the two?"
},
{
"code": null,
"e": 3019,
"s": 2998,
"text": "Finding Your Sources"
},
{
"code": null,
"e": 3141,
"s": 3019,
"text": "The first thing to talk about is sources. What data do you use to adjust for inflation? Where do you find inflation data?"
},
{
"code": null,
"e": 3584,
"s": 3141,
"text": "There’s not always one “right” answer, but if you live in the US or are dealing with American pricing data, the Federal Reserve Economic Data (commonly known by the acronym “FRED”) should be one of your go-to sources. There are dozens of inflation measures out there, but the one I most frequently use is called “CPIAUCNS”. This inflation data set goes all the way back to 1913, which is why it tends to be my favorite for long-term analysis."
},
{
"code": null,
"e": 3915,
"s": 3584,
"text": "There are many other data sets, as well. If you’re looking at housing price data in Minneapolis, for example, you might prefer to look at a housing price index, such as the All-Transactions House Price Index or the Case-Shiller Minneapolis Home Price Index. Normally, however, some variant of CPI is what you’ll use as your index."
},
{
"code": null,
"e": 3930,
"s": 3915,
"text": "Set Your Index"
},
{
"code": null,
"e": 4324,
"s": 3930,
"text": "CPI inflation and housing price indices are already indexed in a certain manner, but you’ll likely need to re-index the data to suit your own purposes. For instance, if your inflation data is indexed to 100 in January 1982, while your data set deals with data running from 2004 to 2017, you’ll likely either want to index your data based on either 2004 prices (beginning) or 2017 prices (end)."
},
{
"code": null,
"e": 4508,
"s": 4324,
"text": "We can do this in Excel or Python. Admittedly, I find it’s normally easier to adjust the data in Excel, but if we had a particularly large data set, Python might be a superior option."
},
{
"code": null,
"e": 4695,
"s": 4508,
"text": "In Python, we could do this by loading our inflation data in and creating a new column for the ‘Index Multiplier’. Then we’d simply multiply the nominal prices by the ‘Index Multiplier.’"
},
{
"code": null,
"e": 4881,
"s": 4695,
"text": "# load inflation datainflation = pd.read_excel(‘inflation_data.xls’, sheetname=’Data’)# create index multiplierinflation[‘CPI_Multiplier’] = inflation[‘CPI’].iloc[-1] / inflation[‘CPI’]"
},
{
"code": null,
"e": 5130,
"s": 4881,
"text": "Note in this example, I’m using the last data value to create the index, so that prices will be indexed to today’s prices. If we used the first data point to index based on the beginning start point, we’d select the first value instead of the last."
},
{
"code": null,
"e": 5234,
"s": 5130,
"text": "Now we have an index to adjust our prices. We need to merge the two data sets to perform the operation."
},
{
"code": null,
"e": 5252,
"s": 5234,
"text": "Matching Up Dates"
},
{
"code": null,
"e": 5430,
"s": 5252,
"text": "Before we can merge, however, we have to deal with the trickiest aspect of this exercise: dates. Dates can be a major pain in programming. There are several ways to handle them."
},
{
"code": null,
"e": 5528,
"s": 5430,
"text": "In a recent data set, I found months and years in separate columns, such as in the example below."
},
{
"code": null,
"e": 5569,
"s": 5528,
"text": "Month Year01 200804 201209 2016"
},
{
"code": null,
"e": 5672,
"s": 5569,
"text": "Meanwhile, the dates on my inflation data were recognized in yyyy/mm/dd format, that looked like this:"
},
{
"code": null,
"e": 5777,
"s": 5672,
"text": "Date CPI_Multiplier2008/01/01 1.0002008/02/01 1.0032008/03/01 1.0052008/04/01 1.011"
},
{
"code": null,
"e": 5799,
"s": 5777,
"text": "How to align the two?"
},
{
"code": null,
"e": 6004,
"s": 5799,
"text": "There are numerous answers, but I created a ‘day’ column and assigned it a value of 1 (to match the dates in the inflation data) and used pd.to_datetime to create a ‘Date’ column in the original data set."
},
{
"code": null,
"e": 6284,
"s": 6004,
"text": "# load data setdf = pd.read_excel('training_data.xlsx')# create new day column for 'day'df['day'] = 1#create new dataframe to store date infonew_df = df[['year', 'month', 'day']]# create new column 'Date' in original data w/ datetime conversiondf['Date'] = pd.to_datetime(new_df)"
},
{
"code": null,
"e": 6393,
"s": 6284,
"text": "In Pandas, pd.to_datetime() is a powerful tool, but you do have to get your data just-right to make it work."
},
{
"code": null,
"e": 6410,
"s": 6393,
"text": "Merging the Data"
},
{
"code": null,
"e": 6702,
"s": 6410,
"text": "Finally, we load the inflation data and use pd.merge to merge the two data frames. The ‘how’ argument specifies the type of join. In this instance, I set ‘df’ (my main data set) as the 1st argument and ‘inflation’ (the inflation data) as the second and used a ‘left’ join to merge on ‘Date’."
},
{
"code": null,
"e": 6771,
"s": 6702,
"text": "# merge dataframedf = pd.merge(df, inflation, how='left', on='Date')"
},
{
"code": null,
"e": 6833,
"s": 6771,
"text": "Now, with the merged dataframe, it’s easy to create an index."
},
{
"code": null,
"e": 6893,
"s": 6833,
"text": "df[‘CPIAdjPrice’] = df[‘SalePrice’] * df[‘CPI_Multiplier’] "
},
{
"code": null,
"e": 6937,
"s": 6893,
"text": "Viola! We can now see prices in real terms!"
},
{
"code": null,
"e": 6949,
"s": 6937,
"text": "Conclusions"
},
{
"code": null,
"e": 7101,
"s": 6949,
"text": "On long-term data series, inflation adjustments can be vital in understanding your data. By using nominal prices, it can also make prediction trickier."
}
] |
Java - Polymorphism | Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.
It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.
The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.
A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.
Let us look at an example.
public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}
Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above examples −
A Deer IS-A Animal
A Deer IS-A Vegetarian
A Deer IS-A Deer
A Deer IS-A Object
When we apply the reference variable facts to a Deer object reference, the following declarations are legal −
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;
All the reference variables d, a, v, o refer to the same Deer object in the heap.
In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes.
We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method.
/* File name : Employee.java */
public class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck() {
System.out.println("Mailing a check to " + this.name + " " + this.address);
}
public String toString() {
return name + " " + address + " " + number;
}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}
}
Now suppose we extend Employee class as follows −
/* File name : Salary.java */
public class Salary extends Employee {
private double salary; // Annual salary
public Salary(String name, String address, int number, double salary) {
super(name, address, number);
setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary >= 0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for " + getName());
return salary/52;
}
}
Now, you study the following program carefully and try to determine its output −
/* File name : VirtualDemo.java */
public class VirtualDemo {
public static void main(String [] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}
This will produce the following result −
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0
Here, we instantiate two Salary objects. One using a Salary reference s, and the other using an Employee reference e.
While invoking s.mailCheck(), the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time.
mailCheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class.
Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class.
This behavior is referred to as virtual method invocation, and these methods are referred to as virtual methods. An overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.
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": 2563,
"s": 2377,
"text": "Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object."
},
{
"code": null,
"e": 2778,
"s": 2563,
"text": "Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object."
},
{
"code": null,
"e": 2995,
"s": 2778,
"text": "It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed."
},
{
"code": null,
"e": 3190,
"s": 2995,
"text": "The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object."
},
{
"code": null,
"e": 3360,
"s": 3190,
"text": "A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type."
},
{
"code": null,
"e": 3387,
"s": 3360,
"text": "Let us look at an example."
},
{
"code": null,
"e": 3496,
"s": 3387,
"text": "public interface Vegetarian{}\npublic class Animal{}\npublic class Deer extends Animal implements Vegetarian{}"
},
{
"code": null,
"e": 3629,
"s": 3496,
"text": "Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above examples −"
},
{
"code": null,
"e": 3648,
"s": 3629,
"text": "A Deer IS-A Animal"
},
{
"code": null,
"e": 3671,
"s": 3648,
"text": "A Deer IS-A Vegetarian"
},
{
"code": null,
"e": 3688,
"s": 3671,
"text": "A Deer IS-A Deer"
},
{
"code": null,
"e": 3707,
"s": 3688,
"text": "A Deer IS-A Object"
},
{
"code": null,
"e": 3817,
"s": 3707,
"text": "When we apply the reference variable facts to a Deer object reference, the following declarations are legal −"
},
{
"code": null,
"e": 3884,
"s": 3817,
"text": "Deer d = new Deer();\nAnimal a = d;\nVegetarian v = d;\nObject o = d;"
},
{
"code": null,
"e": 3966,
"s": 3884,
"text": "All the reference variables d, a, v, o refer to the same Deer object in the heap."
},
{
"code": null,
"e": 4120,
"s": 3966,
"text": "In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes."
},
{
"code": null,
"e": 4381,
"s": 4120,
"text": "We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method."
},
{
"code": null,
"e": 5170,
"s": 4381,
"text": "/* File name : Employee.java */\npublic class Employee {\n private String name;\n private String address;\n private int number;\n\n public Employee(String name, String address, int number) {\n System.out.println(\"Constructing an Employee\");\n this.name = name;\n this.address = address;\n this.number = number;\n }\n\n public void mailCheck() {\n System.out.println(\"Mailing a check to \" + this.name + \" \" + this.address);\n }\n\n public String toString() {\n return name + \" \" + address + \" \" + number;\n }\n\n public String getName() {\n return name;\n }\n\n public String getAddress() {\n return address;\n }\n\n public void setAddress(String newAddress) {\n address = newAddress;\n }\n\n public int getNumber() {\n return number;\n }\n}"
},
{
"code": null,
"e": 5220,
"s": 5170,
"text": "Now suppose we extend Employee class as follows −"
},
{
"code": null,
"e": 5985,
"s": 5220,
"text": "/* File name : Salary.java */\npublic class Salary extends Employee {\n private double salary; // Annual salary\n \n public Salary(String name, String address, int number, double salary) {\n super(name, address, number);\n setSalary(salary);\n }\n \n public void mailCheck() {\n System.out.println(\"Within mailCheck of Salary class \");\n System.out.println(\"Mailing check to \" + getName()\n + \" with salary \" + salary);\n }\n \n public double getSalary() {\n return salary;\n }\n \n public void setSalary(double newSalary) {\n if(newSalary >= 0.0) {\n salary = newSalary;\n }\n }\n \n public double computePay() {\n System.out.println(\"Computing salary pay for \" + getName());\n return salary/52;\n }\n}"
},
{
"code": null,
"e": 6066,
"s": 5985,
"text": "Now, you study the following program carefully and try to determine its output −"
},
{
"code": null,
"e": 6515,
"s": 6066,
"text": "/* File name : VirtualDemo.java */\npublic class VirtualDemo {\n\n public static void main(String [] args) {\n Salary s = new Salary(\"Mohd Mohtashim\", \"Ambehta, UP\", 3, 3600.00);\n Employee e = new Salary(\"John Adams\", \"Boston, MA\", 2, 2400.00);\n System.out.println(\"Call mailCheck using Salary reference --\"); \n s.mailCheck();\n System.out.println(\"\\n Call mailCheck using Employee reference--\");\n e.mailCheck();\n }\n}"
},
{
"code": null,
"e": 6556,
"s": 6515,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 6856,
"s": 6556,
"text": "Constructing an Employee\nConstructing an Employee\n\nCall mailCheck using Salary reference --\nWithin mailCheck of Salary class\nMailing check to Mohd Mohtashim with salary 3600.0\n\nCall mailCheck using Employee reference--\nWithin mailCheck of Salary class\nMailing check to John Adams with salary 2400.0\n"
},
{
"code": null,
"e": 6974,
"s": 6856,
"text": "Here, we instantiate two Salary objects. One using a Salary reference s, and the other using an Employee reference e."
},
{
"code": null,
"e": 7136,
"s": 6974,
"text": "While invoking s.mailCheck(), the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time."
},
{
"code": null,
"e": 7310,
"s": 7136,
"text": "mailCheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class."
},
{
"code": null,
"e": 7474,
"s": 7310,
"text": "Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class."
},
{
"code": null,
"e": 7724,
"s": 7474,
"text": "This behavior is referred to as virtual method invocation, and these methods are referred to as virtual methods. An overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time."
},
{
"code": null,
"e": 7757,
"s": 7724,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 7773,
"s": 7757,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7806,
"s": 7773,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 7822,
"s": 7806,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7857,
"s": 7822,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7871,
"s": 7857,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7905,
"s": 7871,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 7919,
"s": 7905,
"text": " Tushar Kale"
},
{
"code": null,
"e": 7956,
"s": 7919,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7971,
"s": 7956,
"text": " Monica Mittal"
},
{
"code": null,
"e": 8004,
"s": 7971,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8023,
"s": 8004,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 8030,
"s": 8023,
"text": " Print"
},
{
"code": null,
"e": 8041,
"s": 8030,
"text": " Add Notes"
}
] |
SQL DELETE JOIN | 25 Oct, 2021
We use joins to combine data from multiple tables. To delete the same rows or related rows from the table at that time we use delete join. In this article let us see how to delete multiple data using DELETE using JOIN by using MSSQL as a server.
Syntax:
DELETE table1
FROM table1 JOIN table2 ON
table1.attribute_name = table2.attribute_name
WHERE condition
Step 1: We are creating a Database. For this use the below command to create a database named GeeksforGeeks.
Query:
CREATE DATABASE GeeksforGeeks;
Step 2: To use the GeeksforGeeks database use the below command.
Query:
USE GeeksforGeeks
Output:
Step 3: Now we are creating two tables. Create a table for students with 3 columns and library_books with 2 columns using the following SQL query.
Query:
CREATE TABLE student (
student_id VARCHAR(8),
student_name VARCHAR(20),
student_branch VARCHAR(20)
)
Output:
Query:
CREATE TABLE library_books(
lib_id VARCHAR(20),
book_taken INT
)
Output:
Step 4: Viewing the description of the tables.
Query:
EXEC sp_columns students
Output:
Query:
EXEC sp_columns library_books
Output:
Step 5: The query for Inserting rows into the Table. Inserting rows into students and library_books table using the following SQL query.
Query:
INSERT INTO students
VALUES( '1001','PRADEEP','E.C.E'),
( '1002','KIRAN','E.C.E'),
( '1003','PRANAV','E.C.E'),
( '2001','PADMA','C.S.E'),
( '2002','SRUTHI','C.S.E'),
( '2003','HARSITHA','C.S.E'),
( '3001','SAI','I.T'),
( '3002','HARSH','I.T'),
( '3003','HARSHINI','I.T')
Output:
Query:
INSERT INTO library_books
VALUES( '1001',2),
( '1002',3),
( '1003',4),
( '2001',2),
( '3001',3)
Output:
Step 6: Viewing the inserted data
Query:
SELECT * FROM students
Output:
Query:
SELECT * FROM library_books
Output:
Query to delete library entry for id 1001 using join
Query:
DELETE library_books
FROM library_books JOIN students ON
students.student_id =library_books.lib_id
WHERE lib_id= 1001
SELECT * FROM library_books
Output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Update Multiple Columns in Single Update Statement in SQL?
Window functions in SQL
What is Temporary Table in SQL?
SQL using Python
SQL | Sub queries in From Clause
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
RANK() Function in SQL Server
SQL Query to Convert VARCHAR to INT
SQL Query to Compare Two Dates
SQL Query to Insert Multiple Rows | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 274,
"s": 28,
"text": "We use joins to combine data from multiple tables. To delete the same rows or related rows from the table at that time we use delete join. In this article let us see how to delete multiple data using DELETE using JOIN by using MSSQL as a server."
},
{
"code": null,
"e": 282,
"s": 274,
"text": "Syntax:"
},
{
"code": null,
"e": 385,
"s": 282,
"text": "DELETE table1\nFROM table1 JOIN table2 ON\ntable1.attribute_name = table2.attribute_name\nWHERE condition"
},
{
"code": null,
"e": 494,
"s": 385,
"text": "Step 1: We are creating a Database. For this use the below command to create a database named GeeksforGeeks."
},
{
"code": null,
"e": 501,
"s": 494,
"text": "Query:"
},
{
"code": null,
"e": 532,
"s": 501,
"text": "CREATE DATABASE GeeksforGeeks;"
},
{
"code": null,
"e": 597,
"s": 532,
"text": "Step 2: To use the GeeksforGeeks database use the below command."
},
{
"code": null,
"e": 604,
"s": 597,
"text": "Query:"
},
{
"code": null,
"e": 622,
"s": 604,
"text": "USE GeeksforGeeks"
},
{
"code": null,
"e": 630,
"s": 622,
"text": "Output:"
},
{
"code": null,
"e": 777,
"s": 630,
"text": "Step 3: Now we are creating two tables. Create a table for students with 3 columns and library_books with 2 columns using the following SQL query."
},
{
"code": null,
"e": 784,
"s": 777,
"text": "Query:"
},
{
"code": null,
"e": 885,
"s": 784,
"text": "CREATE TABLE student (\nstudent_id VARCHAR(8),\nstudent_name VARCHAR(20),\nstudent_branch VARCHAR(20)\n)"
},
{
"code": null,
"e": 893,
"s": 885,
"text": "Output:"
},
{
"code": null,
"e": 900,
"s": 893,
"text": "Query:"
},
{
"code": null,
"e": 965,
"s": 900,
"text": "CREATE TABLE library_books(\nlib_id VARCHAR(20),\nbook_taken INT\n)"
},
{
"code": null,
"e": 973,
"s": 965,
"text": "Output:"
},
{
"code": null,
"e": 1020,
"s": 973,
"text": "Step 4: Viewing the description of the tables."
},
{
"code": null,
"e": 1027,
"s": 1020,
"text": "Query:"
},
{
"code": null,
"e": 1052,
"s": 1027,
"text": "EXEC sp_columns students"
},
{
"code": null,
"e": 1060,
"s": 1052,
"text": "Output:"
},
{
"code": null,
"e": 1067,
"s": 1060,
"text": "Query:"
},
{
"code": null,
"e": 1097,
"s": 1067,
"text": "EXEC sp_columns library_books"
},
{
"code": null,
"e": 1105,
"s": 1097,
"text": "Output:"
},
{
"code": null,
"e": 1243,
"s": 1105,
"text": "Step 5: The query for Inserting rows into the Table. Inserting rows into students and library_books table using the following SQL query."
},
{
"code": null,
"e": 1250,
"s": 1243,
"text": "Query:"
},
{
"code": null,
"e": 1521,
"s": 1250,
"text": "INSERT INTO students\nVALUES( '1001','PRADEEP','E.C.E'),\n( '1002','KIRAN','E.C.E'),\n( '1003','PRANAV','E.C.E'),\n( '2001','PADMA','C.S.E'),\n( '2002','SRUTHI','C.S.E'),\n( '2003','HARSITHA','C.S.E'),\n( '3001','SAI','I.T'),\n( '3002','HARSH','I.T'),\n( '3003','HARSHINI','I.T')"
},
{
"code": null,
"e": 1529,
"s": 1521,
"text": "Output:"
},
{
"code": null,
"e": 1536,
"s": 1529,
"text": "Query:"
},
{
"code": null,
"e": 1632,
"s": 1536,
"text": "INSERT INTO library_books\nVALUES( '1001',2),\n( '1002',3),\n( '1003',4),\n( '2001',2),\n( '3001',3)"
},
{
"code": null,
"e": 1640,
"s": 1632,
"text": "Output:"
},
{
"code": null,
"e": 1674,
"s": 1640,
"text": "Step 6: Viewing the inserted data"
},
{
"code": null,
"e": 1681,
"s": 1674,
"text": "Query:"
},
{
"code": null,
"e": 1704,
"s": 1681,
"text": "SELECT * FROM students"
},
{
"code": null,
"e": 1712,
"s": 1704,
"text": "Output:"
},
{
"code": null,
"e": 1719,
"s": 1712,
"text": "Query:"
},
{
"code": null,
"e": 1747,
"s": 1719,
"text": "SELECT * FROM library_books"
},
{
"code": null,
"e": 1755,
"s": 1747,
"text": "Output:"
},
{
"code": null,
"e": 1808,
"s": 1755,
"text": "Query to delete library entry for id 1001 using join"
},
{
"code": null,
"e": 1815,
"s": 1808,
"text": "Query:"
},
{
"code": null,
"e": 1963,
"s": 1815,
"text": "DELETE library_books\nFROM library_books JOIN students ON\nstudents.student_id =library_books.lib_id\nWHERE lib_id= 1001 \nSELECT * FROM library_books"
},
{
"code": null,
"e": 1971,
"s": 1963,
"text": "Output:"
},
{
"code": null,
"e": 1978,
"s": 1971,
"text": "Picked"
},
{
"code": null,
"e": 1989,
"s": 1978,
"text": "SQL-Server"
},
{
"code": null,
"e": 1993,
"s": 1989,
"text": "SQL"
},
{
"code": null,
"e": 1997,
"s": 1993,
"text": "SQL"
},
{
"code": null,
"e": 2095,
"s": 1997,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2161,
"s": 2095,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 2185,
"s": 2161,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 2217,
"s": 2185,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 2234,
"s": 2217,
"text": "SQL using Python"
},
{
"code": null,
"e": 2267,
"s": 2234,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 2345,
"s": 2267,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 2375,
"s": 2345,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 2411,
"s": 2375,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 2442,
"s": 2411,
"text": "SQL Query to Compare Two Dates"
}
] |
Angular PrimeNG InputText Component | 19 Aug, 2021
Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the InputText component in angular primeNG. Let’s learn about the properties, styling & their syntaxes that will be used in the code.
InputTextArea component: It is an element that is used to make a text field with multi-line input support.
Properties:
disabled: We can set the input component to be disabled. It is of a boolean data type & the default value is false.
Styling:
p-inputtext: It is a directive & applied to the text input field.
<input type="text" pInputText />
Model Binding: ngModel directive is used to bind the model.
<input type="text" pInputText [(ngModel)]="property"/>
Size: In addition to the regular sizes, there are more than 2 sizes that are available, add p-inputtext-sm for small text input & add p-inputtext-lg for large text input. These classes must be used to change the size of the particular input field.For smaller input text
<input type="text" pInputText class="p-inputtext-sm">
For larger input text
<input type="text" pInputText class="p-inputtext-lg">
Creating Angular Application & Module Installation:
Step 1: Create an Angular application using the following command.ng new appname
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname
cd appname
Step 3: Install PrimeNG in your given directory.npm install primeng --save
npm install primeicons --save
npm install primeng --save
npm install primeicons --save
Project Structure: It will look like the following.
Example 1: This is the basic example that shows how to use InputText component
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG InputText component</h5><div class="sizes"> <input type="text" class="p-inputtext-lg" placeholder="Input text here" pInputText/></div>
app.module.ts
import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; import { AppComponent } from "./app.component"; import { InputTextModule } from "primeng/inputtext"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, InputTextModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}
Output:
Example 2: In this example, we will know how to set the size of the InputText component.
app.component.html
<h2>GeeksforGeeks</h2><h5>PrimeNG InputText component</h5><div class="sizes"> <input type="text" class="p-inputtext-sm" placeholder="Input text here" pInputText/> <input type="text" placeholder="Input text here" pInputText /> <input type="text" class="p-inputtext-lg" placeholder="Input text here" pInputText/></div>
app.module.ts
import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { InputTextModule } from 'primeng/inputtext'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, InputTextModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}
Output:
Reference: https://primefaces.org/primeng/showcase/#/inputtext
Angular-PrimeNG
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Routing in Angular 9/10
Angular PrimeNG Dropdown Component
Angular 10 (blur) Event
How to make a Bootstrap Modal Popup in Angular 9/8 ?
How to create module with Routing in Angular 9 ?
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 404,
"s": 28,
"text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the InputText component in angular primeNG. Let’s learn about the properties, styling & their syntaxes that will be used in the code. "
},
{
"code": null,
"e": 511,
"s": 404,
"text": "InputTextArea component: It is an element that is used to make a text field with multi-line input support."
},
{
"code": null,
"e": 523,
"s": 511,
"text": "Properties:"
},
{
"code": null,
"e": 639,
"s": 523,
"text": "disabled: We can set the input component to be disabled. It is of a boolean data type & the default value is false."
},
{
"code": null,
"e": 648,
"s": 639,
"text": "Styling:"
},
{
"code": null,
"e": 714,
"s": 648,
"text": "p-inputtext: It is a directive & applied to the text input field."
},
{
"code": null,
"e": 747,
"s": 714,
"text": "<input type=\"text\" pInputText />"
},
{
"code": null,
"e": 809,
"s": 749,
"text": "Model Binding: ngModel directive is used to bind the model."
},
{
"code": null,
"e": 864,
"s": 809,
"text": "<input type=\"text\" pInputText [(ngModel)]=\"property\"/>"
},
{
"code": null,
"e": 1134,
"s": 864,
"text": "Size: In addition to the regular sizes, there are more than 2 sizes that are available, add p-inputtext-sm for small text input & add p-inputtext-lg for large text input. These classes must be used to change the size of the particular input field.For smaller input text"
},
{
"code": null,
"e": 1188,
"s": 1134,
"text": "<input type=\"text\" pInputText class=\"p-inputtext-sm\">"
},
{
"code": null,
"e": 1210,
"s": 1188,
"text": "For larger input text"
},
{
"code": null,
"e": 1265,
"s": 1210,
"text": "<input type=\"text\" pInputText class=\"p-inputtext-lg\"> "
},
{
"code": null,
"e": 1317,
"s": 1265,
"text": "Creating Angular Application & Module Installation:"
},
{
"code": null,
"e": 1398,
"s": 1317,
"text": "Step 1: Create an Angular application using the following command.ng new appname"
},
{
"code": null,
"e": 1413,
"s": 1398,
"text": "ng new appname"
},
{
"code": null,
"e": 1520,
"s": 1413,
"text": "Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname"
},
{
"code": null,
"e": 1531,
"s": 1520,
"text": "cd appname"
},
{
"code": null,
"e": 1636,
"s": 1531,
"text": "Step 3: Install PrimeNG in your given directory.npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 1693,
"s": 1636,
"text": "npm install primeng --save\nnpm install primeicons --save"
},
{
"code": null,
"e": 1745,
"s": 1693,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 1827,
"s": 1747,
"text": "Example 1: This is the basic example that shows how to use InputText component "
},
{
"code": null,
"e": 1846,
"s": 1827,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG InputText component</h5><div class=\"sizes\"> <input type=\"text\" class=\"p-inputtext-lg\" placeholder=\"Input text here\" pInputText/></div>",
"e": 2028,
"s": 1846,
"text": null
},
{
"code": null,
"e": 2042,
"s": 2028,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\"; import { AppComponent } from \"./app.component\"; import { InputTextModule } from \"primeng/inputtext\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, InputTextModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}",
"e": 2492,
"s": 2042,
"text": null
},
{
"code": null,
"e": 2500,
"s": 2492,
"text": "Output:"
},
{
"code": null,
"e": 2590,
"s": 2500,
"text": "Example 2: In this example, we will know how to set the size of the InputText component. "
},
{
"code": null,
"e": 2609,
"s": 2590,
"text": "app.component.html"
},
{
"code": "<h2>GeeksforGeeks</h2><h5>PrimeNG InputText component</h5><div class=\"sizes\"> <input type=\"text\" class=\"p-inputtext-sm\" placeholder=\"Input text here\" pInputText/> <input type=\"text\" placeholder=\"Input text here\" pInputText /> <input type=\"text\" class=\"p-inputtext-lg\" placeholder=\"Input text here\" pInputText/></div>",
"e": 2953,
"s": 2609,
"text": null
},
{
"code": null,
"e": 2967,
"s": 2953,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; import { InputTextModule } from 'primeng/inputtext'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, InputTextModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}",
"e": 3446,
"s": 2967,
"text": null
},
{
"code": null,
"e": 3454,
"s": 3446,
"text": "Output:"
},
{
"code": null,
"e": 3517,
"s": 3454,
"text": "Reference: https://primefaces.org/primeng/showcase/#/inputtext"
},
{
"code": null,
"e": 3533,
"s": 3517,
"text": "Angular-PrimeNG"
},
{
"code": null,
"e": 3543,
"s": 3533,
"text": "AngularJS"
},
{
"code": null,
"e": 3560,
"s": 3543,
"text": "Web Technologies"
},
{
"code": null,
"e": 3658,
"s": 3560,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3682,
"s": 3658,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 3717,
"s": 3682,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 3741,
"s": 3717,
"text": "Angular 10 (blur) Event"
},
{
"code": null,
"e": 3794,
"s": 3741,
"text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?"
},
{
"code": null,
"e": 3843,
"s": 3794,
"text": "How to create module with Routing in Angular 9 ?"
},
{
"code": null,
"e": 3876,
"s": 3843,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3938,
"s": 3876,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3999,
"s": 3938,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4049,
"s": 3999,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
LINQ | Method Syntax | 21 May, 2019
In LINQ, Method Syntax is used to call the extension methods of the Enumerable or Queryable static classes. It is also known as Method Extension Syntax or Fluent. However, the compiler always converts the query syntax in method syntax at compile time. It can invoke the standard query operator like Select, Where, GroupBy, Join, Max, etc. You are allowed to call them directly without using query syntax.
Creating first LINQ Query using Method Syntax in C#
Step 1: First add System.Linq namespace in your code.using System.Linq;
using System.Linq;
Step 2: Next, create a data source on which you want to perform operations. For example:List my_list = new List(){
"This is my Dog",
"Name of my Dog is Robin",
"This is my Cat",
"Name of the cat is Mewmew"
};
List my_list = new List(){
"This is my Dog",
"Name of my Dog is Robin",
"This is my Cat",
"Name of the cat is Mewmew"
};
Step 3: Now create the query using the methods provided by the Enumerable or Queryable static classes. For example:
var res = my_list.Where(a=> a.Contains("Dog"));
Here res is the query variable which stores the result of the query expression. Here we are finding those strings which contain “Dog” in it. So, we use Where() method to filters the data source according to the lambda expression given in the method, i.e, a=> a.Contains(“Dog”).
var res = my_list.Where(a=> a.Contains("Dog"));
Here res is the query variable which stores the result of the query expression. Here we are finding those strings which contain “Dog” in it. So, we use Where() method to filters the data source according to the lambda expression given in the method, i.e, a=> a.Contains(“Dog”).
Step 4: Last step is to execute the query by using a foreach loop. For example:foreach(var q in res)
{
Console.WriteLine(q);
}
foreach(var q in res)
{
Console.WriteLine(q);
}
Example:
// Create the first Query in C# using Method Syntaxusing System;using System.Linq;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Data source List<string> my_list = new List<string>() { "This is my Dog", "Name of my Dog is Robin", "This is my Cat", "Name of the cat is Mewmew" }; // Creating LINQ Query // Using Method syntax var res = my_list.Where(a => a.Contains("Dog")); // Executing LINQ Query foreach(var q in res) { Console.WriteLine(q); } }}
This is my Dog
Name of my Dog is Robin
CSharp LINQ
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Delegates
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 May, 2019"
},
{
"code": null,
"e": 457,
"s": 52,
"text": "In LINQ, Method Syntax is used to call the extension methods of the Enumerable or Queryable static classes. It is also known as Method Extension Syntax or Fluent. However, the compiler always converts the query syntax in method syntax at compile time. It can invoke the standard query operator like Select, Where, GroupBy, Join, Max, etc. You are allowed to call them directly without using query syntax."
},
{
"code": null,
"e": 509,
"s": 457,
"text": "Creating first LINQ Query using Method Syntax in C#"
},
{
"code": null,
"e": 581,
"s": 509,
"text": "Step 1: First add System.Linq namespace in your code.using System.Linq;"
},
{
"code": null,
"e": 600,
"s": 581,
"text": "using System.Linq;"
},
{
"code": null,
"e": 846,
"s": 600,
"text": "Step 2: Next, create a data source on which you want to perform operations. For example:List my_list = new List(){\n \"This is my Dog\",\n \"Name of my Dog is Robin\",\n \"This is my Cat\",\n \"Name of the cat is Mewmew\"\n };\n"
},
{
"code": null,
"e": 1004,
"s": 846,
"text": "List my_list = new List(){\n \"This is my Dog\",\n \"Name of my Dog is Robin\",\n \"This is my Cat\",\n \"Name of the cat is Mewmew\"\n };\n"
},
{
"code": null,
"e": 1450,
"s": 1004,
"text": "Step 3: Now create the query using the methods provided by the Enumerable or Queryable static classes. For example: \nvar res = my_list.Where(a=> a.Contains(\"Dog\"));\nHere res is the query variable which stores the result of the query expression. Here we are finding those strings which contain “Dog” in it. So, we use Where() method to filters the data source according to the lambda expression given in the method, i.e, a=> a.Contains(“Dog”)."
},
{
"code": null,
"e": 1504,
"s": 1450,
"text": " \nvar res = my_list.Where(a=> a.Contains(\"Dog\"));\n"
},
{
"code": null,
"e": 1782,
"s": 1504,
"text": "Here res is the query variable which stores the result of the query expression. Here we are finding those strings which contain “Dog” in it. So, we use Where() method to filters the data source according to the lambda expression given in the method, i.e, a=> a.Contains(“Dog”)."
},
{
"code": null,
"e": 1919,
"s": 1782,
"text": "Step 4: Last step is to execute the query by using a foreach loop. For example:foreach(var q in res)\n{\n Console.WriteLine(q);\n}\n"
},
{
"code": null,
"e": 1977,
"s": 1919,
"text": "foreach(var q in res)\n{\n Console.WriteLine(q);\n}\n"
},
{
"code": null,
"e": 1986,
"s": 1977,
"text": "Example:"
},
{
"code": "// Create the first Query in C# using Method Syntaxusing System;using System.Linq;using System.Collections.Generic; class GFG { // Main Method static public void Main() { // Data source List<string> my_list = new List<string>() { \"This is my Dog\", \"Name of my Dog is Robin\", \"This is my Cat\", \"Name of the cat is Mewmew\" }; // Creating LINQ Query // Using Method syntax var res = my_list.Where(a => a.Contains(\"Dog\")); // Executing LINQ Query foreach(var q in res) { Console.WriteLine(q); } }}",
"e": 2642,
"s": 1986,
"text": null
},
{
"code": null,
"e": 2682,
"s": 2642,
"text": "This is my Dog\nName of my Dog is Robin\n"
},
{
"code": null,
"e": 2694,
"s": 2682,
"text": "CSharp LINQ"
},
{
"code": null,
"e": 2697,
"s": 2694,
"text": "C#"
},
{
"code": null,
"e": 2795,
"s": 2697,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2823,
"s": 2795,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 2866,
"s": 2823,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2897,
"s": 2866,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 2946,
"s": 2897,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2961,
"s": 2946,
"text": "C# | Delegates"
},
{
"code": null,
"e": 2977,
"s": 2961,
"text": "C# | Data Types"
},
{
"code": null,
"e": 3000,
"s": 2977,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 3040,
"s": 3000,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 3058,
"s": 3040,
"text": "C# | Constructors"
}
] |
Functions in R Programming | 19 Apr, 2022
Functions are useful when you want to perform a certain task multiple times. A function accepts input arguments and produces the output by executing valid R commands that are inside the function. In R Programming Language when you are creating a function the function name and the file in which you are creating the function need not be the same and you can have one or more function definitions in a single R file.
Built-in Function: Built function R is sq(), mean(), max(), these function are directly call in the program by users.
User-defined Function: R language allow us to write our own function.
Functions are created in R by using the command function(). The general structure of the function file is as follows:
Note: In the above syntax f is the function name, this means that you are creating a function with name f which takes certain arguments and executes the following statements.
Here we will use built-in function like sum(), max() and min().
R
# Find sum of numbers 4 to 6.print(sum(4:6)) # Find max of numbers 4 and 6.print(max(4:6)) # Find min of numbers 4 and 6.print(min(4:6))
Output:
[1] 15
[1] 6
[1] 4
R provides built-in functions like print(), cat(), etc. but we can also create our own functions. These functions are called user-defined functions.
Example:
R
# A simple R function to check# whether x is even or odd evenOdd = function(x){ if(x %% 2 == 0) return("even") else return("odd")} print(evenOdd(4))print(evenOdd(3))
Output:
[1] "even"
[1] "odd"
Now create a function in R that will take a single input and gives us a single output.
Following is an example to create a function that calculates the area of a circle which takes in the arguments the radius. So, to create a function, name the function as “areaOfCircle” and the arguments that are needed to be passed are the “radius” of the circle.
R
# A simple R function to calculate# area of a circle areaOfCircle = function(radius){ area = pi*radius^2 return(area)} print(areaOfCircle(2))
Output:
12.56637
Now create a function in R Language that will take multiple inputs and gives us multiple outputs using a list.
The functions in R Language takes multiple input objects but returned only one object as output, this is, however, not a limitation because you can create lists of all the outputs which you want to create and once the list is created you can access them into the elements of the list and get the answers which you want.
Let us consider this example to create a function “Rectangle” which takes “length” and “width” of the rectangle and returns area and perimeter of that rectangle. Since R Language can return only one object. Hence, create one object which is a list that contains “area” and “perimeter” and return the list.
R
# A simple R function to calculate# area and perimeter of a rectangle Rectangle = function(length, width){ area = length * width perimeter = 2 * (length + width) # create an object called result which is # a list of area and perimeter result = list("Area" = area, "Perimeter" = perimeter) return(result)} resultList = Rectangle(2, 3)print(resultList["Area"])print(resultList["Perimeter"])
Output:
$Area
[1] 6
$Perimeter
[1] 10
Sometimes creating an R script file, loading it, executing it is a lot of work when you want to just create a very small function. So, what we can do in this kind of situation is an inline function.
To create an inline function you have to use the function command with the argument x and then the expression of the function.
Example:
R
# A simple R program to# demonstrate the inline function f = function(x) x^2*4+x/3 print(f(4))print(f(-2))print(0)
Output:
65.33333
15.33333
0
There are several ways you can pass the arguments to the function:
Case 1: Generally in R, the arguments are passed to the function in the same order as in the function definition.
Case 2: If you do not want to follow any order what you can do is you can pass the arguments using the names of the arguments in any order.
Case 3: If the arguments are not passed the default values are used to execute the function.
Now, let us see the examples for each of these cases in the following R code:
R
# A simple R program to demonstrate# passing arguments to a function Rectangle = function(length=5, width=4){ area = length * width return(area)} # Case 1:print(Rectangle(2, 3)) # Case 2:print(Rectangle(width = 8, length = 4)) # Case 3:print(Rectangle())
Output:
6
32
20
In R the functions are executed in a lazy fashion. When we say lazy what it means is if some arguments are missing the function is still executed as long as the execution does not involve those arguments.
Example:
In the function “Cylinder” given below. There are defined three-argument “diameter”, “length” and “radius” in the function and the volume calculation does not involve this argument “radius” in this calculation. Now, when you pass this argument “diameter” and “length” even though you are not passing this “radius” the function will still execute because this radius is not used in the calculations inside the function. Let’s illustrate this in an R code given below:
R
# A simple R program to demonstrate# Lazy evaluations of functions Cylinder = function(diameter, length, radius ){ volume = pi*diameter^2*length/4 return(volume)} # This'll execute because this# radius is not used in the# calculations inside the function.print(Cylinder(5, 10))
Output:
196.3495
If you do not pass the argument and then use it in the definition of the function it will throw an error that this “radius” is not passed and it is being used in the function definition.
Example:
R
# A simple R program to demonstrate# Lazy evaluations of functions Cylinder = function(diameter, length, radius ){ volume = pi*diameter^2*length/4 print(radius) return(volume)} # This'll throw an errorprint(Cylinder(5, 10))
Output:
Error in print(radius) : argument "radius" is missing, with no default
surindertarika1234
kumar_satyam
ruhelaa48
jagdish11910155
Picked
R-Functions
Programming Language
R Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Apr, 2022"
},
{
"code": null,
"e": 468,
"s": 52,
"text": "Functions are useful when you want to perform a certain task multiple times. A function accepts input arguments and produces the output by executing valid R commands that are inside the function. In R Programming Language when you are creating a function the function name and the file in which you are creating the function need not be the same and you can have one or more function definitions in a single R file."
},
{
"code": null,
"e": 586,
"s": 468,
"text": "Built-in Function: Built function R is sq(), mean(), max(), these function are directly call in the program by users."
},
{
"code": null,
"e": 656,
"s": 586,
"text": "User-defined Function: R language allow us to write our own function."
},
{
"code": null,
"e": 775,
"s": 656,
"text": "Functions are created in R by using the command function(). The general structure of the function file is as follows: "
},
{
"code": null,
"e": 950,
"s": 775,
"text": "Note: In the above syntax f is the function name, this means that you are creating a function with name f which takes certain arguments and executes the following statements."
},
{
"code": null,
"e": 1014,
"s": 950,
"text": "Here we will use built-in function like sum(), max() and min()."
},
{
"code": null,
"e": 1016,
"s": 1014,
"text": "R"
},
{
"code": "# Find sum of numbers 4 to 6.print(sum(4:6)) # Find max of numbers 4 and 6.print(max(4:6)) # Find min of numbers 4 and 6.print(min(4:6))",
"e": 1153,
"s": 1016,
"text": null
},
{
"code": null,
"e": 1161,
"s": 1153,
"text": "Output:"
},
{
"code": null,
"e": 1180,
"s": 1161,
"text": "[1] 15\n[1] 6\n[1] 4"
},
{
"code": null,
"e": 1329,
"s": 1180,
"text": "R provides built-in functions like print(), cat(), etc. but we can also create our own functions. These functions are called user-defined functions."
},
{
"code": null,
"e": 1340,
"s": 1329,
"text": "Example: "
},
{
"code": null,
"e": 1342,
"s": 1340,
"text": "R"
},
{
"code": "# A simple R function to check# whether x is even or odd evenOdd = function(x){ if(x %% 2 == 0) return(\"even\") else return(\"odd\")} print(evenOdd(4))print(evenOdd(3))",
"e": 1516,
"s": 1342,
"text": null
},
{
"code": null,
"e": 1525,
"s": 1516,
"text": "Output: "
},
{
"code": null,
"e": 1546,
"s": 1525,
"text": "[1] \"even\"\n[1] \"odd\""
},
{
"code": null,
"e": 1634,
"s": 1546,
"text": "Now create a function in R that will take a single input and gives us a single output. "
},
{
"code": null,
"e": 1900,
"s": 1634,
"text": "Following is an example to create a function that calculates the area of a circle which takes in the arguments the radius. So, to create a function, name the function as “areaOfCircle” and the arguments that are needed to be passed are the “radius” of the circle. "
},
{
"code": null,
"e": 1902,
"s": 1900,
"text": "R"
},
{
"code": "# A simple R function to calculate# area of a circle areaOfCircle = function(radius){ area = pi*radius^2 return(area)} print(areaOfCircle(2))",
"e": 2046,
"s": 1902,
"text": null
},
{
"code": null,
"e": 2055,
"s": 2046,
"text": "Output: "
},
{
"code": null,
"e": 2064,
"s": 2055,
"text": "12.56637"
},
{
"code": null,
"e": 2176,
"s": 2064,
"text": "Now create a function in R Language that will take multiple inputs and gives us multiple outputs using a list. "
},
{
"code": null,
"e": 2496,
"s": 2176,
"text": "The functions in R Language takes multiple input objects but returned only one object as output, this is, however, not a limitation because you can create lists of all the outputs which you want to create and once the list is created you can access them into the elements of the list and get the answers which you want."
},
{
"code": null,
"e": 2803,
"s": 2496,
"text": "Let us consider this example to create a function “Rectangle” which takes “length” and “width” of the rectangle and returns area and perimeter of that rectangle. Since R Language can return only one object. Hence, create one object which is a list that contains “area” and “perimeter” and return the list. "
},
{
"code": null,
"e": 2805,
"s": 2803,
"text": "R"
},
{
"code": "# A simple R function to calculate# area and perimeter of a rectangle Rectangle = function(length, width){ area = length * width perimeter = 2 * (length + width) # create an object called result which is # a list of area and perimeter result = list(\"Area\" = area, \"Perimeter\" = perimeter) return(result)} resultList = Rectangle(2, 3)print(resultList[\"Area\"])print(resultList[\"Perimeter\"])",
"e": 3203,
"s": 2805,
"text": null
},
{
"code": null,
"e": 3212,
"s": 3203,
"text": "Output: "
},
{
"code": null,
"e": 3243,
"s": 3212,
"text": "$Area\n[1] 6\n\n$Perimeter\n[1] 10"
},
{
"code": null,
"e": 3442,
"s": 3243,
"text": "Sometimes creating an R script file, loading it, executing it is a lot of work when you want to just create a very small function. So, what we can do in this kind of situation is an inline function."
},
{
"code": null,
"e": 3570,
"s": 3442,
"text": "To create an inline function you have to use the function command with the argument x and then the expression of the function. "
},
{
"code": null,
"e": 3580,
"s": 3570,
"text": "Example: "
},
{
"code": null,
"e": 3582,
"s": 3580,
"text": "R"
},
{
"code": "# A simple R program to# demonstrate the inline function f = function(x) x^2*4+x/3 print(f(4))print(f(-2))print(0)",
"e": 3698,
"s": 3582,
"text": null
},
{
"code": null,
"e": 3707,
"s": 3698,
"text": "Output: "
},
{
"code": null,
"e": 3727,
"s": 3707,
"text": "65.33333\n15.33333\n0"
},
{
"code": null,
"e": 3795,
"s": 3727,
"text": "There are several ways you can pass the arguments to the function: "
},
{
"code": null,
"e": 3909,
"s": 3795,
"text": "Case 1: Generally in R, the arguments are passed to the function in the same order as in the function definition."
},
{
"code": null,
"e": 4049,
"s": 3909,
"text": "Case 2: If you do not want to follow any order what you can do is you can pass the arguments using the names of the arguments in any order."
},
{
"code": null,
"e": 4142,
"s": 4049,
"text": "Case 3: If the arguments are not passed the default values are used to execute the function."
},
{
"code": null,
"e": 4220,
"s": 4142,
"text": "Now, let us see the examples for each of these cases in the following R code:"
},
{
"code": null,
"e": 4222,
"s": 4220,
"text": "R"
},
{
"code": "# A simple R program to demonstrate# passing arguments to a function Rectangle = function(length=5, width=4){ area = length * width return(area)} # Case 1:print(Rectangle(2, 3)) # Case 2:print(Rectangle(width = 8, length = 4)) # Case 3:print(Rectangle())",
"e": 4479,
"s": 4222,
"text": null
},
{
"code": null,
"e": 4488,
"s": 4479,
"text": "Output: "
},
{
"code": null,
"e": 4496,
"s": 4488,
"text": "6\n32\n20"
},
{
"code": null,
"e": 4701,
"s": 4496,
"text": "In R the functions are executed in a lazy fashion. When we say lazy what it means is if some arguments are missing the function is still executed as long as the execution does not involve those arguments."
},
{
"code": null,
"e": 4711,
"s": 4701,
"text": "Example: "
},
{
"code": null,
"e": 5178,
"s": 4711,
"text": "In the function “Cylinder” given below. There are defined three-argument “diameter”, “length” and “radius” in the function and the volume calculation does not involve this argument “radius” in this calculation. Now, when you pass this argument “diameter” and “length” even though you are not passing this “radius” the function will still execute because this radius is not used in the calculations inside the function. Let’s illustrate this in an R code given below:"
},
{
"code": null,
"e": 5180,
"s": 5178,
"text": "R"
},
{
"code": "# A simple R program to demonstrate# Lazy evaluations of functions Cylinder = function(diameter, length, radius ){ volume = pi*diameter^2*length/4 return(volume)} # This'll execute because this# radius is not used in the# calculations inside the function.print(Cylinder(5, 10))",
"e": 5460,
"s": 5180,
"text": null
},
{
"code": null,
"e": 5469,
"s": 5460,
"text": "Output: "
},
{
"code": null,
"e": 5478,
"s": 5469,
"text": "196.3495"
},
{
"code": null,
"e": 5665,
"s": 5478,
"text": "If you do not pass the argument and then use it in the definition of the function it will throw an error that this “radius” is not passed and it is being used in the function definition."
},
{
"code": null,
"e": 5675,
"s": 5665,
"text": "Example: "
},
{
"code": null,
"e": 5677,
"s": 5675,
"text": "R"
},
{
"code": "# A simple R program to demonstrate# Lazy evaluations of functions Cylinder = function(diameter, length, radius ){ volume = pi*diameter^2*length/4 print(radius) return(volume)} # This'll throw an errorprint(Cylinder(5, 10))",
"e": 5904,
"s": 5677,
"text": null
},
{
"code": null,
"e": 5913,
"s": 5904,
"text": "Output: "
},
{
"code": null,
"e": 5985,
"s": 5913,
"text": "Error in print(radius) : argument \"radius\" is missing, with no default "
},
{
"code": null,
"e": 6004,
"s": 5985,
"text": "surindertarika1234"
},
{
"code": null,
"e": 6017,
"s": 6004,
"text": "kumar_satyam"
},
{
"code": null,
"e": 6027,
"s": 6017,
"text": "ruhelaa48"
},
{
"code": null,
"e": 6043,
"s": 6027,
"text": "jagdish11910155"
},
{
"code": null,
"e": 6050,
"s": 6043,
"text": "Picked"
},
{
"code": null,
"e": 6062,
"s": 6050,
"text": "R-Functions"
},
{
"code": null,
"e": 6083,
"s": 6062,
"text": "Programming Language"
},
{
"code": null,
"e": 6094,
"s": 6083,
"text": "R Language"
},
{
"code": null,
"e": 6110,
"s": 6094,
"text": "Write From Home"
}
] |
Print Fibonacci Series in reverse order | 26 Nov, 2021
Given a number n then print n terms of fibonacci series in reverse order.
Examples:
Input : n = 5
Output : 3 2 1 1 0
Input : n = 8
Output : 13 8 5 3 2 1 1 0
Algorithm
1) Declare an array of size n. 2) Initialize a[0] and a[1] to 0 and 1 respectively. 3) Run a loop from 2 to n-1 and store sum of a[i-2] and a[i-1] in a[i]. 4) Print the array in the reverse order.
C++
Java
Python3
C#
PHP
Javascript
// CPP Program to print Fibonacci// series in reverse order#include <bits/stdc++.h>using namespace std; void reverseFibonacci(int n){ int a[n]; // assigning first and second elements a[0] = 0; a[1] = 1; for (int i = 2; i < n; i++) { // storing sum in the // preceding location a[i] = a[i - 2] + a[i - 1]; } for (int i = n - 1; i >= 0; i--) { // printing array in // reverse order cout << a[i] << " "; }} // Driver functionint main(){ int n = 5; reverseFibonacci(n); return 0;}
// Java Program to print Fibonacci// series in reverse orderimport java.io.*; class GFG { static void reverseFibonacci(int n) { int a[] = new int[n]; // assigning first and second elements a[0] = 0; a[1] = 1; for (int i = 2; i < n; i++) { // storing sum in the // preceding location a[i] = a[i - 2] + a[i - 1]; } for (int i = n - 1; i >= 0; i--) { // printing array in // reverse order System.out.print(a[i] +" "); } } // Driver function public static void main(String[] args) { int n = 5; reverseFibonacci(n); }} // This code is contributed by vt_m.
# Python 3 Program to print Fibonacci# series in reverse order def reverseFibonacci(n): a = [0] * n # assigning first and second elements a[0] = 0 a[1] = 1 for i in range(2, n): # storing sum in the # preceding location a[i] = a[i - 2] + a[i - 1] for i in range(n - 1, -1 , -1): # printing array in # reverse order print(a[i],end=" ") # Driver functionn = 5reverseFibonacci(n)
// C# Program to print Fibonacci// series in reverse orderusing System; class GFG { static void reverseFibonacci(int n) { int []a = new int[n]; // assigning first and second elements a[0] = 0; a[1] = 1; for (int i = 2; i < n; i++) { // storing sum in the // preceding location a[i] = a[i - 2] + a[i - 1]; } for (int i = n - 1; i >= 0; i--) { // printing array in // reverse order Console.Write(a[i] +" "); } } // Driver function public static void Main() { int n = 5; reverseFibonacci(n); }} // This code is contributed by vt_m.
<?php// PHP Program to print Fibonacci// series in reverse order function reverseFibonacci($n){ // assigning first and // second elements $a[0] = 0; $a[1] = 1; for ($i = 2; $i < $n; $i++) { // storing sum in the // preceding location $a[$i] = $a[$i - 2] + $a[$i - 1]; } for ($i = $n - 1; $i >= 0; $i--) { // printing array in // reverse order echo($a[$i] . " "); }} // Driver COde$n = 5;reverseFibonacci($n); // This code is contributed by Ajit.?>
<script> // JavaScript program to print Fibonacci// series in reverse orderfunction reverseFibonacci(n){ let a = []; // Assigning first and second elements a[0] = 0; a[1] = 1; for(let i = 2; i < n; i++) { // Storing sum in the // preceding location a[i] = a[i - 2] + a[i - 1]; } for(let i = n - 1; i >= 0; i--) { // Printing array in // reverse order document.write(a[i] + " "); }} // Driver Codelet n = 5; reverseFibonacci(n); // This code is contributed by avijitmondal1998 </script>
Output:
3 2 1 1 0
Time Complexity: O(n)
Auxiliary Space: O(n)
jit_t
avijitmondal1998
samim2000
Fibonacci
Reverse
Dynamic Programming
Dynamic Programming
Fibonacci
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Floyd Warshall Algorithm | DP-16
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
Sieve of Eratosthenes
Bellman–Ford Algorithm | DP-23
Find if there is a path between two vertices in an undirected graph
Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)
Find minimum number of coins that make a given value | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Nov, 2021"
},
{
"code": null,
"e": 127,
"s": 53,
"text": "Given a number n then print n terms of fibonacci series in reverse order."
},
{
"code": null,
"e": 138,
"s": 127,
"text": "Examples: "
},
{
"code": null,
"e": 212,
"s": 138,
"text": "Input : n = 5\nOutput : 3 2 1 1 0\n\nInput : n = 8\nOutput : 13 8 5 3 2 1 1 0"
},
{
"code": null,
"e": 224,
"s": 212,
"text": "Algorithm "
},
{
"code": null,
"e": 421,
"s": 224,
"text": "1) Declare an array of size n. 2) Initialize a[0] and a[1] to 0 and 1 respectively. 3) Run a loop from 2 to n-1 and store sum of a[i-2] and a[i-1] in a[i]. 4) Print the array in the reverse order."
},
{
"code": null,
"e": 425,
"s": 421,
"text": "C++"
},
{
"code": null,
"e": 430,
"s": 425,
"text": "Java"
},
{
"code": null,
"e": 438,
"s": 430,
"text": "Python3"
},
{
"code": null,
"e": 441,
"s": 438,
"text": "C#"
},
{
"code": null,
"e": 445,
"s": 441,
"text": "PHP"
},
{
"code": null,
"e": 456,
"s": 445,
"text": "Javascript"
},
{
"code": "// CPP Program to print Fibonacci// series in reverse order#include <bits/stdc++.h>using namespace std; void reverseFibonacci(int n){ int a[n]; // assigning first and second elements a[0] = 0; a[1] = 1; for (int i = 2; i < n; i++) { // storing sum in the // preceding location a[i] = a[i - 2] + a[i - 1]; } for (int i = n - 1; i >= 0; i--) { // printing array in // reverse order cout << a[i] << \" \"; }} // Driver functionint main(){ int n = 5; reverseFibonacci(n); return 0;}",
"e": 1013,
"s": 456,
"text": null
},
{
"code": "// Java Program to print Fibonacci// series in reverse orderimport java.io.*; class GFG { static void reverseFibonacci(int n) { int a[] = new int[n]; // assigning first and second elements a[0] = 0; a[1] = 1; for (int i = 2; i < n; i++) { // storing sum in the // preceding location a[i] = a[i - 2] + a[i - 1]; } for (int i = n - 1; i >= 0; i--) { // printing array in // reverse order System.out.print(a[i] +\" \"); } } // Driver function public static void main(String[] args) { int n = 5; reverseFibonacci(n); }} // This code is contributed by vt_m.",
"e": 1775,
"s": 1013,
"text": null
},
{
"code": "# Python 3 Program to print Fibonacci# series in reverse order def reverseFibonacci(n): a = [0] * n # assigning first and second elements a[0] = 0 a[1] = 1 for i in range(2, n): # storing sum in the # preceding location a[i] = a[i - 2] + a[i - 1] for i in range(n - 1, -1 , -1): # printing array in # reverse order print(a[i],end=\" \") # Driver functionn = 5reverseFibonacci(n)",
"e": 2235,
"s": 1775,
"text": null
},
{
"code": "// C# Program to print Fibonacci// series in reverse orderusing System; class GFG { static void reverseFibonacci(int n) { int []a = new int[n]; // assigning first and second elements a[0] = 0; a[1] = 1; for (int i = 2; i < n; i++) { // storing sum in the // preceding location a[i] = a[i - 2] + a[i - 1]; } for (int i = n - 1; i >= 0; i--) { // printing array in // reverse order Console.Write(a[i] +\" \"); } } // Driver function public static void Main() { int n = 5; reverseFibonacci(n); }} // This code is contributed by vt_m.",
"e": 2975,
"s": 2235,
"text": null
},
{
"code": "<?php// PHP Program to print Fibonacci// series in reverse order function reverseFibonacci($n){ // assigning first and // second elements $a[0] = 0; $a[1] = 1; for ($i = 2; $i < $n; $i++) { // storing sum in the // preceding location $a[$i] = $a[$i - 2] + $a[$i - 1]; } for ($i = $n - 1; $i >= 0; $i--) { // printing array in // reverse order echo($a[$i] . \" \"); }} // Driver COde$n = 5;reverseFibonacci($n); // This code is contributed by Ajit.?>",
"e": 3516,
"s": 2975,
"text": null
},
{
"code": "<script> // JavaScript program to print Fibonacci// series in reverse orderfunction reverseFibonacci(n){ let a = []; // Assigning first and second elements a[0] = 0; a[1] = 1; for(let i = 2; i < n; i++) { // Storing sum in the // preceding location a[i] = a[i - 2] + a[i - 1]; } for(let i = n - 1; i >= 0; i--) { // Printing array in // reverse order document.write(a[i] + \" \"); }} // Driver Codelet n = 5; reverseFibonacci(n); // This code is contributed by avijitmondal1998 </script>",
"e": 4103,
"s": 3516,
"text": null
},
{
"code": null,
"e": 4112,
"s": 4103,
"text": "Output: "
},
{
"code": null,
"e": 4122,
"s": 4112,
"text": "3 2 1 1 0"
},
{
"code": null,
"e": 4144,
"s": 4122,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 4166,
"s": 4144,
"text": "Auxiliary Space: O(n)"
},
{
"code": null,
"e": 4172,
"s": 4166,
"text": "jit_t"
},
{
"code": null,
"e": 4189,
"s": 4172,
"text": "avijitmondal1998"
},
{
"code": null,
"e": 4199,
"s": 4189,
"text": "samim2000"
},
{
"code": null,
"e": 4209,
"s": 4199,
"text": "Fibonacci"
},
{
"code": null,
"e": 4217,
"s": 4209,
"text": "Reverse"
},
{
"code": null,
"e": 4237,
"s": 4217,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 4257,
"s": 4237,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 4267,
"s": 4257,
"text": "Fibonacci"
},
{
"code": null,
"e": 4275,
"s": 4267,
"text": "Reverse"
},
{
"code": null,
"e": 4373,
"s": 4275,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4400,
"s": 4373,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 4438,
"s": 4400,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 4471,
"s": 4438,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 4490,
"s": 4471,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 4525,
"s": 4490,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 4547,
"s": 4525,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 4578,
"s": 4547,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 4646,
"s": 4578,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 4714,
"s": 4646,
"text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)"
}
] |
Range Queries for Frequencies of array elements | 07 Jul, 2022
Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type.
Examples:
Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
left = 2, right = 8, element = 8
left = 2, right = 5, element = 6
Output : 3
1
The element 8 appears 3 times in arr[left-1..right-1]
The element 6 appears 1 time in arr[left-1..right-1]
Naive approach: is to traverse from left to right and update count variable whenever we find the element.
Below is the code of Naive approach:-
C++
Java
Python3
C#
PHP
Javascript
// C++ program to find total count of an element// in a range#include<bits/stdc++.h>using namespace std; // Returns count of element in arr[left-1..right-1]int findFrequency(int arr[], int n, int left, int right, int element){ int count = 0; for (int i=left-1; i<=right; ++i) if (arr[i] == element) ++count; return count;} // Driver Codeint main(){ int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; int n = sizeof(arr) / sizeof(arr[0]); // Print frequency of 2 from position 1 to 6 cout << "Frequency of 2 from 1 to 6 = " << findFrequency(arr, n, 1, 6, 2) << endl; // Print frequency of 8 from position 4 to 9 cout << "Frequency of 8 from 4 to 9 = " << findFrequency(arr, n, 4, 9, 8); return 0;}
// JAVA Code to find total count of an element// in a range class GFG { // Returns count of element in arr[left-1..right-1] public static int findFrequency(int arr[], int n, int left, int right, int element) { int count = 0; for (int i = left - 1; i < right; ++i) if (arr[i] == element) ++count; return count; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; int n = arr.length; // Print frequency of 2 from position 1 to 6 System.out.println("Frequency of 2 from 1 to 6 = " + findFrequency(arr, n, 1, 6, 2)); // Print frequency of 8 from position 4 to 9 System.out.println("Frequency of 8 from 4 to 9 = " + findFrequency(arr, n, 4, 9, 8)); } }// This code is contributed by Arnav Kr. Mandal.
# Python program to find total # count of an element in a range # Returns count of element# in arr[left-1..right-1]def findFrequency(arr, n, left, right, element): count = 0 for i in range(left - 1, right): if (arr[i] == element): count += 1 return count # Driver Codearr = [2, 8, 6, 9, 8, 6, 8, 2, 11]n = len(arr) # Print frequency of 2 from position 1 to 6print("Frequency of 2 from 1 to 6 = ", findFrequency(arr, n, 1, 6, 2)) # Print frequency of 8 from position 4 to 9print("Frequency of 8 from 4 to 9 = ", findFrequency(arr, n, 4, 9, 8)) # This code is contributed by Anant Agarwal.
// C# Code to find total count// of an element in a rangeusing System; class GFG { // Returns count of element // in arr[left-1..right-1] public static int findFrequency(int []arr, int n, int left, int right, int element) { int count = 0; for (int i = left - 1; i < right; ++i) if (arr[i] == element) ++count; return count; } // Driver Code public static void Main() { int []arr = {2, 8, 6, 9, 8, 6, 8, 2, 11}; int n = arr.Length; // Print frequency of 2 // from position 1 to 6 Console.WriteLine("Frequency of 2 from 1 to 6 = " + findFrequency(arr, n, 1, 6, 2)); // Print frequency of 8 // from position 4 to 9 Console.Write("Frequency of 8 from 4 to 9 = " + findFrequency(arr, n, 4, 9, 8)); }} // This code is contributed by Nitin Mittal.
<?php// PHP program to find total count of// an element in a range // Returns count of element in// arr[left-1..right-1]function findFrequency(&$arr, $n, $left, $right, $element){ $count = 0; for ($i = $left - 1; $i <= $right; ++$i) if ($arr[$i] == $element) ++$count; return $count;} // Driver Code$arr = array(2, 8, 6, 9, 8, 6, 8, 2, 11);$n = sizeof($arr); // Print frequency of 2 from position 1 to 6echo "Frequency of 2 from 1 to 6 = ". findFrequency($arr, $n, 1, 6, 2) ."\n"; // Print frequency of 8 from position 4 to 9echo "Frequency of 8 from 4 to 9 = ". findFrequency($arr, $n, 4, 9, 8); // This code is contributed by ita_c?>
<script> // Javascript Code to find total count of an element// in a range // Returns count of element in arr[left-1..right-1] function findFrequency(arr,n,left,right,element) { let count = 0; for (let i = left - 1; i < right; ++i) if (arr[i] == element) ++count; return count; } /* Driver program to test above function */ let arr=[2, 8, 6, 9, 8, 6, 8, 2, 11]; let n = arr.length; // Print frequency of 2 from position 1 to 6 document.write("Frequency of 2 from 1 to 6 = " + findFrequency(arr, n, 1, 6, 2)+"<br>"); // Print frequency of 8 from position 4 to 9 document.write("Frequency of 8 from 4 to 9 = " + findFrequency(arr, n, 4, 9, 8)); // This code is contributed by rag2127 </script>
Frequency of 2 from 1 to 6 = 1
Frequency of 8 from 4 to 9 = 2
Time complexity of this approach is O(right – left + 1) or O(n) Auxiliary space: O(1)
An Efficient approach is to use hashing. In C++, we can use unordered_map
At first, we will store the position in map[] of every distinct element as a vector like that
int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};
map[2] = {1, 8}
map[8] = {2, 5, 7}
map[6] = {3, 6}
ans so on...
As we can see that elements in map[] are already in sorted order (Because we inserted elements from left to right), the answer boils down to find the total count in that hash map[] using binary search like method.
In C++ we can use lower_bound which will returns an iterator pointing to the first element in the range [first, last] which has a value not less than ‘left’. and upper_bound returns an iterator pointing to the first element in the range [first,last) which has a value greater than ‘right’.
After that we just need to subtract the upper_bound() and lower_bound() result to get the final answer. For example, suppose if we want to find the total count of 8 in the range from [1 to 6], then the map[8] of lower_bound() function will return the result 0 (pointing to 2) and upper_bound() will return 2 (pointing to 7), so we need to subtract the both the result like 2 – 0 = 2 .
Below is the code of above approach
C++
Python3
// C++ program to find total count of an element#include<bits/stdc++.h>using namespace std; unordered_map< int, vector<int> > store; // Returns frequency of element in arr[left-1..right-1]int findFrequency(int arr[], int n, int left, int right, int element){ // Find the position of first occurrence of element int a = lower_bound(store[element].begin(), store[element].end(), left) - store[element].begin(); // Find the position of last occurrence of element int b = upper_bound(store[element].begin(), store[element].end(), right) - store[element].begin(); return b-a;} // Driver codeint main(){ int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; int n = sizeof(arr) / sizeof(arr[0]); // Storing the indexes of an element in the map for (int i=0; i<n; ++i) store[arr[i]].push_back(i+1); //starting index from 1 // Print frequency of 2 from position 1 to 6 cout << "Frequency of 2 from 1 to 6 = " << findFrequency(arr, n, 1, 6, 2) <<endl; // Print frequency of 8 from position 4 to 9 cout << "Frequency of 8 from 4 to 9 = " << findFrequency(arr, n, 4, 9, 8); return 0;}
# Python3 program to find total count of an elementfrom collections import defaultdict as dictfrom bisect import bisect_left as lower_boundfrom bisect import bisect_right as upper_bound store = dict(list) # Returns frequency of element# in arr[left-1..right-1]def findFrequency(arr, n, left, right, element): # Find the position of # first occurrence of element a = lower_bound(store[element], left) # Find the position of # last occurrence of element b = upper_bound(store[element], right) return b - a # Driver codearr = [2, 8, 6, 9, 8, 6, 8, 2, 11]n = len(arr) # Storing the indexes of# an element in the mapfor i in range(n): store[arr[i]].append(i + 1) # Print frequency of 2 from position 1 to 6print("Frequency of 2 from 1 to 6 = ", findFrequency(arr, n, 1, 6, 2)) # Print frequency of 8 from position 4 to 9print("Frequency of 8 from 4 to 9 = ", findFrequency(arr, n, 4, 9, 8)) # This code is contributed by Mohit Kumar
Frequency of 2 from 1 to 6 = 1
Frequency of 8 from 4 to 9 = 2
This approach will be beneficial if we have a large number of queries of an arbitrary range asking the total frequency of particular element.Time complexity: O(log N) for single query.
This article is contributed by Shubham Bansal. 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.
nitin mittal
ukasp
mohit kumar 29
rag2127
simmytarika5
hardikkoriintern
array-range-queries
Arrays
Hash
Arrays
Hash
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
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Longest Consecutive Subsequence | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 295,
"s": 54,
"text": "Given an array of n non-negative integers. The task is to find frequency of a particular element in the arbitrary range of array[]. The range is given as positions (not 0 based indexes) in array. There can be multiple queries of given type."
},
{
"code": null,
"e": 306,
"s": 295,
"text": "Examples: "
},
{
"code": null,
"e": 572,
"s": 306,
"text": "Input : arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};\n left = 2, right = 8, element = 8\n left = 2, right = 5, element = 6 \nOutput : 3\n 1\nThe element 8 appears 3 times in arr[left-1..right-1]\nThe element 6 appears 1 time in arr[left-1..right-1]"
},
{
"code": null,
"e": 679,
"s": 572,
"text": "Naive approach: is to traverse from left to right and update count variable whenever we find the element. "
},
{
"code": null,
"e": 718,
"s": 679,
"text": "Below is the code of Naive approach:- "
},
{
"code": null,
"e": 722,
"s": 718,
"text": "C++"
},
{
"code": null,
"e": 727,
"s": 722,
"text": "Java"
},
{
"code": null,
"e": 735,
"s": 727,
"text": "Python3"
},
{
"code": null,
"e": 738,
"s": 735,
"text": "C#"
},
{
"code": null,
"e": 742,
"s": 738,
"text": "PHP"
},
{
"code": null,
"e": 753,
"s": 742,
"text": "Javascript"
},
{
"code": "// C++ program to find total count of an element// in a range#include<bits/stdc++.h>using namespace std; // Returns count of element in arr[left-1..right-1]int findFrequency(int arr[], int n, int left, int right, int element){ int count = 0; for (int i=left-1; i<=right; ++i) if (arr[i] == element) ++count; return count;} // Driver Codeint main(){ int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; int n = sizeof(arr) / sizeof(arr[0]); // Print frequency of 2 from position 1 to 6 cout << \"Frequency of 2 from 1 to 6 = \" << findFrequency(arr, n, 1, 6, 2) << endl; // Print frequency of 8 from position 4 to 9 cout << \"Frequency of 8 from 4 to 9 = \" << findFrequency(arr, n, 4, 9, 8); return 0;}",
"e": 1532,
"s": 753,
"text": null
},
{
"code": "// JAVA Code to find total count of an element// in a range class GFG { // Returns count of element in arr[left-1..right-1] public static int findFrequency(int arr[], int n, int left, int right, int element) { int count = 0; for (int i = left - 1; i < right; ++i) if (arr[i] == element) ++count; return count; } /* Driver program to test above function */ public static void main(String[] args) { int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; int n = arr.length; // Print frequency of 2 from position 1 to 6 System.out.println(\"Frequency of 2 from 1 to 6 = \" + findFrequency(arr, n, 1, 6, 2)); // Print frequency of 8 from position 4 to 9 System.out.println(\"Frequency of 8 from 4 to 9 = \" + findFrequency(arr, n, 4, 9, 8)); } }// This code is contributed by Arnav Kr. Mandal.",
"e": 2542,
"s": 1532,
"text": null
},
{
"code": "# Python program to find total # count of an element in a range # Returns count of element# in arr[left-1..right-1]def findFrequency(arr, n, left, right, element): count = 0 for i in range(left - 1, right): if (arr[i] == element): count += 1 return count # Driver Codearr = [2, 8, 6, 9, 8, 6, 8, 2, 11]n = len(arr) # Print frequency of 2 from position 1 to 6print(\"Frequency of 2 from 1 to 6 = \", findFrequency(arr, n, 1, 6, 2)) # Print frequency of 8 from position 4 to 9print(\"Frequency of 8 from 4 to 9 = \", findFrequency(arr, n, 4, 9, 8)) # This code is contributed by Anant Agarwal.",
"e": 3186,
"s": 2542,
"text": null
},
{
"code": "// C# Code to find total count// of an element in a rangeusing System; class GFG { // Returns count of element // in arr[left-1..right-1] public static int findFrequency(int []arr, int n, int left, int right, int element) { int count = 0; for (int i = left - 1; i < right; ++i) if (arr[i] == element) ++count; return count; } // Driver Code public static void Main() { int []arr = {2, 8, 6, 9, 8, 6, 8, 2, 11}; int n = arr.Length; // Print frequency of 2 // from position 1 to 6 Console.WriteLine(\"Frequency of 2 from 1 to 6 = \" + findFrequency(arr, n, 1, 6, 2)); // Print frequency of 8 // from position 4 to 9 Console.Write(\"Frequency of 8 from 4 to 9 = \" + findFrequency(arr, n, 4, 9, 8)); }} // This code is contributed by Nitin Mittal.",
"e": 4205,
"s": 3186,
"text": null
},
{
"code": "<?php// PHP program to find total count of// an element in a range // Returns count of element in// arr[left-1..right-1]function findFrequency(&$arr, $n, $left, $right, $element){ $count = 0; for ($i = $left - 1; $i <= $right; ++$i) if ($arr[$i] == $element) ++$count; return $count;} // Driver Code$arr = array(2, 8, 6, 9, 8, 6, 8, 2, 11);$n = sizeof($arr); // Print frequency of 2 from position 1 to 6echo \"Frequency of 2 from 1 to 6 = \". findFrequency($arr, $n, 1, 6, 2) .\"\\n\"; // Print frequency of 8 from position 4 to 9echo \"Frequency of 8 from 4 to 9 = \". findFrequency($arr, $n, 4, 9, 8); // This code is contributed by ita_c?>",
"e": 4901,
"s": 4205,
"text": null
},
{
"code": "<script> // Javascript Code to find total count of an element// in a range // Returns count of element in arr[left-1..right-1] function findFrequency(arr,n,left,right,element) { let count = 0; for (let i = left - 1; i < right; ++i) if (arr[i] == element) ++count; return count; } /* Driver program to test above function */ let arr=[2, 8, 6, 9, 8, 6, 8, 2, 11]; let n = arr.length; // Print frequency of 2 from position 1 to 6 document.write(\"Frequency of 2 from 1 to 6 = \" + findFrequency(arr, n, 1, 6, 2)+\"<br>\"); // Print frequency of 8 from position 4 to 9 document.write(\"Frequency of 8 from 4 to 9 = \" + findFrequency(arr, n, 4, 9, 8)); // This code is contributed by rag2127 </script>",
"e": 5729,
"s": 4901,
"text": null
},
{
"code": null,
"e": 5791,
"s": 5729,
"text": "Frequency of 2 from 1 to 6 = 1\nFrequency of 8 from 4 to 9 = 2"
},
{
"code": null,
"e": 5877,
"s": 5791,
"text": "Time complexity of this approach is O(right – left + 1) or O(n) Auxiliary space: O(1)"
},
{
"code": null,
"e": 5951,
"s": 5877,
"text": "An Efficient approach is to use hashing. In C++, we can use unordered_map"
},
{
"code": null,
"e": 6046,
"s": 5951,
"text": "At first, we will store the position in map[] of every distinct element as a vector like that "
},
{
"code": null,
"e": 6163,
"s": 6046,
"text": " int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11};\n map[2] = {1, 8}\n map[8] = {2, 5, 7}\n map[6] = {3, 6} \n ans so on..."
},
{
"code": null,
"e": 6379,
"s": 6163,
"text": "As we can see that elements in map[] are already in sorted order (Because we inserted elements from left to right), the answer boils down to find the total count in that hash map[] using binary search like method. "
},
{
"code": null,
"e": 6671,
"s": 6379,
"text": "In C++ we can use lower_bound which will returns an iterator pointing to the first element in the range [first, last] which has a value not less than ‘left’. and upper_bound returns an iterator pointing to the first element in the range [first,last) which has a value greater than ‘right’. "
},
{
"code": null,
"e": 7058,
"s": 6671,
"text": "After that we just need to subtract the upper_bound() and lower_bound() result to get the final answer. For example, suppose if we want to find the total count of 8 in the range from [1 to 6], then the map[8] of lower_bound() function will return the result 0 (pointing to 2) and upper_bound() will return 2 (pointing to 7), so we need to subtract the both the result like 2 – 0 = 2 . "
},
{
"code": null,
"e": 7095,
"s": 7058,
"text": "Below is the code of above approach "
},
{
"code": null,
"e": 7099,
"s": 7095,
"text": "C++"
},
{
"code": null,
"e": 7107,
"s": 7099,
"text": "Python3"
},
{
"code": "// C++ program to find total count of an element#include<bits/stdc++.h>using namespace std; unordered_map< int, vector<int> > store; // Returns frequency of element in arr[left-1..right-1]int findFrequency(int arr[], int n, int left, int right, int element){ // Find the position of first occurrence of element int a = lower_bound(store[element].begin(), store[element].end(), left) - store[element].begin(); // Find the position of last occurrence of element int b = upper_bound(store[element].begin(), store[element].end(), right) - store[element].begin(); return b-a;} // Driver codeint main(){ int arr[] = {2, 8, 6, 9, 8, 6, 8, 2, 11}; int n = sizeof(arr) / sizeof(arr[0]); // Storing the indexes of an element in the map for (int i=0; i<n; ++i) store[arr[i]].push_back(i+1); //starting index from 1 // Print frequency of 2 from position 1 to 6 cout << \"Frequency of 2 from 1 to 6 = \" << findFrequency(arr, n, 1, 6, 2) <<endl; // Print frequency of 8 from position 4 to 9 cout << \"Frequency of 8 from 4 to 9 = \" << findFrequency(arr, n, 4, 9, 8); return 0;}",
"e": 8375,
"s": 7107,
"text": null
},
{
"code": "# Python3 program to find total count of an elementfrom collections import defaultdict as dictfrom bisect import bisect_left as lower_boundfrom bisect import bisect_right as upper_bound store = dict(list) # Returns frequency of element# in arr[left-1..right-1]def findFrequency(arr, n, left, right, element): # Find the position of # first occurrence of element a = lower_bound(store[element], left) # Find the position of # last occurrence of element b = upper_bound(store[element], right) return b - a # Driver codearr = [2, 8, 6, 9, 8, 6, 8, 2, 11]n = len(arr) # Storing the indexes of# an element in the mapfor i in range(n): store[arr[i]].append(i + 1) # Print frequency of 2 from position 1 to 6print(\"Frequency of 2 from 1 to 6 = \", findFrequency(arr, n, 1, 6, 2)) # Print frequency of 8 from position 4 to 9print(\"Frequency of 8 from 4 to 9 = \", findFrequency(arr, n, 4, 9, 8)) # This code is contributed by Mohit Kumar",
"e": 9346,
"s": 8375,
"text": null
},
{
"code": null,
"e": 9408,
"s": 9346,
"text": "Frequency of 2 from 1 to 6 = 1\nFrequency of 8 from 4 to 9 = 2"
},
{
"code": null,
"e": 9593,
"s": 9408,
"text": "This approach will be beneficial if we have a large number of queries of an arbitrary range asking the total frequency of particular element.Time complexity: O(log N) for single query."
},
{
"code": null,
"e": 9892,
"s": 9593,
"text": "This article is contributed by Shubham Bansal. 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. "
},
{
"code": null,
"e": 9905,
"s": 9892,
"text": "nitin mittal"
},
{
"code": null,
"e": 9911,
"s": 9905,
"text": "ukasp"
},
{
"code": null,
"e": 9926,
"s": 9911,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 9934,
"s": 9926,
"text": "rag2127"
},
{
"code": null,
"e": 9947,
"s": 9934,
"text": "simmytarika5"
},
{
"code": null,
"e": 9964,
"s": 9947,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 9984,
"s": 9964,
"text": "array-range-queries"
},
{
"code": null,
"e": 9991,
"s": 9984,
"text": "Arrays"
},
{
"code": null,
"e": 9996,
"s": 9991,
"text": "Hash"
},
{
"code": null,
"e": 10003,
"s": 9996,
"text": "Arrays"
},
{
"code": null,
"e": 10008,
"s": 10003,
"text": "Hash"
},
{
"code": null,
"e": 10106,
"s": 10008,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10121,
"s": 10106,
"text": "Arrays in Java"
},
{
"code": null,
"e": 10167,
"s": 10121,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 10235,
"s": 10167,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 10279,
"s": 10235,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 10311,
"s": 10279,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 10349,
"s": 10311,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 10385,
"s": 10349,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 10416,
"s": 10385,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 10443,
"s": 10416,
"text": "Count pairs with given sum"
}
] |
Zero Knowledge Proof | 11 May, 2022
Zero Knowledge Proof (ZKP) is an encryption scheme originally proposed by MIT researchers Shafi Goldwasser, Silvio Micali and Charles Rackoff in the 1980s.
Zero-knowledge protocols are probabilistic assessments, which means they don’t prove something with as much certainty as simply revealing the entire information would. They provide unlinkable information that can together show the validity of the assertion is probable.
Currently, a website takes the user password as an input and then compares its hash to the stored hash. Similarly a bank requires your credit score to provide you the loan leaving your privacy and information leak risk at the mercy of the host servers. If ZKP can be utilized, the client’s password is unknown the to verifier and the login can still be authenticated. Before ZKP, we always questioned the legitimacy of the prover or the soundness of the proof system, but ZKP questions the morality of the verifier. What if the verifier tries to leak the information?
Example-1: A Colour-blind friend and Two balls : There are two friends Sachin and Sanchita, out of whom Sanchita is colour blind. Sachin has two balls and he needs to prove that both the balls our of different colour. Sanchita switches the balls randomly behind her back and shows it to Sachin who has to tell if the balls are switched or not. If the balls are of the same colour and Sachin had given false information, the probability of him answering correctly is 50%. When the activity is repeated several times, the probability of Sachin giving the correct answer with the false information is significantly low. Here Sachin is the “prover” and Sanchita is the “verifier”. Colour is the absolute information or the algorithm to be executed, and it is proved of its soundness without revealing the information that is the colour to the verifier.
Example-2: Finding Waldo : Finding Waldo is a game where you have to find a person called Waldo from a snapshot of a huge crowd taken from above. Sachin has an algorithm to find Waldo but he doesn’t want to reveal it to Sanchita. Sanchita wants to buy the algorithm but would need to check if the algorithm is working. Sachin cuts a small hole on a cardboard and places over Waldo. Sachin is the “prover” and Sanchita is the “verifier”. The algorithm is proved with zero knowledge about it.
Properties of Zero Knowledge Proof :
Zero-Knowledge – If the statement is true, the verifier will not know that the statement or was. Here statement can be an absolute value or an algorithm.
Completeness – If the statement is true then an honest verifier can be convinced eventually.
Soundness – If the prover is dishonest, they can’t convince the verifier of the soundness of the proof.
Types of Zero Knowledge Proof :
Interactive Zero Knowledge Proof – It requires the verifier to constantly ask a series of questions about the “knowledge” the prover possess. The above example of finding Waldo is interactive since the “prover” did a series of actions to prove the about the soundness of the knowledge to the verifier. Non-Interactive Zero Knowledge Proof – For “interactive” solution to work, both the verifier and the prover needed to be online at the same time making it difficult to scale up on the real world application. Non-interactive Zero-Knowledge Proof do not require an interactive process, avoiding the possibility of collusion. It requires picking a hash function to randomly pick the challenge by the verifier. In 1986, Fiat and Shamir invented the Fiat-Shamir heuristic and successfully changed the interactive zero-knowledge proof to non-interactive zero knowledge proof.
Interactive Zero Knowledge Proof – It requires the verifier to constantly ask a series of questions about the “knowledge” the prover possess. The above example of finding Waldo is interactive since the “prover” did a series of actions to prove the about the soundness of the knowledge to the verifier.
Non-Interactive Zero Knowledge Proof – For “interactive” solution to work, both the verifier and the prover needed to be online at the same time making it difficult to scale up on the real world application. Non-interactive Zero-Knowledge Proof do not require an interactive process, avoiding the possibility of collusion. It requires picking a hash function to randomly pick the challenge by the verifier. In 1986, Fiat and Shamir invented the Fiat-Shamir heuristic and successfully changed the interactive zero-knowledge proof to non-interactive zero knowledge proof.
simranarora5sos
Blockchain
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Become a Blockchain Developer?
Solidity - Mappings
Storage vs Memory in Solidity
How to connect ReactJS with MetaMask ?
Top 7 Interesting Blockchain Project Ideas for Beginners
Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network
Solidity - Enums and Structs
Solidity - Constructors
Solidity - Fall Back Function
Introduction to Solidity | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 May, 2022"
},
{
"code": null,
"e": 209,
"s": 52,
"text": "Zero Knowledge Proof (ZKP) is an encryption scheme originally proposed by MIT researchers Shafi Goldwasser, Silvio Micali and Charles Rackoff in the 1980s. "
},
{
"code": null,
"e": 480,
"s": 209,
"text": "Zero-knowledge protocols are probabilistic assessments, which means they don’t prove something with as much certainty as simply revealing the entire information would. They provide unlinkable information that can together show the validity of the assertion is probable. "
},
{
"code": null,
"e": 1049,
"s": 480,
"text": "Currently, a website takes the user password as an input and then compares its hash to the stored hash. Similarly a bank requires your credit score to provide you the loan leaving your privacy and information leak risk at the mercy of the host servers. If ZKP can be utilized, the client’s password is unknown the to verifier and the login can still be authenticated. Before ZKP, we always questioned the legitimacy of the prover or the soundness of the proof system, but ZKP questions the morality of the verifier. What if the verifier tries to leak the information? "
},
{
"code": null,
"e": 1901,
"s": 1051,
"text": "Example-1: A Colour-blind friend and Two balls : There are two friends Sachin and Sanchita, out of whom Sanchita is colour blind. Sachin has two balls and he needs to prove that both the balls our of different colour. Sanchita switches the balls randomly behind her back and shows it to Sachin who has to tell if the balls are switched or not. If the balls are of the same colour and Sachin had given false information, the probability of him answering correctly is 50%. When the activity is repeated several times, the probability of Sachin giving the correct answer with the false information is significantly low. Here Sachin is the “prover” and Sanchita is the “verifier”. Colour is the absolute information or the algorithm to be executed, and it is proved of its soundness without revealing the information that is the colour to the verifier. "
},
{
"code": null,
"e": 2393,
"s": 1901,
"text": "Example-2: Finding Waldo : Finding Waldo is a game where you have to find a person called Waldo from a snapshot of a huge crowd taken from above. Sachin has an algorithm to find Waldo but he doesn’t want to reveal it to Sanchita. Sanchita wants to buy the algorithm but would need to check if the algorithm is working. Sachin cuts a small hole on a cardboard and places over Waldo. Sachin is the “prover” and Sanchita is the “verifier”. The algorithm is proved with zero knowledge about it. "
},
{
"code": null,
"e": 2432,
"s": 2393,
"text": "Properties of Zero Knowledge Proof : "
},
{
"code": null,
"e": 2588,
"s": 2432,
"text": "Zero-Knowledge – If the statement is true, the verifier will not know that the statement or was. Here statement can be an absolute value or an algorithm. "
},
{
"code": null,
"e": 2683,
"s": 2588,
"text": "Completeness – If the statement is true then an honest verifier can be convinced eventually. "
},
{
"code": null,
"e": 2789,
"s": 2683,
"text": "Soundness – If the prover is dishonest, they can’t convince the verifier of the soundness of the proof. "
},
{
"code": null,
"e": 2823,
"s": 2789,
"text": "Types of Zero Knowledge Proof : "
},
{
"code": null,
"e": 3698,
"s": 2823,
"text": "Interactive Zero Knowledge Proof – It requires the verifier to constantly ask a series of questions about the “knowledge” the prover possess. The above example of finding Waldo is interactive since the “prover” did a series of actions to prove the about the soundness of the knowledge to the verifier. Non-Interactive Zero Knowledge Proof – For “interactive” solution to work, both the verifier and the prover needed to be online at the same time making it difficult to scale up on the real world application. Non-interactive Zero-Knowledge Proof do not require an interactive process, avoiding the possibility of collusion. It requires picking a hash function to randomly pick the challenge by the verifier. In 1986, Fiat and Shamir invented the Fiat-Shamir heuristic and successfully changed the interactive zero-knowledge proof to non-interactive zero knowledge proof. "
},
{
"code": null,
"e": 4002,
"s": 3698,
"text": "Interactive Zero Knowledge Proof – It requires the verifier to constantly ask a series of questions about the “knowledge” the prover possess. The above example of finding Waldo is interactive since the “prover” did a series of actions to prove the about the soundness of the knowledge to the verifier. "
},
{
"code": null,
"e": 4576,
"s": 4004,
"text": "Non-Interactive Zero Knowledge Proof – For “interactive” solution to work, both the verifier and the prover needed to be online at the same time making it difficult to scale up on the real world application. Non-interactive Zero-Knowledge Proof do not require an interactive process, avoiding the possibility of collusion. It requires picking a hash function to randomly pick the challenge by the verifier. In 1986, Fiat and Shamir invented the Fiat-Shamir heuristic and successfully changed the interactive zero-knowledge proof to non-interactive zero knowledge proof. "
},
{
"code": null,
"e": 4594,
"s": 4578,
"text": "simranarora5sos"
},
{
"code": null,
"e": 4605,
"s": 4594,
"text": "Blockchain"
},
{
"code": null,
"e": 4703,
"s": 4605,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4741,
"s": 4703,
"text": "How to Become a Blockchain Developer?"
},
{
"code": null,
"e": 4761,
"s": 4741,
"text": "Solidity - Mappings"
},
{
"code": null,
"e": 4791,
"s": 4761,
"text": "Storage vs Memory in Solidity"
},
{
"code": null,
"e": 4830,
"s": 4791,
"text": "How to connect ReactJS with MetaMask ?"
},
{
"code": null,
"e": 4887,
"s": 4830,
"text": "Top 7 Interesting Blockchain Project Ideas for Beginners"
},
{
"code": null,
"e": 4959,
"s": 4887,
"text": "Ethereum Blockchain - Getting Free Test Ethers For Rinkeby Test Network"
},
{
"code": null,
"e": 4988,
"s": 4959,
"text": "Solidity - Enums and Structs"
},
{
"code": null,
"e": 5012,
"s": 4988,
"text": "Solidity - Constructors"
},
{
"code": null,
"e": 5042,
"s": 5012,
"text": "Solidity - Fall Back Function"
}
] |
How to find maximum between 2 numbers using C#? | Firstly, declare and initialize two numbers.
int num1 = 50;
int num2 = 90;
With that, use if-else to find the maximum number.
if (num1 > num2) {
maxNum = num1;
} else {
maxNum = num2;
}
Above, we have set the maximum value to the variable maxNum and printed it later on.
The following is the complete example to find maximum between 2 numbers in C#.
Live Demo
using System;
namespace Demo {
class Program {
static void Main(string[] args) {
int num1 = 50;
int num2 = 90;
int maxNum;
Console.WriteLine("Number 1: "+num1);
Console.WriteLine("Number 2: "+num2);
if (num1 > num2) {
maxNum = num1;
} else {
maxNum = num2;
}
Console.WriteLine("Maximum number is: "+maxNum);
Console.ReadKey() ;
}
}
}
Number 1: 50
Number 2: 90
Maximum number is: 90 | [
{
"code": null,
"e": 1232,
"s": 1187,
"text": "Firstly, declare and initialize two numbers."
},
{
"code": null,
"e": 1262,
"s": 1232,
"text": "int num1 = 50;\nint num2 = 90;"
},
{
"code": null,
"e": 1313,
"s": 1262,
"text": "With that, use if-else to find the maximum number."
},
{
"code": null,
"e": 1379,
"s": 1313,
"text": "if (num1 > num2) {\n maxNum = num1;\n} else {\n maxNum = num2;\n}"
},
{
"code": null,
"e": 1464,
"s": 1379,
"text": "Above, we have set the maximum value to the variable maxNum and printed it later on."
},
{
"code": null,
"e": 1543,
"s": 1464,
"text": "The following is the complete example to find maximum between 2 numbers in C#."
},
{
"code": null,
"e": 1554,
"s": 1543,
"text": " Live Demo"
},
{
"code": null,
"e": 2020,
"s": 1554,
"text": "using System;\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n int num1 = 50;\n int num2 = 90;\n int maxNum;\n Console.WriteLine(\"Number 1: \"+num1);\n Console.WriteLine(\"Number 2: \"+num2);\n if (num1 > num2) {\n maxNum = num1;\n } else {\n maxNum = num2;\n }\n Console.WriteLine(\"Maximum number is: \"+maxNum);\n Console.ReadKey() ;\n }\n }\n}"
},
{
"code": null,
"e": 2068,
"s": 2020,
"text": "Number 1: 50\nNumber 2: 90\nMaximum number is: 90"
}
] |
Get minimum values in rows or columns with their index position in Pandas-Dataframe | 02 Jul, 2020
Let’s discuss how to find minimum values in rows & columns of a Dataframe and also their index position.
a) Find the minimum value among rows and columns :
Dataframe.min() : This function returns the minimum of the values in the given object. If the input is a series, the method will return a scalar which will be the minimum of the values in the series. If the input is a dataframe, then the method will return a series with a minimum of values over the specified axis in the dataframe. By default, the axis is the index axis.
1) Get minimum values of every column :Use min() function to find the minimum value over the index axis.
Code :
# import pandas libraryimport pandas as pd # list of Tuplesdata = [ (20, 16, 23), (30, None, 11), (40, 34, 11), (50, 35, None), (60, 40, 13) ] # creating a DataFrame objectdf = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e'], columns = ['x', 'y', 'z']) # getting a series object containing # minimum value from each column# of given dataframeminvalue_series = df.min() minvalue_series
Output:
2) Get minimum values of every row :Use min() function on a dataframe with ‘axis = 1’ attribute to find the minimum value over the row axis.
Code :
# import pandas libraryimport pandas as pd # list of Tuplesdata = [ (20, 16, 23), (30, None, 11), (40, 34, 11), (50, 35, None), (60, 40, 13) ] # creating a DataFrame objectdf = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e'], columns = ['x', 'y', 'z']) # getting a series object containing # minimum value from each row# of given dataframeminvalue_series = df.min(axis = 1) minvalue_series
Output:
3) Get minimum values of every column without skipping None Value :Use min() function on a dataframe which has Na value with ‘skipna = False’ attribute to find the minimum value over the column axis.
Code :
# import pandas libraryimport pandas as pd # list of Tuplesdata = [ (20, 16, 23), (30, None, 11), (40, 34, 11), (50, 35, None), (60, 40, 13) ] # creating a DataFrame objectdf = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e'], columns = ['x', 'y', 'z']) # getting a series object containing # minimum value from each column# of given dataframe without# skipping None valueminvalue_series = df.min(skipna = False) minvalue_series
Output:
4) Get minimum value of a single column :Use min() function on a series to find the minimum value in the series.
Code :
# import pandas libraryimport pandas as pd # list of Tuplesdata = [ (20, 16, 23), (30, None, 11), (40, 34, 11), (50, 35, None), (60, 40, 13) ] # creating a DataFrame objectdf = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e'], columns = ['x', 'y', 'z']) # getting a minimum value# from column 'x'minvalue = df['x'].min() minvalue
Output:
20
b) Get row index label or position of minimum values among rows and columns :
Dataframe.idxmin() : This function returns index of first occurrence of minimum over requested axis. While finding the index of the minimum value across any index, all NA/null values are excluded.
1) Get row index label of minimum value in every column :Use idxmin() function to find the index/label of the minimum value along the index axis.
Code :
# import pandas libraryimport pandas as pd # list of Tuplesdata = [ (20, 16, 23), (30, None, 11), (40, 34, 11), (50, 35, None), (60, 40, 13) ] # creating a DataFrame objectdf = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e'], columns = ['x', 'y', 'z']) # get the index position\label of# minimum values in every columnminvalueIndexLabel = df.idxmin() minvalueIndexLabel
Output
2) Get Column names of minimum value in every row :Use idxmin() function with ‘axis = 1’ attribute to find the index/label of the minimum value along the column axis.
Code :
# import pandas libraryimport pandas as pd # list of Tuplesdata = [ (20, 16, 23), (30, None, 11), (40, 34, 11), (50, 35, None), (60, 40, 13) ] # creating a DataFrame objectdf = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e'], columns = ['x', 'y', 'z']) # get the index position\label of# minimum values in every rowminvalueIndexLabel = df.idxmin(axis = 1) minvalueIndexLabel
Output
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n02 Jul, 2020"
},
{
"code": null,
"e": 159,
"s": 54,
"text": "Let’s discuss how to find minimum values in rows & columns of a Dataframe and also their index position."
},
{
"code": null,
"e": 210,
"s": 159,
"text": "a) Find the minimum value among rows and columns :"
},
{
"code": null,
"e": 583,
"s": 210,
"text": "Dataframe.min() : This function returns the minimum of the values in the given object. If the input is a series, the method will return a scalar which will be the minimum of the values in the series. If the input is a dataframe, then the method will return a series with a minimum of values over the specified axis in the dataframe. By default, the axis is the index axis."
},
{
"code": null,
"e": 688,
"s": 583,
"text": "1) Get minimum values of every column :Use min() function to find the minimum value over the index axis."
},
{
"code": null,
"e": 695,
"s": 688,
"text": "Code :"
},
{
"code": "# import pandas libraryimport pandas as pd # list of Tuplesdata = [ (20, 16, 23), (30, None, 11), (40, 34, 11), (50, 35, None), (60, 40, 13) ] # creating a DataFrame objectdf = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e'], columns = ['x', 'y', 'z']) # getting a series object containing # minimum value from each column# of given dataframeminvalue_series = df.min() minvalue_series",
"e": 1161,
"s": 695,
"text": null
},
{
"code": null,
"e": 1169,
"s": 1161,
"text": "Output:"
},
{
"code": null,
"e": 1310,
"s": 1169,
"text": "2) Get minimum values of every row :Use min() function on a dataframe with ‘axis = 1’ attribute to find the minimum value over the row axis."
},
{
"code": null,
"e": 1317,
"s": 1310,
"text": "Code :"
},
{
"code": "# import pandas libraryimport pandas as pd # list of Tuplesdata = [ (20, 16, 23), (30, None, 11), (40, 34, 11), (50, 35, None), (60, 40, 13) ] # creating a DataFrame objectdf = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e'], columns = ['x', 'y', 'z']) # getting a series object containing # minimum value from each row# of given dataframeminvalue_series = df.min(axis = 1) minvalue_series",
"e": 1788,
"s": 1317,
"text": null
},
{
"code": null,
"e": 1796,
"s": 1788,
"text": "Output:"
},
{
"code": null,
"e": 1996,
"s": 1796,
"text": "3) Get minimum values of every column without skipping None Value :Use min() function on a dataframe which has Na value with ‘skipna = False’ attribute to find the minimum value over the column axis."
},
{
"code": null,
"e": 2003,
"s": 1996,
"text": "Code :"
},
{
"code": "# import pandas libraryimport pandas as pd # list of Tuplesdata = [ (20, 16, 23), (30, None, 11), (40, 34, 11), (50, 35, None), (60, 40, 13) ] # creating a DataFrame objectdf = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e'], columns = ['x', 'y', 'z']) # getting a series object containing # minimum value from each column# of given dataframe without# skipping None valueminvalue_series = df.min(skipna = False) minvalue_series",
"e": 2512,
"s": 2003,
"text": null
},
{
"code": null,
"e": 2520,
"s": 2512,
"text": "Output:"
},
{
"code": null,
"e": 2633,
"s": 2520,
"text": "4) Get minimum value of a single column :Use min() function on a series to find the minimum value in the series."
},
{
"code": null,
"e": 2640,
"s": 2633,
"text": "Code :"
},
{
"code": "# import pandas libraryimport pandas as pd # list of Tuplesdata = [ (20, 16, 23), (30, None, 11), (40, 34, 11), (50, 35, None), (60, 40, 13) ] # creating a DataFrame objectdf = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e'], columns = ['x', 'y', 'z']) # getting a minimum value# from column 'x'minvalue = df['x'].min() minvalue",
"e": 3050,
"s": 2640,
"text": null
},
{
"code": null,
"e": 3058,
"s": 3050,
"text": "Output:"
},
{
"code": null,
"e": 3061,
"s": 3058,
"text": "20"
},
{
"code": null,
"e": 3139,
"s": 3061,
"text": "b) Get row index label or position of minimum values among rows and columns :"
},
{
"code": null,
"e": 3336,
"s": 3139,
"text": "Dataframe.idxmin() : This function returns index of first occurrence of minimum over requested axis. While finding the index of the minimum value across any index, all NA/null values are excluded."
},
{
"code": null,
"e": 3482,
"s": 3336,
"text": "1) Get row index label of minimum value in every column :Use idxmin() function to find the index/label of the minimum value along the index axis."
},
{
"code": null,
"e": 3489,
"s": 3482,
"text": "Code :"
},
{
"code": "# import pandas libraryimport pandas as pd # list of Tuplesdata = [ (20, 16, 23), (30, None, 11), (40, 34, 11), (50, 35, None), (60, 40, 13) ] # creating a DataFrame objectdf = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e'], columns = ['x', 'y', 'z']) # get the index position\\label of# minimum values in every columnminvalueIndexLabel = df.idxmin() minvalueIndexLabel",
"e": 3940,
"s": 3489,
"text": null
},
{
"code": null,
"e": 3947,
"s": 3940,
"text": "Output"
},
{
"code": null,
"e": 4114,
"s": 3947,
"text": "2) Get Column names of minimum value in every row :Use idxmin() function with ‘axis = 1’ attribute to find the index/label of the minimum value along the column axis."
},
{
"code": null,
"e": 4121,
"s": 4114,
"text": "Code :"
},
{
"code": "# import pandas libraryimport pandas as pd # list of Tuplesdata = [ (20, 16, 23), (30, None, 11), (40, 34, 11), (50, 35, None), (60, 40, 13) ] # creating a DataFrame objectdf = pd.DataFrame(data, index = ['a', 'b', 'c', 'd', 'e'], columns = ['x', 'y', 'z']) # get the index position\\label of# minimum values in every rowminvalueIndexLabel = df.idxmin(axis = 1) minvalueIndexLabel",
"e": 4577,
"s": 4121,
"text": null
},
{
"code": null,
"e": 4584,
"s": 4577,
"text": "Output"
},
{
"code": null,
"e": 4608,
"s": 4584,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 4622,
"s": 4608,
"text": "Python-pandas"
},
{
"code": null,
"e": 4629,
"s": 4622,
"text": "Python"
}
] |
Elements of Network protocol | 24 Aug, 2020
Protocol :Set of rules that govern data communication.
Network communication protocol requires following elements :
Message encoding :A source message from sender is encoded into signals or waves then transmitted through a medium wired / wireless then received and decoded and message is passed to destination. Encoding is the process of transforming set of Unicode characters into a sequence of bytes.Message Source –> Encoder –> Transmitter –> Transmitter Medium –>
Receiver –>Decoder –> Message destinationMessage formatting and encapsulation :There is an agreed format by sender and receiver. It encapsulates information to identify sender and receiver rightly.A message format will depend on the type of message and the medium through which the message is delivered.Message encapsulation is a process that is used to place one message inside another message for transfer from the source to the destination.Message size :Here long messages must break into small pieces to travel across a network or The process of breaking up a long message into individual pieces before being sent over the network.Example – In mobile phone SMS limits message size to 160 normal alphabet characters. For non-alphabet character, It needs 16 bit of data to represent them limiting size to 70 characters only.Message timing :It manages flow control. Acknowledgments response time out. This requires certain timing control information. It checks for any delays in data passing. It includes rules like Access method, flow control, response timeout.Message delivery options :There are different delivery options like Unicast, Multicast, Broadcast.Sending information to a single person is referred to as a one-to-one delivery and is called unicast which implies that there is only one destination (single destination).To communicate information to more than one person (Group of people at the same time) is referred to as one-to-many and is called multicast which implies that one sender to multiple destinations/recipients for the same message.Sometimes information is to be communicated to every person in the same area. This is referred to as one-to-all and is called broadcast which implies that one sender sends a message to all connected recipients.
Message encoding :A source message from sender is encoded into signals or waves then transmitted through a medium wired / wireless then received and decoded and message is passed to destination. Encoding is the process of transforming set of Unicode characters into a sequence of bytes.Message Source –> Encoder –> Transmitter –> Transmitter Medium –>
Receiver –>Decoder –> Message destination
Message Source –> Encoder –> Transmitter –> Transmitter Medium –>
Receiver –>Decoder –> Message destination
Message formatting and encapsulation :There is an agreed format by sender and receiver. It encapsulates information to identify sender and receiver rightly.A message format will depend on the type of message and the medium through which the message is delivered.Message encapsulation is a process that is used to place one message inside another message for transfer from the source to the destination.
A message format will depend on the type of message and the medium through which the message is delivered.Message encapsulation is a process that is used to place one message inside another message for transfer from the source to the destination.
Message size :Here long messages must break into small pieces to travel across a network or The process of breaking up a long message into individual pieces before being sent over the network.Example – In mobile phone SMS limits message size to 160 normal alphabet characters. For non-alphabet character, It needs 16 bit of data to represent them limiting size to 70 characters only.
Example – In mobile phone SMS limits message size to 160 normal alphabet characters. For non-alphabet character, It needs 16 bit of data to represent them limiting size to 70 characters only.
Message timing :It manages flow control. Acknowledgments response time out. This requires certain timing control information. It checks for any delays in data passing. It includes rules like Access method, flow control, response timeout.
Message delivery options :There are different delivery options like Unicast, Multicast, Broadcast.Sending information to a single person is referred to as a one-to-one delivery and is called unicast which implies that there is only one destination (single destination).To communicate information to more than one person (Group of people at the same time) is referred to as one-to-many and is called multicast which implies that one sender to multiple destinations/recipients for the same message.Sometimes information is to be communicated to every person in the same area. This is referred to as one-to-all and is called broadcast which implies that one sender sends a message to all connected recipients.
Sending information to a single person is referred to as a one-to-one delivery and is called unicast which implies that there is only one destination (single destination).
To communicate information to more than one person (Group of people at the same time) is referred to as one-to-many and is called multicast which implies that one sender to multiple destinations/recipients for the same message.
Sometimes information is to be communicated to every person in the same area. This is referred to as one-to-all and is called broadcast which implies that one sender sends a message to all connected recipients.
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Secure Socket Layer (SSL)
GSM in Wireless Communication
Wireless Application Protocol
Mobile Internet Protocol (or Mobile IP)
Introduction of Mobile Ad hoc Network (MANET)
Advanced Encryption Standard (AES)
Cryptography and its Types
Bluetooth
Intrusion Detection System (IDS)
Dynamic Host Configuration Protocol (DHCP) | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n24 Aug, 2020"
},
{
"code": null,
"e": 108,
"s": 53,
"text": "Protocol :Set of rules that govern data communication."
},
{
"code": null,
"e": 169,
"s": 108,
"text": "Network communication protocol requires following elements :"
},
{
"code": null,
"e": 2293,
"s": 169,
"text": "Message encoding :A source message from sender is encoded into signals or waves then transmitted through a medium wired / wireless then received and decoded and message is passed to destination. Encoding is the process of transforming set of Unicode characters into a sequence of bytes.Message Source –> Encoder –> Transmitter –> Transmitter Medium –>\nReceiver –>Decoder –> Message destinationMessage formatting and encapsulation :There is an agreed format by sender and receiver. It encapsulates information to identify sender and receiver rightly.A message format will depend on the type of message and the medium through which the message is delivered.Message encapsulation is a process that is used to place one message inside another message for transfer from the source to the destination.Message size :Here long messages must break into small pieces to travel across a network or The process of breaking up a long message into individual pieces before being sent over the network.Example – In mobile phone SMS limits message size to 160 normal alphabet characters. For non-alphabet character, It needs 16 bit of data to represent them limiting size to 70 characters only.Message timing :It manages flow control. Acknowledgments response time out. This requires certain timing control information. It checks for any delays in data passing. It includes rules like Access method, flow control, response timeout.Message delivery options :There are different delivery options like Unicast, Multicast, Broadcast.Sending information to a single person is referred to as a one-to-one delivery and is called unicast which implies that there is only one destination (single destination).To communicate information to more than one person (Group of people at the same time) is referred to as one-to-many and is called multicast which implies that one sender to multiple destinations/recipients for the same message.Sometimes information is to be communicated to every person in the same area. This is referred to as one-to-all and is called broadcast which implies that one sender sends a message to all connected recipients."
},
{
"code": null,
"e": 2689,
"s": 2293,
"text": "Message encoding :A source message from sender is encoded into signals or waves then transmitted through a medium wired / wireless then received and decoded and message is passed to destination. Encoding is the process of transforming set of Unicode characters into a sequence of bytes.Message Source –> Encoder –> Transmitter –> Transmitter Medium –>\nReceiver –>Decoder –> Message destination"
},
{
"code": null,
"e": 2799,
"s": 2689,
"text": "Message Source –> Encoder –> Transmitter –> Transmitter Medium –>\nReceiver –>Decoder –> Message destination"
},
{
"code": null,
"e": 3202,
"s": 2799,
"text": "Message formatting and encapsulation :There is an agreed format by sender and receiver. It encapsulates information to identify sender and receiver rightly.A message format will depend on the type of message and the medium through which the message is delivered.Message encapsulation is a process that is used to place one message inside another message for transfer from the source to the destination."
},
{
"code": null,
"e": 3449,
"s": 3202,
"text": "A message format will depend on the type of message and the medium through which the message is delivered.Message encapsulation is a process that is used to place one message inside another message for transfer from the source to the destination."
},
{
"code": null,
"e": 3833,
"s": 3449,
"text": "Message size :Here long messages must break into small pieces to travel across a network or The process of breaking up a long message into individual pieces before being sent over the network.Example – In mobile phone SMS limits message size to 160 normal alphabet characters. For non-alphabet character, It needs 16 bit of data to represent them limiting size to 70 characters only."
},
{
"code": null,
"e": 4025,
"s": 3833,
"text": "Example – In mobile phone SMS limits message size to 160 normal alphabet characters. For non-alphabet character, It needs 16 bit of data to represent them limiting size to 70 characters only."
},
{
"code": null,
"e": 4263,
"s": 4025,
"text": "Message timing :It manages flow control. Acknowledgments response time out. This requires certain timing control information. It checks for any delays in data passing. It includes rules like Access method, flow control, response timeout."
},
{
"code": null,
"e": 4970,
"s": 4263,
"text": "Message delivery options :There are different delivery options like Unicast, Multicast, Broadcast.Sending information to a single person is referred to as a one-to-one delivery and is called unicast which implies that there is only one destination (single destination).To communicate information to more than one person (Group of people at the same time) is referred to as one-to-many and is called multicast which implies that one sender to multiple destinations/recipients for the same message.Sometimes information is to be communicated to every person in the same area. This is referred to as one-to-all and is called broadcast which implies that one sender sends a message to all connected recipients."
},
{
"code": null,
"e": 5142,
"s": 4970,
"text": "Sending information to a single person is referred to as a one-to-one delivery and is called unicast which implies that there is only one destination (single destination)."
},
{
"code": null,
"e": 5370,
"s": 5142,
"text": "To communicate information to more than one person (Group of people at the same time) is referred to as one-to-many and is called multicast which implies that one sender to multiple destinations/recipients for the same message."
},
{
"code": null,
"e": 5581,
"s": 5370,
"text": "Sometimes information is to be communicated to every person in the same area. This is referred to as one-to-all and is called broadcast which implies that one sender sends a message to all connected recipients."
},
{
"code": null,
"e": 5599,
"s": 5581,
"text": "Computer Networks"
},
{
"code": null,
"e": 5617,
"s": 5599,
"text": "Computer Networks"
},
{
"code": null,
"e": 5715,
"s": 5617,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5741,
"s": 5715,
"text": "Secure Socket Layer (SSL)"
},
{
"code": null,
"e": 5771,
"s": 5741,
"text": "GSM in Wireless Communication"
},
{
"code": null,
"e": 5801,
"s": 5771,
"text": "Wireless Application Protocol"
},
{
"code": null,
"e": 5841,
"s": 5801,
"text": "Mobile Internet Protocol (or Mobile IP)"
},
{
"code": null,
"e": 5887,
"s": 5841,
"text": "Introduction of Mobile Ad hoc Network (MANET)"
},
{
"code": null,
"e": 5922,
"s": 5887,
"text": "Advanced Encryption Standard (AES)"
},
{
"code": null,
"e": 5949,
"s": 5922,
"text": "Cryptography and its Types"
},
{
"code": null,
"e": 5959,
"s": 5949,
"text": "Bluetooth"
},
{
"code": null,
"e": 5992,
"s": 5959,
"text": "Intrusion Detection System (IDS)"
}
] |
Software Engineering | Application Composition Estimation Model (COCOMO II | Stage 1) | 14 Mar, 2019
Application Composition Estimation Model allows one to estimate the cost, effort at the stage 1 of the COCOMO II Model.
In this model size is first estimated using Object Points. Object Points are easy to identify and count. Object Points defines screen, reports, third generation (3GL) modules as objects.
Object Point estimation is a new size estimation technique but it is well suited in Application Composition Sector.
Estimation of Efforts:Following steps are taken to estimate effort to develop a project
Step-1: Access Object countsEstimate the number of screens, reports and 3GL components that will comprise this application.
Step-2: Classify complexity levels of each objectWe have to classify each object instance into simple, medium and difficult complexity level depending on values of its characteristics.Complexity levels are assigned according to the given table
Step-3: Assign complexity weights to each objectThe weights are used for three object types i.e, screens, reports and 3GL components.Complexity weight are assigned according to object’s complexity level using following table
Step-4: Determine Object PointsAdd all the weighted object instances to get one number and this is known as object point count.
Object Point
= Sigma (number of object instances)
* (Complexity weight of each object instance)
Step-5: Compute New Object Points (NOP)We have to estimate the %reuse to be achieved in a project.Depending on %reuse
NOP = [(object points) * (100 - %reuse)]/100
NOP are the object point that will need to be developed and differ from the object point count because there may be reuse of some object instance in project.
Step-6: Calculate Productivity rate (PROD)Productivity rate is calculated on the basis of information given about developer’s experience and capability.For calculating it, we use following table
Step-7: Compute the estimated EffortEffort to develop a project can be calculated as
Effort = NOP/PROD
Effort is measured in person-month.
Example:Consider a database application project with
The application has four screens with four views each and seven data tables for three servers and four clients.Application may generate two reports of six section each from seven data tables for two servers and three clients.
The application has four screens with four views each and seven data tables for three servers and four clients.
Application may generate two reports of six section each from seven data tables for two servers and three clients.
10% reuse of object points.Developer’s experience and capability in similar environment is low. Calculate the object point count, New object point and effort to develop such project.
Step-1:Number of screens = 4Number of records = 2
Step-2:For screens,Number of views = 4Number of data tables = 7Number of servers = 3Number of clients = 4by using above given information and table (For Screens),Complexity level for each screen = medium
For reports,Number of sections = 6Number of data tables = 7Number of servers = 2Number of clients = 3by using above given information and table (For Reports),Complexity level for each report = difficult
Step-3:By using complexity weight table we can assign complexity weight to each object instance depending upon their complexity level.Complexity weight for each screen = 2Complexity weight for each report = 8
Step-4:
Object point count
= sigma (Number of object instances) * (its Complexity weight)
= 4 * 2 + 2 * 8 = 24
Step-5:
%reuse of object points = 10% (given)
NOP = [object points * (100 - %reuse)]/100
= [24 * (100 -10)]/100 = 21.6
Step-6:Developer’s experience and capability is low (given)Using information given about developer and productivity rate tableProductivity rate (PROD) of given project = 7
Step-7:
Effort
= NOP/PROD
= 21.6/7
= 3.086 person-month
Therefore, effort to develop the given project = 3.086 person-month.
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Software Engineering | Black box testing
Unit Testing | Software Testing
System Testing
Software Engineering | Integration Testing
Equivalence Partitioning Method
What is DFD(Data Flow Diagram)?
Software Engineering | Calculation of Function Point (FP)
Software Development Life Cycle (SDLC)
Software Processes in Software Engineering
Difference Between Edge Computing and Fog Computing | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Mar, 2019"
},
{
"code": null,
"e": 174,
"s": 54,
"text": "Application Composition Estimation Model allows one to estimate the cost, effort at the stage 1 of the COCOMO II Model."
},
{
"code": null,
"e": 361,
"s": 174,
"text": "In this model size is first estimated using Object Points. Object Points are easy to identify and count. Object Points defines screen, reports, third generation (3GL) modules as objects."
},
{
"code": null,
"e": 477,
"s": 361,
"text": "Object Point estimation is a new size estimation technique but it is well suited in Application Composition Sector."
},
{
"code": null,
"e": 565,
"s": 477,
"text": "Estimation of Efforts:Following steps are taken to estimate effort to develop a project"
},
{
"code": null,
"e": 689,
"s": 565,
"text": "Step-1: Access Object countsEstimate the number of screens, reports and 3GL components that will comprise this application."
},
{
"code": null,
"e": 933,
"s": 689,
"text": "Step-2: Classify complexity levels of each objectWe have to classify each object instance into simple, medium and difficult complexity level depending on values of its characteristics.Complexity levels are assigned according to the given table"
},
{
"code": null,
"e": 1158,
"s": 933,
"text": "Step-3: Assign complexity weights to each objectThe weights are used for three object types i.e, screens, reports and 3GL components.Complexity weight are assigned according to object’s complexity level using following table"
},
{
"code": null,
"e": 1286,
"s": 1158,
"text": "Step-4: Determine Object PointsAdd all the weighted object instances to get one number and this is known as object point count."
},
{
"code": null,
"e": 1395,
"s": 1286,
"text": "Object Point \n= Sigma (number of object instances) \n * (Complexity weight of each object instance)\n"
},
{
"code": null,
"e": 1513,
"s": 1395,
"text": "Step-5: Compute New Object Points (NOP)We have to estimate the %reuse to be achieved in a project.Depending on %reuse"
},
{
"code": null,
"e": 1559,
"s": 1513,
"text": "NOP = [(object points) * (100 - %reuse)]/100\n"
},
{
"code": null,
"e": 1717,
"s": 1559,
"text": "NOP are the object point that will need to be developed and differ from the object point count because there may be reuse of some object instance in project."
},
{
"code": null,
"e": 1912,
"s": 1717,
"text": "Step-6: Calculate Productivity rate (PROD)Productivity rate is calculated on the basis of information given about developer’s experience and capability.For calculating it, we use following table"
},
{
"code": null,
"e": 1997,
"s": 1912,
"text": "Step-7: Compute the estimated EffortEffort to develop a project can be calculated as"
},
{
"code": null,
"e": 2016,
"s": 1997,
"text": "Effort = NOP/PROD\n"
},
{
"code": null,
"e": 2052,
"s": 2016,
"text": "Effort is measured in person-month."
},
{
"code": null,
"e": 2105,
"s": 2052,
"text": "Example:Consider a database application project with"
},
{
"code": null,
"e": 2331,
"s": 2105,
"text": "The application has four screens with four views each and seven data tables for three servers and four clients.Application may generate two reports of six section each from seven data tables for two servers and three clients."
},
{
"code": null,
"e": 2443,
"s": 2331,
"text": "The application has four screens with four views each and seven data tables for three servers and four clients."
},
{
"code": null,
"e": 2558,
"s": 2443,
"text": "Application may generate two reports of six section each from seven data tables for two servers and three clients."
},
{
"code": null,
"e": 2741,
"s": 2558,
"text": "10% reuse of object points.Developer’s experience and capability in similar environment is low. Calculate the object point count, New object point and effort to develop such project."
},
{
"code": null,
"e": 2791,
"s": 2741,
"text": "Step-1:Number of screens = 4Number of records = 2"
},
{
"code": null,
"e": 2995,
"s": 2791,
"text": "Step-2:For screens,Number of views = 4Number of data tables = 7Number of servers = 3Number of clients = 4by using above given information and table (For Screens),Complexity level for each screen = medium"
},
{
"code": null,
"e": 3198,
"s": 2995,
"text": "For reports,Number of sections = 6Number of data tables = 7Number of servers = 2Number of clients = 3by using above given information and table (For Reports),Complexity level for each report = difficult"
},
{
"code": null,
"e": 3407,
"s": 3198,
"text": "Step-3:By using complexity weight table we can assign complexity weight to each object instance depending upon their complexity level.Complexity weight for each screen = 2Complexity weight for each report = 8"
},
{
"code": null,
"e": 3415,
"s": 3407,
"text": "Step-4:"
},
{
"code": null,
"e": 3521,
"s": 3415,
"text": "Object point count \n= sigma (Number of object instances) * (its Complexity weight) \n= 4 * 2 + 2 * 8 = 24 "
},
{
"code": null,
"e": 3529,
"s": 3521,
"text": "Step-5:"
},
{
"code": null,
"e": 3642,
"s": 3529,
"text": "%reuse of object points = 10% (given)\nNOP = [object points * (100 - %reuse)]/100 \n= [24 * (100 -10)]/100 = 21.6 "
},
{
"code": null,
"e": 3814,
"s": 3642,
"text": "Step-6:Developer’s experience and capability is low (given)Using information given about developer and productivity rate tableProductivity rate (PROD) of given project = 7"
},
{
"code": null,
"e": 3822,
"s": 3814,
"text": "Step-7:"
},
{
"code": null,
"e": 3874,
"s": 3822,
"text": "Effort \n= NOP/PROD \n= 21.6/7 \n= 3.086 person-month "
},
{
"code": null,
"e": 3943,
"s": 3874,
"text": "Therefore, effort to develop the given project = 3.086 person-month."
},
{
"code": null,
"e": 3964,
"s": 3943,
"text": "Software Engineering"
},
{
"code": null,
"e": 4062,
"s": 3964,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4103,
"s": 4062,
"text": "Software Engineering | Black box testing"
},
{
"code": null,
"e": 4135,
"s": 4103,
"text": "Unit Testing | Software Testing"
},
{
"code": null,
"e": 4150,
"s": 4135,
"text": "System Testing"
},
{
"code": null,
"e": 4193,
"s": 4150,
"text": "Software Engineering | Integration Testing"
},
{
"code": null,
"e": 4225,
"s": 4193,
"text": "Equivalence Partitioning Method"
},
{
"code": null,
"e": 4257,
"s": 4225,
"text": "What is DFD(Data Flow Diagram)?"
},
{
"code": null,
"e": 4315,
"s": 4257,
"text": "Software Engineering | Calculation of Function Point (FP)"
},
{
"code": null,
"e": 4354,
"s": 4315,
"text": "Software Development Life Cycle (SDLC)"
},
{
"code": null,
"e": 4397,
"s": 4354,
"text": "Software Processes in Software Engineering"
}
] |
Count pairs (a, b) whose sum of cubes is N (a^3 + b^3 = N) in C++ | We are given a number N. The goal is to find ordered pairs of positive numbers such that the sum of their cubes is N.
We will do this by finding solutions to the equation a3 + b3 = N. Where a is not more than cube root of N and b can be calculated as cube root of (N-a3).
Let’s understand with examples.
Input
N=35
Output
Count of pairs of (a,b) where a^3+b^3=N: 2
Explanation
Pairs will be (2,3) and (3,2). 23+33=8+27=35
Input
N=100
Output
Count of pairs of (a,b) where a^3+b^3=N: 0
Explanation
No such pairs possible.
We take integer N.
We take integer N.
Function cubeSum(int n) takes n and returns the count of ordered pairs with sum of cubes as n.
Function cubeSum(int n) takes n and returns the count of ordered pairs with sum of cubes as n.
Take the initial variable count as 0 for pairs.
Take the initial variable count as 0 for pairs.
Traverse using for loop to find a.
Traverse using for loop to find a.
Start from a=1 to a<=cbrt(n) which is cube root of n.
Start from a=1 to a<=cbrt(n) which is cube root of n.
Calculate cube of b as n-pow(a,3).
Calculate cube of b as n-pow(a,3).
Calculate b as cbrt(bcube)
Calculate b as cbrt(bcube)
If pow(b,3)==bcube. Increment count by 1.
If pow(b,3)==bcube. Increment count by 1.
At the end of all loops count will have a total number of such pairs.
At the end of all loops count will have a total number of such pairs.
Return the count as result.
Return the count as result.
Live Demo
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
int cubeSum(int n){
int count = 0;
for (int a = 1; a < cbrt(n); a++){
int bcube=n - (pow(a,3));
int b = cbrt(bcube);
if(pow(b,3)==bcube)
{ count++; }
}
return count;
}
int main(){
int N = 35;
cout <<"Count of pairs of (a,b) where a^3+b^3=N: "<<cubeSum(N);
return 0;
}
If we run the above code it will generate the following output −
Count of pairs of (a,b) where a^3+b^3=N: 2 | [
{
"code": null,
"e": 1180,
"s": 1062,
"text": "We are given a number N. The goal is to find ordered pairs of positive numbers such that the sum of their cubes is N."
},
{
"code": null,
"e": 1334,
"s": 1180,
"text": "We will do this by finding solutions to the equation a3 + b3 = N. Where a is not more than cube root of N and b can be calculated as cube root of (N-a3)."
},
{
"code": null,
"e": 1366,
"s": 1334,
"text": "Let’s understand with examples."
},
{
"code": null,
"e": 1373,
"s": 1366,
"text": "Input "
},
{
"code": null,
"e": 1378,
"s": 1373,
"text": "N=35"
},
{
"code": null,
"e": 1386,
"s": 1378,
"text": "Output "
},
{
"code": null,
"e": 1429,
"s": 1386,
"text": "Count of pairs of (a,b) where a^3+b^3=N: 2"
},
{
"code": null,
"e": 1442,
"s": 1429,
"text": "Explanation "
},
{
"code": null,
"e": 1487,
"s": 1442,
"text": "Pairs will be (2,3) and (3,2). 23+33=8+27=35"
},
{
"code": null,
"e": 1494,
"s": 1487,
"text": "Input "
},
{
"code": null,
"e": 1500,
"s": 1494,
"text": "N=100"
},
{
"code": null,
"e": 1508,
"s": 1500,
"text": "Output "
},
{
"code": null,
"e": 1551,
"s": 1508,
"text": "Count of pairs of (a,b) where a^3+b^3=N: 0"
},
{
"code": null,
"e": 1564,
"s": 1551,
"text": "Explanation "
},
{
"code": null,
"e": 1588,
"s": 1564,
"text": "No such pairs possible."
},
{
"code": null,
"e": 1607,
"s": 1588,
"text": "We take integer N."
},
{
"code": null,
"e": 1626,
"s": 1607,
"text": "We take integer N."
},
{
"code": null,
"e": 1721,
"s": 1626,
"text": "Function cubeSum(int n) takes n and returns the count of ordered pairs with sum of cubes as n."
},
{
"code": null,
"e": 1816,
"s": 1721,
"text": "Function cubeSum(int n) takes n and returns the count of ordered pairs with sum of cubes as n."
},
{
"code": null,
"e": 1864,
"s": 1816,
"text": "Take the initial variable count as 0 for pairs."
},
{
"code": null,
"e": 1912,
"s": 1864,
"text": "Take the initial variable count as 0 for pairs."
},
{
"code": null,
"e": 1947,
"s": 1912,
"text": "Traverse using for loop to find a."
},
{
"code": null,
"e": 1982,
"s": 1947,
"text": "Traverse using for loop to find a."
},
{
"code": null,
"e": 2036,
"s": 1982,
"text": "Start from a=1 to a<=cbrt(n) which is cube root of n."
},
{
"code": null,
"e": 2090,
"s": 2036,
"text": "Start from a=1 to a<=cbrt(n) which is cube root of n."
},
{
"code": null,
"e": 2125,
"s": 2090,
"text": "Calculate cube of b as n-pow(a,3)."
},
{
"code": null,
"e": 2160,
"s": 2125,
"text": "Calculate cube of b as n-pow(a,3)."
},
{
"code": null,
"e": 2187,
"s": 2160,
"text": "Calculate b as cbrt(bcube)"
},
{
"code": null,
"e": 2214,
"s": 2187,
"text": "Calculate b as cbrt(bcube)"
},
{
"code": null,
"e": 2256,
"s": 2214,
"text": "If pow(b,3)==bcube. Increment count by 1."
},
{
"code": null,
"e": 2298,
"s": 2256,
"text": "If pow(b,3)==bcube. Increment count by 1."
},
{
"code": null,
"e": 2368,
"s": 2298,
"text": "At the end of all loops count will have a total number of such pairs."
},
{
"code": null,
"e": 2438,
"s": 2368,
"text": "At the end of all loops count will have a total number of such pairs."
},
{
"code": null,
"e": 2466,
"s": 2438,
"text": "Return the count as result."
},
{
"code": null,
"e": 2494,
"s": 2466,
"text": "Return the count as result."
},
{
"code": null,
"e": 2505,
"s": 2494,
"text": " Live Demo"
},
{
"code": null,
"e": 2885,
"s": 2505,
"text": "#include <bits/stdc++.h>\n#include <math.h>\nusing namespace std;\nint cubeSum(int n){\n int count = 0;\n for (int a = 1; a < cbrt(n); a++){\n int bcube=n - (pow(a,3));\n int b = cbrt(bcube);\n if(pow(b,3)==bcube)\n { count++; }\n }\n return count;\n}\nint main(){\n int N = 35;\n cout <<\"Count of pairs of (a,b) where a^3+b^3=N: \"<<cubeSum(N);\n return 0;\n}"
},
{
"code": null,
"e": 2950,
"s": 2885,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 2993,
"s": 2950,
"text": "Count of pairs of (a,b) where a^3+b^3=N: 2"
}
] |
numpy.exp2() in Python - GeeksforGeeks | 29 Nov, 2018
numpy.exp2(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) :This mathematical function helps user to calculate 2**x for all x being the array elements.
Parameters :
array : [array_like]Input array or object whose elements, we need to test.out : [ndarray, optional]Output array with same dimensions as Input array,placed with result.**kwargs : Allows you to pass keyword variable length of argument to a function.It is used when we want to handle named argument in a function.where : [array_like, optional]True value means to calculate the universalfunctions(ufunc) at that position, False value means to leave thevalue in the output alone.
Return :
An array with 2**x(power of 2) for all x i.e. array elements
Code 1 : Working
# Python program explaining# exp2() functionimport numpy as np in_array = [1, 3, 5, 4]print ("Input array : \n", in_array) exp2_values = np.exp2(in_array)print ("\n2**x values : \n", exp2_values)
Output :
Input array :
[1, 3, 5, 4]
2**x values :
[ 2. 8. 32. 16.]
Code 2 : Graphical representation
# Python program showing# Graphical representation of # exp2() functionimport numpy as npimport matplotlib.pyplot as plt in_array = [1, 2, 3, 4, 5 ,6]out_array = np.exp2(in_array) print("out_array : ", out_array) y = [1, 2, 3, 4, 5 ,6]plt.plot(in_array, y, color = 'blue', marker = "*") # red for numpy.exp2()plt.plot(out_array, y, color = 'red', marker = "o")plt.title("numpy.exp2()")plt.xlabel("X")plt.ylabel("Y")plt.show()
Output :out_array : [ 2. 4. 8. 16. 32. 64.]
References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.exp2.html.
Python numpy-Mathematical Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n29 Nov, 2018"
},
{
"code": null,
"e": 24088,
"s": 23901,
"text": "numpy.exp2(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) :This mathematical function helps user to calculate 2**x for all x being the array elements."
},
{
"code": null,
"e": 24101,
"s": 24088,
"text": "Parameters :"
},
{
"code": null,
"e": 24576,
"s": 24101,
"text": "array : [array_like]Input array or object whose elements, we need to test.out : [ndarray, optional]Output array with same dimensions as Input array,placed with result.**kwargs : Allows you to pass keyword variable length of argument to a function.It is used when we want to handle named argument in a function.where : [array_like, optional]True value means to calculate the universalfunctions(ufunc) at that position, False value means to leave thevalue in the output alone."
},
{
"code": null,
"e": 24585,
"s": 24576,
"text": "Return :"
},
{
"code": null,
"e": 24648,
"s": 24585,
"text": "An array with 2**x(power of 2) for all x i.e. array elements \n"
},
{
"code": null,
"e": 24666,
"s": 24648,
"text": " Code 1 : Working"
},
{
"code": "# Python program explaining# exp2() functionimport numpy as np in_array = [1, 3, 5, 4]print (\"Input array : \\n\", in_array) exp2_values = np.exp2(in_array)print (\"\\n2**x values : \\n\", exp2_values)",
"e": 24864,
"s": 24666,
"text": null
},
{
"code": null,
"e": 24873,
"s": 24864,
"text": "Output :"
},
{
"code": null,
"e": 24942,
"s": 24873,
"text": "Input array : \n [1, 3, 5, 4]\n\n2**x values : \n [ 2. 8. 32. 16.]\n"
},
{
"code": null,
"e": 24977,
"s": 24942,
"text": " Code 2 : Graphical representation"
},
{
"code": "# Python program showing# Graphical representation of # exp2() functionimport numpy as npimport matplotlib.pyplot as plt in_array = [1, 2, 3, 4, 5 ,6]out_array = np.exp2(in_array) print(\"out_array : \", out_array) y = [1, 2, 3, 4, 5 ,6]plt.plot(in_array, y, color = 'blue', marker = \"*\") # red for numpy.exp2()plt.plot(out_array, y, color = 'red', marker = \"o\")plt.title(\"numpy.exp2()\")plt.xlabel(\"X\")plt.ylabel(\"Y\")plt.show() ",
"e": 25409,
"s": 24977,
"text": null
},
{
"code": null,
"e": 25453,
"s": 25409,
"text": "Output :out_array : [ 2. 4. 8. 16. 32. 64.]"
},
{
"code": null,
"e": 25542,
"s": 25453,
"text": "References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.exp2.html."
},
{
"code": null,
"e": 25577,
"s": 25542,
"text": "Python numpy-Mathematical Function"
},
{
"code": null,
"e": 25590,
"s": 25577,
"text": "Python-numpy"
},
{
"code": null,
"e": 25597,
"s": 25590,
"text": "Python"
},
{
"code": null,
"e": 25695,
"s": 25597,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25704,
"s": 25695,
"text": "Comments"
},
{
"code": null,
"e": 25717,
"s": 25704,
"text": "Old Comments"
},
{
"code": null,
"e": 25749,
"s": 25717,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25805,
"s": 25749,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25847,
"s": 25805,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25889,
"s": 25847,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25925,
"s": 25889,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 25947,
"s": 25925,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25986,
"s": 25947,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26013,
"s": 25986,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26044,
"s": 26013,
"text": "Python | os.path.join() method"
}
] |
Find an integer in the given range that satisfies the given conditions - GeeksforGeeks | 14 Sep, 2021
Given two integers L and R where L ≤ R, the task is to find an integer K such that:
L ≤ K ≤ R.All the digits of K are distinct.The value of the expression (L – K) * (K – R) is maximum.
L ≤ K ≤ R.
All the digits of K are distinct.
The value of the expression (L – K) * (K – R) is maximum.
If multiple answers exist then choose the larger value for K.Examples:
Input: L = 5, R = 10 Output: 8Input: L = 50, R = 60 Output: 56
Approach: Iterate from L to R and for each value of K, check whether it contains all distinct digits and (L – K) * (K – R) is maximum. If two or more values give the same maximum value for the expression then choose the greater value for K.Below is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int MAX = 10; // Function that returns true if x// contains all distinct digitsbool distinctDigits(int x){ bool present[MAX] = { false }; while (x > 0) { // Last digit of x int digit = x % 10; // If current digit has // appeared before if (present[digit]) return false; // Mark the current digit // to present present[digit] = true; // Remove the last digit x /= 10; } return true;} // Function to return the// required value of kint findK(int l, int r){ // To store the maximum value // for the given expression int maxExp = INT_MIN; int k = -1; for (int i = l; i <= r; i++) { // If i contains all distinct digits if (distinctDigits(i)) { int exp = (l - i) * (i - r); // If the value of the expression // is also maximum then update k // and the expression if (exp >= maxExp) { k = i; maxExp = exp; } } } return k;} // Driver codeint main(){ int l = 50, r = 60; cout << findK(l, r); return 0;}
// Java implementation of the approachclass GFG{ static int MAX = 10; // Function that returns true if x// contains all distinct digitsstatic boolean distinctDigits(int x){ boolean []present = new boolean[MAX]; while (x > 0) { // Last digit of x int digit = x % 10; // If current digit has // appeared before if (present[digit]) return false; // Mark the current digit // to present present[digit] = true; // Remove the last digit x /= 10; } return true;} // Function to return the// required value of kstatic int findK(int l, int r){ // To store the maximum value // for the given expression int maxExp = Integer.MIN_VALUE; int k = -1; for (int i = l; i <= r; i++) { // If i contains all distinct digits if (distinctDigits(i)) { int exp = (l - i) * (i - r); // If the value of the expression // is also maximum then update k // and the expression if (exp >= maxExp) { k = i; maxExp = exp; } } } return k;} // Driver codepublic static void main(String[] args){ int l = 50, r = 60; System.out.print(findK(l, r)); }} // This code is contributed by 29AjayKumar
# Python3 implementation of the approachimport sysMAX = 10 # Function that returns true if x# contains all distinct digitsdef distinctDigits(x): present = [False for i in range(MAX)] while (x > 0): # Last digit of x digit = x % 10 # If current digit has # appeared before if (present[digit]): return False # Mark the current digit # to present present[digit] = True # Remove the last digit x = x // 10 return True # Function to return the# required value of kdef findK(l, r): # To store the maximum value # for the given expression maxExp = -sys.maxsize - 1 k = -1 for i in range(l, r + 1, 1): # If i contains all distinct digits if (distinctDigits(i)): exp = (l - i) * (i - r) # If the value of the expression # is also maximum then update k # and the expression if (exp >= maxExp): k = i; maxExp = exp return k # Driver codeif __name__ == '__main__': l = 50 r = 60 print(findK(l, r)) # This code is contributed by Surendra_Gangwar
// C# implementation of the approachusing System; class GFG{static int MAX = 10; // Function that returns true if x// contains all distinct digitsstatic bool distinctDigits(int x){ bool []present = new bool[MAX]; while (x > 0) { // Last digit of x int digit = x % 10; // If current digit has // appeared before if (present[digit]) return false; // Mark the current digit // to present present[digit] = true; // Remove the last digit x /= 10; } return true;} // Function to return the// required value of kstatic int findK(int l, int r){ // To store the maximum value // for the given expression int maxExp = int.MinValue; int k = -1; for (int i = l; i <= r; i++) { // If i contains all distinct digits if (distinctDigits(i)) { int exp = (l - i) * (i - r); // If the value of the expression // is also maximum then update k // and the expression if (exp >= maxExp) { k = i; maxExp = exp; } } } return k;} // Driver codepublic static void Main(String[] args){ int l = 50, r = 60; Console.Write(findK(l, r));}} // This code is contributed by Rajput-Ji
<script>// javascript implementation of the approach var MAX = 10; // Function that returns true if x // contains all distinct digits function distinctDigits(x) { var present = new Array(MAX).fill(false); while (x > 0) { // Last digit of x var digit = x % 10; // If current digit has // appeared before if (present[digit]) return false; // Mark the current digit // to present present[digit] = true; // Remove the last digit x = parseInt(x/10); } return true; } // Function to return the // required value of k function findK(l , r) { // To store the maximum value // for the given expression var maxExp = Number.MIN_VALUE; var k = -1; for (var i = l; i <= r; i++) { // If i contains all distinct digits if (distinctDigits(i)) { var exp = (l - i) * (i - r); // If the value of the expression // is also maximum then update k // and the expression if (exp >= maxExp) { k = i; maxExp = exp; } } } return k; } // Driver code var l = 50, r = 60; document.write(findK(l, r)); // This code is contributed by gauravrajput1</script>
56
SURENDRA_GANGWAR
29AjayKumar
Rajput-Ji
GauravRajput1
Competitive Programming
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shortest path in a directed graph by Dijkstra’s algorithm
Breadth First Traversal ( BFS ) on a 2D array
Multistage Graph (Shortest Path)
Runtime Errors
Graph implementation using STL for competitive programming | Set 2 (Weighted graph)
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7 | [
{
"code": null,
"e": 25102,
"s": 25074,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 25188,
"s": 25102,
"text": "Given two integers L and R where L ≤ R, the task is to find an integer K such that: "
},
{
"code": null,
"e": 25291,
"s": 25188,
"text": "L ≤ K ≤ R.All the digits of K are distinct.The value of the expression (L – K) * (K – R) is maximum. "
},
{
"code": null,
"e": 25302,
"s": 25291,
"text": "L ≤ K ≤ R."
},
{
"code": null,
"e": 25336,
"s": 25302,
"text": "All the digits of K are distinct."
},
{
"code": null,
"e": 25396,
"s": 25336,
"text": "The value of the expression (L – K) * (K – R) is maximum. "
},
{
"code": null,
"e": 25469,
"s": 25396,
"text": "If multiple answers exist then choose the larger value for K.Examples: "
},
{
"code": null,
"e": 25534,
"s": 25469,
"text": "Input: L = 5, R = 10 Output: 8Input: L = 50, R = 60 Output: 56 "
},
{
"code": null,
"e": 25829,
"s": 25536,
"text": "Approach: Iterate from L to R and for each value of K, check whether it contains all distinct digits and (L – K) * (K – R) is maximum. If two or more values give the same maximum value for the expression then choose the greater value for K.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25833,
"s": 25829,
"text": "C++"
},
{
"code": null,
"e": 25838,
"s": 25833,
"text": "Java"
},
{
"code": null,
"e": 25847,
"s": 25838,
"text": "Python 3"
},
{
"code": null,
"e": 25850,
"s": 25847,
"text": "C#"
},
{
"code": null,
"e": 25861,
"s": 25850,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; const int MAX = 10; // Function that returns true if x// contains all distinct digitsbool distinctDigits(int x){ bool present[MAX] = { false }; while (x > 0) { // Last digit of x int digit = x % 10; // If current digit has // appeared before if (present[digit]) return false; // Mark the current digit // to present present[digit] = true; // Remove the last digit x /= 10; } return true;} // Function to return the// required value of kint findK(int l, int r){ // To store the maximum value // for the given expression int maxExp = INT_MIN; int k = -1; for (int i = l; i <= r; i++) { // If i contains all distinct digits if (distinctDigits(i)) { int exp = (l - i) * (i - r); // If the value of the expression // is also maximum then update k // and the expression if (exp >= maxExp) { k = i; maxExp = exp; } } } return k;} // Driver codeint main(){ int l = 50, r = 60; cout << findK(l, r); return 0;}",
"e": 27096,
"s": 25861,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ static int MAX = 10; // Function that returns true if x// contains all distinct digitsstatic boolean distinctDigits(int x){ boolean []present = new boolean[MAX]; while (x > 0) { // Last digit of x int digit = x % 10; // If current digit has // appeared before if (present[digit]) return false; // Mark the current digit // to present present[digit] = true; // Remove the last digit x /= 10; } return true;} // Function to return the// required value of kstatic int findK(int l, int r){ // To store the maximum value // for the given expression int maxExp = Integer.MIN_VALUE; int k = -1; for (int i = l; i <= r; i++) { // If i contains all distinct digits if (distinctDigits(i)) { int exp = (l - i) * (i - r); // If the value of the expression // is also maximum then update k // and the expression if (exp >= maxExp) { k = i; maxExp = exp; } } } return k;} // Driver codepublic static void main(String[] args){ int l = 50, r = 60; System.out.print(findK(l, r)); }} // This code is contributed by 29AjayKumar",
"e": 28426,
"s": 27096,
"text": null
},
{
"code": "# Python3 implementation of the approachimport sysMAX = 10 # Function that returns true if x# contains all distinct digitsdef distinctDigits(x): present = [False for i in range(MAX)] while (x > 0): # Last digit of x digit = x % 10 # If current digit has # appeared before if (present[digit]): return False # Mark the current digit # to present present[digit] = True # Remove the last digit x = x // 10 return True # Function to return the# required value of kdef findK(l, r): # To store the maximum value # for the given expression maxExp = -sys.maxsize - 1 k = -1 for i in range(l, r + 1, 1): # If i contains all distinct digits if (distinctDigits(i)): exp = (l - i) * (i - r) # If the value of the expression # is also maximum then update k # and the expression if (exp >= maxExp): k = i; maxExp = exp return k # Driver codeif __name__ == '__main__': l = 50 r = 60 print(findK(l, r)) # This code is contributed by Surendra_Gangwar",
"e": 29609,
"s": 28426,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{static int MAX = 10; // Function that returns true if x// contains all distinct digitsstatic bool distinctDigits(int x){ bool []present = new bool[MAX]; while (x > 0) { // Last digit of x int digit = x % 10; // If current digit has // appeared before if (present[digit]) return false; // Mark the current digit // to present present[digit] = true; // Remove the last digit x /= 10; } return true;} // Function to return the// required value of kstatic int findK(int l, int r){ // To store the maximum value // for the given expression int maxExp = int.MinValue; int k = -1; for (int i = l; i <= r; i++) { // If i contains all distinct digits if (distinctDigits(i)) { int exp = (l - i) * (i - r); // If the value of the expression // is also maximum then update k // and the expression if (exp >= maxExp) { k = i; maxExp = exp; } } } return k;} // Driver codepublic static void Main(String[] args){ int l = 50, r = 60; Console.Write(findK(l, r));}} // This code is contributed by Rajput-Ji",
"e": 30928,
"s": 29609,
"text": null
},
{
"code": "<script>// javascript implementation of the approach var MAX = 10; // Function that returns true if x // contains all distinct digits function distinctDigits(x) { var present = new Array(MAX).fill(false); while (x > 0) { // Last digit of x var digit = x % 10; // If current digit has // appeared before if (present[digit]) return false; // Mark the current digit // to present present[digit] = true; // Remove the last digit x = parseInt(x/10); } return true; } // Function to return the // required value of k function findK(l , r) { // To store the maximum value // for the given expression var maxExp = Number.MIN_VALUE; var k = -1; for (var i = l; i <= r; i++) { // If i contains all distinct digits if (distinctDigits(i)) { var exp = (l - i) * (i - r); // If the value of the expression // is also maximum then update k // and the expression if (exp >= maxExp) { k = i; maxExp = exp; } } } return k; } // Driver code var l = 50, r = 60; document.write(findK(l, r)); // This code is contributed by gauravrajput1</script>",
"e": 32375,
"s": 30928,
"text": null
},
{
"code": null,
"e": 32378,
"s": 32375,
"text": "56"
},
{
"code": null,
"e": 32397,
"s": 32380,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 32409,
"s": 32397,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32419,
"s": 32409,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 32433,
"s": 32419,
"text": "GauravRajput1"
},
{
"code": null,
"e": 32457,
"s": 32433,
"text": "Competitive Programming"
},
{
"code": null,
"e": 32470,
"s": 32457,
"text": "Mathematical"
},
{
"code": null,
"e": 32483,
"s": 32470,
"text": "Mathematical"
},
{
"code": null,
"e": 32581,
"s": 32483,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32639,
"s": 32581,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 32685,
"s": 32639,
"text": "Breadth First Traversal ( BFS ) on a 2D array"
},
{
"code": null,
"e": 32718,
"s": 32685,
"text": "Multistage Graph (Shortest Path)"
},
{
"code": null,
"e": 32733,
"s": 32718,
"text": "Runtime Errors"
},
{
"code": null,
"e": 32817,
"s": 32733,
"text": "Graph implementation using STL for competitive programming | Set 2 (Weighted graph)"
},
{
"code": null,
"e": 32847,
"s": 32817,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 32907,
"s": 32847,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 32922,
"s": 32907,
"text": "C++ Data Types"
},
{
"code": null,
"e": 32965,
"s": 32922,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Plotting a horizontal line on multiple subplots in Python using pyplot | To plot a horizontal line on multiple subplots in Python, we can use subplots to get multiple axes and axhline() method to draw a horizontal line.
Create a figure and a set of subplots. Here, we will create 3 subplots.
Create a figure and a set of subplots. Here, we will create 3 subplots.
Use axhline() method to draw horizontal lines on each axis.
Use axhline() method to draw horizontal lines on each axis.
To display the figure, use show() method.
To display the figure, use show() method.
from matplotlib import pyplot as plt
fig, (ax1, ax2, ax3) = plt.subplots(3)
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
ax1.axhline(y=0.5, xmin=0, xmax=3, c="black", linewidth=2, zorder=0)
ax2.axhline(y=0.5, xmin=0, xmax=3, c="red", linewidth=3, zorder=0)
ax3.axhline(y=0.5, xmin=0, xmax=3, c="yellow", linewidth=4, zorder=0)
plt.show() | [
{
"code": null,
"e": 1209,
"s": 1062,
"text": "To plot a horizontal line on multiple subplots in Python, we can use subplots to get multiple axes and axhline() method to draw a horizontal line."
},
{
"code": null,
"e": 1281,
"s": 1209,
"text": "Create a figure and a set of subplots. Here, we will create 3 subplots."
},
{
"code": null,
"e": 1353,
"s": 1281,
"text": "Create a figure and a set of subplots. Here, we will create 3 subplots."
},
{
"code": null,
"e": 1413,
"s": 1353,
"text": "Use axhline() method to draw horizontal lines on each axis."
},
{
"code": null,
"e": 1473,
"s": 1413,
"text": "Use axhline() method to draw horizontal lines on each axis."
},
{
"code": null,
"e": 1515,
"s": 1473,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1557,
"s": 1515,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1937,
"s": 1557,
"text": "from matplotlib import pyplot as plt\nfig, (ax1, ax2, ax3) = plt.subplots(3)\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nax1.axhline(y=0.5, xmin=0, xmax=3, c=\"black\", linewidth=2, zorder=0)\nax2.axhline(y=0.5, xmin=0, xmax=3, c=\"red\", linewidth=3, zorder=0)\nax3.axhline(y=0.5, xmin=0, xmax=3, c=\"yellow\", linewidth=4, zorder=0)\nplt.show()"
}
] |
DataInputStream readLong() method in Java with Examples - GeeksforGeeks | 05 Jun, 2020
The readLong() method of DataInputStream class in Java is used to read eight input bytes and returns a long value. This method reads the next eight bytes from the input stream and interprets it into long type and returns.
Syntax:
public final long readLong()
throws IOException
Specified By: This method is specified by readLong() method of DataInput interface.
Parameters: This method does not accept any parameter.
Return value: This method returns the long value interpreted by the next eight bytes of the input stream.
Exceptions:
EOFException – It throws EOFException if the input stream is ended before eight bytes can be read.
IOException – This method throws IOException if the stream is closed or some other I/O error occurs.
Below programs illustrate readLong() method in DataInputStream class in IO package:
Program 1: Assume the existence of file “demo.txt”.
// Java program to illustrate// DataInputStream readLong() methodimport java.io.*;public class GFG { public static void main(String[] args) throws IOException { // Create long array long[] buf = { 10000000000l, 20000000000l, 30000000000l }; // Create file output stream FileOutputStream outputStream = new FileOutputStream("c:\\demo.txt"); // Create data output stream DataOutputStream dataOutputStr = new DataOutputStream(outputStream); for (long b : buf) { // Write long value to // the dataOutputStream dataOutputStr.writeLong(b); } dataOutputStr.flush(); // Create file input stream FileInputStream inputStream = new FileInputStream("c:\\demo.txt"); // Create data input stream DataInputStream dataInputStr = new DataInputStream(inputStream); while (dataInputStr.available() > 0) { // Print long values System.out.println( dataInputStr.readLong()); } }}
Program 2: Assume the existence of file “demo.txt”.
// Java program to illustrate// DataInputStream readLong() methodimport java.io.*;public class GFG { public static void main(String[] args) throws IOException { // Create long array long[] buf = { 1234567890L, 9876543210L, 12345678910L }; // Create file output stream FileOutputStream outputStream = new FileOutputStream("c:\\demo.txt"); // Create data output stream DataOutputStream dataOutputStr = new DataOutputStream(outputStream); for (long b : buf) { // Write long value to // the dataOutputStream dataOutputStr.writeLong(b); } dataOutputStr.flush(); // Create file input stream FileInputStream inputStream = new FileInputStream("c:\\demo.txt"); // Create data input stream DataInputStream dataInputStr = new DataInputStream(inputStream); while (dataInputStr.available() > 0) { // Print long values System.out.println( dataInputStr.readLong()); } }}
References:https://docs.oracle.com/javase/10/docs/api/java/io/DataInputStream.html#readLong()
Java-Functions
Java-IO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways of Reading a text file in Java
Stream In Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
HashMap get() Method in Java
Comparator Interface in Java with Examples
Strings in Java
StringBuilder Class in Java with Examples | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n05 Jun, 2020"
},
{
"code": null,
"e": 24170,
"s": 23948,
"text": "The readLong() method of DataInputStream class in Java is used to read eight input bytes and returns a long value. This method reads the next eight bytes from the input stream and interprets it into long type and returns."
},
{
"code": null,
"e": 24178,
"s": 24170,
"text": "Syntax:"
},
{
"code": null,
"e": 24245,
"s": 24178,
"text": "public final long readLong()\n throws IOException\n"
},
{
"code": null,
"e": 24329,
"s": 24245,
"text": "Specified By: This method is specified by readLong() method of DataInput interface."
},
{
"code": null,
"e": 24384,
"s": 24329,
"text": "Parameters: This method does not accept any parameter."
},
{
"code": null,
"e": 24490,
"s": 24384,
"text": "Return value: This method returns the long value interpreted by the next eight bytes of the input stream."
},
{
"code": null,
"e": 24502,
"s": 24490,
"text": "Exceptions:"
},
{
"code": null,
"e": 24601,
"s": 24502,
"text": "EOFException – It throws EOFException if the input stream is ended before eight bytes can be read."
},
{
"code": null,
"e": 24702,
"s": 24601,
"text": "IOException – This method throws IOException if the stream is closed or some other I/O error occurs."
},
{
"code": null,
"e": 24786,
"s": 24702,
"text": "Below programs illustrate readLong() method in DataInputStream class in IO package:"
},
{
"code": null,
"e": 24838,
"s": 24786,
"text": "Program 1: Assume the existence of file “demo.txt”."
},
{
"code": "// Java program to illustrate// DataInputStream readLong() methodimport java.io.*;public class GFG { public static void main(String[] args) throws IOException { // Create long array long[] buf = { 10000000000l, 20000000000l, 30000000000l }; // Create file output stream FileOutputStream outputStream = new FileOutputStream(\"c:\\\\demo.txt\"); // Create data output stream DataOutputStream dataOutputStr = new DataOutputStream(outputStream); for (long b : buf) { // Write long value to // the dataOutputStream dataOutputStr.writeLong(b); } dataOutputStr.flush(); // Create file input stream FileInputStream inputStream = new FileInputStream(\"c:\\\\demo.txt\"); // Create data input stream DataInputStream dataInputStr = new DataInputStream(inputStream); while (dataInputStr.available() > 0) { // Print long values System.out.println( dataInputStr.readLong()); } }}",
"e": 25991,
"s": 24838,
"text": null
},
{
"code": null,
"e": 26043,
"s": 25991,
"text": "Program 2: Assume the existence of file “demo.txt”."
},
{
"code": "// Java program to illustrate// DataInputStream readLong() methodimport java.io.*;public class GFG { public static void main(String[] args) throws IOException { // Create long array long[] buf = { 1234567890L, 9876543210L, 12345678910L }; // Create file output stream FileOutputStream outputStream = new FileOutputStream(\"c:\\\\demo.txt\"); // Create data output stream DataOutputStream dataOutputStr = new DataOutputStream(outputStream); for (long b : buf) { // Write long value to // the dataOutputStream dataOutputStr.writeLong(b); } dataOutputStr.flush(); // Create file input stream FileInputStream inputStream = new FileInputStream(\"c:\\\\demo.txt\"); // Create data input stream DataInputStream dataInputStr = new DataInputStream(inputStream); while (dataInputStr.available() > 0) { // Print long values System.out.println( dataInputStr.readLong()); } }}",
"e": 27194,
"s": 26043,
"text": null
},
{
"code": null,
"e": 27288,
"s": 27194,
"text": "References:https://docs.oracle.com/javase/10/docs/api/java/io/DataInputStream.html#readLong()"
},
{
"code": null,
"e": 27303,
"s": 27288,
"text": "Java-Functions"
},
{
"code": null,
"e": 27319,
"s": 27303,
"text": "Java-IO package"
},
{
"code": null,
"e": 27324,
"s": 27319,
"text": "Java"
},
{
"code": null,
"e": 27329,
"s": 27324,
"text": "Java"
},
{
"code": null,
"e": 27427,
"s": 27329,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27473,
"s": 27427,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 27488,
"s": 27473,
"text": "Stream In Java"
},
{
"code": null,
"e": 27509,
"s": 27488,
"text": "Constructors in Java"
},
{
"code": null,
"e": 27528,
"s": 27509,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 27545,
"s": 27528,
"text": "Generics in Java"
},
{
"code": null,
"e": 27575,
"s": 27545,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 27604,
"s": 27575,
"text": "HashMap get() Method in Java"
},
{
"code": null,
"e": 27647,
"s": 27604,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 27663,
"s": 27647,
"text": "Strings in Java"
}
] |
How to use Measure-Object in PowerShell? | Measure-Object in PowerShell is used to measure the property of the command. There are various measurement parameters are available. For example, Average, Count, sum, maximum, minimum and more.
Get-Process | Measure-Object
PS C:\WINDOWS\system32> Get-Process | Measure-Object
Count : 278
Average :
Sum :
Maximum :
Minimum :
Property :
Here, in the above output, there are total 278 processes are running. If you want to check the maximum memory usage then you can use WorkingSet property with − Maximum Parameter.
Get-Process | Measure-Object -Property WorkingSet -Maximum
PS C:\WINDOWS\system32> Get-Process | Measure-Object -Property WorkingSet –
Maximum
Count : 277
Average :
Sum :
Maximum : 353447936
Minimum :
Property : WorkingSet
You can also use the multiple parameters together like Maximum, Minimum, Sum (To get the total memory consumed in this example) and Average (To get average of memory usage in this example).
Get-Process | Measure-Object -Property WorkingSet -Maximum -Minimum -Sum -
Average
Count : 275
Average : 37769618.1527273
Sum : 10386644992
Maximum : 347447296
Minimum : 8192
Property : WorkingSet
For the text file or the string, you can use measurement properties like Line, Word, character, etc.
Get-Content D:\Temp\testreadC.txt | Measure-Object
Count : 232
Average :
Sum :
Maximum :
Minimum :
Property :
To get the Line, Word and Character count,
Get-Content D:\Temp\testreadC.txt | Measure-Object -Line -Word -Character
Lines Words Characters Property
----- ----- ---------- --------
229 1829 27156
You can also ignore the whitespace and count the characters.
Get-Content D:\Temp\testreadC.txt | Measure-Object -Line -Word -Character -IgnoreWhiteSpace
Lines Words Characters Property
----- ----- ---------- --------
229 1829 7424 | [
{
"code": null,
"e": 1256,
"s": 1062,
"text": "Measure-Object in PowerShell is used to measure the property of the command. There are various measurement parameters are available. For example, Average, Count, sum, maximum, minimum and more."
},
{
"code": null,
"e": 1285,
"s": 1256,
"text": "Get-Process | Measure-Object"
},
{
"code": null,
"e": 1426,
"s": 1285,
"text": "PS C:\\WINDOWS\\system32> Get-Process | Measure-Object\nCount : 278\nAverage :\nSum :\nMaximum :\nMinimum :\nProperty :"
},
{
"code": null,
"e": 1605,
"s": 1426,
"text": "Here, in the above output, there are total 278 processes are running. If you want to check the maximum memory usage then you can use WorkingSet property with − Maximum Parameter."
},
{
"code": null,
"e": 1664,
"s": 1605,
"text": "Get-Process | Measure-Object -Property WorkingSet -Maximum"
},
{
"code": null,
"e": 1857,
"s": 1664,
"text": "PS C:\\WINDOWS\\system32> Get-Process | Measure-Object -Property WorkingSet –\nMaximum\nCount : 277\nAverage :\nSum :\nMaximum : 353447936\nMinimum :\nProperty : WorkingSet"
},
{
"code": null,
"e": 2047,
"s": 1857,
"text": "You can also use the multiple parameters together like Maximum, Minimum, Sum (To get the total memory consumed in this example) and Average (To get average of memory usage in this example)."
},
{
"code": null,
"e": 2130,
"s": 2047,
"text": "Get-Process | Measure-Object -Property WorkingSet -Maximum -Minimum -Sum -\nAverage"
},
{
"code": null,
"e": 2273,
"s": 2130,
"text": "Count : 275\nAverage : 37769618.1527273\nSum : 10386644992\nMaximum : 347447296\nMinimum : 8192\nProperty : WorkingSet"
},
{
"code": null,
"e": 2374,
"s": 2273,
"text": "For the text file or the string, you can use measurement properties like Line, Word, character, etc."
},
{
"code": null,
"e": 2425,
"s": 2374,
"text": "Get-Content D:\\Temp\\testreadC.txt | Measure-Object"
},
{
"code": null,
"e": 2531,
"s": 2425,
"text": "Count : 232\nAverage :\nSum :\nMaximum :\nMinimum :\nProperty :"
},
{
"code": null,
"e": 2574,
"s": 2531,
"text": "To get the Line, Word and Character count,"
},
{
"code": null,
"e": 2648,
"s": 2574,
"text": "Get-Content D:\\Temp\\testreadC.txt | Measure-Object -Line -Word -Character"
},
{
"code": null,
"e": 2778,
"s": 2648,
"text": "Lines Words Characters Property\n----- ----- ---------- --------\n 229 1829 27156"
},
{
"code": null,
"e": 2839,
"s": 2778,
"text": "You can also ignore the whitespace and count the characters."
},
{
"code": null,
"e": 2931,
"s": 2839,
"text": "Get-Content D:\\Temp\\testreadC.txt | Measure-Object -Line -Word -Character -IgnoreWhiteSpace"
},
{
"code": null,
"e": 3066,
"s": 2931,
"text": "Lines Words Characters Property\n----- ----- ---------- --------\n 229 1829 7424"
}
] |
Erlang - whereis | It is called as whereis(Name). Returns the pid of the process that is registered with the name.
whereis(atom,pid)
atom − This is the registered name to give to the process.
atom − This is the registered name to give to the process.
The process id bound to the atom.
-module(helloworld).
-export([start/0, call/2]).
call(Arg1, Arg2) ->
io:fwrite("~p~n",[Arg1]).
start() ->
Pid = spawn(?MODULE, call, ["hello", "process"]),
register(myprocess, Pid),
io:fwrite("~p~n",[whereis(myprocess)]).
When we run the above program, we will get the following result.
<0.55.0>
"hello"
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2397,
"s": 2301,
"text": "It is called as whereis(Name). Returns the pid of the process that is registered with the name."
},
{
"code": null,
"e": 2416,
"s": 2397,
"text": "whereis(atom,pid)\n"
},
{
"code": null,
"e": 2475,
"s": 2416,
"text": "atom − This is the registered name to give to the process."
},
{
"code": null,
"e": 2534,
"s": 2475,
"text": "atom − This is the registered name to give to the process."
},
{
"code": null,
"e": 2568,
"s": 2534,
"text": "The process id bound to the atom."
},
{
"code": null,
"e": 2811,
"s": 2568,
"text": "-module(helloworld). \n-export([start/0, call/2]). \n\ncall(Arg1, Arg2) -> \n io:fwrite(\"~p~n\",[Arg1]). \n\nstart() -> \n Pid = spawn(?MODULE, call, [\"hello\", \"process\"]), \n register(myprocess, Pid), \n io:fwrite(\"~p~n\",[whereis(myprocess)])."
},
{
"code": null,
"e": 2876,
"s": 2811,
"text": "When we run the above program, we will get the following result."
},
{
"code": null,
"e": 2894,
"s": 2876,
"text": "<0.55.0>\n\"hello\"\n"
},
{
"code": null,
"e": 2901,
"s": 2894,
"text": " Print"
},
{
"code": null,
"e": 2912,
"s": 2901,
"text": " Add Notes"
}
] |
Python Group elements at same indices in a multi-list | In this tutorial, we are going to write a program that combines elements of the same indices different lists into a single list. And there is one constraint here. All the lists must be of the same length. Let's see an example to understand it more clearly.
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
We can solve it in different ways. Let's see how to solve with normal loops.
Initialize the list with lists.
Initialize an empty list.
Initialize a variable index to 0.
Iterate over the sub list length timesAppend an empty list to the previous listIterate lists length times.Append the **lists[current_index][index]** to the **result[index]
Append an empty list to the previous list
Iterate lists length times.Append the **lists[current_index][index]** to the **result[index]
Append the **lists[current_index][index]** to the **result[index]
Print the result.
Live Demo
# initializing the list
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# empty list
result = []
# variable to 0
index = 0
# iterating over the sub_list length (3) times
for i in range(len(lists[0])):
# appending an empty sub_list
result.append([])
# iterating lists length (3) times
for j in range(len(lists)):
# adding the element to the result
result[index].append(lists[j][index])
# moving to the next index
index += 1
# printing the result
print(result)
If you run the above code, then you will get the following result.
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
We can solve it using the zip function without any effort. The zip function gives you all the index elements in a tuple as we want. Let's see the code.
Live Demo
# initializing the list
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# using the zip and printing it
print(list(zip(*lists)))
If you run the above code, then you will get the following result.
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
We can convert the tuples into the list by iterating through the lists. It can be done differently.will use another function called map to convert all tuples into lists. It's one line code.
Live Demo
# initializing the list
lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
# using the zip and printing it
print(list(map(list, zip(*lists))))
If you run the above code, then you will get the following result.
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
We have used map to iterate through the list and convert each tuple into the list. You can do same with loops. Try it.
If you have any doubts in the tutorial, mention them in the comment section. | [
{
"code": null,
"e": 1319,
"s": 1062,
"text": "In this tutorial, we are going to write a program that combines elements of the same indices different lists into a single list. And there is one constraint here. All the lists must be of the same length. Let's see an example to understand it more clearly."
},
{
"code": null,
"e": 1353,
"s": 1319,
"text": "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]"
},
{
"code": null,
"e": 1387,
"s": 1353,
"text": "[[1, 4, 7], [2, 5, 8], [3, 6, 9]]"
},
{
"code": null,
"e": 1464,
"s": 1387,
"text": "We can solve it in different ways. Let's see how to solve with normal loops."
},
{
"code": null,
"e": 1496,
"s": 1464,
"text": "Initialize the list with lists."
},
{
"code": null,
"e": 1522,
"s": 1496,
"text": "Initialize an empty list."
},
{
"code": null,
"e": 1556,
"s": 1522,
"text": "Initialize a variable index to 0."
},
{
"code": null,
"e": 1728,
"s": 1556,
"text": "Iterate over the sub list length timesAppend an empty list to the previous listIterate lists length times.Append the **lists[current_index][index]** to the **result[index]"
},
{
"code": null,
"e": 1770,
"s": 1728,
"text": "Append an empty list to the previous list"
},
{
"code": null,
"e": 1863,
"s": 1770,
"text": "Iterate lists length times.Append the **lists[current_index][index]** to the **result[index]"
},
{
"code": null,
"e": 1929,
"s": 1863,
"text": "Append the **lists[current_index][index]** to the **result[index]"
},
{
"code": null,
"e": 1947,
"s": 1929,
"text": "Print the result."
},
{
"code": null,
"e": 1958,
"s": 1947,
"text": " Live Demo"
},
{
"code": null,
"e": 2435,
"s": 1958,
"text": "# initializing the list\nlists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n# empty list\nresult = []\n# variable to 0\nindex = 0\n# iterating over the sub_list length (3) times\nfor i in range(len(lists[0])):\n # appending an empty sub_list\n result.append([])\n # iterating lists length (3) times\n for j in range(len(lists)):\n # adding the element to the result\n result[index].append(lists[j][index])\n# moving to the next index\nindex += 1\n# printing the result\nprint(result)"
},
{
"code": null,
"e": 2502,
"s": 2435,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 2536,
"s": 2502,
"text": "[[1, 4, 7], [2, 5, 8], [3, 6, 9]]"
},
{
"code": null,
"e": 2688,
"s": 2536,
"text": "We can solve it using the zip function without any effort. The zip function gives you all the index elements in a tuple as we want. Let's see the code."
},
{
"code": null,
"e": 2699,
"s": 2688,
"text": " Live Demo"
},
{
"code": null,
"e": 2822,
"s": 2699,
"text": "# initializing the list\nlists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n# using the zip and printing it\nprint(list(zip(*lists)))"
},
{
"code": null,
"e": 2889,
"s": 2822,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 2923,
"s": 2889,
"text": "[(1, 4, 7), (2, 5, 8), (3, 6, 9)]"
},
{
"code": null,
"e": 3113,
"s": 2923,
"text": "We can convert the tuples into the list by iterating through the lists. It can be done differently.will use another function called map to convert all tuples into lists. It's one line code."
},
{
"code": null,
"e": 3124,
"s": 3113,
"text": " Live Demo"
},
{
"code": null,
"e": 3258,
"s": 3124,
"text": "# initializing the list\nlists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]\n# using the zip and printing it\nprint(list(map(list, zip(*lists))))"
},
{
"code": null,
"e": 3325,
"s": 3258,
"text": "If you run the above code, then you will get the following result."
},
{
"code": null,
"e": 3359,
"s": 3325,
"text": "[[1, 4, 7], [2, 5, 8], [3, 6, 9]]"
},
{
"code": null,
"e": 3478,
"s": 3359,
"text": "We have used map to iterate through the list and convert each tuple into the list. You can do same with loops. Try it."
},
{
"code": null,
"e": 3555,
"s": 3478,
"text": "If you have any doubts in the tutorial, mention them in the comment section."
}
] |
An Easy Beginners Guide to SQLite in Python and Pandas | by Julia Kho | Towards Data Science | Welcome to an easy beginners guide to SQLite. In this article, you’ll learn about what SQLite is, how to connect to databases, create tables, insert and query for data, and access SQLite in Pandas. I am assuming that you have a basic understanding of SQL and my focus in the article will be on how to use SQLite in Python.
SQLite is a software library that provides us with an open-source relational data management system where we can store large amounts of data.
It is easy to set up, it’s self-contained (requires minimal support), and does not require a server. A SQLite database is literally just a plain file, which makes it easily accessible and portable. Given the simplicity of SQLite, it is the most widely deployed database engine.
SQLite is great for many reasons, but in practice, you shouldn’t use SQLite if you are handling a gigantic amount of data. The database is actually limited to 281 terabytes.
If you would to follow along, you can download a copy of my Jupyter Notebook here.
We start by importing the SQLite library inside our python file. This library does not have to be downloaded as it should already be included in the standard library if you are using Python 2.5 and above.
import sqlite3 as db
Next, we can either connect to an existing database or create a new one if it doesn’t exist.
conn = db.connect('my_database.db')
Note that the SQLite engine maintains the database as a file with the extension .db. So the line of code above will connect to a file called my_database.db IF IT EXISTS in the folder. If it does not exist, a file called my_database.db will automatically be created on your computer as shown in the snippet above.
In order to interact with our database, we now have to create a cursor. This is what we will use to issue commands that will allow us to query or modify our database.
c = conn.cursor()
Now that we have our database connection and cursor created, we can now start interacting. Let’s create our first table in the database.
We use the method execute on the cursor c we created earlier and we pass in our SQL statement.
c.execute("CREATE TABLE employees (empid INTEGER PRIMARY KEY, firstname NVARCHAR(20), lastname NVARCHAR(20))")
The statement above will create a table called employees with three columns: empid, firstname, and lastname.
You can check that the table was successfully created with the following statements.
c.execute("SELECT name FROM sqlite_master WHERE type='table';")print(c.fetchall())
The select query above will show you all tables that are in your database. Note that the results of the query are not outputted if you only have the first statement. You have to use c.fetchall() in order for the results to show.
To populate the table, we have several options. If only inserting a few rows, you can use the following insert statements to input two rows into the employee table.
c.execute("INSERT INTO employees VALUES (12986,'Michael','Scott')")c.execute("INSERT INTO employees VALUES (12987,'Dwight','Schrute')")
If you have many rows to input into the table, consider making a list of tuples and using theexecutemany()command instead.
new_employees = [(12987, 'Jim', 'Halpert'), (12988, 'Pam', 'Beesly'), (12989, 'Andy', 'Bernard'), (12990, 'Kevin', 'Malone'), (12991, 'Toby', 'Flenderson'), (12992, 'Angela', 'Martin'), (12993, 'Stanley', 'Hudson')]c.executemany('INSERT INTO employees VALUES (?, ?, ?)', new_employees)
Notice that we’ve replaced our insert statement from earlier with (?, ?, ?). The question marks here represent placeholders for the three items that we are inputting into the table.
Let’s take a look at what’s in our table now. We can use the select statement inside the execute command similar to what we did previously.
From the output, we can see all our employees have been correctly inputted into the table. Hurray!
We’ve made a couple changes to our database, but they are not saved to the database just yet! These are just temporary modifications, so we have to make sure to commit those changes with the following command.
conn.commit()
If we don’t, the changes will be lost once we close the connection.
Lastly, it is always good practice for us to close both the cursor and connection once we are done. We can do so with the following commands.
c.close()conn.close()
One cool thing you can do is use both SQLite and Pandas. Pandas has a read_sql_query method that will allow you to return the data as a Pandas dataframe. From there, you can more easily manipulate the data in Pandas. Personally, I prefer bringing the data inside Pandas to work with.
We again have to first establish a connection to our database. Then we can use pd.read_sql_queryand save the output as a dataframe calleddf_employees.
#import libraryimport pandas as pdcon = db.connect('my_database.db')df_employees = pd.read_sql_query('select * from employees', con)
Now that it is a Pandas dataframe, you can use your usual pandas function to manipulate the data as you wish.
For example, let’s say that Stanley (last person in the table) was never meant to be hired and so we need to get rid of him from the table.
df_new = df_employees[:-1]
We can write our new dataframe back to SQLite and replace our original employee table. To write to SQLite, we use the method to_sql() on the new dataframe.
df_new.to_sql("employees", con, if_exists="replace")
We provide three parameters inside this method:
Name of the SQL tableThe connection to the databaseHow to behave if the table already exists. “Replace” will drop the original table. “Fail” will raise a value error in Python. “Append” will insert the data as new rows into the table
Name of the SQL table
The connection to the database
How to behave if the table already exists. “Replace” will drop the original table. “Fail” will raise a value error in Python. “Append” will insert the data as new rows into the table
To check that it worked as we expected, I can query the table again to see if Stanley has been removed. It has!
pd.read_sql_query ('select * from employees', con)
And just like before, once we’re done, let’s close the connection.
con.close()
That’s it! SQLite is pretty simple to use. If you are looking for a good database to practice SQL and/or SQLite, you can download the Chinook database here. More information about the data inside the Chinook database can be found here.
Thank you for reading! Let me know in the comments if you have questions or want to tell a SQL joke. | [
{
"code": null,
"e": 495,
"s": 172,
"text": "Welcome to an easy beginners guide to SQLite. In this article, you’ll learn about what SQLite is, how to connect to databases, create tables, insert and query for data, and access SQLite in Pandas. I am assuming that you have a basic understanding of SQL and my focus in the article will be on how to use SQLite in Python."
},
{
"code": null,
"e": 637,
"s": 495,
"text": "SQLite is a software library that provides us with an open-source relational data management system where we can store large amounts of data."
},
{
"code": null,
"e": 915,
"s": 637,
"text": "It is easy to set up, it’s self-contained (requires minimal support), and does not require a server. A SQLite database is literally just a plain file, which makes it easily accessible and portable. Given the simplicity of SQLite, it is the most widely deployed database engine."
},
{
"code": null,
"e": 1089,
"s": 915,
"text": "SQLite is great for many reasons, but in practice, you shouldn’t use SQLite if you are handling a gigantic amount of data. The database is actually limited to 281 terabytes."
},
{
"code": null,
"e": 1172,
"s": 1089,
"text": "If you would to follow along, you can download a copy of my Jupyter Notebook here."
},
{
"code": null,
"e": 1377,
"s": 1172,
"text": "We start by importing the SQLite library inside our python file. This library does not have to be downloaded as it should already be included in the standard library if you are using Python 2.5 and above."
},
{
"code": null,
"e": 1398,
"s": 1377,
"text": "import sqlite3 as db"
},
{
"code": null,
"e": 1491,
"s": 1398,
"text": "Next, we can either connect to an existing database or create a new one if it doesn’t exist."
},
{
"code": null,
"e": 1527,
"s": 1491,
"text": "conn = db.connect('my_database.db')"
},
{
"code": null,
"e": 1840,
"s": 1527,
"text": "Note that the SQLite engine maintains the database as a file with the extension .db. So the line of code above will connect to a file called my_database.db IF IT EXISTS in the folder. If it does not exist, a file called my_database.db will automatically be created on your computer as shown in the snippet above."
},
{
"code": null,
"e": 2007,
"s": 1840,
"text": "In order to interact with our database, we now have to create a cursor. This is what we will use to issue commands that will allow us to query or modify our database."
},
{
"code": null,
"e": 2025,
"s": 2007,
"text": "c = conn.cursor()"
},
{
"code": null,
"e": 2162,
"s": 2025,
"text": "Now that we have our database connection and cursor created, we can now start interacting. Let’s create our first table in the database."
},
{
"code": null,
"e": 2257,
"s": 2162,
"text": "We use the method execute on the cursor c we created earlier and we pass in our SQL statement."
},
{
"code": null,
"e": 2368,
"s": 2257,
"text": "c.execute(\"CREATE TABLE employees (empid INTEGER PRIMARY KEY, firstname NVARCHAR(20), lastname NVARCHAR(20))\")"
},
{
"code": null,
"e": 2477,
"s": 2368,
"text": "The statement above will create a table called employees with three columns: empid, firstname, and lastname."
},
{
"code": null,
"e": 2562,
"s": 2477,
"text": "You can check that the table was successfully created with the following statements."
},
{
"code": null,
"e": 2645,
"s": 2562,
"text": "c.execute(\"SELECT name FROM sqlite_master WHERE type='table';\")print(c.fetchall())"
},
{
"code": null,
"e": 2874,
"s": 2645,
"text": "The select query above will show you all tables that are in your database. Note that the results of the query are not outputted if you only have the first statement. You have to use c.fetchall() in order for the results to show."
},
{
"code": null,
"e": 3039,
"s": 2874,
"text": "To populate the table, we have several options. If only inserting a few rows, you can use the following insert statements to input two rows into the employee table."
},
{
"code": null,
"e": 3175,
"s": 3039,
"text": "c.execute(\"INSERT INTO employees VALUES (12986,'Michael','Scott')\")c.execute(\"INSERT INTO employees VALUES (12987,'Dwight','Schrute')\")"
},
{
"code": null,
"e": 3298,
"s": 3175,
"text": "If you have many rows to input into the table, consider making a list of tuples and using theexecutemany()command instead."
},
{
"code": null,
"e": 3584,
"s": 3298,
"text": "new_employees = [(12987, 'Jim', 'Halpert'), (12988, 'Pam', 'Beesly'), (12989, 'Andy', 'Bernard'), (12990, 'Kevin', 'Malone'), (12991, 'Toby', 'Flenderson'), (12992, 'Angela', 'Martin'), (12993, 'Stanley', 'Hudson')]c.executemany('INSERT INTO employees VALUES (?, ?, ?)', new_employees)"
},
{
"code": null,
"e": 3766,
"s": 3584,
"text": "Notice that we’ve replaced our insert statement from earlier with (?, ?, ?). The question marks here represent placeholders for the three items that we are inputting into the table."
},
{
"code": null,
"e": 3906,
"s": 3766,
"text": "Let’s take a look at what’s in our table now. We can use the select statement inside the execute command similar to what we did previously."
},
{
"code": null,
"e": 4005,
"s": 3906,
"text": "From the output, we can see all our employees have been correctly inputted into the table. Hurray!"
},
{
"code": null,
"e": 4215,
"s": 4005,
"text": "We’ve made a couple changes to our database, but they are not saved to the database just yet! These are just temporary modifications, so we have to make sure to commit those changes with the following command."
},
{
"code": null,
"e": 4229,
"s": 4215,
"text": "conn.commit()"
},
{
"code": null,
"e": 4297,
"s": 4229,
"text": "If we don’t, the changes will be lost once we close the connection."
},
{
"code": null,
"e": 4439,
"s": 4297,
"text": "Lastly, it is always good practice for us to close both the cursor and connection once we are done. We can do so with the following commands."
},
{
"code": null,
"e": 4461,
"s": 4439,
"text": "c.close()conn.close()"
},
{
"code": null,
"e": 4745,
"s": 4461,
"text": "One cool thing you can do is use both SQLite and Pandas. Pandas has a read_sql_query method that will allow you to return the data as a Pandas dataframe. From there, you can more easily manipulate the data in Pandas. Personally, I prefer bringing the data inside Pandas to work with."
},
{
"code": null,
"e": 4896,
"s": 4745,
"text": "We again have to first establish a connection to our database. Then we can use pd.read_sql_queryand save the output as a dataframe calleddf_employees."
},
{
"code": null,
"e": 5029,
"s": 4896,
"text": "#import libraryimport pandas as pdcon = db.connect('my_database.db')df_employees = pd.read_sql_query('select * from employees', con)"
},
{
"code": null,
"e": 5139,
"s": 5029,
"text": "Now that it is a Pandas dataframe, you can use your usual pandas function to manipulate the data as you wish."
},
{
"code": null,
"e": 5279,
"s": 5139,
"text": "For example, let’s say that Stanley (last person in the table) was never meant to be hired and so we need to get rid of him from the table."
},
{
"code": null,
"e": 5306,
"s": 5279,
"text": "df_new = df_employees[:-1]"
},
{
"code": null,
"e": 5462,
"s": 5306,
"text": "We can write our new dataframe back to SQLite and replace our original employee table. To write to SQLite, we use the method to_sql() on the new dataframe."
},
{
"code": null,
"e": 5515,
"s": 5462,
"text": "df_new.to_sql(\"employees\", con, if_exists=\"replace\")"
},
{
"code": null,
"e": 5563,
"s": 5515,
"text": "We provide three parameters inside this method:"
},
{
"code": null,
"e": 5797,
"s": 5563,
"text": "Name of the SQL tableThe connection to the databaseHow to behave if the table already exists. “Replace” will drop the original table. “Fail” will raise a value error in Python. “Append” will insert the data as new rows into the table"
},
{
"code": null,
"e": 5819,
"s": 5797,
"text": "Name of the SQL table"
},
{
"code": null,
"e": 5850,
"s": 5819,
"text": "The connection to the database"
},
{
"code": null,
"e": 6033,
"s": 5850,
"text": "How to behave if the table already exists. “Replace” will drop the original table. “Fail” will raise a value error in Python. “Append” will insert the data as new rows into the table"
},
{
"code": null,
"e": 6145,
"s": 6033,
"text": "To check that it worked as we expected, I can query the table again to see if Stanley has been removed. It has!"
},
{
"code": null,
"e": 6196,
"s": 6145,
"text": "pd.read_sql_query ('select * from employees', con)"
},
{
"code": null,
"e": 6263,
"s": 6196,
"text": "And just like before, once we’re done, let’s close the connection."
},
{
"code": null,
"e": 6275,
"s": 6263,
"text": "con.close()"
},
{
"code": null,
"e": 6511,
"s": 6275,
"text": "That’s it! SQLite is pretty simple to use. If you are looking for a good database to practice SQL and/or SQLite, you can download the Chinook database here. More information about the data inside the Chinook database can be found here."
}
] |
Python Functions, Explained.. Here is a more intuitive way of... | by Brunna Torino | Towards Data Science | We first learn about functions in high school mathematics. The general concept of functions in maths is that there is an input (let’s call it x) and an output (let’s call it y). We represent a mathematical function like this:
y = f(x)
where f(x) can be any transformation (such as adding, subtracting, multiplication, exponentials...) to the input we call x. One example could be:
y = 2x + 1
where the f represents the equation where we will take the output, multiply it by two and add one, and most importantly, we want to return it as y.
Why am I going back this far? Programming languages will always use fundamental mathematics concepts to build their structure and logic. If you understand what functions are in mathematics, you already understand what functions are in Python (and other programming languages too).
Let’s use the mathematical explanation above to help us understand how to write functions. Try to think about coding as a conversation with the computer, and Python as a means to express your commands step-by-step.
First, we need to define the name of the function, and the input x (just like our mathematical example). We write def from define, the function name (which you could think about as f in mathematics), and the input variable x. We call x the parameter of the function.
def my_function_name(x):
In maths, writing only f(x) will transform x but won’t assign the value of x to any variable that we can refer to later on. So we need to add a return statement to the end of the function:
def my_function_name(x): return y
We are using x and returning y, but what is the connection between the two? How do we calculate y?
If you think about coding as explaining your commands step-by-step, it makes sense for the function calculations to go after defining the function but before returning the value of y.
def my_function_name(x): y = 2*x + 1 return y
Are we done? Not yet!
The difference between defining a function and writing directly:
y = 2*x + 1print(y)
is that we can save functions if we want to use them later, with different values of x. If we want to use it the function in our script, we need to call it into action:
variable1 = my_function_name(4)
Notice anything different here? We are using 4 instead of x when we call the function. In fact, we want x to be equal to 4 at this time. We call 4 the argument of the function. The beauty of functions is that we don’t ever need to define globally what x is: x can take any value we write in between the parentheses when we call the function.
What about variable1? The same concept explained with x applies here: in this one time we are calling the function, we want variable1 to be y. This means that whatever y from our function turns out to be (2*4 + 1 = 9), we want that value to be assigned to variable1.
You can go on to use variable1 in the rest of your script just as if you had written this:
variable1 = 9
Going back to mathematics, let’s say you have a function with two inputs:
y = f(x,y)
You can do the same with Python functions, in the exact same way as maths:
def my_function_name(x,y): y = x + y return y
When calling functions, you need to be consistent with the number of inputs you initially used when defining it:
variable2 = my_function_name(1,2)
You can also not specify the number of arguments by writing *arg as the parameter when defining your function. This is where it differs a bit from mathematics: you can call as many arguments as you want to be used in the function. Here, we are creating a list and append all the numbers in the function arguments to the list.
def my_function_name(*arg): list_of_numbers = [] list_of_numbers.append(arg) return list_of_numbers
For example, if we called the function like this:
my_function_name(1,2,3,4,5,6,7,8,9)
you can expect this output:
Out: [1,2,3,4,5,6,7,8,9]
To illustrate how we would use functions in a more advanced topic, let’s go through an example of how to build a matrix calculator that will return the determinant of 2x2 matrices.
Here, I am defining the function name as matrix_calculator and passing 4 inputs (also known as parameters): x1,x2,y1 and y2 that are used to create the matrix called my_matrix. Next, I calculate the determinant and return it.
If I call the function with the arguments 1, 2, 3 and 4:
matrix_calculator(1,2,3,4)
I will get this output:
-2
Let’s make the calculator more advanced. What if the function could understand if you wanted to calculate the determinant of 2x2 or a 3x3 matrix depending on how many arguments you call the function with?
We will the numpy function np.linalg.det(A) to calculate the determinant, so we will start by importing the numpy package. Next, I will define the function called smart_matrix_calculator and will pass to the function as many arguments as I want by using *arg as the parameter. Then I will transform the numbers into a list, so that we can slice the list and create the matrix.
If the length of the numbers we passed is 9 (if len(arg) == 9) that means we want a 3x3 matrix that has 9 elements.
We transform it into a matrix by slicing the list in the following way:
first three numbers will be x1, y1 and z1 respectively
the next three numbers will be x2, y2 and z2
the last three numbers will be x3, y3 and z3
We transform it into an array in the same line, calculate the determinant, and finally return it at the end of the function.
If we call the function using the numbers (1,2,3,4,1,2,2,1,9) to produce a 3x3 matrix:
smart_matrix_calculator(1,2,3,4,1,2,2,1,9)
We can expect it to return:
Out: -51.0
If we call the function using the numbers (1,2,3,4) to produce a 2x2 matrix:
smart_matrix_calculator(1,2,3,4)
We can expect it to return:
-2.0
Thank you for reading. I hope my way of understanding what functions are and how they worked helped you to understand a bit more about this essential programming skill.
Let me know in the comments if you would like more tutorials about other Python topics! | [
{
"code": null,
"e": 398,
"s": 172,
"text": "We first learn about functions in high school mathematics. The general concept of functions in maths is that there is an input (let’s call it x) and an output (let’s call it y). We represent a mathematical function like this:"
},
{
"code": null,
"e": 407,
"s": 398,
"text": "y = f(x)"
},
{
"code": null,
"e": 553,
"s": 407,
"text": "where f(x) can be any transformation (such as adding, subtracting, multiplication, exponentials...) to the input we call x. One example could be:"
},
{
"code": null,
"e": 564,
"s": 553,
"text": "y = 2x + 1"
},
{
"code": null,
"e": 712,
"s": 564,
"text": "where the f represents the equation where we will take the output, multiply it by two and add one, and most importantly, we want to return it as y."
},
{
"code": null,
"e": 993,
"s": 712,
"text": "Why am I going back this far? Programming languages will always use fundamental mathematics concepts to build their structure and logic. If you understand what functions are in mathematics, you already understand what functions are in Python (and other programming languages too)."
},
{
"code": null,
"e": 1208,
"s": 993,
"text": "Let’s use the mathematical explanation above to help us understand how to write functions. Try to think about coding as a conversation with the computer, and Python as a means to express your commands step-by-step."
},
{
"code": null,
"e": 1475,
"s": 1208,
"text": "First, we need to define the name of the function, and the input x (just like our mathematical example). We write def from define, the function name (which you could think about as f in mathematics), and the input variable x. We call x the parameter of the function."
},
{
"code": null,
"e": 1500,
"s": 1475,
"text": "def my_function_name(x):"
},
{
"code": null,
"e": 1689,
"s": 1500,
"text": "In maths, writing only f(x) will transform x but won’t assign the value of x to any variable that we can refer to later on. So we need to add a return statement to the end of the function:"
},
{
"code": null,
"e": 1730,
"s": 1689,
"text": "def my_function_name(x): return y"
},
{
"code": null,
"e": 1829,
"s": 1730,
"text": "We are using x and returning y, but what is the connection between the two? How do we calculate y?"
},
{
"code": null,
"e": 2013,
"s": 1829,
"text": "If you think about coding as explaining your commands step-by-step, it makes sense for the function calculations to go after defining the function but before returning the value of y."
},
{
"code": null,
"e": 2063,
"s": 2013,
"text": "def my_function_name(x): y = 2*x + 1 return y"
},
{
"code": null,
"e": 2085,
"s": 2063,
"text": "Are we done? Not yet!"
},
{
"code": null,
"e": 2150,
"s": 2085,
"text": "The difference between defining a function and writing directly:"
},
{
"code": null,
"e": 2170,
"s": 2150,
"text": "y = 2*x + 1print(y)"
},
{
"code": null,
"e": 2339,
"s": 2170,
"text": "is that we can save functions if we want to use them later, with different values of x. If we want to use it the function in our script, we need to call it into action:"
},
{
"code": null,
"e": 2371,
"s": 2339,
"text": "variable1 = my_function_name(4)"
},
{
"code": null,
"e": 2713,
"s": 2371,
"text": "Notice anything different here? We are using 4 instead of x when we call the function. In fact, we want x to be equal to 4 at this time. We call 4 the argument of the function. The beauty of functions is that we don’t ever need to define globally what x is: x can take any value we write in between the parentheses when we call the function."
},
{
"code": null,
"e": 2980,
"s": 2713,
"text": "What about variable1? The same concept explained with x applies here: in this one time we are calling the function, we want variable1 to be y. This means that whatever y from our function turns out to be (2*4 + 1 = 9), we want that value to be assigned to variable1."
},
{
"code": null,
"e": 3071,
"s": 2980,
"text": "You can go on to use variable1 in the rest of your script just as if you had written this:"
},
{
"code": null,
"e": 3085,
"s": 3071,
"text": "variable1 = 9"
},
{
"code": null,
"e": 3159,
"s": 3085,
"text": "Going back to mathematics, let’s say you have a function with two inputs:"
},
{
"code": null,
"e": 3170,
"s": 3159,
"text": "y = f(x,y)"
},
{
"code": null,
"e": 3245,
"s": 3170,
"text": "You can do the same with Python functions, in the exact same way as maths:"
},
{
"code": null,
"e": 3295,
"s": 3245,
"text": "def my_function_name(x,y): y = x + y return y"
},
{
"code": null,
"e": 3408,
"s": 3295,
"text": "When calling functions, you need to be consistent with the number of inputs you initially used when defining it:"
},
{
"code": null,
"e": 3442,
"s": 3408,
"text": "variable2 = my_function_name(1,2)"
},
{
"code": null,
"e": 3768,
"s": 3442,
"text": "You can also not specify the number of arguments by writing *arg as the parameter when defining your function. This is where it differs a bit from mathematics: you can call as many arguments as you want to be used in the function. Here, we are creating a list and append all the numbers in the function arguments to the list."
},
{
"code": null,
"e": 3880,
"s": 3768,
"text": "def my_function_name(*arg): list_of_numbers = [] list_of_numbers.append(arg) return list_of_numbers"
},
{
"code": null,
"e": 3930,
"s": 3880,
"text": "For example, if we called the function like this:"
},
{
"code": null,
"e": 3966,
"s": 3930,
"text": "my_function_name(1,2,3,4,5,6,7,8,9)"
},
{
"code": null,
"e": 3994,
"s": 3966,
"text": "you can expect this output:"
},
{
"code": null,
"e": 4019,
"s": 3994,
"text": "Out: [1,2,3,4,5,6,7,8,9]"
},
{
"code": null,
"e": 4200,
"s": 4019,
"text": "To illustrate how we would use functions in a more advanced topic, let’s go through an example of how to build a matrix calculator that will return the determinant of 2x2 matrices."
},
{
"code": null,
"e": 4426,
"s": 4200,
"text": "Here, I am defining the function name as matrix_calculator and passing 4 inputs (also known as parameters): x1,x2,y1 and y2 that are used to create the matrix called my_matrix. Next, I calculate the determinant and return it."
},
{
"code": null,
"e": 4483,
"s": 4426,
"text": "If I call the function with the arguments 1, 2, 3 and 4:"
},
{
"code": null,
"e": 4510,
"s": 4483,
"text": "matrix_calculator(1,2,3,4)"
},
{
"code": null,
"e": 4534,
"s": 4510,
"text": "I will get this output:"
},
{
"code": null,
"e": 4537,
"s": 4534,
"text": "-2"
},
{
"code": null,
"e": 4742,
"s": 4537,
"text": "Let’s make the calculator more advanced. What if the function could understand if you wanted to calculate the determinant of 2x2 or a 3x3 matrix depending on how many arguments you call the function with?"
},
{
"code": null,
"e": 5119,
"s": 4742,
"text": "We will the numpy function np.linalg.det(A) to calculate the determinant, so we will start by importing the numpy package. Next, I will define the function called smart_matrix_calculator and will pass to the function as many arguments as I want by using *arg as the parameter. Then I will transform the numbers into a list, so that we can slice the list and create the matrix."
},
{
"code": null,
"e": 5235,
"s": 5119,
"text": "If the length of the numbers we passed is 9 (if len(arg) == 9) that means we want a 3x3 matrix that has 9 elements."
},
{
"code": null,
"e": 5307,
"s": 5235,
"text": "We transform it into a matrix by slicing the list in the following way:"
},
{
"code": null,
"e": 5362,
"s": 5307,
"text": "first three numbers will be x1, y1 and z1 respectively"
},
{
"code": null,
"e": 5407,
"s": 5362,
"text": "the next three numbers will be x2, y2 and z2"
},
{
"code": null,
"e": 5452,
"s": 5407,
"text": "the last three numbers will be x3, y3 and z3"
},
{
"code": null,
"e": 5577,
"s": 5452,
"text": "We transform it into an array in the same line, calculate the determinant, and finally return it at the end of the function."
},
{
"code": null,
"e": 5664,
"s": 5577,
"text": "If we call the function using the numbers (1,2,3,4,1,2,2,1,9) to produce a 3x3 matrix:"
},
{
"code": null,
"e": 5707,
"s": 5664,
"text": "smart_matrix_calculator(1,2,3,4,1,2,2,1,9)"
},
{
"code": null,
"e": 5735,
"s": 5707,
"text": "We can expect it to return:"
},
{
"code": null,
"e": 5746,
"s": 5735,
"text": "Out: -51.0"
},
{
"code": null,
"e": 5823,
"s": 5746,
"text": "If we call the function using the numbers (1,2,3,4) to produce a 2x2 matrix:"
},
{
"code": null,
"e": 5856,
"s": 5823,
"text": "smart_matrix_calculator(1,2,3,4)"
},
{
"code": null,
"e": 5884,
"s": 5856,
"text": "We can expect it to return:"
},
{
"code": null,
"e": 5889,
"s": 5884,
"text": "-2.0"
},
{
"code": null,
"e": 6058,
"s": 5889,
"text": "Thank you for reading. I hope my way of understanding what functions are and how they worked helped you to understand a bit more about this essential programming skill."
}
] |
Create a temporary file in Java | A temporary file can be created using the method java.io.File.createTempFile(). This method requires two parameters i.e. the prefix to define the file name and the suffix to define the file extension. It also returns the abstract path name for the temporary file created.
A program that demonstrates this is given as follows −
Live Demo
import java.io.File;
public class Demo {
public static void main(String[] args) throws Exception {
File file = File.createTempFile("temp", null);
System.out.println(file.getAbsolutePath());
file.deleteOnExit();
}
}
The output of the above program is as follows −
C:\Users\amit_\AppData\Local\Temp\temp6072597842246154962.tmp
Now let us understand the above program.
A temporary file is created using the method java.io.File.createTempFile(). Then the file path is displayed. Also, the method java.io.File.deleteOnExit() is used to delete the temporary file after the program ends. A code snippet that demonstrates this is given as follows −
File file = File.createTempFile("temp", null);
System.out.println(file.getAbsolutePath());
file.deleteOnExit(); | [
{
"code": null,
"e": 1334,
"s": 1062,
"text": "A temporary file can be created using the method java.io.File.createTempFile(). This method requires two parameters i.e. the prefix to define the file name and the suffix to define the file extension. It also returns the abstract path name for the temporary file created."
},
{
"code": null,
"e": 1389,
"s": 1334,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1400,
"s": 1389,
"text": " Live Demo"
},
{
"code": null,
"e": 1639,
"s": 1400,
"text": "import java.io.File;\npublic class Demo {\n public static void main(String[] args) throws Exception {\n File file = File.createTempFile(\"temp\", null);\n System.out.println(file.getAbsolutePath());\n file.deleteOnExit();\n }\n}"
},
{
"code": null,
"e": 1687,
"s": 1639,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 1749,
"s": 1687,
"text": "C:\\Users\\amit_\\AppData\\Local\\Temp\\temp6072597842246154962.tmp"
},
{
"code": null,
"e": 1790,
"s": 1749,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 2065,
"s": 1790,
"text": "A temporary file is created using the method java.io.File.createTempFile(). Then the file path is displayed. Also, the method java.io.File.deleteOnExit() is used to delete the temporary file after the program ends. A code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 2177,
"s": 2065,
"text": "File file = File.createTempFile(\"temp\", null);\nSystem.out.println(file.getAbsolutePath());\nfile.deleteOnExit();"
}
] |
Javascript - Page Printing | Many times you would like to give a button at your webpage to print out the content of that web page via an actual printer.
JavaScript helps you to implement this functionality using print function of window object.
The JavaScript print function window.print() will print the current web page when executed. You can call this function directly using onclick event as follows:
<head>
<script type="text/javascript">
<!--
//-->
</script>
</head>
<body>
<form>
<input type="button" value="Print" onClick="window.print()" />
</form>
</body>
This will produce following button which let you print this page. Try it by clicking:
This serves your purpose to get page printed out, but this is not a recommended way of giving printing facility. You can do one of the followings to make a page printer friendly:
Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example.
Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example.
If you do not want to keep extra copy of a page then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other script in background to purge printable text and display for final printing. Our site is using same method to give print facility to our site visitors. Check Example.
If you do not want to keep extra copy of a page then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other script in background to purge printable text and display for final printing. Our site is using same method to give print facility to our site visitors. Check Example.
If someone is providing none of the above facilities then you can use browser's standard toolbar to get web pages printed out. Follow the link as follows:
File --> Print --> Click OK button.
Content available at TutorialsPoint.COM
Advertisements
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2590,
"s": 2466,
"text": "Many times you would like to give a button at your webpage to print out the content of that web page via an actual printer."
},
{
"code": null,
"e": 2682,
"s": 2590,
"text": "JavaScript helps you to implement this functionality using print function of window object."
},
{
"code": null,
"e": 2842,
"s": 2682,
"text": "The JavaScript print function window.print() will print the current web page when executed. You can call this function directly using onclick event as follows:"
},
{
"code": null,
"e": 3004,
"s": 2842,
"text": "<head>\n<script type=\"text/javascript\">\n<!--\n//-->\n</script>\n</head>\n<body>\n<form>\n<input type=\"button\" value=\"Print\" onClick=\"window.print()\" />\n</form>\n</body>\n"
},
{
"code": null,
"e": 3090,
"s": 3004,
"text": "This will produce following button which let you print this page. Try it by clicking:"
},
{
"code": null,
"e": 3274,
"s": 3094,
"text": "This serves your purpose to get page printed out, but this is not a recommended way of giving printing facility. You can do one of the followings to make a page printer friendly:"
},
{
"code": null,
"e": 3414,
"s": 3274,
"text": "Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example."
},
{
"code": null,
"e": 3554,
"s": 3414,
"text": "Make a copy of the page and leave out unwanted text and graphics, then link to that printer friendly page from the original. Check Example."
},
{
"code": null,
"e": 3931,
"s": 3554,
"text": "If you do not want to keep extra copy of a page then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other script in background to purge printable text and display for final printing. Our site is using same method to give print facility to our site visitors. Check Example.\n"
},
{
"code": null,
"e": 4307,
"s": 3931,
"text": "If you do not want to keep extra copy of a page then you can mark your printable text using proper comments like <!-- PRINT STARTS HERE -->..... <!-- PRINT ENDS HERE --> and then you can use PERL or any other script in background to purge printable text and display for final printing. Our site is using same method to give print facility to our site visitors. Check Example."
},
{
"code": null,
"e": 4462,
"s": 4307,
"text": "If someone is providing none of the above facilities then you can use browser's standard toolbar to get web pages printed out. Follow the link as follows:"
},
{
"code": null,
"e": 4500,
"s": 4462,
"text": "File --> Print --> Click OK button."
},
{
"code": null,
"e": 4540,
"s": 4500,
"text": "Content available at TutorialsPoint.COM"
},
{
"code": null,
"e": 4557,
"s": 4540,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 4592,
"s": 4557,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4606,
"s": 4592,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4640,
"s": 4606,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 4654,
"s": 4640,
"text": " Lets Kode It"
},
{
"code": null,
"e": 4689,
"s": 4654,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4706,
"s": 4689,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4741,
"s": 4706,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 4758,
"s": 4741,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 4791,
"s": 4758,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 4819,
"s": 4791,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4853,
"s": 4819,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 4881,
"s": 4853,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 4888,
"s": 4881,
"text": " Print"
},
{
"code": null,
"e": 4899,
"s": 4888,
"text": " Add Notes"
}
] |
Sum triangle from an array in C programming | The sum triangle from an array is a triangle that is made by decreasing the number of elements of the array one by one and the new array that is formed is with integers that are the sum of adjacent integers of the existing array. This procedure continues until only one element remains in the array.
Let's take an example to explain the content better,
Array = [3,5,7,8,9]
Output
[106]
[47,59]
[20,27,32]
[8,12,15,17]
[3,5,7,8,9]
Explanation
For the first array : ( 3 + 5 = 8), ( 5 + 7 = 12), ( 7 + 8 = 15),( 8 + 9 = 17)
For the second array: 8 + 12 = 20 , 12 + 15 = 27 , 15 + 17 = 32
For the third array: 20 + 27 = 47 , 27 + 32 = 59
For the final array: 47 + 59 = 106
The code runs as it is shown in the example explanation. So for this we need a recursive function that will call itself for every array.
#include<stdio.h>
void printTriangle(int arr[] , int n) {
if (n < 1) {
return;
}
int temp[n - 1];
for (int i = 0; i < n - 1; i++) {
int x = arr[i] + arr[i + 1];
temp[i] = x;
}
printTriangle(temp, n - 1);
for (int i = 0; i < n ; i++) {
if(i == n - 1)
printf("%d ",arr[i]);
else
printf("%d, ",arr[i]);
}
printf("\n");
}
int main() {
int arr[] = { 3,5,7,8,9};
int n = sizeof(arr) / sizeof(arr[0]);
printTriangle(arr, n);
}
106
47, 59
20, 27, 32
8, 12, 15, 17
3, 5, 7, 8, 9 | [
{
"code": null,
"e": 1362,
"s": 1062,
"text": "The sum triangle from an array is a triangle that is made by decreasing the number of elements of the array one by one and the new array that is formed is with integers that are the sum of adjacent integers of the existing array. This procedure continues until only one element remains in the array."
},
{
"code": null,
"e": 1415,
"s": 1362,
"text": "Let's take an example to explain the content better,"
},
{
"code": null,
"e": 1435,
"s": 1415,
"text": "Array = [3,5,7,8,9]"
},
{
"code": null,
"e": 1442,
"s": 1435,
"text": "Output"
},
{
"code": null,
"e": 1492,
"s": 1442,
"text": "[106]\n[47,59]\n[20,27,32]\n[8,12,15,17]\n[3,5,7,8,9]"
},
{
"code": null,
"e": 1504,
"s": 1492,
"text": "Explanation"
},
{
"code": null,
"e": 1731,
"s": 1504,
"text": "For the first array : ( 3 + 5 = 8), ( 5 + 7 = 12), ( 7 + 8 = 15),( 8 + 9 = 17)\nFor the second array: 8 + 12 = 20 , 12 + 15 = 27 , 15 + 17 = 32\nFor the third array: 20 + 27 = 47 , 27 + 32 = 59\nFor the final array: 47 + 59 = 106"
},
{
"code": null,
"e": 1868,
"s": 1731,
"text": "The code runs as it is shown in the example explanation. So for this we need a recursive function that will call itself for every array."
},
{
"code": null,
"e": 2372,
"s": 1868,
"text": "#include<stdio.h>\nvoid printTriangle(int arr[] , int n) {\n if (n < 1) {\n return;\n }\n int temp[n - 1];\n for (int i = 0; i < n - 1; i++) {\n int x = arr[i] + arr[i + 1];\n temp[i] = x;\n }\n printTriangle(temp, n - 1);\n for (int i = 0; i < n ; i++) {\n if(i == n - 1)\n printf(\"%d \",arr[i]);\n else\n printf(\"%d, \",arr[i]);\n }\n printf(\"\\n\");\n}\nint main() {\n int arr[] = { 3,5,7,8,9};\n int n = sizeof(arr) / sizeof(arr[0]);\n printTriangle(arr, n);\n}"
},
{
"code": null,
"e": 2422,
"s": 2372,
"text": "106\n47, 59\n20, 27, 32\n8, 12, 15, 17\n3, 5, 7, 8, 9"
}
] |
Python 3 - Number cos() Method | The cos() method returns the cosine of x radians.
Following is the syntax for cos() method −
cos(x)
Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object.
x − This must be a numeric value.
This method returns a numeric value between -1 and 1, which represents the cosine of the angle.
The following example shows the usage of cos() method.
#!/usr/bin/python3
import math
print ("cos(3) : ", math.cos(3))
print ("cos(-3) : ", math.cos(-3))
print ("cos(0) : ", math.cos(0))
print ("cos(math.pi) : ", math.cos(math.pi))
print ("cos(2*math.pi) : ", math.cos(2*math.pi))
When we run the above program, it produces the following result −
cos(3) : -0.9899924966
cos(-3) : -0.9899924966
cos(0) : 1.0
cos(math.pi) : -1.0
cos(2*math.pi) : 1.0
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": 2390,
"s": 2340,
"text": "The cos() method returns the cosine of x radians."
},
{
"code": null,
"e": 2433,
"s": 2390,
"text": "Following is the syntax for cos() method −"
},
{
"code": null,
"e": 2441,
"s": 2433,
"text": "cos(x)\n"
},
{
"code": null,
"e": 2588,
"s": 2441,
"text": "Note − This function is not accessible directly, so we need to import math module and then we need to call this function using math static object."
},
{
"code": null,
"e": 2622,
"s": 2588,
"text": "x − This must be a numeric value."
},
{
"code": null,
"e": 2718,
"s": 2622,
"text": "This method returns a numeric value between -1 and 1, which represents the cosine of the angle."
},
{
"code": null,
"e": 2773,
"s": 2718,
"text": "The following example shows the usage of cos() method."
},
{
"code": null,
"e": 3005,
"s": 2773,
"text": "#!/usr/bin/python3\nimport math\n\nprint (\"cos(3) : \", math.cos(3))\nprint (\"cos(-3) : \", math.cos(-3))\nprint (\"cos(0) : \", math.cos(0))\nprint (\"cos(math.pi) : \", math.cos(math.pi))\nprint (\"cos(2*math.pi) : \", math.cos(2*math.pi))"
},
{
"code": null,
"e": 3071,
"s": 3005,
"text": "When we run the above program, it produces the following result −"
},
{
"code": null,
"e": 3178,
"s": 3071,
"text": "cos(3) : -0.9899924966\ncos(-3) : -0.9899924966\ncos(0) : 1.0\ncos(math.pi) : -1.0\ncos(2*math.pi) : 1.0\n"
},
{
"code": null,
"e": 3215,
"s": 3178,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3231,
"s": 3215,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3264,
"s": 3231,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3283,
"s": 3264,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3318,
"s": 3283,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3340,
"s": 3318,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3374,
"s": 3340,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3402,
"s": 3374,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3437,
"s": 3402,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3451,
"s": 3437,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3484,
"s": 3451,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3501,
"s": 3484,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3508,
"s": 3501,
"text": " Print"
},
{
"code": null,
"e": 3519,
"s": 3508,
"text": " Add Notes"
}
] |
Huffman Encoding | Practice | GeeksforGeeks | Given a string S of distinct character of size N and their corresponding frequency f[ ] i.e. character S[i] has f[i] frequency. Your task is to build the Huffman tree print all the huffman codes in preorder traversal of the tree.
Note: While merging if two nodes have the same value, then the node which occurs at first will be taken on the left of Binary Tree and the other one to the right, otherwise Node with less value will be taken on the left of the subtree and other one to the right.
Example 1:
S = "abcdef"
f[] = {5, 9, 12, 13, 16, 45}
Output:
0 100 101 1100 1101 111
Explanation:
HuffmanCodes will be:
f : 0
c : 100
d : 101
a : 1100
b : 1101
e : 111
Hence printing them in the PreOrder of Binary
Tree.
Your Task:
You don't need to read or print anything. Your task is to complete the function huffmanCodes() which takes the given string S, frequency array f[ ] and number of characters N as input parameters and returns a vector of strings containing all huffman codes in order of preorder traversal of the tree.
Expected Time complexity: O(N * LogN)
Expected Space complexity: O(N)
Constraints:
1 ≤ N ≤ 26
0
utsavj5022 weeks ago
#User function Template for python3
from heapq import heapify, heappush, heappop
class Node :
def __init__(self,freq,symbol,left=None,right=None) :
self.freq=freq
self.symbol=symbol
self.left=left
self.right=right
def __lt__(self, other):
return self.freq < other.freq
class Solution:
def traverse(self,root,ans,curr) :
if(root==None) : return;
if(root.symbol!="$" and root.left==None and root.right==None) :
ans.append(curr)
return;
self.traverse(root.left,ans,curr+'0')
self.traverse(root.right,ans,curr+'1')
def huffmanCodes(self,S,f,N):
heap=[]
heapify(heap)
for i in range(N) :
heappush(heap,Node(f[i],S[i]))
while len(heap)>1 :
left=heappop(heap)
right=heappop(heap)
node=Node(left.freq+right.freq,"$",left,right)
heappush(heap,node)
ans=[]
self.traverse(heappop(heap),ans,"")
return ans
# Code here
#{
# Driver Code Starts
#Initial Template for Python 3
if __name__ == '__main__':
t=int(input())
for i in range(t):
S= input()
N= len(S);
f= [int(x) for x in input().split()]
ob = Solution()
ans = ob.huffmanCodes(S,f,N)
for i in ans:
print(i, end = " ")
print()
# } Driver Code Ends
0
revolverocelot3 weeks ago
For C++. Athough using greater<int> gurantees the constraint mentioned in the ‘note’ of this question. However after running a test case I saw it actually violates it, which results in the testcase getting failed.
So instead of greater<>, while intialising prioirty_queue, define your own comparator block as under
struct comp { bool operator()( yourDataType a, yourDataType b) { return a→data > b→data; } };
0
sunboykenneth1 month ago
class HuffmanNode {
public:
int weight;
char charContent;
HuffmanNode* leftChild;
HuffmanNode* rightChild;
public:
HuffmanNode (char charContent, int weight) {
this->charContent = charContent;
this->weight = weight;
leftChild = rightChild = NULL;
}
};
class CompareHuffmanNode {
public:
bool operator()(HuffmanNode* const& p1, HuffmanNode* const& p2)
{
return p1->weight > p2->weight;
}
};
class Solution
{
private:
void fetchAllEncodes(const HuffmanNode *root, string &path, vector<string> &resultCollection) {
if (root->leftChild == NULL && root->rightChild == NULL) {
resultCollection.push_back(path);
return;
}
path += '0';
fetchAllEncodes((root->leftChild), path, resultCollection);
path.pop_back();
path += '1';
fetchAllEncodes((root->rightChild), path, resultCollection);
path.pop_back();
}
public:
vector<string> huffmanCodes(string S,vector<int> f,int N)
{
if (N == 0) {
return {};
}
if (N == 1) {
return {"0"};
}
priority_queue<HuffmanNode*, vector<HuffmanNode*>, CompareHuffmanNode> q;
for (int i = 0; i < N; i++) {
q.push(new HuffmanNode(S[i], f[i]));
}
while (q.size() > 1) {
HuffmanNode* node1 = q.top();
q.pop();
HuffmanNode* node2 = q.top();
q.pop();
HuffmanNode* combinedNode = new HuffmanNode('\0', node1->weight + node2->weight);
combinedNode->leftChild = node1;
combinedNode->rightChild = node2;
q.push(combinedNode);
}
HuffmanNode* root = q.top();
vector<string> resultCollection;
string path;
fetchAllEncodes(root, path, resultCollection);
return resultCollection;
}
};
0
harrypotter01 month ago
import heapq
from functools import total_ordering
@total_ordering
class Node(object):
def __init__(self, freq, char=None, left=None, right=None):
self.freq = freq
self.char = char
self.left = left
self.right = right
def __lt__(self, other):
return self.freq < other.freq
def __eq__(self, other):
return self.freq == other.freq
def __str__(self):
return '(' + str(self.freq) + ', ' + self.char + ')'
def __repr__(self):
return str(self)
def getCodes(root):
ans = []
def recurse(cur, path=''):
if not cur.left and not cur.right:
ans.append(path)
if cur.left:
recurse(cur.left, path+'0')
if cur.right:
recurse(cur.right, path+'1')
recurse(root)
return ans
class Solution:
def huffmanCodes(self, chars,freqs, n):
heap = []
for c, f in zip(chars, freqs):
heapq.heappush(heap, Node(f, c))
while len(heap) > 1:
node1 = heapq.heappop(heap)
node2 = heapq.heappop(heap)
heapq.heappush(heap, Node(node1.freq + node2.freq, None, node1, node2))
return (getCodes(heap[0]))
0
ashutosh442 months ago
Can anyone explains why StringBuilder doesnot work?
public void getString(ArrayList<String> a,Node root,StringBuilder s){ if(root.c != '$'){ a.add(String.valueOf(s)); return; } getString(a,root.left,s.append("0")); getString(a,root.right,s.append("1")); }
0
siddhant072 months ago
struct treeNode{
int val;
char symbol;
treeNode* left;
treeNode* right;
treeNode(int v, char c, treeNode* l = NULL, treeNode *r = NULL){
val = v;
symbol = c;
left = l;
right = r;
}
};
struct comp{
bool operator()(treeNode * node1 , treeNode* node2){
return node1->val > node2->val;
}
};
void preOrderTransversal(treeNode* root, vector<string> &ans, string curr = ""){
if(root == NULL){
return;
}
if(root->symbol != '$' && root->left == NULL && root->right == NULL){
ans.push_back(curr);
return;
}
preOrderTransversal(root->left, ans, curr + '0');
preOrderTransversal(root->right, ans, curr + '1');
return;
}
vector<string> huffmanCodes(string s,vector<int> f,int N)
{
priority_queue<treeNode*, vector<treeNode*>, comp> pq;
for(int i = 0; i < N; i++){
pq.push(new treeNode(f[i], s[i]));
}
while(pq.size() > 1){
treeNode *l = pq.top();
pq.pop();
treeNode *r = pq.top();
pq.pop();
treeNode* node = new treeNode(l->val + r->val, '$', l, r);
pq.push(node);
}
vector<string> ans;
preOrderTransversal(pq.top(), ans, "");
return ans;
}
+2
himanshukug19cs2 months ago
java solution
ArrayList<String> ans = new ArrayList<String>(); class Node implements Comparable<Node>{ int data; Node left; Node right; Node(int data){ this.data=data; this.left=left; this.right=right; } public int compareTo(Node o){ if(this.data == o.data){ return 1; } return this.data-o.data; } } void sol(Node root,String s){ if(root==null) return; if(root.left==null&&root.right==null){ ans.add(s); return; } if(root.left!=null) sol(root.left,s+"0"); if(root.right!=null) sol(root.right,s+"1"); }public ArrayList<String> huffmanCodes(String S, int f[], int N) { // Code hereNode root=null;PriorityQueue<Node> pq = new PriorityQueue<>();for(int i=0;i<N;i++){ Node n = new Node(f[i]); pq.add(n);}while(pq.size()>1){ Node l=pq.poll(); Node r=pq.poll(); root= new Node(l.data+r.data); root.left=l; root.right=r; pq.add(root); }root=pq.remove(); sol(root,""); return ans; }
+2
kumaarsahab4322 months ago
private:
//For making Huffman Tree
struct Node{
int data ;
Node *left, *right ;
Node(int x)
{
data=x ;
left=NULL ;
right=NULL ;
}
} ;
//For making a Min Heap
struct comp{
bool operator()(Node *a, Node *b){
return a->data > b->data;
}
};
public:
//For Encoding the Alphabets
void preorder(Node* root, vector<string> &ans, string c)
{
if(root==NULL) return ;
if(root->left==NULL and root->right==NULL)
{
ans.push_back(c) ;
return ;
}
preorder(root->left, ans, c+"0") ;
preorder(root->right, ans, c+"1") ;
}
vector<string> huffmanCodes(string S,vector<int> f,int N)
{
vector<string> ans ;
priority_queue<Node*, vector<Node*>, comp> pq ;
//For creating leaf nodes
for(int i=0 ; i<f.size() ; i++)
{
Node* temp=new Node(f[i]) ;
pq.push(temp) ;
}
//Creating the Complete Huffman tree
while(pq.size()>1)
{
Node* x=pq.top() ;
pq.pop() ;
Node* y=pq.top() ;
pq.pop() ;
Node* temp=new Node(x->data+y->data) ;
temp->left=x ;
temp->right=y ;
pq.push(temp) ;
}
preorder(pq.top(), ans, "") ;
return ans ;
}
0
balamurali16012 months ago
class Solution {
private static ArrayList<String> results = new ArrayList<>();
public ArrayList<String> huffmanCodes(String S, int f[], int N)
{
results = new ArrayList<>();
PriorityQueue<HuffManNode> priorityQueue = new PriorityQueue<>
(N, Comparator.comparingInt(o -> o.characterCount));
for (int i = 0; i < f.length; i++) {
HuffManNode node = new HuffManNode();
node.characterCount = f[i];
node.character = S.charAt(i);
priorityQueue.add(node);
}
HuffManNode root = null;
while (priorityQueue.size() > 1) {
HuffManNode firstNode = priorityQueue.poll();
HuffManNode secondNode = priorityQueue.poll();
HuffManNode newNode = new HuffManNode();
newNode.characterCount = firstNode.characterCount + secondNode.characterCount;
newNode.character = '-';
newNode.left = firstNode;
newNode.right = secondNode;
root = newNode;
priorityQueue.add(newNode);
}
printQueue(root, "");
return results;
}
private static void printQueue(HuffManNode root, String s) {
if (root.left == null && root.right == null && Character.isLetter(root.character)) {
results.add(s);
return;
}
printQueue(root.left, s + "0");
printQueue(root.right, s + "1");
}
static class HuffManNode {
char character;
int characterCount;
HuffManNode left;
HuffManNode right;
}
}
WHy this code not working?Input:
qwertyuiopasdfghjklzxcvbn 8 9 14 19 20 21 21 25 33 45 50 50 66 68 70 73 74 75 76 82 85 90 94 97 100
And Your Code's output is:
0000 0001 00100 001010 001011 0011 0100 0101 0110 0111 1000 100100 100101 10011 1010 1011 1100 1101 11100 11101 111100 1111010 11110110 11110111 11111
Its Correct output is:
0000 0001 00100 001010 001011 0011 0100 0101 0110 0111 1000 100100 100101 10011 1010 1011 1100 11010 11011 1110 111100 1111010 11110110 11110111 11111
Output Difference
0000 0001 00100 001010 001011 0011 0100 0101 0110 0111 1000 100100 100101 10011 1010 1011 1100 1101 11100 11101 111100 1111010 11110110 11110111 11111
+1
aloksinghbais022 months ago
C++ solution having time complexity as O(N*log(N)) and space complexity as O(N) is as follows :-
Note :- I have tried to solve using set but I got wrong answer so then I tried using priority queue and it got submitted.
If anyone else faces the same problem and get the solution then please respond.
Execution Time :- 0.0 / 1.6 sec
private: class Node{ public: int data; Node *left; Node *right; Node(int data){ this->data = data; left = right = nullptr; } }; struct comp{ bool operator()(Node *node1,Node *node2){ return node1->data > node2->data; } }; public: void preorder(Node *node,string c,vector<string> &ans){ if(!node) return; if(!node->left && !node->right){ ans.push_back(c); return; } preorder(node->left,c + '0',ans); preorder(node->right,c + '1',ans); } vector<string> huffmanCodes(string S,vector<int> f,int N){ priority_queue<Node*,vector<Node*>,comp> pq; for(int i = 0; i < N; i++){ Node *node = new Node(f[i]); pq.push(node); } while(pq.size() > 1){ Node *left = pq.top(); pq.pop(); Node *right = pq.top(); pq.pop(); Node *root = new Node(left->data + right->data); root->left = left; root->right = right; pq.push(root); } Node *root = pq.top(); pq.pop(); vector<string> ans; preorder(root,"",ans); return (ans); }private: class Node{ public: int data; Node *left; Node *right; Node(int data){ this->data = data; left = right = nullptr; } }; struct comp{ bool operator()(Node *node1,Node *node2){ return node1->data > node2->data; } }; public: void preorder(Node *node,string c,vector<string> &ans){ if(!node) return; if(!node->left && !node->right){ ans.push_back(c); return; } preorder(node->left,c + '0',ans); preorder(node->right,c + '1',ans); } vector<string> huffmanCodes(string S,vector<int> f,int N){ priority_queue<Node*,vector<Node*>,comp> pq; for(int i = 0; i < N; i++){ Node *node = new Node(f[i]); pq.push(node); } while(pq.size() > 1){ Node *left = pq.top(); pq.pop(); Node *right = pq.top(); pq.pop(); Node *root = new Node(left->data + right->data); root->left = left; root->right = right; pq.push(root); } Node *root = pq.top(); pq.pop(); vector<string> ans; preorder(root,"",ans); return (ans); }
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": 731,
"s": 238,
"text": "Given a string S of distinct character of size N and their corresponding frequency f[ ] i.e. character S[i] has f[i] frequency. Your task is to build the Huffman tree print all the huffman codes in preorder traversal of the tree.\nNote: While merging if two nodes have the same value, then the node which occurs at first will be taken on the left of Binary Tree and the other one to the right, otherwise Node with less value will be taken on the left of the subtree and other one to the right."
},
{
"code": null,
"e": 742,
"s": 731,
"text": "Example 1:"
},
{
"code": null,
"e": 954,
"s": 742,
"text": "S = \"abcdef\"\nf[] = {5, 9, 12, 13, 16, 45}\nOutput: \n0 100 101 1100 1101 111\nExplanation:\n\nHuffmanCodes will be:\nf : 0\nc : 100\nd : 101\na : 1100\nb : 1101\ne : 111\nHence printing them in the PreOrder of Binary \nTree."
},
{
"code": null,
"e": 1265,
"s": 954,
"text": "Your Task:\nYou don't need to read or print anything. Your task is to complete the function huffmanCodes() which takes the given string S, frequency array f[ ] and number of characters N as input parameters and returns a vector of strings containing all huffman codes in order of preorder traversal of the tree."
},
{
"code": null,
"e": 1337,
"s": 1265,
"text": "Expected Time complexity: O(N * LogN) \nExpected Space complexity: O(N) "
},
{
"code": null,
"e": 1361,
"s": 1337,
"text": "Constraints:\n1 ≤ N ≤ 26"
},
{
"code": null,
"e": 1363,
"s": 1361,
"text": "0"
},
{
"code": null,
"e": 1384,
"s": 1363,
"text": "utsavj5022 weeks ago"
},
{
"code": null,
"e": 2752,
"s": 1384,
"text": "#User function Template for python3\nfrom heapq import heapify, heappush, heappop\nclass Node : \n def __init__(self,freq,symbol,left=None,right=None) : \n self.freq=freq\n self.symbol=symbol\n self.left=left\n self.right=right\n def __lt__(self, other):\n return self.freq < other.freq\n\nclass Solution:\n def traverse(self,root,ans,curr) : \n if(root==None) : return;\n if(root.symbol!=\"$\" and root.left==None and root.right==None) : \n ans.append(curr)\n return;\n self.traverse(root.left,ans,curr+'0')\n self.traverse(root.right,ans,curr+'1')\n \n def huffmanCodes(self,S,f,N):\n heap=[]\n heapify(heap)\n for i in range(N) : \n heappush(heap,Node(f[i],S[i]))\n while len(heap)>1 : \n left=heappop(heap)\n right=heappop(heap)\n node=Node(left.freq+right.freq,\"$\",left,right)\n heappush(heap,node)\n ans=[]\n self.traverse(heappop(heap),ans,\"\")\n return ans\n # Code here\n\n#{ \n# Driver Code Starts\n#Initial Template for Python 3\n\n\nif __name__ == '__main__':\n\tt=int(input())\n\tfor i in range(t):\n\t\tS= input()\n\t\tN= len(S);\n\t\tf= [int(x) for x in input().split()]\n\t\tob = Solution()\n\t\tans = ob.huffmanCodes(S,f,N)\n\t\tfor i in ans:\n\t\t print(i, end = \" \")\n\t\tprint()\n# } Driver Code Ends"
},
{
"code": null,
"e": 2754,
"s": 2752,
"text": "0"
},
{
"code": null,
"e": 2780,
"s": 2754,
"text": "revolverocelot3 weeks ago"
},
{
"code": null,
"e": 2994,
"s": 2780,
"text": "For C++. Athough using greater<int> gurantees the constraint mentioned in the ‘note’ of this question. However after running a test case I saw it actually violates it, which results in the testcase getting failed."
},
{
"code": null,
"e": 3095,
"s": 2994,
"text": "So instead of greater<>, while intialising prioirty_queue, define your own comparator block as under"
},
{
"code": null,
"e": 3245,
"s": 3095,
"text": "struct comp { bool operator()( yourDataType a, yourDataType b) { return a→data > b→data; } };"
},
{
"code": null,
"e": 3247,
"s": 3245,
"text": "0"
},
{
"code": null,
"e": 3272,
"s": 3247,
"text": "sunboykenneth1 month ago"
},
{
"code": null,
"e": 5211,
"s": 3272,
"text": "class HuffmanNode {\npublic:\n int weight;\n char charContent;\n \n HuffmanNode* leftChild;\n HuffmanNode* rightChild;\n \npublic:\n HuffmanNode (char charContent, int weight) {\n this->charContent = charContent;\n this->weight = weight;\n leftChild = rightChild = NULL;\n }\n};\n\nclass CompareHuffmanNode {\npublic:\n bool operator()(HuffmanNode* const& p1, HuffmanNode* const& p2)\n {\n return p1->weight > p2->weight;\n }\n};\n\n\nclass Solution\n{\n private:\n void fetchAllEncodes(const HuffmanNode *root, string &path, vector<string> &resultCollection) {\n if (root->leftChild == NULL && root->rightChild == NULL) {\n resultCollection.push_back(path);\n return;\n }\n \n path += '0';\n fetchAllEncodes((root->leftChild), path, resultCollection);\n path.pop_back();\n path += '1';\n fetchAllEncodes((root->rightChild), path, resultCollection);\n path.pop_back();\n }\n \n\tpublic:\n\t\tvector<string> huffmanCodes(string S,vector<int> f,int N)\n\t\t{\n\t\t if (N == 0) {\n\t\t return {};\n\t\t }\n\t\t \n\t\t if (N == 1) {\n\t\t return {\"0\"};\n\t\t }\n\t\t \n\t\t priority_queue<HuffmanNode*, vector<HuffmanNode*>, CompareHuffmanNode> q;\n\t\t \n\t\t for (int i = 0; i < N; i++) {\n\t\t q.push(new HuffmanNode(S[i], f[i]));\n\t\t }\n\t\t\n\t\t while (q.size() > 1) {\n\t\t HuffmanNode* node1 = q.top();\n\t\t q.pop();\n\t\t HuffmanNode* node2 = q.top();\n\t\t q.pop();\n\t\t \n\t\t HuffmanNode* combinedNode = new HuffmanNode('\\0', node1->weight + node2->weight);\n\t\t combinedNode->leftChild = node1;\n\t\t combinedNode->rightChild = node2;\n\t\n\t\t q.push(combinedNode);\n\t\t }\n\t\t \n\t\t HuffmanNode* root = q.top();\n\t\t vector<string> resultCollection;\n\t\t string path;\n\t\t \n\t\t fetchAllEncodes(root, path, resultCollection);\n\t\t return resultCollection;\n\t\t}\n};"
},
{
"code": null,
"e": 5213,
"s": 5211,
"text": "0"
},
{
"code": null,
"e": 5237,
"s": 5213,
"text": "harrypotter01 month ago"
},
{
"code": null,
"e": 6434,
"s": 5237,
"text": "import heapq\nfrom functools import total_ordering\n@total_ordering\nclass Node(object):\n def __init__(self, freq, char=None, left=None, right=None):\n self.freq = freq\n self.char = char\n self.left = left\n self.right = right\n \n def __lt__(self, other):\n return self.freq < other.freq\n \n def __eq__(self, other):\n return self.freq == other.freq\n \n def __str__(self):\n return '(' + str(self.freq) + ', ' + self.char + ')'\n \n def __repr__(self):\n return str(self)\ndef getCodes(root):\n ans = []\n def recurse(cur, path=''):\n if not cur.left and not cur.right:\n ans.append(path)\n if cur.left:\n recurse(cur.left, path+'0')\n if cur.right:\n recurse(cur.right, path+'1')\n recurse(root)\n return ans\nclass Solution:\n def huffmanCodes(self, chars,freqs, n):\n heap = []\n for c, f in zip(chars, freqs):\n heapq.heappush(heap, Node(f, c))\n \n while len(heap) > 1:\n node1 = heapq.heappop(heap)\n node2 = heapq.heappop(heap)\n heapq.heappush(heap, Node(node1.freq + node2.freq, None, node1, node2))\n return (getCodes(heap[0]))\n "
},
{
"code": null,
"e": 6436,
"s": 6434,
"text": "0"
},
{
"code": null,
"e": 6459,
"s": 6436,
"text": "ashutosh442 months ago"
},
{
"code": null,
"e": 6511,
"s": 6459,
"text": "Can anyone explains why StringBuilder doesnot work?"
},
{
"code": null,
"e": 6763,
"s": 6513,
"text": "public void getString(ArrayList<String> a,Node root,StringBuilder s){ if(root.c != '$'){ a.add(String.valueOf(s)); return; } getString(a,root.left,s.append(\"0\")); getString(a,root.right,s.append(\"1\")); }"
},
{
"code": null,
"e": 6767,
"s": 6765,
"text": "0"
},
{
"code": null,
"e": 6790,
"s": 6767,
"text": "siddhant072 months ago"
},
{
"code": null,
"e": 8224,
"s": 6790,
"text": "struct treeNode{\n\t int val;\n\t char symbol;\n\t treeNode* left;\n\t treeNode* right;\n\t treeNode(int v, char c, treeNode* l = NULL, treeNode *r = NULL){\n\t val = v;\n\t symbol = c;\n\t left = l;\n\t right = r;\n\t }\n\t };\n\t\n\t\n\t struct comp{\n\t bool operator()(treeNode * node1 , treeNode* node2){\n\t return node1->val > node2->val;\n\t }\n\t };\n\t \n\t void preOrderTransversal(treeNode* root, vector<string> &ans, string curr = \"\"){\n\t if(root == NULL){\n\t return;\n\t }\n\t if(root->symbol != '$' && root->left == NULL && root->right == NULL){\n\t ans.push_back(curr);\n\t return;\n\t }\n\t preOrderTransversal(root->left, ans, curr + '0');\n\t preOrderTransversal(root->right, ans, curr + '1');\n\t return;\n\t }\n\t \n\t\n\t\tvector<string> huffmanCodes(string s,vector<int> f,int N)\n\t\t{\n\t\t priority_queue<treeNode*, vector<treeNode*>, comp> pq;\n\t\t for(int i = 0; i < N; i++){\n\t\t pq.push(new treeNode(f[i], s[i]));\n\t\t }\n\t\t while(pq.size() > 1){\n\t\t treeNode *l = pq.top();\n\t\t pq.pop();\n\t\t treeNode *r = pq.top();\n\t\t pq.pop();\n\t\t treeNode* node = new treeNode(l->val + r->val, '$', l, r);\n\t\t pq.push(node);\n\t\t }\n\t\t vector<string> ans;\n\t\t preOrderTransversal(pq.top(), ans, \"\");\n\t\t return ans;\n\t\t}"
},
{
"code": null,
"e": 8227,
"s": 8224,
"text": "+2"
},
{
"code": null,
"e": 8255,
"s": 8227,
"text": "himanshukug19cs2 months ago"
},
{
"code": null,
"e": 8269,
"s": 8255,
"text": "java solution"
},
{
"code": null,
"e": 9378,
"s": 8269,
"text": "ArrayList<String> ans = new ArrayList<String>(); class Node implements Comparable<Node>{ int data; Node left; Node right; Node(int data){ this.data=data; this.left=left; this.right=right; } public int compareTo(Node o){ if(this.data == o.data){ return 1; } return this.data-o.data; } } void sol(Node root,String s){ if(root==null) return; if(root.left==null&&root.right==null){ ans.add(s); return; } if(root.left!=null) sol(root.left,s+\"0\"); if(root.right!=null) sol(root.right,s+\"1\"); }public ArrayList<String> huffmanCodes(String S, int f[], int N) { // Code hereNode root=null;PriorityQueue<Node> pq = new PriorityQueue<>();for(int i=0;i<N;i++){ Node n = new Node(f[i]); pq.add(n);}while(pq.size()>1){ Node l=pq.poll(); Node r=pq.poll(); root= new Node(l.data+r.data); root.left=l; root.right=r; pq.add(root); }root=pq.remove(); sol(root,\"\"); return ans; } "
},
{
"code": null,
"e": 9381,
"s": 9378,
"text": "+2"
},
{
"code": null,
"e": 9408,
"s": 9381,
"text": "kumaarsahab4322 months ago"
},
{
"code": null,
"e": 10828,
"s": 9408,
"text": "private: \n\t//For making Huffman Tree\n struct Node{\n int data ;\n Node *left, *right ;\n Node(int x)\n {\n data=x ;\n left=NULL ;\n right=NULL ;\n }\n } ;\n \n //For making a Min Heap\n struct comp{\n bool operator()(Node *a, Node *b){\n return a->data > b->data;\n }\n };\n\tpublic:\n\t\t\t\n\t\t//For Encoding the Alphabets\n\t void preorder(Node* root, vector<string> &ans, string c)\n\t {\n\t if(root==NULL) return ;\n\t if(root->left==NULL and root->right==NULL)\n\t {\n\t ans.push_back(c) ;\n\t return ; \n\t }\n\t preorder(root->left, ans, c+\"0\") ;\n\t preorder(root->right, ans, c+\"1\") ;\n\t }\n\t\tvector<string> huffmanCodes(string S,vector<int> f,int N)\n\t\t{\n\t\t vector<string> ans ;\n\t\t priority_queue<Node*, vector<Node*>, comp> pq ;\n\t\t \n\t\t //For creating leaf nodes\n\t\t for(int i=0 ; i<f.size() ; i++)\n\t\t {\n\t\t Node* temp=new Node(f[i]) ;\n\t\t pq.push(temp) ;\n\t\t }\n\t\t \n\t\t //Creating the Complete Huffman tree\n\t\t while(pq.size()>1)\n\t\t {\n\t\t Node* x=pq.top() ;\n\t\t pq.pop() ;\n\t\t Node* y=pq.top() ;\n\t\t pq.pop() ;\n\t\t Node* temp=new Node(x->data+y->data) ;\n\t\t temp->left=x ;\n\t\t temp->right=y ;\n\t\t pq.push(temp) ;\n\t\t }\n\t\t \n\t\t preorder(pq.top(), ans, \"\") ;\n\t\t return ans ;\n\t\t}"
},
{
"code": null,
"e": 10830,
"s": 10828,
"text": "0"
},
{
"code": null,
"e": 10857,
"s": 10830,
"text": "balamurali16012 months ago"
},
{
"code": null,
"e": 12462,
"s": 10857,
"text": "class Solution {\n private static ArrayList<String> results = new ArrayList<>();\n\n public ArrayList<String> huffmanCodes(String S, int f[], int N)\n {\n results = new ArrayList<>();\n PriorityQueue<HuffManNode> priorityQueue = new PriorityQueue<>\n (N, Comparator.comparingInt(o -> o.characterCount));\n\n for (int i = 0; i < f.length; i++) {\n HuffManNode node = new HuffManNode();\n node.characterCount = f[i];\n node.character = S.charAt(i);\n priorityQueue.add(node);\n }\n\n HuffManNode root = null;\n\n while (priorityQueue.size() > 1) {\n HuffManNode firstNode = priorityQueue.poll();\n HuffManNode secondNode = priorityQueue.poll();\n\n HuffManNode newNode = new HuffManNode();\n newNode.characterCount = firstNode.characterCount + secondNode.characterCount;\n newNode.character = '-';\n newNode.left = firstNode;\n newNode.right = secondNode;\n\n root = newNode;\n priorityQueue.add(newNode);\n }\n\n printQueue(root, \"\");\n return results;\n }\n private static void printQueue(HuffManNode root, String s) {\n\n if (root.left == null && root.right == null && Character.isLetter(root.character)) {\n results.add(s);\n return;\n }\n printQueue(root.left, s + \"0\");\n printQueue(root.right, s + \"1\");\n\n }\n\n static class HuffManNode {\n char character;\n int characterCount;\n HuffManNode left;\n HuffManNode right;\n }\n}"
},
{
"code": null,
"e": 12497,
"s": 12462,
"text": "WHy this code not working?Input: "
},
{
"code": null,
"e": 12597,
"s": 12497,
"text": "qwertyuiopasdfghjklzxcvbn 8 9 14 19 20 21 21 25 33 45 50 50 66 68 70 73 74 75 76 82 85 90 94 97 100"
},
{
"code": null,
"e": 12625,
"s": 12597,
"text": "And Your Code's output is: "
},
{
"code": null,
"e": 12776,
"s": 12625,
"text": "0000 0001 00100 001010 001011 0011 0100 0101 0110 0111 1000 100100 100101 10011 1010 1011 1100 1101 11100 11101 111100 1111010 11110110 11110111 11111"
},
{
"code": null,
"e": 12800,
"s": 12776,
"text": "Its Correct output is: "
},
{
"code": null,
"e": 12951,
"s": 12800,
"text": "0000 0001 00100 001010 001011 0011 0100 0101 0110 0111 1000 100100 100101 10011 1010 1011 1100 11010 11011 1110 111100 1111010 11110110 11110111 11111"
},
{
"code": null,
"e": 12970,
"s": 12951,
"text": "Output Difference "
},
{
"code": null,
"e": 13123,
"s": 12970,
"text": "0000 0001 00100 001010 001011 0011 0100 0101 0110 0111 1000 100100 100101 10011 1010 1011 1100 1101 11100 11101 111100 1111010 11110110 11110111 11111"
},
{
"code": null,
"e": 13126,
"s": 13123,
"text": "+1"
},
{
"code": null,
"e": 13154,
"s": 13126,
"text": "aloksinghbais022 months ago"
},
{
"code": null,
"e": 13251,
"s": 13154,
"text": "C++ solution having time complexity as O(N*log(N)) and space complexity as O(N) is as follows :-"
},
{
"code": null,
"e": 13375,
"s": 13253,
"text": "Note :- I have tried to solve using set but I got wrong answer so then I tried using priority queue and it got submitted."
},
{
"code": null,
"e": 13455,
"s": 13375,
"text": "If anyone else faces the same problem and get the solution then please respond."
},
{
"code": null,
"e": 13489,
"s": 13457,
"text": "Execution Time :- 0.0 / 1.6 sec"
},
{
"code": null,
"e": 15996,
"s": 13491,
"text": "private: class Node{ public: int data; Node *left; Node *right; Node(int data){ this->data = data; left = right = nullptr; } }; struct comp{ bool operator()(Node *node1,Node *node2){ return node1->data > node2->data; } }; public: void preorder(Node *node,string c,vector<string> &ans){ if(!node) return; if(!node->left && !node->right){ ans.push_back(c); return; } preorder(node->left,c + '0',ans); preorder(node->right,c + '1',ans); } vector<string> huffmanCodes(string S,vector<int> f,int N){ priority_queue<Node*,vector<Node*>,comp> pq; for(int i = 0; i < N; i++){ Node *node = new Node(f[i]); pq.push(node); } while(pq.size() > 1){ Node *left = pq.top(); pq.pop(); Node *right = pq.top(); pq.pop(); Node *root = new Node(left->data + right->data); root->left = left; root->right = right; pq.push(root); } Node *root = pq.top(); pq.pop(); vector<string> ans; preorder(root,\"\",ans); return (ans); }private: class Node{ public: int data; Node *left; Node *right; Node(int data){ this->data = data; left = right = nullptr; } }; struct comp{ bool operator()(Node *node1,Node *node2){ return node1->data > node2->data; } }; public: void preorder(Node *node,string c,vector<string> &ans){ if(!node) return; if(!node->left && !node->right){ ans.push_back(c); return; } preorder(node->left,c + '0',ans); preorder(node->right,c + '1',ans); } vector<string> huffmanCodes(string S,vector<int> f,int N){ priority_queue<Node*,vector<Node*>,comp> pq; for(int i = 0; i < N; i++){ Node *node = new Node(f[i]); pq.push(node); } while(pq.size() > 1){ Node *left = pq.top(); pq.pop(); Node *right = pq.top(); pq.pop(); Node *root = new Node(left->data + right->data); root->left = left; root->right = right; pq.push(root); } Node *root = pq.top(); pq.pop(); vector<string> ans; preorder(root,\"\",ans); return (ans); }"
},
{
"code": null,
"e": 16142,
"s": 15996,
"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": 16178,
"s": 16142,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 16188,
"s": 16178,
"text": "\nProblem\n"
},
{
"code": null,
"e": 16198,
"s": 16188,
"text": "\nContest\n"
},
{
"code": null,
"e": 16261,
"s": 16198,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 16409,
"s": 16261,
"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": 16617,
"s": 16409,
"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": 16723,
"s": 16617,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Generating Geocodes Using Google Maps API | by Francis Adrian Viernes | Towards Data Science | Geocoding is the process of translating text addresses into geographic latitude and longitude coordinates which in turn make it easy to manipulate and analyze massive amounts of geospatial data.
For a data scientist, knowing the geocode makes it easy to plot it in visualization and create other features, such as distances and time differences between two points.
Unlike other types of data, geospatial data benefits greatly from visualization as it makes apparent the occurrence of patterns in neighborhoods or local networks.
As such, businesses profit from the use of it but not if the process involves manually getting the geocodes.
While this process can be done using the open-source package, OpenStreetMap, Google Maps API may produce more accurate data for a wider range of addresses.
In this article, let us examine how to get these geocodes through Python and Google Maps API to speed up our data projects.
The use of Google Maps API comes with a charge and data scientists need to be aware of the pricing before using it.
To use the google maps API, we need to generate our very own API key to use this.
You will see here your dashboard.
To create a new project, follow the GIF above. The option to do this is found in the upper right corner, with a “Select a Project” text. Name the project to better manage current and future projects that involve Google APIs.
Browse the API Library to enable the geocoding service. This is named the “Geocoding API”.
Once the Geocoding API service is enabled, go to the Credentials tab and choose “+Create Credentials”. Once the API key is created copy it to use in your Python code.
You can rename the API and restrict it to keep it safe. There is an edit option to do this under the “API Keys” table for each API key (the pencil sign).
To use the API Key, ensure that you have installed the googlemaps package:
pip install googlemaps
import googlemaps#Set Google MAPS API_Keyg_API = "API-Key Copied"gmaps_key = googlemaps.Client(key=g_API)
For our exercise, let us create fake addresses to use our codes:
from faker import Fakerimport pandas as pdfake = Faker()df = pd.DataFrame(data=[fake.address().replace('\n', " ") for i in range(100)], columns=["address"])# Create columns to store longitude and lattitudedf["longitude"] = Nonedf["latitude"] = Nonefor i in df.index: geocode_obj = gmaps_key.geocode(df.loc[i, "address"]) try: lat = geocode_obj[0]['geometry']['location']['lat'] lon = geocode_obj[0]['geometry']['location']['lng'] df.loc[i,'latitude'] = lat df.loc[i,'longitude'] = lon except: lat = None lon = None
Voila, we’re done!
Geocodes are important because they allow computers to understand our point of reference. That means, with geocodes, analysis and geospatial visualization (geovisualization) are made possible. In addition to that, geocodes are unique.
Using our method above is one of the fastest and surest ways to generate geocodes for our address objects. Some addresses, however, will occasionally result in “None” so manual checking is required for these. From experience, however, these seldom happen when the address variables are clean so we may want to look at how we generate our data before running the code above.
Check out my other articles related to this one:
Mapping Your Favorite Coffee Shop in the Philippines using Google Places API and Folium
Spatial Distance and Machine Learning
Let me know what you think! | [
{
"code": null,
"e": 367,
"s": 172,
"text": "Geocoding is the process of translating text addresses into geographic latitude and longitude coordinates which in turn make it easy to manipulate and analyze massive amounts of geospatial data."
},
{
"code": null,
"e": 537,
"s": 367,
"text": "For a data scientist, knowing the geocode makes it easy to plot it in visualization and create other features, such as distances and time differences between two points."
},
{
"code": null,
"e": 701,
"s": 537,
"text": "Unlike other types of data, geospatial data benefits greatly from visualization as it makes apparent the occurrence of patterns in neighborhoods or local networks."
},
{
"code": null,
"e": 810,
"s": 701,
"text": "As such, businesses profit from the use of it but not if the process involves manually getting the geocodes."
},
{
"code": null,
"e": 966,
"s": 810,
"text": "While this process can be done using the open-source package, OpenStreetMap, Google Maps API may produce more accurate data for a wider range of addresses."
},
{
"code": null,
"e": 1090,
"s": 966,
"text": "In this article, let us examine how to get these geocodes through Python and Google Maps API to speed up our data projects."
},
{
"code": null,
"e": 1206,
"s": 1090,
"text": "The use of Google Maps API comes with a charge and data scientists need to be aware of the pricing before using it."
},
{
"code": null,
"e": 1288,
"s": 1206,
"text": "To use the google maps API, we need to generate our very own API key to use this."
},
{
"code": null,
"e": 1322,
"s": 1288,
"text": "You will see here your dashboard."
},
{
"code": null,
"e": 1547,
"s": 1322,
"text": "To create a new project, follow the GIF above. The option to do this is found in the upper right corner, with a “Select a Project” text. Name the project to better manage current and future projects that involve Google APIs."
},
{
"code": null,
"e": 1638,
"s": 1547,
"text": "Browse the API Library to enable the geocoding service. This is named the “Geocoding API”."
},
{
"code": null,
"e": 1805,
"s": 1638,
"text": "Once the Geocoding API service is enabled, go to the Credentials tab and choose “+Create Credentials”. Once the API key is created copy it to use in your Python code."
},
{
"code": null,
"e": 1959,
"s": 1805,
"text": "You can rename the API and restrict it to keep it safe. There is an edit option to do this under the “API Keys” table for each API key (the pencil sign)."
},
{
"code": null,
"e": 2034,
"s": 1959,
"text": "To use the API Key, ensure that you have installed the googlemaps package:"
},
{
"code": null,
"e": 2057,
"s": 2034,
"text": "pip install googlemaps"
},
{
"code": null,
"e": 2163,
"s": 2057,
"text": "import googlemaps#Set Google MAPS API_Keyg_API = \"API-Key Copied\"gmaps_key = googlemaps.Client(key=g_API)"
},
{
"code": null,
"e": 2228,
"s": 2163,
"text": "For our exercise, let us create fake addresses to use our codes:"
},
{
"code": null,
"e": 2794,
"s": 2228,
"text": "from faker import Fakerimport pandas as pdfake = Faker()df = pd.DataFrame(data=[fake.address().replace('\\n', \" \") for i in range(100)], columns=[\"address\"])# Create columns to store longitude and lattitudedf[\"longitude\"] = Nonedf[\"latitude\"] = Nonefor i in df.index: geocode_obj = gmaps_key.geocode(df.loc[i, \"address\"]) try: lat = geocode_obj[0]['geometry']['location']['lat'] lon = geocode_obj[0]['geometry']['location']['lng'] df.loc[i,'latitude'] = lat df.loc[i,'longitude'] = lon except: lat = None lon = None"
},
{
"code": null,
"e": 2813,
"s": 2794,
"text": "Voila, we’re done!"
},
{
"code": null,
"e": 3048,
"s": 2813,
"text": "Geocodes are important because they allow computers to understand our point of reference. That means, with geocodes, analysis and geospatial visualization (geovisualization) are made possible. In addition to that, geocodes are unique."
},
{
"code": null,
"e": 3422,
"s": 3048,
"text": "Using our method above is one of the fastest and surest ways to generate geocodes for our address objects. Some addresses, however, will occasionally result in “None” so manual checking is required for these. From experience, however, these seldom happen when the address variables are clean so we may want to look at how we generate our data before running the code above."
},
{
"code": null,
"e": 3471,
"s": 3422,
"text": "Check out my other articles related to this one:"
},
{
"code": null,
"e": 3559,
"s": 3471,
"text": "Mapping Your Favorite Coffee Shop in the Philippines using Google Places API and Folium"
},
{
"code": null,
"e": 3597,
"s": 3559,
"text": "Spatial Distance and Machine Learning"
}
] |
How to fetch only N rows at a time in MySQL? | To fetch only N rows at a time, you can use LIMIT operator. Following is the syntax −
select *from yourTableNameLIMIT 0,N;
Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
Name varchar(20)
);
Query OK, 0 rows affected (0.25 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable(Name) values('John');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable(Name) values('Larry');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable(Name) values('Bob');
Query OK, 1 row affected (0.08 sec)
mysql> insert into DemoTable(Name) values('Sam');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable(Name) values('Mike');
Query OK, 1 row affected (0.07 sec)
mysql> insert into DemoTable(Name) values('David');
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable(Name) values('Carol');
Query OK, 1 row affected (0.05 sec)
mysql> insert into DemoTable(Name) values('Ramit');
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable(Name) values('Adam');
Query OK, 1 row affected (0.03 sec)
mysql> insert into DemoTable(Name) values('Chris');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(Name) values('Robert');
Query OK, 1 row affected (0.06 sec)
mysql> insert into DemoTable(Name) values('James');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable(Name) values('Jace');
Query OK, 1 row affected (0.05 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+----+--------+
| Id | Name |
+----+--------+
| 1 | John |
| 2 | Larry |
| 3 | Bob |
| 4 | Sam |
| 5 | Mike |
| 6 | David |
| 7 | Carol |
| 8 | Ramit |
| 9 | Adam |
| 10 | Chris |
| 11 | Robert |
| 12 | James |
| 13 | Jace |
+----+--------+
13 rows in set (0.00 sec)
Following is the query to fetch only N rows at a time. Here, we are fetching only 10 rows −
mysql> select *from DemoTable LIMIT 0,10;
This will produce the following output −
+----+-------+
| Id | Name |
+----+-------+
| 1 | John |
| 2 | Larry |
| 3 | Bob |
| 4 | Sam |
| 5 | Mike |
| 6 | David |
| 7 | Carol |
| 8 | Ramit |
| 9 | Adam |
| 10 | Chris |
+----+-------+
10 rows in set (0.00 sec) | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "To fetch only N rows at a time, you can use LIMIT operator. Following is the syntax −"
},
{
"code": null,
"e": 1185,
"s": 1148,
"text": "select *from yourTableNameLIMIT 0,N;"
},
{
"code": null,
"e": 1215,
"s": 1185,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1360,
"s": 1215,
"text": "mysql> create table DemoTable\n (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n Name varchar(20)\n );\nQuery OK, 0 rows affected (0.25 sec)"
},
{
"code": null,
"e": 1416,
"s": 1360,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 2565,
"s": 1416,
"text": "mysql> insert into DemoTable(Name) values('John');\nQuery OK, 1 row affected (0.08 sec)\n\nmysql> insert into DemoTable(Name) values('Larry');\nQuery OK, 1 row affected (0.07 sec)\n\nmysql> insert into DemoTable(Name) values('Bob');\nQuery OK, 1 row affected (0.08 sec)\n\nmysql> insert into DemoTable(Name) values('Sam');\nQuery OK, 1 row affected (0.07 sec)\n\nmysql> insert into DemoTable(Name) values('Mike');\nQuery OK, 1 row affected (0.07 sec)\n\nmysql> insert into DemoTable(Name) values('David');\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> insert into DemoTable(Name) values('Carol');\nQuery OK, 1 row affected (0.05 sec)\n\nmysql> insert into DemoTable(Name) values('Ramit');\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> insert into DemoTable(Name) values('Adam');\nQuery OK, 1 row affected (0.03 sec)\n\nmysql> insert into DemoTable(Name) values('Chris');\nQuery OK, 1 row affected (0.14 sec)\n\nmysql> insert into DemoTable(Name) values('Robert');\nQuery OK, 1 row affected (0.06 sec)\n\nmysql> insert into DemoTable(Name) values('James');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into DemoTable(Name) values('Jace');\nQuery OK, 1 row affected (0.05 sec)"
},
{
"code": null,
"e": 2625,
"s": 2565,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 2656,
"s": 2625,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2697,
"s": 2656,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2995,
"s": 2697,
"text": "+----+--------+\n| Id | Name |\n+----+--------+\n| 1 | John |\n| 2 | Larry |\n| 3 | Bob |\n| 4 | Sam |\n| 5 | Mike |\n| 6 | David |\n| 7 | Carol |\n| 8 | Ramit |\n| 9 | Adam |\n| 10 | Chris |\n| 11 | Robert |\n| 12 | James |\n| 13 | Jace |\n+----+--------+\n13 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3087,
"s": 2995,
"text": "Following is the query to fetch only N rows at a time. Here, we are fetching only 10 rows −"
},
{
"code": null,
"e": 3129,
"s": 3087,
"text": "mysql> select *from DemoTable LIMIT 0,10;"
},
{
"code": null,
"e": 3170,
"s": 3129,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3406,
"s": 3170,
"text": "+----+-------+\n| Id | Name |\n+----+-------+\n| 1 | John |\n| 2 | Larry |\n| 3 | Bob |\n| 4 | Sam |\n| 5 | Mike |\n| 6 | David |\n| 7 | Carol |\n| 8 | Ramit |\n| 9 | Adam |\n| 10 | Chris |\n+----+-------+\n10 rows in set (0.00 sec)"
}
] |
Selenium Webdriver - Exceptions | If an error occurs, any of the methods fail or an unexpected error happens, an exception is thrown. In Python, all the exceptions are obtained from the BaseException class.
Some of the common Selenium Exceptions are listed below −
ElementNotInteractableException − It is thrown if a webelement is attached to the DOM, but on trying to access the same webelement a different webelement gets accessed.
ElementNotInteractableException − It is thrown if a webelement is attached to the DOM, but on trying to access the same webelement a different webelement gets accessed.
ElementClickInterceptedException − It is thrown if a click operation on a webelement could not happen because another webelement covering that webelement receives the click.
ElementClickInterceptedException − It is thrown if a click operation on a webelement could not happen because another webelement covering that webelement receives the click.
ElementNotVisibleException − It is thrown if a webelement is attached to the DOM, but invisible on the page and inaccessible.
ElementNotVisibleException − It is thrown if a webelement is attached to the DOM, but invisible on the page and inaccessible.
ElementNotSelectableException − It is thrown if we make an attempt to select a webelement which is not selectable.
ElementNotSelectableException − It is thrown if we make an attempt to select a webelement which is not selectable.
ImeActivationFailedException − It is thrown if we fail to activate an IME engine.
ImeActivationFailedException − It is thrown if we fail to activate an IME engine.
ErrorInResponseException − It is thrown if there is an issue on the server side.
ErrorInResponseException − It is thrown if there is an issue on the server side.
InsecureCertificateException − It is thrown if a user gets a certificate warning while navigating an application. It is due to a TLS certificate which is no longer active and valid.
InsecureCertificateException − It is thrown if a user gets a certificate warning while navigating an application. It is due to a TLS certificate which is no longer active and valid.
ImeNotAvailableException − It is thrown if there is no support for the IME engine.
ImeNotAvailableException − It is thrown if there is no support for the IME engine.
InvalidCookieDomainException − It is thrown if we try to add a cookie under a varied domain than the present URL.
InvalidCookieDomainException − It is thrown if we try to add a cookie under a varied domain than the present URL.
InvalidArgumentException − It is thrown if the argument passed to a command is no longer valid.
InvalidArgumentException − It is thrown if the argument passed to a command is no longer valid.
InvalidElementStateException − It is thrown if we try to access a webelement which is not in a valid state.
InvalidElementStateException − It is thrown if we try to access a webelement which is not in a valid state.
InvalidCoordinatesException − It is thrown if the coordinates for interactions are not valid.
InvalidCoordinatesException − It is thrown if the coordinates for interactions are not valid.
InvalidSessionIdException − It is thrown if the session id is not available in the group of live sessions. Thus the given session is either non-existent or inactive.
InvalidSessionIdException − It is thrown if the session id is not available in the group of live sessions. Thus the given session is either non-existent or inactive.
InvalidSelectorException − It is thrown if the locator used to identify an element does not yield a webelement.
InvalidSelectorException − It is thrown if the locator used to identify an element does not yield a webelement.
MoveTargetOutOfBoundsException − It is thrown if the target given in the ActionChains method is out of the scope of the document.
MoveTargetOutOfBoundsException − It is thrown if the target given in the ActionChains method is out of the scope of the document.
InvalidSwitchToTargetException − It is thrown if the frame id/name or the window handle id to be switched to is incorrect.
InvalidSwitchToTargetException − It is thrown if the frame id/name or the window handle id to be switched to is incorrect.
NoSuchAttributeException − It is thrown if an element attribute is not detected.
NoSuchAttributeException − It is thrown if an element attribute is not detected.
NoAlertPresentException − It is thrown if we try to switch to an alert which is non-existent.
NoAlertPresentException − It is thrown if we try to switch to an alert which is non-existent.
NoSuchFrameException − It is thrown if we try to switch to a frame which is non-existent.
NoSuchFrameException − It is thrown if we try to switch to a frame which is non-existent.
StaleElementReferenceException − It is thrown if an element reference is currently stale.
StaleElementReferenceException − It is thrown if an element reference is currently stale.
NoSuchWindowException − It is thrown if we try to switch to a window which is non-existent.
NoSuchWindowException − It is thrown if we try to switch to a window which is non-existent.
UnexpectedAlertPresentException − It is thrown if an alert appears unexpectedly in an automation flow.
UnexpectedAlertPresentException − It is thrown if an alert appears unexpectedly in an automation flow.
UnableToSetCookieException − It is thrown if the webdriver is unsuccessful in setting a cookie.
UnableToSetCookieException − It is thrown if the webdriver is unsuccessful in setting a cookie.
UnexpectedTagNameException − It is thrown if a support class has not received an anticipated webelement.
UnexpectedTagNameException − It is thrown if a support class has not received an anticipated webelement.
NoSuchElementException − It is thrown if the selector used is unable to locate a webelement.
NoSuchElementException − It is thrown if the selector used is unable to locate a webelement.
Let us see an example of a code which throws an exception.
The code implementation for the Selenium Exceptions is as follows −
from selenium import webdriver
driver = webdriver.Chrome(executable_path='../drivers/chromedriver')
#implicit wait time
driver.implicitly_wait(5)
#url launch
driver.get("https://www.tutorialspoint.com/about/about_careers.htm")
#identify element with an incorrect link text value
l = driver.find_element_by_link_text('Teams')
l.click()
#driver quit
driver.quit()
The output shows the message - Process with exit code 1 meaning that the above Python code has encountered an error. Also, NoSuchElementException is thrown since the locator link text is not able to detect the link Teams on the page.
46 Lectures
5.5 hours
Aditya Dua
296 Lectures
146 hours
Arun Motoori
411 Lectures
38.5 hours
In28Minutes Official
22 Lectures
7 hours
Arun Motoori
118 Lectures
17 hours
Arun Motoori
278 Lectures
38.5 hours
Lets Kode It
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2376,
"s": 2203,
"text": "If an error occurs, any of the methods fail or an unexpected error happens, an exception is thrown. In Python, all the exceptions are obtained from the BaseException class."
},
{
"code": null,
"e": 2434,
"s": 2376,
"text": "Some of the common Selenium Exceptions are listed below −"
},
{
"code": null,
"e": 2603,
"s": 2434,
"text": "ElementNotInteractableException − It is thrown if a webelement is attached to the DOM, but on trying to access the same webelement a different webelement gets accessed."
},
{
"code": null,
"e": 2772,
"s": 2603,
"text": "ElementNotInteractableException − It is thrown if a webelement is attached to the DOM, but on trying to access the same webelement a different webelement gets accessed."
},
{
"code": null,
"e": 2946,
"s": 2772,
"text": "ElementClickInterceptedException − It is thrown if a click operation on a webelement could not happen because another webelement covering that webelement receives the click."
},
{
"code": null,
"e": 3120,
"s": 2946,
"text": "ElementClickInterceptedException − It is thrown if a click operation on a webelement could not happen because another webelement covering that webelement receives the click."
},
{
"code": null,
"e": 3246,
"s": 3120,
"text": "ElementNotVisibleException − It is thrown if a webelement is attached to the DOM, but invisible on the page and inaccessible."
},
{
"code": null,
"e": 3372,
"s": 3246,
"text": "ElementNotVisibleException − It is thrown if a webelement is attached to the DOM, but invisible on the page and inaccessible."
},
{
"code": null,
"e": 3487,
"s": 3372,
"text": "ElementNotSelectableException − It is thrown if we make an attempt to select a webelement which is not selectable."
},
{
"code": null,
"e": 3602,
"s": 3487,
"text": "ElementNotSelectableException − It is thrown if we make an attempt to select a webelement which is not selectable."
},
{
"code": null,
"e": 3684,
"s": 3602,
"text": "ImeActivationFailedException − It is thrown if we fail to activate an IME engine."
},
{
"code": null,
"e": 3766,
"s": 3684,
"text": "ImeActivationFailedException − It is thrown if we fail to activate an IME engine."
},
{
"code": null,
"e": 3847,
"s": 3766,
"text": "ErrorInResponseException − It is thrown if there is an issue on the server side."
},
{
"code": null,
"e": 3928,
"s": 3847,
"text": "ErrorInResponseException − It is thrown if there is an issue on the server side."
},
{
"code": null,
"e": 4110,
"s": 3928,
"text": "InsecureCertificateException − It is thrown if a user gets a certificate warning while navigating an application. It is due to a TLS certificate which is no longer active and valid."
},
{
"code": null,
"e": 4292,
"s": 4110,
"text": "InsecureCertificateException − It is thrown if a user gets a certificate warning while navigating an application. It is due to a TLS certificate which is no longer active and valid."
},
{
"code": null,
"e": 4375,
"s": 4292,
"text": "ImeNotAvailableException − It is thrown if there is no support for the IME engine."
},
{
"code": null,
"e": 4458,
"s": 4375,
"text": "ImeNotAvailableException − It is thrown if there is no support for the IME engine."
},
{
"code": null,
"e": 4572,
"s": 4458,
"text": "InvalidCookieDomainException − It is thrown if we try to add a cookie under a varied domain than the present URL."
},
{
"code": null,
"e": 4686,
"s": 4572,
"text": "InvalidCookieDomainException − It is thrown if we try to add a cookie under a varied domain than the present URL."
},
{
"code": null,
"e": 4782,
"s": 4686,
"text": "InvalidArgumentException − It is thrown if the argument passed to a command is no longer valid."
},
{
"code": null,
"e": 4878,
"s": 4782,
"text": "InvalidArgumentException − It is thrown if the argument passed to a command is no longer valid."
},
{
"code": null,
"e": 4986,
"s": 4878,
"text": "InvalidElementStateException − It is thrown if we try to access a webelement which is not in a valid state."
},
{
"code": null,
"e": 5094,
"s": 4986,
"text": "InvalidElementStateException − It is thrown if we try to access a webelement which is not in a valid state."
},
{
"code": null,
"e": 5188,
"s": 5094,
"text": "InvalidCoordinatesException − It is thrown if the coordinates for interactions are not valid."
},
{
"code": null,
"e": 5282,
"s": 5188,
"text": "InvalidCoordinatesException − It is thrown if the coordinates for interactions are not valid."
},
{
"code": null,
"e": 5448,
"s": 5282,
"text": "InvalidSessionIdException − It is thrown if the session id is not available in the group of live sessions. Thus the given session is either non-existent or inactive."
},
{
"code": null,
"e": 5614,
"s": 5448,
"text": "InvalidSessionIdException − It is thrown if the session id is not available in the group of live sessions. Thus the given session is either non-existent or inactive."
},
{
"code": null,
"e": 5726,
"s": 5614,
"text": "InvalidSelectorException − It is thrown if the locator used to identify an element does not yield a webelement."
},
{
"code": null,
"e": 5838,
"s": 5726,
"text": "InvalidSelectorException − It is thrown if the locator used to identify an element does not yield a webelement."
},
{
"code": null,
"e": 5968,
"s": 5838,
"text": "MoveTargetOutOfBoundsException − It is thrown if the target given in the ActionChains method is out of the scope of the document."
},
{
"code": null,
"e": 6098,
"s": 5968,
"text": "MoveTargetOutOfBoundsException − It is thrown if the target given in the ActionChains method is out of the scope of the document."
},
{
"code": null,
"e": 6221,
"s": 6098,
"text": "InvalidSwitchToTargetException − It is thrown if the frame id/name or the window handle id to be switched to is incorrect."
},
{
"code": null,
"e": 6344,
"s": 6221,
"text": "InvalidSwitchToTargetException − It is thrown if the frame id/name or the window handle id to be switched to is incorrect."
},
{
"code": null,
"e": 6425,
"s": 6344,
"text": "NoSuchAttributeException − It is thrown if an element attribute is not detected."
},
{
"code": null,
"e": 6506,
"s": 6425,
"text": "NoSuchAttributeException − It is thrown if an element attribute is not detected."
},
{
"code": null,
"e": 6600,
"s": 6506,
"text": "NoAlertPresentException − It is thrown if we try to switch to an alert which is non-existent."
},
{
"code": null,
"e": 6694,
"s": 6600,
"text": "NoAlertPresentException − It is thrown if we try to switch to an alert which is non-existent."
},
{
"code": null,
"e": 6784,
"s": 6694,
"text": "NoSuchFrameException − It is thrown if we try to switch to a frame which is non-existent."
},
{
"code": null,
"e": 6874,
"s": 6784,
"text": "NoSuchFrameException − It is thrown if we try to switch to a frame which is non-existent."
},
{
"code": null,
"e": 6964,
"s": 6874,
"text": "StaleElementReferenceException − It is thrown if an element reference is currently stale."
},
{
"code": null,
"e": 7054,
"s": 6964,
"text": "StaleElementReferenceException − It is thrown if an element reference is currently stale."
},
{
"code": null,
"e": 7146,
"s": 7054,
"text": "NoSuchWindowException − It is thrown if we try to switch to a window which is non-existent."
},
{
"code": null,
"e": 7238,
"s": 7146,
"text": "NoSuchWindowException − It is thrown if we try to switch to a window which is non-existent."
},
{
"code": null,
"e": 7341,
"s": 7238,
"text": "UnexpectedAlertPresentException − It is thrown if an alert appears unexpectedly in an automation flow."
},
{
"code": null,
"e": 7444,
"s": 7341,
"text": "UnexpectedAlertPresentException − It is thrown if an alert appears unexpectedly in an automation flow."
},
{
"code": null,
"e": 7540,
"s": 7444,
"text": "UnableToSetCookieException − It is thrown if the webdriver is unsuccessful in setting a cookie."
},
{
"code": null,
"e": 7636,
"s": 7540,
"text": "UnableToSetCookieException − It is thrown if the webdriver is unsuccessful in setting a cookie."
},
{
"code": null,
"e": 7741,
"s": 7636,
"text": "UnexpectedTagNameException − It is thrown if a support class has not received an anticipated webelement."
},
{
"code": null,
"e": 7846,
"s": 7741,
"text": "UnexpectedTagNameException − It is thrown if a support class has not received an anticipated webelement."
},
{
"code": null,
"e": 7939,
"s": 7846,
"text": "NoSuchElementException − It is thrown if the selector used is unable to locate a webelement."
},
{
"code": null,
"e": 8032,
"s": 7939,
"text": "NoSuchElementException − It is thrown if the selector used is unable to locate a webelement."
},
{
"code": null,
"e": 8091,
"s": 8032,
"text": "Let us see an example of a code which throws an exception."
},
{
"code": null,
"e": 8159,
"s": 8091,
"text": "The code implementation for the Selenium Exceptions is as follows −"
},
{
"code": null,
"e": 8521,
"s": 8159,
"text": "from selenium import webdriver\ndriver = webdriver.Chrome(executable_path='../drivers/chromedriver')\n#implicit wait time\ndriver.implicitly_wait(5)\n#url launch\ndriver.get(\"https://www.tutorialspoint.com/about/about_careers.htm\")\n#identify element with an incorrect link text value\nl = driver.find_element_by_link_text('Teams')\nl.click()\n#driver quit\ndriver.quit()"
},
{
"code": null,
"e": 8755,
"s": 8521,
"text": "The output shows the message - Process with exit code 1 meaning that the above Python code has encountered an error. Also, NoSuchElementException is thrown since the locator link text is not able to detect the link Teams on the page."
},
{
"code": null,
"e": 8790,
"s": 8755,
"text": "\n 46 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 8802,
"s": 8790,
"text": " Aditya Dua"
},
{
"code": null,
"e": 8838,
"s": 8802,
"text": "\n 296 Lectures \n 146 hours \n"
},
{
"code": null,
"e": 8852,
"s": 8838,
"text": " Arun Motoori"
},
{
"code": null,
"e": 8889,
"s": 8852,
"text": "\n 411 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 8911,
"s": 8889,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 8944,
"s": 8911,
"text": "\n 22 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 8958,
"s": 8944,
"text": " Arun Motoori"
},
{
"code": null,
"e": 8993,
"s": 8958,
"text": "\n 118 Lectures \n 17 hours \n"
},
{
"code": null,
"e": 9007,
"s": 8993,
"text": " Arun Motoori"
},
{
"code": null,
"e": 9044,
"s": 9007,
"text": "\n 278 Lectures \n 38.5 hours \n"
},
{
"code": null,
"e": 9058,
"s": 9044,
"text": " Lets Kode It"
},
{
"code": null,
"e": 9065,
"s": 9058,
"text": " Print"
},
{
"code": null,
"e": 9076,
"s": 9065,
"text": " Add Notes"
}
] |
Stream peek() Method in Java with Examples | 11 Apr, 2022
In Java, Stream provides an powerful alternative to process data where here we will be discussing one of the very frequently used methods named peek() which being a consumer action basically returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This is an intermediate operation, as it creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate.
Syntax:
Stream<T> peek(Consumer<? super T> action)
Here, Stream is an interface and T is the type of stream element. action is a non-interfering action to perform on the elements as they are consumed from the stream and the function returns the new stream.Now we need to understand the lifecycle of peek() method via its internal working via clean java programs listed below as follows:
Note:
This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline.
Since Java 9, if the number of elements is known in advance and unchanged in the stream, the .peek () statement will not be executed due to performance optimization. It is possible to force its operation by a command (formal) changing the number of elements eg. .filter (x -> true).
Using peek without any terminal operation does nothing.
Example 1:
Java
// Java Program to Illustrate peek() Method// of Stream class Without Terminal Operation Count // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a list of Integers List<Integer> list = Arrays.asList(0, 2, 4, 6, 8, 10); // Using peek without any terminal // operation does nothing list.stream().peek(System.out::println); }}
Output:
From the above output, we can perceive that this piece of code will produce no output
Example 2:
Java
// Java Program to Illustrate peek() Method// of Stream class With Terminal Operation Count // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a list of Integers List<Integer> list = Arrays.asList(0, 2, 4, 6, 8, 10); // Using peek with count() method,Method // which is a terminal operation list.stream().peek(System.out::println).count(); }}
Output:
0
2
4
6
8
10
zemiak
solankimayank
germanshephered48
ghiathmakhoul
Java - util package
Java-Functions
java-stream
Java-Stream interface
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n11 Apr, 2022"
},
{
"code": null,
"e": 578,
"s": 54,
"text": "In Java, Stream provides an powerful alternative to process data where here we will be discussing one of the very frequently used methods named peek() which being a consumer action basically returns a stream consisting of the elements of this stream, additionally performing the provided action on each element as elements are consumed from the resulting stream. This is an intermediate operation, as it creates a new stream that, when traversed, contains the elements of the initial stream that match the given predicate. "
},
{
"code": null,
"e": 587,
"s": 578,
"text": "Syntax: "
},
{
"code": null,
"e": 630,
"s": 587,
"text": "Stream<T> peek(Consumer<? super T> action)"
},
{
"code": null,
"e": 966,
"s": 630,
"text": "Here, Stream is an interface and T is the type of stream element. action is a non-interfering action to perform on the elements as they are consumed from the stream and the function returns the new stream.Now we need to understand the lifecycle of peek() method via its internal working via clean java programs listed below as follows:"
},
{
"code": null,
"e": 972,
"s": 966,
"text": "Note:"
},
{
"code": null,
"e": 1104,
"s": 972,
"text": "This method exists mainly to support debugging, where you want to see the elements as they flow past a certain point in a pipeline."
},
{
"code": null,
"e": 1387,
"s": 1104,
"text": "Since Java 9, if the number of elements is known in advance and unchanged in the stream, the .peek () statement will not be executed due to performance optimization. It is possible to force its operation by a command (formal) changing the number of elements eg. .filter (x -> true)."
},
{
"code": null,
"e": 1443,
"s": 1387,
"text": "Using peek without any terminal operation does nothing."
},
{
"code": null,
"e": 1454,
"s": 1443,
"text": "Example 1:"
},
{
"code": null,
"e": 1459,
"s": 1454,
"text": "Java"
},
{
"code": "// Java Program to Illustrate peek() Method// of Stream class Without Terminal Operation Count // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a list of Integers List<Integer> list = Arrays.asList(0, 2, 4, 6, 8, 10); // Using peek without any terminal // operation does nothing list.stream().peek(System.out::println); }}",
"e": 1943,
"s": 1459,
"text": null
},
{
"code": null,
"e": 1955,
"s": 1946,
"text": "Output: "
},
{
"code": null,
"e": 2045,
"s": 1959,
"text": "From the above output, we can perceive that this piece of code will produce no output"
},
{
"code": null,
"e": 2058,
"s": 2047,
"text": "Example 2:"
},
{
"code": null,
"e": 2065,
"s": 2060,
"text": "Java"
},
{
"code": "// Java Program to Illustrate peek() Method// of Stream class With Terminal Operation Count // Importing required classesimport java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating a list of Integers List<Integer> list = Arrays.asList(0, 2, 4, 6, 8, 10); // Using peek with count() method,Method // which is a terminal operation list.stream().peek(System.out::println).count(); }}",
"e": 2567,
"s": 2065,
"text": null
},
{
"code": null,
"e": 2580,
"s": 2570,
"text": "Output: "
},
{
"code": null,
"e": 2595,
"s": 2582,
"text": "0\n2\n4\n6\n8\n10"
},
{
"code": null,
"e": 2604,
"s": 2597,
"text": "zemiak"
},
{
"code": null,
"e": 2618,
"s": 2604,
"text": "solankimayank"
},
{
"code": null,
"e": 2636,
"s": 2618,
"text": "germanshephered48"
},
{
"code": null,
"e": 2650,
"s": 2636,
"text": "ghiathmakhoul"
},
{
"code": null,
"e": 2670,
"s": 2650,
"text": "Java - util package"
},
{
"code": null,
"e": 2685,
"s": 2670,
"text": "Java-Functions"
},
{
"code": null,
"e": 2697,
"s": 2685,
"text": "java-stream"
},
{
"code": null,
"e": 2719,
"s": 2697,
"text": "Java-Stream interface"
},
{
"code": null,
"e": 2724,
"s": 2719,
"text": "Java"
},
{
"code": null,
"e": 2729,
"s": 2724,
"text": "Java"
}
] |
TypeScript | String split() Method | 20 Jun, 2022
The split() is an inbuilt function in TypeScript which is used to splits a String object into an array of strings by separating the string into sub-strings.
Syntax:
string.split([separator][, limit])
Parameter: This method accepts two parameter as mentioned above and described below:
separator – This parameter is the character to use for separating the string.
limit – This parameter is the Integer specifying a limit on the number of splits to be found.
Return Value: This method returns the new array. Below examples illustrate the String split() method in TypeScript.Example 1:
JavaScript
<script> // Original strings var str = "Geeksforgeeks - Best Platform"; // use of String split() Method var newarr = str.split(" "); console.log(newarr);</script>
Output:
[ 'Geeksforgeeks', '-', 'Best', 'Platform' ]
Example 2:
JavaScript
<script> // Original strings var str = "Geeksforgeeks - Best Platform"; // use of String split() Method var newarr = str.split("",14); console.log(newarr);</script>
Output:
[ 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', ' ' ]
surinderdawra388
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n20 Jun, 2022"
},
{
"code": null,
"e": 185,
"s": 28,
"text": "The split() is an inbuilt function in TypeScript which is used to splits a String object into an array of strings by separating the string into sub-strings."
},
{
"code": null,
"e": 193,
"s": 185,
"text": "Syntax:"
},
{
"code": null,
"e": 228,
"s": 193,
"text": "string.split([separator][, limit])"
},
{
"code": null,
"e": 314,
"s": 228,
"text": "Parameter: This method accepts two parameter as mentioned above and described below: "
},
{
"code": null,
"e": 393,
"s": 314,
"text": "separator – This parameter is the character to use for separating the string."
},
{
"code": null,
"e": 487,
"s": 393,
"text": "limit – This parameter is the Integer specifying a limit on the number of splits to be found."
},
{
"code": null,
"e": 614,
"s": 487,
"text": "Return Value: This method returns the new array. Below examples illustrate the String split() method in TypeScript.Example 1: "
},
{
"code": null,
"e": 625,
"s": 614,
"text": "JavaScript"
},
{
"code": "<script> // Original strings var str = \"Geeksforgeeks - Best Platform\"; // use of String split() Method var newarr = str.split(\" \"); console.log(newarr);</script>",
"e": 805,
"s": 625,
"text": null
},
{
"code": null,
"e": 814,
"s": 805,
"text": "Output: "
},
{
"code": null,
"e": 859,
"s": 814,
"text": "[ 'Geeksforgeeks', '-', 'Best', 'Platform' ]"
},
{
"code": null,
"e": 871,
"s": 859,
"text": "Example 2: "
},
{
"code": null,
"e": 882,
"s": 871,
"text": "JavaScript"
},
{
"code": "<script> // Original strings var str = \"Geeksforgeeks - Best Platform\"; // use of String split() Method var newarr = str.split(\"\",14); console.log(newarr);</script>",
"e": 1064,
"s": 882,
"text": null
},
{
"code": null,
"e": 1073,
"s": 1064,
"text": "Output: "
},
{
"code": null,
"e": 1146,
"s": 1073,
"text": "[ 'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'g', 'e', 'e', 'k', 's', ' ' ]"
},
{
"code": null,
"e": 1163,
"s": 1146,
"text": "surinderdawra388"
},
{
"code": null,
"e": 1174,
"s": 1163,
"text": "TypeScript"
},
{
"code": null,
"e": 1185,
"s": 1174,
"text": "JavaScript"
},
{
"code": null,
"e": 1202,
"s": 1185,
"text": "Web Technologies"
}
] |
Implementing Rabin Karp Algorithm Using Rolling Hash in Java | 02 Feb, 2022
There are so many pattern searching algorithms for the string. KMP algorithm, Z algorithm Rabin Karp algorithm, etc these algorithms are the optimization of Naive Pattern searching Algorithm.
Naive Pattern Searching Algorithm:
Input : "AABACACAACAC"
Pattern : "CAC"
Output : [4,9]
AABACACAACAC
Implementation:
Java
// Java Program to Search for a Pattern String in the Input// String returning the indices // Importing input java classesimport java.io.*; // Main classpublic class GFG { // Method 1 // To find pattern in the string static void search(String s, String pattern) { // Iterating over the string in which to be searched // for using the length() method for (int i = 0; i <= s.length() - pattern.length(); ++i) { int check = 1; // Iterating over the string for which is to be // searched using the length() method for (int j = 0; j < pattern.length(); ++j) { // Now, checking the elements of pattern // with the given string using the charAt() // method if (s.charAt(i + j) != pattern.charAt(j)) { // Setting check to zero as pattern is // not detected here check = 0; // Break statement to hault // execution of code break; } } // Now if the check remains same as declared // then pattern is detected at least once if (check == 1) { // Printing the position(index) of the // pattern string in the input string System.out.print(i + " , "); } } } // Method 2 // Main driver method public static void main(String[] args) { // Given custom input string String s = "AABACACAACAC"; // Pattern to be looked after in // the above input string String pattern = "CAC"; // Display message for interpreting the indices // ai where if the pattern exists System.out.print( "Pattern is found at the indices : "); // Calling the above search() method // in the main() method search(s, pattern); }}
Pattern is found at the indices : 4 , 9 ,
Output explanation:
The above algorithm for pattern searching is the basic algorithm the worst as the average time complexity of this algorithm is O(n×m) where n is the pattern and m is the given string.
How can we reduce the complexity of this algorithm?
It is possible with the help of rolling hash. Rabin Karp algorithm is one of the optimized algorithms of the naive algorithm that performs searching by rolling over the string and search the pattern.
Illustration:
Input: txt[] = "THIS IS A TEST TEXT"
pat[] = "TEST"
Output: Pattern found at index 10
Input: txt[] = "AABAACAADAABAABA"
pat[] = "AABA"
Output: Pattern found at index 0
Pattern found at index 9
Pattern found at index 12
Procedure:
Calculate the hash value of the pattern (By creating your own hash function or equation to determining an individual hash value for every character)
Iterate over the string check the hash value of every substring generated of the size of the pattern if matched check every character of the pattern as well as String if all matched print the starting index of the string.
If not matched shift to the next character by skipping the first character and adding the hash value of the next character that we don’t calculate the hash value of the next substring in the string only we slide the window skip the first character and add the last character in the window by calculating its hash value i.e Rolling hash.
Implementation:
Simple Rolling algorithm assuming the pattern of length 2
Initialize temp=4(1+3)Roll the hash value to the next element.Iterate the loop ‘i’ <= Array.length-pattern.lengthRemove the first element from the temp variable and add next element in the temp variable. temp = temp-Array[i]+Array[i.pattern.length()]
Initialize temp=4(1+3)
Roll the hash value to the next element.
Iterate the loop ‘i’ <= Array.length-pattern.length
Remove the first element from the temp variable and add next element in the temp variable. temp = temp-Array[i]+Array[i.pattern.length()]
Java
// Java Program to illustrating Simple Rolling Hashing // Importing input output classesimport java.io.*; // Main classclass GFG { // Method 1 // To search the pattern static void search(String S, String pattern) { // Declaring and initializing the hash values int hash1 = 0; int hash2 = 0; // Iterating over the pattern string to be matched // over for (int i = 0; i < pattern.length(); ++i) { // Storing the hash value of the pattern hash1 += pattern.charAt(i) - 'A'; // Storing First hash value of the string hash2 += S.charAt(i) - 'A'; } // Initially declaring with zero int j = 0; // Iterating over the pattern string to checkout // hash values for (int i = 0; i <= S.length() - pattern.length(); ++i) { // Checking the hash value if (hash2 == hash1) { // Checking the value for (j = 0; j < pattern.length(); ++j) { // Checking for detection of pattern in a // pattern if (pattern.charAt(j) != S.charAt(i + j)) { // Break statement to hault the // execution of program as no // pattern found break; } } } // If execution is not stopped means // pattern(sub-string) is present // So now simply detecting for one or more // occurrences inbetween pattern string using the // length() method if (j == pattern.length()) { // Pattern is detected so printing the index System.out.println(i); } // for last case of loop, have to check, // otherwise, // S.charAt(i + pattern.length()) below will // throw error if (i == S.length() - pattern.length()) break; // Roll the hash value over the string detected hash2 = (int)((hash2) - (S.charAt(i) - 'A')) + S.charAt(i + pattern.length()) - 'A'; } } // Method 2 // Main driver method public static void main(String[] args) { // Input string to be traversed String S = "AABAACAADAABAABA"; // Pattern string to be checked String pattern = "AABA"; // Calling the above search() method(Method1) // in the main() method search(S, pattern); }}
0
9
12
menonkartikeya
simranarora5sos
varshagumber28
Picked
Algorithms
Java
Java Programs
Java
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
How to Start Learning DSA?
Complete Roadmap To Learn DSA From Scratch
Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Object Oriented Programming (OOPs) Concept in Java
Reverse a string in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n02 Feb, 2022"
},
{
"code": null,
"e": 220,
"s": 28,
"text": "There are so many pattern searching algorithms for the string. KMP algorithm, Z algorithm Rabin Karp algorithm, etc these algorithms are the optimization of Naive Pattern searching Algorithm."
},
{
"code": null,
"e": 255,
"s": 220,
"text": "Naive Pattern Searching Algorithm:"
},
{
"code": null,
"e": 329,
"s": 255,
"text": "Input : \"AABACACAACAC\"\nPattern : \"CAC\"\nOutput : [4,9]\n\nAABACACAACAC"
},
{
"code": null,
"e": 345,
"s": 329,
"text": "Implementation:"
},
{
"code": null,
"e": 350,
"s": 345,
"text": "Java"
},
{
"code": "// Java Program to Search for a Pattern String in the Input// String returning the indices // Importing input java classesimport java.io.*; // Main classpublic class GFG { // Method 1 // To find pattern in the string static void search(String s, String pattern) { // Iterating over the string in which to be searched // for using the length() method for (int i = 0; i <= s.length() - pattern.length(); ++i) { int check = 1; // Iterating over the string for which is to be // searched using the length() method for (int j = 0; j < pattern.length(); ++j) { // Now, checking the elements of pattern // with the given string using the charAt() // method if (s.charAt(i + j) != pattern.charAt(j)) { // Setting check to zero as pattern is // not detected here check = 0; // Break statement to hault // execution of code break; } } // Now if the check remains same as declared // then pattern is detected at least once if (check == 1) { // Printing the position(index) of the // pattern string in the input string System.out.print(i + \" , \"); } } } // Method 2 // Main driver method public static void main(String[] args) { // Given custom input string String s = \"AABACACAACAC\"; // Pattern to be looked after in // the above input string String pattern = \"CAC\"; // Display message for interpreting the indices // ai where if the pattern exists System.out.print( \"Pattern is found at the indices : \"); // Calling the above search() method // in the main() method search(s, pattern); }}",
"e": 2332,
"s": 350,
"text": null
},
{
"code": null,
"e": 2375,
"s": 2332,
"text": "Pattern is found at the indices : 4 , 9 , "
},
{
"code": null,
"e": 2395,
"s": 2375,
"text": "Output explanation:"
},
{
"code": null,
"e": 2580,
"s": 2395,
"text": "The above algorithm for pattern searching is the basic algorithm the worst as the average time complexity of this algorithm is O(n×m) where n is the pattern and m is the given string. "
},
{
"code": null,
"e": 2633,
"s": 2580,
"text": "How can we reduce the complexity of this algorithm? "
},
{
"code": null,
"e": 2833,
"s": 2633,
"text": "It is possible with the help of rolling hash. Rabin Karp algorithm is one of the optimized algorithms of the naive algorithm that performs searching by rolling over the string and search the pattern."
},
{
"code": null,
"e": 2852,
"s": 2837,
"text": "Illustration: "
},
{
"code": null,
"e": 3108,
"s": 2852,
"text": "Input: txt[] = \"THIS IS A TEST TEXT\"\n pat[] = \"TEST\"\nOutput: Pattern found at index 10\n\nInput: txt[] = \"AABAACAADAABAABA\"\n pat[] = \"AABA\"\nOutput: Pattern found at index 0\n Pattern found at index 9\n Pattern found at index 12"
},
{
"code": null,
"e": 3119,
"s": 3108,
"text": "Procedure:"
},
{
"code": null,
"e": 3268,
"s": 3119,
"text": "Calculate the hash value of the pattern (By creating your own hash function or equation to determining an individual hash value for every character)"
},
{
"code": null,
"e": 3490,
"s": 3268,
"text": "Iterate over the string check the hash value of every substring generated of the size of the pattern if matched check every character of the pattern as well as String if all matched print the starting index of the string."
},
{
"code": null,
"e": 3827,
"s": 3490,
"text": "If not matched shift to the next character by skipping the first character and adding the hash value of the next character that we don’t calculate the hash value of the next substring in the string only we slide the window skip the first character and add the last character in the window by calculating its hash value i.e Rolling hash."
},
{
"code": null,
"e": 3845,
"s": 3827,
"text": " Implementation: "
},
{
"code": null,
"e": 3903,
"s": 3845,
"text": "Simple Rolling algorithm assuming the pattern of length 2"
},
{
"code": null,
"e": 4154,
"s": 3903,
"text": "Initialize temp=4(1+3)Roll the hash value to the next element.Iterate the loop ‘i’ <= Array.length-pattern.lengthRemove the first element from the temp variable and add next element in the temp variable. temp = temp-Array[i]+Array[i.pattern.length()]"
},
{
"code": null,
"e": 4177,
"s": 4154,
"text": "Initialize temp=4(1+3)"
},
{
"code": null,
"e": 4218,
"s": 4177,
"text": "Roll the hash value to the next element."
},
{
"code": null,
"e": 4270,
"s": 4218,
"text": "Iterate the loop ‘i’ <= Array.length-pattern.length"
},
{
"code": null,
"e": 4408,
"s": 4270,
"text": "Remove the first element from the temp variable and add next element in the temp variable. temp = temp-Array[i]+Array[i.pattern.length()]"
},
{
"code": null,
"e": 4413,
"s": 4408,
"text": "Java"
},
{
"code": "// Java Program to illustrating Simple Rolling Hashing // Importing input output classesimport java.io.*; // Main classclass GFG { // Method 1 // To search the pattern static void search(String S, String pattern) { // Declaring and initializing the hash values int hash1 = 0; int hash2 = 0; // Iterating over the pattern string to be matched // over for (int i = 0; i < pattern.length(); ++i) { // Storing the hash value of the pattern hash1 += pattern.charAt(i) - 'A'; // Storing First hash value of the string hash2 += S.charAt(i) - 'A'; } // Initially declaring with zero int j = 0; // Iterating over the pattern string to checkout // hash values for (int i = 0; i <= S.length() - pattern.length(); ++i) { // Checking the hash value if (hash2 == hash1) { // Checking the value for (j = 0; j < pattern.length(); ++j) { // Checking for detection of pattern in a // pattern if (pattern.charAt(j) != S.charAt(i + j)) { // Break statement to hault the // execution of program as no // pattern found break; } } } // If execution is not stopped means // pattern(sub-string) is present // So now simply detecting for one or more // occurrences inbetween pattern string using the // length() method if (j == pattern.length()) { // Pattern is detected so printing the index System.out.println(i); } // for last case of loop, have to check, // otherwise, // S.charAt(i + pattern.length()) below will // throw error if (i == S.length() - pattern.length()) break; // Roll the hash value over the string detected hash2 = (int)((hash2) - (S.charAt(i) - 'A')) + S.charAt(i + pattern.length()) - 'A'; } } // Method 2 // Main driver method public static void main(String[] args) { // Input string to be traversed String S = \"AABAACAADAABAABA\"; // Pattern string to be checked String pattern = \"AABA\"; // Calling the above search() method(Method1) // in the main() method search(S, pattern); }}",
"e": 7023,
"s": 4413,
"text": null
},
{
"code": null,
"e": 7030,
"s": 7023,
"text": "0\n9\n12"
},
{
"code": null,
"e": 7047,
"s": 7032,
"text": "menonkartikeya"
},
{
"code": null,
"e": 7063,
"s": 7047,
"text": "simranarora5sos"
},
{
"code": null,
"e": 7078,
"s": 7063,
"text": "varshagumber28"
},
{
"code": null,
"e": 7085,
"s": 7078,
"text": "Picked"
},
{
"code": null,
"e": 7096,
"s": 7085,
"text": "Algorithms"
},
{
"code": null,
"e": 7101,
"s": 7096,
"text": "Java"
},
{
"code": null,
"e": 7115,
"s": 7101,
"text": "Java Programs"
},
{
"code": null,
"e": 7120,
"s": 7115,
"text": "Java"
},
{
"code": null,
"e": 7131,
"s": 7120,
"text": "Algorithms"
},
{
"code": null,
"e": 7229,
"s": 7131,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7267,
"s": 7229,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 7335,
"s": 7267,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 7362,
"s": 7335,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 7405,
"s": 7362,
"text": "Complete Roadmap To Learn DSA From Scratch"
},
{
"code": null,
"e": 7472,
"s": 7405,
"text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete"
},
{
"code": null,
"e": 7487,
"s": 7472,
"text": "Arrays in Java"
},
{
"code": null,
"e": 7531,
"s": 7487,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 7567,
"s": 7531,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 7618,
"s": 7567,
"text": "Object Oriented Programming (OOPs) Concept in Java"
}
] |
PHP | ctype_space() Function | 06 Jun, 2018
A ctype_space() function in PHP is used to check whether each and every character of a string is whitespace character or not. It returns True if the all characters are white space, else returns False.
Syntax :
ctype_space(string text)
Parameter Used:
text :- It is a mandatory parameter which specifies the string.
Return Value:Returns TRUE if every character in text contains white space, return false otherwise. the blank character this also includes tab, carriage, vertical tab, line feed, and form feed characters.
Examples:
Input : \r
Output : Yes
Explanation: \r is create white space
Input : abc\r
Output : No
Explanation: characters "abc" are not white space
Below programs illustrate the ctype_space() function.Program 1: taking a single string
<?php// PHP program to check given string is // whitespace character or not $string = "/n/t/r"; if (ctype_space($string)) echo "Yes \n";else echo "No \n"; ?>
No
Program: 2 Taking an array of string and checking for whitespace using ctype_space() function
<?php// PHP program to check given string is // whitespace character or not $strings = array('\n\y\t\x\u\o', "\ngfg\n", "\t"); // Checking above given strings //by used of ctype_space()function .foreach ($strings as $testcase) { if (ctype_space($testcase)) { echo "Yes \n"; } else { echo "No \n"; }}?>
No
No
Yes
Program: 3Takes an example ctype_space() function how to work string in both single quotes ‘ ‘ and double quotes ” ” symbol.
<?php// PHP program to check given string is // whitespace character or not $strings = array('\n', "\n", '\t', "\t"); // Checking above given strings // by used of ctype_space()function . foreach ($strings as $testcase) { if (ctype_space($testcase)) { echo "Yes \n"; } else { echo "No \n"; }}?>
No
Yes
No
Yes
References :http://php.net/manual/en/function.ctype-space.php
PHP-function
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Jun, 2018"
},
{
"code": null,
"e": 229,
"s": 28,
"text": "A ctype_space() function in PHP is used to check whether each and every character of a string is whitespace character or not. It returns True if the all characters are white space, else returns False."
},
{
"code": null,
"e": 238,
"s": 229,
"text": "Syntax :"
},
{
"code": null,
"e": 264,
"s": 238,
"text": "ctype_space(string text)\n"
},
{
"code": null,
"e": 280,
"s": 264,
"text": "Parameter Used:"
},
{
"code": null,
"e": 344,
"s": 280,
"text": "text :- It is a mandatory parameter which specifies the string."
},
{
"code": null,
"e": 548,
"s": 344,
"text": "Return Value:Returns TRUE if every character in text contains white space, return false otherwise. the blank character this also includes tab, carriage, vertical tab, line feed, and form feed characters."
},
{
"code": null,
"e": 558,
"s": 548,
"text": "Examples:"
},
{
"code": null,
"e": 707,
"s": 558,
"text": "Input : \\r \nOutput : Yes\nExplanation: \\r is create white space\n\n\nInput : abc\\r\nOutput : No \nExplanation: characters \"abc\" are not white space\n"
},
{
"code": null,
"e": 794,
"s": 707,
"text": "Below programs illustrate the ctype_space() function.Program 1: taking a single string"
},
{
"code": "<?php// PHP program to check given string is // whitespace character or not $string = \"/n/t/r\"; if (ctype_space($string)) echo \"Yes \\n\";else echo \"No \\n\"; ?>",
"e": 962,
"s": 794,
"text": null
},
{
"code": null,
"e": 966,
"s": 962,
"text": "No\n"
},
{
"code": null,
"e": 1060,
"s": 966,
"text": "Program: 2 Taking an array of string and checking for whitespace using ctype_space() function"
},
{
"code": "<?php// PHP program to check given string is // whitespace character or not $strings = array('\\n\\y\\t\\x\\u\\o', \"\\ngfg\\n\", \"\\t\"); // Checking above given strings //by used of ctype_space()function .foreach ($strings as $testcase) { if (ctype_space($testcase)) { echo \"Yes \\n\"; } else { echo \"No \\n\"; }}?>",
"e": 1394,
"s": 1060,
"text": null
},
{
"code": null,
"e": 1407,
"s": 1394,
"text": "No \nNo \nYes\n"
},
{
"code": null,
"e": 1532,
"s": 1407,
"text": "Program: 3Takes an example ctype_space() function how to work string in both single quotes ‘ ‘ and double quotes ” ” symbol."
},
{
"code": "<?php// PHP program to check given string is // whitespace character or not $strings = array('\\n', \"\\n\", '\\t', \"\\t\"); // Checking above given strings // by used of ctype_space()function . foreach ($strings as $testcase) { if (ctype_space($testcase)) { echo \"Yes \\n\"; } else { echo \"No \\n\"; }}?>",
"e": 1860,
"s": 1532,
"text": null
},
{
"code": null,
"e": 1878,
"s": 1860,
"text": "No \nYes \nNo \nYes\n"
},
{
"code": null,
"e": 1940,
"s": 1878,
"text": "References :http://php.net/manual/en/function.ctype-space.php"
},
{
"code": null,
"e": 1953,
"s": 1940,
"text": "PHP-function"
},
{
"code": null,
"e": 1957,
"s": 1953,
"text": "PHP"
},
{
"code": null,
"e": 1974,
"s": 1957,
"text": "Web Technologies"
},
{
"code": null,
"e": 1978,
"s": 1974,
"text": "PHP"
}
] |
Permutations of a given string | Practice | GeeksforGeeks | Given a string S. The task is to print all permutations of a given string in lexicographically sorted order.
Example 1:
Input: ABC
Output:
ABC ACB BAC BCA CAB CBA
Explanation:
Given string ABC has permutations in 6
forms as ABC, ACB, BAC, BCA, CAB and CBA .
Example 2:
Input: ABSG
Output:
ABGS ABSG AGBS AGSB ASBG ASGB BAGS
BASG BGAS BGSA BSAG BSGA GABS GASB
GBAS GBSA GSAB GSBA SABG SAGB SBAG
SBGA SGAB SGBA
Explanation:
Given string ABSG has 24 permutations.
Your Task:
You don't need to read input or print anything. Your task is to complete the function find_permutaion() which takes the string S as input parameter and returns a vector of string in lexicographical order.
Expected Time Complexity: O(n! * n)
Expected Space Complexity: O(n)
Constraints:
1 <= length of string <= 5
0
rahulsharmaec20b1339in 2 hours
can anyone help me, im getting segmentation fault int v[i]==s condition
bool check(vector<string> &v, string &s)
{
for(int i=0; v.size();i++)
{
if(v[i]==s)
return 0;
}
return 1;
}
vector <string> solun(string &s, vector<string> &v ,int pos)
{
if(pos>=s.size())
{
if(check(v,s) || v.empty()){
v.push_back(s);
}
}
for(int i=pos;i<s.size();i++)
{
swap(s[i],s[pos]);
solun(s,v,pos+1);
swap(s[i],s[pos]);
}
return v;
}
vector<string>find_permutation(string s)
{
vector <string> v;
solun(s,v,0);
sort(v.begin(),v.end());
return v;
}
0
kanein 2 hours
vector<string>ans; void solve(vector<int>&vis,string S,string path){ if(path.length()==S.length()){ ans.push_back(path); return ; } for(int i=0;i<S.length();i++){ if(vis[i]==0){ vis[i]=1; solve(vis,S,path+S[i]); vis[i]=0; } } } vector<string>find_permutation(string S) { // Code here there vector<int>vis(S.length(),0); solve(vis,S,""); sort(ans.begin(),ans.end()); vector<string>res; res.push_back(ans[0]); for(int i=1;i<ans.size();i++){ if(ans[i-1]!=ans[i])res.push_back(ans[i]); } return res; }
0
kane
This comment was deleted.
0
abhishekips07in 1 hour
Python Approach.
class Solution:
def find_permutation(self, S):
res=set()
visit=[False]*len(S)
def dfs(i,ans):
if len(ans)==len(S):
res.add(ans)
return
if i>len(S):
return
for j in range(len(S)):
if visit[j]==True:
continue
visit[j]=True
dfs(j+1,ans+S[j])
visit[j]=False
dfs(0,"")
res=list(res)
res.sort()
return res
0
nitesh8002 hours ago
class solution
{public: unordered_set<string>st; void solve(string s, int i, int n, vector<string>&v) { if(i+1 == n) { if(st.find(s) == st.end()) { v.push_back(s); st.insert(s); } return; } for(int j=i;j<n;j++) { swap(s[i],s[j]); solve(s,i+1,n,v); swap(s[i],s[j]); } } vector<string>find_permutation(string s) { vector<string>v; int n=s.length(); solve(s,0,n,v); sort(v.begin(),v.end()); return v; }};
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 347,
"s": 238,
"text": "Given a string S. The task is to print all permutations of a given string in lexicographically sorted order."
},
{
"code": null,
"e": 360,
"s": 349,
"text": "Example 1:"
},
{
"code": null,
"e": 500,
"s": 360,
"text": "Input: ABC\nOutput:\nABC ACB BAC BCA CAB CBA\nExplanation:\nGiven string ABC has permutations in 6 \nforms as ABC, ACB, BAC, BCA, CAB and CBA .\n"
},
{
"code": null,
"e": 511,
"s": 500,
"text": "Example 2:"
},
{
"code": null,
"e": 707,
"s": 511,
"text": "Input: ABSG\nOutput:\nABGS ABSG AGBS AGSB ASBG ASGB BAGS \nBASG BGAS BGSA BSAG BSGA GABS GASB \nGBAS GBSA GSAB GSBA SABG SAGB SBAG \nSBGA SGAB SGBA\nExplanation:\nGiven string ABSG has 24 permutations.\n"
},
{
"code": null,
"e": 927,
"s": 709,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function find_permutaion() which takes the string S as input parameter and returns a vector of string in lexicographical order."
},
{
"code": null,
"e": 965,
"s": 929,
"text": "Expected Time Complexity: O(n! * n)"
},
{
"code": null,
"e": 997,
"s": 965,
"text": "Expected Space Complexity: O(n)"
},
{
"code": null,
"e": 1041,
"s": 999,
"text": "Constraints:\n1 <= length of string <= 5\n "
},
{
"code": null,
"e": 1045,
"s": 1043,
"text": "0"
},
{
"code": null,
"e": 1076,
"s": 1045,
"text": "rahulsharmaec20b1339in 2 hours"
},
{
"code": null,
"e": 1148,
"s": 1076,
"text": "can anyone help me, im getting segmentation fault int v[i]==s condition"
},
{
"code": null,
"e": 1776,
"s": 1148,
"text": "bool check(vector<string> &v, string &s)\n\t{\n\t for(int i=0; v.size();i++)\n\t {\n\t if(v[i]==s)\n\t return 0;\n\t }\n\t return 1;\n\t}\n\tvector <string> solun(string &s, vector<string> &v ,int pos)\n\t{\n\t if(pos>=s.size())\n\t {\n\t if(check(v,s) || v.empty()){\n\t v.push_back(s); \n\t }\n\t }\n\t for(int i=pos;i<s.size();i++)\n\t {\n\t swap(s[i],s[pos]);\n\t solun(s,v,pos+1);\n\t swap(s[i],s[pos]);\n\t }\n\t return v;\n\t}\n\t\tvector<string>find_permutation(string s)\n\t\t{\n\t\t vector <string> v;\n\t\t solun(s,v,0);\n\t\t sort(v.begin(),v.end());\n\t\t return v;\n\t\t \n\t\t}"
},
{
"code": null,
"e": 1778,
"s": 1776,
"text": "0"
},
{
"code": null,
"e": 1793,
"s": 1778,
"text": "kanein 2 hours"
},
{
"code": null,
"e": 2470,
"s": 1793,
"text": "vector<string>ans; void solve(vector<int>&vis,string S,string path){ if(path.length()==S.length()){ ans.push_back(path); return ; } for(int i=0;i<S.length();i++){ if(vis[i]==0){ vis[i]=1; solve(vis,S,path+S[i]); vis[i]=0; } } } vector<string>find_permutation(string S) { // Code here there vector<int>vis(S.length(),0); solve(vis,S,\"\"); sort(ans.begin(),ans.end()); vector<string>res; res.push_back(ans[0]); for(int i=1;i<ans.size();i++){ if(ans[i-1]!=ans[i])res.push_back(ans[i]); } return res; }"
},
{
"code": null,
"e": 2472,
"s": 2470,
"text": "0"
},
{
"code": null,
"e": 2477,
"s": 2472,
"text": "kane"
},
{
"code": null,
"e": 2503,
"s": 2477,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2505,
"s": 2503,
"text": "0"
},
{
"code": null,
"e": 2528,
"s": 2505,
"text": "abhishekips07in 1 hour"
},
{
"code": null,
"e": 2545,
"s": 2528,
"text": "Python Approach."
},
{
"code": null,
"e": 3073,
"s": 2545,
"text": "class Solution:\n def find_permutation(self, S):\n res=set()\n visit=[False]*len(S)\n def dfs(i,ans):\n if len(ans)==len(S):\n res.add(ans)\n return\n if i>len(S):\n return\n for j in range(len(S)):\n if visit[j]==True:\n continue\n visit[j]=True\n dfs(j+1,ans+S[j])\n visit[j]=False\n dfs(0,\"\")\n res=list(res)\n res.sort()\n return res"
},
{
"code": null,
"e": 3075,
"s": 3073,
"text": "0"
},
{
"code": null,
"e": 3096,
"s": 3075,
"text": "nitesh8002 hours ago"
},
{
"code": null,
"e": 3111,
"s": 3096,
"text": "class solution"
},
{
"code": null,
"e": 3676,
"s": 3111,
"text": "{public: unordered_set<string>st; void solve(string s, int i, int n, vector<string>&v) { if(i+1 == n) { if(st.find(s) == st.end()) { v.push_back(s); st.insert(s); } return; } for(int j=i;j<n;j++) { swap(s[i],s[j]); solve(s,i+1,n,v); swap(s[i],s[j]); } } vector<string>find_permutation(string s) { vector<string>v; int n=s.length(); solve(s,0,n,v); sort(v.begin(),v.end()); return v; }};"
},
{
"code": null,
"e": 3822,
"s": 3676,
"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": 3858,
"s": 3822,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3868,
"s": 3858,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3878,
"s": 3868,
"text": "\nContest\n"
},
{
"code": null,
"e": 3941,
"s": 3878,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4126,
"s": 3941,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 4410,
"s": 4126,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 4556,
"s": 4410,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 4633,
"s": 4556,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 4674,
"s": 4633,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 4702,
"s": 4674,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 4773,
"s": 4702,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 4960,
"s": 4773,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
Program to insert dashes between two adjacent odd digits in given Number | 07 Oct, 2021
Given a large number in form of string N, the task is to insert a dash between two adjacent odd digits in the given number in form of strings.
Examples:
Input: N = 1745389 Output: 1-745-389 Explanation: In string str, str[0] and str[1] both are the odd numbers in consecutive, so insert a dash between them.Input: N = 34657323128437 Output: 3465-7-323-12843-7
Bitwise Approach:
Traverse the whole string of numbers character by character.Compare every consecutive character using logical Bitwise OR and AND operators.If two consecutive characters of the string are odd, insert a dash (-) in them and check for the next two consecutive characters.
Traverse the whole string of numbers character by character.
Compare every consecutive character using logical Bitwise OR and AND operators.
If two consecutive characters of the string are odd, insert a dash (-) in them and check for the next two consecutive characters.
Below is the implementation of the above approach:
C++
Java
Python3
C#
// C++ program for the above approach#include <iostream>#include <string>using namespace std; // Function to check if char ch is// odd or notbool checkOdd(char ch){ return ((ch - '0') & 1);} // Function to insert dash - between// any 2 consecutive digit in string strstring Insert_dash(string num_str){ string result_str = num_str; // Traverse the string character // by character for (int x = 0; x < num_str.length() - 1; x++) { // Compare every consecutive // character with the odd value if (checkOdd(num_str[x]) && checkOdd(num_str[x + 1])) { result_str.insert(x + 1, "-"); num_str = result_str; x++; } } // Print the resultant string return result_str;} // Driver Codeint main(){ // Given number in form of string string str = "1745389"; // Function Call cout << Insert_dash(str); return 0;}
// Java program to implement// the above approachclass GFG{ // Function to check if char ch is// odd or notstatic boolean checkOdd(char ch){ return ((ch - '0') & 1) != 0 ? true : false;} // Function to insert dash - between// any 2 consecutive digit in string strstatic String Insert_dash(String num_str){ StringBuilder result_str = new StringBuilder(num_str); // Traverse the string character // by character for(int x = 0; x < num_str.length() - 1; x++) { // Compare every consecutive // character with the odd value if (checkOdd(num_str.charAt(x)) && checkOdd(num_str.charAt(x + 1))) { result_str.insert(x + 1, "-"); num_str = result_str.toString(); x++; } } // Print the resultant string return result_str.toString();} // Driver Codepublic static void main(String[] args){ // Given number in form of string String str = "1745389"; // Function call System.out.println(Insert_dash(str));}} // This code is contributed by rutvik_56
# Python3 program for the above approach # Function to check if char ch is# odd or notdef checkOdd(ch): return ((ord(ch) - 48) & 1) # Function to insert dash - between# any 2 consecutive digit in string strdef Insert_dash(num_str): result_str = num_str # Traverse the string character # by character x = 0 while(x < len(num_str) - 1): # Compare every consecutive # character with the odd value if (checkOdd(num_str[x]) and checkOdd(num_str[x + 1])): result_str = (result_str[:x + 1] + '-' + result_str[x + 1:]) num_str = result_str x += 1 x += 1 # Print the resultant string return result_str # Driver Code # Given number in form of stringstr = "1745389" # Function callprint(Insert_dash(str)) # This code is contributed by vishu2908
// C# program to implement// the above approachusing System;using System.Text;class GFG{ // Function to check if char ch is// odd or notstatic bool checkOdd(char ch){ return ((ch - '0') & 1) != 0 ? true : false;} // Function to insert dash - between// any 2 consecutive digit in string strstatic String Insert_dash(String num_str){ StringBuilder result_str = new StringBuilder(num_str); // Traverse the string character // by character for(int x = 0; x < num_str.Length - 1; x++) { // Compare every consecutive // character with the odd value if (checkOdd(num_str[x]) && checkOdd(num_str[x + 1])) { result_str.Insert(x + 1, "-"); num_str = result_str.ToString(); x++; } } // Print the resultant string return result_str.ToString();} // Driver Codepublic static void Main(String[] args){ // Given number in form of string String str = "1745389"; // Function call Console.WriteLine(Insert_dash(str));}} // This code is contributed by Rajput-Ji
1-745-389
Time Complexity: O(N) Auxiliary Space: O(1)
Regular Expression Approach:
The given problem can be solved using Regular Expression. The RE for this problem will be:
(?<=[13579])(?=[13579])The given RE matches between odd numbers. We can replace the matched part of zero width with a dash, i.e.str = str.replaceAll(“(?<=[13579])(?=[13579])”, “-“);
Below is the implementation of the above approach:
C++
Java
Python
// C++ Program to implement// the above approach#include <iostream>#include <regex>using namespace std; // Function to insert dash - between// any 2 consecutive odd digitstring Insert_dash(string str){ // Get the regex to be checked const regex pattern("([13579])([13579])"); // Replaces the matched value // (here dash) with given string return regex_replace(str, pattern, "$1-$2");;} // Driver Codeint main(){ string str = "1745389"; cout << Insert_dash(str); return 0;} // This code is contributed by yuvraj_chandra
// Java program for the above approach import java.util.regex.*; public class GFG { // Function to insert dash - between // any 2 consecutive odd digit public static String Insert_dash(String str) { // Get the regex to be checked String regex = "(?<=[13579])(?=[13579])"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Create a matcher for the input String Matcher matcher = pattern.matcher(str); // Get the String to be replaced, // i.e. here dash String stringToBeReplaced = "-"; StringBuilder builder = new StringBuilder(); // Replace every matched pattern // with the target String // using replaceAll() method return (matcher .replaceAll(stringToBeReplaced)); } // Driver Code public static void main(String[] args) { // Given number in form of string String str = "1745389"; // Function Call System.out.println(Insert_dash(str)); }}
# Python program for the above approachimport re # Function to insert dash - between# any 2 consecutive odd digitdef Insert_dash(str): # Get the regex to be checked regex = "(?<=[13579])(?=[13579])" return re.sub(regex,'\1-\2', str) # Driver Code # Given number in form of stringstr = "1745389" # Function Callprint(Insert_dash(str)) # This code is contributed by yuvraj_chandra
1-745-389
vishu2908
rutvik_56
Rajput-Ji
yuvraj_chandra
abhishek0719kadiyan
CPP-regex
java-regular-expression
number-digits
regular-expression
Pattern Searching
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Reverse the substrings of the given String according to the given Array of indices
Check if the given string is shuffled substring of another string
How to check Aadhaar number is valid or not using Regular Expression
How to validate GUID (Globally Unique Identifier) using Regular Expression
How to validate pin code of India using Regular Expression
Write a program to reverse an array or string
Reverse a string in Java
Write a program to print all permutations of a given string
C++ Data Types
Different Methods to Reverse a String in C++ | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Oct, 2021"
},
{
"code": null,
"e": 171,
"s": 28,
"text": "Given a large number in form of string N, the task is to insert a dash between two adjacent odd digits in the given number in form of strings."
},
{
"code": null,
"e": 181,
"s": 171,
"text": "Examples:"
},
{
"code": null,
"e": 388,
"s": 181,
"text": "Input: N = 1745389 Output: 1-745-389 Explanation: In string str, str[0] and str[1] both are the odd numbers in consecutive, so insert a dash between them.Input: N = 34657323128437 Output: 3465-7-323-12843-7"
},
{
"code": null,
"e": 406,
"s": 388,
"text": "Bitwise Approach:"
},
{
"code": null,
"e": 675,
"s": 406,
"text": "Traverse the whole string of numbers character by character.Compare every consecutive character using logical Bitwise OR and AND operators.If two consecutive characters of the string are odd, insert a dash (-) in them and check for the next two consecutive characters."
},
{
"code": null,
"e": 736,
"s": 675,
"text": "Traverse the whole string of numbers character by character."
},
{
"code": null,
"e": 816,
"s": 736,
"text": "Compare every consecutive character using logical Bitwise OR and AND operators."
},
{
"code": null,
"e": 946,
"s": 816,
"text": "If two consecutive characters of the string are odd, insert a dash (-) in them and check for the next two consecutive characters."
},
{
"code": null,
"e": 997,
"s": 946,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1001,
"s": 997,
"text": "C++"
},
{
"code": null,
"e": 1006,
"s": 1001,
"text": "Java"
},
{
"code": null,
"e": 1014,
"s": 1006,
"text": "Python3"
},
{
"code": null,
"e": 1017,
"s": 1014,
"text": "C#"
},
{
"code": "// C++ program for the above approach#include <iostream>#include <string>using namespace std; // Function to check if char ch is// odd or notbool checkOdd(char ch){ return ((ch - '0') & 1);} // Function to insert dash - between// any 2 consecutive digit in string strstring Insert_dash(string num_str){ string result_str = num_str; // Traverse the string character // by character for (int x = 0; x < num_str.length() - 1; x++) { // Compare every consecutive // character with the odd value if (checkOdd(num_str[x]) && checkOdd(num_str[x + 1])) { result_str.insert(x + 1, \"-\"); num_str = result_str; x++; } } // Print the resultant string return result_str;} // Driver Codeint main(){ // Given number in form of string string str = \"1745389\"; // Function Call cout << Insert_dash(str); return 0;}",
"e": 1941,
"s": 1017,
"text": null
},
{
"code": "// Java program to implement// the above approachclass GFG{ // Function to check if char ch is// odd or notstatic boolean checkOdd(char ch){ return ((ch - '0') & 1) != 0 ? true : false;} // Function to insert dash - between// any 2 consecutive digit in string strstatic String Insert_dash(String num_str){ StringBuilder result_str = new StringBuilder(num_str); // Traverse the string character // by character for(int x = 0; x < num_str.length() - 1; x++) { // Compare every consecutive // character with the odd value if (checkOdd(num_str.charAt(x)) && checkOdd(num_str.charAt(x + 1))) { result_str.insert(x + 1, \"-\"); num_str = result_str.toString(); x++; } } // Print the resultant string return result_str.toString();} // Driver Codepublic static void main(String[] args){ // Given number in form of string String str = \"1745389\"; // Function call System.out.println(Insert_dash(str));}} // This code is contributed by rutvik_56",
"e": 3012,
"s": 1941,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to check if char ch is# odd or notdef checkOdd(ch): return ((ord(ch) - 48) & 1) # Function to insert dash - between# any 2 consecutive digit in string strdef Insert_dash(num_str): result_str = num_str # Traverse the string character # by character x = 0 while(x < len(num_str) - 1): # Compare every consecutive # character with the odd value if (checkOdd(num_str[x]) and checkOdd(num_str[x + 1])): result_str = (result_str[:x + 1] + '-' + result_str[x + 1:]) num_str = result_str x += 1 x += 1 # Print the resultant string return result_str # Driver Code # Given number in form of stringstr = \"1745389\" # Function callprint(Insert_dash(str)) # This code is contributed by vishu2908",
"e": 3873,
"s": 3012,
"text": null
},
{
"code": "// C# program to implement// the above approachusing System;using System.Text;class GFG{ // Function to check if char ch is// odd or notstatic bool checkOdd(char ch){ return ((ch - '0') & 1) != 0 ? true : false;} // Function to insert dash - between// any 2 consecutive digit in string strstatic String Insert_dash(String num_str){ StringBuilder result_str = new StringBuilder(num_str); // Traverse the string character // by character for(int x = 0; x < num_str.Length - 1; x++) { // Compare every consecutive // character with the odd value if (checkOdd(num_str[x]) && checkOdd(num_str[x + 1])) { result_str.Insert(x + 1, \"-\"); num_str = result_str.ToString(); x++; } } // Print the resultant string return result_str.ToString();} // Driver Codepublic static void Main(String[] args){ // Given number in form of string String str = \"1745389\"; // Function call Console.WriteLine(Insert_dash(str));}} // This code is contributed by Rajput-Ji",
"e": 4953,
"s": 3873,
"text": null
},
{
"code": null,
"e": 4963,
"s": 4953,
"text": "1-745-389"
},
{
"code": null,
"e": 5010,
"s": 4965,
"text": "Time Complexity: O(N) Auxiliary Space: O(1) "
},
{
"code": null,
"e": 5039,
"s": 5010,
"text": "Regular Expression Approach:"
},
{
"code": null,
"e": 5132,
"s": 5039,
"text": "The given problem can be solved using Regular Expression. The RE for this problem will be: "
},
{
"code": null,
"e": 5314,
"s": 5132,
"text": "(?<=[13579])(?=[13579])The given RE matches between odd numbers. We can replace the matched part of zero width with a dash, i.e.str = str.replaceAll(“(?<=[13579])(?=[13579])”, “-“);"
},
{
"code": null,
"e": 5365,
"s": 5314,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 5369,
"s": 5365,
"text": "C++"
},
{
"code": null,
"e": 5374,
"s": 5369,
"text": "Java"
},
{
"code": null,
"e": 5381,
"s": 5374,
"text": "Python"
},
{
"code": "// C++ Program to implement// the above approach#include <iostream>#include <regex>using namespace std; // Function to insert dash - between// any 2 consecutive odd digitstring Insert_dash(string str){ // Get the regex to be checked const regex pattern(\"([13579])([13579])\"); // Replaces the matched value // (here dash) with given string return regex_replace(str, pattern, \"$1-$2\");;} // Driver Codeint main(){ string str = \"1745389\"; cout << Insert_dash(str); return 0;} // This code is contributed by yuvraj_chandra",
"e": 5913,
"s": 5381,
"text": null
},
{
"code": "// Java program for the above approach import java.util.regex.*; public class GFG { // Function to insert dash - between // any 2 consecutive odd digit public static String Insert_dash(String str) { // Get the regex to be checked String regex = \"(?<=[13579])(?=[13579])\"; // Create a pattern from regex Pattern pattern = Pattern.compile(regex); // Create a matcher for the input String Matcher matcher = pattern.matcher(str); // Get the String to be replaced, // i.e. here dash String stringToBeReplaced = \"-\"; StringBuilder builder = new StringBuilder(); // Replace every matched pattern // with the target String // using replaceAll() method return (matcher .replaceAll(stringToBeReplaced)); } // Driver Code public static void main(String[] args) { // Given number in form of string String str = \"1745389\"; // Function Call System.out.println(Insert_dash(str)); }}",
"e": 6984,
"s": 5913,
"text": null
},
{
"code": "# Python program for the above approachimport re # Function to insert dash - between# any 2 consecutive odd digitdef Insert_dash(str): # Get the regex to be checked regex = \"(?<=[13579])(?=[13579])\" return re.sub(regex,'\\1-\\2', str) # Driver Code # Given number in form of stringstr = \"1745389\" # Function Callprint(Insert_dash(str)) # This code is contributed by yuvraj_chandra",
"e": 7374,
"s": 6984,
"text": null
},
{
"code": null,
"e": 7384,
"s": 7374,
"text": "1-745-389"
},
{
"code": null,
"e": 7396,
"s": 7386,
"text": "vishu2908"
},
{
"code": null,
"e": 7406,
"s": 7396,
"text": "rutvik_56"
},
{
"code": null,
"e": 7416,
"s": 7406,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 7431,
"s": 7416,
"text": "yuvraj_chandra"
},
{
"code": null,
"e": 7451,
"s": 7431,
"text": "abhishek0719kadiyan"
},
{
"code": null,
"e": 7461,
"s": 7451,
"text": "CPP-regex"
},
{
"code": null,
"e": 7485,
"s": 7461,
"text": "java-regular-expression"
},
{
"code": null,
"e": 7499,
"s": 7485,
"text": "number-digits"
},
{
"code": null,
"e": 7518,
"s": 7499,
"text": "regular-expression"
},
{
"code": null,
"e": 7536,
"s": 7518,
"text": "Pattern Searching"
},
{
"code": null,
"e": 7544,
"s": 7536,
"text": "Strings"
},
{
"code": null,
"e": 7552,
"s": 7544,
"text": "Strings"
},
{
"code": null,
"e": 7570,
"s": 7552,
"text": "Pattern Searching"
},
{
"code": null,
"e": 7668,
"s": 7570,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7751,
"s": 7668,
"text": "Reverse the substrings of the given String according to the given Array of indices"
},
{
"code": null,
"e": 7817,
"s": 7751,
"text": "Check if the given string is shuffled substring of another string"
},
{
"code": null,
"e": 7886,
"s": 7817,
"text": "How to check Aadhaar number is valid or not using Regular Expression"
},
{
"code": null,
"e": 7961,
"s": 7886,
"text": "How to validate GUID (Globally Unique Identifier) using Regular Expression"
},
{
"code": null,
"e": 8020,
"s": 7961,
"text": "How to validate pin code of India using Regular Expression"
},
{
"code": null,
"e": 8066,
"s": 8020,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 8091,
"s": 8066,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 8151,
"s": 8091,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 8166,
"s": 8151,
"text": "C++ Data Types"
}
] |
Rename specific column(s) in Pandas | 30 Jul, 2020
Given a pandas Dataframe, let’s see how to rename specific column(s) names using various methods.
First, let’s create a Dataframe:
Python3
# import pandas packageimport pandas as pd # defining a dictionaryd = {"Name": ["John", "Mary", "Helen"], "Marks": [95, 75, 99], "Roll No": [12, 21, 9]} # creating the pandas data framedf = pd.DataFrame(d) df
Output:
Method 1: Using Dataframe.rename().
This method is a way to rename the required columns in Pandas. It allows us to specify the columns’ names to be changed in the form of a dictionary with the keys and values as the current and new names of the respective columns.
Example 1: Renaming a single column.
Python3
# import pandas packageimport pandas as pd # defining a dictionaryd = {"Name": ["John", "Mary", "Helen"], "Marks": [95, 75, 99], "Roll No": [12, 21, 9]} # creating the pandas data framedf = pd.DataFrame(d) # displaying the columns # before renamingprint(df.columns) # renaming the column "A"df.rename(columns = {"Name": "Names"}, inplace = True) # displaying the columns after renamingprint(df.columns)
Output:
Example 2: Renaming multiple columns.
Python3
# import pandas packageimport pandas as pd # defining a dictionaryd = {"Name": ["John", "Mary", "Helen"], "Marks": [95, 75, 99], "Roll No": [12, 21, 9]} # creating the pandas dataframedf = pd.DataFrame(d) # displaying the columns before renamingprint(df.columns) # renaming the columnsdf.rename({"Name": "Student Name", "Marks": "Marks Obtained", "Roll No": "Roll Number"}, axis = "columns", inplace = True) # displaying the columns after renamingprint(df.columns)
Output:
Example 3: Passing the lambda function to rename columns.
Python3
# using the same modified dataframe# df from Renaming Multiple Columns# this adds ':' at the end # of each column namedf = df.rename(columns = lambda x: x+':') # printing the columnsprint(df.columns)
Output:
The lambda function is a small anonymous function that can take any number of arguments but can only have one expression. We can use it if we have to modify all columns at once. It is useful if the number of columns is large, and it is not an easy task to rename them using a list or a dictionary (a lot of code, phew!). In the above example, we used the lambda function to add a colon (‘:’) at the end of each column name.
Method 2: Using the values attribute.
We can use values attribute on the column we want to rename and directly change it.
Python3
# using the same modified dataframe # df from Renaming Multiple Columns# Renaming the third columndf.columns.values[2] = "Roll Number" # printing the columnsprint(df.columns)
Output:
Method 3: Using a new list of column names.
We pass the updated column names as a list to rename the columns. The length of the list we provide should be the same as the number of columns in the data frame. Otherwise, an error occurs.
Python3
# Creating a list of new columnsdf_cols = ["Student Name", "Marks Obtained", "Roll Number"] # printing the columns # before renamingprint(df.columns) # Renaming the columnsdf.columns = df_cols # printing the columns # after renamingprint(df.columns)
Output:
Method 4: Using the Dataframe.columns.str.replace().
In general, if the number of columns in the Pandas dataframe is huge, say nearly 100, and we want to replace the space in all the column names (if it exists) by an underscore. It is not easy to provide a list or dictionary to rename all the columns. Therefore, we use a method as below –
Python3
# printing the column # names before renamingprint(df.columns) # Replacing the space in column # names by an underscoredf.columns = df.columns.str.replace(' ', '_') # printing the column names # after renamingprint(df.columns)
Output:
Also, other string methods such as str.lower can be used to make all the column names lowercase.
Note: Suppose that a column name is not present in the original data frame, but is in the dictionary provided to rename the columns. By default, the errors parameter of the rename() function has the value ‘ignore.’ Therefore, no error is displayed and, the existing columns are renamed as instructed. In contrast, if we set the errors parameter to ‘raise,’ then an error is raised, stating that the particular column does not exist in the original data frame.
Below is an example of the same:
Example 1: No error is raised as by default errors is set to ‘ignore.’
Python3
# NO ERROR IS RAISED # import pandas packageimport pandas as pd # defining a dictionaryd = {"A": [1, 2, 3], "B": [4, 5, 6]} # creating the pandas dataframedf = pd.DataFrame(d) # displaying the columns before renamingprint(df.columns) # renaming the columns# column "C" is not in # the original dataframe # errors parameter is# set to 'ignore' by defaultdf.rename(columns = {"A": "a", "B": "b", "C": "c"}, inplace = True) # displaying the columns# after renamingprint(df.columns)
Output:
Example 2: Setting the parameter errors to ‘raise.’ Error is raised ( column C does not exist in the original data frame.)
Python3
# ERROR IS RAISED # import pandas packageimport pandas as pd # defining a dictionaryd = {"A": [1, 2, 3], "B": [4, 5, 6]} # creating the pandas dataframedf = pd.DataFrame(d) # displaying the columns# before renamingprint(df.columns) # renaming the columns# column "C" is not in the # original dataframe setting# the errors parameter to 'raise'df.rename(columns = {"A": "a", "B": "b", "C": "c"}, inplace = True, errors = 'raise') # displaying the columns # after renamingprint(df.columns)
Output:
Error is raised
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jul, 2020"
},
{
"code": null,
"e": 153,
"s": 54,
"text": "Given a pandas Dataframe, let’s see how to rename specific column(s) names using various methods. "
},
{
"code": null,
"e": 186,
"s": 153,
"text": "First, let’s create a Dataframe:"
},
{
"code": null,
"e": 194,
"s": 186,
"text": "Python3"
},
{
"code": "# import pandas packageimport pandas as pd # defining a dictionaryd = {\"Name\": [\"John\", \"Mary\", \"Helen\"], \"Marks\": [95, 75, 99], \"Roll No\": [12, 21, 9]} # creating the pandas data framedf = pd.DataFrame(d) df",
"e": 414,
"s": 194,
"text": null
},
{
"code": null,
"e": 422,
"s": 414,
"text": "Output:"
},
{
"code": null,
"e": 458,
"s": 422,
"text": "Method 1: Using Dataframe.rename()."
},
{
"code": null,
"e": 688,
"s": 458,
"text": "This method is a way to rename the required columns in Pandas. It allows us to specify the columns’ names to be changed in the form of a dictionary with the keys and values as the current and new names of the respective columns. "
},
{
"code": null,
"e": 725,
"s": 688,
"text": "Example 1: Renaming a single column."
},
{
"code": null,
"e": 733,
"s": 725,
"text": "Python3"
},
{
"code": "# import pandas packageimport pandas as pd # defining a dictionaryd = {\"Name\": [\"John\", \"Mary\", \"Helen\"], \"Marks\": [95, 75, 99], \"Roll No\": [12, 21, 9]} # creating the pandas data framedf = pd.DataFrame(d) # displaying the columns # before renamingprint(df.columns) # renaming the column \"A\"df.rename(columns = {\"Name\": \"Names\"}, inplace = True) # displaying the columns after renamingprint(df.columns)",
"e": 1159,
"s": 733,
"text": null
},
{
"code": null,
"e": 1167,
"s": 1159,
"text": "Output:"
},
{
"code": null,
"e": 1205,
"s": 1167,
"text": "Example 2: Renaming multiple columns."
},
{
"code": null,
"e": 1213,
"s": 1205,
"text": "Python3"
},
{
"code": "# import pandas packageimport pandas as pd # defining a dictionaryd = {\"Name\": [\"John\", \"Mary\", \"Helen\"], \"Marks\": [95, 75, 99], \"Roll No\": [12, 21, 9]} # creating the pandas dataframedf = pd.DataFrame(d) # displaying the columns before renamingprint(df.columns) # renaming the columnsdf.rename({\"Name\": \"Student Name\", \"Marks\": \"Marks Obtained\", \"Roll No\": \"Roll Number\"}, axis = \"columns\", inplace = True) # displaying the columns after renamingprint(df.columns)",
"e": 1723,
"s": 1213,
"text": null
},
{
"code": null,
"e": 1731,
"s": 1723,
"text": "Output:"
},
{
"code": null,
"e": 1789,
"s": 1731,
"text": "Example 3: Passing the lambda function to rename columns."
},
{
"code": null,
"e": 1797,
"s": 1789,
"text": "Python3"
},
{
"code": "# using the same modified dataframe# df from Renaming Multiple Columns# this adds ':' at the end # of each column namedf = df.rename(columns = lambda x: x+':') # printing the columnsprint(df.columns)",
"e": 1998,
"s": 1797,
"text": null
},
{
"code": null,
"e": 2006,
"s": 1998,
"text": "Output:"
},
{
"code": null,
"e": 2430,
"s": 2006,
"text": "The lambda function is a small anonymous function that can take any number of arguments but can only have one expression. We can use it if we have to modify all columns at once. It is useful if the number of columns is large, and it is not an easy task to rename them using a list or a dictionary (a lot of code, phew!). In the above example, we used the lambda function to add a colon (‘:’) at the end of each column name."
},
{
"code": null,
"e": 2468,
"s": 2430,
"text": "Method 2: Using the values attribute."
},
{
"code": null,
"e": 2552,
"s": 2468,
"text": "We can use values attribute on the column we want to rename and directly change it."
},
{
"code": null,
"e": 2560,
"s": 2552,
"text": "Python3"
},
{
"code": "# using the same modified dataframe # df from Renaming Multiple Columns# Renaming the third columndf.columns.values[2] = \"Roll Number\" # printing the columnsprint(df.columns)",
"e": 2737,
"s": 2560,
"text": null
},
{
"code": null,
"e": 2745,
"s": 2737,
"text": "Output:"
},
{
"code": null,
"e": 2789,
"s": 2745,
"text": "Method 3: Using a new list of column names."
},
{
"code": null,
"e": 2980,
"s": 2789,
"text": "We pass the updated column names as a list to rename the columns. The length of the list we provide should be the same as the number of columns in the data frame. Otherwise, an error occurs."
},
{
"code": null,
"e": 2988,
"s": 2980,
"text": "Python3"
},
{
"code": "# Creating a list of new columnsdf_cols = [\"Student Name\", \"Marks Obtained\", \"Roll Number\"] # printing the columns # before renamingprint(df.columns) # Renaming the columnsdf.columns = df_cols # printing the columns # after renamingprint(df.columns)",
"e": 3262,
"s": 2988,
"text": null
},
{
"code": null,
"e": 3270,
"s": 3262,
"text": "Output:"
},
{
"code": null,
"e": 3323,
"s": 3270,
"text": "Method 4: Using the Dataframe.columns.str.replace()."
},
{
"code": null,
"e": 3611,
"s": 3323,
"text": "In general, if the number of columns in the Pandas dataframe is huge, say nearly 100, and we want to replace the space in all the column names (if it exists) by an underscore. It is not easy to provide a list or dictionary to rename all the columns. Therefore, we use a method as below –"
},
{
"code": null,
"e": 3619,
"s": 3611,
"text": "Python3"
},
{
"code": "# printing the column # names before renamingprint(df.columns) # Replacing the space in column # names by an underscoredf.columns = df.columns.str.replace(' ', '_') # printing the column names # after renamingprint(df.columns)",
"e": 3848,
"s": 3619,
"text": null
},
{
"code": null,
"e": 3856,
"s": 3848,
"text": "Output:"
},
{
"code": null,
"e": 3953,
"s": 3856,
"text": "Also, other string methods such as str.lower can be used to make all the column names lowercase."
},
{
"code": null,
"e": 4414,
"s": 3953,
"text": "Note: Suppose that a column name is not present in the original data frame, but is in the dictionary provided to rename the columns. By default, the errors parameter of the rename() function has the value ‘ignore.’ Therefore, no error is displayed and, the existing columns are renamed as instructed. In contrast, if we set the errors parameter to ‘raise,’ then an error is raised, stating that the particular column does not exist in the original data frame. "
},
{
"code": null,
"e": 4447,
"s": 4414,
"text": "Below is an example of the same:"
},
{
"code": null,
"e": 4518,
"s": 4447,
"text": "Example 1: No error is raised as by default errors is set to ‘ignore.’"
},
{
"code": null,
"e": 4526,
"s": 4518,
"text": "Python3"
},
{
"code": "# NO ERROR IS RAISED # import pandas packageimport pandas as pd # defining a dictionaryd = {\"A\": [1, 2, 3], \"B\": [4, 5, 6]} # creating the pandas dataframedf = pd.DataFrame(d) # displaying the columns before renamingprint(df.columns) # renaming the columns# column \"C\" is not in # the original dataframe # errors parameter is# set to 'ignore' by defaultdf.rename(columns = {\"A\": \"a\", \"B\": \"b\", \"C\": \"c\"}, inplace = True) # displaying the columns# after renamingprint(df.columns)",
"e": 5047,
"s": 4526,
"text": null
},
{
"code": null,
"e": 5055,
"s": 5047,
"text": "Output:"
},
{
"code": null,
"e": 5178,
"s": 5055,
"text": "Example 2: Setting the parameter errors to ‘raise.’ Error is raised ( column C does not exist in the original data frame.)"
},
{
"code": null,
"e": 5186,
"s": 5178,
"text": "Python3"
},
{
"code": "# ERROR IS RAISED # import pandas packageimport pandas as pd # defining a dictionaryd = {\"A\": [1, 2, 3], \"B\": [4, 5, 6]} # creating the pandas dataframedf = pd.DataFrame(d) # displaying the columns# before renamingprint(df.columns) # renaming the columns# column \"C\" is not in the # original dataframe setting# the errors parameter to 'raise'df.rename(columns = {\"A\": \"a\", \"B\": \"b\", \"C\": \"c\"}, inplace = True, errors = 'raise') # displaying the columns # after renamingprint(df.columns)",
"e": 5715,
"s": 5186,
"text": null
},
{
"code": null,
"e": 5723,
"s": 5715,
"text": "Output:"
},
{
"code": null,
"e": 5739,
"s": 5723,
"text": "Error is raised"
},
{
"code": null,
"e": 5763,
"s": 5739,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 5786,
"s": 5763,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 5800,
"s": 5786,
"text": "Python-pandas"
},
{
"code": null,
"e": 5807,
"s": 5800,
"text": "Python"
}
] |
Java.io.BufferedReader Class in Java | 03 May, 2022
Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made by a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader.
Implementation: The content inside the file is as follows:
This is first line
this is second line
Example
Java
// Java Program to Illustrate BufferedReader Class// Via Its Methods // Importing required classesimport java.io.BufferedReader;import java.io.FileReader;import java.io.IOException; // Classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating object of FileReader and BufferedReader // class FileReader fr = new FileReader("file.txt"); BufferedReader br = new BufferedReader(fr); char c[] = new char[20]; // Illustrating markSupported() method if (br.markSupported()) { // Print statement System.out.println( "mark() method is supported"); // Illustrating mark method br.mark(100); } // File Contents is as follows: // This is first line // this is second line // Skipping 8 characters br.skip(8); // Illustrating ready() method if (br.ready()) { // Illustrating readLine() method System.out.println(br.readLine()); // Illustrating read(char c[],int off,int len) br.read(c); for (int i = 0; i < 20; i++) { System.out.print(c[i]); } System.out.println(); // Illustrating reset() method br.reset(); for (int i = 0; i < 8; i++) { // Illustrating read() method System.out.print((char)br.read()); } } }}
Output:
mark() method is supported
first line
this is second line
This is
This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
Java-Classes
Java-I/O
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 May, 2022"
},
{
"code": null,
"e": 736,
"s": 52,
"text": "Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes. In general, each read request made by a Reader causes a corresponding read request to be made of the underlying character or byte stream. It is therefore advisable to wrap a BufferedReader around any Reader whose read() operations may be costly, such as FileReaders and InputStreamReaders. Programs that use DataInputStreams for textual input can be localized by replacing each DataInputStream with an appropriate BufferedReader."
},
{
"code": null,
"e": 795,
"s": 736,
"text": "Implementation: The content inside the file is as follows:"
},
{
"code": null,
"e": 834,
"s": 795,
"text": "This is first line\nthis is second line"
},
{
"code": null,
"e": 842,
"s": 834,
"text": "Example"
},
{
"code": null,
"e": 847,
"s": 842,
"text": "Java"
},
{
"code": "// Java Program to Illustrate BufferedReader Class// Via Its Methods // Importing required classesimport java.io.BufferedReader;import java.io.FileReader;import java.io.IOException; // Classclass GFG { // Main driver method public static void main(String[] args) throws IOException { // Creating object of FileReader and BufferedReader // class FileReader fr = new FileReader(\"file.txt\"); BufferedReader br = new BufferedReader(fr); char c[] = new char[20]; // Illustrating markSupported() method if (br.markSupported()) { // Print statement System.out.println( \"mark() method is supported\"); // Illustrating mark method br.mark(100); } // File Contents is as follows: // This is first line // this is second line // Skipping 8 characters br.skip(8); // Illustrating ready() method if (br.ready()) { // Illustrating readLine() method System.out.println(br.readLine()); // Illustrating read(char c[],int off,int len) br.read(c); for (int i = 0; i < 20; i++) { System.out.print(c[i]); } System.out.println(); // Illustrating reset() method br.reset(); for (int i = 0; i < 8; i++) { // Illustrating read() method System.out.print((char)br.read()); } } }}",
"e": 2387,
"s": 847,
"text": null
},
{
"code": null,
"e": 2395,
"s": 2387,
"text": "Output:"
},
{
"code": null,
"e": 2462,
"s": 2395,
"text": "mark() method is supported\nfirst line\nthis is second line\nThis is "
},
{
"code": null,
"e": 2885,
"s": 2462,
"text": "This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 2899,
"s": 2885,
"text": "solankimayank"
},
{
"code": null,
"e": 2912,
"s": 2899,
"text": "Java-Classes"
},
{
"code": null,
"e": 2921,
"s": 2912,
"text": "Java-I/O"
},
{
"code": null,
"e": 2926,
"s": 2921,
"text": "Java"
},
{
"code": null,
"e": 2931,
"s": 2926,
"text": "Java"
}
] |
Least Angle Regression (LARS) | 19 Apr, 2021
Regression is a supervised machine learning task that can predict continuous values (real numbers), as compared to classification, that can predict categorical or discrete values. Before we begin, if you are a beginner, I highly recommend this article. Least Angle Regression (LARS) is an algorithm used in regression for high dimensional data (i.e., data with a large number of attributes). Least Angle Regression is somewhat similar to forward stepwise regression. Since it is used with data that has lots of attributes, at each step, LARS finds the attribute which is most highly correlated to the target value. There may be more than one attribute that has the same correlation. In this scenario, LARS averages the attributes and proceeds in a direction that is at the same angle to the attributes. This is exactly why this algorithm is called Least Angle regression. Basically, LARS makes leaps in the most optimally calculated direction without overfitting the model. Algorithm:
Normalize all values to have zero mean and unit variance.
Find a variable that is most highly correlated to the residual. Move the regression line in this direction until we reach another variable that has the same or higher correlation.
Note : Residual is the difference between the observed value and the predicted value. Variable, here implies an attribute.
When we have two variables that have the same correlation, move the regression line at an angle that is in between (i.e., least angle between the two variables).
Continue this until all of our data is exhausted or until you think the model is big and ‘general’ enough.
Mathematically, LARS works as follows :
All coefficients, ‘B’ are set to 0.
The predictor, xj is found that is most correlated to y.
Increase the coefficient Bj in the direction that is most correlated with y and stop when you find some other predictor xk the has equal or higher correlation than xj.
Extend (Bj, Bk) in a direction that is equiangular (has the same angle) to both xj and xk.
Continue and repeat until all predictors are in the model.
Implementation of LARS in Python3: For this example, we will be using the Boston housing dataset that has the median value of homes in the Boston Massachusetts area. You can learn more bout this dataset here. For evaluation, we will be using the r2 score. The best possible r2 score is 1.0. It can also be negative and is 0, when the predictor always predicts a constant value, regardless of values of attributes. Code:
python3
# Importing modules that are required from sklearn.datasets import load_bostonfrom sklearn.linear_model import LassoLarsfrom sklearn.metrics import r2_scorefrom sklearn.model_selection import train_test_split # Loading datasetdataset = load_boston()X = dataset.datay = dataset.target # Splitting training and testing dataX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.15, random_state = 42) # Creating and fitting the regressorregressor = LassoLars(alpha = 0.1)regressor.fit(X_train, y_train) # Evaluating modelprediction = regressor.predict(X_test) print(f"r2 Score of test set : {r2_score(y_test, prediction)}")
Output:
r2 Score of test set : 0.6815908068381828
We have achieved an r2 score of approximately 0.6816, which is actually quite good. Advantages of using LARS:
Computationally as fast as forward selection but may sometimes be more accurate.
Numerically very efficient when the number of features is much larger than the number of data instances.
It can easily be modified to produce solutions for other estimators.
Disadvantages of using LARS:
LARS is highly sensitive to noise and can produce unpredictable results sometimes.
Reference:
Wikipedia
scikit-learn documentation
Towards Data Science
nidhi_biet
simmytarika5
Machine Learning
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Apr, 2021"
},
{
"code": null,
"e": 1015,
"s": 28,
"text": "Regression is a supervised machine learning task that can predict continuous values (real numbers), as compared to classification, that can predict categorical or discrete values. Before we begin, if you are a beginner, I highly recommend this article. Least Angle Regression (LARS) is an algorithm used in regression for high dimensional data (i.e., data with a large number of attributes). Least Angle Regression is somewhat similar to forward stepwise regression. Since it is used with data that has lots of attributes, at each step, LARS finds the attribute which is most highly correlated to the target value. There may be more than one attribute that has the same correlation. In this scenario, LARS averages the attributes and proceeds in a direction that is at the same angle to the attributes. This is exactly why this algorithm is called Least Angle regression. Basically, LARS makes leaps in the most optimally calculated direction without overfitting the model. Algorithm: "
},
{
"code": null,
"e": 1073,
"s": 1015,
"text": "Normalize all values to have zero mean and unit variance."
},
{
"code": null,
"e": 1253,
"s": 1073,
"text": "Find a variable that is most highly correlated to the residual. Move the regression line in this direction until we reach another variable that has the same or higher correlation."
},
{
"code": null,
"e": 1378,
"s": 1253,
"text": "Note : Residual is the difference between the observed value and the predicted value. Variable, here implies an attribute. "
},
{
"code": null,
"e": 1540,
"s": 1378,
"text": "When we have two variables that have the same correlation, move the regression line at an angle that is in between (i.e., least angle between the two variables)."
},
{
"code": null,
"e": 1647,
"s": 1540,
"text": "Continue this until all of our data is exhausted or until you think the model is big and ‘general’ enough."
},
{
"code": null,
"e": 1691,
"s": 1649,
"text": "Mathematically, LARS works as follows : "
},
{
"code": null,
"e": 1727,
"s": 1691,
"text": "All coefficients, ‘B’ are set to 0."
},
{
"code": null,
"e": 1784,
"s": 1727,
"text": "The predictor, xj is found that is most correlated to y."
},
{
"code": null,
"e": 1952,
"s": 1784,
"text": "Increase the coefficient Bj in the direction that is most correlated with y and stop when you find some other predictor xk the has equal or higher correlation than xj."
},
{
"code": null,
"e": 2043,
"s": 1952,
"text": "Extend (Bj, Bk) in a direction that is equiangular (has the same angle) to both xj and xk."
},
{
"code": null,
"e": 2102,
"s": 2043,
"text": "Continue and repeat until all predictors are in the model."
},
{
"code": null,
"e": 2524,
"s": 2102,
"text": "Implementation of LARS in Python3: For this example, we will be using the Boston housing dataset that has the median value of homes in the Boston Massachusetts area. You can learn more bout this dataset here. For evaluation, we will be using the r2 score. The best possible r2 score is 1.0. It can also be negative and is 0, when the predictor always predicts a constant value, regardless of values of attributes. Code: "
},
{
"code": null,
"e": 2532,
"s": 2524,
"text": "python3"
},
{
"code": "# Importing modules that are required from sklearn.datasets import load_bostonfrom sklearn.linear_model import LassoLarsfrom sklearn.metrics import r2_scorefrom sklearn.model_selection import train_test_split # Loading datasetdataset = load_boston()X = dataset.datay = dataset.target # Splitting training and testing dataX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.15, random_state = 42) # Creating and fitting the regressorregressor = LassoLars(alpha = 0.1)regressor.fit(X_train, y_train) # Evaluating modelprediction = regressor.predict(X_test) print(f\"r2 Score of test set : {r2_score(y_test, prediction)}\")",
"e": 3192,
"s": 2532,
"text": null
},
{
"code": null,
"e": 3202,
"s": 3192,
"text": "Output: "
},
{
"code": null,
"e": 3244,
"s": 3202,
"text": "r2 Score of test set : 0.6815908068381828"
},
{
"code": null,
"e": 3356,
"s": 3244,
"text": "We have achieved an r2 score of approximately 0.6816, which is actually quite good. Advantages of using LARS: "
},
{
"code": null,
"e": 3437,
"s": 3356,
"text": "Computationally as fast as forward selection but may sometimes be more accurate."
},
{
"code": null,
"e": 3542,
"s": 3437,
"text": "Numerically very efficient when the number of features is much larger than the number of data instances."
},
{
"code": null,
"e": 3611,
"s": 3542,
"text": "It can easily be modified to produce solutions for other estimators."
},
{
"code": null,
"e": 3642,
"s": 3611,
"text": "Disadvantages of using LARS: "
},
{
"code": null,
"e": 3725,
"s": 3642,
"text": "LARS is highly sensitive to noise and can produce unpredictable results sometimes."
},
{
"code": null,
"e": 3736,
"s": 3725,
"text": "Reference:"
},
{
"code": null,
"e": 3746,
"s": 3736,
"text": "Wikipedia"
},
{
"code": null,
"e": 3773,
"s": 3746,
"text": "scikit-learn documentation"
},
{
"code": null,
"e": 3794,
"s": 3773,
"text": "Towards Data Science"
},
{
"code": null,
"e": 3807,
"s": 3796,
"text": "nidhi_biet"
},
{
"code": null,
"e": 3820,
"s": 3807,
"text": "simmytarika5"
},
{
"code": null,
"e": 3837,
"s": 3820,
"text": "Machine Learning"
},
{
"code": null,
"e": 3844,
"s": 3837,
"text": "Python"
},
{
"code": null,
"e": 3861,
"s": 3844,
"text": "Machine Learning"
}
] |
Open a new Window with a button in Python-Tkinter | 13 Jul, 2021
Python provides a variety of GUI (Graphic User Interface) such as PyQt, Tkinter, Kivy and soon. Among them, tkinter is the most commonly used GUI module in Python since it is simple and easy to learn and implement as well. The word Tkinter comes from the tk interface. The tkinter module is available in Python standard library.Note: For more information, refer to Python GUI – tkinter
For Ubuntu, you have to install tkinter module by writing following command:
sudo apt-get install python-tk
When a Tkinter program runs, it runs a mainloop (an infinite loop) which is responsible for running a GUI program. At a time only one instance of mainloop can be active, so in order to open a new window we have to use a widget, Toplevel.A Toplevel widget works pretty much like a Frame, but it opens in a separate top-level window, such windows have all the properties that a main window (root/master window) should have.To open a new window with a button, we will use events.Example 1:
Python3
# This will import all the widgets# and modules which are available in# tkinter and ttk modulefrom tkinter import *from tkinter.ttk import * # creates a Tk() objectmaster = Tk() # sets the geometry of main# root windowmaster.geometry("200x200") # function to open a new window# on a button clickdef openNewWindow(): # Toplevel object which will # be treated as a new window newWindow = Toplevel(master) # sets the title of the # Toplevel widget newWindow.title("New Window") # sets the geometry of toplevel newWindow.geometry("200x200") # A Label widget to show in toplevel Label(newWindow, text ="This is a new window").pack() label = Label(master, text ="This is the main window") label.pack(pady = 10) # a button widget which will open a# new window on button clickbtn = Button(master, text ="Click to open a new window", command = openNewWindow)btn.pack(pady = 10) # mainloop, runs infinitelymainloop()
Output:
Example 2: This will be a class based approach, in this we will create a class which will derive Toplevel widget class and will behave like a toplevel. This method will be useful when you want to add some other properties to an existing Toplevel widget class. Every object of this class will be a Toplevel widget. We will also use bind() method to register click event.
Python3
# This will import all the widgets# and modules which are available in# tkinter and ttk modulefrom tkinter import *from tkinter.ttk import * class NewWindow(Toplevel): def __init__(self, master = None): super().__init__(master = master) self.title("New Window") self.geometry("200x200") label = Label(self, text ="This is a new Window") label.pack() # creates a Tk() objectmaster = Tk() # sets the geometry of# main root windowmaster.geometry("200x200") label = Label(master, text ="This is the main window")label.pack(side = TOP, pady = 10) # a button widget which will# open a new window on button clickbtn = Button(master, text ="Click to open a new window") # Following line will bind click event# On any click left / right button# of mouse a new window will be openedbtn.bind("<Button>", lambda e: NewWindow(master)) btn.pack(pady = 10) # mainloop, runs infinitelymainloop()
Output:
rajeev0719singh
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Jul, 2021"
},
{
"code": null,
"e": 415,
"s": 28,
"text": "Python provides a variety of GUI (Graphic User Interface) such as PyQt, Tkinter, Kivy and soon. Among them, tkinter is the most commonly used GUI module in Python since it is simple and easy to learn and implement as well. The word Tkinter comes from the tk interface. The tkinter module is available in Python standard library.Note: For more information, refer to Python GUI – tkinter "
},
{
"code": null,
"e": 493,
"s": 415,
"text": "For Ubuntu, you have to install tkinter module by writing following command: "
},
{
"code": null,
"e": 526,
"s": 493,
"text": "sudo apt-get install python-tk "
},
{
"code": null,
"e": 1015,
"s": 526,
"text": "When a Tkinter program runs, it runs a mainloop (an infinite loop) which is responsible for running a GUI program. At a time only one instance of mainloop can be active, so in order to open a new window we have to use a widget, Toplevel.A Toplevel widget works pretty much like a Frame, but it opens in a separate top-level window, such windows have all the properties that a main window (root/master window) should have.To open a new window with a button, we will use events.Example 1: "
},
{
"code": null,
"e": 1023,
"s": 1015,
"text": "Python3"
},
{
"code": "# This will import all the widgets# and modules which are available in# tkinter and ttk modulefrom tkinter import *from tkinter.ttk import * # creates a Tk() objectmaster = Tk() # sets the geometry of main# root windowmaster.geometry(\"200x200\") # function to open a new window# on a button clickdef openNewWindow(): # Toplevel object which will # be treated as a new window newWindow = Toplevel(master) # sets the title of the # Toplevel widget newWindow.title(\"New Window\") # sets the geometry of toplevel newWindow.geometry(\"200x200\") # A Label widget to show in toplevel Label(newWindow, text =\"This is a new window\").pack() label = Label(master, text =\"This is the main window\") label.pack(pady = 10) # a button widget which will open a# new window on button clickbtn = Button(master, text =\"Click to open a new window\", command = openNewWindow)btn.pack(pady = 10) # mainloop, runs infinitelymainloop()",
"e": 2016,
"s": 1023,
"text": null
},
{
"code": null,
"e": 2026,
"s": 2016,
"text": "Output: "
},
{
"code": null,
"e": 2397,
"s": 2026,
"text": "Example 2: This will be a class based approach, in this we will create a class which will derive Toplevel widget class and will behave like a toplevel. This method will be useful when you want to add some other properties to an existing Toplevel widget class. Every object of this class will be a Toplevel widget. We will also use bind() method to register click event. "
},
{
"code": null,
"e": 2405,
"s": 2397,
"text": "Python3"
},
{
"code": "# This will import all the widgets# and modules which are available in# tkinter and ttk modulefrom tkinter import *from tkinter.ttk import * class NewWindow(Toplevel): def __init__(self, master = None): super().__init__(master = master) self.title(\"New Window\") self.geometry(\"200x200\") label = Label(self, text =\"This is a new Window\") label.pack() # creates a Tk() objectmaster = Tk() # sets the geometry of# main root windowmaster.geometry(\"200x200\") label = Label(master, text =\"This is the main window\")label.pack(side = TOP, pady = 10) # a button widget which will# open a new window on button clickbtn = Button(master, text =\"Click to open a new window\") # Following line will bind click event# On any click left / right button# of mouse a new window will be openedbtn.bind(\"<Button>\", lambda e: NewWindow(master)) btn.pack(pady = 10) # mainloop, runs infinitelymainloop()",
"e": 3359,
"s": 2405,
"text": null
},
{
"code": null,
"e": 3369,
"s": 3359,
"text": "Output: "
},
{
"code": null,
"e": 3387,
"s": 3371,
"text": "rajeev0719singh"
},
{
"code": null,
"e": 3402,
"s": 3387,
"text": "Python-tkinter"
},
{
"code": null,
"e": 3409,
"s": 3402,
"text": "Python"
}
] |
SAML Authentication | 19 Aug, 2020
SAML is an XML based framework that stands for Security Assertion Markup Language. Let us see how SAML is used to enable SSO (Single-Sign-On). SSO is a term used for a type of login method where a company configures all of its web apps in such a way that the user can log in to all of these apps by just signing in once.
Example – When one logs in on gmail.com, they can visit YouTube, Google Drive, and other Google services without having to sign in to each service separately.
The SAML authentication flow is based on two entities –
Service Providers (SP) – The SP receives the authentication from the IdP and grants the authorisation to the user.Identity Providers (IdP) – The IdP authenticates a user and sends their credentials along with their access rights for the service to the SP.
Service Providers (SP) – The SP receives the authentication from the IdP and grants the authorisation to the user.
Identity Providers (IdP) – The IdP authenticates a user and sends their credentials along with their access rights for the service to the SP.
In the example given above, SP will be Gmail and IdP will be Google. SAML enables SSO, and as it is explained above, a user can log in once and the same credentials will be used to log into other SPs.SAML Authentication Workflow –
A user tries to log in to Gmail.Gmail generates a SAML request.The SAML request is sent to Google by the browser, which parses this request, authenticates the user and creates a SAML response. This SAML response is encoded and sent back to the browser.The browser sends this SAML response back to Gmail for verification.If the user is successfully verified, they are logged in to Gmail.
A user tries to log in to Gmail.
Gmail generates a SAML request.
The SAML request is sent to Google by the browser, which parses this request, authenticates the user and creates a SAML response. This SAML response is encoded and sent back to the browser.
The browser sends this SAML response back to Gmail for verification.
If the user is successfully verified, they are logged in to Gmail.
SAML Request –
Some of the important terms in the SAML request are defined below –
ID – Identifier for a particular SAML request.Issuer – The name of the service provider (SP).NameID – The username/email address or phone number which is used to identify a user.AssertionConsumerServiceURL – The SAML URL interface of the SP where the IP sends the auth token.
ID – Identifier for a particular SAML request.
Issuer – The name of the service provider (SP).
NameID – The username/email address or phone number which is used to identify a user.
AssertionConsumerServiceURL – The SAML URL interface of the SP where the IP sends the auth token.
SAML Response –
A SAML response consists of two parts –
Assertion –It is an XML document that has the details of the user. This contains the timestamp of the user login event and the method of authentication used (eg. 2 Factor Authentication, Kerberos, etc.)Signature –It is a Base64 encoded string which protects the integrity of the assertion. (If an attacker tries to change the username in the assertion to the victim’s username, the signature will prevent the hacker from logging in as the user).
Assertion –It is an XML document that has the details of the user. This contains the timestamp of the user login event and the method of authentication used (eg. 2 Factor Authentication, Kerberos, etc.)
Signature –It is a Base64 encoded string which protects the integrity of the assertion. (If an attacker tries to change the username in the assertion to the victim’s username, the signature will prevent the hacker from logging in as the user).
Key Generation –
The Identity Provider (IdP) generates a private key and a public key. It signs the assertion with the private key. The public key is shared with the Service Provider (SP) which uses it to verify the SAML response and then log the user in.SAML Vulnerabilities Exploited by Hackers –
Signature not checked –If someone is able to change the name id (username) in the SAML response and log in as someone else due to the lack of a signature checking process.Signature only checked when it exists –If someone changes the name id value and removes the signature before the response is received by the browser and is still able to log in as the victim.Comment Injection –A user can be registered with an XML comment in the username as follows –email: prerit<!--notprerit-->@test.comWhile processing the SAML response, the SP will ignore the comment and log us in as the victim. The entire SAML response can be intercepted by using a proxy like a burp suite. Note that it has to be decoded first by the URL format and then by the Base64 format in order to be viewed.SAML Replay –The attacker captures the SAML response and uses it multiple times to log in as the victim.
Signature not checked –If someone is able to change the name id (username) in the SAML response and log in as someone else due to the lack of a signature checking process.
Signature only checked when it exists –If someone changes the name id value and removes the signature before the response is received by the browser and is still able to log in as the victim.
Comment Injection –A user can be registered with an XML comment in the username as follows –email: prerit<!--notprerit-->@test.comWhile processing the SAML response, the SP will ignore the comment and log us in as the victim. The entire SAML response can be intercepted by using a proxy like a burp suite. Note that it has to be decoded first by the URL format and then by the Base64 format in order to be viewed.
email: prerit<!--notprerit-->@test.com
While processing the SAML response, the SP will ignore the comment and log us in as the victim. The entire SAML response can be intercepted by using a proxy like a burp suite. Note that it has to be decoded first by the URL format and then by the Base64 format in order to be viewed.
SAML Replay –The attacker captures the SAML response and uses it multiple times to log in as the victim.
Information-Security
Computer Networks
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Aug, 2020"
},
{
"code": null,
"e": 349,
"s": 28,
"text": "SAML is an XML based framework that stands for Security Assertion Markup Language. Let us see how SAML is used to enable SSO (Single-Sign-On). SSO is a term used for a type of login method where a company configures all of its web apps in such a way that the user can log in to all of these apps by just signing in once."
},
{
"code": null,
"e": 508,
"s": 349,
"text": "Example – When one logs in on gmail.com, they can visit YouTube, Google Drive, and other Google services without having to sign in to each service separately."
},
{
"code": null,
"e": 564,
"s": 508,
"text": "The SAML authentication flow is based on two entities –"
},
{
"code": null,
"e": 820,
"s": 564,
"text": "Service Providers (SP) – The SP receives the authentication from the IdP and grants the authorisation to the user.Identity Providers (IdP) – The IdP authenticates a user and sends their credentials along with their access rights for the service to the SP."
},
{
"code": null,
"e": 935,
"s": 820,
"text": "Service Providers (SP) – The SP receives the authentication from the IdP and grants the authorisation to the user."
},
{
"code": null,
"e": 1077,
"s": 935,
"text": "Identity Providers (IdP) – The IdP authenticates a user and sends their credentials along with their access rights for the service to the SP."
},
{
"code": null,
"e": 1308,
"s": 1077,
"text": "In the example given above, SP will be Gmail and IdP will be Google. SAML enables SSO, and as it is explained above, a user can log in once and the same credentials will be used to log into other SPs.SAML Authentication Workflow –"
},
{
"code": null,
"e": 1695,
"s": 1308,
"text": "A user tries to log in to Gmail.Gmail generates a SAML request.The SAML request is sent to Google by the browser, which parses this request, authenticates the user and creates a SAML response. This SAML response is encoded and sent back to the browser.The browser sends this SAML response back to Gmail for verification.If the user is successfully verified, they are logged in to Gmail."
},
{
"code": null,
"e": 1728,
"s": 1695,
"text": "A user tries to log in to Gmail."
},
{
"code": null,
"e": 1760,
"s": 1728,
"text": "Gmail generates a SAML request."
},
{
"code": null,
"e": 1950,
"s": 1760,
"text": "The SAML request is sent to Google by the browser, which parses this request, authenticates the user and creates a SAML response. This SAML response is encoded and sent back to the browser."
},
{
"code": null,
"e": 2019,
"s": 1950,
"text": "The browser sends this SAML response back to Gmail for verification."
},
{
"code": null,
"e": 2086,
"s": 2019,
"text": "If the user is successfully verified, they are logged in to Gmail."
},
{
"code": null,
"e": 2101,
"s": 2086,
"text": "SAML Request –"
},
{
"code": null,
"e": 2169,
"s": 2101,
"text": "Some of the important terms in the SAML request are defined below –"
},
{
"code": null,
"e": 2445,
"s": 2169,
"text": "ID – Identifier for a particular SAML request.Issuer – The name of the service provider (SP).NameID – The username/email address or phone number which is used to identify a user.AssertionConsumerServiceURL – The SAML URL interface of the SP where the IP sends the auth token."
},
{
"code": null,
"e": 2492,
"s": 2445,
"text": "ID – Identifier for a particular SAML request."
},
{
"code": null,
"e": 2540,
"s": 2492,
"text": "Issuer – The name of the service provider (SP)."
},
{
"code": null,
"e": 2626,
"s": 2540,
"text": "NameID – The username/email address or phone number which is used to identify a user."
},
{
"code": null,
"e": 2724,
"s": 2626,
"text": "AssertionConsumerServiceURL – The SAML URL interface of the SP where the IP sends the auth token."
},
{
"code": null,
"e": 2740,
"s": 2724,
"text": "SAML Response –"
},
{
"code": null,
"e": 2780,
"s": 2740,
"text": "A SAML response consists of two parts –"
},
{
"code": null,
"e": 3226,
"s": 2780,
"text": "Assertion –It is an XML document that has the details of the user. This contains the timestamp of the user login event and the method of authentication used (eg. 2 Factor Authentication, Kerberos, etc.)Signature –It is a Base64 encoded string which protects the integrity of the assertion. (If an attacker tries to change the username in the assertion to the victim’s username, the signature will prevent the hacker from logging in as the user)."
},
{
"code": null,
"e": 3429,
"s": 3226,
"text": "Assertion –It is an XML document that has the details of the user. This contains the timestamp of the user login event and the method of authentication used (eg. 2 Factor Authentication, Kerberos, etc.)"
},
{
"code": null,
"e": 3673,
"s": 3429,
"text": "Signature –It is a Base64 encoded string which protects the integrity of the assertion. (If an attacker tries to change the username in the assertion to the victim’s username, the signature will prevent the hacker from logging in as the user)."
},
{
"code": null,
"e": 3690,
"s": 3673,
"text": "Key Generation –"
},
{
"code": null,
"e": 3972,
"s": 3690,
"text": "The Identity Provider (IdP) generates a private key and a public key. It signs the assertion with the private key. The public key is shared with the Service Provider (SP) which uses it to verify the SAML response and then log the user in.SAML Vulnerabilities Exploited by Hackers –"
},
{
"code": null,
"e": 4852,
"s": 3972,
"text": "Signature not checked –If someone is able to change the name id (username) in the SAML response and log in as someone else due to the lack of a signature checking process.Signature only checked when it exists –If someone changes the name id value and removes the signature before the response is received by the browser and is still able to log in as the victim.Comment Injection –A user can be registered with an XML comment in the username as follows –email: prerit<!--notprerit-->@test.comWhile processing the SAML response, the SP will ignore the comment and log us in as the victim. The entire SAML response can be intercepted by using a proxy like a burp suite. Note that it has to be decoded first by the URL format and then by the Base64 format in order to be viewed.SAML Replay –The attacker captures the SAML response and uses it multiple times to log in as the victim."
},
{
"code": null,
"e": 5024,
"s": 4852,
"text": "Signature not checked –If someone is able to change the name id (username) in the SAML response and log in as someone else due to the lack of a signature checking process."
},
{
"code": null,
"e": 5216,
"s": 5024,
"text": "Signature only checked when it exists –If someone changes the name id value and removes the signature before the response is received by the browser and is still able to log in as the victim."
},
{
"code": null,
"e": 5630,
"s": 5216,
"text": "Comment Injection –A user can be registered with an XML comment in the username as follows –email: prerit<!--notprerit-->@test.comWhile processing the SAML response, the SP will ignore the comment and log us in as the victim. The entire SAML response can be intercepted by using a proxy like a burp suite. Note that it has to be decoded first by the URL format and then by the Base64 format in order to be viewed."
},
{
"code": null,
"e": 5669,
"s": 5630,
"text": "email: prerit<!--notprerit-->@test.com"
},
{
"code": null,
"e": 5953,
"s": 5669,
"text": "While processing the SAML response, the SP will ignore the comment and log us in as the victim. The entire SAML response can be intercepted by using a proxy like a burp suite. Note that it has to be decoded first by the URL format and then by the Base64 format in order to be viewed."
},
{
"code": null,
"e": 6058,
"s": 5953,
"text": "SAML Replay –The attacker captures the SAML response and uses it multiple times to log in as the victim."
},
{
"code": null,
"e": 6079,
"s": 6058,
"text": "Information-Security"
},
{
"code": null,
"e": 6097,
"s": 6079,
"text": "Computer Networks"
},
{
"code": null,
"e": 6115,
"s": 6097,
"text": "Computer Networks"
}
] |
Count Non-Leaf Nodes in Tree | Practice | GeeksforGeeks | Given a Binary Tree of size N, your task is to complete the function countNonLeafNodes(), that should return the count of all the non-leaf nodes of the given binary tree.
Example:
Input:
Output:
2
Explanation:
Nodes 1 and 2 are the only non leaf nodes.
Your Task:
You don't need to take input or print anything. Your task is to complete the function countNonLeafNodes() that takes root as input and returns the number of non leaf nodes in the tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(Height of the Tree).
Constraints:
1 ≤ Number of nodes ≤ 105
0
mayank20212 weeks ago
C++ : 0.07/1.07void helper(Node* root, int &count) { if(root && (root->left || root->right) ) { count++; helper(root->left, count); helper(root->right, count); } } int countNonLeafNodes(Node* root) { int count=0; helper(root, count); return count; }
0
harshscode2 weeks ago
if(!root) return 0; if(!root->left and !root->right) return 0; return (1+countNonLeafNodes(root->left)+countNonLeafNodes(root->right));
0
00thirt13n4 weeks ago
Easy C++ Solution:
int countNonLeafNodes(Node* root) {
if(root==NULL)
return 0;
if(root->left==NULL && root->right==NULL))
return 0;
return (1+countNonLeafNodes(root->left)+countNonLeafNodes(root->right));
}
+1
00thirt13n4 weeks ago
1-line C++ Solution:
int countNonLeafNodes(Node* root) {
// Code here
return (!root || (root->left==NULL && root->right==NULL))?0:(1+countNonLeafNodes(root->left)+countNonLeafNodes(root->right));
}
0
jayendra05mishra1 month ago
class Solution { public: int countNonLeafNodes(Node* root) { int count=0; // base case if (root== NULL){ return 0; } if (root == NULL || (root->left == NULL && root->right == NULL)){ return 0; } return 1 + countNonLeafNodes(root->left) + countNonLeafNodes(root->right); }};
0
imohdalam2 months ago
Java
class Solution
{
int countNonLeafNodes(Node root) {
//code here
return sizeOfBT(root) - numberOfLeaves(root);
}
int sizeOfBT(Node root){
if(root == null)
return 0;
return sizeOfBT(root.left) + sizeOfBT(root.right) + 1;
}
int numberOfLeaves(Node root){
if(root == null)
return 0;
if(root.left == null && root.right == null)
return 1;
return numberOfLeaves(root.left) + numberOfLeaves(root.right);
}
}
0
shankarmudiraj8272 months ago
class Solution{int countNonLeafNodes(Node root) { if(root==null) return 0; if(root.left==null && root.right==null) return 0; if(root.left!=null || root.right!=null) return countNonLeafNodes(root.left)+countNonLeafNodes(root.right)+1; return -1;}}
0
maskiyashank883 months ago
Simple Java Solution
int countNonLeafNodes(Node node) {
//code here
if(node == null){
return 0;
}
if(node.left == null && node.right == null){
return 0;
}
return 1 + countNonLeafNodes(node.left) + countNonLeafNodes(node.right);
}
0
amiransarimy3 months ago
Python Solutions
Total Time Taken:
0.2/1.3
class Solution:
def countNonLeafNodes(self, root):
if root is None:
return 0
if root.left is None and root.right is None:
return 0
return 1+ self.countNonLeafNodes(root.left) +self.countNonLeafNodes(root.right)
0
hydracody454 months ago
int countNonLeafNodes(Node* root) { // Code here if(root==NULL){ return 0; } if(root->left==NULL && root->right==NULL){ return 0; } return 1+countNonLeafNodes(root->right)+countNonLeafNodes(root->left); }
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": 409,
"s": 238,
"text": "Given a Binary Tree of size N, your task is to complete the function countNonLeafNodes(), that should return the count of all the non-leaf nodes of the given binary tree."
},
{
"code": null,
"e": 418,
"s": 409,
"text": "Example:"
},
{
"code": null,
"e": 494,
"s": 418,
"text": "Input: \n\nOutput:\n2\nExplanation:\nNodes 1 and 2 are the only non leaf nodes.\n"
},
{
"code": null,
"e": 690,
"s": 494,
"text": "Your Task:\nYou don't need to take input or print anything. Your task is to complete the function countNonLeafNodes() that takes root as input and returns the number of non leaf nodes in the tree."
},
{
"code": null,
"e": 771,
"s": 690,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(Height of the Tree)."
},
{
"code": null,
"e": 810,
"s": 771,
"text": "Constraints:\n1 ≤ Number of nodes ≤ 105"
},
{
"code": null,
"e": 812,
"s": 810,
"text": "0"
},
{
"code": null,
"e": 834,
"s": 812,
"text": "mayank20212 weeks ago"
},
{
"code": null,
"e": 1202,
"s": 834,
"text": "C++ : 0.07/1.07void helper(Node* root, int &count) { if(root && (root->left || root->right) ) { count++; helper(root->left, count); helper(root->right, count); } } int countNonLeafNodes(Node* root) { int count=0; helper(root, count); return count; }"
},
{
"code": null,
"e": 1204,
"s": 1202,
"text": "0"
},
{
"code": null,
"e": 1226,
"s": 1204,
"text": "harshscode2 weeks ago"
},
{
"code": null,
"e": 1394,
"s": 1226,
"text": " if(!root) return 0; if(!root->left and !root->right) return 0; return (1+countNonLeafNodes(root->left)+countNonLeafNodes(root->right)); "
},
{
"code": null,
"e": 1396,
"s": 1394,
"text": "0"
},
{
"code": null,
"e": 1418,
"s": 1396,
"text": "00thirt13n4 weeks ago"
},
{
"code": null,
"e": 1437,
"s": 1418,
"text": "Easy C++ Solution:"
},
{
"code": null,
"e": 1654,
"s": 1437,
"text": "int countNonLeafNodes(Node* root) {\n if(root==NULL)\n \treturn 0; \n if(root->left==NULL && root->right==NULL))\t\n \treturn 0;\n return (1+countNonLeafNodes(root->left)+countNonLeafNodes(root->right));\n }"
},
{
"code": null,
"e": 1657,
"s": 1654,
"text": "+1"
},
{
"code": null,
"e": 1679,
"s": 1657,
"text": "00thirt13n4 weeks ago"
},
{
"code": null,
"e": 1700,
"s": 1679,
"text": "1-line C++ Solution:"
},
{
"code": null,
"e": 1897,
"s": 1700,
"text": "int countNonLeafNodes(Node* root) {\n // Code here\n return (!root || (root->left==NULL && root->right==NULL))?0:(1+countNonLeafNodes(root->left)+countNonLeafNodes(root->right));\n }"
},
{
"code": null,
"e": 1899,
"s": 1897,
"text": "0"
},
{
"code": null,
"e": 1927,
"s": 1899,
"text": "jayendra05mishra1 month ago"
},
{
"code": null,
"e": 2258,
"s": 1927,
"text": "class Solution { public: int countNonLeafNodes(Node* root) { int count=0; // base case if (root== NULL){ return 0; } if (root == NULL || (root->left == NULL && root->right == NULL)){ return 0; } return 1 + countNonLeafNodes(root->left) + countNonLeafNodes(root->right); }};"
},
{
"code": null,
"e": 2260,
"s": 2258,
"text": "0"
},
{
"code": null,
"e": 2282,
"s": 2260,
"text": "imohdalam2 months ago"
},
{
"code": null,
"e": 2287,
"s": 2282,
"text": "Java"
},
{
"code": null,
"e": 2772,
"s": 2287,
"text": "class Solution\n{\n\tint countNonLeafNodes(Node root) {\n\t //code here\n\t return sizeOfBT(root) - numberOfLeaves(root);\n\t}\n\t\n\tint sizeOfBT(Node root){\n\t if(root == null)\n\t return 0;\n\t return sizeOfBT(root.left) + sizeOfBT(root.right) + 1;\n\t}\n\t\n\tint numberOfLeaves(Node root){\n\t if(root == null)\n\t return 0;\n\t \n\t if(root.left == null && root.right == null)\n\t return 1;\n\t \n\t return numberOfLeaves(root.left) + numberOfLeaves(root.right);\n\t}\n}"
},
{
"code": null,
"e": 2774,
"s": 2772,
"text": "0"
},
{
"code": null,
"e": 2804,
"s": 2774,
"text": "shankarmudiraj8272 months ago"
},
{
"code": null,
"e": 3079,
"s": 2804,
"text": "class Solution{int countNonLeafNodes(Node root) { if(root==null) return 0; if(root.left==null && root.right==null) return 0; if(root.left!=null || root.right!=null) return countNonLeafNodes(root.left)+countNonLeafNodes(root.right)+1; return -1;}}"
},
{
"code": null,
"e": 3081,
"s": 3079,
"text": "0"
},
{
"code": null,
"e": 3108,
"s": 3081,
"text": "maskiyashank883 months ago"
},
{
"code": null,
"e": 3129,
"s": 3108,
"text": "Simple Java Solution"
},
{
"code": null,
"e": 3389,
"s": 3131,
"text": "int countNonLeafNodes(Node node) {\n\t //code here\n\t if(node == null){\n\t return 0;\n\t }\n\t if(node.left == null && node.right == null){\n\t return 0;\n\t }\n\t return 1 + countNonLeafNodes(node.left) + countNonLeafNodes(node.right);\n\t}"
},
{
"code": null,
"e": 3391,
"s": 3389,
"text": "0"
},
{
"code": null,
"e": 3416,
"s": 3391,
"text": "amiransarimy3 months ago"
},
{
"code": null,
"e": 3433,
"s": 3416,
"text": "Python Solutions"
},
{
"code": null,
"e": 3451,
"s": 3433,
"text": "Total Time Taken:"
},
{
"code": null,
"e": 3459,
"s": 3451,
"text": "0.2/1.3"
},
{
"code": null,
"e": 3742,
"s": 3461,
"text": "class Solution:\n def countNonLeafNodes(self, root):\n \n if root is None:\n return 0\n \n if root.left is None and root.right is None:\n return 0\n \n return 1+ self.countNonLeafNodes(root.left) +self.countNonLeafNodes(root.right)"
},
{
"code": null,
"e": 3746,
"s": 3744,
"text": "0"
},
{
"code": null,
"e": 3770,
"s": 3746,
"text": "hydracody454 months ago"
},
{
"code": null,
"e": 4033,
"s": 3770,
"text": "int countNonLeafNodes(Node* root) { // Code here if(root==NULL){ return 0; } if(root->left==NULL && root->right==NULL){ return 0; } return 1+countNonLeafNodes(root->right)+countNonLeafNodes(root->left); }"
},
{
"code": null,
"e": 4179,
"s": 4033,
"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": 4215,
"s": 4179,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4225,
"s": 4215,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4235,
"s": 4225,
"text": "\nContest\n"
},
{
"code": null,
"e": 4298,
"s": 4235,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4446,
"s": 4298,
"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": 4654,
"s": 4446,
"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": 4760,
"s": 4654,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
HTTP - Header Fields | HTTP header fields provide required information about the request or response, or about the object sent in the message body. There are four types of HTTP message headers:
General-header: These header fields have general applicability for both request and response messages.
General-header: These header fields have general applicability for both request and response messages.
Client Request-header: These header fields have applicability only for request messages.
Client Request-header: These header fields have applicability only for request messages.
Server Response-header: These header fields have applicability only for response messages.
Server Response-header: These header fields have applicability only for response messages.
Entity-header: These header fields define meta information about the entity-body or, if no body is present, about the resource identified by the request.
Entity-header: These header fields define meta information about the entity-body or, if no body is present, about the resource identified by the request.
The Cache-Control general-header field is used to specify directives that MUST be obeyed by all the caching system. The syntax is as follows:
Cache-Control : cache-request-directive|cache-response-directive
An HTTP client or server can use the Cache-control general header to specify parameters for the cache or to request certain kinds of documents from the cache. The caching directives are specified in a comma-separated list. For example:
Cache-control: no-cache
The following table lists the important cache request directives that can be used by the client in its HTTP request:
A cache must not use the response to satisfy a subsequent request without successful revalidation with the origin server.
The cache should not store anything about the client request or server response.
Indicates that the client is willing to accept a response whose age is not greater than the specified time in seconds.
Indicates that the client is willing to accept a response that has exceeded its expiration time. If seconds are given, it must not be expired by more than that time.
Indicates that the client is willing to accept a response whose freshness lifetime is not less than its current age plus the specified time in seconds.
Does not convert the entity-body.
Does not retrieve new data. The cache can send a document only if it is in the cache, and should not contact the origin-server to see if a newer copy exists.
The following important cache response directives that can be used by the server in its HTTP response:
Indicates that the response may be cached by any cache.
Indicates that all or part of the response message is intended for a single user and must not be cached by a shared cache.
A cache must not use the response to satisfy a subsequent request without successful re-validation with the origin server.
The cache should not store anything about the client request or server response.
Does not convert the entity-body.
The cache must verify the status of the stale documents before using it and expired ones should not be used.
The proxy-revalidate directive has the same meaning as the must- revalidate directive, except that it does not apply to non-shared user agent caches.
Indicates that the client is willing to accept a response whose age is not greater than the specified time in seconds.
The maximum age specified by this directive overrides the maximum age specified by either the max-age directive or the Expires header. The s-maxage directive is always ignored by a private cache.
The Connection general-header field allows the sender to specify options that are desired for that particular connection and must not be communicated by proxies over further connections. Following is the simple syntax for using connection header:
Connection : "Connection"
HTTP/1.1 defines the "close" connection option for the sender to signal that the connection will be closed after completion of the response. For example:
Connection: close
By default, HTTP 1.1 uses persistent connections, where the connection does not automatically close after a transaction. HTTP 1.0, on the other hand, does not have persistent connections by default. If a 1.0 client wishes to use persistent connections, it uses the keep-alive parameter as follows:
Connection: keep-alive
All HTTP date/time stamps MUST be represented in Greenwich Mean Time (GMT), without exception. HTTP applications are allowed to use any of the following three representations of date/time stamps:
Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123
Sunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036
Sun Nov 6 08:49:37 1994 ; ANSI C's asctime() format
Here the first format is the most preferred one.
The Pragma general-header field is used to include implementation specific directives that might apply to any recipient along the request/response chain. For example:
Pragma: no-cache
The only directive defined in HTTP/1.0 is the no-cache directive and is maintained in HTTP 1.1 for backward compatibility. No new Pragma directives will be defined in the future.
The Trailer general field value indicates that the given set of header fields is present in the trailer of a message encoded with chunked transfer-coding. Following is the syntax of Trailer header field:
Trailer : field-name
Message header fields listed in the Trailer header field must not include the following header fields:
Transfer-Encoding
Transfer-Encoding
Content-Length
Content-Length
Trailer
Trailer
The Transfer-Encoding general-header field indicates what type of transformation has been applied to the message body in order to safely transfer it between the sender and the recipient. This is not the same as content-encoding because transfer-encodings are a property of the message, not of the entity-body. The syntax of Transfer-Encoding header field is as follows:
Transfer-Encoding: chunked
All transfer-coding values are case-insensitive.
The Upgrade general-header allows the client to specify what additional communication protocols it supports and would like to use if the server finds it appropriate to switch protocols. For example:
Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11
The Upgrade header field is intended to provide a simple mechanism for transition from HTTP/1.1 to some other, incompatible protocol.
The Via general-header must be used by gateways and proxies to indicate the intermediate protocols and recipients. For example, a request message could be sent from an HTTP/1.0 user agent to an internal proxy code-named "fred", which uses HTTP/1.1 to forward the request to a public proxy at nowhere.com, which completes the request by forwarding it to the origin server at www.ics.uci.edu. The request received by www.ics.uci.edu would then have the following Via header field:
Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)
The Upgrade header field is intended to provide a simple mechanism for transition from HTTP/1.1 to some other, incompatible protocol.
The Warning general-header is used to carry additional information about the status or transformation of a message which might not be reflected in the message. A response may carry more than one Warning header.
Warning : warn-code SP warn-agent SP warn-text SP warn-date
The Accept request-header field can be used to specify certain media types which are acceptable for the response. The general syntax is as follows:
Accept: type/subtype [q=qvalue]
Multiple media types can be listed separated by commas and the optional qvalue represents an acceptable quality level for accept types on a scale of 0 to 1. Following is an example:
Accept: text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c
This would be interpreted as text/html and text/x-c and are the preferred media types, but if they do not exist, then send the text/x-dvi entity, and if that does not exist, send the text/plain entity.
The Accept-Charset request-header field can be used to indicate what character sets are acceptable for the response. Following is the general syntax:
Accept-Charset: character_set [q=qvalue]
Multiple character sets can be listed separated by commas and the optional qvalue represents an acceptable quality level for nonpreferred character sets on a scale of 0 to 1. Following is an example:
Accept-Charset: iso-8859-5, unicode-1-1; q=0.8
The special value "*", if present in the Accept-Charset field, matches every character set and if no Accept-Charset header is present, the default is that any character set is acceptable.
The Accept-Encoding request-header field is similar to Accept, but restricts the content-codings that are acceptable in the response. The general syntax is:
Accept-Encoding: encoding types
Examples are as follows:
Accept-Encoding: compress, gzip
Accept-Encoding:
Accept-Encoding: *
Accept-Encoding: compress;q=0.5, gzip;q=1.0
Accept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0
The Accept-Language request-header field is similar to Accept, but restricts the set of natural languages that are preferred as a response to the request. The general syntax is:
Accept-Language: language [q=qvalue]
Multiple languages can be listed separated by commas and the optional qvalue represents an acceptable quality level for non preferred languages on a scale of 0 to 1. Following is an example:
Accept-Language: da, en-gb;q=0.8, en;q=0.7
The Authorization request-header field value consists of credentials containing the authentication information of the user agent for the realm of the resource being requested. The general syntax is:
Authorization : credentials
The HTTP/1.0 specification defines the BASIC authorization scheme, where the authorization parameter is the string of username:password encoded in base 64. Following is an example:
Authorization: BASIC Z3Vlc3Q6Z3Vlc3QxMjM=
The value decodes into is guest:guest123 where guest is user ID and guest123 is the password.
The Cookie request-header field value contains a name/value pair of information stored for that URL. Following is the general syntax:
Cookie: name=value
Multiple cookies can be specified separated by semicolons as follows:
Cookie: name1=value1;name2=value2;name3=value3
The Expect request-header field is used to indicate that a particular set of server behaviors is required by the client. The general syntax is:
Expect : 100-continue | expectation-extension
If a server receives a request containing an Expect field that includes an expectation-extension that it does not support, it must respond with a 417 (Expectation Failed) status.
The From request-header field contains an Internet e-mail address for the human user who controls the requesting user agent. Following is a simple example:
From: [email protected]
This header field may be used for logging purposes and as a means for identifying the source of invalid or unwanted requests.
The Host request-header field is used to specify the Internet host and the port number of the resource being requested. The general syntax is:
Host : "Host" ":" host [ ":" port ] ;
A host without any trailing port information implies the default port, which is 80. For example, a request on the origin server for http://www.w3.org/pub/WWW/ would be:
GET /pub/WWW/ HTTP/1.1
Host: www.w3.org
The If-Match request-header field is used with a method to make it conditional. This header requests the server to perform the requested method only if the given value in this tag matches the given entity tags represented by ETag. The general syntax is:
If-Match : entity-tag
An asterisk (*) matches any entity, and the transaction continues only if the entity exists. Following are possible examples:
If-Match: "xyzzy"
If-Match: "xyzzy", "r2d2xxxx", "c3piozzzz"
If-Match: *
If none of the entity tags match, or if "*" is given and no current entity exists, the server must not perform the requested method, and must return a 412 (Precondition Failed) response.
The If-Modified-Since request-header field is used with a method to make it conditional. If the requested URL has not been modified since the time specified in this field, an entity will not be returned from the server; instead, a 304 (not modified) response will be returned without any message-body. The general syntax of if-modified-since is:
If-Modified-Since : HTTP-date
An example of the field is:
If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT
If none of the entity tags match, or if "*" is given and no current entity exists, the server must not perform the requested method, and must return a 412 (Precondition Failed) response.
The If-None-Match request-header field is used with a method to make it conditional. This header requests the server to perform the requested method only if one of the given value in this tag matches the given entity tags represented by ETag. The general syntax is:
If-None-Match : entity-tag
An asterisk (*) matches any entity, and the transaction continues only if the entity does not exist. Following are the possible examples:
If-None-Match: "xyzzy"
If-None-Match: "xyzzy", "r2d2xxxx", "c3piozzzz"
If-None-Match: *
The If-Range request-header field can be used with a conditional GET to request only the portion of the entity that is missing, if it has not been changed, and the entire entity if it has been changed. The general syntax is as follows:
If-Range : entity-tag | HTTP-date
Either an entity tag or a date can be used to identify the partial entity already received. For example:
If-Range: Sat, 29 Oct 1994 19:43:31 GMT
Here if the document has not been modified since the given date, the server returns the byte range given by the Range header, otherwise it returns all of the new document.
The If-Unmodified-Since request-header field is used with a method to make it conditional. The general syntax is:
If-Unmodified-Since : HTTP-date
If the requested resource has not been modified since the time specified in this field, the server should perform the requested operation as if the If-Unmodified-Since header were not present. For example:
If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT
If the request results in anything other than a 2xx or 412 status, the If-Unmodified-Since header should be ignored.
The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server. Here is the general syntax:
Max-Forwards : n
The Max-Forwards value is a decimal integer indicating the remaining number of times this request message may be forwarded. This is useful for debugging with the TRACE method, avoiding infinite loops. For example:
Max-Forwards : 5
The Max-Forwards header field may be ignored for all other methods defined in the HTTP specification.
The Proxy-Authorization request-header field allows the client to identify itself (or its user) to a proxy which requires authentication. Here is the general syntax:
Proxy-Authorization : credentials
The Proxy-Authorization field value consists of credentials containing the authentication information of the user agent for the proxy and/or realm of the resource being requested.
The Range request-header field specifies the partial range(s) of the content requested from the document. The general syntax is:
Range: bytes-unit=first-byte-pos "-" [last-byte-pos]
The first-byte-pos value in a byte-range-spec gives the byte-offset of the first byte in a range. The last-byte-pos value gives the byte-offset of the last byte in the range; that is, the byte positions specified are inclusive. You can specify a byte-unit as bytes. Byte offsets start at zero. Some simple examples are as follows:
- The first 500 bytes
Range: bytes=0-499
- The second 500 bytes
Range: bytes=500-999
- The final 500 bytes
Range: bytes=-500
- The first and last bytes only
Range: bytes=0-0,-1
Multiple ranges can be listed, separated by commas. If the first digit in the comma-separated byte range(s) is missing, the range is assumed to count from the end of the document. If the second digit is missing, the range is byte n to the end of the document.
The Referer request-header field allows the client to specify the address (URI) of the resource from which the URL has been requested. The general syntax is as follows:
Referer : absoluteURI | relativeURI
Following is a simple example:
Referer: http://www.tutorialspoint.org/http/index.htm
If the field value is a relative URI, it should be interpreted relative to the Request-URI.
The TE request-header field indicates what extension transfer-coding it is willing to accept in the response and whether or not it is willing to accept trailer fields in a chunked transfer-coding. Following is the general syntax:
TE : t-codings
The presence of the keyword "trailers" indicates that the client is willing to accept trailer fields in a chunked transfer-coding and it is specified either of the ways:
TE: deflate
TE:
TE: trailers, deflate;q=0.5
If the TE field-value is empty or if no TE field is present, then only transfer-coding is chunked. A message with no transfer-coding is always acceptable.
The User-Agent request-header field contains information about the user agent originating the request. Following is the general syntax:
User-Agent : product | comment
Example:
User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)
The Accept-Ranges response-header field allows the server to indicate its acceptance of range requests for a resource. The general syntax is:
Accept-Ranges : range-unit | none
For example a server that accepts byte-range requests may send:
Accept-Ranges: bytes
Servers that do not accept any kind of range request for a resource may send:
Accept-Ranges: none
This will advise the client not to attempt a range request.
The Age response-header field conveys the sender's estimate of the amount of time since the response (or its revalidation) was generated at the origin server. The general syntax is:
Age : delta-seconds
Age values are non-negative decimal integers, representing time in seconds. Following is a simple example:
Age: 1030
An HTTP/1.1 server that includes a cache must include an Age header field in every response generated from its own cache.
The ETag response-header field provides the current value of the entity tag for the requested variant. The general syntax is:
ETag : entity-tag
Here are some simple examples:
ETag: "xyzzy"
ETag: W/"xyzzy"
ETag: ""
The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion. The general syntax is:
Location : absoluteURI
Following is a simple example:
Location: http://www.tutorialspoint.org/http/index.htm
The Content-Location header field differs from Location in that the Content-Location identifies the original location of the entity enclosed in the request.
The Proxy-Authenticate response-header field must be included as a part of a 407 (Proxy Authentication Required) response. The general syntax is:
Proxy-Authenticate : challenge
The Retry-After response-header field can be used with a 503 (Service Unavailable) response to indicate how long the service is expected to be unavailable to the requesting client. The general syntax is:
Retry-After : HTTP-date | delta-seconds
Examples:
Retry-After: Fri, 31 Dec 1999 23:59:59 GMT
Retry-After: 120
In the latter example, the delay is 2 minutes.
The Server response-header field contains information about the software used by the origin server to handle the request. The general syntax is:
Server : product | comment
Following is a simple example:
Server: Apache/2.2.14 (Win32)
If the response is being forwarded through a proxy, the proxy application must not modify the Server response-header.
The Set-Cookie response-header field contains a name/value pair of information to retain for this URL. The general syntax is:
Set-Cookie: NAME=VALUE; OPTIONS
Set-Cookie response header comprises the token Set-Cookie, followed by a comma-separated list of one or more cookies. Here are the possible values you can specify as options:
This option can be used to specify any comment associated with the cookie.
The Domain attribute specifies the domain for which the cookie is valid.
The date the cookie will expire. If it is blank, the cookie will expire when the visitor quits the browser.
The Path attribute specifies the subset of URLs to which this cookie applies.
It instructs the user agent to return the cookie only under a secure connection.
Following is an example of a simple cookie header generated by the server:
Set-Cookie: name1=value1,name2=value2; Expires=Wed, 09 Jun 2021 10:18:14 GMT
The Vary response-header field specifies that the entity has multiple sources and may therefore vary according to the specified list of request header(s). Following is the general syntax:
Vary : field-name
You can specify multiple headers separated by commas and a value of asterisk "*" signals that unspecified parameters are not limited to the request-headers. Following is a simple example:
Vary: Accept-Language, Accept-Encoding
Here field names are case-insensitive.
The WWW-Authenticate response-header field must be included in 401 (Unauthorized) response messages. The field value consists of at least one challenge that indicates the authentication scheme(s) and parameters applicable to the Request-URI. The general syntax is:
WWW-Authenticate : challenge
WWW- Authenticate field value might contain more than one challenge, or if more than one WWW-Authenticate header field is provided, the contents of a challenge itself can contain a comma-separated list of authentication parameters. Following is a simple example:
WWW-Authenticate: BASIC realm="Admin"
The Allow entity-header field lists the set of methods supported by the resource identified by the Request-URI. The general syntax is:
Allow : Method
You can specify multiple methods separated by commas. Following is a simple example:
Allow: GET, HEAD, PUT
This field cannot prevent a client from trying other methods.
The Content-Encoding entity-header field is used as a modifier to the media-type. The general syntax is:
Content-Encoding : content-coding
The content-coding is a characteristic of the entity identified by the Request-URI. Following is a simple example:
Content-Encoding: gzip
If the content-coding of an entity in a request message is not acceptable to the origin server, the server should respond with a status code of 415 (Unsupported Media Type).
The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Following is the general syntax:
Content-Language : language-tag
Multiple languages may be listed for content that is intended for multiple audiences. Following is a simple example:
Content-Language: mi, en
The primary purpose of Content-Language is to allow a user to identify and differentiate entities according to the user's own preferred language.
The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent, had the request been a GET. The general syntax is:
Content-Length : DIGITS
Following is a simple example:
Content-Length: 3495
Any Content-Length greater than or equal to zero is a valid value.
The Content-Location entity-header field may be used to supply the resource location for the entity enclosed in the message when that entity is accessible from a location separate from the requested resource's URI. The general syntax is:
Content-Location: absoluteURI | relativeURI
Following is a simple example:
Content-Location: http://www.tutorialspoint.org/http/index.htm
The value of Content-Location also defines the base URI for the entity.
The Content-MD5 entity-header field may be used to supply an MD5 digest of the entity for checking the integrity
of the message upon receipt. The general syntax is:
Content-MD5 : md5-digest using base64 of 128 bit MD5 digest as per RFC 1864
Following is a simple example:
Content-MD5 : 8c2d46911f3f5a326455f0ed7a8ed3b3
The MD5 digest is computed based on the content of the entity-body, including any content-coding that has been applied, but not including any transfer-encoding applied to the message-body.
The Content-Range entity-header field is sent with a partial entity-body to specify where in the full entity-body the partial body should be applied. The general syntax is:
Content-Range : bytes-unit SP first-byte-pos "-" last-byte-pos
Examples of byte-content-range-spec values, assuming that the entity contains a total of 1234 bytes:
- The first 500 bytes:
Content-Range : bytes 0-499/1234
- The second 500 bytes:
Content-Range : bytes 500-999/1234
- All except for the first 500 bytes:
Content-Range : bytes 500-1233/1234
- The last 500 bytes:
Content-Range : bytes 734-1233/1234
When an HTTP message includes the content of a single range, this content is transmitted with a Content-Range header, and a Content-Length header showing the number of bytes actually transferred. For example,
HTTP/1.1 206 Partial content
Date: Wed, 15 Nov 1995 06:25:24 GMT
Last-Modified: Wed, 15 Nov 1995 04:58:08 GMT
Content-Range: bytes 21010-47021/47022
Content-Length: 26012
Content-Type: image/gif
The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent, had the request been a GET. The general syntax is:
Content-Type : media-type
Following is an example:
Content-Type: text/html; charset=ISO-8859-4
The Expires entity-header field gives the date/time after which the response is considered stale. The general syntax is:
Expires : HTTP-date
Following is an example:
Expires: Thu, 01 Dec 1994 16:00:00 GMT
The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified. The general syntax is:
Last-Modified: HTTP-date
Following is an example:
Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 1950,
"s": 1779,
"text": "HTTP header fields provide required information about the request or response, or about the object sent in the message body. There are four types of HTTP message headers:"
},
{
"code": null,
"e": 2053,
"s": 1950,
"text": "General-header: These header fields have general applicability for both request and response messages."
},
{
"code": null,
"e": 2156,
"s": 2053,
"text": "General-header: These header fields have general applicability for both request and response messages."
},
{
"code": null,
"e": 2246,
"s": 2156,
"text": "Client Request-header: These header fields have applicability only for request messages."
},
{
"code": null,
"e": 2336,
"s": 2246,
"text": "Client Request-header: These header fields have applicability only for request messages."
},
{
"code": null,
"e": 2428,
"s": 2336,
"text": "Server Response-header: These header fields have applicability only for response messages."
},
{
"code": null,
"e": 2520,
"s": 2428,
"text": "Server Response-header: These header fields have applicability only for response messages."
},
{
"code": null,
"e": 2674,
"s": 2520,
"text": "Entity-header: These header fields define meta information about the entity-body or, if no body is present, about the resource identified by the request."
},
{
"code": null,
"e": 2828,
"s": 2674,
"text": "Entity-header: These header fields define meta information about the entity-body or, if no body is present, about the resource identified by the request."
},
{
"code": null,
"e": 2970,
"s": 2828,
"text": "The Cache-Control general-header field is used to specify directives that MUST be obeyed by all the caching system. The syntax is as follows:"
},
{
"code": null,
"e": 3036,
"s": 2970,
"text": "Cache-Control : cache-request-directive|cache-response-directive\n"
},
{
"code": null,
"e": 3272,
"s": 3036,
"text": "An HTTP client or server can use the Cache-control general header to specify parameters for the cache or to request certain kinds of documents from the cache. The caching directives are specified in a comma-separated list. For example:"
},
{
"code": null,
"e": 3297,
"s": 3272,
"text": "Cache-control: no-cache\n"
},
{
"code": null,
"e": 3414,
"s": 3297,
"text": "The following table lists the important cache request directives that can be used by the client in its HTTP request:"
},
{
"code": null,
"e": 3537,
"s": 3414,
"text": "A cache must not use the response to satisfy a subsequent request without successful revalidation with the origin server. "
},
{
"code": null,
"e": 3618,
"s": 3537,
"text": "The cache should not store anything about the client request or server response."
},
{
"code": null,
"e": 3737,
"s": 3618,
"text": "Indicates that the client is willing to accept a response whose age is not greater than the specified time in seconds."
},
{
"code": null,
"e": 3903,
"s": 3737,
"text": "Indicates that the client is willing to accept a response that has exceeded its expiration time. If seconds are given, it must not be expired by more than that time."
},
{
"code": null,
"e": 4055,
"s": 3903,
"text": "Indicates that the client is willing to accept a response whose freshness lifetime is not less than its current age plus the specified time in seconds."
},
{
"code": null,
"e": 4089,
"s": 4055,
"text": "Does not convert the entity-body."
},
{
"code": null,
"e": 4247,
"s": 4089,
"text": "Does not retrieve new data. The cache can send a document only if it is in the cache, and should not contact the origin-server to see if a newer copy exists."
},
{
"code": null,
"e": 4350,
"s": 4247,
"text": "The following important cache response directives that can be used by the server in its HTTP response:"
},
{
"code": null,
"e": 4406,
"s": 4350,
"text": "Indicates that the response may be cached by any cache."
},
{
"code": null,
"e": 4529,
"s": 4406,
"text": "Indicates that all or part of the response message is intended for a single user and must not be cached by a shared cache."
},
{
"code": null,
"e": 4652,
"s": 4529,
"text": "A cache must not use the response to satisfy a subsequent request without successful re-validation with the origin server."
},
{
"code": null,
"e": 4733,
"s": 4652,
"text": "The cache should not store anything about the client request or server response."
},
{
"code": null,
"e": 4767,
"s": 4733,
"text": "Does not convert the entity-body."
},
{
"code": null,
"e": 4876,
"s": 4767,
"text": "The cache must verify the status of the stale documents before using it and expired ones should not be used."
},
{
"code": null,
"e": 5026,
"s": 4876,
"text": "The proxy-revalidate directive has the same meaning as the must- revalidate directive, except that it does not apply to non-shared user agent caches."
},
{
"code": null,
"e": 5145,
"s": 5026,
"text": "Indicates that the client is willing to accept a response whose age is not greater than the specified time in seconds."
},
{
"code": null,
"e": 5341,
"s": 5145,
"text": "The maximum age specified by this directive overrides the maximum age specified by either the max-age directive or the Expires header. The s-maxage directive is always ignored by a private cache."
},
{
"code": null,
"e": 5588,
"s": 5341,
"text": "The Connection general-header field allows the sender to specify options that are desired for that particular connection and must not be communicated by proxies over further connections. Following is the simple syntax for using connection header:"
},
{
"code": null,
"e": 5615,
"s": 5588,
"text": "Connection : \"Connection\"\n"
},
{
"code": null,
"e": 5769,
"s": 5615,
"text": "HTTP/1.1 defines the \"close\" connection option for the sender to signal that the connection will be closed after completion of the response. For example:"
},
{
"code": null,
"e": 5788,
"s": 5769,
"text": "Connection: close\n"
},
{
"code": null,
"e": 6087,
"s": 5788,
"text": "By default, HTTP 1.1 uses persistent connections, where the connection does not automatically close after a transaction. HTTP 1.0, on the other hand, does not have persistent connections by default. If a 1.0 client wishes to use persistent connections, it uses the keep-alive parameter as follows:"
},
{
"code": null,
"e": 6111,
"s": 6087,
"text": "Connection: keep-alive\n"
},
{
"code": null,
"e": 6307,
"s": 6111,
"text": "All HTTP date/time stamps MUST be represented in Greenwich Mean Time (GMT), without exception. HTTP applications are allowed to use any of the following three representations of date/time stamps:"
},
{
"code": null,
"e": 6493,
"s": 6307,
"text": "Sun, 06 Nov 1994 08:49:37 GMT ; RFC 822, updated by RFC 1123\nSunday, 06-Nov-94 08:49:37 GMT ; RFC 850, obsoleted by RFC 1036\nSun Nov 6 08:49:37 1994 ; ANSI C's asctime() format\n"
},
{
"code": null,
"e": 6542,
"s": 6493,
"text": "Here the first format is the most preferred one."
},
{
"code": null,
"e": 6709,
"s": 6542,
"text": "The Pragma general-header field is used to include implementation specific directives that might apply to any recipient along the request/response chain. For example:"
},
{
"code": null,
"e": 6727,
"s": 6709,
"text": "Pragma: no-cache\n"
},
{
"code": null,
"e": 6906,
"s": 6727,
"text": "The only directive defined in HTTP/1.0 is the no-cache directive and is maintained in HTTP 1.1 for backward compatibility. No new Pragma directives will be defined in the future."
},
{
"code": null,
"e": 7110,
"s": 6906,
"text": "The Trailer general field value indicates that the given set of header fields is present in the trailer of a message encoded with chunked transfer-coding. Following is the syntax of Trailer header field:"
},
{
"code": null,
"e": 7132,
"s": 7110,
"text": "Trailer : field-name\n"
},
{
"code": null,
"e": 7235,
"s": 7132,
"text": "Message header fields listed in the Trailer header field must not include the following header fields:"
},
{
"code": null,
"e": 7253,
"s": 7235,
"text": "Transfer-Encoding"
},
{
"code": null,
"e": 7271,
"s": 7253,
"text": "Transfer-Encoding"
},
{
"code": null,
"e": 7286,
"s": 7271,
"text": "Content-Length"
},
{
"code": null,
"e": 7301,
"s": 7286,
"text": "Content-Length"
},
{
"code": null,
"e": 7309,
"s": 7301,
"text": "Trailer"
},
{
"code": null,
"e": 7317,
"s": 7309,
"text": "Trailer"
},
{
"code": null,
"e": 7687,
"s": 7317,
"text": "The Transfer-Encoding general-header field indicates what type of transformation has been applied to the message body in order to safely transfer it between the sender and the recipient. This is not the same as content-encoding because transfer-encodings are a property of the message, not of the entity-body. The syntax of Transfer-Encoding header field is as follows:"
},
{
"code": null,
"e": 7715,
"s": 7687,
"text": "Transfer-Encoding: chunked\n"
},
{
"code": null,
"e": 7764,
"s": 7715,
"text": "All transfer-coding values are case-insensitive."
},
{
"code": null,
"e": 7963,
"s": 7764,
"text": "The Upgrade general-header allows the client to specify what additional communication protocols it supports and would like to use if the server finds it appropriate to switch protocols. For example:"
},
{
"code": null,
"e": 8011,
"s": 7963,
"text": "Upgrade: HTTP/2.0, SHTTP/1.3, IRC/6.9, RTA/x11\n"
},
{
"code": null,
"e": 8145,
"s": 8011,
"text": "The Upgrade header field is intended to provide a simple mechanism for transition from HTTP/1.1 to some other, incompatible protocol."
},
{
"code": null,
"e": 8625,
"s": 8145,
"text": "The Via general-header must be used by gateways and proxies to indicate the intermediate protocols and recipients. For example, a request message could be sent from an HTTP/1.0 user agent to an internal proxy code-named \"fred\", which uses HTTP/1.1 to forward the request to a public proxy at nowhere.com, which completes the request by forwarding it to the origin server at www.ics.uci.edu. The request received by www.ics.uci.edu would then have the following Via header field:"
},
{
"code": null,
"e": 8670,
"s": 8625,
"text": "Via: 1.0 fred, 1.1 nowhere.com (Apache/1.1)\n"
},
{
"code": null,
"e": 8804,
"s": 8670,
"text": "The Upgrade header field is intended to provide a simple mechanism for transition from HTTP/1.1 to some other, incompatible protocol."
},
{
"code": null,
"e": 9015,
"s": 8804,
"text": "The Warning general-header is used to carry additional information about the status or transformation of a message which might not be reflected in the message. A response may carry more than one Warning header."
},
{
"code": null,
"e": 9076,
"s": 9015,
"text": "Warning : warn-code SP warn-agent SP warn-text SP warn-date\n"
},
{
"code": null,
"e": 9224,
"s": 9076,
"text": "The Accept request-header field can be used to specify certain media types which are acceptable for the response. The general syntax is as follows:"
},
{
"code": null,
"e": 9257,
"s": 9224,
"text": "Accept: type/subtype [q=qvalue]\n"
},
{
"code": null,
"e": 9440,
"s": 9257,
"text": "Multiple media types can be listed separated by commas and the optional qvalue represents an acceptable quality level for accept types on a scale of 0 to 1. Following is an example:"
},
{
"code": null,
"e": 9507,
"s": 9440,
"text": "Accept: text/plain; q=0.5, text/html, text/x-dvi; q=0.8, text/x-c\n"
},
{
"code": null,
"e": 9709,
"s": 9507,
"text": "This would be interpreted as text/html and text/x-c and are the preferred media types, but if they do not exist, then send the text/x-dvi entity, and if that does not exist, send the text/plain entity."
},
{
"code": null,
"e": 9859,
"s": 9709,
"text": "The Accept-Charset request-header field can be used to indicate what character sets are acceptable for the response. Following is the general syntax:"
},
{
"code": null,
"e": 9901,
"s": 9859,
"text": "Accept-Charset: character_set [q=qvalue]\n"
},
{
"code": null,
"e": 10102,
"s": 9901,
"text": "Multiple character sets can be listed separated by commas and the optional qvalue represents an acceptable quality level for nonpreferred character sets on a scale of 0 to 1. Following is an example:"
},
{
"code": null,
"e": 10150,
"s": 10102,
"text": "Accept-Charset: iso-8859-5, unicode-1-1; q=0.8\n"
},
{
"code": null,
"e": 10338,
"s": 10150,
"text": "The special value \"*\", if present in the Accept-Charset field, matches every character set and if no Accept-Charset header is present, the default is that any character set is acceptable."
},
{
"code": null,
"e": 10495,
"s": 10338,
"text": "The Accept-Encoding request-header field is similar to Accept, but restricts the content-codings that are acceptable in the response. The general syntax is:"
},
{
"code": null,
"e": 10528,
"s": 10495,
"text": "Accept-Encoding: encoding types\n"
},
{
"code": null,
"e": 10553,
"s": 10528,
"text": "Examples are as follows:"
},
{
"code": null,
"e": 10718,
"s": 10553,
"text": "Accept-Encoding: compress, gzip\nAccept-Encoding:\nAccept-Encoding: *\nAccept-Encoding: compress;q=0.5, gzip;q=1.0\nAccept-Encoding: gzip;q=1.0, identity; q=0.5, *;q=0\n"
},
{
"code": null,
"e": 10896,
"s": 10718,
"text": "The Accept-Language request-header field is similar to Accept, but restricts the set of natural languages that are preferred as a response to the request. The general syntax is:"
},
{
"code": null,
"e": 10934,
"s": 10896,
"text": "Accept-Language: language [q=qvalue]\n"
},
{
"code": null,
"e": 11126,
"s": 10934,
"text": "Multiple languages can be listed separated by commas and the optional qvalue represents an acceptable quality level for non preferred languages on a scale of 0 to 1. Following is an example:"
},
{
"code": null,
"e": 11170,
"s": 11126,
"text": "Accept-Language: da, en-gb;q=0.8, en;q=0.7\n"
},
{
"code": null,
"e": 11369,
"s": 11170,
"text": "The Authorization request-header field value consists of credentials containing the authentication information of the user agent for the realm of the resource being requested. The general syntax is:"
},
{
"code": null,
"e": 11398,
"s": 11369,
"text": "Authorization : credentials\n"
},
{
"code": null,
"e": 11579,
"s": 11398,
"text": "The HTTP/1.0 specification defines the BASIC authorization scheme, where the authorization parameter is the string of username:password encoded in base 64. Following is an example:"
},
{
"code": null,
"e": 11622,
"s": 11579,
"text": "Authorization: BASIC Z3Vlc3Q6Z3Vlc3QxMjM=\n"
},
{
"code": null,
"e": 11716,
"s": 11622,
"text": "The value decodes into is guest:guest123 where guest is user ID and guest123 is the password."
},
{
"code": null,
"e": 11851,
"s": 11716,
"text": "The Cookie request-header field value contains a name/value pair of information stored for that URL. Following is the general syntax:"
},
{
"code": null,
"e": 11871,
"s": 11851,
"text": "Cookie: name=value\n"
},
{
"code": null,
"e": 11941,
"s": 11871,
"text": "Multiple cookies can be specified separated by semicolons as follows:"
},
{
"code": null,
"e": 11989,
"s": 11941,
"text": "Cookie: name1=value1;name2=value2;name3=value3\n"
},
{
"code": null,
"e": 12133,
"s": 11989,
"text": "The Expect request-header field is used to indicate that a particular set of server behaviors is required by the client. The general syntax is:"
},
{
"code": null,
"e": 12180,
"s": 12133,
"text": "Expect : 100-continue | expectation-extension\n"
},
{
"code": null,
"e": 12359,
"s": 12180,
"text": "If a server receives a request containing an Expect field that includes an expectation-extension that it does not support, it must respond with a 417 (Expectation Failed) status."
},
{
"code": null,
"e": 12515,
"s": 12359,
"text": "The From request-header field contains an Internet e-mail address for the human user who controls the requesting user agent. Following is a simple example:"
},
{
"code": null,
"e": 12539,
"s": 12515,
"text": "From: [email protected]\n"
},
{
"code": null,
"e": 12665,
"s": 12539,
"text": "This header field may be used for logging purposes and as a means for identifying the source of invalid or unwanted requests."
},
{
"code": null,
"e": 12808,
"s": 12665,
"text": "The Host request-header field is used to specify the Internet host and the port number of the resource being requested. The general syntax is:"
},
{
"code": null,
"e": 12847,
"s": 12808,
"text": "Host : \"Host\" \":\" host [ \":\" port ] ;\n"
},
{
"code": null,
"e": 13016,
"s": 12847,
"text": "A host without any trailing port information implies the default port, which is 80. For example, a request on the origin server for http://www.w3.org/pub/WWW/ would be:"
},
{
"code": null,
"e": 13057,
"s": 13016,
"text": "GET /pub/WWW/ HTTP/1.1\nHost: www.w3.org\n"
},
{
"code": null,
"e": 13311,
"s": 13057,
"text": "The If-Match request-header field is used with a method to make it conditional. This header requests the server to perform the requested method only if the given value in this tag matches the given entity tags represented by ETag. The general syntax is:"
},
{
"code": null,
"e": 13334,
"s": 13311,
"text": "If-Match : entity-tag\n"
},
{
"code": null,
"e": 13460,
"s": 13334,
"text": "An asterisk (*) matches any entity, and the transaction continues only if the entity exists. Following are possible examples:"
},
{
"code": null,
"e": 13534,
"s": 13460,
"text": "If-Match: \"xyzzy\"\nIf-Match: \"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"\nIf-Match: *\n"
},
{
"code": null,
"e": 13721,
"s": 13534,
"text": "If none of the entity tags match, or if \"*\" is given and no current entity exists, the server must not perform the requested method, and must return a 412 (Precondition Failed) response."
},
{
"code": null,
"e": 14067,
"s": 13721,
"text": "The If-Modified-Since request-header field is used with a method to make it conditional. If the requested URL has not been modified since the time specified in this field, an entity will not be returned from the server; instead, a 304 (not modified) response will be returned without any message-body. The general syntax of if-modified-since is:"
},
{
"code": null,
"e": 14098,
"s": 14067,
"text": "If-Modified-Since : HTTP-date\n"
},
{
"code": null,
"e": 14126,
"s": 14098,
"text": "An example of the field is:"
},
{
"code": null,
"e": 14176,
"s": 14126,
"text": "If-Modified-Since: Sat, 29 Oct 1994 19:43:31 GMT\n"
},
{
"code": null,
"e": 14363,
"s": 14176,
"text": "If none of the entity tags match, or if \"*\" is given and no current entity exists, the server must not perform the requested method, and must return a 412 (Precondition Failed) response."
},
{
"code": null,
"e": 14629,
"s": 14363,
"text": "The If-None-Match request-header field is used with a method to make it conditional. This header requests the server to perform the requested method only if one of the given value in this tag matches the given entity tags represented by ETag. The general syntax is:"
},
{
"code": null,
"e": 14657,
"s": 14629,
"text": "If-None-Match : entity-tag\n"
},
{
"code": null,
"e": 14795,
"s": 14657,
"text": "An asterisk (*) matches any entity, and the transaction continues only if the entity does not exist. Following are the possible examples:"
},
{
"code": null,
"e": 14884,
"s": 14795,
"text": "If-None-Match: \"xyzzy\"\nIf-None-Match: \"xyzzy\", \"r2d2xxxx\", \"c3piozzzz\"\nIf-None-Match: *\n"
},
{
"code": null,
"e": 15120,
"s": 14884,
"text": "The If-Range request-header field can be used with a conditional GET to request only the portion of the entity that is missing, if it has not been changed, and the entire entity if it has been changed. The general syntax is as follows:"
},
{
"code": null,
"e": 15155,
"s": 15120,
"text": "If-Range : entity-tag | HTTP-date\n"
},
{
"code": null,
"e": 15261,
"s": 15155,
"text": "Either an entity tag or a date can be used to identify the partial entity already received. For example:"
},
{
"code": null,
"e": 15302,
"s": 15261,
"text": "If-Range: Sat, 29 Oct 1994 19:43:31 GMT\n"
},
{
"code": null,
"e": 15474,
"s": 15302,
"text": "Here if the document has not been modified since the given date, the server returns the byte range given by the Range header, otherwise it returns all of the new document."
},
{
"code": null,
"e": 15588,
"s": 15474,
"text": "The If-Unmodified-Since request-header field is used with a method to make it conditional. The general syntax is:"
},
{
"code": null,
"e": 15621,
"s": 15588,
"text": "If-Unmodified-Since : HTTP-date\n"
},
{
"code": null,
"e": 15827,
"s": 15621,
"text": "If the requested resource has not been modified since the time specified in this field, the server should perform the requested operation as if the If-Unmodified-Since header were not present. For example:"
},
{
"code": null,
"e": 15879,
"s": 15827,
"text": "If-Unmodified-Since: Sat, 29 Oct 1994 19:43:31 GMT\n"
},
{
"code": null,
"e": 15996,
"s": 15879,
"text": "If the request results in anything other than a 2xx or 412 status, the If-Unmodified-Since header should be ignored."
},
{
"code": null,
"e": 16218,
"s": 15996,
"text": "The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server. Here is the general syntax:"
},
{
"code": null,
"e": 16236,
"s": 16218,
"text": "Max-Forwards : n\n"
},
{
"code": null,
"e": 16451,
"s": 16236,
"text": "The Max-Forwards value is a decimal integer indicating the remaining number of times this request message may be forwarded. This is useful for debugging with the TRACE method, avoiding infinite loops. For example:"
},
{
"code": null,
"e": 16469,
"s": 16451,
"text": "Max-Forwards : 5\n"
},
{
"code": null,
"e": 16571,
"s": 16469,
"text": "The Max-Forwards header field may be ignored for all other methods defined in the HTTP specification."
},
{
"code": null,
"e": 16737,
"s": 16571,
"text": "The Proxy-Authorization request-header field allows the client to identify itself (or its user) to a proxy which requires authentication. Here is the general syntax:"
},
{
"code": null,
"e": 16772,
"s": 16737,
"text": "Proxy-Authorization : credentials\n"
},
{
"code": null,
"e": 16952,
"s": 16772,
"text": "The Proxy-Authorization field value consists of credentials containing the authentication information of the user agent for the proxy and/or realm of the resource being requested."
},
{
"code": null,
"e": 17081,
"s": 16952,
"text": "The Range request-header field specifies the partial range(s) of the content requested from the document. The general syntax is:"
},
{
"code": null,
"e": 17135,
"s": 17081,
"text": "Range: bytes-unit=first-byte-pos \"-\" [last-byte-pos]\n"
},
{
"code": null,
"e": 17467,
"s": 17135,
"text": "The first-byte-pos value in a byte-range-spec gives the byte-offset of the first byte in a range. The last-byte-pos value gives the byte-offset of the last byte in the range; that is, the byte positions specified are inclusive. You can specify a byte-unit as bytes. Byte offsets start at zero. Some simple examples are as follows:"
},
{
"code": null,
"e": 17649,
"s": 17467,
"text": "- The first 500 bytes \nRange: bytes=0-499\n\n- The second 500 bytes\nRange: bytes=500-999\n\n- The final 500 bytes\nRange: bytes=-500\n\n- The first and last bytes only\nRange: bytes=0-0,-1\n"
},
{
"code": null,
"e": 17909,
"s": 17649,
"text": "Multiple ranges can be listed, separated by commas. If the first digit in the comma-separated byte range(s) is missing, the range is assumed to count from the end of the document. If the second digit is missing, the range is byte n to the end of the document."
},
{
"code": null,
"e": 18078,
"s": 17909,
"text": "The Referer request-header field allows the client to specify the address (URI) of the resource from which the URL has been requested. The general syntax is as follows:"
},
{
"code": null,
"e": 18115,
"s": 18078,
"text": "Referer : absoluteURI | relativeURI\n"
},
{
"code": null,
"e": 18146,
"s": 18115,
"text": "Following is a simple example:"
},
{
"code": null,
"e": 18201,
"s": 18146,
"text": "Referer: http://www.tutorialspoint.org/http/index.htm\n"
},
{
"code": null,
"e": 18293,
"s": 18201,
"text": "If the field value is a relative URI, it should be interpreted relative to the Request-URI."
},
{
"code": null,
"e": 18523,
"s": 18293,
"text": "The TE request-header field indicates what extension transfer-coding it is willing to accept in the response and whether or not it is willing to accept trailer fields in a chunked transfer-coding. Following is the general syntax:"
},
{
"code": null,
"e": 18541,
"s": 18523,
"text": "TE : t-codings\n"
},
{
"code": null,
"e": 18711,
"s": 18541,
"text": "The presence of the keyword \"trailers\" indicates that the client is willing to accept trailer fields in a chunked transfer-coding and it is specified either of the ways:"
},
{
"code": null,
"e": 18756,
"s": 18711,
"text": "TE: deflate\nTE:\nTE: trailers, deflate;q=0.5\n"
},
{
"code": null,
"e": 18911,
"s": 18756,
"text": "If the TE field-value is empty or if no TE field is present, then only transfer-coding is chunked. A message with no transfer-coding is always acceptable."
},
{
"code": null,
"e": 19047,
"s": 18911,
"text": "The User-Agent request-header field contains information about the user agent originating the request. Following is the general syntax:"
},
{
"code": null,
"e": 19079,
"s": 19047,
"text": "User-Agent : product | comment\n"
},
{
"code": null,
"e": 19088,
"s": 19079,
"text": "Example:"
},
{
"code": null,
"e": 19148,
"s": 19088,
"text": "User-Agent: Mozilla/4.0 (compatible; MSIE5.01; Windows NT)\n"
},
{
"code": null,
"e": 19290,
"s": 19148,
"text": "The Accept-Ranges response-header field allows the server to indicate its acceptance of range requests for a resource. The general syntax is:"
},
{
"code": null,
"e": 19326,
"s": 19290,
"text": "Accept-Ranges : range-unit | none\n"
},
{
"code": null,
"e": 19391,
"s": 19326,
"text": "For example a server that accepts byte-range requests may send:"
},
{
"code": null,
"e": 19413,
"s": 19391,
"text": "Accept-Ranges: bytes\n"
},
{
"code": null,
"e": 19492,
"s": 19413,
"text": " Servers that do not accept any kind of range request for a resource may send:"
},
{
"code": null,
"e": 19513,
"s": 19492,
"text": "Accept-Ranges: none\n"
},
{
"code": null,
"e": 19573,
"s": 19513,
"text": "This will advise the client not to attempt a range request."
},
{
"code": null,
"e": 19755,
"s": 19573,
"text": "The Age response-header field conveys the sender's estimate of the amount of time since the response (or its revalidation) was generated at the origin server. The general syntax is:"
},
{
"code": null,
"e": 19776,
"s": 19755,
"text": "Age : delta-seconds\n"
},
{
"code": null,
"e": 19883,
"s": 19776,
"text": "Age values are non-negative decimal integers, representing time in seconds. Following is a simple example:"
},
{
"code": null,
"e": 19894,
"s": 19883,
"text": "Age: 1030\n"
},
{
"code": null,
"e": 20016,
"s": 19894,
"text": "An HTTP/1.1 server that includes a cache must include an Age header field in every response generated from its own cache."
},
{
"code": null,
"e": 20142,
"s": 20016,
"text": "The ETag response-header field provides the current value of the entity tag for the requested variant. The general syntax is:"
},
{
"code": null,
"e": 20162,
"s": 20142,
"text": "ETag : entity-tag\n"
},
{
"code": null,
"e": 20193,
"s": 20162,
"text": "Here are some simple examples:"
},
{
"code": null,
"e": 20233,
"s": 20193,
"text": "ETag: \"xyzzy\"\nETag: W/\"xyzzy\"\nETag: \"\"\n"
},
{
"code": null,
"e": 20382,
"s": 20233,
"text": "The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion. The general syntax is:"
},
{
"code": null,
"e": 20406,
"s": 20382,
"text": "Location : absoluteURI\n"
},
{
"code": null,
"e": 20437,
"s": 20406,
"text": "Following is a simple example:"
},
{
"code": null,
"e": 20493,
"s": 20437,
"text": "Location: http://www.tutorialspoint.org/http/index.htm\n"
},
{
"code": null,
"e": 20650,
"s": 20493,
"text": "The Content-Location header field differs from Location in that the Content-Location identifies the original location of the entity enclosed in the request."
},
{
"code": null,
"e": 20796,
"s": 20650,
"text": "The Proxy-Authenticate response-header field must be included as a part of a 407 (Proxy Authentication Required) response. The general syntax is:"
},
{
"code": null,
"e": 20829,
"s": 20796,
"text": "Proxy-Authenticate : challenge\n"
},
{
"code": null,
"e": 21033,
"s": 20829,
"text": "The Retry-After response-header field can be used with a 503 (Service Unavailable) response to indicate how long the service is expected to be unavailable to the requesting client. The general syntax is:"
},
{
"code": null,
"e": 21074,
"s": 21033,
"text": "Retry-After : HTTP-date | delta-seconds\n"
},
{
"code": null,
"e": 21084,
"s": 21074,
"text": "Examples:"
},
{
"code": null,
"e": 21145,
"s": 21084,
"text": "Retry-After: Fri, 31 Dec 1999 23:59:59 GMT\nRetry-After: 120\n"
},
{
"code": null,
"e": 21192,
"s": 21145,
"text": "In the latter example, the delay is 2 minutes."
},
{
"code": null,
"e": 21337,
"s": 21192,
"text": "The Server response-header field contains information about the software used by the origin server to handle the request. The general syntax is:"
},
{
"code": null,
"e": 21365,
"s": 21337,
"text": "Server : product | comment\n"
},
{
"code": null,
"e": 21396,
"s": 21365,
"text": "Following is a simple example:"
},
{
"code": null,
"e": 21427,
"s": 21396,
"text": "Server: Apache/2.2.14 (Win32)\n"
},
{
"code": null,
"e": 21545,
"s": 21427,
"text": "If the response is being forwarded through a proxy, the proxy application must not modify the Server response-header."
},
{
"code": null,
"e": 21671,
"s": 21545,
"text": "The Set-Cookie response-header field contains a name/value pair of information to retain for this URL. The general syntax is:"
},
{
"code": null,
"e": 21704,
"s": 21671,
"text": "Set-Cookie: NAME=VALUE; OPTIONS\n"
},
{
"code": null,
"e": 21879,
"s": 21704,
"text": "Set-Cookie response header comprises the token Set-Cookie, followed by a comma-separated list of one or more cookies. Here are the possible values you can specify as options:"
},
{
"code": null,
"e": 21954,
"s": 21879,
"text": "This option can be used to specify any comment associated with the cookie."
},
{
"code": null,
"e": 22028,
"s": 21954,
"text": " The Domain attribute specifies the domain for which the cookie is valid."
},
{
"code": null,
"e": 22136,
"s": 22028,
"text": "The date the cookie will expire. If it is blank, the cookie will expire when the visitor quits the browser."
},
{
"code": null,
"e": 22214,
"s": 22136,
"text": "The Path attribute specifies the subset of URLs to which this cookie applies."
},
{
"code": null,
"e": 22295,
"s": 22214,
"text": "It instructs the user agent to return the cookie only under a secure connection."
},
{
"code": null,
"e": 22370,
"s": 22295,
"text": "Following is an example of a simple cookie header generated by the server:"
},
{
"code": null,
"e": 22448,
"s": 22370,
"text": "Set-Cookie: name1=value1,name2=value2; Expires=Wed, 09 Jun 2021 10:18:14 GMT\n"
},
{
"code": null,
"e": 22636,
"s": 22448,
"text": "The Vary response-header field specifies that the entity has multiple sources and may therefore vary according to the specified list of request header(s). Following is the general syntax:"
},
{
"code": null,
"e": 22655,
"s": 22636,
"text": "Vary : field-name\n"
},
{
"code": null,
"e": 22843,
"s": 22655,
"text": "You can specify multiple headers separated by commas and a value of asterisk \"*\" signals that unspecified parameters are not limited to the request-headers. Following is a simple example:"
},
{
"code": null,
"e": 22883,
"s": 22843,
"text": "Vary: Accept-Language, Accept-Encoding\n"
},
{
"code": null,
"e": 22922,
"s": 22883,
"text": "Here field names are case-insensitive."
},
{
"code": null,
"e": 23187,
"s": 22922,
"text": "The WWW-Authenticate response-header field must be included in 401 (Unauthorized) response messages. The field value consists of at least one challenge that indicates the authentication scheme(s) and parameters applicable to the Request-URI. The general syntax is:"
},
{
"code": null,
"e": 23217,
"s": 23187,
"text": "WWW-Authenticate : challenge\n"
},
{
"code": null,
"e": 23480,
"s": 23217,
"text": "WWW- Authenticate field value might contain more than one challenge, or if more than one WWW-Authenticate header field is provided, the contents of a challenge itself can contain a comma-separated list of authentication parameters. Following is a simple example:"
},
{
"code": null,
"e": 23519,
"s": 23480,
"text": "WWW-Authenticate: BASIC realm=\"Admin\"\n"
},
{
"code": null,
"e": 23654,
"s": 23519,
"text": "The Allow entity-header field lists the set of methods supported by the resource identified by the Request-URI. The general syntax is:"
},
{
"code": null,
"e": 23670,
"s": 23654,
"text": "Allow : Method\n"
},
{
"code": null,
"e": 23755,
"s": 23670,
"text": "You can specify multiple methods separated by commas. Following is a simple example:"
},
{
"code": null,
"e": 23778,
"s": 23755,
"text": "Allow: GET, HEAD, PUT\n"
},
{
"code": null,
"e": 23840,
"s": 23778,
"text": "This field cannot prevent a client from trying other methods."
},
{
"code": null,
"e": 23945,
"s": 23840,
"text": "The Content-Encoding entity-header field is used as a modifier to the media-type. The general syntax is:"
},
{
"code": null,
"e": 23980,
"s": 23945,
"text": "Content-Encoding : content-coding\n"
},
{
"code": null,
"e": 24095,
"s": 23980,
"text": "The content-coding is a characteristic of the entity identified by the Request-URI. Following is a simple example:"
},
{
"code": null,
"e": 24119,
"s": 24095,
"text": "Content-Encoding: gzip\n"
},
{
"code": null,
"e": 24293,
"s": 24119,
"text": "If the content-coding of an entity in a request message is not acceptable to the origin server, the server should respond with a status code of 415 (Unsupported Media Type)."
},
{
"code": null,
"e": 24451,
"s": 24293,
"text": "The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Following is the general syntax:"
},
{
"code": null,
"e": 24484,
"s": 24451,
"text": "Content-Language : language-tag\n"
},
{
"code": null,
"e": 24601,
"s": 24484,
"text": "Multiple languages may be listed for content that is intended for multiple audiences. Following is a simple example:"
},
{
"code": null,
"e": 24627,
"s": 24601,
"text": "Content-Language: mi, en\n"
},
{
"code": null,
"e": 24773,
"s": 24627,
"text": "The primary purpose of Content-Language is to allow a user to identify and differentiate entities according to the user's own preferred language."
},
{
"code": null,
"e": 25044,
"s": 24773,
"text": "The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent, had the request been a GET. The general syntax is:"
},
{
"code": null,
"e": 25069,
"s": 25044,
"text": "Content-Length : DIGITS\n"
},
{
"code": null,
"e": 25100,
"s": 25069,
"text": "Following is a simple example:"
},
{
"code": null,
"e": 25122,
"s": 25100,
"text": "Content-Length: 3495\n"
},
{
"code": null,
"e": 25189,
"s": 25122,
"text": "Any Content-Length greater than or equal to zero is a valid value."
},
{
"code": null,
"e": 25427,
"s": 25189,
"text": "The Content-Location entity-header field may be used to supply the resource location for the entity enclosed in the message when that entity is accessible from a location separate from the requested resource's URI. The general syntax is:"
},
{
"code": null,
"e": 25474,
"s": 25427,
"text": "Content-Location: absoluteURI | relativeURI \n"
},
{
"code": null,
"e": 25505,
"s": 25474,
"text": "Following is a simple example:"
},
{
"code": null,
"e": 25569,
"s": 25505,
"text": "Content-Location: http://www.tutorialspoint.org/http/index.htm\n"
},
{
"code": null,
"e": 25642,
"s": 25569,
"text": "The value of Content-Location also defines the base URI for the entity. "
},
{
"code": null,
"e": 25807,
"s": 25642,
"text": "The Content-MD5 entity-header field may be used to supply an MD5 digest of the entity for checking the integrity\nof the message upon receipt. The general syntax is:"
},
{
"code": null,
"e": 25885,
"s": 25807,
"text": "Content-MD5 : md5-digest using base64 of 128 bit MD5 digest as per RFC 1864\n"
},
{
"code": null,
"e": 25916,
"s": 25885,
"text": "Following is a simple example:"
},
{
"code": null,
"e": 25965,
"s": 25916,
"text": "Content-MD5 : 8c2d46911f3f5a326455f0ed7a8ed3b3\n"
},
{
"code": null,
"e": 26154,
"s": 25965,
"text": "The MD5 digest is computed based on the content of the entity-body, including any content-coding that has been applied, but not including any transfer-encoding applied to the message-body."
},
{
"code": null,
"e": 26328,
"s": 26154,
"text": "The Content-Range entity-header field is sent with a partial entity-body to specify where in the full entity-body the partial body should be applied. The general syntax is:"
},
{
"code": null,
"e": 26392,
"s": 26328,
"text": "Content-Range : bytes-unit SP first-byte-pos \"-\" last-byte-pos\n"
},
{
"code": null,
"e": 26493,
"s": 26392,
"text": "Examples of byte-content-range-spec values, assuming that the entity contains a total of 1234 bytes:"
},
{
"code": null,
"e": 26744,
"s": 26493,
"text": "- The first 500 bytes:\nContent-Range : bytes 0-499/1234\n\n- The second 500 bytes:\nContent-Range : bytes 500-999/1234\n\n- All except for the first 500 bytes:\nContent-Range : bytes 500-1233/1234\n\n- The last 500 bytes:\nContent-Range : bytes 734-1233/1234\n"
},
{
"code": null,
"e": 26954,
"s": 26744,
"text": "When an HTTP message includes the content of a single range, this content is transmitted with a Content-Range header, and a Content-Length header showing the number of bytes actually transferred. For example,"
},
{
"code": null,
"e": 27150,
"s": 26954,
"text": "HTTP/1.1 206 Partial content\nDate: Wed, 15 Nov 1995 06:25:24 GMT\nLast-Modified: Wed, 15 Nov 1995 04:58:08 GMT\nContent-Range: bytes 21010-47021/47022\nContent-Length: 26012\nContent-Type: image/gif\n"
},
{
"code": null,
"e": 27382,
"s": 27150,
"text": "The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent, had the request been a GET. The general syntax is:"
},
{
"code": null,
"e": 27409,
"s": 27382,
"text": "Content-Type : media-type\n"
},
{
"code": null,
"e": 27434,
"s": 27409,
"text": "Following is an example:"
},
{
"code": null,
"e": 27479,
"s": 27434,
"text": "Content-Type: text/html; charset=ISO-8859-4\n"
},
{
"code": null,
"e": 27600,
"s": 27479,
"text": "The Expires entity-header field gives the date/time after which the response is considered stale. The general syntax is:"
},
{
"code": null,
"e": 27621,
"s": 27600,
"text": "Expires : HTTP-date\n"
},
{
"code": null,
"e": 27646,
"s": 27621,
"text": "Following is an example:"
},
{
"code": null,
"e": 27686,
"s": 27646,
"text": "Expires: Thu, 01 Dec 1994 16:00:00 GMT\n"
},
{
"code": null,
"e": 27842,
"s": 27686,
"text": "The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified. The general syntax is:"
},
{
"code": null,
"e": 27868,
"s": 27842,
"text": "Last-Modified: HTTP-date\n"
},
{
"code": null,
"e": 27893,
"s": 27868,
"text": "Following is an example:"
},
{
"code": null,
"e": 27939,
"s": 27893,
"text": "Last-Modified: Tue, 15 Nov 1994 12:45:26 GMT\n"
},
{
"code": null,
"e": 27946,
"s": 27939,
"text": " Print"
},
{
"code": null,
"e": 27957,
"s": 27946,
"text": " Add Notes"
}
] |
Java Program for Heap Sort - GeeksforGeeks | 27 Mar, 2019
Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.
// Java program for implementation of Heap Sortpublic class HeapSort{ public void sort(int arr[]) { int n = arr.length; // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i=n-1; i>=0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap void heapify(int arr[], int n, int i) { int largest = i; // Initialize largest as root int l = 2*i + 1; // left = 2*i + 1 int r = 2*i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i]+" "); System.out.println(); } // Driver program public static void main(String args[]) { int arr[] = {12, 11, 13, 5, 6, 7}; int n = arr.length; HeapSort ob = new HeapSort(); ob.sort(arr); System.out.println("Sorted array is"); printArray(arr); }}
Please refer complete article on Heap Sort for more details!
Heap Sort
Heap
Java Programs
Sorting
Sorting
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Building Heap from Array
Sliding Window Maximum (Maximum of all subarrays of size k)
Insertion and Deletion in Heaps
Max Heap in Java
Merge k sorted arrays | Set 1
Convert a String to Character array in Java
Initializing a List in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class | [
{
"code": null,
"e": 23677,
"s": 23649,
"text": "\n27 Mar, 2019"
},
{
"code": null,
"e": 23928,
"s": 23677,
"text": "Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element."
},
{
"code": "// Java program for implementation of Heap Sortpublic class HeapSort{ public void sort(int arr[]) { int n = arr.length; // Build heap (rearrange array) for (int i = n / 2 - 1; i >= 0; i--) heapify(arr, n, i); // One by one extract an element from heap for (int i=n-1; i>=0; i--) { // Move current root to end int temp = arr[0]; arr[0] = arr[i]; arr[i] = temp; // call max heapify on the reduced heap heapify(arr, i, 0); } } // To heapify a subtree rooted with node i which is // an index in arr[]. n is size of heap void heapify(int arr[], int n, int i) { int largest = i; // Initialize largest as root int l = 2*i + 1; // left = 2*i + 1 int r = 2*i + 2; // right = 2*i + 2 // If left child is larger than root if (l < n && arr[l] > arr[largest]) largest = l; // If right child is larger than largest so far if (r < n && arr[r] > arr[largest]) largest = r; // If largest is not root if (largest != i) { int swap = arr[i]; arr[i] = arr[largest]; arr[largest] = swap; // Recursively heapify the affected sub-tree heapify(arr, n, largest); } } /* A utility function to print array of size n */ static void printArray(int arr[]) { int n = arr.length; for (int i=0; i<n; ++i) System.out.print(arr[i]+\" \"); System.out.println(); } // Driver program public static void main(String args[]) { int arr[] = {12, 11, 13, 5, 6, 7}; int n = arr.length; HeapSort ob = new HeapSort(); ob.sort(arr); System.out.println(\"Sorted array is\"); printArray(arr); }}",
"e": 25799,
"s": 23928,
"text": null
},
{
"code": null,
"e": 25860,
"s": 25799,
"text": "Please refer complete article on Heap Sort for more details!"
},
{
"code": null,
"e": 25870,
"s": 25860,
"text": "Heap Sort"
},
{
"code": null,
"e": 25875,
"s": 25870,
"text": "Heap"
},
{
"code": null,
"e": 25889,
"s": 25875,
"text": "Java Programs"
},
{
"code": null,
"e": 25897,
"s": 25889,
"text": "Sorting"
},
{
"code": null,
"e": 25905,
"s": 25897,
"text": "Sorting"
},
{
"code": null,
"e": 25910,
"s": 25905,
"text": "Heap"
},
{
"code": null,
"e": 26008,
"s": 25910,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26017,
"s": 26008,
"text": "Comments"
},
{
"code": null,
"e": 26030,
"s": 26017,
"text": "Old Comments"
},
{
"code": null,
"e": 26055,
"s": 26030,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 26115,
"s": 26055,
"text": "Sliding Window Maximum (Maximum of all subarrays of size k)"
},
{
"code": null,
"e": 26147,
"s": 26115,
"text": "Insertion and Deletion in Heaps"
},
{
"code": null,
"e": 26164,
"s": 26147,
"text": "Max Heap in Java"
},
{
"code": null,
"e": 26194,
"s": 26164,
"text": "Merge k sorted arrays | Set 1"
},
{
"code": null,
"e": 26238,
"s": 26194,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 26266,
"s": 26238,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 26292,
"s": 26266,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 26326,
"s": 26292,
"text": "Convert Double to Integer in Java"
}
] |
Preventing an image from being draggable or selectable in HTML without using JS | Add the following code snippet to image properties, and prevent images from being dragged and selected.
img {
user-drag: none;
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
}
On double click on a text or image, it is highlighted (selected). The user select property can be used to prevent this. By setting this property to none, we can prevent our image from being selected (highlighted).
You can try to run the following code to prevent the image from being selected −
<!DOCTYPE html>
<html>
<head>
<style>
img {
-drag: none;
user-select: none;
-moz-user-select: none;
-webkit-user-drag: none;
-webkit-user-select: none;
-ms-user-select: none;
}
</style>
</head>
<body>
<img src = "https://www.tutorialspoint.com/images/python3.png" alt = "Python" width = "62" height = "62">
</body>
</html> | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "Add the following code snippet to image properties, and prevent images from being dragged and selected."
},
{
"code": null,
"e": 1331,
"s": 1166,
"text": "img { \n user-drag: none; \n user-select: none;\n -moz-user-select: none;\n -webkit-user-drag: none;\n -webkit-user-select: none;\n -ms-user-select: none;\n}"
},
{
"code": null,
"e": 1545,
"s": 1331,
"text": "On double click on a text or image, it is highlighted (selected). The user select property can be used to prevent this. By setting this property to none, we can prevent our image from being selected (highlighted)."
},
{
"code": null,
"e": 1626,
"s": 1545,
"text": "You can try to run the following code to prevent the image from being selected −"
},
{
"code": null,
"e": 2069,
"s": 1626,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n img {\n -drag: none;\n user-select: none;\n -moz-user-select: none;\n -webkit-user-drag: none;\n -webkit-user-select: none;\n -ms-user-select: none;\n }\n </style>\n </head>\n <body>\n <img src = \"https://www.tutorialspoint.com/images/python3.png\" alt = \"Python\" width = \"62\" height = \"62\">\n </body>\n</html>"
}
] |
Recursive sum all the digits of a number JavaScript | Let’s say, we are required to create a function that takes in a number and finds the sum of its
digits recursively until the sum is a one-digit number.
For example −
findSum(12345) = 1+2+3+4+5 = 15 = 1+5 = 6
So, the output should be 6.
Let’s write the code for this function findSum() −
// using recursion
const findSum = (num) => {
if(num < 10){
return num;
}
const lastDigit = num % 10;
const remainingNum = Math.floor(num / 10);
return findSum(lastDigit + findSum(remainingNum));
}
console.log(findSum(2568));
We check if the number is less than 10, it’s already minified and we should return it and from the
function otherwise we should return the call to the function that recursively takes the last digit
from the number adds to it until it becomes less than 10.
So, the output for this code will be −
3 | [
{
"code": null,
"e": 1214,
"s": 1062,
"text": "Let’s say, we are required to create a function that takes in a number and finds the sum of its\ndigits recursively until the sum is a one-digit number."
},
{
"code": null,
"e": 1228,
"s": 1214,
"text": "For example −"
},
{
"code": null,
"e": 1270,
"s": 1228,
"text": "findSum(12345) = 1+2+3+4+5 = 15 = 1+5 = 6"
},
{
"code": null,
"e": 1298,
"s": 1270,
"text": "So, the output should be 6."
},
{
"code": null,
"e": 1349,
"s": 1298,
"text": "Let’s write the code for this function findSum() −"
},
{
"code": null,
"e": 1596,
"s": 1349,
"text": "// using recursion\nconst findSum = (num) => {\n if(num < 10){\n return num;\n }\n const lastDigit = num % 10;\n const remainingNum = Math.floor(num / 10);\n return findSum(lastDigit + findSum(remainingNum));\n}\nconsole.log(findSum(2568));"
},
{
"code": null,
"e": 1852,
"s": 1596,
"text": "We check if the number is less than 10, it’s already minified and we should return it and from the\nfunction otherwise we should return the call to the function that recursively takes the last digit\nfrom the number adds to it until it becomes less than 10."
},
{
"code": null,
"e": 1891,
"s": 1852,
"text": "So, the output for this code will be −"
},
{
"code": null,
"e": 1893,
"s": 1891,
"text": "3"
}
] |
How to change the color code of corrplot in R? | To change the color code of corrplot, we can use colorRampPalette function inside corrplot function. We can provide different colors in colorRampPalette that we want to display in the corrplot.
Check out the below given example to understand how it can be done.
Following snippet creates a sample data frame −
x<-rpois(20,2)
y<-rpois(20,5)
z<-rpois(20,5)
a<-rpois(20,1)
b<-rpois(20,2)
df<-data.frame(x,y,z,a,b)
df
The following dataframe is created −
x y z a b
1 0 2 5 2 1
2 1 7 4 1 3
3 1 2 6 0 5
4 0 6 1 1 3
5 3 4 5 0 4
6 1 3 4 1 2
7 0 8 10 0 3
8 1 3 2 1 1
9 0 6 6 3 2
10 1 4 7 2 1
11 2 3 4 1 2
12 0 7 12 1 2
13 2 7 7 0 2
14 2 6 7 1 1
15 2 6 4 2 3
16 1 8 7 1 3
17 3 3 13 1 4
18 0 4 6 3 1
19 2 5 3 1 3
20 2 8 4 0 0
To find the correlation matrix, add the following code to the above snippet −
x<-rpois(20,2)
y<-rpois(20,5)
z<-rpois(20,5)
a<-rpois(20,1)
b<-rpois(20,2)
df<-data.frame(x,y,z,a,b)
Corr_M<-cor(df)
Corr_M
If you execute all the above given snippets as a single program, it generates the following output −
x y z a b
x 1.00000000 -0.1124089 0.02748119 -0.42486657 0.2408651
y -0.11240888 1.0000000 0.15417565 -0.20276944 -0.1140731
z 0.02748119 0.1541756 1.00000000 -0.07005503 0.1766658
a -0.42486657 -0.2027694 -0.07005503 1.00000000 -0.3479217
b 0.24086512 -0.1140731 0.17666576 -0.34792175 1.0000000
To load corrplot package and create a correlation matrix plot, add the following code to the above snippet −
library(corrplot)
corrplot(abs(Corr_M),method="color",cl.lim=c(0,1))
If you execute all the above given snippets as a single program, it generates the following output −
To create a correlation matrix plot with different colors, add the following code to the above snippet −
corrplot(abs(Corr_M),method="color",col=colorRampPalette(c("white","lightblue","red"))(100),cl.lim=c(0,1))
If you execute all the above given snippets as a single program, it generates the following output − | [
{
"code": null,
"e": 1256,
"s": 1062,
"text": "To change the color code of corrplot, we can use colorRampPalette function inside corrplot function. We can provide different colors in colorRampPalette that we want to display in the corrplot."
},
{
"code": null,
"e": 1324,
"s": 1256,
"text": "Check out the below given example to understand how it can be done."
},
{
"code": null,
"e": 1372,
"s": 1324,
"text": "Following snippet creates a sample data frame −"
},
{
"code": null,
"e": 1476,
"s": 1372,
"text": "x<-rpois(20,2)\ny<-rpois(20,5)\nz<-rpois(20,5)\na<-rpois(20,1)\nb<-rpois(20,2)\ndf<-data.frame(x,y,z,a,b)\ndf"
},
{
"code": null,
"e": 1513,
"s": 1476,
"text": "The following dataframe is created −"
},
{
"code": null,
"e": 1849,
"s": 1513,
"text": " x y z a b\n1 0 2 5 2 1\n2 1 7 4 1 3\n3 1 2 6 0 5\n4 0 6 1 1 3\n5 3 4 5 0 4\n6 1 3 4 1 2\n7 0 8 10 0 3\n8 1 3 2 1 1\n9 0 6 6 3 2\n10 1 4 7 2 1\n11 2 3 4 1 2\n12 0 7 12 1 2\n13 2 7 7 0 2\n14 2 6 7 1 1\n15 2 6 4 2 3\n16 1 8 7 1 3\n17 3 3 13 1 4\n18 0 4 6 3 1\n19 2 5 3 1 3\n20 2 8 4 0 0"
},
{
"code": null,
"e": 1927,
"s": 1849,
"text": "To find the correlation matrix, add the following code to the above snippet −"
},
{
"code": null,
"e": 2051,
"s": 1927,
"text": "x<-rpois(20,2)\ny<-rpois(20,5)\nz<-rpois(20,5)\na<-rpois(20,1)\nb<-rpois(20,2)\ndf<-data.frame(x,y,z,a,b)\nCorr_M<-cor(df)\nCorr_M"
},
{
"code": null,
"e": 2152,
"s": 2051,
"text": "If you execute all the above given snippets as a single program, it generates the following output −"
},
{
"code": null,
"e": 2506,
"s": 2152,
"text": " x y z a b\nx 1.00000000 -0.1124089 0.02748119 -0.42486657 0.2408651\ny -0.11240888 1.0000000 0.15417565 -0.20276944 -0.1140731\nz 0.02748119 0.1541756 1.00000000 -0.07005503 0.1766658\na -0.42486657 -0.2027694 -0.07005503 1.00000000 -0.3479217\nb 0.24086512 -0.1140731 0.17666576 -0.34792175 1.0000000"
},
{
"code": null,
"e": 2615,
"s": 2506,
"text": "To load corrplot package and create a correlation matrix plot, add the following code to the above snippet −"
},
{
"code": null,
"e": 2684,
"s": 2615,
"text": "library(corrplot)\ncorrplot(abs(Corr_M),method=\"color\",cl.lim=c(0,1))"
},
{
"code": null,
"e": 2785,
"s": 2684,
"text": "If you execute all the above given snippets as a single program, it generates the following output −"
},
{
"code": null,
"e": 2890,
"s": 2785,
"text": "To create a correlation matrix plot with different colors, add the following code to the above snippet −"
},
{
"code": null,
"e": 2998,
"s": 2890,
"text": "corrplot(abs(Corr_M),method=\"color\",col=colorRampPalette(c(\"white\",\"lightblue\",\"red\"))(100),cl.lim=c(0,1))\n"
},
{
"code": null,
"e": 3099,
"s": 2998,
"text": "If you execute all the above given snippets as a single program, it generates the following output −"
}
] |
Program to print the initials of a name with the surname | 13 Jun, 2022
Given a full name in the form of a string, the task is to print the initials of a name, in short, and surname in full. Examples:
Input: Devashish Kumar Gupta
Output: D. K. Gupta
Input: Ishita Bhuiya
Output: I. Bhuiya
Approach: The basic approach is to extract words one by one and then print the first letter of the word, followed by a dot(.). For the surname, extract and print the whole word. Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to print the initials// of a name with the surname#include <bits/stdc++.h>using namespace std; void printInitials(string str){ int len = str.length(); // to remove any leading or trailing spaces str.erase(0, str.find_first_not_of(' ')); str.erase(str.find_last_not_of(' ') + 1); // to store extracted words string t = ""; for (int i = 0; i < len; i++) { char ch = str[i]; if (ch != ' ') // forming the word t = t + ch; // when space is encountered // it means the name is completed // and thereby extracted else { // printing the first letter // of the name in capital letters cout << (char)toupper(t[0]) << ". "; t = ""; } } string temp = ""; // for the surname, we have to print the entire // surname and not just the initial // string "t" has the surname now for (int j = 0; j < t.length(); j++) { // first letter of surname in capital letter if (j == 0) temp = temp + (char)toupper(t[0]); // rest of the letters in small else temp = temp + (char)tolower(t[j]); } // printing surname cout << temp << endl;} // Driver Codeint main(){ string str = "ishita bhuiya"; printInitials(str);} // This code is contributed by// sanjeev2552
// Java program to print the initials// of a name with the surnameimport java.util.*; class Initials { public static void printInitials(String str) { int len = str.length(); // to remove any leading or trailing spaces str = str.trim(); // to store extracted words String t = ""; for (int i = 0; i < len; i++) { char ch = str.charAt(i); if (ch != ' ') { // forming the word t = t + ch; } // when space is encountered // it means the name is completed // and thereby extracted else { // printing the first letter // of the name in capital letters System.out.print(Character.toUpperCase(t.charAt(0)) + ". "); t = ""; } } String temp = ""; // for the surname, we have to print the entire // surname and not just the initial // string "t" has the surname now for (int j = 0; j < t.length(); j++) { // first letter of surname in capital letter if (j == 0) temp = temp + Character.toUpperCase(t.charAt(0)); // rest of the letters in small else temp = temp + Character.toLowerCase(t.charAt(j)); } // printing surname System.out.println(temp); } public static void main(String[] args) { String str = "ishita bhuiya"; printInitials(str); }}
# Python program to print the initials# of a name with the surnamedef printInitials(string: str): length = len(string) # to remove any leading or trailing spaces string.strip() # to store extracted words t = "" for i in range(length): ch = string[i] if ch != ' ': # forming the word t += ch # when space is encountered # it means the name is completed # and thereby extracted else: # printing the first letter # of the name in capital letters print(t[0].upper() + ". ", end="") t = "" temp = "" # for the surname, we have to print the entire # surname and not just the initial # string "t" has the surname now for j in range(len(t)): # first letter of surname in capital letter if j == 0: temp += t[0].upper() # rest of the letters in small else: temp += t[j].lower() # printing surname print(temp) # Driver Codeif __name__ == "__main__": string = "ishita bhuiya" printInitials(string) # This code is contributed by# sanjeev2552
// C# program to print the initials// of a name with the surnameusing System; class Initials { public static void printInitials(string str) { int len = str.Length ; // to remove any leading or trailing spaces str = str.Trim(); // to store extracted words String t = ""; for (int i = 0; i < len; i++) { char ch = str[i]; if (ch != ' ') { // forming the word t = t + ch; } // when space is encountered // it means the name is completed // and thereby extracted else { // printing the first letter // of the name in capital letters Console.Write(Char.ToUpper(t[0]) + ". "); t = ""; } } string temp = ""; // for the surname, we have to print the entire // surname and not just the initial // string "t" has the surname now for (int j = 0; j < t.Length; j++) { // first letter of surname in capital letter if (j == 0) temp = temp + Char.ToUpper(t[0]); // rest of the letters in small else temp = temp + Char.ToLower(t[j]); } // printing surname Console.WriteLine(temp); } public static void Main() { string str = "ishita bhuiya"; printInitials(str); } // This code is contributed by Ryuga}
<script> // JavaScript program to print the initials// of a name with the surnamefunction printInitials(string){ let Length = string.length // to remove any leading or trailing spaces string = string.trim() // to store extracted words let t = "" for(let i=0;i<Length;i++){ let ch = string[i] if(ch != ' ') // forming the word t += ch // when space is encountered // it means the name is completed // and thereby extracted else{ // printing the first letter // of the name in capital letters document.write(t[0].toUpperCase() + ". ","") t = "" } } let temp = "" // for the surname, we have to print the entire // surname and not just the initial // string "t" has the surname now for(let j=0;j<t.length;j++){ // first letter of surname in capital letter if(j == 0) temp += t[0].toUpperCase() // rest of the letters in small else temp += t[j].toLowerCase() } // printing surname document.write(temp,"</br>")} // Driver Code let string = "ishita bhuiya"printInitials(string) // this code is contributed by shinjanpatra </script>
I. Bhuiya
ankthon
sanjeev2552
shinjanpatra
School Programming
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n13 Jun, 2022"
},
{
"code": null,
"e": 181,
"s": 52,
"text": "Given a full name in the form of a string, the task is to print the initials of a name, in short, and surname in full. Examples:"
},
{
"code": null,
"e": 270,
"s": 181,
"text": "Input: Devashish Kumar Gupta\nOutput: D. K. Gupta\n\nInput: Ishita Bhuiya\nOutput: I. Bhuiya"
},
{
"code": null,
"e": 500,
"s": 270,
"text": "Approach: The basic approach is to extract words one by one and then print the first letter of the word, followed by a dot(.). For the surname, extract and print the whole word. Below is the implementation of the above approach: "
},
{
"code": null,
"e": 504,
"s": 500,
"text": "C++"
},
{
"code": null,
"e": 509,
"s": 504,
"text": "Java"
},
{
"code": null,
"e": 517,
"s": 509,
"text": "Python3"
},
{
"code": null,
"e": 520,
"s": 517,
"text": "C#"
},
{
"code": null,
"e": 531,
"s": 520,
"text": "Javascript"
},
{
"code": "// C++ program to print the initials// of a name with the surname#include <bits/stdc++.h>using namespace std; void printInitials(string str){ int len = str.length(); // to remove any leading or trailing spaces str.erase(0, str.find_first_not_of(' ')); str.erase(str.find_last_not_of(' ') + 1); // to store extracted words string t = \"\"; for (int i = 0; i < len; i++) { char ch = str[i]; if (ch != ' ') // forming the word t = t + ch; // when space is encountered // it means the name is completed // and thereby extracted else { // printing the first letter // of the name in capital letters cout << (char)toupper(t[0]) << \". \"; t = \"\"; } } string temp = \"\"; // for the surname, we have to print the entire // surname and not just the initial // string \"t\" has the surname now for (int j = 0; j < t.length(); j++) { // first letter of surname in capital letter if (j == 0) temp = temp + (char)toupper(t[0]); // rest of the letters in small else temp = temp + (char)tolower(t[j]); } // printing surname cout << temp << endl;} // Driver Codeint main(){ string str = \"ishita bhuiya\"; printInitials(str);} // This code is contributed by// sanjeev2552",
"e": 1908,
"s": 531,
"text": null
},
{
"code": "// Java program to print the initials// of a name with the surnameimport java.util.*; class Initials { public static void printInitials(String str) { int len = str.length(); // to remove any leading or trailing spaces str = str.trim(); // to store extracted words String t = \"\"; for (int i = 0; i < len; i++) { char ch = str.charAt(i); if (ch != ' ') { // forming the word t = t + ch; } // when space is encountered // it means the name is completed // and thereby extracted else { // printing the first letter // of the name in capital letters System.out.print(Character.toUpperCase(t.charAt(0)) + \". \"); t = \"\"; } } String temp = \"\"; // for the surname, we have to print the entire // surname and not just the initial // string \"t\" has the surname now for (int j = 0; j < t.length(); j++) { // first letter of surname in capital letter if (j == 0) temp = temp + Character.toUpperCase(t.charAt(0)); // rest of the letters in small else temp = temp + Character.toLowerCase(t.charAt(j)); } // printing surname System.out.println(temp); } public static void main(String[] args) { String str = \"ishita bhuiya\"; printInitials(str); }}",
"e": 3471,
"s": 1908,
"text": null
},
{
"code": "# Python program to print the initials# of a name with the surnamedef printInitials(string: str): length = len(string) # to remove any leading or trailing spaces string.strip() # to store extracted words t = \"\" for i in range(length): ch = string[i] if ch != ' ': # forming the word t += ch # when space is encountered # it means the name is completed # and thereby extracted else: # printing the first letter # of the name in capital letters print(t[0].upper() + \". \", end=\"\") t = \"\" temp = \"\" # for the surname, we have to print the entire # surname and not just the initial # string \"t\" has the surname now for j in range(len(t)): # first letter of surname in capital letter if j == 0: temp += t[0].upper() # rest of the letters in small else: temp += t[j].lower() # printing surname print(temp) # Driver Codeif __name__ == \"__main__\": string = \"ishita bhuiya\" printInitials(string) # This code is contributed by# sanjeev2552",
"e": 4614,
"s": 3471,
"text": null
},
{
"code": "// C# program to print the initials// of a name with the surnameusing System; class Initials { public static void printInitials(string str) { int len = str.Length ; // to remove any leading or trailing spaces str = str.Trim(); // to store extracted words String t = \"\"; for (int i = 0; i < len; i++) { char ch = str[i]; if (ch != ' ') { // forming the word t = t + ch; } // when space is encountered // it means the name is completed // and thereby extracted else { // printing the first letter // of the name in capital letters Console.Write(Char.ToUpper(t[0]) + \". \"); t = \"\"; } } string temp = \"\"; // for the surname, we have to print the entire // surname and not just the initial // string \"t\" has the surname now for (int j = 0; j < t.Length; j++) { // first letter of surname in capital letter if (j == 0) temp = temp + Char.ToUpper(t[0]); // rest of the letters in small else temp = temp + Char.ToLower(t[j]); } // printing surname Console.WriteLine(temp); } public static void Main() { string str = \"ishita bhuiya\"; printInitials(str); } // This code is contributed by Ryuga}",
"e": 6138,
"s": 4614,
"text": null
},
{
"code": "<script> // JavaScript program to print the initials// of a name with the surnamefunction printInitials(string){ let Length = string.length // to remove any leading or trailing spaces string = string.trim() // to store extracted words let t = \"\" for(let i=0;i<Length;i++){ let ch = string[i] if(ch != ' ') // forming the word t += ch // when space is encountered // it means the name is completed // and thereby extracted else{ // printing the first letter // of the name in capital letters document.write(t[0].toUpperCase() + \". \",\"\") t = \"\" } } let temp = \"\" // for the surname, we have to print the entire // surname and not just the initial // string \"t\" has the surname now for(let j=0;j<t.length;j++){ // first letter of surname in capital letter if(j == 0) temp += t[0].toUpperCase() // rest of the letters in small else temp += t[j].toLowerCase() } // printing surname document.write(temp,\"</br>\")} // Driver Code let string = \"ishita bhuiya\"printInitials(string) // this code is contributed by shinjanpatra </script>",
"e": 7385,
"s": 6138,
"text": null
},
{
"code": null,
"e": 7395,
"s": 7385,
"text": "I. Bhuiya"
},
{
"code": null,
"e": 7403,
"s": 7395,
"text": "ankthon"
},
{
"code": null,
"e": 7415,
"s": 7403,
"text": "sanjeev2552"
},
{
"code": null,
"e": 7428,
"s": 7415,
"text": "shinjanpatra"
},
{
"code": null,
"e": 7447,
"s": 7428,
"text": "School Programming"
},
{
"code": null,
"e": 7455,
"s": 7447,
"text": "Strings"
},
{
"code": null,
"e": 7463,
"s": 7455,
"text": "Strings"
}
] |
Minimum Deletions | Practice | GeeksforGeeks | Given a string of S as input. Your task is to write a program to remove or delete the minimum number of characters from the string so that the resultant string is a palindrome.
Note: The order of characters in the string should be maintained.
Example 1:
Input: S = "aebcbda"
Output: 2
Explanation: Remove characters 'e'
and 'd'.
Example 2:
Input: S = "geeksforgeeks"
Output: 8
Explanation: One of the possible result
string can be "eefee", so answer is
13 - 5 = 8.
Your Task:
You don't need to read input or print anything. Your task is to complete the function minimumNumberOfDeletions() which takes the string S as inputs and returns the minimum number of deletions required to convert S into a pallindrome.
Expected Time Complexity: O(|S|2)
Expected Auxiliary Space: O(|S|2)
Constraints:
1 ≤ |S| ≤ 103
0
chessnoobdj3 days ago
C++ bottom-up
int minimumNumberOfDeletions(string S) {
int n = S.size();
int dp[n+1][n+1];
memset(dp, 0, sizeof(dp));
for(int i=0; i<=n; i++)
dp[i][i] = 1;
for(int i=0; i<n; i++){
for(int j=i-1; j>=0; j--){
dp[i][j] = max(dp[i-1][j], dp[i][j+1]);
if(S[i] == S[j])
dp[i][j] = max(dp[i][j], 2+dp[i-1][j+1]);
}
}
return n-dp[n-1][0];
}
0
dharpranoy22551 month ago
Python Solution: 0.77/1.22
class Solution: def delete(s,smap): if s==s[::-1]: return 0 if smap.get(s,-1)==-1: i,j=0,len(s)-1 while s[i]==s[j]: i+=1 j-=1 if s[i]!=s[j]: l=Solution.delete(s[i+1:j+1],smap) r=Solution.delete(s[i:j],smap) smap[s]=min(r,l)+1 return smap[s] def minimumNumberOfDeletions(self,S): smap={} return Solution.delete(S,smap)
0
patildhiren442 months ago
Java - Tabulation
static int lps(String s, String t, int n){
int[][] dp = new int[n+1][n+1];
for(int i=1; i<=n; i++){
for(int j=1; j<=n; j++){
if(s.charAt(i-1)==t.charAt(j-1)){
dp[i][j] = 1 + dp[i-1][j-1];
}else{
dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);
}
}
}
return dp[n][n];
}
static int minimumNumberOfDeletions(String s) {
//your code here
int n = s.length();
String t = new StringBuilder(s).reverse().toString();
return n - lps(s, t, n);
}
0
ameenul88083 months ago
Optimized DP solution (1-d space)
int minimumNumberOfDeletions(string s) {
// code here
string p = s;
int m = s.length();
reverse(s.begin(),s.end());
vector<int> prev(m+1,0);
for(int i=1;i<=m;i++){
vector<int> curr(m+1,0);
for(int j=1;j<=m;j++){
if(p[i-1]==s[j-1]) curr[j] = 1 + prev[j-1];
else curr[j] = max( prev[j], curr[j-1]);
}
prev = curr;
}
return m-prev[m];
}
0
pankajsinghrajput3 months ago
//SIMPLE DP SOL
class Solution{ int lcs(string s,string str) { int m=s.size(); int n=str.size(); int dp[m+1][n+1]; for(int i=0;i<m+1;i++) { for(int j=0;j<n+1;j++) { if(i==0||j==0) dp[i][j]=0; } } for(int i=1;i<m+1;i++) { for(int j=1;j<n+1;j++) { if(s[i-1]==str[j-1]) { dp[i][j]=1+dp[i-1][j-1]; } else { dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } return dp[m][n]; }
public: int minimumNumberOfDeletions(string S) { // code here string str=S; reverse(str.begin(),str.end()); int l=lcs(S,str); return S.size()-l; } };
0
geminicode4 months ago
my approach in python!!
def minimumNumberOfDeletions(self,S):
# code here
dp = [[0 for i in range(len(S))] for j in range(len(S))]
for g in range(len(S)):
for i,j in zip(range(0,len(S)-g),range(g,len(S))):
if g == 0 :
dp[i][j] = 0
elif g==1:
if S[i] == S[j] :
dp[i][j] = 0
else:
dp[i][j] = 1
else:
if S[i] == S[j]:
dp[i][j] = dp[i+1][j-1]
else:
dp[i][j] = 1 + min(dp[i+1][j],dp[i][j-1])
return dp[0][len(S)-1]
+2
jhav16434 months ago
C++ Top Down Approach in 0.0/1.1
int minimumNumberOfDeletions(string s) { string str = s; reverse(str.begin(), str.end()); int n = s.length(); int ans[n+1][n+1]; for(int i=0; i<=n; i++) { for(int j=0; j<=n; j++) { if(i==0 || j==0) { ans[i][j] = 0; } else if(s[i-1] == str[j-1]) { ans[i][j] = 1+ans[i-1][j-1]; } else { ans[i][j] = max(ans[i][j-1], ans[i-1][j]); } } } return n - ans[n][n]; }
0
sikkusaurav1235 months ago
/////////---------------top + down approch----------------//////////////
public: int minimumNumberOfDeletions(string s1) { string s2=s1; reverse(s2.begin(),s2.end()); int m=s1.length(); int n=s2.length(); int t[m+1][n+1]; for(int i=0;i<m+1;i++) { for(int j=0;j<n+1;j++) { if(i==0||j==0) { t[i][j]=0; } } } for(int i=1;i<m+1;i++) { for(int j=1;j<n+1;j++) { if(s1[i-1]==s2[j-1]) { t[i][j]=1+t[i-1][j-1]; } else { t[i][j]=max(t[i-1][j],t[i][j-1]); } } } return m-t[m][n]; }
0
bhargav_417 months ago
Java Solution | LCS Bottom-Up Approach
class Solution{
static int minimumNumberOfDeletions(String s1) {
int n = s1.length();
StringBuilder sb = new StringBuilder(s1);
sb.reverse();
String s2 = sb.toString();
int[][] dp = new int[n+1][n+1];
for(int i=0;i<n+1;i++){
for(int j=0;j<n+1;j++){
if(i==0 || j==0) dp[i][j] = 0;
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(s1.charAt(i-1)==s2.charAt(j-1)) dp[i][j] = 1+ dp[i-1][j-1];
else dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);
}
}
return n-dp[n][n];
}
}
0
s37randive8 months ago
int minimumNumberOfDeletions(string s) {
// code here
string t=string(s.rbegin(),s.rend());
int dp[s.length()+1][s.length()+1];
for(int i=0;i<s.length()+1;i++){
dp[i][0]=0;
}
for(int i=1;i<s.length()+1;i++){
dp[0][i]=0;
}
for(int i=1;i<s.length()+1;i++){
for(int j=1;j<s.length()+1;j++){
if(s[i-1]==t[j-1]){
dp[i][j]=1+dp[i-1][j-1];
}else{
dp[i][j]=max(dp[i-1][j],dp[i][j-1]);
}
}
}
return s.length()-dp[s.length()][s.length()];
}
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.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems 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": 481,
"s": 238,
"text": "Given a string of S as input. Your task is to write a program to remove or delete the minimum number of characters from the string so that the resultant string is a palindrome.\nNote: The order of characters in the string should be maintained."
},
{
"code": null,
"e": 492,
"s": 481,
"text": "Example 1:"
},
{
"code": null,
"e": 568,
"s": 492,
"text": "Input: S = \"aebcbda\"\nOutput: 2\nExplanation: Remove characters 'e' \nand 'd'."
},
{
"code": null,
"e": 579,
"s": 568,
"text": "Example 2:"
},
{
"code": null,
"e": 706,
"s": 579,
"text": "Input: S = \"geeksforgeeks\"\nOutput: 8\nExplanation: One of the possible result\nstring can be \"eefee\", so answer is \n13 - 5 = 8.\n"
},
{
"code": null,
"e": 1050,
"s": 706,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function minimumNumberOfDeletions() which takes the string S as inputs and returns the minimum number of deletions required to convert S into a pallindrome.\n\nExpected Time Complexity: O(|S|2)\nExpected Auxiliary Space: O(|S|2)\n\nConstraints:\n1 ≤ |S| ≤ 103"
},
{
"code": null,
"e": 1052,
"s": 1050,
"text": "0"
},
{
"code": null,
"e": 1074,
"s": 1052,
"text": "chessnoobdj3 days ago"
},
{
"code": null,
"e": 1088,
"s": 1074,
"text": "C++ bottom-up"
},
{
"code": null,
"e": 1557,
"s": 1088,
"text": "int minimumNumberOfDeletions(string S) { \n int n = S.size();\n int dp[n+1][n+1];\n memset(dp, 0, sizeof(dp));\n for(int i=0; i<=n; i++)\n dp[i][i] = 1;\n for(int i=0; i<n; i++){\n for(int j=i-1; j>=0; j--){\n dp[i][j] = max(dp[i-1][j], dp[i][j+1]);\n if(S[i] == S[j])\n dp[i][j] = max(dp[i][j], 2+dp[i-1][j+1]);\n }\n }\n return n-dp[n-1][0];\n } "
},
{
"code": null,
"e": 1559,
"s": 1557,
"text": "0"
},
{
"code": null,
"e": 1585,
"s": 1559,
"text": "dharpranoy22551 month ago"
},
{
"code": null,
"e": 1612,
"s": 1585,
"text": "Python Solution: 0.77/1.22"
},
{
"code": null,
"e": 2074,
"s": 1612,
"text": "class Solution: def delete(s,smap): if s==s[::-1]: return 0 if smap.get(s,-1)==-1: i,j=0,len(s)-1 while s[i]==s[j]: i+=1 j-=1 if s[i]!=s[j]: l=Solution.delete(s[i+1:j+1],smap) r=Solution.delete(s[i:j],smap) smap[s]=min(r,l)+1 return smap[s] def minimumNumberOfDeletions(self,S): smap={} return Solution.delete(S,smap)"
},
{
"code": null,
"e": 2076,
"s": 2074,
"text": "0"
},
{
"code": null,
"e": 2102,
"s": 2076,
"text": "patildhiren442 months ago"
},
{
"code": null,
"e": 2120,
"s": 2102,
"text": "Java - Tabulation"
},
{
"code": null,
"e": 2788,
"s": 2120,
"text": "static int lps(String s, String t, int n){\n int[][] dp = new int[n+1][n+1];\n \n for(int i=1; i<=n; i++){\n for(int j=1; j<=n; j++){\n \n if(s.charAt(i-1)==t.charAt(j-1)){\n dp[i][j] = 1 + dp[i-1][j-1];\n }else{\n dp[i][j] = Math.max(dp[i-1][j], dp[i][j-1]);\n }\n }\n }\n return dp[n][n];\n }\n \n static int minimumNumberOfDeletions(String s) {\n //your code here\n int n = s.length();\n \n String t = new StringBuilder(s).reverse().toString();\n \n return n - lps(s, t, n);\n }"
},
{
"code": null,
"e": 2790,
"s": 2788,
"text": "0"
},
{
"code": null,
"e": 2814,
"s": 2790,
"text": "ameenul88083 months ago"
},
{
"code": null,
"e": 2848,
"s": 2814,
"text": "Optimized DP solution (1-d space)"
},
{
"code": null,
"e": 3342,
"s": 2848,
"text": "int minimumNumberOfDeletions(string s) { \n // code here\n string p = s;\n int m = s.length();\n reverse(s.begin(),s.end());\n vector<int> prev(m+1,0);\n \n for(int i=1;i<=m;i++){\n vector<int> curr(m+1,0);\n for(int j=1;j<=m;j++){\n if(p[i-1]==s[j-1]) curr[j] = 1 + prev[j-1];\n else curr[j] = max( prev[j], curr[j-1]);\n }\n prev = curr;\n }\n return m-prev[m];\n } "
},
{
"code": null,
"e": 3344,
"s": 3342,
"text": "0"
},
{
"code": null,
"e": 3374,
"s": 3344,
"text": "pankajsinghrajput3 months ago"
},
{
"code": null,
"e": 3390,
"s": 3374,
"text": "//SIMPLE DP SOL"
},
{
"code": null,
"e": 4013,
"s": 3390,
"text": "class Solution{ int lcs(string s,string str) { int m=s.size(); int n=str.size(); int dp[m+1][n+1]; for(int i=0;i<m+1;i++) { for(int j=0;j<n+1;j++) { if(i==0||j==0) dp[i][j]=0; } } for(int i=1;i<m+1;i++) { for(int j=1;j<n+1;j++) { if(s[i-1]==str[j-1]) { dp[i][j]=1+dp[i-1][j-1]; } else { dp[i][j]=max(dp[i-1][j],dp[i][j-1]); } } } return dp[m][n]; }"
},
{
"code": null,
"e": 4201,
"s": 4015,
"text": " public: int minimumNumberOfDeletions(string S) { // code here string str=S; reverse(str.begin(),str.end()); int l=lcs(S,str); return S.size()-l; } };"
},
{
"code": null,
"e": 4205,
"s": 4203,
"text": "0"
},
{
"code": null,
"e": 4228,
"s": 4205,
"text": "geminicode4 months ago"
},
{
"code": null,
"e": 4252,
"s": 4228,
"text": "my approach in python!!"
},
{
"code": null,
"e": 4936,
"s": 4252,
"text": "def minimumNumberOfDeletions(self,S):\n # code here \n \n dp = [[0 for i in range(len(S))] for j in range(len(S))]\n for g in range(len(S)):\n for i,j in zip(range(0,len(S)-g),range(g,len(S))):\n if g == 0 :\n dp[i][j] = 0\n elif g==1:\n if S[i] == S[j] :\n dp[i][j] = 0\n else:\n dp[i][j] = 1\n else:\n if S[i] == S[j]:\n dp[i][j] = dp[i+1][j-1]\n else:\n dp[i][j] = 1 + min(dp[i+1][j],dp[i][j-1])\n return dp[0][len(S)-1]"
},
{
"code": null,
"e": 4939,
"s": 4936,
"text": "+2"
},
{
"code": null,
"e": 4960,
"s": 4939,
"text": "jhav16434 months ago"
},
{
"code": null,
"e": 4993,
"s": 4960,
"text": "C++ Top Down Approach in 0.0/1.1"
},
{
"code": null,
"e": 5677,
"s": 4993,
"text": "int minimumNumberOfDeletions(string s) { string str = s; reverse(str.begin(), str.end()); int n = s.length(); int ans[n+1][n+1]; for(int i=0; i<=n; i++) { for(int j=0; j<=n; j++) { if(i==0 || j==0) { ans[i][j] = 0; } else if(s[i-1] == str[j-1]) { ans[i][j] = 1+ans[i-1][j-1]; } else { ans[i][j] = max(ans[i][j-1], ans[i-1][j]); } } } return n - ans[n][n]; }"
},
{
"code": null,
"e": 5679,
"s": 5677,
"text": "0"
},
{
"code": null,
"e": 5706,
"s": 5679,
"text": "sikkusaurav1235 months ago"
},
{
"code": null,
"e": 5779,
"s": 5706,
"text": "/////////---------------top + down approch----------------//////////////"
},
{
"code": null,
"e": 6384,
"s": 5779,
"text": "public: int minimumNumberOfDeletions(string s1) { string s2=s1; reverse(s2.begin(),s2.end()); int m=s1.length(); int n=s2.length(); int t[m+1][n+1]; for(int i=0;i<m+1;i++) { for(int j=0;j<n+1;j++) { if(i==0||j==0) { t[i][j]=0; } } } for(int i=1;i<m+1;i++) { for(int j=1;j<n+1;j++) { if(s1[i-1]==s2[j-1]) { t[i][j]=1+t[i-1][j-1]; } else { t[i][j]=max(t[i-1][j],t[i][j-1]); } } } return m-t[m][n]; } "
},
{
"code": null,
"e": 6386,
"s": 6384,
"text": "0"
},
{
"code": null,
"e": 6409,
"s": 6386,
"text": "bhargav_417 months ago"
},
{
"code": null,
"e": 6448,
"s": 6409,
"text": "Java Solution | LCS Bottom-Up Approach"
},
{
"code": null,
"e": 7103,
"s": 6450,
"text": "class Solution{\n static int minimumNumberOfDeletions(String s1) {\n int n = s1.length();\n StringBuilder sb = new StringBuilder(s1);\n sb.reverse();\n String s2 = sb.toString();\n int[][] dp = new int[n+1][n+1];\n for(int i=0;i<n+1;i++){\n for(int j=0;j<n+1;j++){\n if(i==0 || j==0) dp[i][j] = 0;\n }\n }\n for(int i=1;i<=n;i++){\n for(int j=1;j<=n;j++){\n if(s1.charAt(i-1)==s2.charAt(j-1)) dp[i][j] = 1+ dp[i-1][j-1];\n else dp[i][j] = Math.max(dp[i-1][j],dp[i][j-1]);\n }\n }\n return n-dp[n][n];\n }\n}"
},
{
"code": null,
"e": 7105,
"s": 7103,
"text": "0"
},
{
"code": null,
"e": 7128,
"s": 7105,
"text": "s37randive8 months ago"
},
{
"code": null,
"e": 7761,
"s": 7128,
"text": "int minimumNumberOfDeletions(string s) { \n // code here\n string t=string(s.rbegin(),s.rend());\n int dp[s.length()+1][s.length()+1];\n for(int i=0;i<s.length()+1;i++){\n dp[i][0]=0;\n }\n for(int i=1;i<s.length()+1;i++){\n dp[0][i]=0;\n }\n for(int i=1;i<s.length()+1;i++){\n for(int j=1;j<s.length()+1;j++){\n if(s[i-1]==t[j-1]){\n dp[i][j]=1+dp[i-1][j-1];\n }else{\n dp[i][j]=max(dp[i-1][j],dp[i][j-1]);\n }\n }\n }\n return s.length()-dp[s.length()][s.length()];\n } "
},
{
"code": null,
"e": 7907,
"s": 7761,
"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": 7943,
"s": 7907,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7953,
"s": 7943,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7963,
"s": 7953,
"text": "\nContest\n"
},
{
"code": null,
"e": 8026,
"s": 7963,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8211,
"s": 8026,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 8495,
"s": 8211,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 8641,
"s": 8495,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 8718,
"s": 8641,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 8759,
"s": 8718,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 8787,
"s": 8759,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 8858,
"s": 8787,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 9045,
"s": 8858,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
PyQtGraph – Setting Background of Plot Window | 24 Sep, 2020
In this article we will see how we can set the background of the plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).Plot windows consist of two main parts: the Plot Panel containing the actual plotted graphics and the Control Panel. By default PyQtGraph plot window color is black although we can change this any time, it background is set to the None it become transparent.
We can create a plot window with the help of command given below
# creating a pyqtgraph plot window
window = pg.plot()
In order to do this we use setBackground method with the plot window object
Syntax : window.setBackground(background)
Argument : It takes string as argument
Return : It returns None
Below is the implementation
# importing pyqtgraph as pgimport pyqtgraph as pg # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui # importing numpy as npimport numpy as np import time # creating a pyqtgraph plot windowwindow = pg.plot() # titletitle = "GeeksforGeeks PyQtGraph" # setting window titlewindow.setWindowTitle(title) # create list for y-axisy1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2] # create horizontal list i.e x-axisx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # create pyqt5graph bar graph item # with width = 0.6# with bar colors = greenbargraph1 = pg.BarGraphItem(x = x, height = y1, width = 0.6, brush ='g') # add item to plot window# adding bargraph item to the windowwindow.addItem(bargraph1) # setting plot window background color to yellowwindow.setBackground('y') # main methodif __name__ == '__main__': # importing system import sys # Start Qt event loop unless running in interactive mode or using if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_()
Output :
Python-gui
Python-PyQtGraph
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Sep, 2020"
},
{
"code": null,
"e": 766,
"s": 28,
"text": "In this article we will see how we can set the background of the plot window in the PyQtGraph module. PyQtGraph is a graphics and user interface library for Python that provides functionality commonly required in designing and science applications. Its primary goals are to provide fast, interactive graphics for displaying data (plots, video, etc.) and second is to provide tools to aid in rapid application development (for example, property trees such as used in Qt Designer).Plot windows consist of two main parts: the Plot Panel containing the actual plotted graphics and the Control Panel. By default PyQtGraph plot window color is black although we can change this any time, it background is set to the None it become transparent."
},
{
"code": null,
"e": 831,
"s": 766,
"text": "We can create a plot window with the help of command given below"
},
{
"code": null,
"e": 886,
"s": 831,
"text": "# creating a pyqtgraph plot window\nwindow = pg.plot()\n"
},
{
"code": null,
"e": 962,
"s": 886,
"text": "In order to do this we use setBackground method with the plot window object"
},
{
"code": null,
"e": 1004,
"s": 962,
"text": "Syntax : window.setBackground(background)"
},
{
"code": null,
"e": 1043,
"s": 1004,
"text": "Argument : It takes string as argument"
},
{
"code": null,
"e": 1068,
"s": 1043,
"text": "Return : It returns None"
},
{
"code": null,
"e": 1096,
"s": 1068,
"text": "Below is the implementation"
},
{
"code": "# importing pyqtgraph as pgimport pyqtgraph as pg # importing QtCore and QtGui from the pyqtgraph modulefrom pyqtgraph.Qt import QtCore, QtGui # importing numpy as npimport numpy as np import time # creating a pyqtgraph plot windowwindow = pg.plot() # titletitle = \"GeeksforGeeks PyQtGraph\" # setting window titlewindow.setWindowTitle(title) # create list for y-axisy1 = [5, 5, 7, 10, 3, 8, 9, 1, 6, 2] # create horizontal list i.e x-axisx = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] # create pyqt5graph bar graph item # with width = 0.6# with bar colors = greenbargraph1 = pg.BarGraphItem(x = x, height = y1, width = 0.6, brush ='g') # add item to plot window# adding bargraph item to the windowwindow.addItem(bargraph1) # setting plot window background color to yellowwindow.setBackground('y') # main methodif __name__ == '__main__': # importing system import sys # Start Qt event loop unless running in interactive mode or using if (sys.flags.interactive != 1) or not hasattr(QtCore, 'PYQT_VERSION'): QtGui.QApplication.instance().exec_() ",
"e": 2191,
"s": 1096,
"text": null
},
{
"code": null,
"e": 2200,
"s": 2191,
"text": "Output :"
},
{
"code": null,
"e": 2211,
"s": 2200,
"text": "Python-gui"
},
{
"code": null,
"e": 2228,
"s": 2211,
"text": "Python-PyQtGraph"
},
{
"code": null,
"e": 2235,
"s": 2228,
"text": "Python"
}
] |
HackingTool – ALL IN ONE Hacking Tool For Hackers | 22 Nov, 2021
HackingTool is a free and open-source tool available on GitHub. HackingTool is used as an information-gathering tool. HackingTool is used to scan websites for information gathering and find vulnerabilities in websites and webapps. HackingTool is one of the easiest and useful tool for performing reconnaissance on websites and web apps. The HackingTool tool is also available for Linux, window, and android phones ( termux ) that is coded in both bash and python language. HackingTool interface is very similar to Metasploit 1 and Metasploit. HackingTool provides command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain). We can target any domain using Fsociety. The interactive console provides a number of helpful features, such as command completion and contextual help. This tool is written in python language. You must have Python language installed in your kali Linux to use this tool. HackingTool is Penetration Testing Framework. HackingTool is a complete framework of tools of hacking. This is very useful when you get all the tools in a single framework.
Step 1: Use the following command to install the tool from GitHub. Use the second command to move into the directory of the tool.
git clone https://github.com/Z4nzu/hackingtool.git chmod -R 755 hackingtool && cd hackingtool
Step 2: Now you are in the directory of the tool. Use the following command to install dependencies of the tool.
sudo pip3 install -r requirement.txt
Step 3: All the dependencies of the tool have been installed. Now use the following command to run the tool.
sudo hackingtool
The framework has been installed successfully. Now we will see how to install a tool from the framework.
choose option 1
1
Now choose any tool from this framework. Select IP for scanning
2
The tool is running successfully. Similarly, you can use any tool from framework.
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 1183,
"s": 52,
"text": "HackingTool is a free and open-source tool available on GitHub. HackingTool is used as an information-gathering tool. HackingTool is used to scan websites for information gathering and find vulnerabilities in websites and webapps. HackingTool is one of the easiest and useful tool for performing reconnaissance on websites and web apps. The HackingTool tool is also available for Linux, window, and android phones ( termux ) that is coded in both bash and python language. HackingTool interface is very similar to Metasploit 1 and Metasploit. HackingTool provides command-line interface that you can run on Kali Linux. This tool can be used to get information about our target(domain). We can target any domain using Fsociety. The interactive console provides a number of helpful features, such as command completion and contextual help. This tool is written in python language. You must have Python language installed in your kali Linux to use this tool. HackingTool is Penetration Testing Framework. HackingTool is a complete framework of tools of hacking. This is very useful when you get all the tools in a single framework."
},
{
"code": null,
"e": 1313,
"s": 1183,
"text": "Step 1: Use the following command to install the tool from GitHub. Use the second command to move into the directory of the tool."
},
{
"code": null,
"e": 1407,
"s": 1313,
"text": "git clone https://github.com/Z4nzu/hackingtool.git chmod -R 755 hackingtool && cd hackingtool"
},
{
"code": null,
"e": 1520,
"s": 1407,
"text": "Step 2: Now you are in the directory of the tool. Use the following command to install dependencies of the tool."
},
{
"code": null,
"e": 1557,
"s": 1520,
"text": "sudo pip3 install -r requirement.txt"
},
{
"code": null,
"e": 1666,
"s": 1557,
"text": "Step 3: All the dependencies of the tool have been installed. Now use the following command to run the tool."
},
{
"code": null,
"e": 1683,
"s": 1666,
"text": "sudo hackingtool"
},
{
"code": null,
"e": 1788,
"s": 1683,
"text": "The framework has been installed successfully. Now we will see how to install a tool from the framework."
},
{
"code": null,
"e": 1804,
"s": 1788,
"text": "choose option 1"
},
{
"code": null,
"e": 1806,
"s": 1804,
"text": "1"
},
{
"code": null,
"e": 1870,
"s": 1806,
"text": "Now choose any tool from this framework. Select IP for scanning"
},
{
"code": null,
"e": 1872,
"s": 1870,
"text": "2"
},
{
"code": null,
"e": 1954,
"s": 1872,
"text": "The tool is running successfully. Similarly, you can use any tool from framework."
},
{
"code": null,
"e": 1965,
"s": 1954,
"text": "Kali-Linux"
},
{
"code": null,
"e": 1977,
"s": 1965,
"text": "Linux-Tools"
},
{
"code": null,
"e": 1988,
"s": 1977,
"text": "Linux-Unix"
}
] |
MySQL | SHA1( ) Function | 17 Feb, 2021
The MySQL SHA1() function is used for encrypting a string using the SHA-1 technique. The SHA1 stands for secure hash algorithm and it produces a 160-bit checksum for a user inputted string.
The MySQL SHA1() function returns NULL if the string passed as an argument is a NULL string. The SHA1() function accepts one parameter which is the string to be encrypted.
Syntax:
SHA1(string)
Parameters Used:
string – It is used to specify the plain text string that is to be encrypted.
Return Value: The SHA1() function in MySQL returns the encrypted string or NULL if the string passed is an empty string.
Supported Versions of MySQL:
MySQL 5.7
MySQL 5.6
MySQL 5.5
MySQL 5.1
MySQL 5.0
MySQL 4.1
Example-1: Implementing SHA1() function on a string.
SELECT
SHA1('geeksforgeeks');
Output:
69c9a5c19c5c27e43cb0efc4c8644ed6d03a110b
Example-2: Implementing SHA1() function on a string which has a combination of characters and integers.
SELECT
SHA1('geeksforgeeks123');
Output:
53ce00666cbef425ab8d06ed652095bea20a1616
Example-3: Implementing SHA1() function on a NULL string and returning the length of the string after compression.
SELECT
SHA1(NULL);
Output:
NULL
simranarora5sos
mysql
SQLmysql
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Feb, 2021"
},
{
"code": null,
"e": 219,
"s": 28,
"text": "The MySQL SHA1() function is used for encrypting a string using the SHA-1 technique. The SHA1 stands for secure hash algorithm and it produces a 160-bit checksum for a user inputted string. "
},
{
"code": null,
"e": 392,
"s": 219,
"text": "The MySQL SHA1() function returns NULL if the string passed as an argument is a NULL string. The SHA1() function accepts one parameter which is the string to be encrypted. "
},
{
"code": null,
"e": 402,
"s": 392,
"text": "Syntax: "
},
{
"code": null,
"e": 415,
"s": 402,
"text": "SHA1(string)"
},
{
"code": null,
"e": 433,
"s": 415,
"text": "Parameters Used: "
},
{
"code": null,
"e": 512,
"s": 433,
"text": "string – It is used to specify the plain text string that is to be encrypted. "
},
{
"code": null,
"e": 634,
"s": 512,
"text": "Return Value: The SHA1() function in MySQL returns the encrypted string or NULL if the string passed is an empty string. "
},
{
"code": null,
"e": 664,
"s": 634,
"text": "Supported Versions of MySQL: "
},
{
"code": null,
"e": 676,
"s": 666,
"text": "MySQL 5.7"
},
{
"code": null,
"e": 686,
"s": 676,
"text": "MySQL 5.6"
},
{
"code": null,
"e": 696,
"s": 686,
"text": "MySQL 5.5"
},
{
"code": null,
"e": 706,
"s": 696,
"text": "MySQL 5.1"
},
{
"code": null,
"e": 716,
"s": 706,
"text": "MySQL 5.0"
},
{
"code": null,
"e": 726,
"s": 716,
"text": "MySQL 4.1"
},
{
"code": null,
"e": 781,
"s": 726,
"text": "Example-1: Implementing SHA1() function on a string. "
},
{
"code": null,
"e": 814,
"s": 781,
"text": "SELECT \nSHA1('geeksforgeeks'); "
},
{
"code": null,
"e": 824,
"s": 814,
"text": "Output: "
},
{
"code": null,
"e": 866,
"s": 824,
"text": "69c9a5c19c5c27e43cb0efc4c8644ed6d03a110b "
},
{
"code": null,
"e": 972,
"s": 866,
"text": "Example-2: Implementing SHA1() function on a string which has a combination of characters and integers. "
},
{
"code": null,
"e": 1007,
"s": 972,
"text": "SELECT \nSHA1('geeksforgeeks123'); "
},
{
"code": null,
"e": 1017,
"s": 1007,
"text": "Output: "
},
{
"code": null,
"e": 1059,
"s": 1017,
"text": "53ce00666cbef425ab8d06ed652095bea20a1616 "
},
{
"code": null,
"e": 1176,
"s": 1059,
"text": "Example-3: Implementing SHA1() function on a NULL string and returning the length of the string after compression. "
},
{
"code": null,
"e": 1198,
"s": 1176,
"text": "SELECT \nSHA1(NULL); "
},
{
"code": null,
"e": 1208,
"s": 1198,
"text": "Output: "
},
{
"code": null,
"e": 1214,
"s": 1208,
"text": "NULL "
},
{
"code": null,
"e": 1232,
"s": 1216,
"text": "simranarora5sos"
},
{
"code": null,
"e": 1238,
"s": 1232,
"text": "mysql"
},
{
"code": null,
"e": 1247,
"s": 1238,
"text": "SQLmysql"
},
{
"code": null,
"e": 1251,
"s": 1247,
"text": "SQL"
},
{
"code": null,
"e": 1255,
"s": 1251,
"text": "SQL"
}
] |
Inorder traversal of an N-ary Tree | 12 Oct, 2021
Given an N-ary tree containing, the task is to print the inorder traversal of the tree.
Examples:
Input: N = 3
Output: 5 6 2 7 3 1 4Input: N = 3
Output: 2 5 3 1 4 6
Approach: The inorder traversal of an N-ary tree is defined as visiting all the children except the last then the root and finally the last child recursively.
Recursively visit the first child.
Recursively visit the second child.
.....
Recursively visit the second last child.
Print the data in the node.
Recursively visit the last child.
Repeat the above steps till all the nodes are visited.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Class for the node of the treestruct Node{ int data; // List of children struct Node **children; int length; Node() { length = 0; data = 0; } Node(int n, int data_) { children = new Node*(); length = n; data = data_; }}; // Function to print the inorder traversal// of the n-ary treevoid inorder(Node *node){ if (node == NULL) return; // Total children count int total = node->length; // All the children except the last for (int i = 0; i < total - 1; i++) inorder(node->children[i]); // Print the current node's data cout<< node->data << " "; // Last child inorder(node->children[total - 1]);} // Driver codeint main(){ /* Create the following tree 1 / | \ 2 3 4 / | \ 5 6 7 */ int n = 3; Node* root = new Node(n, 1); root->children[0] = new Node(n, 2); root->children[1] = new Node(n, 3); root->children[2] = new Node(n, 4); root->children[0]->children[0] = new Node(n, 5); root->children[0]->children[1] = new Node(n, 6); root->children[0]->children[2] = new Node(n, 7); inorder(root); return 0;} // This code is Contributed by Arnab Kundu
// Java implementation of the approachclass GFG { // Class for the node of the tree static class Node { int data; // List of children Node children[]; Node(int n, int data) { children = new Node[n]; this.data = data; } } // Function to print the inorder traversal // of the n-ary tree static void inorder(Node node) { if (node == null) return; // Total children count int total = node.children.length; // All the children except the last for (int i = 0; i < total - 1; i++) inorder(node.children[i]); // Print the current node's data System.out.print("" + node.data + " "); // Last child inorder(node.children[total - 1]); } // Driver code public static void main(String[] args) { /* Create the following tree 1 / | \ 2 3 4 / | \ 5 6 7 */ int n = 3; Node root = new Node(n, 1); root.children[0] = new Node(n, 2); root.children[1] = new Node(n, 3); root.children[2] = new Node(n, 4); root.children[0].children[0] = new Node(n, 5); root.children[0].children[1] = new Node(n, 6); root.children[0].children[2] = new Node(n, 7); inorder(root); }}
# Python3 implementation of the approachclass GFG: # Class for the node of the tree class Node: def __init__(self,n,data): # List of children self.children = [None]*n self.data = data # Function to print the inorder traversal # of the n-ary tree def inorder(self, node): if node == None: return # Total children count total = len(node.children) # All the children except the last for i in range(total-1): self.inorder(node.children[i]) # Print the current node's data print(node.data,end=" ") # Last child self.inorder(node.children[total-1]) # Driver code def main(self): # Create the following tree # 1 # / | \ # 2 3 4 # / | \ # 5 6 7 n = 3 root = self.Node(n, 1) root.children[0] = self.Node(n, 2) root.children[1] = self.Node(n, 3) root.children[2] = self.Node(n, 4) root.children[0].children[0] = self.Node(n, 5) root.children[0].children[1] = self.Node(n, 6) root.children[0].children[2] = self.Node(n, 7) self.inorder(root) ob = GFG() # Create class objectob.main() # Call main function # This code is contributed by Shivam Singh
// C# implementation of the approachusing System; class GFG{ // Class for the node of the tree public class Node { public int data; // List of children public Node []children; public Node(int n, int data) { children = new Node[n]; this.data = data; } } // Function to print the inorder traversal // of the n-ary tree static void inorder(Node node) { if (node == null) return; // Total children count int total = node.children.Length; // All the children except the last for (int i = 0; i < total - 1; i++) inorder(node.children[i]); // Print the current node's data Console.Write("" + node.data + " "); // Last child inorder(node.children[total - 1]); } // Driver code public static void Main() { /* Create the following tree 1 / | \ 2 3 4 / | \ 5 6 7 */ int n = 3; Node root = new Node(n, 1); root.children[0] = new Node(n, 2); root.children[1] = new Node(n, 3); root.children[2] = new Node(n, 4); root.children[0].children[0] = new Node(n, 5); root.children[0].children[1] = new Node(n, 6); root.children[0].children[2] = new Node(n, 7); inorder(root); }} // This code is contributed by AnkitRai01
<script> // JavaScript implementation of the approach// Class for the node of the treeclass Node{ constructor(n, data) { this.data = data; this.children = Array(n); }}// Function to print the inorder traversal// of the n-ary treefunction inorder(node){ if (node == null) return; // Total children count var total = node.children.length; // All the children except the last for (var i = 0; i < total - 1; i++) inorder(node.children[i]); // Print the current node's data document.write("" + node.data + " "); // Last child inorder(node.children[total - 1]);} // Driver code/* Create the following tree 1 / | \ 2 3 4 / | \ 5 6 7*/var n = 3;var root = new Node(n, 1);root.children[0] = new Node(n, 2);root.children[1] = new Node(n, 3);root.children[2] = new Node(n, 4);root.children[0].children[0] = new Node(n, 5);root.children[0].children[1] = new Node(n, 6);root.children[0].children[2] = new Node(n, 7);inorder(root); </script>
5 6 2 7 3 1 4
Time Complexity: O(n)
Space Complexity: O(n)
ankthon
andrew1234
SHIVAMSINGH67
user_pbdh
itsok
ashutoshsinghgeeksforgeeks
suryadeepartist
Inorder Traversal
n-ary-tree
Data Structures
Tree
Data Structures
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Oct, 2021"
},
{
"code": null,
"e": 142,
"s": 54,
"text": "Given an N-ary tree containing, the task is to print the inorder traversal of the tree."
},
{
"code": null,
"e": 153,
"s": 142,
"text": "Examples: "
},
{
"code": null,
"e": 168,
"s": 153,
"text": "Input: N = 3 "
},
{
"code": null,
"e": 204,
"s": 168,
"text": "Output: 5 6 2 7 3 1 4Input: N = 3 "
},
{
"code": null,
"e": 225,
"s": 204,
"text": "Output: 2 5 3 1 4 6 "
},
{
"code": null,
"e": 385,
"s": 225,
"text": "Approach: The inorder traversal of an N-ary tree is defined as visiting all the children except the last then the root and finally the last child recursively. "
},
{
"code": null,
"e": 420,
"s": 385,
"text": "Recursively visit the first child."
},
{
"code": null,
"e": 456,
"s": 420,
"text": "Recursively visit the second child."
},
{
"code": null,
"e": 462,
"s": 456,
"text": "....."
},
{
"code": null,
"e": 503,
"s": 462,
"text": "Recursively visit the second last child."
},
{
"code": null,
"e": 531,
"s": 503,
"text": "Print the data in the node."
},
{
"code": null,
"e": 565,
"s": 531,
"text": "Recursively visit the last child."
},
{
"code": null,
"e": 620,
"s": 565,
"text": "Repeat the above steps till all the nodes are visited."
},
{
"code": null,
"e": 673,
"s": 620,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 677,
"s": 673,
"text": "C++"
},
{
"code": null,
"e": 682,
"s": 677,
"text": "Java"
},
{
"code": null,
"e": 690,
"s": 682,
"text": "Python3"
},
{
"code": null,
"e": 693,
"s": 690,
"text": "C#"
},
{
"code": null,
"e": 704,
"s": 693,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Class for the node of the treestruct Node{ int data; // List of children struct Node **children; int length; Node() { length = 0; data = 0; } Node(int n, int data_) { children = new Node*(); length = n; data = data_; }}; // Function to print the inorder traversal// of the n-ary treevoid inorder(Node *node){ if (node == NULL) return; // Total children count int total = node->length; // All the children except the last for (int i = 0; i < total - 1; i++) inorder(node->children[i]); // Print the current node's data cout<< node->data << \" \"; // Last child inorder(node->children[total - 1]);} // Driver codeint main(){ /* Create the following tree 1 / | \\ 2 3 4 / | \\ 5 6 7 */ int n = 3; Node* root = new Node(n, 1); root->children[0] = new Node(n, 2); root->children[1] = new Node(n, 3); root->children[2] = new Node(n, 4); root->children[0]->children[0] = new Node(n, 5); root->children[0]->children[1] = new Node(n, 6); root->children[0]->children[2] = new Node(n, 7); inorder(root); return 0;} // This code is Contributed by Arnab Kundu",
"e": 2032,
"s": 704,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG { // Class for the node of the tree static class Node { int data; // List of children Node children[]; Node(int n, int data) { children = new Node[n]; this.data = data; } } // Function to print the inorder traversal // of the n-ary tree static void inorder(Node node) { if (node == null) return; // Total children count int total = node.children.length; // All the children except the last for (int i = 0; i < total - 1; i++) inorder(node.children[i]); // Print the current node's data System.out.print(\"\" + node.data + \" \"); // Last child inorder(node.children[total - 1]); } // Driver code public static void main(String[] args) { /* Create the following tree 1 / | \\ 2 3 4 / | \\ 5 6 7 */ int n = 3; Node root = new Node(n, 1); root.children[0] = new Node(n, 2); root.children[1] = new Node(n, 3); root.children[2] = new Node(n, 4); root.children[0].children[0] = new Node(n, 5); root.children[0].children[1] = new Node(n, 6); root.children[0].children[2] = new Node(n, 7); inorder(root); }}",
"e": 3424,
"s": 2032,
"text": null
},
{
"code": "# Python3 implementation of the approachclass GFG: # Class for the node of the tree class Node: def __init__(self,n,data): # List of children self.children = [None]*n self.data = data # Function to print the inorder traversal # of the n-ary tree def inorder(self, node): if node == None: return # Total children count total = len(node.children) # All the children except the last for i in range(total-1): self.inorder(node.children[i]) # Print the current node's data print(node.data,end=\" \") # Last child self.inorder(node.children[total-1]) # Driver code def main(self): # Create the following tree # 1 # / | \\ # 2 3 4 # / | \\ # 5 6 7 n = 3 root = self.Node(n, 1) root.children[0] = self.Node(n, 2) root.children[1] = self.Node(n, 3) root.children[2] = self.Node(n, 4) root.children[0].children[0] = self.Node(n, 5) root.children[0].children[1] = self.Node(n, 6) root.children[0].children[2] = self.Node(n, 7) self.inorder(root) ob = GFG() # Create class objectob.main() # Call main function # This code is contributed by Shivam Singh",
"e": 4823,
"s": 3424,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Class for the node of the tree public class Node { public int data; // List of children public Node []children; public Node(int n, int data) { children = new Node[n]; this.data = data; } } // Function to print the inorder traversal // of the n-ary tree static void inorder(Node node) { if (node == null) return; // Total children count int total = node.children.Length; // All the children except the last for (int i = 0; i < total - 1; i++) inorder(node.children[i]); // Print the current node's data Console.Write(\"\" + node.data + \" \"); // Last child inorder(node.children[total - 1]); } // Driver code public static void Main() { /* Create the following tree 1 / | \\ 2 3 4 / | \\ 5 6 7 */ int n = 3; Node root = new Node(n, 1); root.children[0] = new Node(n, 2); root.children[1] = new Node(n, 3); root.children[2] = new Node(n, 4); root.children[0].children[0] = new Node(n, 5); root.children[0].children[1] = new Node(n, 6); root.children[0].children[2] = new Node(n, 7); inorder(root); }} // This code is contributed by AnkitRai01",
"e": 6270,
"s": 4823,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach// Class for the node of the treeclass Node{ constructor(n, data) { this.data = data; this.children = Array(n); }}// Function to print the inorder traversal// of the n-ary treefunction inorder(node){ if (node == null) return; // Total children count var total = node.children.length; // All the children except the last for (var i = 0; i < total - 1; i++) inorder(node.children[i]); // Print the current node's data document.write(\"\" + node.data + \" \"); // Last child inorder(node.children[total - 1]);} // Driver code/* Create the following tree 1 / | \\ 2 3 4 / | \\ 5 6 7*/var n = 3;var root = new Node(n, 1);root.children[0] = new Node(n, 2);root.children[1] = new Node(n, 3);root.children[2] = new Node(n, 4);root.children[0].children[0] = new Node(n, 5);root.children[0].children[1] = new Node(n, 6);root.children[0].children[2] = new Node(n, 7);inorder(root); </script>",
"e": 7292,
"s": 6270,
"text": null
},
{
"code": null,
"e": 7307,
"s": 7292,
"text": "5 6 2 7 3 1 4 "
},
{
"code": null,
"e": 7330,
"s": 7307,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 7354,
"s": 7330,
"text": "Space Complexity: O(n)"
},
{
"code": null,
"e": 7362,
"s": 7354,
"text": "ankthon"
},
{
"code": null,
"e": 7373,
"s": 7362,
"text": "andrew1234"
},
{
"code": null,
"e": 7387,
"s": 7373,
"text": "SHIVAMSINGH67"
},
{
"code": null,
"e": 7397,
"s": 7387,
"text": "user_pbdh"
},
{
"code": null,
"e": 7403,
"s": 7397,
"text": "itsok"
},
{
"code": null,
"e": 7430,
"s": 7403,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 7446,
"s": 7430,
"text": "suryadeepartist"
},
{
"code": null,
"e": 7464,
"s": 7446,
"text": "Inorder Traversal"
},
{
"code": null,
"e": 7475,
"s": 7464,
"text": "n-ary-tree"
},
{
"code": null,
"e": 7491,
"s": 7475,
"text": "Data Structures"
},
{
"code": null,
"e": 7496,
"s": 7491,
"text": "Tree"
},
{
"code": null,
"e": 7512,
"s": 7496,
"text": "Data Structures"
},
{
"code": null,
"e": 7517,
"s": 7512,
"text": "Tree"
}
] |
Sub-tree with minimum color difference in a 2-coloured tree | 30 Aug, 2021
A tree with N nodes and N-1 edges is given with 2 different colours for its nodes. Find the sub-tree with minimum colour difference i.e. abs(1-colour nodes – 2-colour nodes) is minimum. Examples:
Input :
Edges : 1 2
1 3
2 4
3 5
Colours : 1 1 2 2 1 [1-based indexing where
index denotes the node]
Output : 2
Explanation : The sub-tree {1-2} and {1-2-3-5}
have color difference of 2. Sub-tree {1-2} has two
1-colour nodes and zero 2-colour nodes. So, color
difference is 2. Sub-tree {1-2-3-5} has three 1-colour
nodes and one 2-colour nodes. So color diff = 2.
Method 1 : The problem can be solved by checking every possible sub-tree from every node of the tree. This will take exponential time as we will check for sub-trees from every node.Method 2 : (Efficient) If we observe, we are solving a portion of the tree several times. This produces recurring sub-problems. We can use Dynamic Programming approach to get the minimum color difference in one traversal. To make things simpler, we can have color values as 1 and -1. Now, if we have a sub-tree with both colored nodes equal, our sum of colors will be 0. To get the minimum difference, we should have maximum negative sum or maximum positive sum.
Case 1 When we need to have a sub-tree with maximum sum : We take a node if its value > 0, i.e. sum(parent) += max(0, sum(child))
Case 2 When we need to have a sub-tree with minimum sum(or max negative sum) : We take a node if its value < 0, i.e. sum(parent) += min(0, sum(child))
To get the minimum sum, we can interchange the colors of nodes, i.e. -1 becomes 1 and vice-versa.Below is the implementation :
C++
Java
Python3
C#
Javascript
// CPP code to find the sub-tree with minimum color// difference in a 2-coloured tree#include <bits/stdc++.h>using namespace std; // Tree traversal to compute minimum differencevoid dfs(int node, int parent, vector<int> tree[], int colour[], int answer[]){ // Initial min difference is the color of node answer[node] = colour[node]; // Traversing its children for (auto u : tree[node]) { // Not traversing the parent if (u == parent) continue; dfs(u, node, tree, colour, answer); // If the child is adding positively to // difference, we include it in the answer // Otherwise, we leave the sub-tree and // include 0 (nothing) in the answer answer[node] += max(answer[u], 0); }} int maxDiff(vector<int> tree[], int colour[], int N){ int answer[N + 1]; memset(answer, 0, sizeof(answer)); // DFS for colour difference : 1colour - 2colour dfs(1, 0, tree, colour, answer); // Minimum colour difference is maximum answer value int high = 0; for (int i = 1; i <= N; i++) { high = max(high, answer[i]); // Clearing the current value // to check for colour2 as well answer[i] = 0; } // Interchanging the colours for (int i = 1; i <= N; i++) { if (colour[i] == -1) colour[i] = 1; else colour[i] = -1; } // DFS for colour difference : 2colour - 1colour dfs(1, 0, tree, colour, answer); // Checking if colour2 makes the minimum colour // difference for (int i = 1; i < N; i++) high = max(high, answer[i]); return high;} // Driver codeint main(){ // Nodes int N = 5; // Adjacency list representation vector<int> tree[N + 1]; // Edges tree[1].push_back(2); tree[2].push_back(1); tree[1].push_back(3); tree[3].push_back(1); tree[2].push_back(4); tree[4].push_back(2); tree[3].push_back(5); tree[5].push_back(3); // Index represent the colour of that node // There is no Node 0, so we start from // index 1 to N int colour[] = { 0, 1, 1, -1, -1, 1 }; // Printing the result cout << maxDiff(tree, colour, N); return 0;}
// Java code to find the sub-tree// with minimum color difference// in a 2-coloured treeimport java.util.*;class GFG{ // Tree traversal to compute minimum differencestatic void dfs(int node, int parent, Vector<Integer> tree[], int colour[], int answer[]){ // Initial min difference is // the color of node answer[node] = colour[node]; // Traversing its children for (Integer u : tree[node]) { // Not traversing the parent if (u == parent) continue; dfs(u, node, tree, colour, answer); // If the child is adding positively to // difference, we include it in the answer // Otherwise, we leave the sub-tree and // include 0 (nothing) in the answer answer[node] += Math.max(answer[u], 0); }} static int maxDiff(Vector<Integer> tree[], int colour[], int N){ int []answer = new int[N + 1]; // DFS for colour difference : 1colour - 2colour dfs(1, 0, tree, colour, answer); // Minimum colour difference is // maximum answer value int high = 0; for (int i = 1; i <= N; i++) { high = Math.max(high, answer[i]); // Clearing the current value // to check for colour2 as well answer[i] = 0; } // Interchanging the colours for (int i = 1; i <= N; i++) { if (colour[i] == -1) colour[i] = 1; else colour[i] = -1; } // DFS for colour difference : 2colour - 1colour dfs(1, 0, tree, colour, answer); // Checking if colour2 makes the // minimum colour difference for (int i = 1; i < N; i++) high = Math.max(high, answer[i]); return high;} // Driver codepublic static void main(String []args){ // Nodes int N = 5; // Adjacency list representation Vector<Integer> tree[] = new Vector[N + 1]; for(int i = 0; i < N + 1; i++) tree[i] = new Vector<Integer>(); // Edges tree[1].add(2); tree[2].add(1); tree[1].add(3); tree[3].add(1); tree[2].add(4); tree[4].add(2); tree[3].add(5); tree[5].add(3); // Index represent the colour of that node // There is no Node 0, so we start from // index 1 to N int colour[] = { 0, 1, 1, -1, -1, 1 }; // Printing the result System.out.println(maxDiff(tree, colour, N));}} // This code is contributed by 29AjayKumar
# Python3 code to find the sub-tree# with minimum color difference# in a 2-coloured tree # Tree traversal to compute minimum differencedef dfs(node, parent, tree, colour, answer): # Initial min difference is # the color of node answer[node] = colour[node] # Traversing its children for u in tree[node]: # Not traversing the parent if (u == parent): continue dfs(u, node, tree, colour, answer) # If the child is Adding positively to # difference, we include it in the answer # Otherwise, we leave the sub-tree and # include 0 (nothing) in the answer answer[node] += max(answer[u], 0) def maxDiff(tree, colour, N): answer = [0 for _ in range(N+1)] # DFS for colour difference : 1colour - 2colour dfs(1, 0, tree, colour, answer) # Minimum colour difference is # maximum answer value high = 0 for i in range(1, N+1): high = max(high, answer[i]) # Clearing the current value # to check for colour2 as well answer[i] = 0 # Interchanging the colours for i in range(1, N+1): if colour[i] == -1: colour[i] = 1 else: colour[i] = -1 # DFS for colour difference : 2colour - 1colour dfs(1, 0, tree, colour, answer) # Checking if colour2 makes the # minimum colour difference for i in range(1, N): high = max(high, answer[i]) return high # Driver code# NodesN = 5 # Adjacency list representationtree = [list() for _ in range(N+1)] # Edgestree[1].append(2)tree[2].append(1)tree[1].append(3)tree[3].append(1)tree[2].append(4)tree[4].append(2)tree[3].append(5)tree[5].append(3) # Index represent the colour of that node# There is no Node 0, so we start from# index 1 to Ncolour = [0, 1, 1, -1, -1, 1] # Printing the resultprint(maxDiff(tree, colour, N)) # This code is contributed by nitibi9839.
// C# code to find the sub-tree// with minimum color difference// in a 2-coloured treeusing System;using System.Collections.Generic; class GFG{ // Tree traversal to compute minimum differencestatic void dfs(int node, int parent, List<int> []tree, int []colour, int []answer){ // Initial min difference is // the color of node answer[node] = colour[node]; // Traversing its children foreach (int u in tree[node]) { // Not traversing the parent if (u == parent) continue; dfs(u, node, tree, colour, answer); // If the child is Adding positively to // difference, we include it in the answer // Otherwise, we leave the sub-tree and // include 0 (nothing) in the answer answer[node] += Math.Max(answer[u], 0); }} static int maxDiff(List<int> []tree, int []colour, int N){ int []answer = new int[N + 1]; // DFS for colour difference : 1colour - 2colour dfs(1, 0, tree, colour, answer); // Minimum colour difference is // maximum answer value int high = 0; for (int i = 1; i <= N; i++) { high = Math.Max(high, answer[i]); // Clearing the current value // to check for colour2 as well answer[i] = 0; } // Interchanging the colours for (int i = 1; i <= N; i++) { if (colour[i] == -1) colour[i] = 1; else colour[i] = -1; } // DFS for colour difference : 2colour - 1colour dfs(1, 0, tree, colour, answer); // Checking if colour2 makes the // minimum colour difference for (int i = 1; i < N; i++) high = Math.Max(high, answer[i]); return high;} // Driver codepublic static void Main(String []args){ // Nodes int N = 5; // Adjacency list representation List<int> []tree = new List<int>[N + 1]; for(int i = 0; i < N + 1; i++) tree[i] = new List<int>(); // Edges tree[1].Add(2); tree[2].Add(1); tree[1].Add(3); tree[3].Add(1); tree[2].Add(4); tree[4].Add(2); tree[3].Add(5); tree[5].Add(3); // Index represent the colour of that node // There is no Node 0, so we start from // index 1 to N int []colour = { 0, 1, 1, -1, -1, 1 }; // Printing the result Console.WriteLine(maxDiff(tree, colour, N));}} // This code is contributed by Rajput-Ji
<script> // JavaScript code to find the sub-tree// with minimum color difference// in a 2-coloured tree // Tree traversal to compute minimum differencefunction dfs(node, parent, tree, colour, answer){ // Initial min difference is // the color of node answer[node] = colour[node]; // Traversing its children for(var u of tree[node]) { // Not traversing the parent if (u == parent) continue; dfs(u, node, tree, colour, answer); // If the child is Adding positively to // difference, we include it in the answer // Otherwise, we leave the sub-tree and // include 0 (nothing) in the answer answer[node] += Math.max(answer[u], 0); }} function maxDiff(tree, colour, N){ var answer = Array(N+1).fill(0); // DFS for colour difference : 1colour - 2colour dfs(1, 0, tree, colour, answer); // Minimum colour difference is // maximum answer value var high = 0; for (var i = 1; i <= N; i++) { high = Math.max(high, answer[i]); // Clearing the current value // to check for colour2 as well answer[i] = 0; } // Interchanging the colours for (var i = 1; i <= N; i++) { if (colour[i] == -1) colour[i] = 1; else colour[i] = -1; } // DFS for colour difference : 2colour - 1colour dfs(1, 0, tree, colour, answer); // Checking if colour2 makes the // minimum colour difference for (var i = 1; i < N; i++) high = Math.max(high, answer[i]); return high;} // Driver code// Nodesvar N = 5;// Adjacency list representationvar tree = Array.from(Array(N+1), ()=>Array()); // Edgestree[1].push(2);tree[2].push(1);tree[1].push(3);tree[3].push(1);tree[2].push(4);tree[4].push(2);tree[3].push(5);tree[5].push(3);// Index represent the colour of that node// There is no Node 0, so we start from// index 1 to Nvar colour = [0, 1, 1, -1, -1, 1];// Printing the resultdocument.write(maxDiff(tree, colour, N)); </script>
Output:
2
This article is contributed by Rohit Thapliyal. 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.
29AjayKumar
Rajput-Ji
rutvik_56
nitibi9839
Dynamic Programming
Tree
Dynamic Programming
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Aug, 2021"
},
{
"code": null,
"e": 252,
"s": 54,
"text": "A tree with N nodes and N-1 edges is given with 2 different colours for its nodes. Find the sub-tree with minimum colour difference i.e. abs(1-colour nodes – 2-colour nodes) is minimum. Examples: "
},
{
"code": null,
"e": 662,
"s": 252,
"text": "Input : \nEdges : 1 2\n 1 3\n 2 4\n 3 5\nColours : 1 1 2 2 1 [1-based indexing where \n index denotes the node]\nOutput : 2\nExplanation : The sub-tree {1-2} and {1-2-3-5}\nhave color difference of 2. Sub-tree {1-2} has two\n1-colour nodes and zero 2-colour nodes. So, color \ndifference is 2. Sub-tree {1-2-3-5} has three 1-colour\nnodes and one 2-colour nodes. So color diff = 2."
},
{
"code": null,
"e": 1310,
"s": 664,
"text": "Method 1 : The problem can be solved by checking every possible sub-tree from every node of the tree. This will take exponential time as we will check for sub-trees from every node.Method 2 : (Efficient) If we observe, we are solving a portion of the tree several times. This produces recurring sub-problems. We can use Dynamic Programming approach to get the minimum color difference in one traversal. To make things simpler, we can have color values as 1 and -1. Now, if we have a sub-tree with both colored nodes equal, our sum of colors will be 0. To get the minimum difference, we should have maximum negative sum or maximum positive sum. "
},
{
"code": null,
"e": 1440,
"s": 1310,
"text": "Case 1 When we need to have a sub-tree with maximum sum : We take a node if its value > 0, i.e. sum(parent) += max(0, sum(child))"
},
{
"code": null,
"e": 1591,
"s": 1440,
"text": "Case 2 When we need to have a sub-tree with minimum sum(or max negative sum) : We take a node if its value < 0, i.e. sum(parent) += min(0, sum(child))"
},
{
"code": null,
"e": 1720,
"s": 1591,
"text": "To get the minimum sum, we can interchange the colors of nodes, i.e. -1 becomes 1 and vice-versa.Below is the implementation : "
},
{
"code": null,
"e": 1724,
"s": 1720,
"text": "C++"
},
{
"code": null,
"e": 1729,
"s": 1724,
"text": "Java"
},
{
"code": null,
"e": 1737,
"s": 1729,
"text": "Python3"
},
{
"code": null,
"e": 1740,
"s": 1737,
"text": "C#"
},
{
"code": null,
"e": 1751,
"s": 1740,
"text": "Javascript"
},
{
"code": "// CPP code to find the sub-tree with minimum color// difference in a 2-coloured tree#include <bits/stdc++.h>using namespace std; // Tree traversal to compute minimum differencevoid dfs(int node, int parent, vector<int> tree[], int colour[], int answer[]){ // Initial min difference is the color of node answer[node] = colour[node]; // Traversing its children for (auto u : tree[node]) { // Not traversing the parent if (u == parent) continue; dfs(u, node, tree, colour, answer); // If the child is adding positively to // difference, we include it in the answer // Otherwise, we leave the sub-tree and // include 0 (nothing) in the answer answer[node] += max(answer[u], 0); }} int maxDiff(vector<int> tree[], int colour[], int N){ int answer[N + 1]; memset(answer, 0, sizeof(answer)); // DFS for colour difference : 1colour - 2colour dfs(1, 0, tree, colour, answer); // Minimum colour difference is maximum answer value int high = 0; for (int i = 1; i <= N; i++) { high = max(high, answer[i]); // Clearing the current value // to check for colour2 as well answer[i] = 0; } // Interchanging the colours for (int i = 1; i <= N; i++) { if (colour[i] == -1) colour[i] = 1; else colour[i] = -1; } // DFS for colour difference : 2colour - 1colour dfs(1, 0, tree, colour, answer); // Checking if colour2 makes the minimum colour // difference for (int i = 1; i < N; i++) high = max(high, answer[i]); return high;} // Driver codeint main(){ // Nodes int N = 5; // Adjacency list representation vector<int> tree[N + 1]; // Edges tree[1].push_back(2); tree[2].push_back(1); tree[1].push_back(3); tree[3].push_back(1); tree[2].push_back(4); tree[4].push_back(2); tree[3].push_back(5); tree[5].push_back(3); // Index represent the colour of that node // There is no Node 0, so we start from // index 1 to N int colour[] = { 0, 1, 1, -1, -1, 1 }; // Printing the result cout << maxDiff(tree, colour, N); return 0;}",
"e": 3976,
"s": 1751,
"text": null
},
{
"code": "// Java code to find the sub-tree// with minimum color difference// in a 2-coloured treeimport java.util.*;class GFG{ // Tree traversal to compute minimum differencestatic void dfs(int node, int parent, Vector<Integer> tree[], int colour[], int answer[]){ // Initial min difference is // the color of node answer[node] = colour[node]; // Traversing its children for (Integer u : tree[node]) { // Not traversing the parent if (u == parent) continue; dfs(u, node, tree, colour, answer); // If the child is adding positively to // difference, we include it in the answer // Otherwise, we leave the sub-tree and // include 0 (nothing) in the answer answer[node] += Math.max(answer[u], 0); }} static int maxDiff(Vector<Integer> tree[], int colour[], int N){ int []answer = new int[N + 1]; // DFS for colour difference : 1colour - 2colour dfs(1, 0, tree, colour, answer); // Minimum colour difference is // maximum answer value int high = 0; for (int i = 1; i <= N; i++) { high = Math.max(high, answer[i]); // Clearing the current value // to check for colour2 as well answer[i] = 0; } // Interchanging the colours for (int i = 1; i <= N; i++) { if (colour[i] == -1) colour[i] = 1; else colour[i] = -1; } // DFS for colour difference : 2colour - 1colour dfs(1, 0, tree, colour, answer); // Checking if colour2 makes the // minimum colour difference for (int i = 1; i < N; i++) high = Math.max(high, answer[i]); return high;} // Driver codepublic static void main(String []args){ // Nodes int N = 5; // Adjacency list representation Vector<Integer> tree[] = new Vector[N + 1]; for(int i = 0; i < N + 1; i++) tree[i] = new Vector<Integer>(); // Edges tree[1].add(2); tree[2].add(1); tree[1].add(3); tree[3].add(1); tree[2].add(4); tree[4].add(2); tree[3].add(5); tree[5].add(3); // Index represent the colour of that node // There is no Node 0, so we start from // index 1 to N int colour[] = { 0, 1, 1, -1, -1, 1 }; // Printing the result System.out.println(maxDiff(tree, colour, N));}} // This code is contributed by 29AjayKumar",
"e": 6362,
"s": 3976,
"text": null
},
{
"code": "# Python3 code to find the sub-tree# with minimum color difference# in a 2-coloured tree # Tree traversal to compute minimum differencedef dfs(node, parent, tree, colour, answer): # Initial min difference is # the color of node answer[node] = colour[node] # Traversing its children for u in tree[node]: # Not traversing the parent if (u == parent): continue dfs(u, node, tree, colour, answer) # If the child is Adding positively to # difference, we include it in the answer # Otherwise, we leave the sub-tree and # include 0 (nothing) in the answer answer[node] += max(answer[u], 0) def maxDiff(tree, colour, N): answer = [0 for _ in range(N+1)] # DFS for colour difference : 1colour - 2colour dfs(1, 0, tree, colour, answer) # Minimum colour difference is # maximum answer value high = 0 for i in range(1, N+1): high = max(high, answer[i]) # Clearing the current value # to check for colour2 as well answer[i] = 0 # Interchanging the colours for i in range(1, N+1): if colour[i] == -1: colour[i] = 1 else: colour[i] = -1 # DFS for colour difference : 2colour - 1colour dfs(1, 0, tree, colour, answer) # Checking if colour2 makes the # minimum colour difference for i in range(1, N): high = max(high, answer[i]) return high # Driver code# NodesN = 5 # Adjacency list representationtree = [list() for _ in range(N+1)] # Edgestree[1].append(2)tree[2].append(1)tree[1].append(3)tree[3].append(1)tree[2].append(4)tree[4].append(2)tree[3].append(5)tree[5].append(3) # Index represent the colour of that node# There is no Node 0, so we start from# index 1 to Ncolour = [0, 1, 1, -1, -1, 1] # Printing the resultprint(maxDiff(tree, colour, N)) # This code is contributed by nitibi9839.",
"e": 8258,
"s": 6362,
"text": null
},
{
"code": "// C# code to find the sub-tree// with minimum color difference// in a 2-coloured treeusing System;using System.Collections.Generic; class GFG{ // Tree traversal to compute minimum differencestatic void dfs(int node, int parent, List<int> []tree, int []colour, int []answer){ // Initial min difference is // the color of node answer[node] = colour[node]; // Traversing its children foreach (int u in tree[node]) { // Not traversing the parent if (u == parent) continue; dfs(u, node, tree, colour, answer); // If the child is Adding positively to // difference, we include it in the answer // Otherwise, we leave the sub-tree and // include 0 (nothing) in the answer answer[node] += Math.Max(answer[u], 0); }} static int maxDiff(List<int> []tree, int []colour, int N){ int []answer = new int[N + 1]; // DFS for colour difference : 1colour - 2colour dfs(1, 0, tree, colour, answer); // Minimum colour difference is // maximum answer value int high = 0; for (int i = 1; i <= N; i++) { high = Math.Max(high, answer[i]); // Clearing the current value // to check for colour2 as well answer[i] = 0; } // Interchanging the colours for (int i = 1; i <= N; i++) { if (colour[i] == -1) colour[i] = 1; else colour[i] = -1; } // DFS for colour difference : 2colour - 1colour dfs(1, 0, tree, colour, answer); // Checking if colour2 makes the // minimum colour difference for (int i = 1; i < N; i++) high = Math.Max(high, answer[i]); return high;} // Driver codepublic static void Main(String []args){ // Nodes int N = 5; // Adjacency list representation List<int> []tree = new List<int>[N + 1]; for(int i = 0; i < N + 1; i++) tree[i] = new List<int>(); // Edges tree[1].Add(2); tree[2].Add(1); tree[1].Add(3); tree[3].Add(1); tree[2].Add(4); tree[4].Add(2); tree[3].Add(5); tree[5].Add(3); // Index represent the colour of that node // There is no Node 0, so we start from // index 1 to N int []colour = { 0, 1, 1, -1, -1, 1 }; // Printing the result Console.WriteLine(maxDiff(tree, colour, N));}} // This code is contributed by Rajput-Ji",
"e": 10652,
"s": 8258,
"text": null
},
{
"code": "<script> // JavaScript code to find the sub-tree// with minimum color difference// in a 2-coloured tree // Tree traversal to compute minimum differencefunction dfs(node, parent, tree, colour, answer){ // Initial min difference is // the color of node answer[node] = colour[node]; // Traversing its children for(var u of tree[node]) { // Not traversing the parent if (u == parent) continue; dfs(u, node, tree, colour, answer); // If the child is Adding positively to // difference, we include it in the answer // Otherwise, we leave the sub-tree and // include 0 (nothing) in the answer answer[node] += Math.max(answer[u], 0); }} function maxDiff(tree, colour, N){ var answer = Array(N+1).fill(0); // DFS for colour difference : 1colour - 2colour dfs(1, 0, tree, colour, answer); // Minimum colour difference is // maximum answer value var high = 0; for (var i = 1; i <= N; i++) { high = Math.max(high, answer[i]); // Clearing the current value // to check for colour2 as well answer[i] = 0; } // Interchanging the colours for (var i = 1; i <= N; i++) { if (colour[i] == -1) colour[i] = 1; else colour[i] = -1; } // DFS for colour difference : 2colour - 1colour dfs(1, 0, tree, colour, answer); // Checking if colour2 makes the // minimum colour difference for (var i = 1; i < N; i++) high = Math.max(high, answer[i]); return high;} // Driver code// Nodesvar N = 5;// Adjacency list representationvar tree = Array.from(Array(N+1), ()=>Array()); // Edgestree[1].push(2);tree[2].push(1);tree[1].push(3);tree[3].push(1);tree[2].push(4);tree[4].push(2);tree[3].push(5);tree[5].push(3);// Index represent the colour of that node// There is no Node 0, so we start from// index 1 to Nvar colour = [0, 1, 1, -1, -1, 1];// Printing the resultdocument.write(maxDiff(tree, colour, N)); </script>",
"e": 12672,
"s": 10652,
"text": null
},
{
"code": null,
"e": 12682,
"s": 12672,
"text": "Output: "
},
{
"code": null,
"e": 12684,
"s": 12682,
"text": "2"
},
{
"code": null,
"e": 13108,
"s": 12684,
"text": "This article is contributed by Rohit Thapliyal. 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": 13120,
"s": 13108,
"text": "29AjayKumar"
},
{
"code": null,
"e": 13130,
"s": 13120,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 13140,
"s": 13130,
"text": "rutvik_56"
},
{
"code": null,
"e": 13151,
"s": 13140,
"text": "nitibi9839"
},
{
"code": null,
"e": 13171,
"s": 13151,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 13176,
"s": 13171,
"text": "Tree"
},
{
"code": null,
"e": 13196,
"s": 13176,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 13201,
"s": 13196,
"text": "Tree"
}
] |
How to Add Dynamic Markers in Google Maps with Firebase Firstore? | 31 Jan, 2021
We have seen adding markers to Google Maps in Android. Along with that, we have also added multiple markers on Google Maps in Android. Many apps use a dynamic feature to add a marker on the Google Maps and update them according to requirements. In this article, we will take a look at adding markers to Google Map from Firebase in Android.
We will be building a simple application in which we will be displaying a map with a simple marker and we will add a marker to it from Firebase. We have to add markers from Firebase Firestore to our map. 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. Make sure to select Maps Activity while creating a new Project.
Step 2: Generating an API key for using Google Maps
To generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY.
Step 3: Connecting your app with the Firebase
After creating a new project and adding a key for Google Maps. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot.
Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen.
After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file. Check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section.
implementation ‘com.google.firebase:firebase-firestore:22.0.1’
After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App.
Step 4: Working with the AndroidManifest.xml file
For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml. Inside that file add the below permissions to it.
XML
<!--Permissions for internet--><uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Step 5: Working with the MapsActivity.java file
Go to the MapsActivity.java file and refer to the following code. Below is the code for the MapsActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.widget.Toast; import androidx.annotation.Nullable;import androidx.fragment.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory;import com.google.android.gms.maps.GoogleMap;import com.google.android.gms.maps.OnMapReadyCallback;import com.google.android.gms.maps.SupportMapFragment;import com.google.android.gms.maps.model.LatLng;import com.google.android.gms.maps.model.MarkerOptions;import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.DocumentSnapshot;import com.google.firebase.firestore.EventListener;import com.google.firebase.firestore.FirebaseFirestore;import com.google.firebase.firestore.FirebaseFirestoreException;import com.google.firebase.firestore.GeoPoint; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; FirebaseFirestore db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // initializing our firebase firestore. db = FirebaseFirestore.getInstance(); // Obtain the SupportMapFragment and get // notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // creating a variable for document reference. DocumentReference documentReference = db.collection("MapsData").document("7QWDor9vozLaHdFYV9kh"); // calling document reference class with on snap shot listener. documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { if (value != null && value.exists()) { // below line is to create a geo point and we are getting // geo point from firebase and setting to it. GeoPoint geoPoint = value.getGeoPoint("geoPoint"); // getting latitude and longitude from geo point // and setting it to our location. LatLng location = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()); // adding marker to each location on google maps mMap.addMarker(new MarkerOptions().position(location).title("Marker")); // below line is use to move camera. mMap.moveCamera(CameraUpdateFactory.newLatLng(location)); } else { Toast.makeText(MapsActivity.this, "Error found is " + error, Toast.LENGTH_SHORT).show(); } } }); }}
Step 6: Adding data to Firebase Firestore in Android
Go to the browser and open Firebase in your browser. After opening Firebase you will get to see the below page and on this page Click on Go to Console option in the top right corner.
After clicking on this screen you will get to see the below screen with your all project inside that select your project.
Inside that screen click n Firebase Firestore Database in the left window.
After clicking on the Create Database option you will get to see the below screen.
Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting test mode click on the Next option and you will get to see the below screen.
Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside our app and click on the submit button. To add data just click on the Start Collection button and provide the Collection ID as MapsData. After that provide the Document ID as 7QWDor9vozLaHdFYV9kh and inside the Field write down geoPoint, and select type as geopoint, and enter the Latitude and Longitude of the desired location. At last click on the Save button.
After adding the data to Firebase. Now run your app and see the output of the app. You can change the value in the geopoint with your latitude and longitude field and you can get to see the real-time updates on your maps with added Markers.
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. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jan, 2021"
},
{
"code": null,
"e": 369,
"s": 28,
"text": "We have seen adding markers to Google Maps in Android. Along with that, we have also added multiple markers on Google Maps in Android. Many apps use a dynamic feature to add a marker on the Google Maps and update them according to requirements. In this article, we will take a look at adding markers to Google Map from Firebase in Android. "
},
{
"code": null,
"e": 740,
"s": 369,
"text": "We will be building a simple application in which we will be displaying a map with a simple marker and we will add a marker to it from Firebase. We have to add markers from Firebase Firestore to our map. 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": 769,
"s": 740,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 995,
"s": 769,
"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. Make sure to select Maps Activity while creating a new Project."
},
{
"code": null,
"e": 1047,
"s": 995,
"text": "Step 2: Generating an API key for using Google Maps"
},
{
"code": null,
"e": 1405,
"s": 1047,
"text": "To generate the API key for Maps you may refer to How to Generate API Key for Using Google Maps in Android. After generating your API key for Google Maps. We have to add this key to our Project. For adding this key in our app navigate to the values folder > google_maps_api.xml file and at line 23 you have to add your API key in the place of YOUR_API_KEY. "
},
{
"code": null,
"e": 1451,
"s": 1405,
"text": "Step 3: Connecting your app with the Firebase"
},
{
"code": null,
"e": 1689,
"s": 1451,
"text": "After creating a new project and adding a key for Google Maps. Navigate to the Tools option on the top bar. Inside that click on Firebase. After clicking on Firebase, you can get to see the right column mentioned below in the screenshot."
},
{
"code": null,
"e": 2098,
"s": 1689,
"text": "Inside that column Navigate to Firebase Cloud Firestore. Click on that option and you will get to see two options on Connect app to Firebase and Add Cloud Firestore to your app. Click on Connect now option and your app will be connected to Firebase. After that click on the second option and now your App is connected to Firebase. After connecting your app to Firebase you will get to see the below screen. "
},
{
"code": null,
"e": 2432,
"s": 2098,
"text": "After that verify that dependency for the Firebase Firestore database has been added to our Gradle file. Navigate to the app > Gradle Scripts inside that file. Check whether the below dependency is added or not. If the below dependency is not present in your build.gradle file. Add the below dependency in the dependencies section. "
},
{
"code": null,
"e": 2495,
"s": 2432,
"text": "implementation ‘com.google.firebase:firebase-firestore:22.0.1’"
},
{
"code": null,
"e": 2732,
"s": 2495,
"text": "After adding this dependency sync your project and now we are ready for creating our app. If you want to know more about connecting your app to Firebase. Refer to this article to get in detail about How to add Firebase to Android App. "
},
{
"code": null,
"e": 2782,
"s": 2732,
"text": "Step 4: Working with the AndroidManifest.xml file"
},
{
"code": null,
"e": 2997,
"s": 2782,
"text": "For adding data to Firebase we should have to give permissions for accessing the internet. For adding these permissions navigate to the app > AndroidManifest.xml. Inside that file add the below permissions to it. "
},
{
"code": null,
"e": 3001,
"s": 2997,
"text": "XML"
},
{
"code": "<!--Permissions for internet--><uses-permission android:name=\"android.permission.INTERNET\" /> <uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />",
"e": 3170,
"s": 3001,
"text": null
},
{
"code": null,
"e": 3218,
"s": 3170,
"text": "Step 5: Working with the MapsActivity.java file"
},
{
"code": null,
"e": 3408,
"s": 3218,
"text": "Go to the MapsActivity.java file and refer to the following code. Below is the code for the MapsActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 3413,
"s": 3408,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.widget.Toast; import androidx.annotation.Nullable;import androidx.fragment.app.FragmentActivity; import com.google.android.gms.maps.CameraUpdateFactory;import com.google.android.gms.maps.GoogleMap;import com.google.android.gms.maps.OnMapReadyCallback;import com.google.android.gms.maps.SupportMapFragment;import com.google.android.gms.maps.model.LatLng;import com.google.android.gms.maps.model.MarkerOptions;import com.google.firebase.firestore.DocumentReference;import com.google.firebase.firestore.DocumentSnapshot;import com.google.firebase.firestore.EventListener;import com.google.firebase.firestore.FirebaseFirestore;import com.google.firebase.firestore.FirebaseFirestoreException;import com.google.firebase.firestore.GeoPoint; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback { private GoogleMap mMap; FirebaseFirestore db; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); // initializing our firebase firestore. db = FirebaseFirestore.getInstance(); // Obtain the SupportMapFragment and get // notified when the map is ready to be used. SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); mapFragment.getMapAsync(this); } @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; // creating a variable for document reference. DocumentReference documentReference = db.collection(\"MapsData\").document(\"7QWDor9vozLaHdFYV9kh\"); // calling document reference class with on snap shot listener. documentReference.addSnapshotListener(new EventListener<DocumentSnapshot>() { @Override public void onEvent(@Nullable DocumentSnapshot value, @Nullable FirebaseFirestoreException error) { if (value != null && value.exists()) { // below line is to create a geo point and we are getting // geo point from firebase and setting to it. GeoPoint geoPoint = value.getGeoPoint(\"geoPoint\"); // getting latitude and longitude from geo point // and setting it to our location. LatLng location = new LatLng(geoPoint.getLatitude(), geoPoint.getLongitude()); // adding marker to each location on google maps mMap.addMarker(new MarkerOptions().position(location).title(\"Marker\")); // below line is use to move camera. mMap.moveCamera(CameraUpdateFactory.newLatLng(location)); } else { Toast.makeText(MapsActivity.this, \"Error found is \" + error, Toast.LENGTH_SHORT).show(); } } }); }}",
"e": 6445,
"s": 3413,
"text": null
},
{
"code": null,
"e": 6498,
"s": 6445,
"text": "Step 6: Adding data to Firebase Firestore in Android"
},
{
"code": null,
"e": 6685,
"s": 6498,
"text": "Go to the browser and open Firebase in your browser. After opening Firebase you will get to see the below page and on this page Click on Go to Console option in the top right corner. "
},
{
"code": null,
"e": 6809,
"s": 6685,
"text": "After clicking on this screen you will get to see the below screen with your all project inside that select your project. "
},
{
"code": null,
"e": 6886,
"s": 6809,
"text": "Inside that screen click n Firebase Firestore Database in the left window. "
},
{
"code": null,
"e": 6971,
"s": 6886,
"text": "After clicking on the Create Database option you will get to see the below screen. "
},
{
"code": null,
"e": 7256,
"s": 6971,
"text": "Inside this screen, we have to select the Start in test mode option. We are using test mode because we are not setting authentication inside our app. So we are selecting Start in test mode. After selecting test mode click on the Next option and you will get to see the below screen. "
},
{
"code": null,
"e": 7811,
"s": 7256,
"text": "Inside this screen, we just have to click on the Enable button to enable our Firebase Firestore database. After completing this process we just have to run our application and add data inside our app and click on the submit button. To add data just click on the Start Collection button and provide the Collection ID as MapsData. After that provide the Document ID as 7QWDor9vozLaHdFYV9kh and inside the Field write down geoPoint, and select type as geopoint, and enter the Latitude and Longitude of the desired location. At last click on the Save button."
},
{
"code": null,
"e": 8054,
"s": 7811,
"text": "After adding the data to Firebase. Now run your app and see the output of the app. You can change the value in the geopoint with your latitude and longitude field and you can get to see the real-time updates on your maps with added Markers. "
},
{
"code": null,
"e": 8062,
"s": 8054,
"text": "android"
},
{
"code": null,
"e": 8086,
"s": 8062,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 8094,
"s": 8086,
"text": "Android"
},
{
"code": null,
"e": 8099,
"s": 8094,
"text": "Java"
},
{
"code": null,
"e": 8118,
"s": 8099,
"text": "Technical Scripter"
},
{
"code": null,
"e": 8123,
"s": 8118,
"text": "Java"
},
{
"code": null,
"e": 8131,
"s": 8123,
"text": "Android"
}
] |
Automating Lambda modules deployment with GitLab CI | by Daniel Da Costa | Towards Data Science | While working with terraform lambda modules, I had a hard time finding out the best repository architecture to automate my lambdas deployment. I couldn’t find any article that I could use as a guideline, that’s why I’m writing this article.
While working on big projects, project organization is a must-have. In this story, you will be presented to one way to organize your repositories so that it facilitates the deployment procedure, making it much more scalable.
In this article, we'll be building the following repositories architecture:
Lambda-Module: Repository containing the Terraform Lambda module.
Lambda-Infra: Repository containing Terraform code for deployment into AWS.
Lambda-Code: Repository containing the lambda code for deployment using Gitlab-CI.
As defined by HashiCorp:
A module is a container for multiple resources that are used together.
Using terraform modules solve problems like organize configuration, encapsulate configuration, re-use configuration and it provides consistency and ensure best practice.
We'll be using an AWS lambda module that can be found in here. I won't go into details of how to build a lambda module, since it isn’t the main goal of this article.
Once you have your module ready, you can set up a repository that will centralize all of your lambdas infrastructure. In the example below, each .tf represents a different lambda.
.├── README.md├── lambda_alarm.tf├── lambda_general.tf├── lambda_sms.tf
With you lambda-module ready, you can use it to build your lambda infrastructure.
As it can be seen on the code below, we are storing our lambda zip file in a s3 bucket that has versioning activated. This is a crucial step, since it will be the version id of our zip file in s3 that will trigger the lambda re-deployment, in case of any change in the code.
In the example above, lambda-sms.zip is our lambda source code that will be defined below.
In order to automate the lambda deployment, it will be necessary to zip your lambda code and put it into your s3 bucket.
First, let’s check our lambda code example.
.├── README.md└── .gitlab-ci.yml└── lambda ├── config.py ├── database.py ├── handler.py ├── package ├── queries │ └── save_data.sql └── requirements.txt
Our CI will be responsible for:
Running Flake8 in order to check for syntax error and linting conventions.
Installing the lambda dependencies defined at requirements.txt
Zipping our code
Moving it to AWS s3 bucket using AWS CLI
Following The Principle of Least Privileges in AWS, you should create an IAM user that has only the Put-Object permission:
You are going to store your AWS CLI credentials in the CICD settings for your GitLab project:
With everything set up, when you push your code to your Master branch your lambda code will be zipped and stored in your S3 bucket.
Let’s go through all the deployment procedure:
Create your lambda code and push it to your GitLab repository.
Your code will then be zipped and stored in your versioned s3 Bucket.
Run the terraform in lambda-infra code.
Terraform will check for changes in the version id of your lambda source code.
If it detects that a new .zip file has been uploaded to s3, it will then re-deploy your lambda.
This architecture made my life much easier, giving my code much more scalability. I hope it helps you as it helped me! | [
{
"code": null,
"e": 412,
"s": 171,
"text": "While working with terraform lambda modules, I had a hard time finding out the best repository architecture to automate my lambdas deployment. I couldn’t find any article that I could use as a guideline, that’s why I’m writing this article."
},
{
"code": null,
"e": 637,
"s": 412,
"text": "While working on big projects, project organization is a must-have. In this story, you will be presented to one way to organize your repositories so that it facilitates the deployment procedure, making it much more scalable."
},
{
"code": null,
"e": 713,
"s": 637,
"text": "In this article, we'll be building the following repositories architecture:"
},
{
"code": null,
"e": 779,
"s": 713,
"text": "Lambda-Module: Repository containing the Terraform Lambda module."
},
{
"code": null,
"e": 855,
"s": 779,
"text": "Lambda-Infra: Repository containing Terraform code for deployment into AWS."
},
{
"code": null,
"e": 938,
"s": 855,
"text": "Lambda-Code: Repository containing the lambda code for deployment using Gitlab-CI."
},
{
"code": null,
"e": 963,
"s": 938,
"text": "As defined by HashiCorp:"
},
{
"code": null,
"e": 1034,
"s": 963,
"text": "A module is a container for multiple resources that are used together."
},
{
"code": null,
"e": 1204,
"s": 1034,
"text": "Using terraform modules solve problems like organize configuration, encapsulate configuration, re-use configuration and it provides consistency and ensure best practice."
},
{
"code": null,
"e": 1370,
"s": 1204,
"text": "We'll be using an AWS lambda module that can be found in here. I won't go into details of how to build a lambda module, since it isn’t the main goal of this article."
},
{
"code": null,
"e": 1550,
"s": 1370,
"text": "Once you have your module ready, you can set up a repository that will centralize all of your lambdas infrastructure. In the example below, each .tf represents a different lambda."
},
{
"code": null,
"e": 1622,
"s": 1550,
"text": ".├── README.md├── lambda_alarm.tf├── lambda_general.tf├── lambda_sms.tf"
},
{
"code": null,
"e": 1704,
"s": 1622,
"text": "With you lambda-module ready, you can use it to build your lambda infrastructure."
},
{
"code": null,
"e": 1979,
"s": 1704,
"text": "As it can be seen on the code below, we are storing our lambda zip file in a s3 bucket that has versioning activated. This is a crucial step, since it will be the version id of our zip file in s3 that will trigger the lambda re-deployment, in case of any change in the code."
},
{
"code": null,
"e": 2070,
"s": 1979,
"text": "In the example above, lambda-sms.zip is our lambda source code that will be defined below."
},
{
"code": null,
"e": 2191,
"s": 2070,
"text": "In order to automate the lambda deployment, it will be necessary to zip your lambda code and put it into your s3 bucket."
},
{
"code": null,
"e": 2235,
"s": 2191,
"text": "First, let’s check our lambda code example."
},
{
"code": null,
"e": 2411,
"s": 2235,
"text": ".├── README.md└── .gitlab-ci.yml└── lambda ├── config.py ├── database.py ├── handler.py ├── package ├── queries │ └── save_data.sql └── requirements.txt"
},
{
"code": null,
"e": 2443,
"s": 2411,
"text": "Our CI will be responsible for:"
},
{
"code": null,
"e": 2518,
"s": 2443,
"text": "Running Flake8 in order to check for syntax error and linting conventions."
},
{
"code": null,
"e": 2581,
"s": 2518,
"text": "Installing the lambda dependencies defined at requirements.txt"
},
{
"code": null,
"e": 2598,
"s": 2581,
"text": "Zipping our code"
},
{
"code": null,
"e": 2639,
"s": 2598,
"text": "Moving it to AWS s3 bucket using AWS CLI"
},
{
"code": null,
"e": 2762,
"s": 2639,
"text": "Following The Principle of Least Privileges in AWS, you should create an IAM user that has only the Put-Object permission:"
},
{
"code": null,
"e": 2856,
"s": 2762,
"text": "You are going to store your AWS CLI credentials in the CICD settings for your GitLab project:"
},
{
"code": null,
"e": 2988,
"s": 2856,
"text": "With everything set up, when you push your code to your Master branch your lambda code will be zipped and stored in your S3 bucket."
},
{
"code": null,
"e": 3035,
"s": 2988,
"text": "Let’s go through all the deployment procedure:"
},
{
"code": null,
"e": 3098,
"s": 3035,
"text": "Create your lambda code and push it to your GitLab repository."
},
{
"code": null,
"e": 3168,
"s": 3098,
"text": "Your code will then be zipped and stored in your versioned s3 Bucket."
},
{
"code": null,
"e": 3208,
"s": 3168,
"text": "Run the terraform in lambda-infra code."
},
{
"code": null,
"e": 3287,
"s": 3208,
"text": "Terraform will check for changes in the version id of your lambda source code."
},
{
"code": null,
"e": 3383,
"s": 3287,
"text": "If it detects that a new .zip file has been uploaded to s3, it will then re-deploy your lambda."
}
] |
Guide to install TuriCreate in Python3.x - GeeksforGeeks | 06 Oct, 2021
Before Installing first you need to what is actually Turi Create. So, Turi Create is an open-source toolset for creating Core ML models, for tasks such as image classification, object detection, style transfers, recommendations, and many more.
System Requirements
Python 2.7, 3.5, 3.6, 3.7
At least 4gb of RAM
x86_64 Architecture.
Note: For installing purpose the recommended step is to first create a virtual environment in your system.
1. Ubuntu Step 1 : Create a virtual environment and activate it.
# Installing virtual environment using pip
pip install virtualenv
# Create a virtual environment
cd ~
virtual venv
# Activate your virtual environment
source ~/venv/bin/activate
installing a virtual environment using pip
Alternatively, if you are using Anaconda(https://www.anaconda.com/), you may use its virtual environment:
# creating a virtual environment using Anaconda.
conda create -n anaconda
Creating a virtual environment
# activating the virtual environment using anaconda
conda activate <virtual-environment-name>
Activating virtual environment
Step 2 : Install turicreate within your virtual environment
(venv) pip install -U turicreate
Installing turicreate
2. Windows : In windows, you cannot directly install this package but you can use the Windows subsystem for Linux(WSL) to install turicreate in your system.
Step 1 : Install WSL
# Open powershell as Administrator and run the following command
Enable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux
Note: When prompted restart your computer.
Step 2 : After your PC has restarted launch the Microsoft Store and search for Linux. Select the Linux distribution of your choice. For this tutorial, we are using the Ubuntu 18.04 LTS distro.
Step 3 : From the distro’s page, select get, and install.
Step 4 : Launch the distro from the Start menu or by clicking the “launch” button on the Microsoft Store.
Step 5 : You will have to initialize your new distro. Follow the prompts to set up a new Linux account (username and password). You will need your password later when installing packages using sudo.
set your username and password
Step 6 : Update and upgrade your distros packages using the following command.
sudo apt-get update && sudo apt-get upgrade
Output
Step 7 : Installing dependencies and setting up your environment.
# Installing dependencies
sudo apt-get install -y libstdc++6 python-setuptools
sudo apt-get install python3-pip
# Installing virtualenv using pip3
sudo pip3 install virtualenv
# Creating a virtual environment using virtualenv
virtualenv venv
# Activating the created virtual environment
source venv/bin/activate
Step 8 : Now Install turicreate in your virtual environment.
(venv)pip3 install turicreate
Installing turicreate
Congratulation turicreate has been successfully installed in your system. Happy coding.
surinderdawra388
how-to-install
python-modules
Installation Guide
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install FFmpeg on Windows?
How to Install and Run Apache Kafka on Windows?
How to Install Jupyter Notebook on MacOS?
How to Add External JAR File to an IntelliJ IDEA Project?
Beautifulsoup Installation - Python
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe | [
{
"code": null,
"e": 24241,
"s": 24213,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 24485,
"s": 24241,
"text": "Before Installing first you need to what is actually Turi Create. So, Turi Create is an open-source toolset for creating Core ML models, for tasks such as image classification, object detection, style transfers, recommendations, and many more."
},
{
"code": null,
"e": 24506,
"s": 24485,
"text": "System Requirements "
},
{
"code": null,
"e": 24532,
"s": 24506,
"text": "Python 2.7, 3.5, 3.6, 3.7"
},
{
"code": null,
"e": 24552,
"s": 24532,
"text": "At least 4gb of RAM"
},
{
"code": null,
"e": 24573,
"s": 24552,
"text": "x86_64 Architecture."
},
{
"code": null,
"e": 24680,
"s": 24573,
"text": "Note: For installing purpose the recommended step is to first create a virtual environment in your system."
},
{
"code": null,
"e": 24747,
"s": 24680,
"text": "1. Ubuntu Step 1 : Create a virtual environment and activate it. "
},
{
"code": null,
"e": 24929,
"s": 24747,
"text": "# Installing virtual environment using pip\npip install virtualenv\n\n# Create a virtual environment\ncd ~\nvirtual venv\n\n# Activate your virtual environment\nsource ~/venv/bin/activate\n "
},
{
"code": null,
"e": 24972,
"s": 24929,
"text": "installing a virtual environment using pip"
},
{
"code": null,
"e": 25079,
"s": 24972,
"text": "Alternatively, if you are using Anaconda(https://www.anaconda.com/), you may use its virtual environment: "
},
{
"code": null,
"e": 25154,
"s": 25079,
"text": "# creating a virtual environment using Anaconda.\nconda create -n anaconda"
},
{
"code": null,
"e": 25185,
"s": 25154,
"text": "Creating a virtual environment"
},
{
"code": null,
"e": 25279,
"s": 25185,
"text": "# activating the virtual environment using anaconda\nconda activate <virtual-environment-name>"
},
{
"code": null,
"e": 25310,
"s": 25279,
"text": "Activating virtual environment"
},
{
"code": null,
"e": 25371,
"s": 25310,
"text": "Step 2 : Install turicreate within your virtual environment "
},
{
"code": null,
"e": 25404,
"s": 25371,
"text": "(venv) pip install -U turicreate"
},
{
"code": null,
"e": 25426,
"s": 25404,
"text": "Installing turicreate"
},
{
"code": null,
"e": 25583,
"s": 25426,
"text": "2. Windows : In windows, you cannot directly install this package but you can use the Windows subsystem for Linux(WSL) to install turicreate in your system."
},
{
"code": null,
"e": 25604,
"s": 25583,
"text": "Step 1 : Install WSL"
},
{
"code": null,
"e": 25754,
"s": 25604,
"text": "# Open powershell as Administrator and run the following command\nEnable-WindowsOptionalFeature -Online -FeatureName Microsoft-Windows-Subsystem-Linux"
},
{
"code": null,
"e": 25798,
"s": 25754,
"text": "Note: When prompted restart your computer. "
},
{
"code": null,
"e": 25991,
"s": 25798,
"text": "Step 2 : After your PC has restarted launch the Microsoft Store and search for Linux. Select the Linux distribution of your choice. For this tutorial, we are using the Ubuntu 18.04 LTS distro."
},
{
"code": null,
"e": 26050,
"s": 25991,
"text": "Step 3 : From the distro’s page, select get, and install. "
},
{
"code": null,
"e": 26157,
"s": 26050,
"text": "Step 4 : Launch the distro from the Start menu or by clicking the “launch” button on the Microsoft Store. "
},
{
"code": null,
"e": 26356,
"s": 26157,
"text": "Step 5 : You will have to initialize your new distro. Follow the prompts to set up a new Linux account (username and password). You will need your password later when installing packages using sudo."
},
{
"code": null,
"e": 26387,
"s": 26356,
"text": "set your username and password"
},
{
"code": null,
"e": 26466,
"s": 26387,
"text": "Step 6 : Update and upgrade your distros packages using the following command."
},
{
"code": null,
"e": 26510,
"s": 26466,
"text": "sudo apt-get update && sudo apt-get upgrade"
},
{
"code": null,
"e": 26517,
"s": 26510,
"text": "Output"
},
{
"code": null,
"e": 26584,
"s": 26517,
"text": "Step 7 : Installing dependencies and setting up your environment. "
},
{
"code": null,
"e": 26900,
"s": 26584,
"text": "# Installing dependencies\nsudo apt-get install -y libstdc++6 python-setuptools\nsudo apt-get install python3-pip\n\n# Installing virtualenv using pip3\nsudo pip3 install virtualenv \n\n# Creating a virtual environment using virtualenv\nvirtualenv venv\n\n# Activating the created virtual environment\nsource venv/bin/activate"
},
{
"code": null,
"e": 26962,
"s": 26900,
"text": "Step 8 : Now Install turicreate in your virtual environment. "
},
{
"code": null,
"e": 26992,
"s": 26962,
"text": "(venv)pip3 install turicreate"
},
{
"code": null,
"e": 27014,
"s": 26992,
"text": "Installing turicreate"
},
{
"code": null,
"e": 27102,
"s": 27014,
"text": "Congratulation turicreate has been successfully installed in your system. Happy coding."
},
{
"code": null,
"e": 27121,
"s": 27104,
"text": "surinderdawra388"
},
{
"code": null,
"e": 27136,
"s": 27121,
"text": "how-to-install"
},
{
"code": null,
"e": 27151,
"s": 27136,
"text": "python-modules"
},
{
"code": null,
"e": 27170,
"s": 27151,
"text": "Installation Guide"
},
{
"code": null,
"e": 27177,
"s": 27170,
"text": "Python"
},
{
"code": null,
"e": 27275,
"s": 27177,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27284,
"s": 27275,
"text": "Comments"
},
{
"code": null,
"e": 27297,
"s": 27284,
"text": "Old Comments"
},
{
"code": null,
"e": 27331,
"s": 27297,
"text": "How to Install FFmpeg on Windows?"
},
{
"code": null,
"e": 27379,
"s": 27331,
"text": "How to Install and Run Apache Kafka on Windows?"
},
{
"code": null,
"e": 27421,
"s": 27379,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 27479,
"s": 27421,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 27515,
"s": 27479,
"text": "Beautifulsoup Installation - Python"
},
{
"code": null,
"e": 27543,
"s": 27515,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 27593,
"s": 27543,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 27615,
"s": 27593,
"text": "Python map() function"
}
] |
Model Selection & Assessment. Going beyond the train-val-test split | by Michał Oleszak | Towards Data Science | A standard modeling workflow would see you partitioning your data into the training, validation, and testing sets. You would then fit your models to the training data, then use the validation set to perform model selection, and finally, evaluate the very best selected model on the test data to see what generalization performance can be expected of it (model assessment). This flow is presumably your best bet to make sure you have selected the right model and that you won’t be startled once you deploy it to production.
That being said, one cannot always afford the luxury of setting data aside to form validation and testing sets. If you have very little data, you’d rather use it all for training. In this article, we will discuss methods for selecting and assessing models that let you do exactly this — no validation nor test sets required!
This article is based on a chapter from Hastie, T., Tibshirani, R., & Friedman, J. H. (2009). The elements of statistical learning: data mining, inference, and prediction. 2nd ed. New York: Springer.
While comparing competing models, you would like to pick the one performing best on new, unseen data. That’s what you would normally use the validation set for: validation data are not seen by the model while it’s being fit, so choosing a model that works best for these data is a good strategy. Alas, in our setting you have no validation data to check different models against! To see what to do about it, let’s first introduce a couple of error measures:
Training error is the error you get when you run the trained model on the same data it was trained on.
Testing (or generalization) error is the error you get when you run your model on completely new, unseen data.
Imagine that after training the model, you observe new values of the response variable for the same values of the features that you had in your training data. For instance, let’s say you are predicting a house’s price based on the number of rooms. In your training data, you had a house worth $300k with 5 rooms, and now you observe a house sold for $350k, also with 5 rooms. The error the model makes on these new data is called the in-sample error (since the values of the features are the same as in the training sample — not the most straightforward of notations, I agree).
Now, consider this quantity: in-sample error — training error. It is typically positive: the training error is smaller because it is based on the very same data the model was optimized for. But what does it amount to exactly? Well, it can be shown that (up to an expectation) it holds that
where N is the number of observations and the last term is the covariance between the training set response and its predictions. The larger this covariance, the stronger we fit the model to training data (to the point of overfitting), so the training error goes down, increasing the left-hand side of the equation.
Let’s assume (and this an important assumption) that we are dealing with a model that is linear in its parameters. This means we are talking linear or logistic regression models, non-linear splines, or auto-regressive models, for instance. When that’s the case, then the covariance term above simplifies to d * σε2, where d is a measure of model complexity (number of features in linear regression, number of basis functions in regression splines) and σε2 is the error variance. After substituting this simplification and rearranging terms, we get
What does this give us? If we could estimate the right-most term, we could then add it to the training error to obtain an estimate of the in-sample error. And the in-sample error is all we need for model selection! Sure, it doesn’t give us information about the models’ generalization performance (that’s the role of model assessment, read on). Also, we don’t really care about the in-sample error’s specific value — it’s rather uncommon to see the same feature values after deployment as in the training data. But the relative magnitude of in-sample errors across different models allows us to pick the best one.
The above formula is also known as the Mallows’s Cp:
and when the models are fit under squared loss, it can be used for model selection — we simply pick the model with the lowest Cp.
If the models are not necessarily fit under squared loss, we need to adjust Mallows’s Cp slightly. Recall we are discussing models linear in their parameters: think linear or logistic regression, regression splines, or ARIMA models. They are typically estimated by maximum likelihood, and under the Gaussian model, it holds (up to a constant) that
Solving for e_train and substituting this into the formula for Cp we arrive at the Akaike Information Criterion or AIC:
The AIC is basically a penalized likelihood. It goes up as the model complexity d increases and goes down as the model’s fit to the data (the loglikelihood) increases, trading-off these two. We pick the model with the lowest AIC. The best thing about it is that even though AIC is computed using only the training data, minimizing it is asymptotically equivalent to minimizing the leave-one-out cross-validation mean squared error, which makes it great for model selection. For more caveats on the AIC (also in the context of time series forecasting) check out this excellent post by Rob Hyndman, the author of the R’s forecast package.
Let us now look at a Python example of model selection with AIC. We will use the infamous Boston housing data from scikit-learn’s datasets. Let’s fit two linear regression models explaining house prices. We will employ the statsmodels package for this, as it conveniently computes the AIC for us. Both models will use the number of rooms and house age as features. Model 1 will use the neighborhood crime rate on top of that, while model 2 will use distance to large employment centers instead. Which of the two models is better?
Model1 AIC: 3268.8701039911457Model2 AIC: 3300.3758836602733
As far as the AIC is concerned, Model 1 (the one using the crime rate) is better, as it scores a lower AIC value.
AIC is not the only information criterion. Another one is the BIC, or Bayesian Information Criterion, also known as the Schwarz criterion. Similarly to the AIC, the BIC is also a penalized likelihood, but with a different penalty term:
This penalty tends to penalize more complex models more heavily than the AIC. Let’s see how our two housing price models score on BIC.
Model1 BIC: 3285.7762506682957Model2 BIC: 3317.2820303374233
Again, Model 1 is preferred, as it scores a lower BIC. In our examples, both criteria where unanimous, but it does not have to be the case. Which criterion should we then base our model selection on? There is no one-size-fits-all answer, but here are a few things to keep in mind:
BIC is asymptotically consistent, which means it has a high probability of selecting the true model (the one according to which data were generated) when presented a set of competing models.
AIC does not have the consistency property, but do you believe there is a true model to be selected?
BIC prefers more parsimonious models. For small data samples, it might end up selecting too simple models. On the other hand, for large samples, AIC tends to choose too complex ones.
Now that we have selected our model to be the one including the crime rate feature, it would be great to know what kind of performance can we expect of it once deployed. That’s the job of model assessment — to estimate the testing error of a model.
One way to do so is via the well-known procedure of cross-validation. We split the data randomly into k subsets, or folds, and then iterate through them, leaving the current fold out and fitting the model the remaining k−1 folds. Then, we evaluate the model’s error on the left-out fold and proceed to the next iteration. This way, we obtain k error estimates. Once averaged, they form the cross-validated estimate of the testing error. Pretty simple, right? But what should be the value of k?
The choice of k, like so many other choices in machine learning, is between the bias and the variance. Going to the extreme of setting k=N results in the so-called leave-one-out cross-validation. In this setting, each observation constitutes its own fold. As a result, the training sets will be very similar across the folds — indeed, they will only differ by one observation. Consequently, the CV estimate of the testing error might suffer from high variance. On the other hand, when k is small, we risk high bias. This is because the smaller the k, the fewer observations constitute the k−1 training folds. For instance, consider N=100 observations. With k=10, each fold has 10 observations and so each training is based on 90 observations. With k=4, each training uses only 75 observations. If the model performance decreases with less training data, too low k will lead to an over-estimated error.
Ultimately, the choice of k should depend on your application. k=N is rarely a good idea — it’s also quite computationally expensive to run (N models need to be trained)! You know your data best — if you are willing to assume (or have proved) that less data won’t make much of a difference to your model’s performance, then you’re good to go with a small k of say 3 or 5. But that’s probably not the case if you have only little data (should you have big data, you could just follow the standard train/validation/test split and ignore this article). Hence, a slightly larger k of say 10 might be worth a shot. One more thing to consider: if your k will be too small, the error will be over-estimated, meaning that the true testing error is likely to be less than what your CV tells you. If you’re satisfied with the cross-validated error estimate, you’re likely to be even happier with the production performance.
Let’s assess our selected model with 10-fold cross-validation. To do this, we’ll use the scikit-learn API.
Cross-validated testing MSE: 43.925463559757674
To sum up: what has just happened? In case you don’t have enough data to set aside a validation and a test set, you need other ways to do your model selection and assessment. We have shown what are information criteria and how to use them for model selection, and then how to estimate the expected real-world performance of the selected model with cross-validation.
Why not use CV for model selection, I hear you ask. You could! However, with small data, information criteria tend to be more reliable. And if your CV will be biased due to too little data, at least you will know the model you’ve selected is the right one — even if its cross-validated testing error estimate was far from perfect.
Thanks for reading! I hope you have learned something useful that will benefit your projects 🚀
If you liked this post, try one of my other articles. Can’t choose? Pick one of these:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Hastie, T., Tibshirani, R., & Friedman, J. H. (2009). The elements of statistical learning: data mining, inference, and prediction. 2nd ed. New York: Springer.https://robjhyndman.com/hyndsight/aic/
Hastie, T., Tibshirani, R., & Friedman, J. H. (2009). The elements of statistical learning: data mining, inference, and prediction. 2nd ed. New York: Springer. | [
{
"code": null,
"e": 570,
"s": 47,
"text": "A standard modeling workflow would see you partitioning your data into the training, validation, and testing sets. You would then fit your models to the training data, then use the validation set to perform model selection, and finally, evaluate the very best selected model on the test data to see what generalization performance can be expected of it (model assessment). This flow is presumably your best bet to make sure you have selected the right model and that you won’t be startled once you deploy it to production."
},
{
"code": null,
"e": 895,
"s": 570,
"text": "That being said, one cannot always afford the luxury of setting data aside to form validation and testing sets. If you have very little data, you’d rather use it all for training. In this article, we will discuss methods for selecting and assessing models that let you do exactly this — no validation nor test sets required!"
},
{
"code": null,
"e": 1095,
"s": 895,
"text": "This article is based on a chapter from Hastie, T., Tibshirani, R., & Friedman, J. H. (2009). The elements of statistical learning: data mining, inference, and prediction. 2nd ed. New York: Springer."
},
{
"code": null,
"e": 1553,
"s": 1095,
"text": "While comparing competing models, you would like to pick the one performing best on new, unseen data. That’s what you would normally use the validation set for: validation data are not seen by the model while it’s being fit, so choosing a model that works best for these data is a good strategy. Alas, in our setting you have no validation data to check different models against! To see what to do about it, let’s first introduce a couple of error measures:"
},
{
"code": null,
"e": 1656,
"s": 1553,
"text": "Training error is the error you get when you run the trained model on the same data it was trained on."
},
{
"code": null,
"e": 1767,
"s": 1656,
"text": "Testing (or generalization) error is the error you get when you run your model on completely new, unseen data."
},
{
"code": null,
"e": 2345,
"s": 1767,
"text": "Imagine that after training the model, you observe new values of the response variable for the same values of the features that you had in your training data. For instance, let’s say you are predicting a house’s price based on the number of rooms. In your training data, you had a house worth $300k with 5 rooms, and now you observe a house sold for $350k, also with 5 rooms. The error the model makes on these new data is called the in-sample error (since the values of the features are the same as in the training sample — not the most straightforward of notations, I agree)."
},
{
"code": null,
"e": 2635,
"s": 2345,
"text": "Now, consider this quantity: in-sample error — training error. It is typically positive: the training error is smaller because it is based on the very same data the model was optimized for. But what does it amount to exactly? Well, it can be shown that (up to an expectation) it holds that"
},
{
"code": null,
"e": 2950,
"s": 2635,
"text": "where N is the number of observations and the last term is the covariance between the training set response and its predictions. The larger this covariance, the stronger we fit the model to training data (to the point of overfitting), so the training error goes down, increasing the left-hand side of the equation."
},
{
"code": null,
"e": 3498,
"s": 2950,
"text": "Let’s assume (and this an important assumption) that we are dealing with a model that is linear in its parameters. This means we are talking linear or logistic regression models, non-linear splines, or auto-regressive models, for instance. When that’s the case, then the covariance term above simplifies to d * σε2, where d is a measure of model complexity (number of features in linear regression, number of basis functions in regression splines) and σε2 is the error variance. After substituting this simplification and rearranging terms, we get"
},
{
"code": null,
"e": 4112,
"s": 3498,
"text": "What does this give us? If we could estimate the right-most term, we could then add it to the training error to obtain an estimate of the in-sample error. And the in-sample error is all we need for model selection! Sure, it doesn’t give us information about the models’ generalization performance (that’s the role of model assessment, read on). Also, we don’t really care about the in-sample error’s specific value — it’s rather uncommon to see the same feature values after deployment as in the training data. But the relative magnitude of in-sample errors across different models allows us to pick the best one."
},
{
"code": null,
"e": 4165,
"s": 4112,
"text": "The above formula is also known as the Mallows’s Cp:"
},
{
"code": null,
"e": 4295,
"s": 4165,
"text": "and when the models are fit under squared loss, it can be used for model selection — we simply pick the model with the lowest Cp."
},
{
"code": null,
"e": 4643,
"s": 4295,
"text": "If the models are not necessarily fit under squared loss, we need to adjust Mallows’s Cp slightly. Recall we are discussing models linear in their parameters: think linear or logistic regression, regression splines, or ARIMA models. They are typically estimated by maximum likelihood, and under the Gaussian model, it holds (up to a constant) that"
},
{
"code": null,
"e": 4763,
"s": 4643,
"text": "Solving for e_train and substituting this into the formula for Cp we arrive at the Akaike Information Criterion or AIC:"
},
{
"code": null,
"e": 5400,
"s": 4763,
"text": "The AIC is basically a penalized likelihood. It goes up as the model complexity d increases and goes down as the model’s fit to the data (the loglikelihood) increases, trading-off these two. We pick the model with the lowest AIC. The best thing about it is that even though AIC is computed using only the training data, minimizing it is asymptotically equivalent to minimizing the leave-one-out cross-validation mean squared error, which makes it great for model selection. For more caveats on the AIC (also in the context of time series forecasting) check out this excellent post by Rob Hyndman, the author of the R’s forecast package."
},
{
"code": null,
"e": 5930,
"s": 5400,
"text": "Let us now look at a Python example of model selection with AIC. We will use the infamous Boston housing data from scikit-learn’s datasets. Let’s fit two linear regression models explaining house prices. We will employ the statsmodels package for this, as it conveniently computes the AIC for us. Both models will use the number of rooms and house age as features. Model 1 will use the neighborhood crime rate on top of that, while model 2 will use distance to large employment centers instead. Which of the two models is better?"
},
{
"code": null,
"e": 5991,
"s": 5930,
"text": "Model1 AIC: 3268.8701039911457Model2 AIC: 3300.3758836602733"
},
{
"code": null,
"e": 6105,
"s": 5991,
"text": "As far as the AIC is concerned, Model 1 (the one using the crime rate) is better, as it scores a lower AIC value."
},
{
"code": null,
"e": 6341,
"s": 6105,
"text": "AIC is not the only information criterion. Another one is the BIC, or Bayesian Information Criterion, also known as the Schwarz criterion. Similarly to the AIC, the BIC is also a penalized likelihood, but with a different penalty term:"
},
{
"code": null,
"e": 6476,
"s": 6341,
"text": "This penalty tends to penalize more complex models more heavily than the AIC. Let’s see how our two housing price models score on BIC."
},
{
"code": null,
"e": 6537,
"s": 6476,
"text": "Model1 BIC: 3285.7762506682957Model2 BIC: 3317.2820303374233"
},
{
"code": null,
"e": 6818,
"s": 6537,
"text": "Again, Model 1 is preferred, as it scores a lower BIC. In our examples, both criteria where unanimous, but it does not have to be the case. Which criterion should we then base our model selection on? There is no one-size-fits-all answer, but here are a few things to keep in mind:"
},
{
"code": null,
"e": 7009,
"s": 6818,
"text": "BIC is asymptotically consistent, which means it has a high probability of selecting the true model (the one according to which data were generated) when presented a set of competing models."
},
{
"code": null,
"e": 7110,
"s": 7009,
"text": "AIC does not have the consistency property, but do you believe there is a true model to be selected?"
},
{
"code": null,
"e": 7293,
"s": 7110,
"text": "BIC prefers more parsimonious models. For small data samples, it might end up selecting too simple models. On the other hand, for large samples, AIC tends to choose too complex ones."
},
{
"code": null,
"e": 7542,
"s": 7293,
"text": "Now that we have selected our model to be the one including the crime rate feature, it would be great to know what kind of performance can we expect of it once deployed. That’s the job of model assessment — to estimate the testing error of a model."
},
{
"code": null,
"e": 8036,
"s": 7542,
"text": "One way to do so is via the well-known procedure of cross-validation. We split the data randomly into k subsets, or folds, and then iterate through them, leaving the current fold out and fitting the model the remaining k−1 folds. Then, we evaluate the model’s error on the left-out fold and proceed to the next iteration. This way, we obtain k error estimates. Once averaged, they form the cross-validated estimate of the testing error. Pretty simple, right? But what should be the value of k?"
},
{
"code": null,
"e": 8938,
"s": 8036,
"text": "The choice of k, like so many other choices in machine learning, is between the bias and the variance. Going to the extreme of setting k=N results in the so-called leave-one-out cross-validation. In this setting, each observation constitutes its own fold. As a result, the training sets will be very similar across the folds — indeed, they will only differ by one observation. Consequently, the CV estimate of the testing error might suffer from high variance. On the other hand, when k is small, we risk high bias. This is because the smaller the k, the fewer observations constitute the k−1 training folds. For instance, consider N=100 observations. With k=10, each fold has 10 observations and so each training is based on 90 observations. With k=4, each training uses only 75 observations. If the model performance decreases with less training data, too low k will lead to an over-estimated error."
},
{
"code": null,
"e": 9852,
"s": 8938,
"text": "Ultimately, the choice of k should depend on your application. k=N is rarely a good idea — it’s also quite computationally expensive to run (N models need to be trained)! You know your data best — if you are willing to assume (or have proved) that less data won’t make much of a difference to your model’s performance, then you’re good to go with a small k of say 3 or 5. But that’s probably not the case if you have only little data (should you have big data, you could just follow the standard train/validation/test split and ignore this article). Hence, a slightly larger k of say 10 might be worth a shot. One more thing to consider: if your k will be too small, the error will be over-estimated, meaning that the true testing error is likely to be less than what your CV tells you. If you’re satisfied with the cross-validated error estimate, you’re likely to be even happier with the production performance."
},
{
"code": null,
"e": 9959,
"s": 9852,
"text": "Let’s assess our selected model with 10-fold cross-validation. To do this, we’ll use the scikit-learn API."
},
{
"code": null,
"e": 10007,
"s": 9959,
"text": "Cross-validated testing MSE: 43.925463559757674"
},
{
"code": null,
"e": 10373,
"s": 10007,
"text": "To sum up: what has just happened? In case you don’t have enough data to set aside a validation and a test set, you need other ways to do your model selection and assessment. We have shown what are information criteria and how to use them for model selection, and then how to estimate the expected real-world performance of the selected model with cross-validation."
},
{
"code": null,
"e": 10704,
"s": 10373,
"text": "Why not use CV for model selection, I hear you ask. You could! However, with small data, information criteria tend to be more reliable. And if your CV will be biased due to too little data, at least you will know the model you’ve selected is the right one — even if its cross-validated testing error estimate was far from perfect."
},
{
"code": null,
"e": 10799,
"s": 10704,
"text": "Thanks for reading! I hope you have learned something useful that will benefit your projects 🚀"
},
{
"code": null,
"e": 10886,
"s": 10799,
"text": "If you liked this post, try one of my other articles. Can’t choose? Pick one of these:"
},
{
"code": null,
"e": 10909,
"s": 10886,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10932,
"s": 10909,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10955,
"s": 10932,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11153,
"s": 10955,
"text": "Hastie, T., Tibshirani, R., & Friedman, J. H. (2009). The elements of statistical learning: data mining, inference, and prediction. 2nd ed. New York: Springer.https://robjhyndman.com/hyndsight/aic/"
}
] |
Optimising Disk Usage in Elasticsearch | by Niels D. Goet | Towards Data Science | Elasticsearch (ES) has gained traction in recent years because it offers a robust and scalable engine for storing and analysing large volumes of data with low latency. If you’re a data engineer or data scientist working with large (and fast-growing) volumes of data, you’ll know that optimising for storage is a key component of building high-quality solutions. In this post, I discuss three strategies for optimising disk usage when using ES. Replication code for this blog post is available on GitHub.
Before we start exploring Elasticsearch (ES) storage optimisation, let’s review some ES fundamentals.
If you ask, say, four developers to describe what ES is, you’ll likely get as many different answers. And that’s not surprising: ES can be used as a storage engine, for applying machine learning to model data in real time, and for analysing events and logs, to name but a few applications. Further, ES can work with different data types (both structured and unstructured), while its distributed nature allows it to scale with large volumes of data. It is with reason, therefore, that ES has become the solution of choice for a growing number of companies across a variety of sectors, including the likes of Airbnb, Uber, Walmart, Cisco, and eBay.
To appreciate the power of ES, we need to understand its fundamental principles. Elasticsearch is a distributed search and analytics engine built on top of Lucene. When you set up and deploy an Elasticsearch cluster, you can add different nodes (servers). Both your data and the queries that you run against the data in your ES indices are distributed across those nodes — all done automatically to offer scalability and high availability.
The data in ES is organised in “indices”. Elasticsearch indices are logical groupings of data that follow a schema, but the term also covers the actual physical organisation of the data through shards. Each index consists of a “logical grouping of one or more physical shards”. Each shard, in turn, is a self-contained index.
The data that is stored in ES indices are JSON objects called “documents”. These documents consist of fields (key-value pairs), and are partitioned among “shards”, and the shards are distributed across nodes. Each document belongs to a “primary shard” and to one or multiple “replica shards” (provided you have configured replica shards for your index). As such, Elasticsearch is built for redundancy through a design that consists of nodes and shards, with primary shards and replicas.
In what follows, I’ll focus on three strategies to optimise data storage in ES: i) designing your indices well; ii) optimising your index mapping: and iii) using hot-warm-cold architecture. We’ll be using the netflix_movies index that I set up in my earlier blog post on Elasticsearch. This is a dataset of metadata on Netflix shows available on Kaggle. We’ll optimise this index step by step.
If you’d like to learn more about provisioning an ES cluster and setting up indices, please read my post on Creating and Managing Elasticsearch Indices with Python.
towardsdatascience.com
Before we start, please note that the data used in this blog post contains only 7787 “static” entries and cannot be classified as “Big Data” by any stretch of the imagination. However, the principles discussed in this post can be generalised to Big Data and streaming in general.
First, at risk of stating the obvious: you have to design your Elasticsearch indices well. This starts with deciding what goes into your indices, and more importantly, what does not. For example, do you need to store all your data in Elasticsearch? Or, do you only need to use Elasticsearch as a low-latency store for a subset of your data that needs to be accessible for an application, while the rest of the data can be stored elsewhere? If the answer is yes to the latter question, you can likely identify some “quick wins” easily and remove redundant data.
Once you’ve decided what data needs to be available in Elasticsearch, make sure you define your mappings well. Elasticsearch is able to infer the mapping of your data using dynamic field mapping. This means that ES adds the field type to your mapping dynamically whenever it detects a new field in a document. But that does not mean that it does so in a way that is optimal for data storage or for the purposes that you have in mind.
Dynamic field mapping (when the dynamic parameter is set to true) will for example index string fields as both text and keyword. You’ll typically only need one of these two. The text field type is broken down into individual terms upon indexing and allows for partial matching. Conversely, the keyword type is not analysed (or rather: “tokenized”) when indexing and only allows for exact matching (in our netflix_movies example, we can use the keyword field type for the type field, which takes one of two values — “Movie” or “TV Show”).
To establish a baseline to compare our optimisation strategies against, we’ll first write the Netflix movies data to a new ES index without defining our own mapping, using dynamic field mapping. ES infers the following mapping for our netflix_movies data:
{ "netflix_movies_dynamic_field_mapping": { "mappings": { "properties": { "cast": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "country": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "date_added": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "description": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "director": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "duration": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "listed_in": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "rating": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "release_year": { "type": "long" }, "show_id": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "title": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } }, "type": { "type": "text", "fields": { "keyword": { "type": "keyword", "ignore_above": 256 } } } } } }}
Note that our aim is to reduce the disk usage of our indices, that is, the store.size parameter. This parameter represents the storage size of your primary and replication shards for the index on your cluster. You can inspect the store size of your indices using the CAT indices API in your Kibana console. Using dynamic field mapping, we get a baseline store size of 17.1 MB (see screenshot below).
Can we do any better than our baseline of 17.1 MB by explicitly defining a mapping? Let’s start off with the simple (and unoptimised) mapping from my earlier blog post. We make all fields of the text type with the exception of release_year (which we’ll define as an integer):
The index store size for netflix_movies is 9.3 MB, a reduction of 7.8 MB compared to our baseline mapping (a reduction of nearly 46 perc.).
The second strategy to reduce your indices’ store size involves optimising your mapping. There are several choices you can make to reduce store size when you define a mapping. The tradeoff here is between search capabilities and limiting the size of your indices: typically, the more you optimise for storage, the less flexibility you will have in querying your data.
First, choose the right data types for your fields. In our netflix_movies example, we can make type, country, and rating fields into keyword field types, since these fields can only take on a number of predefined values and we can expect not to have to use partial matches.
Also make sure to check whether your variables can be fit into “smaller” data types. For example, we can reduce the size of release_year further by using the short instead of the integer field type. The short field type is a 16-bit integer. Our improved index looks as follows:
This optimised index gets us down to 8.7mb compared to our baseline of 17.1 MB (a 49.1 percent reduction). This represents a 6.5 percent reduction in disk usage compared to our unoptimised mapping (9.3 MB). However, if you’re working with truly large volumes of data even these small percentages can represent significant savings.
Second, you can disable indexing for fields that you don’t need to filter on. Indexing is the organisation of data for fast retrieval. In ES, text fields are for example stored in an inverted index (i.e.: documents — terms → terms — documents), while numeric field types, for example, are stored in BKD trees.
In our netflix_movies example, potential candidates to exclude from indexing are duration and description. The first is not defined consistently between series and movies (the former is measured in seasons, the latter in minutes). I’d likely further process this data and create a new field instead if I wanted to filter on duration. description, in turn, may be useful for partial matches, but let’s assume (for illustrative purposes) that we’re only interested in identifying movies by their metadata, and read their description afterwards.
To switch off indexing for specific fields, we set the index option to False:
Writing our netflix_movies data with this new mapping produces an index that has a total size of 7.5 MB (a 3.0 percent reduction compared to our previous iteration).
Third, you can drop normalisation factors for text fields if you don’t need the relevance scores. Normalisation factors are stored in the index to use for scoring, that is, the process of attaching a numeric value to the relevance of a document to the query defined by the user. These normalisation factors take up considerable amount of disk space (i.e. a byte per document per field, including for documents that don’t contain the field in question).
Let’s assume we’re not interested in the relevance scores, and that we can drop the normalisation factors for all our text fields. Our updated mapping looks like this (note the addition of “norms”: False):
Removing normalisation factors for all text fields brings us down to 7.3 MB (another 1.2 percent reduction compared to our previous optimisation step).
In summary, for our different optimisation options we see the following index store sizes and disk usage reduction for the netflix_movies data:
A third strategy to optimise disk usage (or rather: to reduce the cost of disk usage) is to use a hot-warm-cold architecture, using index lifecycle management (ILM) and automate index rollover.
The creators of the Elastic (ELK) Stack (that is: Elasticsearch, Kibana, Beats, and Logstash) announced better support for lower-cost cold tiers in November 2020 for their Elasticsearch Service. The official ES Service now supports cold tiers that can live in object stores, including AWS’ Simple Cloud Storage (S3), Google Cloud Storage, Azure Blob Storage, Hadoop Distributed File Store (HDFS), and Shared filesystems such as NFS. Compared to the warm tier, cold storage should cut your cluster storage by up to 50 percent.
The cold tier functionality is part of Elastic’s item lifecycle management, and you can define your own criteria for data transition rules. This means that you can store your older data more cheaply on S3 as “searchable snapshots”, while maintaining query-ability. Search performance should be comparable to searching a regular index.
Using hot-warm-cold architecture with ES involves configuring a lifecycle policy to define hot, warm, and cold phases for your indices. You can for example configure your index to roll over from hot to warm after a set number of days, or after the index has reached a certain size limit. You can repeat this pattern for warm-to-cold rollover.
Lifecycle policies can be configured via the Kibana console. Alternatively, you can use the create or update policy API. The example below defines a policy that rolls over the index and starts writing to a new index if either the data is older than 30 days, or if the index’s size exceeds 20 GB. Subsequently, the policy moves the current index (the one that was rolled over) to the warm phase after 60 days, and to the cold phase after 75 days.
PUT _ilm/policy/netflix_movies_lp{ "policy": { "phases": { "hot": { "actions": { "rollover": { "max_size": "20gb", "max_age": "30d" } } }, "warm": { "min_age": "60d" }, "cold": { "min_age": "75d", "actions": { "searchable_snapshot": { "snapshot_repository": "my-repository" } } }, "delete": { "min_age": "90d", "actions": { "delete": {} } } } }}
In a second step, we can associate the above policy with any document that goes into the netflix_movies index:
PUT _index_template/netflix_movies_template{ "index_patterns": ["netflix_movies"], "data_stream": { }, "template": { "settings": { "number_of_shards": 1, "number_of_replicas": 1, "index.lifecycle.name": "netflix_movies_lp" } }}
Subsequently, any document pushed to the index will be subject to the netflix_movies_lp lifecycle policy, and progressively moved from hot to warm to cold storage.
A final side-note on the topic of ILM and hot-warm-cold architecture: Elastic has announced support for frozen tiers, which will also be powered by searchable snapshots. Data in a frozen tier cannot be changed and is meant for documents that are accessed rarely (further information on Elasticsearch’s data tiers is available here). However, at the time of writing this feature is in an experimental phase and cannot yet be used on the Elasticsearch Service.
There are a bunch of other strategies to optimise for storage in ES that I have not discussed in this post, such as applying the best compression codec, using larger shards, and reducing the number of shards (using the shrink API). Check out some of the links below if you’d like to learn more about any of these options.
Thanks for reading! What other ES storage optimisation strategies have you come across that you’d recommend? Please leave your suggestions in the comments!
Support my work: If you liked this article and you’d like to support my work, please consider becoming a paying Medium member via my referral page. The price of the subscription is the same if you sign up via my referral page, but I will receive part of your monthly membership fee.
If you liked this article, here are some other articles you may enjoy:
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
If you’d like to get into the details of some of the aspects and features of ES described in this post, here is an overview of some of the sources that I’ve found useful, organised by topic (all sources used for this post are linked throughout the text).
A general introduction to ES
On nodes, shards, and indices
On dynamic field mapping
An overview of both disk and data storage optimisation strategies for Elasticsearch, with benchmarks
On optimising disk usage
On automating rollover with ILM
On different available Elasticsearch tiers on Elastic’s Elasticsearch Service
On Elasticsearch Service’s “cold tier” and searchable snapshots
On Elasticsearch Service’s data lifecycle management with data tiers
Disclaimer: “Elasticsearch” and “Kibana” are trademarks of Elasticsearch BV, registered in the U.S. and in other countries. Description and/or use of any third-party services and/or trademarks in this blog post should not be seen as endorsement for or by their respective rights holders.
Please read this disclaimer carefully before relying on any of the content in my articles on Medium.com. | [
{
"code": null,
"e": 551,
"s": 47,
"text": "Elasticsearch (ES) has gained traction in recent years because it offers a robust and scalable engine for storing and analysing large volumes of data with low latency. If you’re a data engineer or data scientist working with large (and fast-growing) volumes of data, you’ll know that optimising for storage is a key component of building high-quality solutions. In this post, I discuss three strategies for optimising disk usage when using ES. Replication code for this blog post is available on GitHub."
},
{
"code": null,
"e": 653,
"s": 551,
"text": "Before we start exploring Elasticsearch (ES) storage optimisation, let’s review some ES fundamentals."
},
{
"code": null,
"e": 1300,
"s": 653,
"text": "If you ask, say, four developers to describe what ES is, you’ll likely get as many different answers. And that’s not surprising: ES can be used as a storage engine, for applying machine learning to model data in real time, and for analysing events and logs, to name but a few applications. Further, ES can work with different data types (both structured and unstructured), while its distributed nature allows it to scale with large volumes of data. It is with reason, therefore, that ES has become the solution of choice for a growing number of companies across a variety of sectors, including the likes of Airbnb, Uber, Walmart, Cisco, and eBay."
},
{
"code": null,
"e": 1740,
"s": 1300,
"text": "To appreciate the power of ES, we need to understand its fundamental principles. Elasticsearch is a distributed search and analytics engine built on top of Lucene. When you set up and deploy an Elasticsearch cluster, you can add different nodes (servers). Both your data and the queries that you run against the data in your ES indices are distributed across those nodes — all done automatically to offer scalability and high availability."
},
{
"code": null,
"e": 2066,
"s": 1740,
"text": "The data in ES is organised in “indices”. Elasticsearch indices are logical groupings of data that follow a schema, but the term also covers the actual physical organisation of the data through shards. Each index consists of a “logical grouping of one or more physical shards”. Each shard, in turn, is a self-contained index."
},
{
"code": null,
"e": 2553,
"s": 2066,
"text": "The data that is stored in ES indices are JSON objects called “documents”. These documents consist of fields (key-value pairs), and are partitioned among “shards”, and the shards are distributed across nodes. Each document belongs to a “primary shard” and to one or multiple “replica shards” (provided you have configured replica shards for your index). As such, Elasticsearch is built for redundancy through a design that consists of nodes and shards, with primary shards and replicas."
},
{
"code": null,
"e": 2947,
"s": 2553,
"text": "In what follows, I’ll focus on three strategies to optimise data storage in ES: i) designing your indices well; ii) optimising your index mapping: and iii) using hot-warm-cold architecture. We’ll be using the netflix_movies index that I set up in my earlier blog post on Elasticsearch. This is a dataset of metadata on Netflix shows available on Kaggle. We’ll optimise this index step by step."
},
{
"code": null,
"e": 3112,
"s": 2947,
"text": "If you’d like to learn more about provisioning an ES cluster and setting up indices, please read my post on Creating and Managing Elasticsearch Indices with Python."
},
{
"code": null,
"e": 3135,
"s": 3112,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3415,
"s": 3135,
"text": "Before we start, please note that the data used in this blog post contains only 7787 “static” entries and cannot be classified as “Big Data” by any stretch of the imagination. However, the principles discussed in this post can be generalised to Big Data and streaming in general."
},
{
"code": null,
"e": 3976,
"s": 3415,
"text": "First, at risk of stating the obvious: you have to design your Elasticsearch indices well. This starts with deciding what goes into your indices, and more importantly, what does not. For example, do you need to store all your data in Elasticsearch? Or, do you only need to use Elasticsearch as a low-latency store for a subset of your data that needs to be accessible for an application, while the rest of the data can be stored elsewhere? If the answer is yes to the latter question, you can likely identify some “quick wins” easily and remove redundant data."
},
{
"code": null,
"e": 4410,
"s": 3976,
"text": "Once you’ve decided what data needs to be available in Elasticsearch, make sure you define your mappings well. Elasticsearch is able to infer the mapping of your data using dynamic field mapping. This means that ES adds the field type to your mapping dynamically whenever it detects a new field in a document. But that does not mean that it does so in a way that is optimal for data storage or for the purposes that you have in mind."
},
{
"code": null,
"e": 4948,
"s": 4410,
"text": "Dynamic field mapping (when the dynamic parameter is set to true) will for example index string fields as both text and keyword. You’ll typically only need one of these two. The text field type is broken down into individual terms upon indexing and allows for partial matching. Conversely, the keyword type is not analysed (or rather: “tokenized”) when indexing and only allows for exact matching (in our netflix_movies example, we can use the keyword field type for the type field, which takes one of two values — “Movie” or “TV Show”)."
},
{
"code": null,
"e": 5204,
"s": 4948,
"text": "To establish a baseline to compare our optimisation strategies against, we’ll first write the Netflix movies data to a new ES index without defining our own mapping, using dynamic field mapping. ES infers the following mapping for our netflix_movies data:"
},
{
"code": null,
"e": 6878,
"s": 5204,
"text": "{ \"netflix_movies_dynamic_field_mapping\": { \"mappings\": { \"properties\": { \"cast\": { \"type\": \"text\", \"fields\": { \"keyword\": { \"type\": \"keyword\", \"ignore_above\": 256 } } }, \"country\": { \"type\": \"text\", \"fields\": { \"keyword\": { \"type\": \"keyword\", \"ignore_above\": 256 } } }, \"date_added\": { \"type\": \"text\", \"fields\": { \"keyword\": { \"type\": \"keyword\", \"ignore_above\": 256 } } }, \"description\": { \"type\": \"text\", \"fields\": { \"keyword\": { \"type\": \"keyword\", \"ignore_above\": 256 } } }, \"director\": { \"type\": \"text\", \"fields\": { \"keyword\": { \"type\": \"keyword\", \"ignore_above\": 256 } } }, \"duration\": { \"type\": \"text\", \"fields\": { \"keyword\": { \"type\": \"keyword\", \"ignore_above\": 256 } } }, \"listed_in\": { \"type\": \"text\", \"fields\": { \"keyword\": { \"type\": \"keyword\", \"ignore_above\": 256 } } }, \"rating\": { \"type\": \"text\", \"fields\": { \"keyword\": { \"type\": \"keyword\", \"ignore_above\": 256 } } }, \"release_year\": { \"type\": \"long\" }, \"show_id\": { \"type\": \"text\", \"fields\": { \"keyword\": { \"type\": \"keyword\", \"ignore_above\": 256 } } }, \"title\": { \"type\": \"text\", \"fields\": { \"keyword\": { \"type\": \"keyword\", \"ignore_above\": 256 } } }, \"type\": { \"type\": \"text\", \"fields\": { \"keyword\": { \"type\": \"keyword\", \"ignore_above\": 256 } } } } } }}"
},
{
"code": null,
"e": 7278,
"s": 6878,
"text": "Note that our aim is to reduce the disk usage of our indices, that is, the store.size parameter. This parameter represents the storage size of your primary and replication shards for the index on your cluster. You can inspect the store size of your indices using the CAT indices API in your Kibana console. Using dynamic field mapping, we get a baseline store size of 17.1 MB (see screenshot below)."
},
{
"code": null,
"e": 7554,
"s": 7278,
"text": "Can we do any better than our baseline of 17.1 MB by explicitly defining a mapping? Let’s start off with the simple (and unoptimised) mapping from my earlier blog post. We make all fields of the text type with the exception of release_year (which we’ll define as an integer):"
},
{
"code": null,
"e": 7694,
"s": 7554,
"text": "The index store size for netflix_movies is 9.3 MB, a reduction of 7.8 MB compared to our baseline mapping (a reduction of nearly 46 perc.)."
},
{
"code": null,
"e": 8062,
"s": 7694,
"text": "The second strategy to reduce your indices’ store size involves optimising your mapping. There are several choices you can make to reduce store size when you define a mapping. The tradeoff here is between search capabilities and limiting the size of your indices: typically, the more you optimise for storage, the less flexibility you will have in querying your data."
},
{
"code": null,
"e": 8336,
"s": 8062,
"text": "First, choose the right data types for your fields. In our netflix_movies example, we can make type, country, and rating fields into keyword field types, since these fields can only take on a number of predefined values and we can expect not to have to use partial matches."
},
{
"code": null,
"e": 8614,
"s": 8336,
"text": "Also make sure to check whether your variables can be fit into “smaller” data types. For example, we can reduce the size of release_year further by using the short instead of the integer field type. The short field type is a 16-bit integer. Our improved index looks as follows:"
},
{
"code": null,
"e": 8945,
"s": 8614,
"text": "This optimised index gets us down to 8.7mb compared to our baseline of 17.1 MB (a 49.1 percent reduction). This represents a 6.5 percent reduction in disk usage compared to our unoptimised mapping (9.3 MB). However, if you’re working with truly large volumes of data even these small percentages can represent significant savings."
},
{
"code": null,
"e": 9255,
"s": 8945,
"text": "Second, you can disable indexing for fields that you don’t need to filter on. Indexing is the organisation of data for fast retrieval. In ES, text fields are for example stored in an inverted index (i.e.: documents — terms → terms — documents), while numeric field types, for example, are stored in BKD trees."
},
{
"code": null,
"e": 9798,
"s": 9255,
"text": "In our netflix_movies example, potential candidates to exclude from indexing are duration and description. The first is not defined consistently between series and movies (the former is measured in seasons, the latter in minutes). I’d likely further process this data and create a new field instead if I wanted to filter on duration. description, in turn, may be useful for partial matches, but let’s assume (for illustrative purposes) that we’re only interested in identifying movies by their metadata, and read their description afterwards."
},
{
"code": null,
"e": 9876,
"s": 9798,
"text": "To switch off indexing for specific fields, we set the index option to False:"
},
{
"code": null,
"e": 10042,
"s": 9876,
"text": "Writing our netflix_movies data with this new mapping produces an index that has a total size of 7.5 MB (a 3.0 percent reduction compared to our previous iteration)."
},
{
"code": null,
"e": 10495,
"s": 10042,
"text": "Third, you can drop normalisation factors for text fields if you don’t need the relevance scores. Normalisation factors are stored in the index to use for scoring, that is, the process of attaching a numeric value to the relevance of a document to the query defined by the user. These normalisation factors take up considerable amount of disk space (i.e. a byte per document per field, including for documents that don’t contain the field in question)."
},
{
"code": null,
"e": 10701,
"s": 10495,
"text": "Let’s assume we’re not interested in the relevance scores, and that we can drop the normalisation factors for all our text fields. Our updated mapping looks like this (note the addition of “norms”: False):"
},
{
"code": null,
"e": 10853,
"s": 10701,
"text": "Removing normalisation factors for all text fields brings us down to 7.3 MB (another 1.2 percent reduction compared to our previous optimisation step)."
},
{
"code": null,
"e": 10997,
"s": 10853,
"text": "In summary, for our different optimisation options we see the following index store sizes and disk usage reduction for the netflix_movies data:"
},
{
"code": null,
"e": 11191,
"s": 10997,
"text": "A third strategy to optimise disk usage (or rather: to reduce the cost of disk usage) is to use a hot-warm-cold architecture, using index lifecycle management (ILM) and automate index rollover."
},
{
"code": null,
"e": 11717,
"s": 11191,
"text": "The creators of the Elastic (ELK) Stack (that is: Elasticsearch, Kibana, Beats, and Logstash) announced better support for lower-cost cold tiers in November 2020 for their Elasticsearch Service. The official ES Service now supports cold tiers that can live in object stores, including AWS’ Simple Cloud Storage (S3), Google Cloud Storage, Azure Blob Storage, Hadoop Distributed File Store (HDFS), and Shared filesystems such as NFS. Compared to the warm tier, cold storage should cut your cluster storage by up to 50 percent."
},
{
"code": null,
"e": 12052,
"s": 11717,
"text": "The cold tier functionality is part of Elastic’s item lifecycle management, and you can define your own criteria for data transition rules. This means that you can store your older data more cheaply on S3 as “searchable snapshots”, while maintaining query-ability. Search performance should be comparable to searching a regular index."
},
{
"code": null,
"e": 12395,
"s": 12052,
"text": "Using hot-warm-cold architecture with ES involves configuring a lifecycle policy to define hot, warm, and cold phases for your indices. You can for example configure your index to roll over from hot to warm after a set number of days, or after the index has reached a certain size limit. You can repeat this pattern for warm-to-cold rollover."
},
{
"code": null,
"e": 12841,
"s": 12395,
"text": "Lifecycle policies can be configured via the Kibana console. Alternatively, you can use the create or update policy API. The example below defines a policy that rolls over the index and starts writing to a new index if either the data is older than 30 days, or if the index’s size exceeds 20 GB. Subsequently, the policy moves the current index (the one that was rolled over) to the warm phase after 60 days, and to the cold phase after 75 days."
},
{
"code": null,
"e": 13376,
"s": 12841,
"text": "PUT _ilm/policy/netflix_movies_lp{ \"policy\": { \"phases\": { \"hot\": { \"actions\": { \"rollover\": { \"max_size\": \"20gb\", \"max_age\": \"30d\" } } }, \"warm\": { \"min_age\": \"60d\" }, \"cold\": { \"min_age\": \"75d\", \"actions\": { \"searchable_snapshot\": { \"snapshot_repository\": \"my-repository\" } } }, \"delete\": { \"min_age\": \"90d\", \"actions\": { \"delete\": {} } } } }}"
},
{
"code": null,
"e": 13487,
"s": 13376,
"text": "In a second step, we can associate the above policy with any document that goes into the netflix_movies index:"
},
{
"code": null,
"e": 13764,
"s": 13487,
"text": "PUT _index_template/netflix_movies_template{ \"index_patterns\": [\"netflix_movies\"], \"data_stream\": { }, \"template\": { \"settings\": { \"number_of_shards\": 1, \"number_of_replicas\": 1, \"index.lifecycle.name\": \"netflix_movies_lp\" } }}"
},
{
"code": null,
"e": 13928,
"s": 13764,
"text": "Subsequently, any document pushed to the index will be subject to the netflix_movies_lp lifecycle policy, and progressively moved from hot to warm to cold storage."
},
{
"code": null,
"e": 14387,
"s": 13928,
"text": "A final side-note on the topic of ILM and hot-warm-cold architecture: Elastic has announced support for frozen tiers, which will also be powered by searchable snapshots. Data in a frozen tier cannot be changed and is meant for documents that are accessed rarely (further information on Elasticsearch’s data tiers is available here). However, at the time of writing this feature is in an experimental phase and cannot yet be used on the Elasticsearch Service."
},
{
"code": null,
"e": 14709,
"s": 14387,
"text": "There are a bunch of other strategies to optimise for storage in ES that I have not discussed in this post, such as applying the best compression codec, using larger shards, and reducing the number of shards (using the shrink API). Check out some of the links below if you’d like to learn more about any of these options."
},
{
"code": null,
"e": 14865,
"s": 14709,
"text": "Thanks for reading! What other ES storage optimisation strategies have you come across that you’d recommend? Please leave your suggestions in the comments!"
},
{
"code": null,
"e": 15148,
"s": 14865,
"text": "Support my work: If you liked this article and you’d like to support my work, please consider becoming a paying Medium member via my referral page. The price of the subscription is the same if you sign up via my referral page, but I will receive part of your monthly membership fee."
},
{
"code": null,
"e": 15219,
"s": 15148,
"text": "If you liked this article, here are some other articles you may enjoy:"
},
{
"code": null,
"e": 15242,
"s": 15219,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 15265,
"s": 15242,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 15288,
"s": 15265,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 15311,
"s": 15288,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 15566,
"s": 15311,
"text": "If you’d like to get into the details of some of the aspects and features of ES described in this post, here is an overview of some of the sources that I’ve found useful, organised by topic (all sources used for this post are linked throughout the text)."
},
{
"code": null,
"e": 15595,
"s": 15566,
"text": "A general introduction to ES"
},
{
"code": null,
"e": 15625,
"s": 15595,
"text": "On nodes, shards, and indices"
},
{
"code": null,
"e": 15650,
"s": 15625,
"text": "On dynamic field mapping"
},
{
"code": null,
"e": 15751,
"s": 15650,
"text": "An overview of both disk and data storage optimisation strategies for Elasticsearch, with benchmarks"
},
{
"code": null,
"e": 15776,
"s": 15751,
"text": "On optimising disk usage"
},
{
"code": null,
"e": 15808,
"s": 15776,
"text": "On automating rollover with ILM"
},
{
"code": null,
"e": 15886,
"s": 15808,
"text": "On different available Elasticsearch tiers on Elastic’s Elasticsearch Service"
},
{
"code": null,
"e": 15950,
"s": 15886,
"text": "On Elasticsearch Service’s “cold tier” and searchable snapshots"
},
{
"code": null,
"e": 16019,
"s": 15950,
"text": "On Elasticsearch Service’s data lifecycle management with data tiers"
},
{
"code": null,
"e": 16307,
"s": 16019,
"text": "Disclaimer: “Elasticsearch” and “Kibana” are trademarks of Elasticsearch BV, registered in the U.S. and in other countries. Description and/or use of any third-party services and/or trademarks in this blog post should not be seen as endorsement for or by their respective rights holders."
}
] |
KnockoutJS - checked Binding | This binding is used to create a link between a checkable form element and ViewModel property. Mostly these form elements are inclusive of check box and radio buttons. This is also a two-way binding method wherein the moment the user checks form control, the respective ViewModel property is changed and vice versa.
checked: <binding-value>
The checkable element's state is set to parameter value. Earlier the value will be overwritten.
The checkable element's state is set to parameter value. Earlier the value will be overwritten.
Checkbox − The DOM element is checked when the ViewModel parameter value is true and is unchecked if it is false. Non-zero numbers, non-empty string, and non-null objects are interpreted at true Boolean value, whereas undefined, zero, and empty strings are considered as false value.
Checkbox − The DOM element is checked when the ViewModel parameter value is true and is unchecked if it is false. Non-zero numbers, non-empty string, and non-null objects are interpreted at true Boolean value, whereas undefined, zero, and empty strings are considered as false value.
Radio Buttons − Radio buttons work in a form of a String format. Meaning, KnockoutJS will set the elements value only when the parameter value matches exactly with Radio Button node's value. The property is set with the new value the moment the user selects a new Radio button value.
Radio Buttons − Radio buttons work in a form of a String format. Meaning, KnockoutJS will set the elements value only when the parameter value matches exactly with Radio Button node's value. The property is set with the new value the moment the user selects a new Radio button value.
If the parameter is an observable, then elements value is checked or unchecked as and when the underlying observable is changed. Element is processed only once if no observable is used.
If the parameter is an observable, then elements value is checked or unchecked as and when the underlying observable is changed. Element is processed only once if no observable is used.
checkedValue − checkedValue option is used to hold the value used by the checkedbinding instead of the element's value attribute. This is very useful when the checked value is something other than a String (like an Integer or an object).
checkedValue − checkedValue option is used to hold the value used by the checkedbinding instead of the element's value attribute. This is very useful when the checked value is something other than a String (like an Integer or an object).
For example, take a look at the following code snippet where the item object themselves are included into chosenValue array, when the respective checkboxes are checked.
<!-- ko foreach: items -->
<input type = "checkbox" data-bind = "checkedValue: $data,
checked: $root.chosenValue" />
<span data-bind = "text: itemName"></span>
<!-- /ko -->
<script type = "text/javascript">
var viewModel = {
itemsToBeSeen: ko.observableArray ([
{ itemName: 'Item Number One' },
{ itemName: 'Item Number Two' }
]),
chosenValue: ko.observableArray()
};
</script>
If the checkedValue parameter is an Observable value, then the binding will update the checked model property whenever the underlying value changes. For radio buttons, KO will just update the model value. For checkboxes, it will replace the old value with the new value.
Let us take a look at the following example which demonstrates the use of checkbox control.
<!DOCTYPE html>
<head>
<title>KnockoutJS Checked checkbox Binding</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<p> The required files are installed.
Please check below to complete installation</p>
<p><input type = "checkbox" data-bind = "checked: agreeFlag" />
I agree to all terms and conditions applied.</p>
<button data-bind = "enable: agreeFlag">Finish</button>
<script type = "text/javascript">
function ViewModel() {
this.agreeFlag = ko.observable(false) // Initially unchecked
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Let's carry out the following steps to see how the above code works −
Save the above code in checked-checkbox-bind.htm file.
Save the above code in checked-checkbox-bind.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
The Finish button is activated only when the user agrees with the terms and conditions.
The Finish button is activated only when the user agrees with the terms and conditions.
The required files are installed. Please check below to complete installation
I agree to all terms and conditions applied.
Let us see below example which demonstrates use of radio-button control −
<!DOCTYPE html>
<head>
<title>KnockoutJS Checked Radio Button Binding</title>
<script src = "https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js"
type = "text/javascript"></script>
</head>
<body>
<p> Select gender type from below:</p>
<div><input type = "radio" name = "gender" value = "Male"
data-bind = "checked: checkGender" /> Male</div>
<div><input type = "radio" name = "gender" value = "Female"
data-bind = "checked: checkGender" /> Female</div>
<div><p>You have selected: <span
data-bind = "text:checkGender "></span></p></div>
<script type = "text/javascript">
function ViewModel () {
checkGender = ko.observable("Male") // Initially male is selected
};
var vm = new ViewModel();
ko.applyBindings(vm);
</script>
</body>
</html>
Let's carry out the following steps to see how the above code works −
Save the above code in checked-radio-button-bind.htm file.
Save the above code in checked-radio-button-bind.htm file.
Open this HTML file in a browser.
Open this HTML file in a browser.
The radio button holds the gender type value.
The radio button holds the gender type value.
Select gender type from below −
You have selected: Male
38 Lectures
2 hours
Skillbakerystudios
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2168,
"s": 1852,
"text": "This binding is used to create a link between a checkable form element and ViewModel property. Mostly these form elements are inclusive of check box and radio buttons. This is also a two-way binding method wherein the moment the user checks form control, the respective ViewModel property is changed and vice versa."
},
{
"code": null,
"e": 2194,
"s": 2168,
"text": "checked: <binding-value>\n"
},
{
"code": null,
"e": 2290,
"s": 2194,
"text": "The checkable element's state is set to parameter value. Earlier the value will be overwritten."
},
{
"code": null,
"e": 2386,
"s": 2290,
"text": "The checkable element's state is set to parameter value. Earlier the value will be overwritten."
},
{
"code": null,
"e": 2670,
"s": 2386,
"text": "Checkbox − The DOM element is checked when the ViewModel parameter value is true and is unchecked if it is false. Non-zero numbers, non-empty string, and non-null objects are interpreted at true Boolean value, whereas undefined, zero, and empty strings are considered as false value."
},
{
"code": null,
"e": 2954,
"s": 2670,
"text": "Checkbox − The DOM element is checked when the ViewModel parameter value is true and is unchecked if it is false. Non-zero numbers, non-empty string, and non-null objects are interpreted at true Boolean value, whereas undefined, zero, and empty strings are considered as false value."
},
{
"code": null,
"e": 3238,
"s": 2954,
"text": "Radio Buttons − Radio buttons work in a form of a String format. Meaning, KnockoutJS will set the elements value only when the parameter value matches exactly with Radio Button node's value. The property is set with the new value the moment the user selects a new Radio button value."
},
{
"code": null,
"e": 3522,
"s": 3238,
"text": "Radio Buttons − Radio buttons work in a form of a String format. Meaning, KnockoutJS will set the elements value only when the parameter value matches exactly with Radio Button node's value. The property is set with the new value the moment the user selects a new Radio button value."
},
{
"code": null,
"e": 3708,
"s": 3522,
"text": "If the parameter is an observable, then elements value is checked or unchecked as and when the underlying observable is changed. Element is processed only once if no observable is used."
},
{
"code": null,
"e": 3894,
"s": 3708,
"text": "If the parameter is an observable, then elements value is checked or unchecked as and when the underlying observable is changed. Element is processed only once if no observable is used."
},
{
"code": null,
"e": 4132,
"s": 3894,
"text": "checkedValue − checkedValue option is used to hold the value used by the checkedbinding instead of the element's value attribute. This is very useful when the checked value is something other than a String (like an Integer or an object)."
},
{
"code": null,
"e": 4370,
"s": 4132,
"text": "checkedValue − checkedValue option is used to hold the value used by the checkedbinding instead of the element's value attribute. This is very useful when the checked value is something other than a String (like an Integer or an object)."
},
{
"code": null,
"e": 4539,
"s": 4370,
"text": "For example, take a look at the following code snippet where the item object themselves are included into chosenValue array, when the respective checkboxes are checked."
},
{
"code": null,
"e": 4987,
"s": 4539,
"text": "<!-- ko foreach: items -->\n <input type = \"checkbox\" data-bind = \"checkedValue: $data, \n checked: $root.chosenValue\" />\n <span data-bind = \"text: itemName\"></span>\n<!-- /ko -->\n\n<script type = \"text/javascript\">\n var viewModel = {\n \n itemsToBeSeen: ko.observableArray ([\n { itemName: 'Item Number One' },\n { itemName: 'Item Number Two' }\n ]),\n \n chosenValue: ko.observableArray()\n };\n</script>"
},
{
"code": null,
"e": 5258,
"s": 4987,
"text": "If the checkedValue parameter is an Observable value, then the binding will update the checked model property whenever the underlying value changes. For radio buttons, KO will just update the model value. For checkboxes, it will replace the old value with the new value."
},
{
"code": null,
"e": 5350,
"s": 5258,
"text": "Let us take a look at the following example which demonstrates the use of checkbox control."
},
{
"code": null,
"e": 6154,
"s": 5350,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Checked checkbox Binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <p> The required files are installed. \n Please check below to complete installation</p>\n \n <p><input type = \"checkbox\" data-bind = \"checked: agreeFlag\" />\n I agree to all terms and conditions applied.</p>\n \n <button data-bind = \"enable: agreeFlag\">Finish</button>\n\n <script type = \"text/javascript\">\n function ViewModel() {\n this.agreeFlag = ko.observable(false) // Initially unchecked\n };\n\n var vm = new ViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 6224,
"s": 6154,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 6279,
"s": 6224,
"text": "Save the above code in checked-checkbox-bind.htm file."
},
{
"code": null,
"e": 6334,
"s": 6279,
"text": "Save the above code in checked-checkbox-bind.htm file."
},
{
"code": null,
"e": 6368,
"s": 6334,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 6402,
"s": 6368,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 6490,
"s": 6402,
"text": "The Finish button is activated only when the user agrees with the terms and conditions."
},
{
"code": null,
"e": 6578,
"s": 6490,
"text": "The Finish button is activated only when the user agrees with the terms and conditions."
},
{
"code": null,
"e": 6658,
"s": 6578,
"text": " The required files are installed. Please check below to complete installation "
},
{
"code": null,
"e": 6703,
"s": 6658,
"text": "I agree to all terms and conditions applied."
},
{
"code": null,
"e": 6777,
"s": 6703,
"text": "Let us see below example which demonstrates use of radio-button control −"
},
{
"code": null,
"e": 7703,
"s": 6777,
"text": "<!DOCTYPE html>\n <head>\n <title>KnockoutJS Checked Radio Button Binding</title>\n <script src = \"https://ajax.aspnetcdn.com/ajax/knockout/knockout-3.3.0.js\"\n type = \"text/javascript\"></script>\n </head>\n\n <body>\n <p> Select gender type from below:</p>\n <div><input type = \"radio\" name = \"gender\" value = \"Male\" \n data-bind = \"checked: checkGender\" /> Male</div>\n \n <div><input type = \"radio\" name = \"gender\" value = \"Female\" \n data-bind = \"checked: checkGender\" /> Female</div>\n \n <div><p>You have selected: <span \n data-bind = \"text:checkGender \"></span></p></div>\n\n <script type = \"text/javascript\">\n function ViewModel () {\n checkGender = ko.observable(\"Male\") // Initially male is selected\n };\n\n var vm = new ViewModel();\n ko.applyBindings(vm);\n </script>\n \n </body>\n</html>"
},
{
"code": null,
"e": 7773,
"s": 7703,
"text": "Let's carry out the following steps to see how the above code works −"
},
{
"code": null,
"e": 7832,
"s": 7773,
"text": "Save the above code in checked-radio-button-bind.htm file."
},
{
"code": null,
"e": 7891,
"s": 7832,
"text": "Save the above code in checked-radio-button-bind.htm file."
},
{
"code": null,
"e": 7925,
"s": 7891,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 7959,
"s": 7925,
"text": "Open this HTML file in a browser."
},
{
"code": null,
"e": 8005,
"s": 7959,
"text": "The radio button holds the gender type value."
},
{
"code": null,
"e": 8051,
"s": 8005,
"text": "The radio button holds the gender type value."
},
{
"code": null,
"e": 8084,
"s": 8051,
"text": " Select gender type from below −"
},
{
"code": null,
"e": 8108,
"s": 8084,
"text": "You have selected: Male"
},
{
"code": null,
"e": 8141,
"s": 8108,
"text": "\n 38 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 8161,
"s": 8141,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 8168,
"s": 8161,
"text": " Print"
},
{
"code": null,
"e": 8179,
"s": 8168,
"text": " Add Notes"
}
] |
Tryit Editor v3.7 | Tryit: Use CSS and JavaScript to show an element on click | [] |
Image Classification using Fastai v2 on Colab | by C K | Towards Data Science | Fastai is a library built on top of PyTorch for deep learning applications. Their mission is to make deep learning easier to use and getting more people from all backgrounds involved. They also provide free courses for Fastai.
Fastai v2 was released in August, I will use it to build and train a deep learning model to classify different sports fields on Colab in just a few lines of codes.
First, I need to collect images for the model to learn. I wish to have a model classifying different sports fields: baseball, basketball, soccer, tennis, and American football. I searched and downloaded the images and saved them in separate folders and uploaded to Google Drive.
Once the dataset is ready, I can start the work on Colab.
First upgrade fastai,
!pip install fastai --upgrade -q
and import fastai.vision,
from fastai.vision.all import *
then mount the Google Drive and setup the path
from google.colab import drivedrive.mount(‘/content/gdrive’, force_remount=True)root_dir = ‘gdrive/My Drive/Colab Notebooks/’base_dir = root_dir + ‘ball_class’path=Path(base_dir)
Now we are ready to go.
Fastai provide a mid-level API: DataBlock to deal with data, it is quite easy to use.
fields = DataBlock(blocks=(ImageBlock, CategoryBlock), get_items=get_image_files, get_y=parent_label, splitter=RandomSplitter(valid_pct=0.2, seed=42), item_tfms=RandomResizedCrop(224, min_scale=0.5), batch_tfms=aug_transforms())
Different blocks can be used, in this case, we used ImageBlock as the x and CategoryBlock as the label. It is also possible to use other blocks such as MultiCategoryBlock, MaskBlock, PointBlock, BBoxBlock, BBoxLblBlock for different applications.
I used get_image_files function in fastai to get the path of the images as the x and used parent_label method to find the folder names as the label. There are some built-in functions in fastai, you can also write your own function to do this.
Then I used RandomSplitter to split the training and validation dataset.
Then used RandomResizedCrop to resize the image to 224 and aug_transforms() for data augmentation.
This is kind of a template of Fastai DataBlock, it is quite flexible, you can change it based on your situation. You can find the detailed tutorial here.
Once we have the DataBlock ready, we can create dataloader:
and check the labels using vocab
and show some of the images with lables
Now we are ready for training.
I created a CNN learner using resnet34:
learn = cnn_learner(dls, resnet34, metrics=error_rate)
and used lr_find() to find a suitable learning rate
then we can train the model using fit_one_cycle
Only after 5 epochs, we can achieve >90% accuracy.
Now we can unfreeze the network and train the whole network.
Let’s it, only after a few epochs, we achieve 95% accuracy.
We can also interpret the model. The confusion matrix can be plotted using this :
We can also use this to see the image with the highest loss.
This article shows a simple and quick example of image classification using fastai. It is possible to create more complicated and interesting applications using this powerful library.
Thanks for reading, happy coding. | [
{
"code": null,
"e": 399,
"s": 172,
"text": "Fastai is a library built on top of PyTorch for deep learning applications. Their mission is to make deep learning easier to use and getting more people from all backgrounds involved. They also provide free courses for Fastai."
},
{
"code": null,
"e": 563,
"s": 399,
"text": "Fastai v2 was released in August, I will use it to build and train a deep learning model to classify different sports fields on Colab in just a few lines of codes."
},
{
"code": null,
"e": 842,
"s": 563,
"text": "First, I need to collect images for the model to learn. I wish to have a model classifying different sports fields: baseball, basketball, soccer, tennis, and American football. I searched and downloaded the images and saved them in separate folders and uploaded to Google Drive."
},
{
"code": null,
"e": 900,
"s": 842,
"text": "Once the dataset is ready, I can start the work on Colab."
},
{
"code": null,
"e": 922,
"s": 900,
"text": "First upgrade fastai,"
},
{
"code": null,
"e": 955,
"s": 922,
"text": "!pip install fastai --upgrade -q"
},
{
"code": null,
"e": 981,
"s": 955,
"text": "and import fastai.vision,"
},
{
"code": null,
"e": 1013,
"s": 981,
"text": "from fastai.vision.all import *"
},
{
"code": null,
"e": 1060,
"s": 1013,
"text": "then mount the Google Drive and setup the path"
},
{
"code": null,
"e": 1239,
"s": 1060,
"text": "from google.colab import drivedrive.mount(‘/content/gdrive’, force_remount=True)root_dir = ‘gdrive/My Drive/Colab Notebooks/’base_dir = root_dir + ‘ball_class’path=Path(base_dir)"
},
{
"code": null,
"e": 1263,
"s": 1239,
"text": "Now we are ready to go."
},
{
"code": null,
"e": 1349,
"s": 1263,
"text": "Fastai provide a mid-level API: DataBlock to deal with data, it is quite easy to use."
},
{
"code": null,
"e": 1588,
"s": 1349,
"text": "fields = DataBlock(blocks=(ImageBlock, CategoryBlock), get_items=get_image_files, get_y=parent_label, splitter=RandomSplitter(valid_pct=0.2, seed=42), item_tfms=RandomResizedCrop(224, min_scale=0.5), batch_tfms=aug_transforms())"
},
{
"code": null,
"e": 1835,
"s": 1588,
"text": "Different blocks can be used, in this case, we used ImageBlock as the x and CategoryBlock as the label. It is also possible to use other blocks such as MultiCategoryBlock, MaskBlock, PointBlock, BBoxBlock, BBoxLblBlock for different applications."
},
{
"code": null,
"e": 2078,
"s": 1835,
"text": "I used get_image_files function in fastai to get the path of the images as the x and used parent_label method to find the folder names as the label. There are some built-in functions in fastai, you can also write your own function to do this."
},
{
"code": null,
"e": 2151,
"s": 2078,
"text": "Then I used RandomSplitter to split the training and validation dataset."
},
{
"code": null,
"e": 2250,
"s": 2151,
"text": "Then used RandomResizedCrop to resize the image to 224 and aug_transforms() for data augmentation."
},
{
"code": null,
"e": 2404,
"s": 2250,
"text": "This is kind of a template of Fastai DataBlock, it is quite flexible, you can change it based on your situation. You can find the detailed tutorial here."
},
{
"code": null,
"e": 2464,
"s": 2404,
"text": "Once we have the DataBlock ready, we can create dataloader:"
},
{
"code": null,
"e": 2497,
"s": 2464,
"text": "and check the labels using vocab"
},
{
"code": null,
"e": 2537,
"s": 2497,
"text": "and show some of the images with lables"
},
{
"code": null,
"e": 2568,
"s": 2537,
"text": "Now we are ready for training."
},
{
"code": null,
"e": 2608,
"s": 2568,
"text": "I created a CNN learner using resnet34:"
},
{
"code": null,
"e": 2663,
"s": 2608,
"text": "learn = cnn_learner(dls, resnet34, metrics=error_rate)"
},
{
"code": null,
"e": 2715,
"s": 2663,
"text": "and used lr_find() to find a suitable learning rate"
},
{
"code": null,
"e": 2763,
"s": 2715,
"text": "then we can train the model using fit_one_cycle"
},
{
"code": null,
"e": 2814,
"s": 2763,
"text": "Only after 5 epochs, we can achieve >90% accuracy."
},
{
"code": null,
"e": 2875,
"s": 2814,
"text": "Now we can unfreeze the network and train the whole network."
},
{
"code": null,
"e": 2935,
"s": 2875,
"text": "Let’s it, only after a few epochs, we achieve 95% accuracy."
},
{
"code": null,
"e": 3017,
"s": 2935,
"text": "We can also interpret the model. The confusion matrix can be plotted using this :"
},
{
"code": null,
"e": 3078,
"s": 3017,
"text": "We can also use this to see the image with the highest loss."
},
{
"code": null,
"e": 3262,
"s": 3078,
"text": "This article shows a simple and quick example of image classification using fastai. It is possible to create more complicated and interesting applications using this powerful library."
}
] |
Bootstrapping for Inferential Statistics | by Samarth Agrawal | Towards Data Science | Bootstrap is a powerful, computer-based method for statistical inference without relying on too many assumption. It’s just magical to form a sampling distribution just from only one sample data. No formula needed for my statistical inference. Not only that, in fact, it is widely applied in other statistical inference such as confidence interval, regression model, even the field of machine learning.
In this article we will primarily talk about two things
Building Confidence IntervalsHypothesis Testing
Building Confidence Intervals
Hypothesis Testing
Link to the github for the code and dataset.
In real world — we don’t really know about our true population. For that it could be the entire population of planet or past, present and future transactions of a company. We just don’t know the real value of parameter. So we rely on sampling distributions to infer something about the parameter for these large populations.
There are a lot of different names for hypothesis test and the way we build confidence intervals:
T-Test
Two sample t-test
Z-test
chi-squared Test
Bootstrapping approach can be used in place of any of these. We will walk through an example to see how will use a sampling distribution to build a confidence interval for our parameter of interest.
Objective : Let’s say we want to get an idea on what’s the mean height of the people who drinks coffee
We have a dataset of all the coffee drinkers. `coffee_full.csv`
coffee_full = pd.read_csv(‘coffee_dataset.csv’)
From that i will create a sample dataset of 200 datapoints. lets call it coffee_red. This because in reality we never get full population
coffee_red = coffee_full.sample(n=200)
Proportion of coffee drinkers in our dataset
[coffee_red[‘drinks_coffee’]==True].mean()---Output---0.595
Average height of coffee drinkers in our dataset
coffee_red[coffee_red[‘drinks_coffee’]==True]['height'].mean()---Output---68.119 inches
Let’s bootstrap from sample to create a confidence interval
# Let's first create an empty list for storing means of bootstrapped samplesboot_means = []# Let's write a loop for creating 1000 bootstrapped samplesfor i in range(1000): bootsample = coffee_red.sample(200, replace=True) bootsample_mean = bootsample.[bootsample[‘drinks_coffee’]==True]['height'].mean() boot_means.append(bootsample_mean)boot_means = np.array(boot_means)
For a 95% confidence interval — we cut-off 2.5% from each side and then these values from the sampling distribution that will give us the range where we believe the parameter would be “with 95% confidence”
# we build 95% in the middle portionnp.percentile(boot_means, 2.5), np.percentile(boot_means, 97.5)---Output---(66.00, 67.59)
We can interpret these values as the bounds where we believe the mean height of all coffee drinkers in the population to be with 95% confidence
To visualize this, let’s look at the following graph
plt.hist(boot_means, alpha=0.7);plt.axvline(np.percentile(boot_means, 2.5), color='red', linewidth=2) ;plt.axvline(np.percentile(boot_means, 97.5), color='red', linewidth=2) ;
We are 95% confident that the mean height of all the coffee drinkers is between 66.0 and 67.59 inches
Let’s go back and see what the population mean actually was
coffee_full[coffee_full[‘drinks_coffee’]==True][‘height’].mean()---Output---66.44 inch
We can see that our original mean height is within our 95% confidence interval
There are many traditional approaches for building confidence intervals which are already built in python. Here’s a good stackoverflow link
import statsmodels.stats.api as smX1 = coffee_red[coffee_red['drinks_coffee']==True]['height'] X2 = coffee_red[coffee_red['drinks_coffee']==False]['height']cm = sm.CompareMeans(sm.DescrStatsW(X1), sm.DescrStatsW(X2))print (cm.tconfint_diff(usevar='unequal'))
Notice that the intervals for bootstrapping method and the built in using the traditional method are nearly identical
As a data scientist you have to first translate the questions into what it’s called hypothesis. Then you need to use the data to justify which hypothesis is likely to be true.
Let’s say we wanted to ask a questions whether the average height for all the coffee drinkers is greater than 70 inches.
Here we will have to define what are called as Null hypothesis and Alternate hypothesis. Null hypothesis is something that is assumed to be true by default even before we collect data. Alternate hypothesis is something that we are trying to prove using data
We can bootstrap a sample set of data and compute the sample mean again and again, build a sampling distribution and confidence interval to determine what are the reasonable values for the population mean with some level of confidence
means = []for i in range(10000): bootsample = sample_df.sample(n=150, replace = True) bootsample_mean = bootsample[bootsample['drinks_coffee']==True] means.append(bootsample_mean['height'].mean())means = np.array(means)np.percentile(means, 2.5), np.percentile(means, 97.5)---Output---(66.00, 67.59)
We can see that our 95% confidence interval is (66.0 , 67.59). Value of 70 is beyond 95% confidence interval so it is safe to say that alternate hypothesis is not true. We fail to reject our null hypothesis
We start by assuming that null hypothesis is true. If we were to simulate the values closest to the null hypothesis we would know what the sampling distribution will look like
We are going to simulate from the normal distribution in this case
null_vals = np.random.normal(loc = 70, scale = np.std(means), size =10000)
70 is our hypothesized mean
Each of the simulated draws here represent a possible mean from the null hypothesis. We can now ask the question where the sample mean falls in this distribution
plt.hist(null_vals, alpha=0.7);plt.axvline(sample_mean, color = 'red', linewidth=2);
We can see that it falls far below this distribution from the norm and we don’t think it probably came from this null hypothesized value. Hence we can say that our null hypothesis is true
p_value = (null_vals > sample_mean).mean()p_value--Output--1.0
Large p-value suggest that we can not reject our null hypothesis. which means that our population mean is indeed less than or equal to 70
We calculate p value as the proportion of the simulated draws that are larger than our sample mean
Graphically p-value here indicates area under the curve for all the values greater than the highlighted red line. which is basically all the data
Please feel free to write your thoughts / suggestions / feedback
Quite an informative article on the foundations of Bootstrapping- Introduction to bootstrap method
Stackoverflow link for T-test-Confidence interval for t-test | [
{
"code": null,
"e": 573,
"s": 171,
"text": "Bootstrap is a powerful, computer-based method for statistical inference without relying on too many assumption. It’s just magical to form a sampling distribution just from only one sample data. No formula needed for my statistical inference. Not only that, in fact, it is widely applied in other statistical inference such as confidence interval, regression model, even the field of machine learning."
},
{
"code": null,
"e": 629,
"s": 573,
"text": "In this article we will primarily talk about two things"
},
{
"code": null,
"e": 677,
"s": 629,
"text": "Building Confidence IntervalsHypothesis Testing"
},
{
"code": null,
"e": 707,
"s": 677,
"text": "Building Confidence Intervals"
},
{
"code": null,
"e": 726,
"s": 707,
"text": "Hypothesis Testing"
},
{
"code": null,
"e": 771,
"s": 726,
"text": "Link to the github for the code and dataset."
},
{
"code": null,
"e": 1096,
"s": 771,
"text": "In real world — we don’t really know about our true population. For that it could be the entire population of planet or past, present and future transactions of a company. We just don’t know the real value of parameter. So we rely on sampling distributions to infer something about the parameter for these large populations."
},
{
"code": null,
"e": 1194,
"s": 1096,
"text": "There are a lot of different names for hypothesis test and the way we build confidence intervals:"
},
{
"code": null,
"e": 1201,
"s": 1194,
"text": "T-Test"
},
{
"code": null,
"e": 1219,
"s": 1201,
"text": "Two sample t-test"
},
{
"code": null,
"e": 1226,
"s": 1219,
"text": "Z-test"
},
{
"code": null,
"e": 1243,
"s": 1226,
"text": "chi-squared Test"
},
{
"code": null,
"e": 1442,
"s": 1243,
"text": "Bootstrapping approach can be used in place of any of these. We will walk through an example to see how will use a sampling distribution to build a confidence interval for our parameter of interest."
},
{
"code": null,
"e": 1545,
"s": 1442,
"text": "Objective : Let’s say we want to get an idea on what’s the mean height of the people who drinks coffee"
},
{
"code": null,
"e": 1609,
"s": 1545,
"text": "We have a dataset of all the coffee drinkers. `coffee_full.csv`"
},
{
"code": null,
"e": 1657,
"s": 1609,
"text": "coffee_full = pd.read_csv(‘coffee_dataset.csv’)"
},
{
"code": null,
"e": 1795,
"s": 1657,
"text": "From that i will create a sample dataset of 200 datapoints. lets call it coffee_red. This because in reality we never get full population"
},
{
"code": null,
"e": 1834,
"s": 1795,
"text": "coffee_red = coffee_full.sample(n=200)"
},
{
"code": null,
"e": 1879,
"s": 1834,
"text": "Proportion of coffee drinkers in our dataset"
},
{
"code": null,
"e": 1939,
"s": 1879,
"text": "[coffee_red[‘drinks_coffee’]==True].mean()---Output---0.595"
},
{
"code": null,
"e": 1988,
"s": 1939,
"text": "Average height of coffee drinkers in our dataset"
},
{
"code": null,
"e": 2076,
"s": 1988,
"text": "coffee_red[coffee_red[‘drinks_coffee’]==True]['height'].mean()---Output---68.119 inches"
},
{
"code": null,
"e": 2136,
"s": 2076,
"text": "Let’s bootstrap from sample to create a confidence interval"
},
{
"code": null,
"e": 2517,
"s": 2136,
"text": "# Let's first create an empty list for storing means of bootstrapped samplesboot_means = []# Let's write a loop for creating 1000 bootstrapped samplesfor i in range(1000): bootsample = coffee_red.sample(200, replace=True) bootsample_mean = bootsample.[bootsample[‘drinks_coffee’]==True]['height'].mean() boot_means.append(bootsample_mean)boot_means = np.array(boot_means)"
},
{
"code": null,
"e": 2723,
"s": 2517,
"text": "For a 95% confidence interval — we cut-off 2.5% from each side and then these values from the sampling distribution that will give us the range where we believe the parameter would be “with 95% confidence”"
},
{
"code": null,
"e": 2849,
"s": 2723,
"text": "# we build 95% in the middle portionnp.percentile(boot_means, 2.5), np.percentile(boot_means, 97.5)---Output---(66.00, 67.59)"
},
{
"code": null,
"e": 2993,
"s": 2849,
"text": "We can interpret these values as the bounds where we believe the mean height of all coffee drinkers in the population to be with 95% confidence"
},
{
"code": null,
"e": 3046,
"s": 2993,
"text": "To visualize this, let’s look at the following graph"
},
{
"code": null,
"e": 3222,
"s": 3046,
"text": "plt.hist(boot_means, alpha=0.7);plt.axvline(np.percentile(boot_means, 2.5), color='red', linewidth=2) ;plt.axvline(np.percentile(boot_means, 97.5), color='red', linewidth=2) ;"
},
{
"code": null,
"e": 3324,
"s": 3222,
"text": "We are 95% confident that the mean height of all the coffee drinkers is between 66.0 and 67.59 inches"
},
{
"code": null,
"e": 3384,
"s": 3324,
"text": "Let’s go back and see what the population mean actually was"
},
{
"code": null,
"e": 3471,
"s": 3384,
"text": "coffee_full[coffee_full[‘drinks_coffee’]==True][‘height’].mean()---Output---66.44 inch"
},
{
"code": null,
"e": 3550,
"s": 3471,
"text": "We can see that our original mean height is within our 95% confidence interval"
},
{
"code": null,
"e": 3690,
"s": 3550,
"text": "There are many traditional approaches for building confidence intervals which are already built in python. Here’s a good stackoverflow link"
},
{
"code": null,
"e": 3949,
"s": 3690,
"text": "import statsmodels.stats.api as smX1 = coffee_red[coffee_red['drinks_coffee']==True]['height'] X2 = coffee_red[coffee_red['drinks_coffee']==False]['height']cm = sm.CompareMeans(sm.DescrStatsW(X1), sm.DescrStatsW(X2))print (cm.tconfint_diff(usevar='unequal'))"
},
{
"code": null,
"e": 4067,
"s": 3949,
"text": "Notice that the intervals for bootstrapping method and the built in using the traditional method are nearly identical"
},
{
"code": null,
"e": 4243,
"s": 4067,
"text": "As a data scientist you have to first translate the questions into what it’s called hypothesis. Then you need to use the data to justify which hypothesis is likely to be true."
},
{
"code": null,
"e": 4364,
"s": 4243,
"text": "Let’s say we wanted to ask a questions whether the average height for all the coffee drinkers is greater than 70 inches."
},
{
"code": null,
"e": 4622,
"s": 4364,
"text": "Here we will have to define what are called as Null hypothesis and Alternate hypothesis. Null hypothesis is something that is assumed to be true by default even before we collect data. Alternate hypothesis is something that we are trying to prove using data"
},
{
"code": null,
"e": 4857,
"s": 4622,
"text": "We can bootstrap a sample set of data and compute the sample mean again and again, build a sampling distribution and confidence interval to determine what are the reasonable values for the population mean with some level of confidence"
},
{
"code": null,
"e": 5162,
"s": 4857,
"text": "means = []for i in range(10000): bootsample = sample_df.sample(n=150, replace = True) bootsample_mean = bootsample[bootsample['drinks_coffee']==True] means.append(bootsample_mean['height'].mean())means = np.array(means)np.percentile(means, 2.5), np.percentile(means, 97.5)---Output---(66.00, 67.59)"
},
{
"code": null,
"e": 5369,
"s": 5162,
"text": "We can see that our 95% confidence interval is (66.0 , 67.59). Value of 70 is beyond 95% confidence interval so it is safe to say that alternate hypothesis is not true. We fail to reject our null hypothesis"
},
{
"code": null,
"e": 5545,
"s": 5369,
"text": "We start by assuming that null hypothesis is true. If we were to simulate the values closest to the null hypothesis we would know what the sampling distribution will look like"
},
{
"code": null,
"e": 5612,
"s": 5545,
"text": "We are going to simulate from the normal distribution in this case"
},
{
"code": null,
"e": 5687,
"s": 5612,
"text": "null_vals = np.random.normal(loc = 70, scale = np.std(means), size =10000)"
},
{
"code": null,
"e": 5715,
"s": 5687,
"text": "70 is our hypothesized mean"
},
{
"code": null,
"e": 5877,
"s": 5715,
"text": "Each of the simulated draws here represent a possible mean from the null hypothesis. We can now ask the question where the sample mean falls in this distribution"
},
{
"code": null,
"e": 5962,
"s": 5877,
"text": "plt.hist(null_vals, alpha=0.7);plt.axvline(sample_mean, color = 'red', linewidth=2);"
},
{
"code": null,
"e": 6150,
"s": 5962,
"text": "We can see that it falls far below this distribution from the norm and we don’t think it probably came from this null hypothesized value. Hence we can say that our null hypothesis is true"
},
{
"code": null,
"e": 6213,
"s": 6150,
"text": "p_value = (null_vals > sample_mean).mean()p_value--Output--1.0"
},
{
"code": null,
"e": 6351,
"s": 6213,
"text": "Large p-value suggest that we can not reject our null hypothesis. which means that our population mean is indeed less than or equal to 70"
},
{
"code": null,
"e": 6450,
"s": 6351,
"text": "We calculate p value as the proportion of the simulated draws that are larger than our sample mean"
},
{
"code": null,
"e": 6596,
"s": 6450,
"text": "Graphically p-value here indicates area under the curve for all the values greater than the highlighted red line. which is basically all the data"
},
{
"code": null,
"e": 6661,
"s": 6596,
"text": "Please feel free to write your thoughts / suggestions / feedback"
},
{
"code": null,
"e": 6760,
"s": 6661,
"text": "Quite an informative article on the foundations of Bootstrapping- Introduction to bootstrap method"
}
] |
How to Get the Data Type of a Pytorch Tensor? - GeeksforGeeks | 21 Jul, 2021
In this article, we are going to create a tensor and get the data type. The Pytorch is used to process the tensors. Tensors are multidimensional arrays. PyTorch accelerates the scientific computation of tensors as it has various inbuilt functions.
A vector is a one-dimensional tensor that holds elements of multiple data types. We can create a vector using PyTorch. Pytorch is available in the Python torch module so, we need to import it
Syntax:
import pytorch
One dimensional vector is created using the torch.tensor() method.
Syntax:
torch.tensor([element1,element2,.,element n],dtype)
Parameters:
dtype: Specify the data type.
dtype=torch.datatype
Example: Python program to create tensor elements not specifying the data type.
Python3
# importing torch moduleimport torch # create one dimensional tensor with# integer type elementsa = torch.tensor([10, 20, 30, 40, 50])print(a) # create one dimensional tensor with # float type elementsb = torch.tensor([10.12, 20.56, 30.00, 40.3, 50.4])print(b)
Output:
tensor([10, 20, 30, 40, 50])
tensor([10.1200, 20.5600, 30.0000, 40.3000, 50.4000])
The following data types are supported by vector:
We can get the data type by using dtype command:
Syntax:
tensor_name.dtype
Example 1: Python program to create tensor with integer data types and display data type
Python3
# import torchimport torch # create a tensor with unsigned integer type of 8 bytes sizea = torch.tensor([100, 200, 2, 3, 4], dtype=torch.uint8)# display tensorprint(a)# display data typeprint(a.dtype) # create a tensor with integer type of 8 bytes sizea = torch.tensor([1, 2, -6, -8, 0], dtype=torch.int8) # display tensorprint(a) # display data typeprint(a.dtype) # create a tensor with integer type of 16 bytes sizea = torch.tensor([1, 2, -6, -8, 0], dtype=torch.int16) # display tensorprint(a) # display data typeprint(a.dtype) # create a tensor with integer type of 32 bytes sizea = torch.tensor([1, 2, -6, -8, 0], dtype=torch.int32) # display tensorprint(a) # display data typeprint(a.dtype) # create a tensor with integer type of 64 bytes sizea = torch.tensor([1, 2, -6, -8, 0], dtype=torch.int64) # display tensorprint(a) # display data typeprint(a.dtype)
Output:
tensor([100, 200, 2, 3, 4], dtype=torch.uint8)
torch.uint8
tensor([ 1, 2, -6, -8, 0], dtype=torch.int8)
torch.int8
tensor([ 1, 2, -6, -8, 0], dtype=torch.int16)
torch.int16
tensor([ 1, 2, -6, -8, 0], dtype=torch.int32)
torch.int32
tensor([ 1, 2, -6, -8, 0])
torch.int64
Example 2: Create float type and display data types.
Python3
# import torchimport torch # create a tensor with float typea = torch.tensor([100, 200, 2, 3, 4], dtype=torch.float) # display tensorprint(a) # display data typeprint(a.dtype) # create a tensor with double typea = torch.tensor([1, 2, -6, -8, 0], dtype=torch.double) # display tensorprint(a) # display data typeprint(a.dtype)
Output:
tensor([100., 200., 2., 3., 4.])
torch.float32
tensor([ 1., 2., -6., -8., 0.], dtype=torch.float64)
torch.float64
Example 3: Create a tensor with boolean type
Python3
# import torchimport torch # create a tensor with bool typea = torch.tensor([100, 200, 2, 3, 4], dtype=torch.bool) # display tensorprint(a) # display data typeprint(a.dtype) # create a tensor with bool typea = torch.tensor([0, 0, 0, 1, 2], dtype=torch.bool) # display tensorprint(a) # display data typeprint(a.dtype)
Output:
tensor([True, True, True, True, True])
torch.bool
tensor([False, False, False, True, True])
torch.bool
Picked
Python-PyTorch
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n21 Jul, 2021"
},
{
"code": null,
"e": 25895,
"s": 25647,
"text": "In this article, we are going to create a tensor and get the data type. The Pytorch is used to process the tensors. Tensors are multidimensional arrays. PyTorch accelerates the scientific computation of tensors as it has various inbuilt functions."
},
{
"code": null,
"e": 26087,
"s": 25895,
"text": "A vector is a one-dimensional tensor that holds elements of multiple data types. We can create a vector using PyTorch. Pytorch is available in the Python torch module so, we need to import it"
},
{
"code": null,
"e": 26095,
"s": 26087,
"text": "Syntax:"
},
{
"code": null,
"e": 26110,
"s": 26095,
"text": "import pytorch"
},
{
"code": null,
"e": 26177,
"s": 26110,
"text": "One dimensional vector is created using the torch.tensor() method."
},
{
"code": null,
"e": 26185,
"s": 26177,
"text": "Syntax:"
},
{
"code": null,
"e": 26237,
"s": 26185,
"text": "torch.tensor([element1,element2,.,element n],dtype)"
},
{
"code": null,
"e": 26249,
"s": 26237,
"text": "Parameters:"
},
{
"code": null,
"e": 26279,
"s": 26249,
"text": "dtype: Specify the data type."
},
{
"code": null,
"e": 26300,
"s": 26279,
"text": "dtype=torch.datatype"
},
{
"code": null,
"e": 26380,
"s": 26300,
"text": "Example: Python program to create tensor elements not specifying the data type."
},
{
"code": null,
"e": 26388,
"s": 26380,
"text": "Python3"
},
{
"code": "# importing torch moduleimport torch # create one dimensional tensor with# integer type elementsa = torch.tensor([10, 20, 30, 40, 50])print(a) # create one dimensional tensor with # float type elementsb = torch.tensor([10.12, 20.56, 30.00, 40.3, 50.4])print(b)",
"e": 26651,
"s": 26388,
"text": null
},
{
"code": null,
"e": 26659,
"s": 26651,
"text": "Output:"
},
{
"code": null,
"e": 26742,
"s": 26659,
"text": "tensor([10, 20, 30, 40, 50])\ntensor([10.1200, 20.5600, 30.0000, 40.3000, 50.4000])"
},
{
"code": null,
"e": 26792,
"s": 26742,
"text": "The following data types are supported by vector:"
},
{
"code": null,
"e": 26841,
"s": 26792,
"text": "We can get the data type by using dtype command:"
},
{
"code": null,
"e": 26849,
"s": 26841,
"text": "Syntax:"
},
{
"code": null,
"e": 26867,
"s": 26849,
"text": "tensor_name.dtype"
},
{
"code": null,
"e": 26956,
"s": 26867,
"text": "Example 1: Python program to create tensor with integer data types and display data type"
},
{
"code": null,
"e": 26964,
"s": 26956,
"text": "Python3"
},
{
"code": "# import torchimport torch # create a tensor with unsigned integer type of 8 bytes sizea = torch.tensor([100, 200, 2, 3, 4], dtype=torch.uint8)# display tensorprint(a)# display data typeprint(a.dtype) # create a tensor with integer type of 8 bytes sizea = torch.tensor([1, 2, -6, -8, 0], dtype=torch.int8) # display tensorprint(a) # display data typeprint(a.dtype) # create a tensor with integer type of 16 bytes sizea = torch.tensor([1, 2, -6, -8, 0], dtype=torch.int16) # display tensorprint(a) # display data typeprint(a.dtype) # create a tensor with integer type of 32 bytes sizea = torch.tensor([1, 2, -6, -8, 0], dtype=torch.int32) # display tensorprint(a) # display data typeprint(a.dtype) # create a tensor with integer type of 64 bytes sizea = torch.tensor([1, 2, -6, -8, 0], dtype=torch.int64) # display tensorprint(a) # display data typeprint(a.dtype)",
"e": 27848,
"s": 26964,
"text": null
},
{
"code": null,
"e": 27856,
"s": 27848,
"text": "Output:"
},
{
"code": null,
"e": 28140,
"s": 27856,
"text": "tensor([100, 200, 2, 3, 4], dtype=torch.uint8)\ntorch.uint8\ntensor([ 1, 2, -6, -8, 0], dtype=torch.int8)\ntorch.int8\ntensor([ 1, 2, -6, -8, 0], dtype=torch.int16)\ntorch.int16\ntensor([ 1, 2, -6, -8, 0], dtype=torch.int32)\ntorch.int32\ntensor([ 1, 2, -6, -8, 0])\ntorch.int64"
},
{
"code": null,
"e": 28193,
"s": 28140,
"text": "Example 2: Create float type and display data types."
},
{
"code": null,
"e": 28201,
"s": 28193,
"text": "Python3"
},
{
"code": "# import torchimport torch # create a tensor with float typea = torch.tensor([100, 200, 2, 3, 4], dtype=torch.float) # display tensorprint(a) # display data typeprint(a.dtype) # create a tensor with double typea = torch.tensor([1, 2, -6, -8, 0], dtype=torch.double) # display tensorprint(a) # display data typeprint(a.dtype)",
"e": 28536,
"s": 28201,
"text": null
},
{
"code": null,
"e": 28544,
"s": 28536,
"text": "Output:"
},
{
"code": null,
"e": 28666,
"s": 28544,
"text": "tensor([100., 200., 2., 3., 4.])\ntorch.float32\ntensor([ 1., 2., -6., -8., 0.], dtype=torch.float64)\ntorch.float64"
},
{
"code": null,
"e": 28711,
"s": 28666,
"text": "Example 3: Create a tensor with boolean type"
},
{
"code": null,
"e": 28719,
"s": 28711,
"text": "Python3"
},
{
"code": "# import torchimport torch # create a tensor with bool typea = torch.tensor([100, 200, 2, 3, 4], dtype=torch.bool) # display tensorprint(a) # display data typeprint(a.dtype) # create a tensor with bool typea = torch.tensor([0, 0, 0, 1, 2], dtype=torch.bool) # display tensorprint(a) # display data typeprint(a.dtype)",
"e": 29046,
"s": 28719,
"text": null
},
{
"code": null,
"e": 29054,
"s": 29046,
"text": "Output:"
},
{
"code": null,
"e": 29159,
"s": 29054,
"text": "tensor([True, True, True, True, True])\ntorch.bool\ntensor([False, False, False, True, True])\ntorch.bool"
},
{
"code": null,
"e": 29166,
"s": 29159,
"text": "Picked"
},
{
"code": null,
"e": 29181,
"s": 29166,
"text": "Python-PyTorch"
},
{
"code": null,
"e": 29188,
"s": 29181,
"text": "Python"
},
{
"code": null,
"e": 29286,
"s": 29188,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29318,
"s": 29286,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29360,
"s": 29318,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 29402,
"s": 29360,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 29458,
"s": 29402,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 29485,
"s": 29458,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 29516,
"s": 29485,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 29552,
"s": 29516,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 29581,
"s": 29552,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 29603,
"s": 29581,
"text": "Defaultdict in Python"
}
] |
How Julia Perfected Multiple Dispatch | by Emmett Boudreau | Towards Data Science | Although the Julia programming language is new and not quite popular, at least for now, this does not stop the language from achieving some pretty spectacular feats. The Julia programming language is a lot more unique than many users or viewers even understand, as it resides in its own paradigm. This paradigm is awesome in my subjective opinion, and I have really fell in love with the fantastic type system and parametric polymorphism in the programming language. Julia Computing has dubbed this paradigm
“ The Multiple Dispatch Paradigm”
Okay, so not the most creative naming, but there are so many great reasons to use this paradigm, and with it the Julia programming language. For me, multiple dispatch is a very natural way to program, especially when it comes to scientific computing. On top of that though, there are several things that the language has done to make multiple dispatch even better than it has ever been in any language prior. Before we get into multiple dispatch, one more thing; all of the examples in this article are going to be taken from a package I am currently working to release, it is an object-oriented DataFrames package that makes a bridge between options like DataFrames.jl and Pandas.py in Julia. If you would like to learn more about, contribute, or support this package (thank you,) you may check the package out here:
github.com
Before we touch on what is so great about the way the Julia language has expanded and worked with multiple dispatch across the board, let us first touch on what exactly multiple dispatch is. Multiple dispatch is a generic programming concept that was originally introduced to solve a problem in the functional programming paradigm. This problem was that there were simply too many method names, when methods are not private to the types we are working with, we must have a separate call for each type, even if said functions do the same thing.
For example, let us pretend we have our own functional programming language, and we want to get the length of an iterable array, we would call:
length(array)
Now let us say we also wanted to get the length of a the chars in a string — since functional programming primarily focuses on declarative, and more vitally — GLOBAL — programming, we can only have one definition of length. Since we have already used this definition on the array, we would need to change this function’s alias:
length_str(string)
Needless to say, specifying what type you are about to pass inside of a method call is just a tedious and disgusting interaction between programmer, methods, and types. This is where multiple dispatch comes in. With multiple dispatch, the methods can be defined specifically to work with the type of provided arguments, like our example before:
length(array)length(string)
And all we need to do is add the specific type we are writing to into our method definitions in order to facilitate this. If you would like to learn a bit more about why multiple dispatch is so cool, and a few more technicalities on the subject, I have an article with more detail one may read here:
towardsdatascience.com
Also, that was published almost two years ago — why.
One thing that definitely makes multiple dispatch convenient is one-line definitions. In Julia, the function key-word is optional. Julia can tell we are calling a method whenever we put parenthesis after an alias, e.g.
example()
If we were to run this, we would get the same error as without the parenthesis, however with a stack-trace, because the Julia compiler has now noticed that we are not necessarily working within the global scope, as it has evaluated that we are working with a function that has its own scope. This is an interesting difference, check it out:
All of this creates the ability to not only quickly create functions in one line, but also change function calls in one line. Consider the following example from OddFrames.jl where our functions that will become children of our type are defined:
head(x::Int64) = _head(labels, columns, coldata, x)head() = _head(labels, columns, coldata, 5)# Dropdrop(x) = _drop(x, columns)drop(x::Symbol) = _drop(x, labels, columns, coldata)drop(x::String) = _drop(Symbol(x), labels, columns, coldata)dropna() = _dropna(columns)dtype(x::Symbol) = typeof(coldata[findall(x->x == x, labels)[1]][1])dtype(x::Symbol, y::Type) = _dtype(columns[findall(x->x == x,labels)[1]], y)
In many of these examples, we see that the arguments change from the first to the second definition. In the first instance, we provide data from the type into the function, along with the provided value. In the second instance, we provide a default value for x so there are no input arguments. What is so valuable about these examples is that some of these input arguments even need to be changed before we can actually provide them. For example, consider the dtype() function.
dtype(x::Symbol) = typeof(coldata[findall(x->x == x, labels)[1]][1])
In this example, if we were to simply provide the symbol to get the data-type, we would have a huge problem. As the symbol we need is not only in a different array to the data, but we also do not know which array! Fortunately, we can do all of the writing for this in one line, and the resulting code even looks clean!
Probably my favorite implementation of multiple dispatch into the Julia programming language is that of dispatch. Consider the constructor for our Immutable OddFrame (I chose this because it is a lot shorter.)
struct ImmutableOddFrame <: AbstractOddFramelabels::Array{Symbol}columns::Array{Any}coldata::Array{Pair}head::Function
This is what is called the outer constructor. We can call this outer constructor directly, and the return will always be the type ImmutableOddFrame. In order to make such a call, however, we would need to provide
labels
columns
coldata
head
all by ourselves. How on Earth are we supposed to do that? Especially given that head() is a function. Are we seriously meant to write our own functions in order to use this type? Of course not. Furthermore, the data inside of this type is essentially only for the actual module to utilize in such a way, not the end-user. The end-user simply needs to provide some much more high-level declarative data. For example, the file-path of the file they would like to load data from:
function OddFrame(file_path::String)# Labels/Columnsextensions = Dict("csv" => read_csv)extension = split(file_path, '.')[2]labels, columns = extensions[extension](file_path)
This is all done through dispatch, and the calls are essentially the same for both the inner constructor and the outer constructor — just the types passed are different. Needless to say, this brings constructors to an entirely new level of power! If you would like to learn more about constructors, you may either read this article or watch this video if you desire:
towardsdatascience.com
Needless to say, Julia has changed the game completely, not just in the much smaller world of multiple dispatch applications of software, but also in the world of programming overall! The multiple dispatch paradigm really does bring multiple dispatch programming to an entirely new level. The concept is taken so much further and with so much power with the abilities of constructors. From this whole article, it is probably the constructors that make the most significant impact here. Thank you very much for reading, it really does mean the world to me! I hope this article was interesting, and filled you in a bit more on the multiple dispatch paradigm — which is awesome! | [
{
"code": null,
"e": 680,
"s": 172,
"text": "Although the Julia programming language is new and not quite popular, at least for now, this does not stop the language from achieving some pretty spectacular feats. The Julia programming language is a lot more unique than many users or viewers even understand, as it resides in its own paradigm. This paradigm is awesome in my subjective opinion, and I have really fell in love with the fantastic type system and parametric polymorphism in the programming language. Julia Computing has dubbed this paradigm"
},
{
"code": null,
"e": 714,
"s": 680,
"text": "“ The Multiple Dispatch Paradigm”"
},
{
"code": null,
"e": 1532,
"s": 714,
"text": "Okay, so not the most creative naming, but there are so many great reasons to use this paradigm, and with it the Julia programming language. For me, multiple dispatch is a very natural way to program, especially when it comes to scientific computing. On top of that though, there are several things that the language has done to make multiple dispatch even better than it has ever been in any language prior. Before we get into multiple dispatch, one more thing; all of the examples in this article are going to be taken from a package I am currently working to release, it is an object-oriented DataFrames package that makes a bridge between options like DataFrames.jl and Pandas.py in Julia. If you would like to learn more about, contribute, or support this package (thank you,) you may check the package out here:"
},
{
"code": null,
"e": 1543,
"s": 1532,
"text": "github.com"
},
{
"code": null,
"e": 2087,
"s": 1543,
"text": "Before we touch on what is so great about the way the Julia language has expanded and worked with multiple dispatch across the board, let us first touch on what exactly multiple dispatch is. Multiple dispatch is a generic programming concept that was originally introduced to solve a problem in the functional programming paradigm. This problem was that there were simply too many method names, when methods are not private to the types we are working with, we must have a separate call for each type, even if said functions do the same thing."
},
{
"code": null,
"e": 2231,
"s": 2087,
"text": "For example, let us pretend we have our own functional programming language, and we want to get the length of an iterable array, we would call:"
},
{
"code": null,
"e": 2245,
"s": 2231,
"text": "length(array)"
},
{
"code": null,
"e": 2573,
"s": 2245,
"text": "Now let us say we also wanted to get the length of a the chars in a string — since functional programming primarily focuses on declarative, and more vitally — GLOBAL — programming, we can only have one definition of length. Since we have already used this definition on the array, we would need to change this function’s alias:"
},
{
"code": null,
"e": 2592,
"s": 2573,
"text": "length_str(string)"
},
{
"code": null,
"e": 2937,
"s": 2592,
"text": "Needless to say, specifying what type you are about to pass inside of a method call is just a tedious and disgusting interaction between programmer, methods, and types. This is where multiple dispatch comes in. With multiple dispatch, the methods can be defined specifically to work with the type of provided arguments, like our example before:"
},
{
"code": null,
"e": 2965,
"s": 2937,
"text": "length(array)length(string)"
},
{
"code": null,
"e": 3265,
"s": 2965,
"text": "And all we need to do is add the specific type we are writing to into our method definitions in order to facilitate this. If you would like to learn a bit more about why multiple dispatch is so cool, and a few more technicalities on the subject, I have an article with more detail one may read here:"
},
{
"code": null,
"e": 3288,
"s": 3265,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3341,
"s": 3288,
"text": "Also, that was published almost two years ago — why."
},
{
"code": null,
"e": 3560,
"s": 3341,
"text": "One thing that definitely makes multiple dispatch convenient is one-line definitions. In Julia, the function key-word is optional. Julia can tell we are calling a method whenever we put parenthesis after an alias, e.g."
},
{
"code": null,
"e": 3570,
"s": 3560,
"text": "example()"
},
{
"code": null,
"e": 3911,
"s": 3570,
"text": "If we were to run this, we would get the same error as without the parenthesis, however with a stack-trace, because the Julia compiler has now noticed that we are not necessarily working within the global scope, as it has evaluated that we are working with a function that has its own scope. This is an interesting difference, check it out:"
},
{
"code": null,
"e": 4157,
"s": 3911,
"text": "All of this creates the ability to not only quickly create functions in one line, but also change function calls in one line. Consider the following example from OddFrames.jl where our functions that will become children of our type are defined:"
},
{
"code": null,
"e": 4568,
"s": 4157,
"text": "head(x::Int64) = _head(labels, columns, coldata, x)head() = _head(labels, columns, coldata, 5)# Dropdrop(x) = _drop(x, columns)drop(x::Symbol) = _drop(x, labels, columns, coldata)drop(x::String) = _drop(Symbol(x), labels, columns, coldata)dropna() = _dropna(columns)dtype(x::Symbol) = typeof(coldata[findall(x->x == x, labels)[1]][1])dtype(x::Symbol, y::Type) = _dtype(columns[findall(x->x == x,labels)[1]], y)"
},
{
"code": null,
"e": 5046,
"s": 4568,
"text": "In many of these examples, we see that the arguments change from the first to the second definition. In the first instance, we provide data from the type into the function, along with the provided value. In the second instance, we provide a default value for x so there are no input arguments. What is so valuable about these examples is that some of these input arguments even need to be changed before we can actually provide them. For example, consider the dtype() function."
},
{
"code": null,
"e": 5115,
"s": 5046,
"text": "dtype(x::Symbol) = typeof(coldata[findall(x->x == x, labels)[1]][1])"
},
{
"code": null,
"e": 5434,
"s": 5115,
"text": "In this example, if we were to simply provide the symbol to get the data-type, we would have a huge problem. As the symbol we need is not only in a different array to the data, but we also do not know which array! Fortunately, we can do all of the writing for this in one line, and the resulting code even looks clean!"
},
{
"code": null,
"e": 5644,
"s": 5434,
"text": "Probably my favorite implementation of multiple dispatch into the Julia programming language is that of dispatch. Consider the constructor for our Immutable OddFrame (I chose this because it is a lot shorter.)"
},
{
"code": null,
"e": 5763,
"s": 5644,
"text": "struct ImmutableOddFrame <: AbstractOddFramelabels::Array{Symbol}columns::Array{Any}coldata::Array{Pair}head::Function"
},
{
"code": null,
"e": 5976,
"s": 5763,
"text": "This is what is called the outer constructor. We can call this outer constructor directly, and the return will always be the type ImmutableOddFrame. In order to make such a call, however, we would need to provide"
},
{
"code": null,
"e": 5983,
"s": 5976,
"text": "labels"
},
{
"code": null,
"e": 5991,
"s": 5983,
"text": "columns"
},
{
"code": null,
"e": 5999,
"s": 5991,
"text": "coldata"
},
{
"code": null,
"e": 6004,
"s": 5999,
"text": "head"
},
{
"code": null,
"e": 6482,
"s": 6004,
"text": "all by ourselves. How on Earth are we supposed to do that? Especially given that head() is a function. Are we seriously meant to write our own functions in order to use this type? Of course not. Furthermore, the data inside of this type is essentially only for the actual module to utilize in such a way, not the end-user. The end-user simply needs to provide some much more high-level declarative data. For example, the file-path of the file they would like to load data from:"
},
{
"code": null,
"e": 6657,
"s": 6482,
"text": "function OddFrame(file_path::String)# Labels/Columnsextensions = Dict(\"csv\" => read_csv)extension = split(file_path, '.')[2]labels, columns = extensions[extension](file_path)"
},
{
"code": null,
"e": 7024,
"s": 6657,
"text": "This is all done through dispatch, and the calls are essentially the same for both the inner constructor and the outer constructor — just the types passed are different. Needless to say, this brings constructors to an entirely new level of power! If you would like to learn more about constructors, you may either read this article or watch this video if you desire:"
},
{
"code": null,
"e": 7047,
"s": 7024,
"text": "towardsdatascience.com"
}
] |
Text Cleaning Methods for Natural Language Processing | by Rebecca Vickery | Towards Data Science | Natural language processing is defined as “the application of computational techniques to the analysis and synthesis of natural language and speech”. In order to perform these computational tasks, we first need to convert the language of text into a language that the machine can understand.
In the following post, I am going to describe the most common steps involved in preparing text data for natural language processing. I’ll discuss some tools that can be used to perform these steps and provide some example python code to execute them.
Throughout this article, I will be using a data set taken from Kaggle which can be downloaded here. This data set consists of text from tweets and a target variable which categorises them into those that are about a genuine disaster and those that are not. The code below reads the data into a data frame using pandas. For simplicity, I have dropped all columns except the text and target variable.
import pandas as pdpd.set_option('display.max_colwidth', -1)train_data = pd.read_csv('train.csv')cols_to_drop = ['id', 'keyword', 'location']train_data = train_data.drop(cols_to_drop, axis=1)train_data.head()
One of the key steps in processing language data is to remove noise so that the machine can more easily detect the patterns in the data. Text data contains a lot of noise, this takes the form of special characters such as hashtags, punctuation and numbers. All of which are difficult for computers to understand if they are present in the data. We need to, therefore, process the data to remove these elements.
Additionally, it is also important to apply some attention to the casing of words. If we include both upper case and lower case versions of the same words then the computer will see these as different entities, even though they may be the same.
The code below performs these steps. To keep a track of the changes we are making to the text I have put the clean text into a new column. The output is shown below the code.
import redef clean_text(df, text_field, new_text_field_name): df[new_text_field_name] = df[text_field].str.lower() df[new_text_field_name] = df[new_text_field_name].apply(lambda elem: re.sub(r"(@[A-Za-z0-9]+)|([^0-9A-Za-z \t])|(\w+:\/\/\S+)|^rt|http.+?", "", elem)) # remove numbers df[new_text_field_name] = df[new_text_field_name].apply(lambda elem: re.sub(r"\d+", "", elem)) return dfdata_clean = clean_text(train_data, 'text', 'text_clean')data_clean.head()
Stop words are commonly occurring words that for some computational processes provide little information or in some cases introduce unnecessary noise and therefore need to be removed. This is particularly the case for text classification tasks.
There are other instances where the removal of stop words is either not advised or needs to be more carefully considered. This includes any situation where the meaning of a piece of text may be lost by the removal of a stop word. For example, if we were building a chatbot and removed the word“not” from this phrase “i am not happy” then the reverse meaning may in fact be interpreted by the algorithm. This would be particularly important for use cases such as chatbots or sentiment analysis.
The Natural Language Toolkit (NLTK) python library has built-in methods for removing stop words. The code below uses this to remove stop words from the tweets.
import nltk.corpusnltk.download('stopwords')from nltk.corpus import stopwordsstop = stopwords.words('english')data_clean['text_clean'] = data_clean['text_clean'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))data_clean.head()
Stemming is the process of reducing words to their root form. For example, the words “rain”, “raining” and “rained” have very similar, and in many cases, the same meaning. The process of stemming will reduce these to the root form of “rain”. This is again a way to reduce noise and the dimensionality of the data.
The NLTK library also has methods to perform the task of stemming. The code below uses the PorterStemmer to stem the words in my example above. As you can see from the output all the words now become “rain”.
from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenizeword_list = ['rains', 'raining', 'rain', 'rained']ps = PorterStemmer()for w in word_list: print(ps.stem(w))
Before we can perform stemming on our data we need to tokenise the tweets. This is a method used to split the text into its constituent parts usually words. The code below uses NLTK to do this. I have put the output into a new column called “text_tokens”.
import nltk nltk.download('punkt')from nltk.tokenize import sent_tokenize, word_tokenizedata_clean['text_tokens'] = data_clean['text_clean'].apply(lambda x: word_tokenize(x))data_clean.head()
The code below uses the PorterStemmer method from NLTK to apply stemming to the text_tokens and outputs the processed text to a new column.
def word_stemmer(text): stem_text = [PorterStemmer().stem(i) for i in text] return stem_textdata_clean['text_tokens_stem'] = data_clean['text_tokens'].apply(lambda x: word_stemmer(x))data_clean.head()
The goal of lemmatization is the same as for stemming, in that it aims to reduce words to their root form. However, stemming is known to be a fairly crude method of doing this. Lemmatization, on the other hand, is a tool that performs full morphological analysis to more accurately find the root, or “lemma” for a word.
Again NLTK can be used to perform this task.
nltk.download('wordnet')from nltk.stem import WordNetLemmatizerdef word_lemmatizer(text): lem_text = [WordNetLemmatizer().lemmatize(i) for i in text] return lem_textdata_clean['text_tokens_lemma'] = data_clean['text_tokens'].apply(lambda x: word_lemmatizer(x))data_clean.head()
Part of speech (POS) tagging is a method to categorise words which gives some information relating to the way in which that word is used in speech.
There are eight primary parts of speech and they each have a corresponding tag. These are shown in the table below.
The NLTK libary has a method to perform POS tagging. The below code performs POS tagging on the tweets in our data set and returns a new column.
def word_pos_tagger(text): pos_tagged_text = nltk.pos_tag(text) return pos_tagged_textnltk.download('averaged_perceptron_tagger')data_clean['text_tokens_pos_tagged'] = data_clean['text_tokens'].apply(lambda x: word_pos_tagger(x))data_clean.head()
Chunking builds on POS tagging in that it uses the information from the POS tags to extract meaningful phrases from text. In many types of texts, if we reduce everything down to individual words we may lose a lot of meaning. In our tweets, for example, we have a lot of location names and other phrases which are important to keep together.
If we take this sentence “forest fire near la ronge sask canada” the location name “la ronge” and the words “forest fire” will convey an important meaning that we might not want to lose.
The spaCy python library has a method for this. If we apply this method to the above sentence we can see that it separates out the appropriate phrases.
import spacynlp = spacy.load('en')text = nlp("forest fire near la ronge sask canada")for chunk in text.noun_chunks: print(chunk.text, chunk.label_, chunk.root.text)
This article gives a brief overview of some of the most popular methods for cleaning text data ready for natural language processing. For a deeper dive into these concepts and tools, this blog nlpforhackers.io is one of my favourites.
If you are interested in applying machine learning techniques to this data I wrote an article last week on how to make your first submission to the Kaggle competition where this dataset comes from.
Thanks for reading! | [
{
"code": null,
"e": 464,
"s": 172,
"text": "Natural language processing is defined as “the application of computational techniques to the analysis and synthesis of natural language and speech”. In order to perform these computational tasks, we first need to convert the language of text into a language that the machine can understand."
},
{
"code": null,
"e": 715,
"s": 464,
"text": "In the following post, I am going to describe the most common steps involved in preparing text data for natural language processing. I’ll discuss some tools that can be used to perform these steps and provide some example python code to execute them."
},
{
"code": null,
"e": 1114,
"s": 715,
"text": "Throughout this article, I will be using a data set taken from Kaggle which can be downloaded here. This data set consists of text from tweets and a target variable which categorises them into those that are about a genuine disaster and those that are not. The code below reads the data into a data frame using pandas. For simplicity, I have dropped all columns except the text and target variable."
},
{
"code": null,
"e": 1323,
"s": 1114,
"text": "import pandas as pdpd.set_option('display.max_colwidth', -1)train_data = pd.read_csv('train.csv')cols_to_drop = ['id', 'keyword', 'location']train_data = train_data.drop(cols_to_drop, axis=1)train_data.head()"
},
{
"code": null,
"e": 1734,
"s": 1323,
"text": "One of the key steps in processing language data is to remove noise so that the machine can more easily detect the patterns in the data. Text data contains a lot of noise, this takes the form of special characters such as hashtags, punctuation and numbers. All of which are difficult for computers to understand if they are present in the data. We need to, therefore, process the data to remove these elements."
},
{
"code": null,
"e": 1979,
"s": 1734,
"text": "Additionally, it is also important to apply some attention to the casing of words. If we include both upper case and lower case versions of the same words then the computer will see these as different entities, even though they may be the same."
},
{
"code": null,
"e": 2154,
"s": 1979,
"text": "The code below performs these steps. To keep a track of the changes we are making to the text I have put the clean text into a new column. The output is shown below the code."
},
{
"code": null,
"e": 2638,
"s": 2154,
"text": "import redef clean_text(df, text_field, new_text_field_name): df[new_text_field_name] = df[text_field].str.lower() df[new_text_field_name] = df[new_text_field_name].apply(lambda elem: re.sub(r\"(@[A-Za-z0-9]+)|([^0-9A-Za-z \\t])|(\\w+:\\/\\/\\S+)|^rt|http.+?\", \"\", elem)) # remove numbers df[new_text_field_name] = df[new_text_field_name].apply(lambda elem: re.sub(r\"\\d+\", \"\", elem)) return dfdata_clean = clean_text(train_data, 'text', 'text_clean')data_clean.head()"
},
{
"code": null,
"e": 2883,
"s": 2638,
"text": "Stop words are commonly occurring words that for some computational processes provide little information or in some cases introduce unnecessary noise and therefore need to be removed. This is particularly the case for text classification tasks."
},
{
"code": null,
"e": 3377,
"s": 2883,
"text": "There are other instances where the removal of stop words is either not advised or needs to be more carefully considered. This includes any situation where the meaning of a piece of text may be lost by the removal of a stop word. For example, if we were building a chatbot and removed the word“not” from this phrase “i am not happy” then the reverse meaning may in fact be interpreted by the algorithm. This would be particularly important for use cases such as chatbots or sentiment analysis."
},
{
"code": null,
"e": 3537,
"s": 3377,
"text": "The Natural Language Toolkit (NLTK) python library has built-in methods for removing stop words. The code below uses this to remove stop words from the tweets."
},
{
"code": null,
"e": 3794,
"s": 3537,
"text": "import nltk.corpusnltk.download('stopwords')from nltk.corpus import stopwordsstop = stopwords.words('english')data_clean['text_clean'] = data_clean['text_clean'].apply(lambda x: ' '.join([word for word in x.split() if word not in (stop)]))data_clean.head()"
},
{
"code": null,
"e": 4108,
"s": 3794,
"text": "Stemming is the process of reducing words to their root form. For example, the words “rain”, “raining” and “rained” have very similar, and in many cases, the same meaning. The process of stemming will reduce these to the root form of “rain”. This is again a way to reduce noise and the dimensionality of the data."
},
{
"code": null,
"e": 4316,
"s": 4108,
"text": "The NLTK library also has methods to perform the task of stemming. The code below uses the PorterStemmer to stem the words in my example above. As you can see from the output all the words now become “rain”."
},
{
"code": null,
"e": 4502,
"s": 4316,
"text": "from nltk.stem import PorterStemmer from nltk.tokenize import word_tokenizeword_list = ['rains', 'raining', 'rain', 'rained']ps = PorterStemmer()for w in word_list: print(ps.stem(w))"
},
{
"code": null,
"e": 4758,
"s": 4502,
"text": "Before we can perform stemming on our data we need to tokenise the tweets. This is a method used to split the text into its constituent parts usually words. The code below uses NLTK to do this. I have put the output into a new column called “text_tokens”."
},
{
"code": null,
"e": 4950,
"s": 4758,
"text": "import nltk nltk.download('punkt')from nltk.tokenize import sent_tokenize, word_tokenizedata_clean['text_tokens'] = data_clean['text_clean'].apply(lambda x: word_tokenize(x))data_clean.head()"
},
{
"code": null,
"e": 5090,
"s": 4950,
"text": "The code below uses the PorterStemmer method from NLTK to apply stemming to the text_tokens and outputs the processed text to a new column."
},
{
"code": null,
"e": 5297,
"s": 5090,
"text": "def word_stemmer(text): stem_text = [PorterStemmer().stem(i) for i in text] return stem_textdata_clean['text_tokens_stem'] = data_clean['text_tokens'].apply(lambda x: word_stemmer(x))data_clean.head()"
},
{
"code": null,
"e": 5617,
"s": 5297,
"text": "The goal of lemmatization is the same as for stemming, in that it aims to reduce words to their root form. However, stemming is known to be a fairly crude method of doing this. Lemmatization, on the other hand, is a tool that performs full morphological analysis to more accurately find the root, or “lemma” for a word."
},
{
"code": null,
"e": 5662,
"s": 5617,
"text": "Again NLTK can be used to perform this task."
},
{
"code": null,
"e": 5946,
"s": 5662,
"text": "nltk.download('wordnet')from nltk.stem import WordNetLemmatizerdef word_lemmatizer(text): lem_text = [WordNetLemmatizer().lemmatize(i) for i in text] return lem_textdata_clean['text_tokens_lemma'] = data_clean['text_tokens'].apply(lambda x: word_lemmatizer(x))data_clean.head()"
},
{
"code": null,
"e": 6094,
"s": 5946,
"text": "Part of speech (POS) tagging is a method to categorise words which gives some information relating to the way in which that word is used in speech."
},
{
"code": null,
"e": 6210,
"s": 6094,
"text": "There are eight primary parts of speech and they each have a corresponding tag. These are shown in the table below."
},
{
"code": null,
"e": 6355,
"s": 6210,
"text": "The NLTK libary has a method to perform POS tagging. The below code performs POS tagging on the tweets in our data set and returns a new column."
},
{
"code": null,
"e": 6608,
"s": 6355,
"text": "def word_pos_tagger(text): pos_tagged_text = nltk.pos_tag(text) return pos_tagged_textnltk.download('averaged_perceptron_tagger')data_clean['text_tokens_pos_tagged'] = data_clean['text_tokens'].apply(lambda x: word_pos_tagger(x))data_clean.head()"
},
{
"code": null,
"e": 6949,
"s": 6608,
"text": "Chunking builds on POS tagging in that it uses the information from the POS tags to extract meaningful phrases from text. In many types of texts, if we reduce everything down to individual words we may lose a lot of meaning. In our tweets, for example, we have a lot of location names and other phrases which are important to keep together."
},
{
"code": null,
"e": 7136,
"s": 6949,
"text": "If we take this sentence “forest fire near la ronge sask canada” the location name “la ronge” and the words “forest fire” will convey an important meaning that we might not want to lose."
},
{
"code": null,
"e": 7288,
"s": 7136,
"text": "The spaCy python library has a method for this. If we apply this method to the above sentence we can see that it separates out the appropriate phrases."
},
{
"code": null,
"e": 7456,
"s": 7288,
"text": "import spacynlp = spacy.load('en')text = nlp(\"forest fire near la ronge sask canada\")for chunk in text.noun_chunks: print(chunk.text, chunk.label_, chunk.root.text)"
},
{
"code": null,
"e": 7691,
"s": 7456,
"text": "This article gives a brief overview of some of the most popular methods for cleaning text data ready for natural language processing. For a deeper dive into these concepts and tools, this blog nlpforhackers.io is one of my favourites."
},
{
"code": null,
"e": 7889,
"s": 7691,
"text": "If you are interested in applying machine learning techniques to this data I wrote an article last week on how to make your first submission to the Kaggle competition where this dataset comes from."
}
] |
n-th number with digits in {0, 1, 2, 3, 4, 5} | 24 Feb, 2022
Given a number n and we have to find n-th number such that it’s digits only consist 0, 1, 2, 3, 4 or 5.
Examples :
Input: n = 6
Output: 5
Input: n = 10
Output: 13
We first store 0, 1, 2, 3, 4, 5 in an array. We can see that next numbers will be 10, 11, 12,,13, 14, 15 and after that numbers will be 20, 21, 23, 24, 25 and so on. We can see the pattern that is repeating again and again. We save the calculated result and use it for further calculations. next 6 numbers are- 1*10+0 = 10 1*10+1 = 11 1*10+2 = 12 1*10+3 = 13 1*10+4 = 14 1*10+5 = 15and after that next 6 numbers will be- 2*10+0 = 20 2*10+1 = 21 2*10+2 = 22 2*10+3 = 23 2*10+4 = 24 2*10+5 = 25We use this pattern to find the n-th number. Below is complete algorithm.
1) push 0 to 5 in ans vector
2) for i=0 to n/6
for j=0 to 6
// this will be the case when first
// digit will be zero
if (ans[i]*10! = 0)
ans.push_back(ans[i]*10 + ans[j])
3) print ans[n-1]
C++
Java
Python3
C#
Javascript
// C++ program to find n-th number with digits// in {0, 1, 2, 3, 4, 5}#include <bits/stdc++.h>using namespace std; // Returns the N-th number with given digitsint findNth(int n){ // vector to store results vector<int> ans; // push first 6 numbers in the answer for (int i = 0; i < 6; i++) ans.push_back(i); // calculate further results for (int i = 0; i <= n / 6; i++) for (int j = 0; j < 6; j++) if ((ans[i] * 10) != 0) ans.push_back(ans[i] * 10 + ans[j]); return ans[n - 1];} // Driver codeint main(){ int n = 10; cout << findNth(n); return 0;}
// Java program to find n-th number with digits// in {0, 1, 2, 3, 4, 5}import java.io.*;import java.util.*; class GFG{ // Returns the N-th number with given digits public static int findNth(int n) { // vector to store results ArrayList<Integer> ans = new ArrayList<Integer>(); // push first 6 numbers in the answer for (int i = 0; i < 6; i++) ans.add(i); // calculate further results for (int i = 0; i <= n / 6; i++) for (int j = 0; j < 6; j++) if ((ans.get(i) * 10) != 0) ans.add(ans.get(i) * 10 + ans.get(j)); return ans.get(n - 1); } // Driver code public static void main(String[] args) { int n = 10; int ans = findNth(n); System.out.println(ans); }} // This code is contributed by RohitOberoi.
# Python3 program to find n-th number with digits# in {0, 1, 2, 3, 4, 5} # Returns the N-th number with given digitsdef findNth(n): # vector to store results ans = [] # push first 6 numbers in the answer for i in range(6): ans.append(i) # calculate further results for i in range(n // 6 + 1): for j in range(6): if ((ans[i] * 10) != 0): ans.append(ans[i] * 10 + ans[j]) return ans[n - 1] # Driver codeif __name__ == "__main__": n = 10 print(findNth(n)) # This code is contributed by ukasp.
// C# program to find n-th number with digits// in {0, 1, 2, 3, 4, 5}using System;using System.Collections.Generic; class GFG{ // Returns the N-th number with given digitspublic static int findNth(int n){ // Vector to store results List<int> ans = new List<int>(); // Push first 6 numbers in the answer for(int i = 0; i < 6; i++) ans.Add(i); // Calculate further results for(int i = 0; i <= n / 6; i++) for(int j = 0; j < 6; j++) if ((ans[i] * 10) != 0) ans.Add(ans[i] * 10 + ans[j]); return ans[n - 1];} // Driver codepublic static void Main(String[] args){ int n = 10; int ans = findNth(n); Console.WriteLine(ans);}} // This code is contributed by Rajput-Ji
<script> // Javascript program to find n-th// number with digits// in {0, 1, 2, 3, 4, 5} // Returns the N-th number with given digits function findNth(n) { // vector to store results var ans = []; // push first 6 numbers in the answer for (i = 0; i < 6; i++) ans.push(i); // calculate further results for (i = 0; i <= n / 6; i++) for (j = 0; j < 6; j++) if ((ans[i] * 10) != 0) ans.push(ans[i] * 10 + ans[j]); return ans[n - 1]; } // Driver code var n = 10; var ans = findNth(n); document.write(ans); // This code contributed by Rajput-Ji </script>
13
Efficient Method :
Algorithm :
First convert number n to base 6.Store the converted value simultaneously in an array.Print that array in reverse order.
First convert number n to base 6.
Store the converted value simultaneously in an array.
Print that array in reverse order.
Below is the implementation of the above algorithm:
C++
Java
Python3
C#
Javascript
// CPP code to find nth number// with digits 0, 1, 2, 3, 4, 5#include <bits/stdc++.h>using namespace std; #define max 100000 // function to convert num to base 6int baseconversion(int arr[], int num, int base) { int i = 0, rem, j; if (num == 0) { return 0; } while (num > 0) { rem = num % base; arr[i++] = rem; num /= base; } return i;} // Driver codeint main(){ // initialize an array to 0 int arr[max] = { 0 }; int n = 10; // function calling to convert // number n to base 6 int size = baseconversion(arr, n - 1, 6); // if size is zero then return zero if (size == 0) cout << size; for (int i = size - 1; i >= 0; i--) { cout << arr[i]; } return 0;} // Code is contributed by Anivesh Tiwari.
// Java code to find nth number// with digits 0, 1, 2, 3, 4, 5class GFG { static final int max = 100000; // function to convert num to base 6 static int baseconversion(int arr[], int num, int base) { int i = 0, rem, j; if (num == 0) { return 0; } while (num > 0) { rem = num % base; arr[i++] = rem; num /= base; } return i; } // Driver code public static void main (String[] args) { // initialize an array to 0 int arr[] = new int[max]; int n = 10; // function calling to convert // number n to base 6 int size = baseconversion(arr, n - 1, 6); // if size is zero then return zero if (size == 0) System.out.print(size); for (int i = size - 1; i >= 0; i--) { System.out.print(arr[i]); } }} // This code is contributed by Anant Agarwal.
# Python code to find nth number# with digits 0, 1, 2, 3, 4, 5max = 100000; # function to convert num to base 6def baseconversion(arr, num, base): i = 0; if (num == 0): return 0; while (num > 0): rem = num % base; i = i + 1; arr[i] = rem; num = num//base; return i; # Driver codeif __name__ == '__main__': # initialize an array to 0 arr = [0 for i in range(max)]; n = 10; # function calling to convert # number n to base 6 size = baseconversion(arr, n - 1, 6); # if size is zero then return zero if (size == 0): print(size); for i in range(size, 0, -1): print(arr[i], end = ""); # This code is contributed by gauravrajput1
// C# code to find nth number// with digits 0, 1, 2, 3, 4, 5using System; class GFG { static int max = 100000; // function to convert num to base 6 static int baseconversion(int []arr, int num, int bas) { int i = 0, rem; if (num == 0) { return 0; } while (num > 0) { rem = num % bas; arr[i++] = rem; num /= bas; } return i; } // Driver code public static void Main () { // initialize an array to 0 int []arr = new int[max]; int n = 10; // function calling to convert // number n to base 6 int size = baseconversion(arr, n - 1, 6); // if size is zero then return zero if (size == 0) Console.Write(size); for (int i = size - 1; i >= 0; i--) { Console.Write(arr[i]); } }} // This code is contributed by nitin mittal
<script>// javascript code to find nth number// with digits 0, 1, 2, 3, 4, 5var max = 100000; // function to convert num to base 6 function baseconversion(arr , num , base) { var i = 0, rem, j; if (num == 0) { return 0; } while (num > 0) { rem = num % base; arr[i++] = rem; num = parseInt(num/base); } return i; } // Driver code // initialize an array to 0 var arr = Array(max).fill(0); var n = 10; // function calling to convert // number n to base 6 var size = baseconversion(arr, n - 1, 6); // if size is zero then return zero if (size == 0) document.write(size); for (i = size - 1; i >= 0; i--) { document.write(arr[i]); } // This code contributed by Rajput-Ji</script>
Output:
13
Another Efficient Method:
Algorithm:
Decrease the number N by 1.2. Convert the number N to base 6.
Decrease the number N by 1.
2. Convert the number N to base 6.
Below is the implementation of the above algorithm :
C++
Java
Python3
C#
Javascript
// C++ code to find nth number// with digits 0, 1, 2, 3, 4, 5 #include <iostream>using namespace std; int ans(int n){ // If the Number is less than 6 return the number as it is. if(n < 6){ return n; } //Call the function again and again the get the desired result. //And convert the number to base 6. return n%6 + 10*(ans(n/6));} int getSpecialNumber(int N){ //Decrease the Number by 1 and Call ans function // to convert N to base 6 return ans(--N);} /*Example:-Input: N = 17Output: 24 Explanation:-decrease 17 by 1N = 16call ans() on 16 ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less than 6 the ans returns value as it is. 4 + 10*(2) = 24 hence answer is 24.*/ int main(){ int N = 17; int answer = getSpecialNumber(N); cout<<answer<<endl; return 0;} // This Code is contributed by Regis Caelum
// Java code to find nth number// with digits 0, 1, 2, 3, 4, 5import java.util.*; class GFG{ static int ans(int n){ // If the Number is less than 6 return // the number as it is. if (n < 6) { return n; } // Call the function again and again // the get the desired result. // And convert the number to base 6. return n % 6 + 10 * (ans(n / 6));} static int getSpecialNumber(int N){ // Decrease the Number by 1 and Call // ans function to convert N to base 6 return ans(--N);} /* * Example:- Input: N = 17 Output: 24 * * Explanation:- decrease 17 by 1 N = 16 call ans() on 16 * * ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less * than 6 the ans returns value as it is. 4 + 10*(2) = 24 * * hence answer is 24. */// Driver codepublic static void main(String[] args){ int N = 17; int answer = getSpecialNumber(N); System.out.println(answer);}} // This code is contributed by Rajput-Ji
# Python3 code to find nth number# with digits 0, 1, 2, 3, 4, 5def ans(n): # If the Number is less than 6 return # the number as it is. if (n < 6): return n # Call the function again and again # the get the desired result. # And convert the number to base 6. return n % 6 + 10 * (ans(n // 6)) - 1 def getSpecialNumber(N): # Decrease the Number by 1 and Call # ans function to convert N to base 6 return ans(N) ''' * Example:- Input: N = 17 Output: 24 * * Explanation:- decrease 17 by 1 N = 16 call ans() on 16 * * ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less than 6 the ans returns * value as it is. 4 + 10*(2) = 24 * * hence answer is 24. '''# Driver codeif __name__ == '__main__': N = 17 answer = getSpecialNumber(N) print(answer) # This code contributed by aashish1995
// C# code to find nth number// with digits 0, 1, 2, 3, 4, 5using System; public class GFG{ static int ans(int n){ // If the Number is less than 6 return // the number as it is. if (n < 6) { return n; } // Call the function again and again // the get the desired result. // And convert the number to base 6. return n % 6 + 10 * (ans(n / 6));} static int getSpecialNumber(int N){ // Decrease the Number by 1 and Call // ans function to convert N to base 6 return ans(--N);} /* * Example:- Input: N = 17 Output: 24 * * Explanation:- decrease 17 by 1 N = 16 call ans() on 16 * * ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less * than 6 the ans returns value as it is. 4 + 10*(2) = 24 * * hence answer is 24. */// Driver codepublic static void Main(String[] args){ int N = 17; int answer = getSpecialNumber(N); Console.WriteLine(answer);}} // This code is contributed by Rajput-Ji
<script>// javascript code to find nth number// with digits 0, 1, 2, 3, 4, 5 function ans(n) { // If the Number is less than 6 return // the number as it is. if (n < 6) { return n; } // Call the function again and again // the get the desired result. // And convert the number to base 6. return n % 6 + 10 * (ans(parseInt(n / 6))); } function getSpecialNumber(N) { // Decrease the Number by 1 and Call // ans function to convert N to base 6 return ans(--N); } /* * Example:- Input: N = 17 Output: 24 * * Explanation:- decrease 17 by 1 N = 16 call ans() on 16 * * ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less than 6 the ans returns * value as it is. 4 + 10*(2) = 24 * * hence answer is 24. */ // Driver code var N = 17; var answer = getSpecialNumber(N); document.write(answer); // This code contributed by Rajput-Ji</script>
24
Time Complexity: O(logN)Auxiliary Space: O(1)
nitin mittal
regiscaelum
mulchandanimanisha5
RohitOberoi
ukasp
Rajput-Ji
aashish1995
GauravRajput1
kk9826225
Morgan Stanley
number-digits
Dynamic Programming
Mathematical
Morgan Stanley
Dynamic Programming
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Find if there is a path between two vertices in an undirected graph
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
Floyd Warshall Algorithm | DP-16
Coin Change | DP-7
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays
Coin Change | DP-7 | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 156,
"s": 52,
"text": "Given a number n and we have to find n-th number such that it’s digits only consist 0, 1, 2, 3, 4 or 5."
},
{
"code": null,
"e": 168,
"s": 156,
"text": "Examples : "
},
{
"code": null,
"e": 218,
"s": 168,
"text": "Input: n = 6\nOutput: 5\n\nInput: n = 10\nOutput: 13"
},
{
"code": null,
"e": 784,
"s": 218,
"text": "We first store 0, 1, 2, 3, 4, 5 in an array. We can see that next numbers will be 10, 11, 12,,13, 14, 15 and after that numbers will be 20, 21, 23, 24, 25 and so on. We can see the pattern that is repeating again and again. We save the calculated result and use it for further calculations. next 6 numbers are- 1*10+0 = 10 1*10+1 = 11 1*10+2 = 12 1*10+3 = 13 1*10+4 = 14 1*10+5 = 15and after that next 6 numbers will be- 2*10+0 = 20 2*10+1 = 21 2*10+2 = 22 2*10+3 = 23 2*10+4 = 24 2*10+5 = 25We use this pattern to find the n-th number. Below is complete algorithm."
},
{
"code": null,
"e": 1028,
"s": 784,
"text": "1) push 0 to 5 in ans vector\n2) for i=0 to n/6\n for j=0 to 6 \n // this will be the case when first \n // digit will be zero \n if (ans[i]*10! = 0) \n ans.push_back(ans[i]*10 + ans[j])\n3) print ans[n-1]"
},
{
"code": null,
"e": 1032,
"s": 1028,
"text": "C++"
},
{
"code": null,
"e": 1037,
"s": 1032,
"text": "Java"
},
{
"code": null,
"e": 1045,
"s": 1037,
"text": "Python3"
},
{
"code": null,
"e": 1048,
"s": 1045,
"text": "C#"
},
{
"code": null,
"e": 1059,
"s": 1048,
"text": "Javascript"
},
{
"code": "// C++ program to find n-th number with digits// in {0, 1, 2, 3, 4, 5}#include <bits/stdc++.h>using namespace std; // Returns the N-th number with given digitsint findNth(int n){ // vector to store results vector<int> ans; // push first 6 numbers in the answer for (int i = 0; i < 6; i++) ans.push_back(i); // calculate further results for (int i = 0; i <= n / 6; i++) for (int j = 0; j < 6; j++) if ((ans[i] * 10) != 0) ans.push_back(ans[i] * 10 + ans[j]); return ans[n - 1];} // Driver codeint main(){ int n = 10; cout << findNth(n); return 0;}",
"e": 1708,
"s": 1059,
"text": null
},
{
"code": "// Java program to find n-th number with digits// in {0, 1, 2, 3, 4, 5}import java.io.*;import java.util.*; class GFG{ // Returns the N-th number with given digits public static int findNth(int n) { // vector to store results ArrayList<Integer> ans = new ArrayList<Integer>(); // push first 6 numbers in the answer for (int i = 0; i < 6; i++) ans.add(i); // calculate further results for (int i = 0; i <= n / 6; i++) for (int j = 0; j < 6; j++) if ((ans.get(i) * 10) != 0) ans.add(ans.get(i) * 10 + ans.get(j)); return ans.get(n - 1); } // Driver code public static void main(String[] args) { int n = 10; int ans = findNth(n); System.out.println(ans); }} // This code is contributed by RohitOberoi.",
"e": 2475,
"s": 1708,
"text": null
},
{
"code": "# Python3 program to find n-th number with digits# in {0, 1, 2, 3, 4, 5} # Returns the N-th number with given digitsdef findNth(n): # vector to store results ans = [] # push first 6 numbers in the answer for i in range(6): ans.append(i) # calculate further results for i in range(n // 6 + 1): for j in range(6): if ((ans[i] * 10) != 0): ans.append(ans[i] * 10 + ans[j]) return ans[n - 1] # Driver codeif __name__ == \"__main__\": n = 10 print(findNth(n)) # This code is contributed by ukasp.",
"e": 3067,
"s": 2475,
"text": null
},
{
"code": "// C# program to find n-th number with digits// in {0, 1, 2, 3, 4, 5}using System;using System.Collections.Generic; class GFG{ // Returns the N-th number with given digitspublic static int findNth(int n){ // Vector to store results List<int> ans = new List<int>(); // Push first 6 numbers in the answer for(int i = 0; i < 6; i++) ans.Add(i); // Calculate further results for(int i = 0; i <= n / 6; i++) for(int j = 0; j < 6; j++) if ((ans[i] * 10) != 0) ans.Add(ans[i] * 10 + ans[j]); return ans[n - 1];} // Driver codepublic static void Main(String[] args){ int n = 10; int ans = findNth(n); Console.WriteLine(ans);}} // This code is contributed by Rajput-Ji",
"e": 3826,
"s": 3067,
"text": null
},
{
"code": "<script> // Javascript program to find n-th// number with digits// in {0, 1, 2, 3, 4, 5} // Returns the N-th number with given digits function findNth(n) { // vector to store results var ans = []; // push first 6 numbers in the answer for (i = 0; i < 6; i++) ans.push(i); // calculate further results for (i = 0; i <= n / 6; i++) for (j = 0; j < 6; j++) if ((ans[i] * 10) != 0) ans.push(ans[i] * 10 + ans[j]); return ans[n - 1]; } // Driver code var n = 10; var ans = findNth(n); document.write(ans); // This code contributed by Rajput-Ji </script>",
"e": 4524,
"s": 3826,
"text": null
},
{
"code": null,
"e": 4527,
"s": 4524,
"text": "13"
},
{
"code": null,
"e": 4546,
"s": 4527,
"text": "Efficient Method :"
},
{
"code": null,
"e": 4559,
"s": 4546,
"text": "Algorithm : "
},
{
"code": null,
"e": 4680,
"s": 4559,
"text": "First convert number n to base 6.Store the converted value simultaneously in an array.Print that array in reverse order."
},
{
"code": null,
"e": 4714,
"s": 4680,
"text": "First convert number n to base 6."
},
{
"code": null,
"e": 4768,
"s": 4714,
"text": "Store the converted value simultaneously in an array."
},
{
"code": null,
"e": 4803,
"s": 4768,
"text": "Print that array in reverse order."
},
{
"code": null,
"e": 4855,
"s": 4803,
"text": "Below is the implementation of the above algorithm:"
},
{
"code": null,
"e": 4859,
"s": 4855,
"text": "C++"
},
{
"code": null,
"e": 4864,
"s": 4859,
"text": "Java"
},
{
"code": null,
"e": 4872,
"s": 4864,
"text": "Python3"
},
{
"code": null,
"e": 4875,
"s": 4872,
"text": "C#"
},
{
"code": null,
"e": 4886,
"s": 4875,
"text": "Javascript"
},
{
"code": "// CPP code to find nth number// with digits 0, 1, 2, 3, 4, 5#include <bits/stdc++.h>using namespace std; #define max 100000 // function to convert num to base 6int baseconversion(int arr[], int num, int base) { int i = 0, rem, j; if (num == 0) { return 0; } while (num > 0) { rem = num % base; arr[i++] = rem; num /= base; } return i;} // Driver codeint main(){ // initialize an array to 0 int arr[max] = { 0 }; int n = 10; // function calling to convert // number n to base 6 int size = baseconversion(arr, n - 1, 6); // if size is zero then return zero if (size == 0) cout << size; for (int i = size - 1; i >= 0; i--) { cout << arr[i]; } return 0;} // Code is contributed by Anivesh Tiwari.",
"e": 5686,
"s": 4886,
"text": null
},
{
"code": "// Java code to find nth number// with digits 0, 1, 2, 3, 4, 5class GFG { static final int max = 100000; // function to convert num to base 6 static int baseconversion(int arr[], int num, int base) { int i = 0, rem, j; if (num == 0) { return 0; } while (num > 0) { rem = num % base; arr[i++] = rem; num /= base; } return i; } // Driver code public static void main (String[] args) { // initialize an array to 0 int arr[] = new int[max]; int n = 10; // function calling to convert // number n to base 6 int size = baseconversion(arr, n - 1, 6); // if size is zero then return zero if (size == 0) System.out.print(size); for (int i = size - 1; i >= 0; i--) { System.out.print(arr[i]); } }} // This code is contributed by Anant Agarwal.",
"e": 6722,
"s": 5686,
"text": null
},
{
"code": "# Python code to find nth number# with digits 0, 1, 2, 3, 4, 5max = 100000; # function to convert num to base 6def baseconversion(arr, num, base): i = 0; if (num == 0): return 0; while (num > 0): rem = num % base; i = i + 1; arr[i] = rem; num = num//base; return i; # Driver codeif __name__ == '__main__': # initialize an array to 0 arr = [0 for i in range(max)]; n = 10; # function calling to convert # number n to base 6 size = baseconversion(arr, n - 1, 6); # if size is zero then return zero if (size == 0): print(size); for i in range(size, 0, -1): print(arr[i], end = \"\"); # This code is contributed by gauravrajput1",
"e": 7440,
"s": 6722,
"text": null
},
{
"code": "// C# code to find nth number// with digits 0, 1, 2, 3, 4, 5using System; class GFG { static int max = 100000; // function to convert num to base 6 static int baseconversion(int []arr, int num, int bas) { int i = 0, rem; if (num == 0) { return 0; } while (num > 0) { rem = num % bas; arr[i++] = rem; num /= bas; } return i; } // Driver code public static void Main () { // initialize an array to 0 int []arr = new int[max]; int n = 10; // function calling to convert // number n to base 6 int size = baseconversion(arr, n - 1, 6); // if size is zero then return zero if (size == 0) Console.Write(size); for (int i = size - 1; i >= 0; i--) { Console.Write(arr[i]); } }} // This code is contributed by nitin mittal",
"e": 8450,
"s": 7440,
"text": null
},
{
"code": "<script>// javascript code to find nth number// with digits 0, 1, 2, 3, 4, 5var max = 100000; // function to convert num to base 6 function baseconversion(arr , num , base) { var i = 0, rem, j; if (num == 0) { return 0; } while (num > 0) { rem = num % base; arr[i++] = rem; num = parseInt(num/base); } return i; } // Driver code // initialize an array to 0 var arr = Array(max).fill(0); var n = 10; // function calling to convert // number n to base 6 var size = baseconversion(arr, n - 1, 6); // if size is zero then return zero if (size == 0) document.write(size); for (i = size - 1; i >= 0; i--) { document.write(arr[i]); } // This code contributed by Rajput-Ji</script>",
"e": 9330,
"s": 8450,
"text": null
},
{
"code": null,
"e": 9339,
"s": 9330,
"text": "Output: "
},
{
"code": null,
"e": 9342,
"s": 9339,
"text": "13"
},
{
"code": null,
"e": 9368,
"s": 9342,
"text": "Another Efficient Method:"
},
{
"code": null,
"e": 9379,
"s": 9368,
"text": "Algorithm:"
},
{
"code": null,
"e": 9441,
"s": 9379,
"text": "Decrease the number N by 1.2. Convert the number N to base 6."
},
{
"code": null,
"e": 9469,
"s": 9441,
"text": "Decrease the number N by 1."
},
{
"code": null,
"e": 9504,
"s": 9469,
"text": "2. Convert the number N to base 6."
},
{
"code": null,
"e": 9557,
"s": 9504,
"text": "Below is the implementation of the above algorithm :"
},
{
"code": null,
"e": 9561,
"s": 9557,
"text": "C++"
},
{
"code": null,
"e": 9566,
"s": 9561,
"text": "Java"
},
{
"code": null,
"e": 9574,
"s": 9566,
"text": "Python3"
},
{
"code": null,
"e": 9577,
"s": 9574,
"text": "C#"
},
{
"code": null,
"e": 9588,
"s": 9577,
"text": "Javascript"
},
{
"code": "// C++ code to find nth number// with digits 0, 1, 2, 3, 4, 5 #include <iostream>using namespace std; int ans(int n){ // If the Number is less than 6 return the number as it is. if(n < 6){ return n; } //Call the function again and again the get the desired result. //And convert the number to base 6. return n%6 + 10*(ans(n/6));} int getSpecialNumber(int N){ //Decrease the Number by 1 and Call ans function // to convert N to base 6 return ans(--N);} /*Example:-Input: N = 17Output: 24 Explanation:-decrease 17 by 1N = 16call ans() on 16 ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less than 6 the ans returns value as it is. 4 + 10*(2) = 24 hence answer is 24.*/ int main(){ int N = 17; int answer = getSpecialNumber(N); cout<<answer<<endl; return 0;} // This Code is contributed by Regis Caelum",
"e": 10424,
"s": 9588,
"text": null
},
{
"code": "// Java code to find nth number// with digits 0, 1, 2, 3, 4, 5import java.util.*; class GFG{ static int ans(int n){ // If the Number is less than 6 return // the number as it is. if (n < 6) { return n; } // Call the function again and again // the get the desired result. // And convert the number to base 6. return n % 6 + 10 * (ans(n / 6));} static int getSpecialNumber(int N){ // Decrease the Number by 1 and Call // ans function to convert N to base 6 return ans(--N);} /* * Example:- Input: N = 17 Output: 24 * * Explanation:- decrease 17 by 1 N = 16 call ans() on 16 * * ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less * than 6 the ans returns value as it is. 4 + 10*(2) = 24 * * hence answer is 24. */// Driver codepublic static void main(String[] args){ int N = 17; int answer = getSpecialNumber(N); System.out.println(answer);}} // This code is contributed by Rajput-Ji",
"e": 11382,
"s": 10424,
"text": null
},
{
"code": "# Python3 code to find nth number# with digits 0, 1, 2, 3, 4, 5def ans(n): # If the Number is less than 6 return # the number as it is. if (n < 6): return n # Call the function again and again # the get the desired result. # And convert the number to base 6. return n % 6 + 10 * (ans(n // 6)) - 1 def getSpecialNumber(N): # Decrease the Number by 1 and Call # ans function to convert N to base 6 return ans(N) ''' * Example:- Input: N = 17 Output: 24 * * Explanation:- decrease 17 by 1 N = 16 call ans() on 16 * * ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less than 6 the ans returns * value as it is. 4 + 10*(2) = 24 * * hence answer is 24. '''# Driver codeif __name__ == '__main__': N = 17 answer = getSpecialNumber(N) print(answer) # This code contributed by aashish1995",
"e": 12227,
"s": 11382,
"text": null
},
{
"code": "// C# code to find nth number// with digits 0, 1, 2, 3, 4, 5using System; public class GFG{ static int ans(int n){ // If the Number is less than 6 return // the number as it is. if (n < 6) { return n; } // Call the function again and again // the get the desired result. // And convert the number to base 6. return n % 6 + 10 * (ans(n / 6));} static int getSpecialNumber(int N){ // Decrease the Number by 1 and Call // ans function to convert N to base 6 return ans(--N);} /* * Example:- Input: N = 17 Output: 24 * * Explanation:- decrease 17 by 1 N = 16 call ans() on 16 * * ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less * than 6 the ans returns value as it is. 4 + 10*(2) = 24 * * hence answer is 24. */// Driver codepublic static void Main(String[] args){ int N = 17; int answer = getSpecialNumber(N); Console.WriteLine(answer);}} // This code is contributed by Rajput-Ji",
"e": 13184,
"s": 12227,
"text": null
},
{
"code": "<script>// javascript code to find nth number// with digits 0, 1, 2, 3, 4, 5 function ans(n) { // If the Number is less than 6 return // the number as it is. if (n < 6) { return n; } // Call the function again and again // the get the desired result. // And convert the number to base 6. return n % 6 + 10 * (ans(parseInt(n / 6))); } function getSpecialNumber(N) { // Decrease the Number by 1 and Call // ans function to convert N to base 6 return ans(--N); } /* * Example:- Input: N = 17 Output: 24 * * Explanation:- decrease 17 by 1 N = 16 call ans() on 16 * * ans(): 16%6 + 10*(ans(16/6)) since 16/6 = 2 it is less than 6 the ans returns * value as it is. 4 + 10*(2) = 24 * * hence answer is 24. */ // Driver code var N = 17; var answer = getSpecialNumber(N); document.write(answer); // This code contributed by Rajput-Ji</script>",
"e": 14193,
"s": 13184,
"text": null
},
{
"code": null,
"e": 14196,
"s": 14193,
"text": "24"
},
{
"code": null,
"e": 14242,
"s": 14196,
"text": "Time Complexity: O(logN)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 14255,
"s": 14242,
"text": "nitin mittal"
},
{
"code": null,
"e": 14267,
"s": 14255,
"text": "regiscaelum"
},
{
"code": null,
"e": 14287,
"s": 14267,
"text": "mulchandanimanisha5"
},
{
"code": null,
"e": 14299,
"s": 14287,
"text": "RohitOberoi"
},
{
"code": null,
"e": 14305,
"s": 14299,
"text": "ukasp"
},
{
"code": null,
"e": 14315,
"s": 14305,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 14327,
"s": 14315,
"text": "aashish1995"
},
{
"code": null,
"e": 14341,
"s": 14327,
"text": "GauravRajput1"
},
{
"code": null,
"e": 14351,
"s": 14341,
"text": "kk9826225"
},
{
"code": null,
"e": 14366,
"s": 14351,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 14380,
"s": 14366,
"text": "number-digits"
},
{
"code": null,
"e": 14400,
"s": 14380,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 14413,
"s": 14400,
"text": "Mathematical"
},
{
"code": null,
"e": 14428,
"s": 14413,
"text": "Morgan Stanley"
},
{
"code": null,
"e": 14448,
"s": 14428,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 14461,
"s": 14448,
"text": "Mathematical"
},
{
"code": null,
"e": 14559,
"s": 14461,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 14627,
"s": 14559,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 14654,
"s": 14627,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 14692,
"s": 14654,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 14725,
"s": 14692,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 14744,
"s": 14725,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 14787,
"s": 14744,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 14847,
"s": 14787,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 14862,
"s": 14847,
"text": "C++ Data Types"
},
{
"code": null,
"e": 14886,
"s": 14862,
"text": "Merge two sorted arrays"
}
] |
java.net.ServerSocket Class in Java | 27 Apr, 2022
ServerSocket Class is used for providing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket throws an exception if it can’t listen on the specified port (for example, the port is already being used).
It is widely used so the applications of java.net.ServerSocket class which is as follows:
In java.nio channel, ServerSocket class is used for retrieving a serverSocket associated with this channel.In java.rmi.Server, ServerSocket class is used to create a server socket on the specified port (port 0 indicates an anonymous port).In javax.net, Server socket is used widely so as to:return an unbound server socket.return a server socket bound to the specified port.return a server socket bound to the specified port, and uses the specified connection backlog.return a server socket bound to the specified port, with a specified listen backlog and local IP.
In java.nio channel, ServerSocket class is used for retrieving a serverSocket associated with this channel.
In java.rmi.Server, ServerSocket class is used to create a server socket on the specified port (port 0 indicates an anonymous port).
In javax.net, Server socket is used widely so as to:return an unbound server socket.return a server socket bound to the specified port.return a server socket bound to the specified port, and uses the specified connection backlog.return a server socket bound to the specified port, with a specified listen backlog and local IP.
return an unbound server socket.
return a server socket bound to the specified port.
return a server socket bound to the specified port, and uses the specified connection backlog.
return a server socket bound to the specified port, with a specified listen backlog and local IP.
Let us do go through the methods of this class which is as follows:
implementation:
Example 1 Server-Side
Java
// Java Program to implement ServerSocket class// Server Side // Importing required librariesimport java.io.*;import java.net.*; // Main classpublic class MyServer { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating an object of ServerSocket class // in the main() method for socket connection ServerSocket ss = new ServerSocket(6666); // Establishing a connection Socket soc = ss.accept(); // Invoking input stream via getInputStream() // method by creating DataInputStream class // object DataInputStream dis = new DataInputStream(soc.getInputStream()); String str = (String)dis.readUTF(); // Display the string on the console System.out.println("message= " + str); // Lastly close the socket using standard close // method to release memory resources ss.close(); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception on the console System.out.println(e); } }}
Output:
Example 2 Client-Side
Java
// Java Program to implement ServerSocket class// Client - side // Importing required librariesimport java.io.*;import java.net.*; // Main classpublic class MyClient { // Main driver method public static void main(String[] args) { // Try block to check if exception occurs try { // Creating Socket class object and // initializing Socket Socket soc = new Socket("localhost", 6666); DataOutputStream d = new DataOutputStream( soc.getOutputStream()); // Message to be displayed d.writeUTF("Hello GFG Readers!"); // Flushing out internal buffers, // optimizing for better performance d.flush(); // Closing the connections // Closing DataOutputStream d.close(); // Closing socket soc.close(); } // Catch block to handle exceptions catch (Exception e) { // Print the exception on the console System.out.println(e); } }}
Output:
saurabh1990aror
sooda367
gabaa406
anikakapoor
eklw78ks3sewuo2ouubbbd70mv9tis3ve13vmi3c
Java-net-package
Picked
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Apr, 2022"
},
{
"code": null,
"e": 301,
"s": 28,
"text": "ServerSocket Class is used for providing system-independent implementation of the server-side of a client/server Socket Connection. The constructor for ServerSocket throws an exception if it can’t listen on the specified port (for example, the port is already being used)."
},
{
"code": null,
"e": 391,
"s": 301,
"text": "It is widely used so the applications of java.net.ServerSocket class which is as follows:"
},
{
"code": null,
"e": 957,
"s": 391,
"text": "In java.nio channel, ServerSocket class is used for retrieving a serverSocket associated with this channel.In java.rmi.Server, ServerSocket class is used to create a server socket on the specified port (port 0 indicates an anonymous port).In javax.net, Server socket is used widely so as to:return an unbound server socket.return a server socket bound to the specified port.return a server socket bound to the specified port, and uses the specified connection backlog.return a server socket bound to the specified port, with a specified listen backlog and local IP."
},
{
"code": null,
"e": 1065,
"s": 957,
"text": "In java.nio channel, ServerSocket class is used for retrieving a serverSocket associated with this channel."
},
{
"code": null,
"e": 1198,
"s": 1065,
"text": "In java.rmi.Server, ServerSocket class is used to create a server socket on the specified port (port 0 indicates an anonymous port)."
},
{
"code": null,
"e": 1525,
"s": 1198,
"text": "In javax.net, Server socket is used widely so as to:return an unbound server socket.return a server socket bound to the specified port.return a server socket bound to the specified port, and uses the specified connection backlog.return a server socket bound to the specified port, with a specified listen backlog and local IP."
},
{
"code": null,
"e": 1558,
"s": 1525,
"text": "return an unbound server socket."
},
{
"code": null,
"e": 1610,
"s": 1558,
"text": "return a server socket bound to the specified port."
},
{
"code": null,
"e": 1705,
"s": 1610,
"text": "return a server socket bound to the specified port, and uses the specified connection backlog."
},
{
"code": null,
"e": 1803,
"s": 1705,
"text": "return a server socket bound to the specified port, with a specified listen backlog and local IP."
},
{
"code": null,
"e": 1871,
"s": 1803,
"text": "Let us do go through the methods of this class which is as follows:"
},
{
"code": null,
"e": 1887,
"s": 1871,
"text": "implementation:"
},
{
"code": null,
"e": 1909,
"s": 1887,
"text": "Example 1 Server-Side"
},
{
"code": null,
"e": 1914,
"s": 1909,
"text": "Java"
},
{
"code": "// Java Program to implement ServerSocket class// Server Side // Importing required librariesimport java.io.*;import java.net.*; // Main classpublic class MyServer { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating an object of ServerSocket class // in the main() method for socket connection ServerSocket ss = new ServerSocket(6666); // Establishing a connection Socket soc = ss.accept(); // Invoking input stream via getInputStream() // method by creating DataInputStream class // object DataInputStream dis = new DataInputStream(soc.getInputStream()); String str = (String)dis.readUTF(); // Display the string on the console System.out.println(\"message= \" + str); // Lastly close the socket using standard close // method to release memory resources ss.close(); } // Catch block to handle the exceptions catch (Exception e) { // Display the exception on the console System.out.println(e); } }}",
"e": 3147,
"s": 1914,
"text": null
},
{
"code": null,
"e": 3155,
"s": 3147,
"text": "Output:"
},
{
"code": null,
"e": 3178,
"s": 3155,
"text": "Example 2 Client-Side "
},
{
"code": null,
"e": 3183,
"s": 3178,
"text": "Java"
},
{
"code": "// Java Program to implement ServerSocket class// Client - side // Importing required librariesimport java.io.*;import java.net.*; // Main classpublic class MyClient { // Main driver method public static void main(String[] args) { // Try block to check if exception occurs try { // Creating Socket class object and // initializing Socket Socket soc = new Socket(\"localhost\", 6666); DataOutputStream d = new DataOutputStream( soc.getOutputStream()); // Message to be displayed d.writeUTF(\"Hello GFG Readers!\"); // Flushing out internal buffers, // optimizing for better performance d.flush(); // Closing the connections // Closing DataOutputStream d.close(); // Closing socket soc.close(); } // Catch block to handle exceptions catch (Exception e) { // Print the exception on the console System.out.println(e); } }}",
"e": 4253,
"s": 3183,
"text": null
},
{
"code": null,
"e": 4261,
"s": 4253,
"text": "Output:"
},
{
"code": null,
"e": 4279,
"s": 4263,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 4288,
"s": 4279,
"text": "sooda367"
},
{
"code": null,
"e": 4297,
"s": 4288,
"text": "gabaa406"
},
{
"code": null,
"e": 4309,
"s": 4297,
"text": "anikakapoor"
},
{
"code": null,
"e": 4350,
"s": 4309,
"text": "eklw78ks3sewuo2ouubbbd70mv9tis3ve13vmi3c"
},
{
"code": null,
"e": 4367,
"s": 4350,
"text": "Java-net-package"
},
{
"code": null,
"e": 4374,
"s": 4367,
"text": "Picked"
},
{
"code": null,
"e": 4379,
"s": 4374,
"text": "Java"
},
{
"code": null,
"e": 4384,
"s": 4379,
"text": "Java"
}
] |
Tensorflow.js tf.layers.dense() Function | 26 May, 2021
The tf.layers.dense() is an inbuilt function of Tensorflow.js library. This function is used to create fully connected layers, in which every output depends on every input.
Syntax:
tf.layers.dense(args)
Parameters: This function takes the args object as a parameter which can have the following properties:
units: It is a positive number that defines the dimensionality of the output space.
activation: Specifies which activation function to use.
useBias: specifies whether to apply a bias or not.
kernelInitializer: Specifies which initializer to use for the dense kernel weight matrix.
biasInitializer: Specifies the bias vector for this layer.
inputDim: Defines input shape as [inputDim].
kernelConstraint: Specifies the constraint for the kernel.
biasConstraint: Specifics constraint for the bias vector.
kernelRegularizer: Specifies the regularizer function applied to the dense kernel weights matrix.
biasRegularizer: Specifies the regularizer function applied to the bias vector.
activityRegularizer: Specifies the regularizer function applied to the activation.
inputShape: If this parameter is defined, it will create another input layer to insert before this layer.
batchInputShape: If this parameter is defined, it will create another input layer to insert before this layer.
batchSize : Used to construct batchInputShape, if not already specified.
dtype: Specifies the data type for this layer. The default value of this parameter is ‘float32’.
name: Specifies name for this layer.
trainable: Specifies whether the weights of this layer are updated by fit.
weights: Specifies the initial weight values of the layer.
inputDType : It is used to denote the inputDType and its value can be ‘float32’ or ‘int32’ or ‘bool’ or ‘complex64’ or ‘string’.
Return value: It returns a Dense object.
Example 1:
Javascript
import * as tf from "@tensorflow/tfjs" // Create a new dense layerconst denseLayer = tf.layers.dense({ units: 2, kernelInitializer: 'heNormal', useBias: true}); const input = tf.ones([2, 3]);const output = denseLayer.apply(input); // Print the outputoutput.print()
Output:
Example 2:
Javascript
import * as tf from "@tensorflow/tfjs" // Create a new dense layerconst denseLayer = tf.layers.dense({ units: 3, kernelInitializer: 'heNormal', useBias: false}); const input = tf.ones([2, 3, 3]);const output = denseLayer.apply(input); // Print the outputoutput.print()
Output:
Example 3:
Javascript
import * as tf from "@tensorflow/tfjs" // Create a new dense layerconst denseLayer = tf.layers.dense({ units: 3, kernelInitializer: 'ones', useBias: false}); const input = tf.ones([2, 3, 3]);const output = denseLayer.apply(input); // Print the outputoutput.print()
Output:
Example 4:
Javascript
import * as tf from "@tensorflow/tfjs" // Create a new dense layerconst denseLayer = tf.layers.dense({ units: 3, kernelInitializer: 'randomUniform', useBias: false}); const input = tf.ones([2, 3, 3]);const output = denseLayer.apply(input); // Print the outputoutput.print()
Output:
Reference: https://js.tensorflow.org/api/latest/#layers.dense
Picked
Tensorflow
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 227,
"s": 54,
"text": "The tf.layers.dense() is an inbuilt function of Tensorflow.js library. This function is used to create fully connected layers, in which every output depends on every input."
},
{
"code": null,
"e": 235,
"s": 227,
"text": "Syntax:"
},
{
"code": null,
"e": 257,
"s": 235,
"text": "tf.layers.dense(args)"
},
{
"code": null,
"e": 361,
"s": 257,
"text": "Parameters: This function takes the args object as a parameter which can have the following properties:"
},
{
"code": null,
"e": 445,
"s": 361,
"text": "units: It is a positive number that defines the dimensionality of the output space."
},
{
"code": null,
"e": 501,
"s": 445,
"text": "activation: Specifies which activation function to use."
},
{
"code": null,
"e": 552,
"s": 501,
"text": "useBias: specifies whether to apply a bias or not."
},
{
"code": null,
"e": 642,
"s": 552,
"text": "kernelInitializer: Specifies which initializer to use for the dense kernel weight matrix."
},
{
"code": null,
"e": 701,
"s": 642,
"text": "biasInitializer: Specifies the bias vector for this layer."
},
{
"code": null,
"e": 746,
"s": 701,
"text": "inputDim: Defines input shape as [inputDim]."
},
{
"code": null,
"e": 805,
"s": 746,
"text": "kernelConstraint: Specifies the constraint for the kernel."
},
{
"code": null,
"e": 863,
"s": 805,
"text": "biasConstraint: Specifics constraint for the bias vector."
},
{
"code": null,
"e": 961,
"s": 863,
"text": "kernelRegularizer: Specifies the regularizer function applied to the dense kernel weights matrix."
},
{
"code": null,
"e": 1041,
"s": 961,
"text": "biasRegularizer: Specifies the regularizer function applied to the bias vector."
},
{
"code": null,
"e": 1124,
"s": 1041,
"text": "activityRegularizer: Specifies the regularizer function applied to the activation."
},
{
"code": null,
"e": 1230,
"s": 1124,
"text": "inputShape: If this parameter is defined, it will create another input layer to insert before this layer."
},
{
"code": null,
"e": 1341,
"s": 1230,
"text": "batchInputShape: If this parameter is defined, it will create another input layer to insert before this layer."
},
{
"code": null,
"e": 1414,
"s": 1341,
"text": "batchSize : Used to construct batchInputShape, if not already specified."
},
{
"code": null,
"e": 1511,
"s": 1414,
"text": "dtype: Specifies the data type for this layer. The default value of this parameter is ‘float32’."
},
{
"code": null,
"e": 1548,
"s": 1511,
"text": "name: Specifies name for this layer."
},
{
"code": null,
"e": 1623,
"s": 1548,
"text": "trainable: Specifies whether the weights of this layer are updated by fit."
},
{
"code": null,
"e": 1682,
"s": 1623,
"text": "weights: Specifies the initial weight values of the layer."
},
{
"code": null,
"e": 1811,
"s": 1682,
"text": "inputDType : It is used to denote the inputDType and its value can be ‘float32’ or ‘int32’ or ‘bool’ or ‘complex64’ or ‘string’."
},
{
"code": null,
"e": 1852,
"s": 1811,
"text": "Return value: It returns a Dense object."
},
{
"code": null,
"e": 1863,
"s": 1852,
"text": "Example 1:"
},
{
"code": null,
"e": 1874,
"s": 1863,
"text": "Javascript"
},
{
"code": "import * as tf from \"@tensorflow/tfjs\" // Create a new dense layerconst denseLayer = tf.layers.dense({ units: 2, kernelInitializer: 'heNormal', useBias: true}); const input = tf.ones([2, 3]);const output = denseLayer.apply(input); // Print the outputoutput.print()",
"e": 2152,
"s": 1874,
"text": null
},
{
"code": null,
"e": 2160,
"s": 2152,
"text": "Output:"
},
{
"code": null,
"e": 2171,
"s": 2160,
"text": "Example 2:"
},
{
"code": null,
"e": 2182,
"s": 2171,
"text": "Javascript"
},
{
"code": "import * as tf from \"@tensorflow/tfjs\" // Create a new dense layerconst denseLayer = tf.layers.dense({ units: 3, kernelInitializer: 'heNormal', useBias: false}); const input = tf.ones([2, 3, 3]);const output = denseLayer.apply(input); // Print the outputoutput.print()",
"e": 2464,
"s": 2182,
"text": null
},
{
"code": null,
"e": 2472,
"s": 2464,
"text": "Output:"
},
{
"code": null,
"e": 2483,
"s": 2472,
"text": "Example 3:"
},
{
"code": null,
"e": 2494,
"s": 2483,
"text": "Javascript"
},
{
"code": "import * as tf from \"@tensorflow/tfjs\" // Create a new dense layerconst denseLayer = tf.layers.dense({ units: 3, kernelInitializer: 'ones', useBias: false}); const input = tf.ones([2, 3, 3]);const output = denseLayer.apply(input); // Print the outputoutput.print()",
"e": 2774,
"s": 2494,
"text": null
},
{
"code": null,
"e": 2782,
"s": 2774,
"text": "Output:"
},
{
"code": null,
"e": 2793,
"s": 2782,
"text": "Example 4:"
},
{
"code": null,
"e": 2804,
"s": 2793,
"text": "Javascript"
},
{
"code": "import * as tf from \"@tensorflow/tfjs\" // Create a new dense layerconst denseLayer = tf.layers.dense({ units: 3, kernelInitializer: 'randomUniform', useBias: false}); const input = tf.ones([2, 3, 3]);const output = denseLayer.apply(input); // Print the outputoutput.print()",
"e": 3091,
"s": 2804,
"text": null
},
{
"code": null,
"e": 3099,
"s": 3091,
"text": "Output:"
},
{
"code": null,
"e": 3161,
"s": 3099,
"text": "Reference: https://js.tensorflow.org/api/latest/#layers.dense"
},
{
"code": null,
"e": 3168,
"s": 3161,
"text": "Picked"
},
{
"code": null,
"e": 3179,
"s": 3168,
"text": "Tensorflow"
},
{
"code": null,
"e": 3193,
"s": 3179,
"text": "Tensorflow.js"
},
{
"code": null,
"e": 3204,
"s": 3193,
"text": "JavaScript"
},
{
"code": null,
"e": 3221,
"s": 3204,
"text": "Web Technologies"
}
] |
Find the winner of the game with N piles of boxes | 14 Jun, 2022
Given N piles containing White(W) and Black(B) boxes only, two players A and B play a game. Player A may remove any number of boxes from the top of the pile having the topmost box White, and Player B may remove any number of boxes from the top of the pile having the topmost box Black. If there is a pile with top as W, then player A has removed one or more boxes. Similarly, if there is a pile with top as B, then player B has to remove one or more boxes. They play alternating, with the player A first to move. Both players play optimally. The task is to find the winner of the game (who cannot make the last move). Player last to move loses the game.Examples:
Input: N = 2 WBW, BWB Output: A Player A can remove all boxes from pile 1. Now player B has to make a choice from pile 2. Whatever choice player B makes, he/she has to make the last move.Input: N = 3 WWWW, WBWB, WBBW Output: B
Approach: The game theory problems, where the player who makes the last move lose the game, are called Misère Nim’s Game.
If there are consecutive occurrences of the same box in any pile, we can simply replace them with one copy of the same box, since it is optimal to remove all occurrences of the box present at the top. So, we can compress all piles to get the pile of form BWBWBW or WBWBWB.Now, suppose there’s a pile, which have topmost box differing from its bottom-most box, we can prove that the answer remains the same even without this pile, because if one player makes a move on this pile, the other player makes the next move by removing a box from the same pile, resulting in exactly same position for the first player.If a pile has both top and bottom-most box as the same, It requires one or the player to make one extra move. So, just count the number of extra move each player has to make. The player which runs off out extra moves first wins the game.
If there are consecutive occurrences of the same box in any pile, we can simply replace them with one copy of the same box, since it is optimal to remove all occurrences of the box present at the top. So, we can compress all piles to get the pile of form BWBWBW or WBWBWB.
Now, suppose there’s a pile, which have topmost box differing from its bottom-most box, we can prove that the answer remains the same even without this pile, because if one player makes a move on this pile, the other player makes the next move by removing a box from the same pile, resulting in exactly same position for the first player.
If a pile has both top and bottom-most box as the same, It requires one or the player to make one extra move. So, just count the number of extra move each player has to make. The player which runs off out extra moves first wins the game.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// Program to find winner of the game#include <bits/stdc++.h>using namespace std; // Function to return find winner of gamestring Winner(int n, string pile[]){ int a = 0, b = 0; for (int i = 0; i < n; ++i) { int l = pile[i].length(); // Piles begins and ends with White box 'W' if (pile[i][0] == pile[i][l - 1] && pile[i][0] == 'W') a++; // Piles begins and ends with Black box 'B' if (pile[i][0] == pile[i][l - 1] && pile[i][0] == 'B') b++; } if (a <= b) return "A"; else return "B";} // Driver codeint main(){ int n = 2; string pile[n] = { "WBW", "BWB" }; // function to print required answer cout << Winner(n, pile); return 0;}
// Program to find winner of the gameclass GFG{ // Function to return find winner of gamestatic String Winner(int n, String []pile){ int a = 0, b = 0; for (int i = 0; i < n; ++i) { int l = pile[i].length(); // Piles begins and ends with White box 'W' if (pile[i].charAt(0) == pile[i].charAt(l - 1) && pile[i].charAt(0) == 'W') a++; // Piles begins and ends with Black box 'B' if (pile[i].charAt(0) == pile[i].charAt(l - 1) && pile[i].charAt(0) == 'B') b++; } if (a <= b) return "A"; else return "B";} // Driver codepublic static void main(String[] args){ int n = 2; String pile[] = { "WBW", "BWB" }; // function to print required answer System.out.println(Winner(n, pile));}} // This code is contributed by Rajput-Ji
# Python3 code to find winner of the game # Function to return find winner of gamedef Winner(n, pile): a, b = 0, 0 for i in range(0, n): l = len(pile[i]) # Piles begins and ends with White box 'W' if (pile[i][0] == pile[i][l - 1] and pile[i][0] == 'W'): a += 1 # Piles begins and ends with Black box 'B' if (pile[i][0] == pile[i][l - 1] and pile[i][0] == 'B'): b += 1 if a <= b: return "A" else: return "B" # Driver codeif __name__ == "__main__": n = 2 pile = ["WBW", "BWB"] # function to print required answer print(Winner(n, pile)) # This code is contributed by Rituraj Jain
// Program to find winner of the gameusing System; class GFG{ // Function to return find winner of gamestatic String Winner(int n, String []pile){ int a = 0, b = 0; for (int i = 0; i < n; ++i) { int l = pile[i].Length; // Piles begins and ends with White box 'W' if (pile[i][0] == pile[i][l - 1] && pile[i][0] == 'W') a++; // Piles begins and ends with Black box 'B' if (pile[i][0] == pile[i][l - 1] && pile[i][0] == 'B') b++; } if (a <= b) return "A"; else return "B";} // Driver codepublic static void Main(String[] args){ int n = 2; String []pile = { "WBW", "BWB" }; // function to print required answer Console.WriteLine(Winner(n, pile));}} // This code is contributed by Princi Singh
<script> // Program to find winner of the game // Function to return find winner of gamefunction Winner(n, pile){ var a = 0, b = 0; for (var i = 0; i < n; ++i) { var l = pile[i].length; // Piles begins and ends with White box 'W' if (pile[i][0] == pile[i][l - 1] && pile[i][0] == 'W') a++; // Piles begins and ends with Black box 'B' if (pile[i][0] == pile[i][l - 1] && pile[i][0] == 'B') b++; } if (a <= b) return "A"; else return "B";} // Driver codevar n = 2;var pile = ["WBW", "BWB"]; // function to print required answerdocument.write( Winner(n, pile)); // This code is contributed by noob2000.</script>
A
Time Complexity: O(N)
Auxiliary Space : O(1)
rituraj_jain
Rajput-Ji
princi singh
noob2000
devendrasalunke
Game Theory
Game Theory
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chessboard Pawn-Pawn game
Josephus Problem | (Iterative Solution)
Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)
Minesweeper Solver
Classification of Algorithms with Examples
Zero-Sum Game
Find the player who will win by choosing a number in range [1, K] with sum total N
Game Theory (Normal-form Game) | Set 6 (Graphical Method [2 X N] Game)
Maximum cells attacked by Rook or Bishop in given Chessboard
Game Development with Unity | Introduction | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 717,
"s": 52,
"text": "Given N piles containing White(W) and Black(B) boxes only, two players A and B play a game. Player A may remove any number of boxes from the top of the pile having the topmost box White, and Player B may remove any number of boxes from the top of the pile having the topmost box Black. If there is a pile with top as W, then player A has removed one or more boxes. Similarly, if there is a pile with top as B, then player B has to remove one or more boxes. They play alternating, with the player A first to move. Both players play optimally. The task is to find the winner of the game (who cannot make the last move). Player last to move loses the game.Examples: "
},
{
"code": null,
"e": 944,
"s": 717,
"text": "Input: N = 2 WBW, BWB Output: A Player A can remove all boxes from pile 1. Now player B has to make a choice from pile 2. Whatever choice player B makes, he/she has to make the last move.Input: N = 3 WWWW, WBWB, WBBW Output: B"
},
{
"code": null,
"e": 1071,
"s": 946,
"text": "Approach: The game theory problems, where the player who makes the last move lose the game, are called Misère Nim’s Game. "
},
{
"code": null,
"e": 1919,
"s": 1071,
"text": "If there are consecutive occurrences of the same box in any pile, we can simply replace them with one copy of the same box, since it is optimal to remove all occurrences of the box present at the top. So, we can compress all piles to get the pile of form BWBWBW or WBWBWB.Now, suppose there’s a pile, which have topmost box differing from its bottom-most box, we can prove that the answer remains the same even without this pile, because if one player makes a move on this pile, the other player makes the next move by removing a box from the same pile, resulting in exactly same position for the first player.If a pile has both top and bottom-most box as the same, It requires one or the player to make one extra move. So, just count the number of extra move each player has to make. The player which runs off out extra moves first wins the game."
},
{
"code": null,
"e": 2192,
"s": 1919,
"text": "If there are consecutive occurrences of the same box in any pile, we can simply replace them with one copy of the same box, since it is optimal to remove all occurrences of the box present at the top. So, we can compress all piles to get the pile of form BWBWBW or WBWBWB."
},
{
"code": null,
"e": 2531,
"s": 2192,
"text": "Now, suppose there’s a pile, which have topmost box differing from its bottom-most box, we can prove that the answer remains the same even without this pile, because if one player makes a move on this pile, the other player makes the next move by removing a box from the same pile, resulting in exactly same position for the first player."
},
{
"code": null,
"e": 2769,
"s": 2531,
"text": "If a pile has both top and bottom-most box as the same, It requires one or the player to make one extra move. So, just count the number of extra move each player has to make. The player which runs off out extra moves first wins the game."
},
{
"code": null,
"e": 2821,
"s": 2769,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 2825,
"s": 2821,
"text": "C++"
},
{
"code": null,
"e": 2830,
"s": 2825,
"text": "Java"
},
{
"code": null,
"e": 2838,
"s": 2830,
"text": "Python3"
},
{
"code": null,
"e": 2841,
"s": 2838,
"text": "C#"
},
{
"code": null,
"e": 2852,
"s": 2841,
"text": "Javascript"
},
{
"code": "// Program to find winner of the game#include <bits/stdc++.h>using namespace std; // Function to return find winner of gamestring Winner(int n, string pile[]){ int a = 0, b = 0; for (int i = 0; i < n; ++i) { int l = pile[i].length(); // Piles begins and ends with White box 'W' if (pile[i][0] == pile[i][l - 1] && pile[i][0] == 'W') a++; // Piles begins and ends with Black box 'B' if (pile[i][0] == pile[i][l - 1] && pile[i][0] == 'B') b++; } if (a <= b) return \"A\"; else return \"B\";} // Driver codeint main(){ int n = 2; string pile[n] = { \"WBW\", \"BWB\" }; // function to print required answer cout << Winner(n, pile); return 0;}",
"e": 3590,
"s": 2852,
"text": null
},
{
"code": "// Program to find winner of the gameclass GFG{ // Function to return find winner of gamestatic String Winner(int n, String []pile){ int a = 0, b = 0; for (int i = 0; i < n; ++i) { int l = pile[i].length(); // Piles begins and ends with White box 'W' if (pile[i].charAt(0) == pile[i].charAt(l - 1) && pile[i].charAt(0) == 'W') a++; // Piles begins and ends with Black box 'B' if (pile[i].charAt(0) == pile[i].charAt(l - 1) && pile[i].charAt(0) == 'B') b++; } if (a <= b) return \"A\"; else return \"B\";} // Driver codepublic static void main(String[] args){ int n = 2; String pile[] = { \"WBW\", \"BWB\" }; // function to print required answer System.out.println(Winner(n, pile));}} // This code is contributed by Rajput-Ji",
"e": 4434,
"s": 3590,
"text": null
},
{
"code": "# Python3 code to find winner of the game # Function to return find winner of gamedef Winner(n, pile): a, b = 0, 0 for i in range(0, n): l = len(pile[i]) # Piles begins and ends with White box 'W' if (pile[i][0] == pile[i][l - 1] and pile[i][0] == 'W'): a += 1 # Piles begins and ends with Black box 'B' if (pile[i][0] == pile[i][l - 1] and pile[i][0] == 'B'): b += 1 if a <= b: return \"A\" else: return \"B\" # Driver codeif __name__ == \"__main__\": n = 2 pile = [\"WBW\", \"BWB\"] # function to print required answer print(Winner(n, pile)) # This code is contributed by Rituraj Jain",
"e": 5138,
"s": 4434,
"text": null
},
{
"code": "// Program to find winner of the gameusing System; class GFG{ // Function to return find winner of gamestatic String Winner(int n, String []pile){ int a = 0, b = 0; for (int i = 0; i < n; ++i) { int l = pile[i].Length; // Piles begins and ends with White box 'W' if (pile[i][0] == pile[i][l - 1] && pile[i][0] == 'W') a++; // Piles begins and ends with Black box 'B' if (pile[i][0] == pile[i][l - 1] && pile[i][0] == 'B') b++; } if (a <= b) return \"A\"; else return \"B\";} // Driver codepublic static void Main(String[] args){ int n = 2; String []pile = { \"WBW\", \"BWB\" }; // function to print required answer Console.WriteLine(Winner(n, pile));}} // This code is contributed by Princi Singh",
"e": 5957,
"s": 5138,
"text": null
},
{
"code": "<script> // Program to find winner of the game // Function to return find winner of gamefunction Winner(n, pile){ var a = 0, b = 0; for (var i = 0; i < n; ++i) { var l = pile[i].length; // Piles begins and ends with White box 'W' if (pile[i][0] == pile[i][l - 1] && pile[i][0] == 'W') a++; // Piles begins and ends with Black box 'B' if (pile[i][0] == pile[i][l - 1] && pile[i][0] == 'B') b++; } if (a <= b) return \"A\"; else return \"B\";} // Driver codevar n = 2;var pile = [\"WBW\", \"BWB\"]; // function to print required answerdocument.write( Winner(n, pile)); // This code is contributed by noob2000.</script>",
"e": 6655,
"s": 5957,
"text": null
},
{
"code": null,
"e": 6657,
"s": 6655,
"text": "A"
},
{
"code": null,
"e": 6681,
"s": 6659,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 6705,
"s": 6681,
"text": "Auxiliary Space : O(1) "
},
{
"code": null,
"e": 6718,
"s": 6705,
"text": "rituraj_jain"
},
{
"code": null,
"e": 6728,
"s": 6718,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 6741,
"s": 6728,
"text": "princi singh"
},
{
"code": null,
"e": 6750,
"s": 6741,
"text": "noob2000"
},
{
"code": null,
"e": 6766,
"s": 6750,
"text": "devendrasalunke"
},
{
"code": null,
"e": 6778,
"s": 6766,
"text": "Game Theory"
},
{
"code": null,
"e": 6790,
"s": 6778,
"text": "Game Theory"
},
{
"code": null,
"e": 6888,
"s": 6790,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6914,
"s": 6888,
"text": "Chessboard Pawn-Pawn game"
},
{
"code": null,
"e": 6954,
"s": 6914,
"text": "Josephus Problem | (Iterative Solution)"
},
{
"code": null,
"e": 7028,
"s": 6954,
"text": "Game Theory (Normal-form Game) | Set 4 (Dominance Property-Pure Strategy)"
},
{
"code": null,
"e": 7047,
"s": 7028,
"text": "Minesweeper Solver"
},
{
"code": null,
"e": 7090,
"s": 7047,
"text": "Classification of Algorithms with Examples"
},
{
"code": null,
"e": 7104,
"s": 7090,
"text": "Zero-Sum Game"
},
{
"code": null,
"e": 7187,
"s": 7104,
"text": "Find the player who will win by choosing a number in range [1, K] with sum total N"
},
{
"code": null,
"e": 7258,
"s": 7187,
"text": "Game Theory (Normal-form Game) | Set 6 (Graphical Method [2 X N] Game)"
},
{
"code": null,
"e": 7319,
"s": 7258,
"text": "Maximum cells attacked by Rook or Bishop in given Chessboard"
}
] |
How to upload files asynchronously using jQuery? | 03 Aug, 2021
To upload files from local machine to the server is called file uploading. It works exactly the same as the definition, when we select file from the browser and click submit button, the browser takes file from local machine and submit it to the server and server does its job to save the file to the defined path. Here use ajax and jQuery to upload a file asynchronously.
Used Function:
FormData(): It creates a new FormData object.
FormData.append(): It appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
move_uploaded_file(): It moves an uploaded file to a new location.
Steps to run the Program:
Create a folder upload in the xampp/htdocs directory.
Copy and edit the html/jQuery code as per requirement.
Create a file upload.php and copy the php code given below.
Start the Apache server and open the html file using browser.
Select any text or image file and click on Upload button.
The file will be uploaded to the “upload” folder in xamp/htdocs.
If the file is an image, it will be displayed as well, if not an image file then “Uploaded file does not have an image” message will be displayed instead.
Example:
upload.php<?php /* Getting file name */$filename = $_FILES['file']['name']; /* Location */$location = "upload/".$filename;$uploadOk = 1; if($uploadOk == 0){ echo 0;}else{ /* Upload file */ if(move_uploaded_file($_FILES['file']['tmp_name'], $location)){ echo $location; }else{ echo 0; }}?>
<?php /* Getting file name */$filename = $_FILES['file']['name']; /* Location */$location = "upload/".$filename;$uploadOk = 1; if($uploadOk == 0){ echo 0;}else{ /* Upload file */ if(move_uploaded_file($_FILES['file']['tmp_name'], $location)){ echo $location; }else{ echo 0; }}?>
HTML File:<!DOCTYPE html><html><head> <title> Async file upload with jQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script></head> <body> <div align="center"> <form method="post" action="" enctype="multipart/form-data" id="myform"> <div > <input type="file" id="file" name="file" /> <input type="button" class="button" value="Upload" id="but_upload"> </div> </form> </div> <script type="text/javascript"> $(document).ready(function() { $("#but_upload").click(function() { var fd = new FormData(); var files = $('#file')[0].files[0]; fd.append('file', files); $.ajax({ url: 'upload.php', type: 'post', data: fd, contentType: false, processData: false, success: function(response){ if(response != 0){ alert('file uploaded'); } else{ alert('file not uploaded'); } }, }); }); }); </script></body> </html>
<!DOCTYPE html><html><head> <title> Async file upload with jQuery </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script></head> <body> <div align="center"> <form method="post" action="" enctype="multipart/form-data" id="myform"> <div > <input type="file" id="file" name="file" /> <input type="button" class="button" value="Upload" id="but_upload"> </div> </form> </div> <script type="text/javascript"> $(document).ready(function() { $("#but_upload").click(function() { var fd = new FormData(); var files = $('#file')[0].files[0]; fd.append('file', files); $.ajax({ url: 'upload.php', type: 'post', data: fd, contentType: false, processData: false, success: function(response){ if(response != 0){ alert('file uploaded'); } else{ alert('file not uploaded'); } }, }); }); }); </script></body> </html>
Output:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-Misc
Picked
JQuery
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 426,
"s": 54,
"text": "To upload files from local machine to the server is called file uploading. It works exactly the same as the definition, when we select file from the browser and click submit button, the browser takes file from local machine and submit it to the server and server does its job to save the file to the defined path. Here use ajax and jQuery to upload a file asynchronously."
},
{
"code": null,
"e": 441,
"s": 426,
"text": "Used Function:"
},
{
"code": null,
"e": 487,
"s": 441,
"text": "FormData(): It creates a new FormData object."
},
{
"code": null,
"e": 622,
"s": 487,
"text": "FormData.append(): It appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist."
},
{
"code": null,
"e": 689,
"s": 622,
"text": "move_uploaded_file(): It moves an uploaded file to a new location."
},
{
"code": null,
"e": 715,
"s": 689,
"text": "Steps to run the Program:"
},
{
"code": null,
"e": 769,
"s": 715,
"text": "Create a folder upload in the xampp/htdocs directory."
},
{
"code": null,
"e": 824,
"s": 769,
"text": "Copy and edit the html/jQuery code as per requirement."
},
{
"code": null,
"e": 884,
"s": 824,
"text": "Create a file upload.php and copy the php code given below."
},
{
"code": null,
"e": 946,
"s": 884,
"text": "Start the Apache server and open the html file using browser."
},
{
"code": null,
"e": 1004,
"s": 946,
"text": "Select any text or image file and click on Upload button."
},
{
"code": null,
"e": 1069,
"s": 1004,
"text": "The file will be uploaded to the “upload” folder in xamp/htdocs."
},
{
"code": null,
"e": 1224,
"s": 1069,
"text": "If the file is an image, it will be displayed as well, if not an image file then “Uploaded file does not have an image” message will be displayed instead."
},
{
"code": null,
"e": 1233,
"s": 1224,
"text": "Example:"
},
{
"code": null,
"e": 1545,
"s": 1233,
"text": "upload.php<?php /* Getting file name */$filename = $_FILES['file']['name']; /* Location */$location = \"upload/\".$filename;$uploadOk = 1; if($uploadOk == 0){ echo 0;}else{ /* Upload file */ if(move_uploaded_file($_FILES['file']['tmp_name'], $location)){ echo $location; }else{ echo 0; }}?>"
},
{
"code": "<?php /* Getting file name */$filename = $_FILES['file']['name']; /* Location */$location = \"upload/\".$filename;$uploadOk = 1; if($uploadOk == 0){ echo 0;}else{ /* Upload file */ if(move_uploaded_file($_FILES['file']['tmp_name'], $location)){ echo $location; }else{ echo 0; }}?>",
"e": 1847,
"s": 1545,
"text": null
},
{
"code": null,
"e": 3252,
"s": 1847,
"text": "HTML File:<!DOCTYPE html><html><head> <title> Async file upload with jQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script></head> <body> <div align=\"center\"> <form method=\"post\" action=\"\" enctype=\"multipart/form-data\" id=\"myform\"> <div > <input type=\"file\" id=\"file\" name=\"file\" /> <input type=\"button\" class=\"button\" value=\"Upload\" id=\"but_upload\"> </div> </form> </div> <script type=\"text/javascript\"> $(document).ready(function() { $(\"#but_upload\").click(function() { var fd = new FormData(); var files = $('#file')[0].files[0]; fd.append('file', files); $.ajax({ url: 'upload.php', type: 'post', data: fd, contentType: false, processData: false, success: function(response){ if(response != 0){ alert('file uploaded'); } else{ alert('file not uploaded'); } }, }); }); }); </script></body> </html>"
},
{
"code": "<!DOCTYPE html><html><head> <title> Async file upload with jQuery </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script></head> <body> <div align=\"center\"> <form method=\"post\" action=\"\" enctype=\"multipart/form-data\" id=\"myform\"> <div > <input type=\"file\" id=\"file\" name=\"file\" /> <input type=\"button\" class=\"button\" value=\"Upload\" id=\"but_upload\"> </div> </form> </div> <script type=\"text/javascript\"> $(document).ready(function() { $(\"#but_upload\").click(function() { var fd = new FormData(); var files = $('#file')[0].files[0]; fd.append('file', files); $.ajax({ url: 'upload.php', type: 'post', data: fd, contentType: false, processData: false, success: function(response){ if(response != 0){ alert('file uploaded'); } else{ alert('file not uploaded'); } }, }); }); }); </script></body> </html>",
"e": 4647,
"s": 3252,
"text": null
},
{
"code": null,
"e": 4655,
"s": 4647,
"text": "Output:"
},
{
"code": null,
"e": 4923,
"s": 4655,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 4935,
"s": 4923,
"text": "jQuery-Misc"
},
{
"code": null,
"e": 4942,
"s": 4935,
"text": "Picked"
},
{
"code": null,
"e": 4949,
"s": 4942,
"text": "JQuery"
},
{
"code": null,
"e": 4966,
"s": 4949,
"text": "Web Technologies"
},
{
"code": null,
"e": 4993,
"s": 4966,
"text": "Web technologies Questions"
}
] |
Multithreading in Java | 24 Feb, 2021
Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process.
Threads can be created by using two mechanisms :
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Extending the Thread class Implementing the Runnable Interface
Extending the Thread class
Implementing the Runnable Interface
Thread creation by extending the Thread classWe create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object.
Java
// Java code for thread creation by extending// the Thread classclass MultithreadingDemo extends Thread { public void run() { try { // Displaying the thread that is running System.out.println( "Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println("Exception is caught"); } }} // Main Classpublic class Multithread { public static void main(String[] args) { int n = 8; // Number of threads for (int i = 0; i < n; i++) { MultithreadingDemo object = new MultithreadingDemo(); object.start(); } }}
Thread 15 is running
Thread 14 is running
Thread 16 is running
Thread 12 is running
Thread 11 is running
Thread 13 is running
Thread 18 is running
Thread 17 is running
Thread creation by implementing the Runnable InterfaceWe create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object.
Java
// Java code for thread creation by implementing// the Runnable Interfaceclass MultithreadingDemo implements Runnable { public void run() { try { // Displaying the thread that is running System.out.println( "Thread " + Thread.currentThread().getId() + " is running"); } catch (Exception e) { // Throwing an exception System.out.println("Exception is caught"); } }} // Main Classclass Multithread { public static void main(String[] args) { int n = 8; // Number of threads for (int i = 0; i < n; i++) { Thread object = new Thread(new MultithreadingDemo()); object.start(); } }}
Thread 13 is running
Thread 11 is running
Thread 12 is running
Thread 15 is running
Thread 14 is running
Thread 18 is running
Thread 17 is running
Thread 16 is running
Thread Class vs Runnable Interface
If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.Using runnable will give you an object that can be shared amongst multiple threads.
If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.
Using runnable will give you an object that can be shared amongst multiple threads.
This article is contributed by Mehak Narang. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
PrashantSingh27
shrivastava.sukriti
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Feb, 2021"
},
{
"code": null,
"e": 287,
"s": 52,
"text": "Multithreading is a Java feature that allows concurrent execution of two or more parts of a program for maximum utilization of CPU. Each part of such program is called a thread. So, threads are light-weight processes within a process."
},
{
"code": null,
"e": 337,
"s": 287,
"text": "Threads can be created by using two mechanisms : "
},
{
"code": null,
"e": 346,
"s": 337,
"text": "Chapters"
},
{
"code": null,
"e": 373,
"s": 346,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 423,
"s": 373,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 446,
"s": 423,
"text": "captions off, selected"
},
{
"code": null,
"e": 454,
"s": 446,
"text": "English"
},
{
"code": null,
"e": 478,
"s": 454,
"text": "This is a modal window."
},
{
"code": null,
"e": 547,
"s": 478,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 569,
"s": 547,
"text": "End of dialog window."
},
{
"code": null,
"e": 632,
"s": 569,
"text": "Extending the Thread class Implementing the Runnable Interface"
},
{
"code": null,
"e": 660,
"s": 632,
"text": "Extending the Thread class "
},
{
"code": null,
"e": 696,
"s": 660,
"text": "Implementing the Runnable Interface"
},
{
"code": null,
"e": 1067,
"s": 696,
"text": "Thread creation by extending the Thread classWe create a class that extends the java.lang.Thread class. This class overrides the run() method available in the Thread class. A thread begins its life inside run() method. We create an object of our new class and call start() method to start the execution of a thread. Start() invokes the run() method on the Thread object."
},
{
"code": null,
"e": 1072,
"s": 1067,
"text": "Java"
},
{
"code": "// Java code for thread creation by extending// the Thread classclass MultithreadingDemo extends Thread { public void run() { try { // Displaying the thread that is running System.out.println( \"Thread \" + Thread.currentThread().getId() + \" is running\"); } catch (Exception e) { // Throwing an exception System.out.println(\"Exception is caught\"); } }} // Main Classpublic class Multithread { public static void main(String[] args) { int n = 8; // Number of threads for (int i = 0; i < n; i++) { MultithreadingDemo object = new MultithreadingDemo(); object.start(); } }}",
"e": 1819,
"s": 1072,
"text": null
},
{
"code": null,
"e": 1988,
"s": 1819,
"text": "Thread 15 is running\nThread 14 is running\nThread 16 is running\nThread 12 is running\nThread 11 is running\nThread 13 is running\nThread 18 is running\nThread 17 is running\n"
},
{
"code": null,
"e": 2215,
"s": 1988,
"text": "Thread creation by implementing the Runnable InterfaceWe create a new class which implements java.lang.Runnable interface and override run() method. Then we instantiate a Thread object and call start() method on this object. "
},
{
"code": null,
"e": 2220,
"s": 2215,
"text": "Java"
},
{
"code": "// Java code for thread creation by implementing// the Runnable Interfaceclass MultithreadingDemo implements Runnable { public void run() { try { // Displaying the thread that is running System.out.println( \"Thread \" + Thread.currentThread().getId() + \" is running\"); } catch (Exception e) { // Throwing an exception System.out.println(\"Exception is caught\"); } }} // Main Classclass Multithread { public static void main(String[] args) { int n = 8; // Number of threads for (int i = 0; i < n; i++) { Thread object = new Thread(new MultithreadingDemo()); object.start(); } }}",
"e": 2974,
"s": 2220,
"text": null
},
{
"code": null,
"e": 3143,
"s": 2974,
"text": "Thread 13 is running\nThread 11 is running\nThread 12 is running\nThread 15 is running\nThread 14 is running\nThread 18 is running\nThread 17 is running\nThread 16 is running\n"
},
{
"code": null,
"e": 3179,
"s": 3143,
"text": "Thread Class vs Runnable Interface "
},
{
"code": null,
"e": 3667,
"s": 3179,
"text": "If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface.Using runnable will give you an object that can be shared amongst multiple threads. "
},
{
"code": null,
"e": 3881,
"s": 3667,
"text": "If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple inheritance. But, if we implement the Runnable interface, our class can still extend other base classes."
},
{
"code": null,
"e": 4072,
"s": 3881,
"text": "We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt methods like yield(), interrupt() etc. that are not available in Runnable interface."
},
{
"code": null,
"e": 4157,
"s": 4072,
"text": "Using runnable will give you an object that can be shared amongst multiple threads. "
},
{
"code": null,
"e": 4327,
"s": 4157,
"text": "This article is contributed by Mehak Narang. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 4343,
"s": 4327,
"text": "PrashantSingh27"
},
{
"code": null,
"e": 4363,
"s": 4343,
"text": "shrivastava.sukriti"
},
{
"code": null,
"e": 4368,
"s": 4363,
"text": "Java"
},
{
"code": null,
"e": 4373,
"s": 4368,
"text": "Java"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.