title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
|---|---|---|
Remove elements from a Dictionary using Javascript
|
To remove an element from the dictionary, we first need to check if it exists in the dictionary.
We'll use the hasKey method for that. Then we can directly delete it using the delete operator.
We'll return a Boolean so that the place where we call this method can know whether the key already existed or not in the dictionary.
delete(key) {
if(this.hasKey(key)) {
delete this.container[key];
return true;
}
return false;
}
You can test this using −
const myMap = new MyMap();
myMap.put("key1", "value1");
myMap.put("key2", "value2");
myMap.display(); myMap.delete("key2");
myMap.display();
This will give the output −
{ key1: 'value1', key2: 'value2' }
{ key1: 'value1' }
In ES6, you have the delete method to remove values from the map. For example,
const myMap = new Map([
["key1", "value1"],
["key2", "value2"]
]);
myMap.delete("key2");
console.log(myMap.has("key1"))
console.log(myMap.has("key2"))
This will give the output −
True
False
|
[
{
"code": null,
"e": 1159,
"s": 1062,
"text": "To remove an element from the dictionary, we first need to check if it exists in the dictionary."
},
{
"code": null,
"e": 1255,
"s": 1159,
"text": "We'll use the hasKey method for that. Then we can directly delete it using the delete operator."
},
{
"code": null,
"e": 1390,
"s": 1255,
"text": "We'll return a Boolean so that the place where we call this method can know whether the key already existed or not in the dictionary. "
},
{
"code": null,
"e": 1507,
"s": 1390,
"text": "delete(key) {\n if(this.hasKey(key)) {\n delete this.container[key];\n return true;\n }\n return false;\n}"
},
{
"code": null,
"e": 1534,
"s": 1507,
"text": "You can test this using − "
},
{
"code": null,
"e": 1677,
"s": 1534,
"text": "const myMap = new MyMap();\nmyMap.put(\"key1\", \"value1\");\nmyMap.put(\"key2\", \"value2\");\n\nmyMap.display(); myMap.delete(\"key2\");\n\nmyMap.display();"
},
{
"code": null,
"e": 1705,
"s": 1677,
"text": "This will give the output −"
},
{
"code": null,
"e": 1759,
"s": 1705,
"text": "{ key1: 'value1', key2: 'value2' }\n{ key1: 'value1' }"
},
{
"code": null,
"e": 1839,
"s": 1759,
"text": "In ES6, you have the delete method to remove values from the map. For example, "
},
{
"code": null,
"e": 1997,
"s": 1839,
"text": "const myMap = new Map([\n [\"key1\", \"value1\"],\n [\"key2\", \"value2\"]\n]);\nmyMap.delete(\"key2\");\n\nconsole.log(myMap.has(\"key1\"))\nconsole.log(myMap.has(\"key2\"))"
},
{
"code": null,
"e": 2025,
"s": 1997,
"text": "This will give the output −"
},
{
"code": null,
"e": 2036,
"s": 2025,
"text": "True\nFalse"
}
] |
Minimum cost to reverse edges such that there is path between every pair of nodes - GeeksforGeeks
|
19 Jul, 2021
Given a connected, directional graph. Each node is connected to exactly two other nodes. There is weight associated with each edge denoting the cost to reverse its direction. The task is to find the minimum cost to reverse some edges of the graph such that it is possible to go from each node to every other node.Examples:
Input:
5
1 2 7
5 1 8
5 4 5
3 4 1
3 2 10
Output: 15
Input:
6
1 5 4
5 3 8
2 4 15
1 6 16
2 3 23
4 6 42
Output: 39
Approach:
In order to reach from each node to every other node, the graph must form a ring i.e Direct all edges on it in one of 2 directions either clockwise or anti-clockwise. Let us denote the cost of redirecting all the clockwise edges to anticlockwise direction as cost1 and vice versa as cost2. The answer is clearly the minimum of these two costs.
Maintain two boolean arrays start and end. The start and end arrays denote whether there is an edge starting from or ending at a given node. Whenever we encounter an edge going from node a to node b, we first check the condition if there is an edge already starting from node a or ending at node b. If there is an edge that satisfying the condition, the edge is in the opposite direction to the edge already present. In this case, we update cost2 and store the edge in the opposite direction. Otherwise, we update the cost1. This way we are able to maintain the costs of both orientations. Finally, print the minimum cost.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ code to find// the minimum cost to// reverse the edges#include <bits/stdc++.h>using namespace std; // Function to calculate// min cost for reversing// the edgesint minCost(vector<vector<int> >& graph, int n){ int cost1 = 0, cost2 = 0; // bool array to mark // start and end node // of a graph bool start[n + 1] = { false }; bool end[n + 1] = { false }; for (int i = 0; i < n; i++) { int a = graph[i][0]; int b = graph[i][1]; int c = graph[i][2]; // This edge must // start from b and end at a if (start[a] || end[b]) { cost2 += c; start[b] = true; end[a] = true; } // This edge must // start from a and end at b else { cost1 += c; start[a] = true; end[b] = true; } } // Return minimum of // both possibilities return min(cost1, cost2);} // Driver codeint main(){ int n = 5; // Adjacency list representation // of a graph vector<vector<int> > graph = { { 1, 2, 7 }, { 5, 1, 8 }, { 5, 4, 5 }, { 3, 4, 1 }, { 3, 2, 10 } }; int ans = minCost(graph, n); cout << ans << '\n'; return 0;}
// Java code to find the minimum cost to// reverse the edgesclass GFG{ // Function to calculate min cost for// reversing the edgesstatic int minCost(int[][] graph, int n){ int cost1 = 0, cost2 = 0; // bool array to mark start and // end node of a graph boolean []start = new boolean[n + 1]; boolean []end = new boolean[n + 1]; for (int i = 0; i < n; i++) { int a = graph[i][0]; int b = graph[i][1]; int c = graph[i][2]; // This edge must start from b // and end at a if (start[a] || end[b]) { cost2 += c; start[b] = true; end[a] = true; } // This edge must start from a // and end at b else { cost1 += c; start[a] = true; end[b] = true; } } // Return minimum of both possibilities return Math.min(cost1, cost2);} // Driver codepublic static void main(String[] args){ int n = 5; // Adjacency list representation // of a graph int [][]graph = {{ 1, 2, 7 }, { 5, 1, 8 }, { 5, 4, 5 }, { 3, 4, 1 }, { 3, 2, 10 }}; int ans = minCost(graph, n); System.out.println(ans);}} // This code is contributed by Rajput-Ji
# Python code to find the minimum cost to# reverse the edges # Function to calculate min cost for# reversing the edgesdef minCost(graph, n): cost1, cost2 = 0, 0; # bool array to mark start and # end node of a graph start = [False]*(n + 1); end = [False]*(n + 1); for i in range(n): a = graph[i][0]; b = graph[i][1]; c = graph[i][2]; # This edge must start from b # and end at a if (start[a] or end[b]): cost2 += c; start[b] = True; end[a] = True; # This edge must start from a # and end at b else: cost1 += c; start[a] = True; end[b] = True; # Return minimum of both possibilities return min(cost1, cost2); # Driver codeif __name__ == '__main__': n = 5; # Adjacency list representation # of a graph graph = [[ 1, 2, 7 ], [ 5, 1, 8 ], [ 5, 4, 5 ], [ 3, 4, 1 ], [ 3, 2, 10 ]]; ans = minCost(graph, n); print(ans); # This code is contributed by 29AjayKumar
// C# code to find the minimum cost to// reverse the edgesusing System; class GFG{ // Function to calculate min cost for// reversing the edgesstatic int minCost(int[,] graph, int n){ int cost1 = 0, cost2 = 0; // bool array to mark start and // end node of a graph Boolean []start = new Boolean[n + 1]; Boolean []end = new Boolean[n + 1]; for (int i = 0; i < n; i++) { int a = graph[i, 0]; int b = graph[i, 1]; int c = graph[i, 2]; // This edge must start from b // and end at a if (start[a] || end[b]) { cost2 += c; start[b] = true; end[a] = true; } // This edge must start from a // and end at b else { cost1 += c; start[a] = true; end[b] = true; } } // Return minimum of both possibilities return Math.Min(cost1, cost2);} // Driver codepublic static void Main(String[] args){ int n = 5; // Adjacency list representation // of a graph int [,]graph = {{ 1, 2, 7 }, { 5, 1, 8 }, { 5, 4, 5 }, { 3, 4, 1 }, { 3, 2, 10 }}; int ans = minCost(graph, n); Console.WriteLine(ans);}} // This code is contributed by PrinciRaj1992
<script> // JavaScript code to find// the minimum cost to// reverse the edges // Function to calculate// min cost for reversing// the edgesfunction minCost(graph, n) { let cost1 = 0, cost2 = 0; // bool array to mark // start and end node // of a graph let start = new Array(n + 1).fill(false); let end = new Array(n + 1).fill(false); for (let i = 0; i < n; i++) { let a = graph[i][0]; let b = graph[i][1]; let c = graph[i][2]; // This edge must // start from b and end at a if (start[a] || end[b]) { cost2 += c; start[b] = true; end[a] = true; } // This edge must // start from a and end at b else { cost1 += c; start[a] = true; end[b] = true; } } // Return minimum of // both possibilities return Math.min(cost1, cost2);} // Driver code let n = 5;// Adjacency list representation// of a graphlet graph = [ [1, 2, 7], [5, 1, 8], [5, 4, 5], [3, 4, 1], [3, 2, 10]]; let ans = minCost(graph, n);document.write(ans + '<br>'); </script>
15
Time Complexity: O(N) where N is number of edges
Rajput-Ji
princiraj1992
29AjayKumar
_saurabh_jaiswal
varshagumber28
direct
Algorithms
Arrays
Graph
Arrays
Graph
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
DSA Sheet by Love Babbar
K means Clustering - Introduction
SCAN (Elevator) Disk Scheduling Algorithms
Quadratic Probing in Hashing
Difference between Informed and Uninformed Search in AI
Arrays in Java
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Largest Sum Contiguous Subarray
|
[
{
"code": null,
"e": 24610,
"s": 24582,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 24935,
"s": 24610,
"text": "Given a connected, directional graph. Each node is connected to exactly two other nodes. There is weight associated with each edge denoting the cost to reverse its direction. The task is to find the minimum cost to reverse some edges of the graph such that it is possible to go from each node to every other node.Examples: "
},
{
"code": null,
"e": 24987,
"s": 24935,
"text": "Input: \n5\n1 2 7\n5 1 8\n5 4 5\n3 4 1\n3 2 10\nOutput: 15"
},
{
"code": null,
"e": 25047,
"s": 24987,
"text": "Input:\n6\n1 5 4\n5 3 8\n2 4 15\n1 6 16\n2 3 23\n4 6 42\nOutput: 39"
},
{
"code": null,
"e": 25060,
"s": 25049,
"text": "Approach: "
},
{
"code": null,
"e": 25404,
"s": 25060,
"text": "In order to reach from each node to every other node, the graph must form a ring i.e Direct all edges on it in one of 2 directions either clockwise or anti-clockwise. Let us denote the cost of redirecting all the clockwise edges to anticlockwise direction as cost1 and vice versa as cost2. The answer is clearly the minimum of these two costs."
},
{
"code": null,
"e": 26027,
"s": 25404,
"text": "Maintain two boolean arrays start and end. The start and end arrays denote whether there is an edge starting from or ending at a given node. Whenever we encounter an edge going from node a to node b, we first check the condition if there is an edge already starting from node a or ending at node b. If there is an edge that satisfying the condition, the edge is in the opposite direction to the edge already present. In this case, we update cost2 and store the edge in the opposite direction. Otherwise, we update the cost1. This way we are able to maintain the costs of both orientations. Finally, print the minimum cost."
},
{
"code": null,
"e": 26076,
"s": 26027,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 26080,
"s": 26076,
"text": "C++"
},
{
"code": null,
"e": 26085,
"s": 26080,
"text": "Java"
},
{
"code": null,
"e": 26093,
"s": 26085,
"text": "Python3"
},
{
"code": null,
"e": 26096,
"s": 26093,
"text": "C#"
},
{
"code": null,
"e": 26107,
"s": 26096,
"text": "Javascript"
},
{
"code": "// C++ code to find// the minimum cost to// reverse the edges#include <bits/stdc++.h>using namespace std; // Function to calculate// min cost for reversing// the edgesint minCost(vector<vector<int> >& graph, int n){ int cost1 = 0, cost2 = 0; // bool array to mark // start and end node // of a graph bool start[n + 1] = { false }; bool end[n + 1] = { false }; for (int i = 0; i < n; i++) { int a = graph[i][0]; int b = graph[i][1]; int c = graph[i][2]; // This edge must // start from b and end at a if (start[a] || end[b]) { cost2 += c; start[b] = true; end[a] = true; } // This edge must // start from a and end at b else { cost1 += c; start[a] = true; end[b] = true; } } // Return minimum of // both possibilities return min(cost1, cost2);} // Driver codeint main(){ int n = 5; // Adjacency list representation // of a graph vector<vector<int> > graph = { { 1, 2, 7 }, { 5, 1, 8 }, { 5, 4, 5 }, { 3, 4, 1 }, { 3, 2, 10 } }; int ans = minCost(graph, n); cout << ans << '\\n'; return 0;}",
"e": 27338,
"s": 26107,
"text": null
},
{
"code": "// Java code to find the minimum cost to// reverse the edgesclass GFG{ // Function to calculate min cost for// reversing the edgesstatic int minCost(int[][] graph, int n){ int cost1 = 0, cost2 = 0; // bool array to mark start and // end node of a graph boolean []start = new boolean[n + 1]; boolean []end = new boolean[n + 1]; for (int i = 0; i < n; i++) { int a = graph[i][0]; int b = graph[i][1]; int c = graph[i][2]; // This edge must start from b // and end at a if (start[a] || end[b]) { cost2 += c; start[b] = true; end[a] = true; } // This edge must start from a // and end at b else { cost1 += c; start[a] = true; end[b] = true; } } // Return minimum of both possibilities return Math.min(cost1, cost2);} // Driver codepublic static void main(String[] args){ int n = 5; // Adjacency list representation // of a graph int [][]graph = {{ 1, 2, 7 }, { 5, 1, 8 }, { 5, 4, 5 }, { 3, 4, 1 }, { 3, 2, 10 }}; int ans = minCost(graph, n); System.out.println(ans);}} // This code is contributed by Rajput-Ji",
"e": 28645,
"s": 27338,
"text": null
},
{
"code": "# Python code to find the minimum cost to# reverse the edges # Function to calculate min cost for# reversing the edgesdef minCost(graph, n): cost1, cost2 = 0, 0; # bool array to mark start and # end node of a graph start = [False]*(n + 1); end = [False]*(n + 1); for i in range(n): a = graph[i][0]; b = graph[i][1]; c = graph[i][2]; # This edge must start from b # and end at a if (start[a] or end[b]): cost2 += c; start[b] = True; end[a] = True; # This edge must start from a # and end at b else: cost1 += c; start[a] = True; end[b] = True; # Return minimum of both possibilities return min(cost1, cost2); # Driver codeif __name__ == '__main__': n = 5; # Adjacency list representation # of a graph graph = [[ 1, 2, 7 ], [ 5, 1, 8 ], [ 5, 4, 5 ], [ 3, 4, 1 ], [ 3, 2, 10 ]]; ans = minCost(graph, n); print(ans); # This code is contributed by 29AjayKumar",
"e": 29766,
"s": 28645,
"text": null
},
{
"code": "// C# code to find the minimum cost to// reverse the edgesusing System; class GFG{ // Function to calculate min cost for// reversing the edgesstatic int minCost(int[,] graph, int n){ int cost1 = 0, cost2 = 0; // bool array to mark start and // end node of a graph Boolean []start = new Boolean[n + 1]; Boolean []end = new Boolean[n + 1]; for (int i = 0; i < n; i++) { int a = graph[i, 0]; int b = graph[i, 1]; int c = graph[i, 2]; // This edge must start from b // and end at a if (start[a] || end[b]) { cost2 += c; start[b] = true; end[a] = true; } // This edge must start from a // and end at b else { cost1 += c; start[a] = true; end[b] = true; } } // Return minimum of both possibilities return Math.Min(cost1, cost2);} // Driver codepublic static void Main(String[] args){ int n = 5; // Adjacency list representation // of a graph int [,]graph = {{ 1, 2, 7 }, { 5, 1, 8 }, { 5, 4, 5 }, { 3, 4, 1 }, { 3, 2, 10 }}; int ans = minCost(graph, n); Console.WriteLine(ans);}} // This code is contributed by PrinciRaj1992",
"e": 31085,
"s": 29766,
"text": null
},
{
"code": "<script> // JavaScript code to find// the minimum cost to// reverse the edges // Function to calculate// min cost for reversing// the edgesfunction minCost(graph, n) { let cost1 = 0, cost2 = 0; // bool array to mark // start and end node // of a graph let start = new Array(n + 1).fill(false); let end = new Array(n + 1).fill(false); for (let i = 0; i < n; i++) { let a = graph[i][0]; let b = graph[i][1]; let c = graph[i][2]; // This edge must // start from b and end at a if (start[a] || end[b]) { cost2 += c; start[b] = true; end[a] = true; } // This edge must // start from a and end at b else { cost1 += c; start[a] = true; end[b] = true; } } // Return minimum of // both possibilities return Math.min(cost1, cost2);} // Driver code let n = 5;// Adjacency list representation// of a graphlet graph = [ [1, 2, 7], [5, 1, 8], [5, 4, 5], [3, 4, 1], [3, 2, 10]]; let ans = minCost(graph, n);document.write(ans + '<br>'); </script>",
"e": 32215,
"s": 31085,
"text": null
},
{
"code": null,
"e": 32218,
"s": 32215,
"text": "15"
},
{
"code": null,
"e": 32270,
"s": 32220,
"text": "Time Complexity: O(N) where N is number of edges "
},
{
"code": null,
"e": 32280,
"s": 32270,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 32294,
"s": 32280,
"text": "princiraj1992"
},
{
"code": null,
"e": 32306,
"s": 32294,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32323,
"s": 32306,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 32338,
"s": 32323,
"text": "varshagumber28"
},
{
"code": null,
"e": 32345,
"s": 32338,
"text": "direct"
},
{
"code": null,
"e": 32356,
"s": 32345,
"text": "Algorithms"
},
{
"code": null,
"e": 32363,
"s": 32356,
"text": "Arrays"
},
{
"code": null,
"e": 32369,
"s": 32363,
"text": "Graph"
},
{
"code": null,
"e": 32376,
"s": 32369,
"text": "Arrays"
},
{
"code": null,
"e": 32382,
"s": 32376,
"text": "Graph"
},
{
"code": null,
"e": 32393,
"s": 32382,
"text": "Algorithms"
},
{
"code": null,
"e": 32491,
"s": 32393,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32500,
"s": 32491,
"text": "Comments"
},
{
"code": null,
"e": 32513,
"s": 32500,
"text": "Old Comments"
},
{
"code": null,
"e": 32538,
"s": 32513,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 32572,
"s": 32538,
"text": "K means Clustering - Introduction"
},
{
"code": null,
"e": 32615,
"s": 32572,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 32644,
"s": 32615,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 32700,
"s": 32644,
"text": "Difference between Informed and Uninformed Search in AI"
},
{
"code": null,
"e": 32715,
"s": 32700,
"text": "Arrays in Java"
},
{
"code": null,
"e": 32731,
"s": 32715,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 32758,
"s": 32731,
"text": "Program for array rotation"
},
{
"code": null,
"e": 32806,
"s": 32758,
"text": "Stack Data Structure (Introduction and Program)"
}
] |
Node at a given index in linked list | Practice | GeeksforGeeks
|
Given a singly linked list with N nodes and a number X. The task is to find the node at the given index (X)(1 based index) of linked list.
Input:
First line of input contains number of testcases T. For each testcase, first line of input contains space seperated two integers, length of linked list and X.
Output:
For each testcase, there will be single line of output containing data at Xth node.
User Task:
The task is to complete the function GetNth() which takes head reference and index as arguments and should return the data at Xth position in the linked list.
Constraints:
1 <= T <= 30
1 <= N <= 100
K <= N
1 <= value <= 103
Example:
Input:
2
6 5
1 2 3 4 657 76
10 2
8 7 10 8 6 1 20 91 21 2
Output:
657
7
Explanation:
Testcase 1: Element at 5th index in the linked list is 657 (1-based indexing).
0
uvuv3925710 hours ago
int ans=0; while(node!=null) { ans++; if(ans==ind) return node.data; node = node.next; } return -1;
0
sricharanpindi0051 week ago
def getNth(head, k): c=0 temp=head while temp: c=c+1 if c==k: return temp.data temp=temp.next
#python3
0
pk9466171 week ago
I think it is quite easy using recursion ...
int GetNth(struct node* head, int index){ // Code here if(index==1){ return head->data; } if(head!=NULL and index!=1){ return GetNth(head->next,index-1); }}
0
neelasatyasai931 week ago
#PYTHON CODE
def getNth(head, k):
# Code here
c=0
temp=head
if temp==None:
return 0
else:
while c != k-1:
temp=temp.next
c+=1
return temp.data
0
saikrishnakasa1232 weeks ago
#here k is the no.of times times the loop should #repeat , so loop until the k and simply print #the data present there
def getNth(head, k):
c=1
n=head
for _ in range(k-1):
n=n.next
return n.data
#Thank me ,if you love it!
0
09himanshusah2 weeks ago
#JavaScript Solution
class Solution {
GetNth(head,index){
//code here
let current = head;
let count = 1;
while(current) {
if(count === index) {
return current.data;
}
current = current.next;
count++;
}
}
}
0
prabhakarsati294262 weeks ago
def getNth(head, k): # Code here if (k == 1): return head.data temp = head count = 1 ans = None while temp is not None: temp = temp.next count = count + 1 if (count == k): ans = temp.data return ans
0
riyaraip082 weeks ago
struct node* temp = head; int c=1; while(temp!=NULL){ if(index==c){ return temp->data; break; } c++; temp = temp->next; } return 0;
0
erreshusingh2 weeks ago
int GetNth(struct node* head, int index){ // Code here if(index == 1){ return head->data; } else{ return GetNth(head->next, index-1); }}
0
bajpayeevinayak2283 weeks ago
int getback(struct node* cur, int index,int i){ if(i>index-2) {return cur->data;}
getback(cur->next,index,i+1);}int GetNth(struct node* head, int index){ // Code here struct node *cur=head; int z=getback(cur,index,0); return z;}
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": 378,
"s": 238,
"text": "Given a singly linked list with N nodes and a number X. The task is to find the node at the given index (X)(1 based index) of linked list. "
},
{
"code": null,
"e": 544,
"s": 378,
"text": "Input:\nFirst line of input contains number of testcases T. For each testcase, first line of input contains space seperated two integers, length of linked list and X."
},
{
"code": null,
"e": 636,
"s": 544,
"text": "Output:\nFor each testcase, there will be single line of output containing data at Xth node."
},
{
"code": null,
"e": 806,
"s": 636,
"text": "User Task:\nThe task is to complete the function GetNth() which takes head reference and index as arguments and should return the data at Xth position in the linked list."
},
{
"code": null,
"e": 871,
"s": 806,
"text": "Constraints:\n1 <= T <= 30\n1 <= N <= 100\nK <= N\n1 <= value <= 103"
},
{
"code": null,
"e": 937,
"s": 871,
"text": "Example:\nInput:\n2\n6 5\n1 2 3 4 657 76\n10 2\n8 7 10 8 6 1 20 91 21 2"
},
{
"code": null,
"e": 951,
"s": 937,
"text": "Output:\n657\n7"
},
{
"code": null,
"e": 1045,
"s": 951,
"text": "Explanation:\nTestcase 1: Element at 5th index in the linked list is 657 (1-based indexing).\n "
},
{
"code": null,
"e": 1047,
"s": 1045,
"text": "0"
},
{
"code": null,
"e": 1069,
"s": 1047,
"text": "uvuv3925710 hours ago"
},
{
"code": null,
"e": 1235,
"s": 1069,
"text": "int ans=0; while(node!=null) { ans++; if(ans==ind) return node.data; node = node.next; } return -1;"
},
{
"code": null,
"e": 1237,
"s": 1235,
"text": "0"
},
{
"code": null,
"e": 1265,
"s": 1237,
"text": "sricharanpindi0051 week ago"
},
{
"code": null,
"e": 1393,
"s": 1265,
"text": "def getNth(head, k): c=0 temp=head while temp: c=c+1 if c==k: return temp.data temp=temp.next"
},
{
"code": null,
"e": 1402,
"s": 1393,
"text": "#python3"
},
{
"code": null,
"e": 1404,
"s": 1402,
"text": "0"
},
{
"code": null,
"e": 1423,
"s": 1404,
"text": "pk9466171 week ago"
},
{
"code": null,
"e": 1468,
"s": 1423,
"text": "I think it is quite easy using recursion ..."
},
{
"code": null,
"e": 1634,
"s": 1468,
"text": "int GetNth(struct node* head, int index){ // Code here if(index==1){ return head->data; } if(head!=NULL and index!=1){ return GetNth(head->next,index-1); }} "
},
{
"code": null,
"e": 1636,
"s": 1634,
"text": "0"
},
{
"code": null,
"e": 1662,
"s": 1636,
"text": "neelasatyasai931 week ago"
},
{
"code": null,
"e": 1863,
"s": 1662,
"text": "#PYTHON CODE\ndef getNth(head, k):\n # Code here\n c=0\n temp=head\n if temp==None:\n return 0\n else:\n while c != k-1:\n temp=temp.next\n c+=1\n return temp.data"
},
{
"code": null,
"e": 1865,
"s": 1863,
"text": "0"
},
{
"code": null,
"e": 1894,
"s": 1865,
"text": "saikrishnakasa1232 weeks ago"
},
{
"code": null,
"e": 2141,
"s": 1894,
"text": "#here k is the no.of times times the loop should #repeat , so loop until the k and simply print #the data present there\ndef getNth(head, k):\n c=1\n n=head\n for _ in range(k-1):\n n=n.next\n return n.data\n#Thank me ,if you love it!"
},
{
"code": null,
"e": 2143,
"s": 2141,
"text": "0"
},
{
"code": null,
"e": 2168,
"s": 2143,
"text": "09himanshusah2 weeks ago"
},
{
"code": null,
"e": 2189,
"s": 2168,
"text": "#JavaScript Solution"
},
{
"code": null,
"e": 2443,
"s": 2189,
"text": "class Solution {\n GetNth(head,index){\n //code here\n let current = head;\n let count = 1;\n while(current) {\n if(count === index) {\n return current.data;\n }\n current = current.next;\n count++;\n }\n }\n}"
},
{
"code": null,
"e": 2445,
"s": 2443,
"text": "0"
},
{
"code": null,
"e": 2475,
"s": 2445,
"text": "prabhakarsati294262 weeks ago"
},
{
"code": null,
"e": 2723,
"s": 2475,
"text": "def getNth(head, k): # Code here if (k == 1): return head.data temp = head count = 1 ans = None while temp is not None: temp = temp.next count = count + 1 if (count == k): ans = temp.data return ans"
},
{
"code": null,
"e": 2725,
"s": 2723,
"text": "0"
},
{
"code": null,
"e": 2747,
"s": 2725,
"text": "riyaraip082 weeks ago"
},
{
"code": null,
"e": 2912,
"s": 2747,
"text": " struct node* temp = head; int c=1; while(temp!=NULL){ if(index==c){ return temp->data; break; } c++; temp = temp->next; } return 0;"
},
{
"code": null,
"e": 2914,
"s": 2912,
"text": "0"
},
{
"code": null,
"e": 2938,
"s": 2914,
"text": "erreshusingh2 weeks ago"
},
{
"code": null,
"e": 3083,
"s": 2938,
"text": "int GetNth(struct node* head, int index){ // Code here if(index == 1){ return head->data; } else{ return GetNth(head->next, index-1); }}"
},
{
"code": null,
"e": 3085,
"s": 3083,
"text": "0"
},
{
"code": null,
"e": 3115,
"s": 3085,
"text": "bajpayeevinayak2283 weeks ago"
},
{
"code": null,
"e": 3199,
"s": 3115,
"text": "int getback(struct node* cur, int index,int i){ if(i>index-2) {return cur->data;}"
},
{
"code": null,
"e": 3346,
"s": 3199,
"text": "getback(cur->next,index,i+1);}int GetNth(struct node* head, int index){ // Code here struct node *cur=head; int z=getback(cur,index,0); return z;}"
},
{
"code": null,
"e": 3492,
"s": 3346,
"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": 3528,
"s": 3492,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3538,
"s": 3528,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3548,
"s": 3538,
"text": "\nContest\n"
},
{
"code": null,
"e": 3611,
"s": 3548,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3759,
"s": 3611,
"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": 3967,
"s": 3759,
"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": 4073,
"s": 3967,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to combine two vectors while replacing the NA values with the values in the other vector in R?
|
Sometimes we have vectors with NA values, also there might be a situation that one of vector having an NA at a position and the other vector has the numerical values at the same position. For example, 1, 2, NA and 1, 2, 3. In this case, we might want to combine these two vectors to make a single vector. This can be done by using coalesce function of dplyr package.
> library(dplyr)
> x1<-sample(c(1:4,NA),20,replace=TRUE)
> x1
[1] NA 4 NA 1 2 NA 4 1 4 1 2 3 1 4 2 2 NA 2 2 1
Live Demo
> y1<-1:20
> y1
[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
> coalesce(x1,y1)
[1] 1 4 3 1 2 6 4 1 4 1 2 3 1 4 2 2 17 2 2 1
Live Demo
> x2<-sample(c(5,NA,10),50,replace=TRUE)
> x2
[1] 10 5 NA 5 5 NA 5 NA NA 5 NA 10 NA 10 5 NA NA NA 10 5 5 NA NA 5 NA
[26] 5 10 5 10 10 10 10 NA NA 5 NA 5 NA 5 NA 10 10 NA 10 NA 5 NA 10 10 5
Live Demo
> y2<-sample(c(5,8,10),50,replace=TRUE)
> y2
[1] 5 5 10 5 10 8 8 8 5 10 8 5 10 8 10 5 5 8 5 5 10 8 8 8 10
[26] 5 10 5 5 10 10 5 5 10 10 8 10 10 8 8 10 5 5 5 8 5 10 5 8 8
> coalesce(x2,y2)
[1] 10 5 10 5 5 8 5 8 5 5 8 10 10 10 5 5 5 8 10 5 5 8 8 5 10
[26] 5 10 5 10 10 10 10 5 10 5 8 5 10 5 8 10 10 5 10 8 5 10 10 10 5
Live Demo
> x3<-sample(c(2,4,16,NA,10),100,replace=TRUE)
> x3
[1] 2 2 16 16 NA NA 2 16 16 4 4 4 NA 10 2 4 NA 2 4 NA 16 2 10 10 16
[26] NA 2 16 2 10 NA 4 2 10 10 16 10 16 10 NA 4 4 4 4 10 NA NA 10 16 10
[51] 4 4 NA 16 16 2 NA 10 16 16 16 16 2 4 16 2 2 16 NA 2 NA 4 16 4 16
[76] 2 4 NA NA 2 2 10 16 10 4 10 4 10 NA 10 NA 4 10 4 16 2 4 2 16 2
Live Demo
> y3<-sample(c(2,4,16,8,10),100,replace=TRUE)
> y3
[1] 10 2 8 8 10 8 10 8 4 2 10 4 16 10 8 2 8 8 2 2 4 4 2 10 10
[26] 8 16 8 16 4 4 2 16 2 16 8 4 16 4 8 8 10 10 4 4 4 4 2 4 10
[51] 2 8 2 4 2 10 8 8 4 4 2 10 2 16 8 8 10 8 2 2 10 16 10 10 2
[76] 4 10 2 4 10 4 8 16 4 2 4 2 16 4 8 10 4 8 10 16 4 4 4 10 2
> coalesce(x3,y3)
[1] 2 2 16 16 10 8 2 16 16 4 4 4 16 10 2 4 8 2 4 2 16 2 10 10 16
[26] 8 2 16 2 10 4 4 2 10 10 16 10 16 10 8 4 4 4 4 10 4 4 10 16 10
[51] 4 4 2 16 16 2 8 10 16 16 16 16 2 4 16 2 2 16 2 2 10 4 16 4 16
[76] 2 4 2 4 2 2 10 16 10 4 10 4 10 4 10 10 4 10 4 16 2 4 2 16 2
Live Demo
> x4<-sample(rnorm(10),50,replace=TRUE)
> x4
[1] -0.02879712 1.31733536 -0.02879712 -0.77268752 0.47775338 1.23117578
[7] 1.23117578 -0.77268752 1.31733536 0.30903710 0.47775338 1.31733536
[13] -0.77268752 0.30903710 1.31733536 -1.65681391 -1.65681391 1.31733536
[19] -0.02879712 0.47775338 0.30903710 -0.77268752 0.08699075 -0.02879712
[25] -1.65681391 -0.77268752 0.45328379 1.23117578 0.08699075 -1.65681391
[31] 1.23117578 0.47775338 1.25889501 0.45328379 1.31733536 -1.65681391
[37] 0.45328379 0.30903710 0.45328379 1.31733536 0.30903710 0.45328379
[43] 0.08699075 1.31733536 -1.65681391 1.31733536 -0.77268752 -1.65681391
[49] -0.77268752 1.25889501
Live Demo
> y4<-sample(c(rnorm(10),NA),50,replace=TRUE)
> y4
[1] -0.6383008 -0.6383008 1.0152569 1.0152569 0.5242708 -0.6383008
[7] -0.3965653 NA 0.5242708 -0.4664776 NA NA
[13] 1.1300389 -0.3965653 -0.3965653 1.0152569 -0.9956721 -0.4664776
[19] -0.4664776 -0.3610621 NA 0.4749585 -0.4664776 -0.3965653
[25] -0.3610621 -0.9956721 -0.6383008 NA 1.0152569 -0.4664776
[31] 0.4749585 NA -0.4664776 -0.9956721 NA -0.3610621
[37] -0.3965653 1.0152569 0.4749585 0.5242708 0.5242708 -0.3965653
[43] -0.4664776 -0.8300846 -0.9956721 NA 1.0152569 -0.9956721
[49] -0.4664776 -0.6383008
> coalesce(x4,y4)
[1] -0.02879712 1.31733536 -0.02879712 -0.77268752 0.47775338 1.23117578
[7] 1.23117578 -0.77268752 1.31733536 0.30903710 0.47775338 1.31733536
[13] -0.77268752 0.30903710 1.31733536 -1.65681391 -1.65681391 1.31733536
[19] -0.02879712 0.47775338 0.30903710 -0.77268752 0.08699075 -0.02879712
[25] -1.65681391 -0.77268752 0.45328379 1.23117578 0.08699075 -1.65681391
[31] 1.23117578 0.47775338 1.25889501 0.45328379 1.31733536 -1.65681391
[37] 0.45328379 0.30903710 0.45328379 1.31733536 0.30903710 0.45328379
[43] 0.08699075 1.31733536 -1.65681391 1.31733536 -0.77268752 -1.65681391
[49] -0.77268752 1.25889501
Live Demo
> x5<-sample(c(runif(10,2,5)),50,replace=TRUE)
> x5
[1] 4.791954 4.447842 4.479391 4.627612 4.447842 2.460460 2.460460 4.627612
[9] 4.130456 2.904874 2.904874 2.460460 4.804377 2.517587 4.447842 4.627612
[17] 4.804377 4.791954 4.479391 2.460460 4.479391 4.479391 4.130456 3.218738
[25] 4.447842 4.130456 2.460460 4.791954 4.479391 3.218738 4.479391 4.479391
[33] 4.791954 2.517587 4.447842 4.479391 3.218738 4.130456 3.218738 4.791954
[41] 2.904874 4.479391 4.791954 2.904874 4.479391 4.791954 4.479391 4.130456
[49] 4.804377 4.791954
Live Demo
> y5<-sample(c(runif(10,3,5)),50,replace=TRUE)
> y5
[1] 4.805609 4.832933 3.553856 4.832933 4.942905 4.805609 4.942905 4.608437
[9] 4.832933 4.163457 4.832933 4.608437 3.013883 4.608437 4.942905 4.163457
[17] 4.743048 3.013883 3.013883 4.743048 3.553856 4.743048 3.933597 3.933597
[25] 4.743048 4.508212 4.805609 4.743048 3.013883 4.163457 4.942905 4.743048
[33] 4.942905 4.508212 3.553856 4.608437 3.553856 4.743048 3.933597 4.163457
[41] 3.933597 4.508212 4.608437 4.508212 3.933597 4.942905 4.508212 4.832933
[49] 4.832933 4.805609
> coalesce(x5,y5)
[1] 4.791954 4.447842 4.479391 4.627612 4.447842 2.460460 2.460460 4.627612
[9] 4.130456 2.904874 2.904874 2.460460 4.804377 2.517587 4.447842 4.627612
[17] 4.804377 4.791954 4.479391 2.460460 4.479391 4.479391 4.130456 3.218738
[25] 4.447842 4.130456 2.460460 4.791954 4.479391 3.218738 4.479391 4.479391
[33] 4.791954 2.517587 4.447842 4.479391 3.218738 4.130456 3.218738 4.791954
[41] 2.904874 4.479391 4.791954 2.904874 4.479391 4.791954 4.479391 4.130456
[49] 4.804377 4.791954
|
[
{
"code": null,
"e": 1429,
"s": 1062,
"text": "Sometimes we have vectors with NA values, also there might be a situation that one of vector having an NA at a position and the other vector has the numerical values at the same position. For example, 1, 2, NA and 1, 2, 3. In this case, we might want to combine these two vectors to make a single vector. This can be done by using coalesce function of dplyr package."
},
{
"code": null,
"e": 1491,
"s": 1429,
"text": "> library(dplyr)\n> x1<-sample(c(1:4,NA),20,replace=TRUE)\n> x1"
},
{
"code": null,
"e": 1539,
"s": 1491,
"text": "[1] NA 4 NA 1 2 NA 4 1 4 1 2 3 1 4 2 2 NA 2 2 1"
},
{
"code": null,
"e": 1550,
"s": 1539,
"text": " Live Demo"
},
{
"code": null,
"e": 1566,
"s": 1550,
"text": "> y1<-1:20\n> y1"
},
{
"code": null,
"e": 1621,
"s": 1566,
"text": "[1] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20"
},
{
"code": null,
"e": 1639,
"s": 1621,
"text": "> coalesce(x1,y1)"
},
{
"code": null,
"e": 1685,
"s": 1639,
"text": "[1] 1 4 3 1 2 6 4 1 4 1 2 3 1 4 2 2 17 2 2 1\n"
},
{
"code": null,
"e": 1696,
"s": 1685,
"text": " Live Demo"
},
{
"code": null,
"e": 1742,
"s": 1696,
"text": "> x2<-sample(c(5,NA,10),50,replace=TRUE)\n> x2"
},
{
"code": null,
"e": 1885,
"s": 1742,
"text": "[1] 10 5 NA 5 5 NA 5 NA NA 5 NA 10 NA 10 5 NA NA NA 10 5 5 NA NA 5 NA\n[26] 5 10 5 10 10 10 10 NA NA 5 NA 5 NA 5 NA 10 10 NA 10 NA 5 NA 10 10 5"
},
{
"code": null,
"e": 1896,
"s": 1885,
"text": " Live Demo"
},
{
"code": null,
"e": 1941,
"s": 1896,
"text": "> y2<-sample(c(5,8,10),50,replace=TRUE)\n> y2"
},
{
"code": null,
"e": 2066,
"s": 1941,
"text": "[1] 5 5 10 5 10 8 8 8 5 10 8 5 10 8 10 5 5 8 5 5 10 8 8 8 10\n[26] 5 10 5 5 10 10 5 5 10 10 8 10 10 8 8 10 5 5 5 8 5 10 5 8 8"
},
{
"code": null,
"e": 2084,
"s": 2066,
"text": "> coalesce(x2,y2)"
},
{
"code": null,
"e": 2213,
"s": 2084,
"text": "[1] 10 5 10 5 5 8 5 8 5 5 8 10 10 10 5 5 5 8 10 5 5 8 8 5 10\n[26] 5 10 5 10 10 10 10 5 10 5 8 5 10 5 8 10 10 5 10 8 5 10 10 10 5"
},
{
"code": null,
"e": 2224,
"s": 2213,
"text": " Live Demo"
},
{
"code": null,
"e": 2276,
"s": 2224,
"text": "> x3<-sample(c(2,4,16,NA,10),100,replace=TRUE)\n> x3"
},
{
"code": null,
"e": 2554,
"s": 2276,
"text": "[1] 2 2 16 16 NA NA 2 16 16 4 4 4 NA 10 2 4 NA 2 4 NA 16 2 10 10 16\n[26] NA 2 16 2 10 NA 4 2 10 10 16 10 16 10 NA 4 4 4 4 10 NA NA 10 16 10\n[51] 4 4 NA 16 16 2 NA 10 16 16 16 16 2 4 16 2 2 16 NA 2 NA 4 16 4 16\n[76] 2 4 NA NA 2 2 10 16 10 4 10 4 10 NA 10 NA 4 10 4 16 2 4 2 16 2"
},
{
"code": null,
"e": 2565,
"s": 2554,
"text": " Live Demo"
},
{
"code": null,
"e": 2616,
"s": 2565,
"text": "> y3<-sample(c(2,4,16,8,10),100,replace=TRUE)\n> y3"
},
{
"code": null,
"e": 2867,
"s": 2616,
"text": "[1] 10 2 8 8 10 8 10 8 4 2 10 4 16 10 8 2 8 8 2 2 4 4 2 10 10\n[26] 8 16 8 16 4 4 2 16 2 16 8 4 16 4 8 8 10 10 4 4 4 4 2 4 10\n[51] 2 8 2 4 2 10 8 8 4 4 2 10 2 16 8 8 10 8 2 2 10 16 10 10 2\n[76] 4 10 2 4 10 4 8 16 4 2 4 2 16 4 8 10 4 8 10 16 4 4 4 10 2"
},
{
"code": null,
"e": 2885,
"s": 2867,
"text": "> coalesce(x3,y3)"
},
{
"code": null,
"e": 3149,
"s": 2885,
"text": "[1] 2 2 16 16 10 8 2 16 16 4 4 4 16 10 2 4 8 2 4 2 16 2 10 10 16\n[26] 8 2 16 2 10 4 4 2 10 10 16 10 16 10 8 4 4 4 4 10 4 4 10 16 10\n[51] 4 4 2 16 16 2 8 10 16 16 16 16 2 4 16 2 2 16 2 2 10 4 16 4 16\n[76] 2 4 2 4 2 2 10 16 10 4 10 4 10 4 10 10 4 10 4 16 2 4 2 16 2"
},
{
"code": null,
"e": 3160,
"s": 3149,
"text": " Live Demo"
},
{
"code": null,
"e": 3205,
"s": 3160,
"text": "> x4<-sample(rnorm(10),50,replace=TRUE)\n> x4"
},
{
"code": null,
"e": 3816,
"s": 3205,
"text": "[1] -0.02879712 1.31733536 -0.02879712 -0.77268752 0.47775338 1.23117578\n[7] 1.23117578 -0.77268752 1.31733536 0.30903710 0.47775338 1.31733536\n[13] -0.77268752 0.30903710 1.31733536 -1.65681391 -1.65681391 1.31733536\n[19] -0.02879712 0.47775338 0.30903710 -0.77268752 0.08699075 -0.02879712\n[25] -1.65681391 -0.77268752 0.45328379 1.23117578 0.08699075 -1.65681391\n[31] 1.23117578 0.47775338 1.25889501 0.45328379 1.31733536 -1.65681391\n[37] 0.45328379 0.30903710 0.45328379 1.31733536 0.30903710 0.45328379\n[43] 0.08699075 1.31733536 -1.65681391 1.31733536 -0.77268752 -1.65681391\n[49] -0.77268752 1.25889501"
},
{
"code": null,
"e": 3827,
"s": 3816,
"text": " Live Demo"
},
{
"code": null,
"e": 3878,
"s": 3827,
"text": "> y4<-sample(c(rnorm(10),NA),50,replace=TRUE)\n> y4"
},
{
"code": null,
"e": 4393,
"s": 3878,
"text": "[1] -0.6383008 -0.6383008 1.0152569 1.0152569 0.5242708 -0.6383008\n[7] -0.3965653 NA 0.5242708 -0.4664776 NA NA\n[13] 1.1300389 -0.3965653 -0.3965653 1.0152569 -0.9956721 -0.4664776\n[19] -0.4664776 -0.3610621 NA 0.4749585 -0.4664776 -0.3965653\n[25] -0.3610621 -0.9956721 -0.6383008 NA 1.0152569 -0.4664776\n[31] 0.4749585 NA -0.4664776 -0.9956721 NA -0.3610621\n[37] -0.3965653 1.0152569 0.4749585 0.5242708 0.5242708 -0.3965653\n[43] -0.4664776 -0.8300846 -0.9956721 NA 1.0152569 -0.9956721\n[49] -0.4664776 -0.6383008"
},
{
"code": null,
"e": 4411,
"s": 4393,
"text": "> coalesce(x4,y4)"
},
{
"code": null,
"e": 5022,
"s": 4411,
"text": "[1] -0.02879712 1.31733536 -0.02879712 -0.77268752 0.47775338 1.23117578\n[7] 1.23117578 -0.77268752 1.31733536 0.30903710 0.47775338 1.31733536\n[13] -0.77268752 0.30903710 1.31733536 -1.65681391 -1.65681391 1.31733536\n[19] -0.02879712 0.47775338 0.30903710 -0.77268752 0.08699075 -0.02879712\n[25] -1.65681391 -0.77268752 0.45328379 1.23117578 0.08699075 -1.65681391\n[31] 1.23117578 0.47775338 1.25889501 0.45328379 1.31733536 -1.65681391\n[37] 0.45328379 0.30903710 0.45328379 1.31733536 0.30903710 0.45328379\n[43] 0.08699075 1.31733536 -1.65681391 1.31733536 -0.77268752 -1.65681391\n[49] -0.77268752 1.25889501"
},
{
"code": null,
"e": 5033,
"s": 5022,
"text": " Live Demo"
},
{
"code": null,
"e": 5085,
"s": 5033,
"text": "> x5<-sample(c(runif(10,2,5)),50,replace=TRUE)\n> x5"
},
{
"code": null,
"e": 5568,
"s": 5085,
"text": "[1] 4.791954 4.447842 4.479391 4.627612 4.447842 2.460460 2.460460 4.627612\n[9] 4.130456 2.904874 2.904874 2.460460 4.804377 2.517587 4.447842 4.627612\n[17] 4.804377 4.791954 4.479391 2.460460 4.479391 4.479391 4.130456 3.218738\n[25] 4.447842 4.130456 2.460460 4.791954 4.479391 3.218738 4.479391 4.479391\n[33] 4.791954 2.517587 4.447842 4.479391 3.218738 4.130456 3.218738 4.791954\n[41] 2.904874 4.479391 4.791954 2.904874 4.479391 4.791954 4.479391 4.130456\n[49] 4.804377 4.791954"
},
{
"code": null,
"e": 5579,
"s": 5568,
"text": " Live Demo"
},
{
"code": null,
"e": 5631,
"s": 5579,
"text": "> y5<-sample(c(runif(10,3,5)),50,replace=TRUE)\n> y5"
},
{
"code": null,
"e": 6114,
"s": 5631,
"text": "[1] 4.805609 4.832933 3.553856 4.832933 4.942905 4.805609 4.942905 4.608437\n[9] 4.832933 4.163457 4.832933 4.608437 3.013883 4.608437 4.942905 4.163457\n[17] 4.743048 3.013883 3.013883 4.743048 3.553856 4.743048 3.933597 3.933597\n[25] 4.743048 4.508212 4.805609 4.743048 3.013883 4.163457 4.942905 4.743048\n[33] 4.942905 4.508212 3.553856 4.608437 3.553856 4.743048 3.933597 4.163457\n[41] 3.933597 4.508212 4.608437 4.508212 3.933597 4.942905 4.508212 4.832933\n[49] 4.832933 4.805609"
},
{
"code": null,
"e": 6132,
"s": 6114,
"text": "> coalesce(x5,y5)"
},
{
"code": null,
"e": 6615,
"s": 6132,
"text": "[1] 4.791954 4.447842 4.479391 4.627612 4.447842 2.460460 2.460460 4.627612\n[9] 4.130456 2.904874 2.904874 2.460460 4.804377 2.517587 4.447842 4.627612\n[17] 4.804377 4.791954 4.479391 2.460460 4.479391 4.479391 4.130456 3.218738\n[25] 4.447842 4.130456 2.460460 4.791954 4.479391 3.218738 4.479391 4.479391\n[33] 4.791954 2.517587 4.447842 4.479391 3.218738 4.130456 3.218738 4.791954\n[41] 2.904874 4.479391 4.791954 2.904874 4.479391 4.791954 4.479391 4.130456\n[49] 4.804377 4.791954"
}
] |
Abstract Base Classes in Python (abc)
|
A class is called an Abstract class if it contains one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and its abstract methods must be implemented by its subclasses.
Abstract base classes provide a way to define interfaces when other techniques like hasattr() would be clumsy or subtly wrong (for example with magic methods). ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but are still recognized by isinstance() and issubclass() functions. There are many built-in ABCs in Python. ABCs for Data structures like Iterator, Generator, Set, mapping etc. are defined in collections.abc module. The numbers module defines numeric tower which is a collection of base classes for numeric data types. The 'abc' module in Python library provides the infrastructure for defining custom abstract base classes.
'abc' works by marking methods of the base class as abstract. This is done by @absttractmethod decorator. A concrete class which is a sub class of such abstract base class then implements the abstract base by overriding its abstract methods.
The abc module defines ABCMeta class which is a metaclass for defining abstract base class. Following example defines Shape class as an abstract base class using ABCMeta. The shape class has area() method decorated by abstractmethod.
A Rectangle class now uses above Shape class as its parent and implementing the abstract area() method. Since it is a concrete class, it can be instantiated and imlemented area() method can be called.
import abc
class Shape(metaclass=abc.ABCMeta):
@abc.abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, x,y):
self.l = x
self.b=y
def area(self):
return self.l*self.b
r = Rectangle(10,20)
print ('area: ',r.area())
Note the abstract base class may have more than one abstract methods. The child class must implement all of them failing which TypeError will be raised.
the abc module also defines ABC helper class which can be used instead of ABCMeta class in definition of abstract base class.
class Shape(abc.ABC):
@abc.abstractmethod
def area(self):
pass
Instead of subclassing from abstract base class, it can be registered as abstract base by register class decorator.
class Shape(abc.ABC):
@abc.abstractmethod
def area(self):
pass
@Shape.register
class Rectangle():
def __init__(self, x,y):
self.l = x
self.b=y
def area(self):
return self.l*self.b
You may also provide class methods and static methods in abstract base class by decorators @abstractclassmethod and @abstractstatic method decorators respectively.
|
[
{
"code": null,
"e": 1330,
"s": 1062,
"text": "A class is called an Abstract class if it contains one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and its abstract methods must be implemented by its subclasses."
},
{
"code": null,
"e": 2001,
"s": 1330,
"text": "Abstract base classes provide a way to define interfaces when other techniques like hasattr() would be clumsy or subtly wrong (for example with magic methods). ABCs introduce virtual subclasses, which are classes that don’t inherit from a class but are still recognized by isinstance() and issubclass() functions. There are many built-in ABCs in Python. ABCs for Data structures like Iterator, Generator, Set, mapping etc. are defined in collections.abc module. The numbers module defines numeric tower which is a collection of base classes for numeric data types. The 'abc' module in Python library provides the infrastructure for defining custom abstract base classes."
},
{
"code": null,
"e": 2243,
"s": 2001,
"text": "'abc' works by marking methods of the base class as abstract. This is done by @absttractmethod decorator. A concrete class which is a sub class of such abstract base class then implements the abstract base by overriding its abstract methods."
},
{
"code": null,
"e": 2477,
"s": 2243,
"text": "The abc module defines ABCMeta class which is a metaclass for defining abstract base class. Following example defines Shape class as an abstract base class using ABCMeta. The shape class has area() method decorated by abstractmethod."
},
{
"code": null,
"e": 2678,
"s": 2477,
"text": "A Rectangle class now uses above Shape class as its parent and implementing the abstract area() method. Since it is a concrete class, it can be instantiated and imlemented area() method can be called."
},
{
"code": null,
"e": 2955,
"s": 2678,
"text": "import abc\nclass Shape(metaclass=abc.ABCMeta):\n @abc.abstractmethod\n def area(self):\n pass\nclass Rectangle(Shape):\n def __init__(self, x,y):\n self.l = x\n self.b=y\n def area(self):\n return self.l*self.b\nr = Rectangle(10,20)\nprint ('area: ',r.area())"
},
{
"code": null,
"e": 3108,
"s": 2955,
"text": "Note the abstract base class may have more than one abstract methods. The child class must implement all of them failing which TypeError will be raised."
},
{
"code": null,
"e": 3234,
"s": 3108,
"text": "the abc module also defines ABC helper class which can be used instead of ABCMeta class in definition of abstract base class."
},
{
"code": null,
"e": 3309,
"s": 3234,
"text": "class Shape(abc.ABC):\n @abc.abstractmethod\n def area(self):\n pass"
},
{
"code": null,
"e": 3425,
"s": 3309,
"text": "Instead of subclassing from abstract base class, it can be registered as abstract base by register class decorator."
},
{
"code": null,
"e": 3635,
"s": 3425,
"text": "class Shape(abc.ABC):\n @abc.abstractmethod\n def area(self):\n pass\n@Shape.register\nclass Rectangle():\n def __init__(self, x,y):\n self.l = x\n self.b=y\n def area(self):\n return self.l*self.b"
},
{
"code": null,
"e": 3799,
"s": 3635,
"text": "You may also provide class methods and static methods in abstract base class by decorators @abstractclassmethod and @abstractstatic method decorators respectively."
}
] |
JavaScript - Date getHours() Method
|
Javascript Date getHours() method returns the hour in the specified date according to local time. The value returned by getHours() is an integer between 0 and 23.
Its syntax is as follows −
Date.getHours()
Returns the hour in the specified date according to local time.
Try the following example.
<html>
<head>
<title>JavaScript getHours Method</title>
</head>
<body>
<script type = "text/javascript">
var dt = new Date("December 25, 1995 23:15:00");
document.write("getHours() : " + dt.getHours() );
</script>
</body>
</html>
getHours() : 23
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": 2629,
"s": 2466,
"text": "Javascript Date getHours() method returns the hour in the specified date according to local time. The value returned by getHours() is an integer between 0 and 23."
},
{
"code": null,
"e": 2656,
"s": 2629,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2673,
"s": 2656,
"text": "Date.getHours()\n"
},
{
"code": null,
"e": 2737,
"s": 2673,
"text": "Returns the hour in the specified date according to local time."
},
{
"code": null,
"e": 2764,
"s": 2737,
"text": "Try the following example."
},
{
"code": null,
"e": 3056,
"s": 2764,
"text": "<html>\n <head>\n <title>JavaScript getHours Method</title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var dt = new Date(\"December 25, 1995 23:15:00\");\n document.write(\"getHours() : \" + dt.getHours() ); \n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 3074,
"s": 3056,
"text": "getHours() : 23 \n"
},
{
"code": null,
"e": 3109,
"s": 3074,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3123,
"s": 3109,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3157,
"s": 3123,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3171,
"s": 3157,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3206,
"s": 3171,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3223,
"s": 3206,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3258,
"s": 3223,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3275,
"s": 3258,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3308,
"s": 3275,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3336,
"s": 3308,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3370,
"s": 3336,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3398,
"s": 3370,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3405,
"s": 3398,
"text": " Print"
},
{
"code": null,
"e": 3416,
"s": 3405,
"text": " Add Notes"
}
] |
How to reset the primary key of a table in mysql?
|
The reset the primary key of a table means to reset the auto_increment property to 1. The syntax is as follows to reset the primary key of a table.
alter table yourTableName auto_increment = 1;
To understand, let us create a table −
mysql> create table ResetPrimaryKey
−> (
−> Id int auto_increment,
−> PRIMARY KEY(Id)
−> );
Query OK, 0 rows affected (0.59 sec)
Insert some records into the table. The query to insert records is as follows −
mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.18 sec)
mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.15 sec)
mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.09 sec)
mysql> insert into ResetPrimaryKey values();
Query OK, 1 row affected (0.09 sec)
Now you can display all records with the help of select statement. The query is as follows −
mysql> select *from ResetPrimaryKey;
The following is the output that displays only the ID, which is a Primary Key:
+----+
| Id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
+----+
4 rows in set (0.00 sec)
Here is the query to reset the primary key of a table using alter −
mysql> alter table ResetPrimaryKey auto_increment = 1;
Query OK, 0 rows affected (0.21 sec)
Records: 0 Duplicates: 0 Warnings: 0
The query to check that we have added auto_increment property successfully or not:
mysql> desc ResetPrimaryKey;
The following is the output −
+-------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------+---------+------+-----+---------+----------------+
| Id | int(11) | NO | PRI | NULL | auto_increment |
+-------+---------+------+-----+---------+----------------+
1 row in set (0.11 sec)
|
[
{
"code": null,
"e": 1210,
"s": 1062,
"text": "The reset the primary key of a table means to reset the auto_increment property to 1. The syntax is as follows to reset the primary key of a table."
},
{
"code": null,
"e": 1256,
"s": 1210,
"text": "alter table yourTableName auto_increment = 1;"
},
{
"code": null,
"e": 1295,
"s": 1256,
"text": "To understand, let us create a table −"
},
{
"code": null,
"e": 1430,
"s": 1295,
"text": "mysql> create table ResetPrimaryKey\n−> (\n −> Id int auto_increment,\n −> PRIMARY KEY(Id)\n−> );\nQuery OK, 0 rows affected (0.59 sec)"
},
{
"code": null,
"e": 1510,
"s": 1430,
"text": "Insert some records into the table. The query to insert records is as follows −"
},
{
"code": null,
"e": 1837,
"s": 1510,
"text": "mysql> insert into ResetPrimaryKey values();\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into ResetPrimaryKey values();\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into ResetPrimaryKey values();\nQuery OK, 1 row affected (0.09 sec)\n\nmysql> insert into ResetPrimaryKey values();\nQuery OK, 1 row affected (0.09 sec)"
},
{
"code": null,
"e": 1930,
"s": 1837,
"text": "Now you can display all records with the help of select statement. The query is as follows −"
},
{
"code": null,
"e": 1967,
"s": 1930,
"text": "mysql> select *from ResetPrimaryKey;"
},
{
"code": null,
"e": 2046,
"s": 1967,
"text": "The following is the output that displays only the ID, which is a Primary Key:"
},
{
"code": null,
"e": 2127,
"s": 2046,
"text": "+----+\n| Id |\n+----+\n| 1 |\n| 2 |\n| 3 |\n| 4 |\n+----+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2195,
"s": 2127,
"text": "Here is the query to reset the primary key of a table using alter −"
},
{
"code": null,
"e": 2324,
"s": 2195,
"text": "mysql> alter table ResetPrimaryKey auto_increment = 1;\nQuery OK, 0 rows affected (0.21 sec)\nRecords: 0 Duplicates: 0 Warnings: 0"
},
{
"code": null,
"e": 2407,
"s": 2324,
"text": "The query to check that we have added auto_increment property successfully or not:"
},
{
"code": null,
"e": 2436,
"s": 2407,
"text": "mysql> desc ResetPrimaryKey;"
},
{
"code": null,
"e": 2466,
"s": 2436,
"text": "The following is the output −"
},
{
"code": null,
"e": 2790,
"s": 2466,
"text": "+-------+---------+------+-----+---------+----------------+\n| Field | Type | Null | Key | Default | Extra |\n+-------+---------+------+-----+---------+----------------+\n| Id | int(11) | NO | PRI | NULL | auto_increment |\n+-------+---------+------+-----+---------+----------------+\n1 row in set (0.11 sec)"
}
] |
AI with Python â Genetic Algorithms
|
This chapter discusses Genetic Algorithms of AI in detail.
Genetic Algorithms (GAs) are search based algorithms based on the concepts of natural selection and genetics. GAs are a subset of a much larger branch of computation known as Evolutionary Computation.
GAs were developed by John Holland and his students and colleagues at the University of Michigan, most notably David E. Goldberg. It has since been tried on various optimization problems with a high degree of success.
In GAs, we have a pool of possible solutions to the given problem. These solutions then undergo recombination and mutation (like in natural genetics), produces new children, and the process is repeated for various generations. Each individual (or candidate solution) is assigned a fitness value (based on its objective function value) and the fitter individuals are given a higher chance to mate and yield fitter individuals. This is in line with the Darwinian Theory of Survival of the Fittest.
Thus, it keeps evolving better individuals or solutions over generations, till it reaches a stopping criterion.
Genetic Algorithms are sufficiently randomized in nature, but they perform much better than random local search (where we just try random solutions, keeping track of the best so far), as they exploit historical information as well.
Optimization is an action of making design, situation, resource and system, as effective as possible. The following block diagram shows the optimization process −
The following is a sequence of steps of GA mechanism when used for optimization of problems.
Step 1 − Generate the initial population randomly.
Step 1 − Generate the initial population randomly.
Step 2 − Select the initial solution with best fitness values.
Step 2 − Select the initial solution with best fitness values.
Step 3 − Recombine the selected solutions using mutation and crossover operators.
Step 3 − Recombine the selected solutions using mutation and crossover operators.
Step 4 − Insert an offspring into the population.
Step 4 − Insert an offspring into the population.
Step 5 − Now, if the stop condition is met, return the solution with their best fitness value. Else go to step 2.
Step 5 − Now, if the stop condition is met, return the solution with their best fitness value. Else go to step 2.
For solving the problem by using Genetic Algorithms in Python, we are going to use a powerful package for GA called DEAP. It is a library of novel evolutionary computation framework for rapid prototyping and testing of ideas. We can install this package with the help of the following command on command prompt −
pip install deap
If you are using anaconda environment, then following command can be used to install deap −
conda install -c conda-forge deap
This section explains you the implementation of solutions using Genetic Algorithms.
The following example shows you how to generate a bit string that would contain 15 ones, based on the One Max problem.
Import the necessary packages as shown −
import random
from deap import base, creator, tools
Define the evaluation function. It is the first step to create a genetic algorithm.
def eval_func(individual):
target_sum = 15
return len(individual) - abs(sum(individual) - target_sum),
Now, create the toolbox with the right parameters −
def create_toolbox(num_bits):
creator.create("FitnessMax", base.Fitness, weights=(1.0,))
creator.create("Individual", list, fitness=creator.FitnessMax)
Initialize the toolbox
toolbox = base.Toolbox()
toolbox.register("attr_bool", random.randint, 0, 1)
toolbox.register("individual", tools.initRepeat, creator.Individual,
toolbox.attr_bool, num_bits)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
Register the evaluation operator −
toolbox.register("evaluate", eval_func)
Now, register the crossover operator −
toolbox.register("mate", tools.cxTwoPoint)
Register a mutation operator −
toolbox.register("mutate", tools.mutFlipBit, indpb = 0.05)
Define the operator for breeding −
toolbox.register("select", tools.selTournament, tournsize = 3)
return toolbox
if __name__ == "__main__":
num_bits = 45
toolbox = create_toolbox(num_bits)
random.seed(7)
population = toolbox.population(n = 500)
probab_crossing, probab_mutating = 0.5, 0.2
num_generations = 10
print('\nEvolution process starts')
Evaluate the entire population −
fitnesses = list(map(toolbox.evaluate, population))
for ind, fit in zip(population, fitnesses):
ind.fitness.values = fit
print('\nEvaluated', len(population), 'individuals')
Create and iterate through generations −
for g in range(num_generations):
print("\n- Generation", g)
Selecting the next generation individuals −
offspring = toolbox.select(population, len(population))
Now, clone the selected individuals −
offspring = list(map(toolbox.clone, offspring))
Apply crossover and mutation on the offspring −
for child1, child2 in zip(offspring[::2], offspring[1::2]):
if random.random() < probab_crossing:
toolbox.mate(child1, child2)
Delete the fitness value of child
del child1.fitness.values
del child2.fitness.values
Now, apply mutation −
for mutant in offspring:
if random.random() < probab_mutating:
toolbox.mutate(mutant)
del mutant.fitness.values
Evaluate the individuals with an invalid fitness −
invalid_ind = [ind for ind in offspring if not ind.fitness.valid]
fitnesses = map(toolbox.evaluate, invalid_ind)
for ind, fit in zip(invalid_ind, fitnesses):
ind.fitness.values = fit
print('Evaluated', len(invalid_ind), 'individuals')
Now, replace population with next generation individual −
population[:] = offspring
Print the statistics for the current generations −
fits = [ind.fitness.values[0] for ind in population]
length = len(population)
mean = sum(fits) / length
sum2 = sum(x*x for x in fits)
std = abs(sum2 / length - mean**2)**0.5
print('Min =', min(fits), ', Max =', max(fits))
print('Average =', round(mean, 2), ', Standard deviation =',
round(std, 2))
print("\n- Evolution ends")
Print the final output −
best_ind = tools.selBest(population, 1)[0]
print('\nBest individual:\n', best_ind)
print('\nNumber of ones:', sum(best_ind))
Following would be the output:
Evolution process starts
Evaluated 500 individuals
- Generation 0
Evaluated 295 individuals
Min = 32.0 , Max = 45.0
Average = 40.29 , Standard deviation = 2.61
- Generation 1
Evaluated 292 individuals
Min = 34.0 , Max = 45.0
Average = 42.35 , Standard deviation = 1.91
- Generation 2
Evaluated 277 individuals
Min = 37.0 , Max = 45.0
Average = 43.39 , Standard deviation = 1.46
... ... ... ...
- Generation 9
Evaluated 299 individuals
Min = 40.0 , Max = 45.0
Average = 44.12 , Standard deviation = 1.11
- Evolution ends
Best individual:
[0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1,
1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0,
1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1]
Number of ones: 15
It is one of the best known problems in genetic programming. All symbolic regression problems use an arbitrary data distribution, and try to fit the most accurate data with a symbolic formula. Usually, a measure like the RMSE (Root Mean Square Error) is used to measure an individual’s fitness. It is a classic regressor problem and here we are using the equation 5x3-6x2+8x=1. We need to follow all the steps as followed in the above example, but the main part would be to create the primitive sets because they are the building blocks for the individuals so the evaluation can start. Here we will be using the classic set of primitives.
The following Python code explains this in detail −
import operator
import math
import random
import numpy as np
from deap import algorithms, base, creator, tools, gp
def division_operator(numerator, denominator):
if denominator == 0:
return 1
return numerator / denominator
def eval_func(individual, points):
func = toolbox.compile(expr=individual)
return math.fsum(mse) / len(points),
def create_toolbox():
pset = gp.PrimitiveSet("MAIN", 1)
pset.addPrimitive(operator.add, 2)
pset.addPrimitive(operator.sub, 2)
pset.addPrimitive(operator.mul, 2)
pset.addPrimitive(division_operator, 2)
pset.addPrimitive(operator.neg, 1)
pset.addPrimitive(math.cos, 1)
pset.addPrimitive(math.sin, 1)
pset.addEphemeralConstant("rand101", lambda: random.randint(-1,1))
pset.renameArguments(ARG0 = 'x')
creator.create("FitnessMin", base.Fitness, weights = (-1.0,))
creator.create("Individual",gp.PrimitiveTree,fitness=creator.FitnessMin)
toolbox = base.Toolbox()
toolbox.register("expr", gp.genHalfAndHalf, pset=pset, min_=1, max_=2)
toolbox.expr)
toolbox.register("population",tools.initRepeat,list, toolbox.individual)
toolbox.register("compile", gp.compile, pset = pset)
toolbox.register("evaluate", eval_func, points = [x/10. for x in range(-10,10)])
toolbox.register("select", tools.selTournament, tournsize = 3)
toolbox.register("mate", gp.cxOnePoint)
toolbox.register("expr_mut", gp.genFull, min_=0, max_=2)
toolbox.register("mutate", gp.mutUniform, expr = toolbox.expr_mut, pset = pset)
toolbox.decorate("mate", gp.staticLimit(key = operator.attrgetter("height"), max_value = 17))
toolbox.decorate("mutate", gp.staticLimit(key = operator.attrgetter("height"), max_value = 17))
return toolbox
if __name__ == "__main__":
random.seed(7)
toolbox = create_toolbox()
population = toolbox.population(n = 450)
hall_of_fame = tools.HallOfFame(1)
stats_fit = tools.Statistics(lambda x: x.fitness.values)
stats_size = tools.Statistics(len)
mstats = tools.MultiStatistics(fitness=stats_fit, size = stats_size)
mstats.register("avg", np.mean)
mstats.register("std", np.std)
mstats.register("min", np.min)
mstats.register("max", np.max)
probab_crossover = 0.4
probab_mutate = 0.2
number_gen = 10
population, log = algorithms.eaSimple(population, toolbox,
probab_crossover, probab_mutate, number_gen,
stats = mstats, halloffame = hall_of_fame, verbose = True)
Note that all the basic steps are same as used while generating bit patterns. This program will give us the output as min, max, std (standard deviation) after 10 number of generations.
78 Lectures
7 hours
Arnab Chakraborty
87 Lectures
9.5 hours
DigiFisk (Programming Is Fun)
10 Lectures
1 hours
Nikoloz Sanakoevi
15 Lectures
54 mins
Mukund Kumar Mishra
11 Lectures
1 hours
Gilad James, PhD
20 Lectures
2 hours
Gilad James, PhD
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2264,
"s": 2205,
"text": "This chapter discusses Genetic Algorithms of AI in detail."
},
{
"code": null,
"e": 2465,
"s": 2264,
"text": "Genetic Algorithms (GAs) are search based algorithms based on the concepts of natural selection and genetics. GAs are a subset of a much larger branch of computation known as Evolutionary Computation."
},
{
"code": null,
"e": 2683,
"s": 2465,
"text": "GAs were developed by John Holland and his students and colleagues at the University of Michigan, most notably David E. Goldberg. It has since been tried on various optimization problems with a high degree of success."
},
{
"code": null,
"e": 3179,
"s": 2683,
"text": "In GAs, we have a pool of possible solutions to the given problem. These solutions then undergo recombination and mutation (like in natural genetics), produces new children, and the process is repeated for various generations. Each individual (or candidate solution) is assigned a fitness value (based on its objective function value) and the fitter individuals are given a higher chance to mate and yield fitter individuals. This is in line with the Darwinian Theory of Survival of the Fittest."
},
{
"code": null,
"e": 3291,
"s": 3179,
"text": "Thus, it keeps evolving better individuals or solutions over generations, till it reaches a stopping criterion."
},
{
"code": null,
"e": 3523,
"s": 3291,
"text": "Genetic Algorithms are sufficiently randomized in nature, but they perform much better than random local search (where we just try random solutions, keeping track of the best so far), as they exploit historical information as well."
},
{
"code": null,
"e": 3686,
"s": 3523,
"text": "Optimization is an action of making design, situation, resource and system, as effective as possible. The following block diagram shows the optimization process −"
},
{
"code": null,
"e": 3779,
"s": 3686,
"text": "The following is a sequence of steps of GA mechanism when used for optimization of problems."
},
{
"code": null,
"e": 3830,
"s": 3779,
"text": "Step 1 − Generate the initial population randomly."
},
{
"code": null,
"e": 3881,
"s": 3830,
"text": "Step 1 − Generate the initial population randomly."
},
{
"code": null,
"e": 3944,
"s": 3881,
"text": "Step 2 − Select the initial solution with best fitness values."
},
{
"code": null,
"e": 4007,
"s": 3944,
"text": "Step 2 − Select the initial solution with best fitness values."
},
{
"code": null,
"e": 4089,
"s": 4007,
"text": "Step 3 − Recombine the selected solutions using mutation and crossover operators."
},
{
"code": null,
"e": 4171,
"s": 4089,
"text": "Step 3 − Recombine the selected solutions using mutation and crossover operators."
},
{
"code": null,
"e": 4221,
"s": 4171,
"text": "Step 4 − Insert an offspring into the population."
},
{
"code": null,
"e": 4271,
"s": 4221,
"text": "Step 4 − Insert an offspring into the population."
},
{
"code": null,
"e": 4385,
"s": 4271,
"text": "Step 5 − Now, if the stop condition is met, return the solution with their best fitness value. Else go to step 2."
},
{
"code": null,
"e": 4499,
"s": 4385,
"text": "Step 5 − Now, if the stop condition is met, return the solution with their best fitness value. Else go to step 2."
},
{
"code": null,
"e": 4812,
"s": 4499,
"text": "For solving the problem by using Genetic Algorithms in Python, we are going to use a powerful package for GA called DEAP. It is a library of novel evolutionary computation framework for rapid prototyping and testing of ideas. We can install this package with the help of the following command on command prompt −"
},
{
"code": null,
"e": 4830,
"s": 4812,
"text": "pip install deap\n"
},
{
"code": null,
"e": 4922,
"s": 4830,
"text": "If you are using anaconda environment, then following command can be used to install deap −"
},
{
"code": null,
"e": 4957,
"s": 4922,
"text": "conda install -c conda-forge deap\n"
},
{
"code": null,
"e": 5041,
"s": 4957,
"text": "This section explains you the implementation of solutions using Genetic Algorithms."
},
{
"code": null,
"e": 5160,
"s": 5041,
"text": "The following example shows you how to generate a bit string that would contain 15 ones, based on the One Max problem."
},
{
"code": null,
"e": 5201,
"s": 5160,
"text": "Import the necessary packages as shown −"
},
{
"code": null,
"e": 5253,
"s": 5201,
"text": "import random\nfrom deap import base, creator, tools"
},
{
"code": null,
"e": 5337,
"s": 5253,
"text": "Define the evaluation function. It is the first step to create a genetic algorithm."
},
{
"code": null,
"e": 5446,
"s": 5337,
"text": "def eval_func(individual):\n target_sum = 15\n return len(individual) - abs(sum(individual) - target_sum),"
},
{
"code": null,
"e": 5498,
"s": 5446,
"text": "Now, create the toolbox with the right parameters −"
},
{
"code": null,
"e": 5656,
"s": 5498,
"text": "def create_toolbox(num_bits):\n creator.create(\"FitnessMax\", base.Fitness, weights=(1.0,))\n creator.create(\"Individual\", list, fitness=creator.FitnessMax)"
},
{
"code": null,
"e": 5679,
"s": 5656,
"text": "Initialize the toolbox"
},
{
"code": null,
"e": 5935,
"s": 5679,
"text": " toolbox = base.Toolbox()\ntoolbox.register(\"attr_bool\", random.randint, 0, 1)\ntoolbox.register(\"individual\", tools.initRepeat, creator.Individual,\n toolbox.attr_bool, num_bits)\ntoolbox.register(\"population\", tools.initRepeat, list, toolbox.individual)"
},
{
"code": null,
"e": 5970,
"s": 5935,
"text": "Register the evaluation operator −"
},
{
"code": null,
"e": 6010,
"s": 5970,
"text": "toolbox.register(\"evaluate\", eval_func)"
},
{
"code": null,
"e": 6049,
"s": 6010,
"text": "Now, register the crossover operator −"
},
{
"code": null,
"e": 6092,
"s": 6049,
"text": "toolbox.register(\"mate\", tools.cxTwoPoint)"
},
{
"code": null,
"e": 6123,
"s": 6092,
"text": "Register a mutation operator −"
},
{
"code": null,
"e": 6182,
"s": 6123,
"text": "toolbox.register(\"mutate\", tools.mutFlipBit, indpb = 0.05)"
},
{
"code": null,
"e": 6217,
"s": 6182,
"text": "Define the operator for breeding −"
},
{
"code": null,
"e": 6549,
"s": 6217,
"text": "toolbox.register(\"select\", tools.selTournament, tournsize = 3)\nreturn toolbox\nif __name__ == \"__main__\":\n num_bits = 45\n toolbox = create_toolbox(num_bits)\n random.seed(7)\n population = toolbox.population(n = 500)\n probab_crossing, probab_mutating = 0.5, 0.2\n num_generations = 10\n print('\\nEvolution process starts')"
},
{
"code": null,
"e": 6582,
"s": 6549,
"text": "Evaluate the entire population −"
},
{
"code": null,
"e": 6759,
"s": 6582,
"text": "fitnesses = list(map(toolbox.evaluate, population))\nfor ind, fit in zip(population, fitnesses):\n ind.fitness.values = fit\nprint('\\nEvaluated', len(population), 'individuals')"
},
{
"code": null,
"e": 6800,
"s": 6759,
"text": "Create and iterate through generations −"
},
{
"code": null,
"e": 6863,
"s": 6800,
"text": "for g in range(num_generations):\n print(\"\\n- Generation\", g)"
},
{
"code": null,
"e": 6907,
"s": 6863,
"text": "Selecting the next generation individuals −"
},
{
"code": null,
"e": 6963,
"s": 6907,
"text": "offspring = toolbox.select(population, len(population))"
},
{
"code": null,
"e": 7001,
"s": 6963,
"text": "Now, clone the selected individuals −"
},
{
"code": null,
"e": 7049,
"s": 7001,
"text": "offspring = list(map(toolbox.clone, offspring))"
},
{
"code": null,
"e": 7097,
"s": 7049,
"text": "Apply crossover and mutation on the offspring −"
},
{
"code": null,
"e": 7230,
"s": 7097,
"text": "for child1, child2 in zip(offspring[::2], offspring[1::2]):\n if random.random() < probab_crossing:\n toolbox.mate(child1, child2)"
},
{
"code": null,
"e": 7264,
"s": 7230,
"text": "Delete the fitness value of child"
},
{
"code": null,
"e": 7316,
"s": 7264,
"text": "del child1.fitness.values\ndel child2.fitness.values"
},
{
"code": null,
"e": 7338,
"s": 7316,
"text": "Now, apply mutation −"
},
{
"code": null,
"e": 7459,
"s": 7338,
"text": "for mutant in offspring:\n if random.random() < probab_mutating:\n toolbox.mutate(mutant)\n del mutant.fitness.values"
},
{
"code": null,
"e": 7510,
"s": 7459,
"text": "Evaluate the individuals with an invalid fitness −"
},
{
"code": null,
"e": 7748,
"s": 7510,
"text": "invalid_ind = [ind for ind in offspring if not ind.fitness.valid]\nfitnesses = map(toolbox.evaluate, invalid_ind)\nfor ind, fit in zip(invalid_ind, fitnesses):\n ind.fitness.values = fit\nprint('Evaluated', len(invalid_ind), 'individuals')"
},
{
"code": null,
"e": 7806,
"s": 7748,
"text": "Now, replace population with next generation individual −"
},
{
"code": null,
"e": 7832,
"s": 7806,
"text": "population[:] = offspring"
},
{
"code": null,
"e": 7883,
"s": 7832,
"text": "Print the statistics for the current generations −"
},
{
"code": null,
"e": 8209,
"s": 7883,
"text": "fits = [ind.fitness.values[0] for ind in population]\nlength = len(population)\nmean = sum(fits) / length\nsum2 = sum(x*x for x in fits)\nstd = abs(sum2 / length - mean**2)**0.5\nprint('Min =', min(fits), ', Max =', max(fits))\nprint('Average =', round(mean, 2), ', Standard deviation =',\nround(std, 2))\nprint(\"\\n- Evolution ends\")"
},
{
"code": null,
"e": 8234,
"s": 8209,
"text": "Print the final output −"
},
{
"code": null,
"e": 9095,
"s": 8234,
"text": " best_ind = tools.selBest(population, 1)[0]\n print('\\nBest individual:\\n', best_ind)\n print('\\nNumber of ones:', sum(best_ind))\nFollowing would be the output:\nEvolution process starts\nEvaluated 500 individuals\n- Generation 0\nEvaluated 295 individuals\nMin = 32.0 , Max = 45.0\nAverage = 40.29 , Standard deviation = 2.61\n- Generation 1\nEvaluated 292 individuals\nMin = 34.0 , Max = 45.0\nAverage = 42.35 , Standard deviation = 1.91\n- Generation 2\nEvaluated 277 individuals\nMin = 37.0 , Max = 45.0\nAverage = 43.39 , Standard deviation = 1.46\n... ... ... ...\n- Generation 9\nEvaluated 299 individuals\nMin = 40.0 , Max = 45.0\nAverage = 44.12 , Standard deviation = 1.11\n- Evolution ends\nBest individual:\n[0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 1, \n 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0,\n 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1]\nNumber of ones: 15\n"
},
{
"code": null,
"e": 9734,
"s": 9095,
"text": "It is one of the best known problems in genetic programming. All symbolic regression problems use an arbitrary data distribution, and try to fit the most accurate data with a symbolic formula. Usually, a measure like the RMSE (Root Mean Square Error) is used to measure an individual’s fitness. It is a classic regressor problem and here we are using the equation 5x3-6x2+8x=1. We need to follow all the steps as followed in the above example, but the main part would be to create the primitive sets because they are the building blocks for the individuals so the evaluation can start. Here we will be using the classic set of primitives."
},
{
"code": null,
"e": 9786,
"s": 9734,
"text": "The following Python code explains this in detail −"
},
{
"code": null,
"e": 12220,
"s": 9786,
"text": "import operator\nimport math\nimport random\nimport numpy as np\nfrom deap import algorithms, base, creator, tools, gp\ndef division_operator(numerator, denominator):\n if denominator == 0:\n return 1\n return numerator / denominator\ndef eval_func(individual, points):\n func = toolbox.compile(expr=individual)\n return math.fsum(mse) / len(points),\ndef create_toolbox():\n pset = gp.PrimitiveSet(\"MAIN\", 1)\n pset.addPrimitive(operator.add, 2)\n pset.addPrimitive(operator.sub, 2)\n pset.addPrimitive(operator.mul, 2)\n pset.addPrimitive(division_operator, 2)\n pset.addPrimitive(operator.neg, 1)\n pset.addPrimitive(math.cos, 1)\n pset.addPrimitive(math.sin, 1)\n pset.addEphemeralConstant(\"rand101\", lambda: random.randint(-1,1))\n pset.renameArguments(ARG0 = 'x')\n creator.create(\"FitnessMin\", base.Fitness, weights = (-1.0,))\n creator.create(\"Individual\",gp.PrimitiveTree,fitness=creator.FitnessMin)\n toolbox = base.Toolbox()\n toolbox.register(\"expr\", gp.genHalfAndHalf, pset=pset, min_=1, max_=2)\n toolbox.expr)\n toolbox.register(\"population\",tools.initRepeat,list, toolbox.individual)\n toolbox.register(\"compile\", gp.compile, pset = pset)\n toolbox.register(\"evaluate\", eval_func, points = [x/10. for x in range(-10,10)])\n toolbox.register(\"select\", tools.selTournament, tournsize = 3)\n toolbox.register(\"mate\", gp.cxOnePoint)\n toolbox.register(\"expr_mut\", gp.genFull, min_=0, max_=2)\n toolbox.register(\"mutate\", gp.mutUniform, expr = toolbox.expr_mut, pset = pset)\n toolbox.decorate(\"mate\", gp.staticLimit(key = operator.attrgetter(\"height\"), max_value = 17))\n toolbox.decorate(\"mutate\", gp.staticLimit(key = operator.attrgetter(\"height\"), max_value = 17))\n return toolbox\nif __name__ == \"__main__\":\n random.seed(7)\n toolbox = create_toolbox()\n population = toolbox.population(n = 450)\n hall_of_fame = tools.HallOfFame(1)\n stats_fit = tools.Statistics(lambda x: x.fitness.values)\n stats_size = tools.Statistics(len)\n mstats = tools.MultiStatistics(fitness=stats_fit, size = stats_size)\n mstats.register(\"avg\", np.mean)\n mstats.register(\"std\", np.std)\n mstats.register(\"min\", np.min)\n mstats.register(\"max\", np.max)\n probab_crossover = 0.4\n probab_mutate = 0.2\n number_gen = 10\n population, log = algorithms.eaSimple(population, toolbox,\n probab_crossover, probab_mutate, number_gen,\n stats = mstats, halloffame = hall_of_fame, verbose = True)\n"
},
{
"code": null,
"e": 12405,
"s": 12220,
"text": "Note that all the basic steps are same as used while generating bit patterns. This program will give us the output as min, max, std (standard deviation) after 10 number of generations."
},
{
"code": null,
"e": 12438,
"s": 12405,
"text": "\n 78 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 12457,
"s": 12438,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 12492,
"s": 12457,
"text": "\n 87 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 12523,
"s": 12492,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 12556,
"s": 12523,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12575,
"s": 12556,
"text": " Nikoloz Sanakoevi"
},
{
"code": null,
"e": 12607,
"s": 12575,
"text": "\n 15 Lectures \n 54 mins\n"
},
{
"code": null,
"e": 12628,
"s": 12607,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 12661,
"s": 12628,
"text": "\n 11 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 12679,
"s": 12661,
"text": " Gilad James, PhD"
},
{
"code": null,
"e": 12712,
"s": 12679,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 12730,
"s": 12712,
"text": " Gilad James, PhD"
},
{
"code": null,
"e": 12737,
"s": 12730,
"text": " Print"
},
{
"code": null,
"e": 12748,
"s": 12737,
"text": " Add Notes"
}
] |
How to do groupby on a multiindex in Pandas?
|
Multiindex Data Frame is a data frame with more than one index. Let’s say the following is our csv stored on the Desktop −
At first, import the pandas library and read the above CSV file −
import pandas as pd
df = pd.read_csv("C:/Users/amit_/Desktop/sales.csv") print(df)
We will form the ‘Car‘ and ‘Place‘ columns of the Dataframe as the index −
df = df.set_index(['Car', 'Place'])
The DataFrame is now a multi-indexed DataFrame having the ‘Car‘ and ‘Place‘ columns as an index.
Now, let us use groupby on the multiindex dataframe:
res = df.groupby(level=['Car'])['UnitsSold'].mean() print(res)
Following is the code −
import pandas as pd
df = pd.read_csv("C:/Users/amit_/Desktop/sales.csv")
print(df)
# set Car and Place columns of the DataFrame as index
df = df.set_index(['Car', 'Place'])
# sorting
df.sort_index()
# groupby on multiindex datafram
res = df.groupby(level=['Car'])['UnitsSold'].mean()
print(res)
This will produce the following output −
Car Place Sold
0 BMW Delhi 95
1 Mercedes Hyderabad 80
2 Lamborgini Chandigarh 80
3 Audi Bangalore 75
4 Mercedes Hyderabad 90
5 Porsche Mumbai 90
6 RollsRoyce Mumbai 95
7 BMW Delhi 50
Car
Audi 75.8
BMW 72.5
Lamborgini 80.0
Mercedes 85.0
Porsche 90.0
RollsRoyce 95.0
Name: UnitsSold, dtype: float64
|
[
{
"code": null,
"e": 1185,
"s": 1062,
"text": "Multiindex Data Frame is a data frame with more than one index. Let’s say the following is our csv stored on the Desktop −"
},
{
"code": null,
"e": 1251,
"s": 1185,
"text": "At first, import the pandas library and read the above CSV file −"
},
{
"code": null,
"e": 1335,
"s": 1251,
"text": "import pandas as pd\n\ndf = pd.read_csv(\"C:/Users/amit_/Desktop/sales.csv\") print(df)"
},
{
"code": null,
"e": 1410,
"s": 1335,
"text": "We will form the ‘Car‘ and ‘Place‘ columns of the Dataframe as the index −"
},
{
"code": null,
"e": 1446,
"s": 1410,
"text": "df = df.set_index(['Car', 'Place'])"
},
{
"code": null,
"e": 1543,
"s": 1446,
"text": "The DataFrame is now a multi-indexed DataFrame having the ‘Car‘ and ‘Place‘ columns as an index."
},
{
"code": null,
"e": 1596,
"s": 1543,
"text": "Now, let us use groupby on the multiindex dataframe:"
},
{
"code": null,
"e": 1659,
"s": 1596,
"text": "res = df.groupby(level=['Car'])['UnitsSold'].mean() print(res)"
},
{
"code": null,
"e": 1683,
"s": 1659,
"text": "Following is the code −"
},
{
"code": null,
"e": 1982,
"s": 1683,
"text": "import pandas as pd\n\ndf = pd.read_csv(\"C:/Users/amit_/Desktop/sales.csv\")\nprint(df)\n\n# set Car and Place columns of the DataFrame as index\ndf = df.set_index(['Car', 'Place'])\n\n# sorting\ndf.sort_index()\n\n# groupby on multiindex datafram\nres = df.groupby(level=['Car'])['UnitsSold'].mean()\nprint(res)"
},
{
"code": null,
"e": 2023,
"s": 1982,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2506,
"s": 2023,
"text": " Car Place Sold\n0 BMW Delhi 95\n1 Mercedes Hyderabad 80\n2 Lamborgini Chandigarh 80\n3 Audi Bangalore 75\n4 Mercedes Hyderabad 90\n5 Porsche Mumbai 90\n6 RollsRoyce Mumbai 95\n7 BMW Delhi 50\nCar\nAudi 75.8\nBMW 72.5\nLamborgini 80.0\nMercedes 85.0\nPorsche 90.0\nRollsRoyce 95.0\nName: UnitsSold, dtype: float64"
}
] |
Java - Methods
|
A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console.
Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program design.
Considering the following example to explain the syntax of a method −
Syntax
public static int methodName(int a, int b) {
// body
}
Here,
public static − modifier
public static − modifier
int − return type
int − return type
methodName − name of the method
methodName − name of the method
a, b − formal parameters
a, b − formal parameters
int a, int b − list of parameters
int a, int b − list of parameters
Method definition consists of a method header and a method body. The same is shown in the following syntax −
Syntax
modifier returnType nameOfMethod (Parameter List) {
// method body
}
The syntax shown above includes −
modifier − It defines the access type of the method and it is optional to use.
modifier − It defines the access type of the method and it is optional to use.
returnType − Method may return a value.
returnType − Method may return a value.
nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.
nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.
Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.
Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.
method body − The method body defines what the method does with the statements.
method body − The method body defines what the method does with the statements.
Example
Here is the source code of the above defined method called min(). This method takes two parameters num1 and num2 and returns the maximum between the two −
/** the snippet returns the minimum between two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
For using a method, it should be called. There are two ways in which a method is called i.e., method returns a value or returning nothing (no return value).
The process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method. This called method then returns control to the caller in two conditions, when −
the return statement is executed.
it reaches the method ending closing brace.
The methods returning void is considered as call to a statement. Lets consider an example −
System.out.println("This is tutorialspoint.com!");
The method returning value can be understood by the following example −
int result = sum(6, 9);
Following is the example to demonstrate how to define a method and how to call it −
Example
public class ExampleMinNumber {
public static void main(String[] args) {
int a = 11;
int b = 6;
int c = minFunction(a, b);
System.out.println("Minimum Value = " + c);
}
/** returns the minimum of two numbers */
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
This will produce the following result −
Output
Minimum value = 6
The void keyword allows us to create methods which do not return a value. Here, in the following example we're considering a void method methodRankPoints. This method is a void method, which does not return any value. Call to a void method must be a statement i.e. methodRankPoints(255.7);. It is a Java statement which ends with a semicolon as shown in the following example.
Example
public class ExampleVoid {
public static void main(String[] args) {
methodRankPoints(255.7);
}
public static void methodRankPoints(double points) {
if (points >= 202.5) {
System.out.println("Rank:A1");
}else if (points >= 122.4) {
System.out.println("Rank:A2");
}else {
System.out.println("Rank:A3");
}
}
}
This will produce the following result −
Output
Rank:A1
While working under calling process, arguments is to be passed. These should be in the same order as their respective parameters in the method specification. Parameters can be passed by value or by reference.
Passing Parameters by Value means calling a method with a parameter. Through this, the argument value is passed to the parameter.
Example
The following program shows an example of passing parameter by value. The values of the arguments remains the same even after the method invocation.
public class swappingExample {
public static void main(String[] args) {
int a = 30;
int b = 45;
System.out.println("Before swapping, a = " + a + " and b = " + b);
// Invoke the swap method
swapFunction(a, b);
System.out.println("\n**Now, Before and After swapping values will be same here**:");
System.out.println("After swapping, a = " + a + " and b is " + b);
}
public static void swapFunction(int a, int b) {
System.out.println("Before swapping(Inside), a = " + a + " b = " + b);
// Swap n1 with n2
int c = a;
a = b;
b = c;
System.out.println("After swapping(Inside), a = " + a + " b = " + b);
}
}
This will produce the following result −
Output
Before swapping, a = 30 and b = 45
Before swapping(Inside), a = 30 b = 45
After swapping(Inside), a = 45 b = 30
**Now, Before and After swapping values will be same here**:
After swapping, a = 30 and b is 45
When a class has two or more methods by the same name but different parameters, it is known as method overloading. It is different from overriding. In overriding, a method has the same method name, type, number of parameters, etc.
Let’s consider the example discussed earlier for finding minimum numbers of integer type. If, let’s say we want to find the minimum number of double type. Then the concept of overloading will be introduced to create two or more methods with the same name but different parameters.
The following example explains the same −
Example
public class ExampleOverloading {
public static void main(String[] args) {
int a = 11;
int b = 6;
double c = 7.3;
double d = 9.4;
int result1 = minFunction(a, b);
// same function name with different parameters
double result2 = minFunction(c, d);
System.out.println("Minimum Value = " + result1);
System.out.println("Minimum Value = " + result2);
}
// for integer
public static int minFunction(int n1, int n2) {
int min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
// for double
public static double minFunction(double n1, double n2) {
double min;
if (n1 > n2)
min = n2;
else
min = n1;
return min;
}
}
This will produce the following result −
Output
Minimum Value = 6
Minimum Value = 7.3
Overloading methods makes program readable. Here, two methods are given by the same name but with different parameters. The minimum number from integer and double types is the result.
Sometimes you will want to pass some information into a program when you run it. This is accomplished by passing command-line arguments to main( ).
A command-line argument is the information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ).
Example
The following program displays all of the command-line arguments that it is called with −
public class CommandLine {
public static void main(String args[]) {
for(int i = 0; i<args.length; i++) {
System.out.println("args[" + i + "]: " + args[i]);
}
}
}
Try executing this program as shown here −
$java CommandLine this is a command line 200 -100
This will produce the following result −
Output
args[0]: this
args[1]: is
args[2]: a
args[3]: command
args[4]: line
args[5]: 200
args[6]: -100
this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.
Note − The keyword this is used only within instance methods or constructors
In general, the keyword this is used to −
Differentiate the instance variables from local variables if they have same names, within a constructor or a method.
Differentiate the instance variables from local variables if they have same names, within a constructor or a method.
class Student {
int age;
Student(int age) {
this.age = age;
}
}
Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.
Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.
class Student {
int age
Student() {
this(20);
}
Student(int age) {
this.age = age;
}
}
Example
Here is an example that uses this keyword to access the members of a class. Copy and paste the following program in a file with the name, This_Example.java.
public class This_Example {
// Instance variable num
int num = 10;
This_Example() {
System.out.println("This is an example program on keyword this");
}
This_Example(int num) {
// Invoking the default constructor
this();
// Assigning the local variable num to the instance variable num
this.num = num;
}
public void greet() {
System.out.println("Hi Welcome to Tutorialspoint");
}
public void print() {
// Local variable num
int num = 20;
// Printing the local variable
System.out.println("value of local variable num is : "+num);
// Printing the instance variable
System.out.println("value of instance variable num is : "+this.num);
// Invoking the greet method of a class
this.greet();
}
public static void main(String[] args) {
// Instantiating the class
This_Example obj1 = new This_Example();
// Invoking the print method
obj1.print();
// Passing a new value to the num variable through parametrized constructor
This_Example obj2 = new This_Example(30);
// Invoking the print method again
obj2.print();
}
}
This will produce the following result −
Output
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint
JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows −
typeName... parameterName
In the method declaration, you specify the type followed by an ellipsis (...). Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it.
Example
public class VarargsDemo {
public static void main(String args[]) {
// Call method with variable args
printMax(34, 3, 3, 2, 56.5);
printMax(new double[]{1, 2, 3});
}
public static void printMax( double... numbers) {
if (numbers.length == 0) {
System.out.println("No argument passed");
return;
}
double result = numbers[0];
for (int i = 1; i < numbers.length; i++)
if (numbers[i] > result)
result = numbers[i];
System.out.println("The max value is " + result);
}
}
This will produce the following result −
Output
The max value is 56.5
The max value is 3.0
It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.
For example, you might use finalize( ) to make sure that an open file owned by that object is closed.
To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that method whenever it is about to recycle an object of that class.
Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.
The finalize( ) method has this general form −
protected void finalize( ) {
// finalization code here
}
Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.
This means that you cannot know when or even if finalize( ) will be executed. For example, if your program ends before garbage collection occurs, finalize( ) will not execute.
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": 2626,
"s": 2377,
"text": "A Java method is a collection of statements that are grouped together to perform an operation. When you call the System.out.println() method, for example, the system actually executes several statements in order to display a message on the console."
},
{
"code": null,
"e": 2803,
"s": 2626,
"text": "Now you will learn how to create your own methods with or without return values, invoke a method with or without parameters, and apply method abstraction in the program design."
},
{
"code": null,
"e": 2873,
"s": 2803,
"text": "Considering the following example to explain the syntax of a method −"
},
{
"code": null,
"e": 2880,
"s": 2873,
"text": "Syntax"
},
{
"code": null,
"e": 2939,
"s": 2880,
"text": "public static int methodName(int a, int b) {\n // body\n}\n"
},
{
"code": null,
"e": 2945,
"s": 2939,
"text": "Here,"
},
{
"code": null,
"e": 2970,
"s": 2945,
"text": "public static − modifier"
},
{
"code": null,
"e": 2995,
"s": 2970,
"text": "public static − modifier"
},
{
"code": null,
"e": 3013,
"s": 2995,
"text": "int − return type"
},
{
"code": null,
"e": 3031,
"s": 3013,
"text": "int − return type"
},
{
"code": null,
"e": 3063,
"s": 3031,
"text": "methodName − name of the method"
},
{
"code": null,
"e": 3095,
"s": 3063,
"text": "methodName − name of the method"
},
{
"code": null,
"e": 3120,
"s": 3095,
"text": "a, b − formal parameters"
},
{
"code": null,
"e": 3145,
"s": 3120,
"text": "a, b − formal parameters"
},
{
"code": null,
"e": 3179,
"s": 3145,
"text": "int a, int b − list of parameters"
},
{
"code": null,
"e": 3213,
"s": 3179,
"text": "int a, int b − list of parameters"
},
{
"code": null,
"e": 3322,
"s": 3213,
"text": "Method definition consists of a method header and a method body. The same is shown in the following syntax −"
},
{
"code": null,
"e": 3329,
"s": 3322,
"text": "Syntax"
},
{
"code": null,
"e": 3402,
"s": 3329,
"text": "modifier returnType nameOfMethod (Parameter List) {\n // method body\n}\n"
},
{
"code": null,
"e": 3436,
"s": 3402,
"text": "The syntax shown above includes −"
},
{
"code": null,
"e": 3515,
"s": 3436,
"text": "modifier − It defines the access type of the method and it is optional to use."
},
{
"code": null,
"e": 3594,
"s": 3515,
"text": "modifier − It defines the access type of the method and it is optional to use."
},
{
"code": null,
"e": 3634,
"s": 3594,
"text": "returnType − Method may return a value."
},
{
"code": null,
"e": 3674,
"s": 3634,
"text": "returnType − Method may return a value."
},
{
"code": null,
"e": 3787,
"s": 3674,
"text": "nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list."
},
{
"code": null,
"e": 3900,
"s": 3787,
"text": "nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list."
},
{
"code": null,
"e": 4058,
"s": 3900,
"text": "Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters."
},
{
"code": null,
"e": 4216,
"s": 4058,
"text": "Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters."
},
{
"code": null,
"e": 4296,
"s": 4216,
"text": "method body − The method body defines what the method does with the statements."
},
{
"code": null,
"e": 4376,
"s": 4296,
"text": "method body − The method body defines what the method does with the statements."
},
{
"code": null,
"e": 4384,
"s": 4376,
"text": "Example"
},
{
"code": null,
"e": 4540,
"s": 4384,
"text": "Here is the source code of the above defined method called min(). This method takes two parameters num1 and num2 and returns the maximum between the two −"
},
{
"code": null,
"e": 4735,
"s": 4540,
"text": "/** the snippet returns the minimum between two numbers */\n\npublic static int minFunction(int n1, int n2) {\n int min;\n if (n1 > n2)\n min = n2;\n else\n min = n1;\n\n return min; \n}"
},
{
"code": null,
"e": 4892,
"s": 4735,
"text": "For using a method, it should be called. There are two ways in which a method is called i.e., method returns a value or returning nothing (no return value)."
},
{
"code": null,
"e": 5105,
"s": 4892,
"text": "The process of method calling is simple. When a program invokes a method, the program control gets transferred to the called method. This called method then returns control to the caller in two conditions, when −"
},
{
"code": null,
"e": 5139,
"s": 5105,
"text": "the return statement is executed."
},
{
"code": null,
"e": 5183,
"s": 5139,
"text": "it reaches the method ending closing brace."
},
{
"code": null,
"e": 5275,
"s": 5183,
"text": "The methods returning void is considered as call to a statement. Lets consider an example −"
},
{
"code": null,
"e": 5326,
"s": 5275,
"text": "System.out.println(\"This is tutorialspoint.com!\");"
},
{
"code": null,
"e": 5398,
"s": 5326,
"text": "The method returning value can be understood by the following example −"
},
{
"code": null,
"e": 5422,
"s": 5398,
"text": "int result = sum(6, 9);"
},
{
"code": null,
"e": 5506,
"s": 5422,
"text": "Following is the example to demonstrate how to define a method and how to call it −"
},
{
"code": null,
"e": 5514,
"s": 5506,
"text": "Example"
},
{
"code": null,
"e": 5924,
"s": 5514,
"text": "public class ExampleMinNumber {\n \n public static void main(String[] args) {\n int a = 11;\n int b = 6;\n int c = minFunction(a, b);\n System.out.println(\"Minimum Value = \" + c);\n }\n\n /** returns the minimum of two numbers */\n public static int minFunction(int n1, int n2) {\n int min;\n if (n1 > n2)\n min = n2;\n else\n min = n1;\n\n return min; \n }\n}"
},
{
"code": null,
"e": 5965,
"s": 5924,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 5972,
"s": 5965,
"text": "Output"
},
{
"code": null,
"e": 5991,
"s": 5972,
"text": "Minimum value = 6\n"
},
{
"code": null,
"e": 6368,
"s": 5991,
"text": "The void keyword allows us to create methods which do not return a value. Here, in the following example we're considering a void method methodRankPoints. This method is a void method, which does not return any value. Call to a void method must be a statement i.e. methodRankPoints(255.7);. It is a Java statement which ends with a semicolon as shown in the following example."
},
{
"code": null,
"e": 6376,
"s": 6368,
"text": "Example"
},
{
"code": null,
"e": 6754,
"s": 6376,
"text": "public class ExampleVoid {\n\n public static void main(String[] args) {\n methodRankPoints(255.7);\n }\n\n public static void methodRankPoints(double points) {\n if (points >= 202.5) {\n System.out.println(\"Rank:A1\");\n }else if (points >= 122.4) {\n System.out.println(\"Rank:A2\");\n }else {\n System.out.println(\"Rank:A3\");\n }\n }\n}"
},
{
"code": null,
"e": 6795,
"s": 6754,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 6802,
"s": 6795,
"text": "Output"
},
{
"code": null,
"e": 6811,
"s": 6802,
"text": "Rank:A1\n"
},
{
"code": null,
"e": 7020,
"s": 6811,
"text": "While working under calling process, arguments is to be passed. These should be in the same order as their respective parameters in the method specification. Parameters can be passed by value or by reference."
},
{
"code": null,
"e": 7150,
"s": 7020,
"text": "Passing Parameters by Value means calling a method with a parameter. Through this, the argument value is passed to the parameter."
},
{
"code": null,
"e": 7158,
"s": 7150,
"text": "Example"
},
{
"code": null,
"e": 7307,
"s": 7158,
"text": "The following program shows an example of passing parameter by value. The values of the arguments remains the same even after the method invocation."
},
{
"code": null,
"e": 8008,
"s": 7307,
"text": "public class swappingExample {\n\n public static void main(String[] args) {\n int a = 30;\n int b = 45;\n System.out.println(\"Before swapping, a = \" + a + \" and b = \" + b);\n\n // Invoke the swap method\n swapFunction(a, b);\n System.out.println(\"\\n**Now, Before and After swapping values will be same here**:\");\n System.out.println(\"After swapping, a = \" + a + \" and b is \" + b);\n }\n\n public static void swapFunction(int a, int b) {\n System.out.println(\"Before swapping(Inside), a = \" + a + \" b = \" + b);\n \n // Swap n1 with n2\n int c = a;\n a = b;\n b = c;\n System.out.println(\"After swapping(Inside), a = \" + a + \" b = \" + b);\n }\n}"
},
{
"code": null,
"e": 8049,
"s": 8008,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 8056,
"s": 8049,
"text": "Output"
},
{
"code": null,
"e": 8266,
"s": 8056,
"text": "Before swapping, a = 30 and b = 45\nBefore swapping(Inside), a = 30 b = 45\nAfter swapping(Inside), a = 45 b = 30\n\n**Now, Before and After swapping values will be same here**:\nAfter swapping, a = 30 and b is 45\n"
},
{
"code": null,
"e": 8497,
"s": 8266,
"text": "When a class has two or more methods by the same name but different parameters, it is known as method overloading. It is different from overriding. In overriding, a method has the same method name, type, number of parameters, etc."
},
{
"code": null,
"e": 8778,
"s": 8497,
"text": "Let’s consider the example discussed earlier for finding minimum numbers of integer type. If, let’s say we want to find the minimum number of double type. Then the concept of overloading will be introduced to create two or more methods with the same name but different parameters."
},
{
"code": null,
"e": 8820,
"s": 8778,
"text": "The following example explains the same −"
},
{
"code": null,
"e": 8828,
"s": 8820,
"text": "Example"
},
{
"code": null,
"e": 9616,
"s": 8828,
"text": "public class ExampleOverloading {\n\n public static void main(String[] args) {\n int a = 11;\n int b = 6;\n double c = 7.3;\n double d = 9.4;\n int result1 = minFunction(a, b);\n \n // same function name with different parameters\n double result2 = minFunction(c, d);\n System.out.println(\"Minimum Value = \" + result1);\n System.out.println(\"Minimum Value = \" + result2);\n }\n\n // for integer\n public static int minFunction(int n1, int n2) {\n int min;\n if (n1 > n2)\n min = n2;\n else\n min = n1;\n\n return min; \n }\n \n // for double\n public static double minFunction(double n1, double n2) {\n double min;\n if (n1 > n2)\n min = n2;\n else\n min = n1;\n\n return min; \n }\n}"
},
{
"code": null,
"e": 9657,
"s": 9616,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 9664,
"s": 9657,
"text": "Output"
},
{
"code": null,
"e": 9703,
"s": 9664,
"text": "Minimum Value = 6\nMinimum Value = 7.3\n"
},
{
"code": null,
"e": 9887,
"s": 9703,
"text": "Overloading methods makes program readable. Here, two methods are given by the same name but with different parameters. The minimum number from integer and double types is the result."
},
{
"code": null,
"e": 10035,
"s": 9887,
"text": "Sometimes you will want to pass some information into a program when you run it. This is accomplished by passing command-line arguments to main( )."
},
{
"code": null,
"e": 10300,
"s": 10035,
"text": "A command-line argument is the information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( )."
},
{
"code": null,
"e": 10308,
"s": 10300,
"text": "Example"
},
{
"code": null,
"e": 10398,
"s": 10308,
"text": "The following program displays all of the command-line arguments that it is called with −"
},
{
"code": null,
"e": 10590,
"s": 10398,
"text": "public class CommandLine {\n\n public static void main(String args[]) { \n for(int i = 0; i<args.length; i++) {\n System.out.println(\"args[\" + i + \"]: \" + args[i]);\n }\n }\n}"
},
{
"code": null,
"e": 10633,
"s": 10590,
"text": "Try executing this program as shown here −"
},
{
"code": null,
"e": 10684,
"s": 10633,
"text": "$java CommandLine this is a command line 200 -100\n"
},
{
"code": null,
"e": 10725,
"s": 10684,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 10732,
"s": 10725,
"text": "Output"
},
{
"code": null,
"e": 10828,
"s": 10732,
"text": "args[0]: this\nargs[1]: is\nargs[2]: a\nargs[3]: command\nargs[4]: line\nargs[5]: 200\nargs[6]: -100\n"
},
{
"code": null,
"e": 11057,
"s": 10828,
"text": "this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods."
},
{
"code": null,
"e": 11134,
"s": 11057,
"text": "Note − The keyword this is used only within instance methods or constructors"
},
{
"code": null,
"e": 11176,
"s": 11134,
"text": "In general, the keyword this is used to −"
},
{
"code": null,
"e": 11293,
"s": 11176,
"text": "Differentiate the instance variables from local variables if they have same names, within a constructor or a method."
},
{
"code": null,
"e": 11410,
"s": 11293,
"text": "Differentiate the instance variables from local variables if they have same names, within a constructor or a method."
},
{
"code": null,
"e": 11493,
"s": 11410,
"text": "class Student {\n int age; \n Student(int age) {\n this.age = age;\t\n }\n}"
},
{
"code": null,
"e": 11631,
"s": 11493,
"text": "Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation."
},
{
"code": null,
"e": 11769,
"s": 11631,
"text": "Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation."
},
{
"code": null,
"e": 11888,
"s": 11769,
"text": "class Student {\n int age\n Student() {\n this(20);\n }\n \n Student(int age) {\n this.age = age;\t\n }\n}"
},
{
"code": null,
"e": 11896,
"s": 11888,
"text": "Example"
},
{
"code": null,
"e": 12053,
"s": 11896,
"text": "Here is an example that uses this keyword to access the members of a class. Copy and paste the following program in a file with the name, This_Example.java."
},
{
"code": null,
"e": 13306,
"s": 12053,
"text": "public class This_Example {\n // Instance variable num\n int num = 10;\n\t\n This_Example() {\n System.out.println(\"This is an example program on keyword this\");\t\n }\n\n This_Example(int num) {\n // Invoking the default constructor\n this();\n \n // Assigning the local variable num to the instance variable num\n this.num = num;\t \n }\n \n public void greet() {\n System.out.println(\"Hi Welcome to Tutorialspoint\");\n }\n \n public void print() {\n // Local variable num\n int num = 20;\n \n // Printing the local variable\n System.out.println(\"value of local variable num is : \"+num);\n \n // Printing the instance variable\n System.out.println(\"value of instance variable num is : \"+this.num);\n \n // Invoking the greet method of a class\n this.greet(); \n }\n \n public static void main(String[] args) {\n // Instantiating the class\n This_Example obj1 = new This_Example();\n \n // Invoking the print method\n obj1.print();\n\t \n // Passing a new value to the num variable through parametrized constructor\n This_Example obj2 = new This_Example(30);\n \n // Invoking the print method again\n obj2.print(); \n }\n}"
},
{
"code": null,
"e": 13347,
"s": 13306,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 13354,
"s": 13347,
"text": "Output"
},
{
"code": null,
"e": 13651,
"s": 13354,
"text": "This is an example program on keyword this \nvalue of local variable num is : 20\nvalue of instance variable num is : 10\nHi Welcome to Tutorialspoint\nThis is an example program on keyword this \nvalue of local variable num is : 20\nvalue of instance variable num is : 30\nHi Welcome to Tutorialspoint\n"
},
{
"code": null,
"e": 13793,
"s": 13651,
"text": "JDK 1.5 enables you to pass a variable number of arguments of the same type to a method. The parameter in the method is declared as follows −"
},
{
"code": null,
"e": 13820,
"s": 13793,
"text": "typeName... parameterName\n"
},
{
"code": null,
"e": 14051,
"s": 13820,
"text": "In the method declaration, you specify the type followed by an ellipsis (...). Only one variable-length parameter may be specified in a method, and this parameter must be the last parameter. Any regular parameters must precede it."
},
{
"code": null,
"e": 14059,
"s": 14051,
"text": "Example"
},
{
"code": null,
"e": 14619,
"s": 14059,
"text": "public class VarargsDemo {\n\n public static void main(String args[]) {\n // Call method with variable args \n\t printMax(34, 3, 3, 2, 56.5);\n printMax(new double[]{1, 2, 3});\n }\n\n public static void printMax( double... numbers) {\n if (numbers.length == 0) {\n System.out.println(\"No argument passed\");\n return;\n }\n\n double result = numbers[0];\n\n for (int i = 1; i < numbers.length; i++)\n if (numbers[i] > result)\n result = numbers[i];\n System.out.println(\"The max value is \" + result);\n }\n}"
},
{
"code": null,
"e": 14660,
"s": 14619,
"text": "This will produce the following result −"
},
{
"code": null,
"e": 14667,
"s": 14660,
"text": "Output"
},
{
"code": null,
"e": 14711,
"s": 14667,
"text": "The max value is 56.5\nThe max value is 3.0\n"
},
{
"code": null,
"e": 14932,
"s": 14711,
"text": "It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly."
},
{
"code": null,
"e": 15034,
"s": 14932,
"text": "For example, you might use finalize( ) to make sure that an open file owned by that object is closed."
},
{
"code": null,
"e": 15199,
"s": 15034,
"text": "To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that method whenever it is about to recycle an object of that class."
},
{
"code": null,
"e": 15315,
"s": 15199,
"text": "Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed."
},
{
"code": null,
"e": 15362,
"s": 15315,
"text": "The finalize( ) method has this general form −"
},
{
"code": null,
"e": 15423,
"s": 15362,
"text": "protected void finalize( ) {\n // finalization code here\n}\n"
},
{
"code": null,
"e": 15537,
"s": 15423,
"text": "Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class."
},
{
"code": null,
"e": 15713,
"s": 15537,
"text": "This means that you cannot know when or even if finalize( ) will be executed. For example, if your program ends before garbage collection occurs, finalize( ) will not execute."
},
{
"code": null,
"e": 15746,
"s": 15713,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 15762,
"s": 15746,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 15795,
"s": 15762,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 15811,
"s": 15795,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 15846,
"s": 15811,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 15860,
"s": 15846,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 15894,
"s": 15860,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 15908,
"s": 15894,
"text": " Tushar Kale"
},
{
"code": null,
"e": 15945,
"s": 15908,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 15960,
"s": 15945,
"text": " Monica Mittal"
},
{
"code": null,
"e": 15993,
"s": 15960,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 16012,
"s": 15993,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 16019,
"s": 16012,
"text": " Print"
},
{
"code": null,
"e": 16030,
"s": 16019,
"text": " Add Notes"
}
] |
PHP | array_chunk() Function
|
09 Aug, 2019
The array_chunk() function is an inbuilt function in PHP which is used to split an array into parts or chunks of given size depending upon the parameters passed to the function. The last chunk may contain fewer elements than the desired size of the chunk.
Syntax:
array array_chunk( $array, $size, $preserve_keys )
Parameters: This function accepts three parameters as shown in the above syntax. The parameters are described below:
$array: This parameter represents the array that is needed to be divided into chunks.
$size: This parameter is an integer which defines the size of the chunks to be created.
$preserve_keys: This parameter takes Boolean value. When this parameter is set to TRUE then the keys are preserved, otherwise the chunk is reindexed starting from 0.
Return value: This function returns a multidimensional array indexed starting from 0. Each chunk contains $size number of elements, except the last chunk which may contain lesser number of elements.
Examples:
Input : $input_array = array('a', 'b', 'c', 'd', 'e');
array_chunk($input_array, 2);
Output : Array(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)
Input : $input_array = array('a', 'b', 'c', 'd', 'e');
array_chunk($input_array, 2, true)
Output : Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[2] => c
[3] => d
)
[2] => Array
(
[4] => e
)
)
In the first example a multidimensional array is returned in which each chunk contains 2 elements. In the second example, since the third argument is passed as true therefore the index of elements in each chunk is the same as their index in the original array from which the chunk is created. In this case, each chunk contains 2 elements which are the value of size passed to the function.
Below programs illustrate the array_chunk() function in PHP:
Program 1:
<?php $input_array = array('a', 'b', 'c', 'd', 'e'); print_r(array_chunk($input_array, 2)); ?>
Output:
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[0] => c
[1] => d
)
[2] => Array
(
[0] => e
)
)
Program 2:
<?php $input_array = array('a', 'b', 'c', 'd', 'e'); print_r(array_chunk($input_array, 2, true)); ?>
Output:
Array
(
[0] => Array
(
[0] => a
[1] => b
)
[1] => Array
(
[2] => c
[3] => d
)
[2] => Array
(
[4] => e
)
)
Reference: http://php.net/manual/en/function.array-chunk.php
PHP-array
PHP-function
PHP
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 ?
PHP in_array() Function
How to delete an array element based on key in PHP?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
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": 53,
"s": 25,
"text": "\n09 Aug, 2019"
},
{
"code": null,
"e": 309,
"s": 53,
"text": "The array_chunk() function is an inbuilt function in PHP which is used to split an array into parts or chunks of given size depending upon the parameters passed to the function. The last chunk may contain fewer elements than the desired size of the chunk."
},
{
"code": null,
"e": 317,
"s": 309,
"text": "Syntax:"
},
{
"code": null,
"e": 369,
"s": 317,
"text": "array array_chunk( $array, $size, $preserve_keys )\n"
},
{
"code": null,
"e": 486,
"s": 369,
"text": "Parameters: This function accepts three parameters as shown in the above syntax. The parameters are described below:"
},
{
"code": null,
"e": 572,
"s": 486,
"text": "$array: This parameter represents the array that is needed to be divided into chunks."
},
{
"code": null,
"e": 660,
"s": 572,
"text": "$size: This parameter is an integer which defines the size of the chunks to be created."
},
{
"code": null,
"e": 826,
"s": 660,
"text": "$preserve_keys: This parameter takes Boolean value. When this parameter is set to TRUE then the keys are preserved, otherwise the chunk is reindexed starting from 0."
},
{
"code": null,
"e": 1025,
"s": 826,
"text": "Return value: This function returns a multidimensional array indexed starting from 0. Each chunk contains $size number of elements, except the last chunk which may contain lesser number of elements."
},
{
"code": null,
"e": 1035,
"s": 1025,
"text": "Examples:"
},
{
"code": null,
"e": 1986,
"s": 1035,
"text": "Input : $input_array = array('a', 'b', 'c', 'd', 'e');\n array_chunk($input_array, 2);\nOutput : Array(\n [0] => Array\n (\n [0] => a\n [1] => b\n )\n [1] => Array\n (\n [0] => c\n [1] => d\n )\n [2] => Array\n (\n [0] => e\n )\n )\n\nInput : $input_array = array('a', 'b', 'c', 'd', 'e');\n array_chunk($input_array, 2, true)\nOutput : Array\n (\n [0] => Array\n (\n [0] => a\n [1] => b\n )\n [1] => Array\n (\n [2] => c\n [3] => d\n )\n [2] => Array\n (\n [4] => e\n )\n ) \n"
},
{
"code": null,
"e": 2376,
"s": 1986,
"text": "In the first example a multidimensional array is returned in which each chunk contains 2 elements. In the second example, since the third argument is passed as true therefore the index of elements in each chunk is the same as their index in the original array from which the chunk is created. In this case, each chunk contains 2 elements which are the value of size passed to the function."
},
{
"code": null,
"e": 2437,
"s": 2376,
"text": "Below programs illustrate the array_chunk() function in PHP:"
},
{
"code": null,
"e": 2448,
"s": 2437,
"text": "Program 1:"
},
{
"code": "<?php $input_array = array('a', 'b', 'c', 'd', 'e'); print_r(array_chunk($input_array, 2)); ?>",
"e": 2546,
"s": 2448,
"text": null
},
{
"code": null,
"e": 2554,
"s": 2546,
"text": "Output:"
},
{
"code": null,
"e": 2780,
"s": 2554,
"text": "Array\n(\n [0] => Array\n (\n [0] => a\n [1] => b\n )\n [1] => Array\n (\n [0] => c\n [1] => d\n )\n [2] => Array\n (\n [0] => e\n )\n)"
},
{
"code": null,
"e": 2791,
"s": 2780,
"text": "Program 2:"
},
{
"code": "<?php $input_array = array('a', 'b', 'c', 'd', 'e'); print_r(array_chunk($input_array, 2, true)); ?>",
"e": 2895,
"s": 2791,
"text": null
},
{
"code": null,
"e": 2903,
"s": 2895,
"text": "Output:"
},
{
"code": null,
"e": 3129,
"s": 2903,
"text": "Array\n(\n [0] => Array\n (\n [0] => a\n [1] => b\n )\n [1] => Array\n (\n [2] => c\n [3] => d\n )\n [2] => Array\n (\n [4] => e\n )\n)"
},
{
"code": null,
"e": 3190,
"s": 3129,
"text": "Reference: http://php.net/manual/en/function.array-chunk.php"
},
{
"code": null,
"e": 3200,
"s": 3190,
"text": "PHP-array"
},
{
"code": null,
"e": 3213,
"s": 3200,
"text": "PHP-function"
},
{
"code": null,
"e": 3217,
"s": 3213,
"text": "PHP"
},
{
"code": null,
"e": 3234,
"s": 3217,
"text": "Web Technologies"
},
{
"code": null,
"e": 3238,
"s": 3234,
"text": "PHP"
},
{
"code": null,
"e": 3336,
"s": 3238,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3381,
"s": 3336,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 3405,
"s": 3381,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 3457,
"s": 3405,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 3507,
"s": 3457,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 3547,
"s": 3507,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3580,
"s": 3547,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3642,
"s": 3580,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3703,
"s": 3642,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3753,
"s": 3703,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Find the last two missing digits of the given phone number
|
08 Mar, 2022
Given eight digits of a phone number as an integer N, the task is to find the missing last two digits and print the complete number when the last two digits are the sum of given eight digits.Examples:
Input: N = 98765432 Output: 9876543244Input: N = 10000000 Output: 1000000001
Approach:
Get the eight digits of the phone number from N one by one using the Modulo 10 operator (%10).
Add these digits in a variable say sum to get the sum of the eight digits.
Now, there are two cases: If sum < 10 then it is a single digit i.e. insert 0 in the beginning to make it a two digit number without affecting the value.Else sum is the number represented by the last two digits.
If sum < 10 then it is a single digit i.e. insert 0 in the beginning to make it a two digit number without affecting the value.
Else sum is the number represented by the last two digits.
Below is the implementation of the above approach:
C++
Java
Python 3
C#
Javascript
// C++ implementation of the approach #include <iostream>using namespace std; // Function to find the last two// digits of the number and// print the complete numbervoid findPhoneNumber(int n){ int temp = n; int sum; // Sum of the first eight // digits of the number while (temp != 0) { sum += temp % 10; temp = temp / 10; } // if sum < 10, then the two digits // are '0' and the value of sum if (sum < 10) cout << n << "0" << sum; // if sum > 10, then the two digits // are the value of sum else cout << n << sum;} // Driver codeint main(){ long int n = 98765432; findPhoneNumber(n); return 0;}
// Java implementation of the approachclass GFG{ // Function to find the last two// digits of the number and// print the complete numberstatic void findPhoneNumber(int n){ int temp = n; int sum = 0; // Sum of the first eight // digits of the number while (temp != 0) { sum += temp % 10; temp = temp / 10; } // if sum < 10, then the two digits // are '0' and the value of sum if (sum < 10) System.out.print(n + "0" + sum); // if sum > 10, then the two digits // are the value of sum else System.out.print(n +""+ sum);} // Driver codepublic static void main(String[] args){ int n = 98765432; findPhoneNumber(n);}} // This code is contributed by PrinciRaj1992
# Python 3 implementation of the approach # Function to find the last two# digits of the number and# print the complete numberdef findPhoneNumber(n): temp = n sum = 0 # Sum of the first eight # digits of the number while (temp != 0): sum += temp % 10 temp = temp // 10 # if sum < 10, then the two digits # are '0' and the value of sum if (sum < 10): print(n,"0",sum) # if sum > 10, then the two digits # are the value of sum else: n = str(n) sum = str(sum) n += sum print(n) # Driver codeif __name__ == '__main__': n = 98765432 findPhoneNumber(n) # This code is contributed by Surendra_Gangwar
// C# implementation of the approachusing System; class GFG{ // Function to find the last two// digits of the number and// print the complete numberstatic void findPhoneNumber(int n){ int temp = n; int sum = 0; // Sum of the first eight // digits of the number while (temp != 0) { sum += temp % 10; temp = temp / 10; } // if sum < 10, then the two digits // are '0' and the value of sum if (sum < 10) Console.Write(n + "0" + sum); // if sum > 10, then the two digits // are the value of sum else Console.Write(n + "" + sum);} // Driver codestatic public void Main (){ int n = 98765432; findPhoneNumber(n);}} // This code is contributed by jit_t
<script> // Javascript implementation of the approach // Function to find the last two// digits of the number and// print the complete numberfunction findPhoneNumber(n){ let temp = n; let sum=0; // Sum of the first eight // digits of the number while (temp != 0) { sum += temp % 10; temp = Math.floor(temp / 10); } // if sum < 10, then the two digits // are '0' and the value of sum if (sum < 10) document.write(n + "0" + sum); // if sum > 10, then the two digits // are the value of sum else document.write(n + "" + sum);} // Driver code let n = 98765432; findPhoneNumber(n); // This code is contributed by Mayank Tyagi </script>
9876543244
Time Complexity: O(log10n)
Auxiliary Space: O(1)
_saitama
SURENDRA_GANGWAR
princiraj1992
jit_t
mayanktyagi1709
subhammahato348
Mathematical
School Programming
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Algorithm to solve Rubik's Cube
Program to print prime numbers from 1 to N.
Merge two sorted arrays with O(1) extra space
Segment Tree | Set 1 (Sum of given range)
Fizz Buzz Implementation
Python Dictionary
Reverse a string in Java
Arrays in C/C++
Introduction To PYTHON
Interfaces in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Mar, 2022"
},
{
"code": null,
"e": 231,
"s": 28,
"text": "Given eight digits of a phone number as an integer N, the task is to find the missing last two digits and print the complete number when the last two digits are the sum of given eight digits.Examples: "
},
{
"code": null,
"e": 310,
"s": 231,
"text": "Input: N = 98765432 Output: 9876543244Input: N = 10000000 Output: 1000000001 "
},
{
"code": null,
"e": 324,
"s": 312,
"text": "Approach: "
},
{
"code": null,
"e": 419,
"s": 324,
"text": "Get the eight digits of the phone number from N one by one using the Modulo 10 operator (%10)."
},
{
"code": null,
"e": 494,
"s": 419,
"text": "Add these digits in a variable say sum to get the sum of the eight digits."
},
{
"code": null,
"e": 706,
"s": 494,
"text": "Now, there are two cases: If sum < 10 then it is a single digit i.e. insert 0 in the beginning to make it a two digit number without affecting the value.Else sum is the number represented by the last two digits."
},
{
"code": null,
"e": 834,
"s": 706,
"text": "If sum < 10 then it is a single digit i.e. insert 0 in the beginning to make it a two digit number without affecting the value."
},
{
"code": null,
"e": 893,
"s": 834,
"text": "Else sum is the number represented by the last two digits."
},
{
"code": null,
"e": 946,
"s": 893,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 950,
"s": 946,
"text": "C++"
},
{
"code": null,
"e": 955,
"s": 950,
"text": "Java"
},
{
"code": null,
"e": 964,
"s": 955,
"text": "Python 3"
},
{
"code": null,
"e": 967,
"s": 964,
"text": "C#"
},
{
"code": null,
"e": 978,
"s": 967,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach #include <iostream>using namespace std; // Function to find the last two// digits of the number and// print the complete numbervoid findPhoneNumber(int n){ int temp = n; int sum; // Sum of the first eight // digits of the number while (temp != 0) { sum += temp % 10; temp = temp / 10; } // if sum < 10, then the two digits // are '0' and the value of sum if (sum < 10) cout << n << \"0\" << sum; // if sum > 10, then the two digits // are the value of sum else cout << n << sum;} // Driver codeint main(){ long int n = 98765432; findPhoneNumber(n); return 0;}",
"e": 1653,
"s": 978,
"text": null
},
{
"code": "// Java implementation of the approachclass GFG{ // Function to find the last two// digits of the number and// print the complete numberstatic void findPhoneNumber(int n){ int temp = n; int sum = 0; // Sum of the first eight // digits of the number while (temp != 0) { sum += temp % 10; temp = temp / 10; } // if sum < 10, then the two digits // are '0' and the value of sum if (sum < 10) System.out.print(n + \"0\" + sum); // if sum > 10, then the two digits // are the value of sum else System.out.print(n +\"\"+ sum);} // Driver codepublic static void main(String[] args){ int n = 98765432; findPhoneNumber(n);}} // This code is contributed by PrinciRaj1992",
"e": 2388,
"s": 1653,
"text": null
},
{
"code": "# Python 3 implementation of the approach # Function to find the last two# digits of the number and# print the complete numberdef findPhoneNumber(n): temp = n sum = 0 # Sum of the first eight # digits of the number while (temp != 0): sum += temp % 10 temp = temp // 10 # if sum < 10, then the two digits # are '0' and the value of sum if (sum < 10): print(n,\"0\",sum) # if sum > 10, then the two digits # are the value of sum else: n = str(n) sum = str(sum) n += sum print(n) # Driver codeif __name__ == '__main__': n = 98765432 findPhoneNumber(n) # This code is contributed by Surendra_Gangwar",
"e": 3074,
"s": 2388,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Function to find the last two// digits of the number and// print the complete numberstatic void findPhoneNumber(int n){ int temp = n; int sum = 0; // Sum of the first eight // digits of the number while (temp != 0) { sum += temp % 10; temp = temp / 10; } // if sum < 10, then the two digits // are '0' and the value of sum if (sum < 10) Console.Write(n + \"0\" + sum); // if sum > 10, then the two digits // are the value of sum else Console.Write(n + \"\" + sum);} // Driver codestatic public void Main (){ int n = 98765432; findPhoneNumber(n);}} // This code is contributed by jit_t",
"e": 3800,
"s": 3074,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to find the last two// digits of the number and// print the complete numberfunction findPhoneNumber(n){ let temp = n; let sum=0; // Sum of the first eight // digits of the number while (temp != 0) { sum += temp % 10; temp = Math.floor(temp / 10); } // if sum < 10, then the two digits // are '0' and the value of sum if (sum < 10) document.write(n + \"0\" + sum); // if sum > 10, then the two digits // are the value of sum else document.write(n + \"\" + sum);} // Driver code let n = 98765432; findPhoneNumber(n); // This code is contributed by Mayank Tyagi </script>",
"e": 4507,
"s": 3800,
"text": null
},
{
"code": null,
"e": 4518,
"s": 4507,
"text": "9876543244"
},
{
"code": null,
"e": 4547,
"s": 4520,
"text": "Time Complexity: O(log10n)"
},
{
"code": null,
"e": 4569,
"s": 4547,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 4578,
"s": 4569,
"text": "_saitama"
},
{
"code": null,
"e": 4595,
"s": 4578,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 4609,
"s": 4595,
"text": "princiraj1992"
},
{
"code": null,
"e": 4615,
"s": 4609,
"text": "jit_t"
},
{
"code": null,
"e": 4631,
"s": 4615,
"text": "mayanktyagi1709"
},
{
"code": null,
"e": 4647,
"s": 4631,
"text": "subhammahato348"
},
{
"code": null,
"e": 4660,
"s": 4647,
"text": "Mathematical"
},
{
"code": null,
"e": 4679,
"s": 4660,
"text": "School Programming"
},
{
"code": null,
"e": 4687,
"s": 4679,
"text": "Strings"
},
{
"code": null,
"e": 4695,
"s": 4687,
"text": "Strings"
},
{
"code": null,
"e": 4708,
"s": 4695,
"text": "Mathematical"
},
{
"code": null,
"e": 4806,
"s": 4708,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4838,
"s": 4806,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 4882,
"s": 4838,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 4928,
"s": 4882,
"text": "Merge two sorted arrays with O(1) extra space"
},
{
"code": null,
"e": 4970,
"s": 4928,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 4995,
"s": 4970,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 5013,
"s": 4995,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5038,
"s": 5013,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 5054,
"s": 5038,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 5077,
"s": 5054,
"text": "Introduction To PYTHON"
}
] |
Python – How to Iterate over nested dictionary ?
|
10 Oct, 2021
In this article, we will discuss how to iterate over a nested dictionary in Python.
Nested dictionary means dictionary inside a dictionary and we are going to see every possible way of iterating over such a data structure.
Nested dictionary in use:
{‘Student 1’: {‘Name’: ‘Bobby’, ‘Id’: 1, ‘Age’: 20},
‘Student 2’: {‘Name’: ‘ojaswi’, ‘Id’: 2, ‘Age’: 22},
‘Student 3’: {‘Name’: ‘rohith’, ‘Id’: 3, ‘Age’: 20}}
For this we will use for loop to iterate through a dictionary to get the all the key , values of nested dictionaries.
Syntax:
for i in dictionary_name:
print(dictionary_name[i])
where
dictionary_name is the input dictionary
dictionary_name[i] is the value to get dictionaries
Example: Python program to get the nested dictionaries from a dictionary
Python3
# create a nested dictionary with 3 # fields of 3 studentsdata = { 'Student 1': {'Name': 'Bobby', 'Id': 1, "Age": 20}, 'Student 2': {'Name': 'ojaswi', 'Id': 2, "Age": 22}, 'Student 3': {'Name': 'rohith', 'Id': 3, "Age": 20},} # iterate all the nested dictionaries with # both keys and valuesfor i in data: # display print(data[i])
Output:
{'Name': 'Bobby', 'Id': 1, 'Age': 20}
{'Name': 'ojaswi', 'Id': 2, 'Age': 22}
{'Name': 'rohith', 'Id': 3, 'Age': 20}
It is also possible to get only either keys or values if the that is what the requirement asks for. Again for this for loop is employed with a little variation.
To get keys from the nested dictionary for each iteration keys() function is called.
Syntax:
data[i].keys()
Example: Python program to get keys from the nested dictionary
Python3
# create a nested dictionary with 3 fields of 3 studentsdata = { 'Student 1': {'Name': 'Bobby', 'Id': 1, "Age": 20}, 'Student 2': {'Name': 'ojaswi', 'Id': 2, "Age": 22}, 'Student 3': {'Name': 'rohith', 'Id': 3, "Age": 20},} # iterate all the nested dictionaries with keysfor i in data: # display print(data[i].keys())
Output:
dict_values(['Bobby', 1, 20])
dict_values(['ojaswi', 2, 22])
dict_values(['rohith', 3, 20])
Similarly to get values, after each iteration values() function is used to get the job done.
Syntax:
data[i].values()
Example: Python program to get values from the nested dictionary
Python3
# create a nested dictionary with 3 fields of 3 studentsdata = { 'Student 1': {'Name': 'Bobby', 'Id': 1, "Age": 20}, 'Student 2': {'Name': 'ojaswi', 'Id': 2, "Age": 22}, 'Student 3': {'Name': 'rohith', 'Id': 3, "Age": 20},} # iterate all the nested dictionaries with valuesfor i in data: # display print(data[i].values())
Output:
dict_values(['Bobby', 1, 20])
dict_values(['ojaswi', 2, 22])
dict_values(['rohith', 3, 20])
Picked
Python dictionary-programs
python-dict
Python
Python Programs
python-dict
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
Python Program for Fibonacci numbers
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Oct, 2021"
},
{
"code": null,
"e": 112,
"s": 28,
"text": "In this article, we will discuss how to iterate over a nested dictionary in Python."
},
{
"code": null,
"e": 252,
"s": 112,
"text": "Nested dictionary means dictionary inside a dictionary and we are going to see every possible way of iterating over such a data structure. "
},
{
"code": null,
"e": 278,
"s": 252,
"text": "Nested dictionary in use:"
},
{
"code": null,
"e": 332,
"s": 278,
"text": "{‘Student 1’: {‘Name’: ‘Bobby’, ‘Id’: 1, ‘Age’: 20}, "
},
{
"code": null,
"e": 386,
"s": 332,
"text": "‘Student 2’: {‘Name’: ‘ojaswi’, ‘Id’: 2, ‘Age’: 22}, "
},
{
"code": null,
"e": 439,
"s": 386,
"text": "‘Student 3’: {‘Name’: ‘rohith’, ‘Id’: 3, ‘Age’: 20}}"
},
{
"code": null,
"e": 557,
"s": 439,
"text": "For this we will use for loop to iterate through a dictionary to get the all the key , values of nested dictionaries."
},
{
"code": null,
"e": 565,
"s": 557,
"text": "Syntax:"
},
{
"code": null,
"e": 622,
"s": 565,
"text": "for i in dictionary_name:\n print(dictionary_name[i])"
},
{
"code": null,
"e": 628,
"s": 622,
"text": "where"
},
{
"code": null,
"e": 668,
"s": 628,
"text": "dictionary_name is the input dictionary"
},
{
"code": null,
"e": 720,
"s": 668,
"text": "dictionary_name[i] is the value to get dictionaries"
},
{
"code": null,
"e": 793,
"s": 720,
"text": "Example: Python program to get the nested dictionaries from a dictionary"
},
{
"code": null,
"e": 801,
"s": 793,
"text": "Python3"
},
{
"code": "# create a nested dictionary with 3 # fields of 3 studentsdata = { 'Student 1': {'Name': 'Bobby', 'Id': 1, \"Age\": 20}, 'Student 2': {'Name': 'ojaswi', 'Id': 2, \"Age\": 22}, 'Student 3': {'Name': 'rohith', 'Id': 3, \"Age\": 20},} # iterate all the nested dictionaries with # both keys and valuesfor i in data: # display print(data[i])",
"e": 1155,
"s": 801,
"text": null
},
{
"code": null,
"e": 1163,
"s": 1155,
"text": "Output:"
},
{
"code": null,
"e": 1279,
"s": 1163,
"text": "{'Name': 'Bobby', 'Id': 1, 'Age': 20}\n{'Name': 'ojaswi', 'Id': 2, 'Age': 22}\n{'Name': 'rohith', 'Id': 3, 'Age': 20}"
},
{
"code": null,
"e": 1440,
"s": 1279,
"text": "It is also possible to get only either keys or values if the that is what the requirement asks for. Again for this for loop is employed with a little variation."
},
{
"code": null,
"e": 1525,
"s": 1440,
"text": "To get keys from the nested dictionary for each iteration keys() function is called."
},
{
"code": null,
"e": 1533,
"s": 1525,
"text": "Syntax:"
},
{
"code": null,
"e": 1548,
"s": 1533,
"text": "data[i].keys()"
},
{
"code": null,
"e": 1611,
"s": 1548,
"text": "Example: Python program to get keys from the nested dictionary"
},
{
"code": null,
"e": 1619,
"s": 1611,
"text": "Python3"
},
{
"code": "# create a nested dictionary with 3 fields of 3 studentsdata = { 'Student 1': {'Name': 'Bobby', 'Id': 1, \"Age\": 20}, 'Student 2': {'Name': 'ojaswi', 'Id': 2, \"Age\": 22}, 'Student 3': {'Name': 'rohith', 'Id': 3, \"Age\": 20},} # iterate all the nested dictionaries with keysfor i in data: # display print(data[i].keys())",
"e": 1953,
"s": 1619,
"text": null
},
{
"code": null,
"e": 1961,
"s": 1953,
"text": "Output:"
},
{
"code": null,
"e": 2053,
"s": 1961,
"text": "dict_values(['Bobby', 1, 20])\ndict_values(['ojaswi', 2, 22])\ndict_values(['rohith', 3, 20])"
},
{
"code": null,
"e": 2146,
"s": 2053,
"text": "Similarly to get values, after each iteration values() function is used to get the job done."
},
{
"code": null,
"e": 2154,
"s": 2146,
"text": "Syntax:"
},
{
"code": null,
"e": 2171,
"s": 2154,
"text": "data[i].values()"
},
{
"code": null,
"e": 2236,
"s": 2171,
"text": "Example: Python program to get values from the nested dictionary"
},
{
"code": null,
"e": 2244,
"s": 2236,
"text": "Python3"
},
{
"code": "# create a nested dictionary with 3 fields of 3 studentsdata = { 'Student 1': {'Name': 'Bobby', 'Id': 1, \"Age\": 20}, 'Student 2': {'Name': 'ojaswi', 'Id': 2, \"Age\": 22}, 'Student 3': {'Name': 'rohith', 'Id': 3, \"Age\": 20},} # iterate all the nested dictionaries with valuesfor i in data: # display print(data[i].values())",
"e": 2582,
"s": 2244,
"text": null
},
{
"code": null,
"e": 2590,
"s": 2582,
"text": "Output:"
},
{
"code": null,
"e": 2682,
"s": 2590,
"text": "dict_values(['Bobby', 1, 20])\ndict_values(['ojaswi', 2, 22])\ndict_values(['rohith', 3, 20])"
},
{
"code": null,
"e": 2689,
"s": 2682,
"text": "Picked"
},
{
"code": null,
"e": 2716,
"s": 2689,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 2728,
"s": 2716,
"text": "python-dict"
},
{
"code": null,
"e": 2735,
"s": 2728,
"text": "Python"
},
{
"code": null,
"e": 2751,
"s": 2735,
"text": "Python Programs"
},
{
"code": null,
"e": 2763,
"s": 2751,
"text": "python-dict"
},
{
"code": null,
"e": 2861,
"s": 2763,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2893,
"s": 2861,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2920,
"s": 2893,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2951,
"s": 2920,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 2972,
"s": 2951,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3028,
"s": 2972,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3050,
"s": 3028,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3089,
"s": 3050,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 3127,
"s": 3089,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 3176,
"s": 3127,
"text": "Python | Convert string dictionary to dictionary"
}
] |
Word Break Problem | DP-32 | Set – 2
|
22 Jun, 2022
Given a non-empty sequence S and a dictionary dict[] containing a list of non-empty words, print all possible ways to break the sentence in individual dictionary words.Examples:
Input: S = “catsanddog” dict[] = {“cat”, “cats”, “and”, “sand”, “dog”} Output: “cats and dog” “cat sand dog”Input: S = “pineapplepenapple” dict[] = {“apple”, “pen”, “applepen”, “pine”, “pineapple”} Output: “pine apple pen apple” “pineapple pen apple” “pine applepen apple”
A similar problem to this is discussed in this article, where the task is to check that is there any solution such that the sequence can be broken into the dictionary words.Approach: The idea is to check for every substring starting from any position I , such that it ends at the length of the string which is present in the dictionary then simply recurse for the substring [0, I]. Meanwhile, store the overlapping subproblems for each substring to avoid the computation of the subproblem again. Overlapping subproblems can be shown as follows –
Below is the implementation of the above approach:
C++
Java
Python3
Javascript
// C++ implementation to break// a sequence into the words of// the dictionary #include <bits/stdc++.h> using namespace std; // Unordered_map used for storing// the sentences the key string// can be broken intounordered_map<string, vector<string> > mp; // Unordered_set used// to store the dictionary.unordered_set<string> dict; // Utility function used for// printing the obtained resultvoid printResult(vector<string> A){ for (int i = 0; i < A.size(); i++) cout << A[i] << '\n';} // Utility function for// appending new words// to already existing stringsvector<string> combine( vector<string> prev, string word){ // Loop to find the append string // which can be broken into for (int i = 0; i < prev.size(); i++) { prev[i] += " " + word; } return prev;} // Utility function for word Breakvector<string> wordBreakUtil(string s){ // Condition to check if the // subproblem is already computed if (mp.find(s) != mp.end()) return mp[s]; vector<string> res; // If the whole word is a dictionary // word then directly append into // the result array for the string if (dict.find(s) != dict.end()) res.push_back(s); // Loop to iterate over the substring for (int i = 1; i < s.length(); i++) { string word = s.substr(i); // If the substring is present into // the dictionary then recurse for // other substring of the string if (dict.find(word) != dict.end()) { string rem = s.substr(0, i); vector<string> prev = combine(wordBreakUtil(rem), word); res.insert(res.end(), prev.begin(), prev.end()); } } // Store the subproblem // into the map mp[s] = res; return res;} // Master wordBreak function converts// the string vector to unordered_setvector<string> wordBreak(string s, vector<string>& wordDict){ // Clear the previous stored data mp.clear(); dict.clear(); dict.insert(wordDict.begin(), wordDict.end()); return wordBreakUtil(s);} // Driver Codeint main(){ vector<string> wordDict1 = { "cat", "cats", "and", "sand", "dog" }; printResult(wordBreak("catsanddog", wordDict1)); return 0;}
import java.util.*;import java.io.*; // Java program for the above approachclass GFG{ // Unordered_map used for storing // the sentences the key String // can be broken into static TreeMap<String, ArrayList<String>> mp = new TreeMap<String, ArrayList<String>>(); // Unordered_set used // to store the dictionary. static TreeSet<String> dict = new TreeSet<String>(); // Utility function used for // printing the obtained result static void printResult(ArrayList<String> A) { for (int i = 0 ; i < A.size() ; i++){ System.out.println(A.get(i)); } } // Utility function for // appending new words // to already existing strings static ArrayList<String> combine(ArrayList<String> prev, String word){ // Loop to find the append String // which can be broken into for (int i = 0 ; i < prev.size() ; i++) { prev.set(i, prev.get(i) + " " + word); } return prev; } // Utility function for word Break static ArrayList<String> wordBreakUtil(String s) { // Condition to check if the // subproblem is already computed if (mp.containsKey(s)){ return mp.get(s); } ArrayList<String> res = new ArrayList<String>(); // If the whole word is a dictionary // word then directly append into // the result array for the String if (dict.contains(s)) res.add(s); // Loop to iterate over the substring for (int i = 1 ; i < s.length() ; i++) { String word = s.substring(i); // If the substring is present into // the dictionary then recurse for // other substring of the String if (dict.contains(word)) { String rem = s.substring(0, i); ArrayList<String> prev = combine(wordBreakUtil(rem), word); for(int j = 0 ; j < prev.size() ; j++){ res.add(prev.get(j)); } } } // Store the subproblem // into the map mp.put(s, res); return res; } // Master wordBreak function converts // the String vector to unordered_set static ArrayList<String> wordBreak(String s, ArrayList<String> wordDict) { // Clear the previous stored data mp.clear(); dict.clear(); dict.addAll(wordDict); return wordBreakUtil(s); } // Driver Code public static void main(String args[]) { ArrayList<String> wordDict1 = new ArrayList<String>( List.of("cat", "cats", "and", "sand", "dog") ); printResult(wordBreak("catsanddog", wordDict1)); }} // This code is contributed by subhamgoyal2014.
# Python3 implementation to break# a sequence into the words of# the dictionary # Unordered_map used for storing# the sentences the key string# can be broken intomp = dict() # Unordered_set used# to store the dictionary.dict_t = set() # Utility function used for# printing the obtained resultdef printResult(A): for i in range(len(A)): print(A[i]) # Utility function for# appending new words# to already existing stringsdef combine( prev, word): # Loop to find the append string # which can be broken into for i in range(len(prev)): prev[i] += " " + word; return prev; # Utility function for word Breakdef wordBreakUtil(s): # Condition to check if the # subproblem is already computed if (s in mp): return mp[s]; res = [] # If the whole word is a dictionary # word then directly append into # the result array for the string if (s in dict_t): res.append(s); # Loop to iterate over the substring for i in range(1, len(s)): word = s[i:]; # If the substring is present into # the dictionary then recurse for # other substring of the string if (word in dict_t): rem = s[:i] prev = combine(wordBreakUtil(rem), word); for i in prev: res.append(i) # Store the subproblem # into the map #res is an reference so we need to assign an reference to something if its keep on changing #res values changes after it start going through combine method #you can check if you had a doubt so here we just clone res x=[] for i in res: x.append(i) mp[s] = x; return res; # Master wordBreak function converts# the string vector to unordered_setdef wordBreak(s, wordDict): # Clear the previous stored data mp.clear(); dict_t.clear(); for i in wordDict: dict_t.add(i) return wordBreakUtil(s); # Driver Codeif __name__=='__main__': wordDict1 = ["cat", "cats", "and", "sand", "dog" ] printResult(wordBreak("catsanddog", wordDict1)); # This code is contributed by rutvik_56
<script> // JavaScript implementation to break// a sequence into the words of// the dictionary // Unordered_map used for storing// the sentences the key string// can be broken intolet mp = new Map() // Unordered_set used// to store the dictionary.let dict_t = new Set() // Utility function used for// printing the obtained resultfunction printResult(A){ for(let i=0;i<A.length;i++) document.write(A[i],"</br>")}// Utility function for// pushing new words// to already existing stringsfunction combine(prev, word){ // Loop to find the push string // which can be broken into for (let i=0;i<prev.length;i++) prev[i] += " " + word; return prev;}// Utility function for word Breakfunction wordBreakUtil(s){ // Condition to check if the // subproblem is already computed if (mp.has(s)) return mp.get(s) let res = [] // If the whole word is a dictionary // word then directly push into // the result array for the string if (dict_t.has(s)) res.push(s); // Loop to iterate over the substring for(let i=1;i<s.length;i++){ let word = s.substring(i,) // If the substring is present into // the dictionary then recurse for // other substring of the string if (dict_t.has(word)){ let rem = s.substring(0,i) let prev = combine(wordBreakUtil(rem), word); for(let i of prev) res.push(i) } } // Store the subproblem // into the map // res is an reference so we need to assign an reference to something if its keep on changing // res values changes after it start going through combine method // you can check if you had a doubt so here we just clone res let x=[] for(let i of res) x.push(i) mp.set(s, x) return res} // Master wordBreak function converts// the string vector to unordered_setfunction wordBreak(s, wordDict){ // Clear the previous stored data mp.clear(); dict_t.clear(); for(let i of wordDict) dict_t.add(i) return wordBreakUtil(s);} // Driver Code let wordDict1 = ["cat", "cats", "and", "sand", "dog" ];printResult(wordBreak("catsanddog", wordDict1)); // This code is contributed by shinjanpatra </script>
cat sand dog
cats and dog
Time Complexity: O(2^N), where N is the length of the given string.Auxiliary Space: O(S + N). where S is the sum of all characters of wordDict1.
rutvik_56
purnaanrup100
sumitgumber28
simmytarika5
pankajsharmagfg
shinjanpatra
subhamgoyal2014
Algorithms
Dynamic Programming
Recursion
Dynamic Programming
Recursion
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
Understanding Time Complexity with Simple Examples
Largest Sum Contiguous Subarray
Program for Fibonacci numbers
0-1 Knapsack Problem | DP-10
Subset Sum Problem | DP-25
Longest Palindromic Substring | Set 1
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 232,
"s": 52,
"text": "Given a non-empty sequence S and a dictionary dict[] containing a list of non-empty words, print all possible ways to break the sentence in individual dictionary words.Examples: "
},
{
"code": null,
"e": 507,
"s": 232,
"text": "Input: S = “catsanddog” dict[] = {“cat”, “cats”, “and”, “sand”, “dog”} Output: “cats and dog” “cat sand dog”Input: S = “pineapplepenapple” dict[] = {“apple”, “pen”, “applepen”, “pine”, “pineapple”} Output: “pine apple pen apple” “pineapple pen apple” “pine applepen apple” "
},
{
"code": null,
"e": 1057,
"s": 509,
"text": "A similar problem to this is discussed in this article, where the task is to check that is there any solution such that the sequence can be broken into the dictionary words.Approach: The idea is to check for every substring starting from any position I , such that it ends at the length of the string which is present in the dictionary then simply recurse for the substring [0, I]. Meanwhile, store the overlapping subproblems for each substring to avoid the computation of the subproblem again. Overlapping subproblems can be shown as follows – "
},
{
"code": null,
"e": 1110,
"s": 1057,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 1114,
"s": 1110,
"text": "C++"
},
{
"code": null,
"e": 1119,
"s": 1114,
"text": "Java"
},
{
"code": null,
"e": 1127,
"s": 1119,
"text": "Python3"
},
{
"code": null,
"e": 1138,
"s": 1127,
"text": "Javascript"
},
{
"code": "// C++ implementation to break// a sequence into the words of// the dictionary #include <bits/stdc++.h> using namespace std; // Unordered_map used for storing// the sentences the key string// can be broken intounordered_map<string, vector<string> > mp; // Unordered_set used// to store the dictionary.unordered_set<string> dict; // Utility function used for// printing the obtained resultvoid printResult(vector<string> A){ for (int i = 0; i < A.size(); i++) cout << A[i] << '\\n';} // Utility function for// appending new words// to already existing stringsvector<string> combine( vector<string> prev, string word){ // Loop to find the append string // which can be broken into for (int i = 0; i < prev.size(); i++) { prev[i] += \" \" + word; } return prev;} // Utility function for word Breakvector<string> wordBreakUtil(string s){ // Condition to check if the // subproblem is already computed if (mp.find(s) != mp.end()) return mp[s]; vector<string> res; // If the whole word is a dictionary // word then directly append into // the result array for the string if (dict.find(s) != dict.end()) res.push_back(s); // Loop to iterate over the substring for (int i = 1; i < s.length(); i++) { string word = s.substr(i); // If the substring is present into // the dictionary then recurse for // other substring of the string if (dict.find(word) != dict.end()) { string rem = s.substr(0, i); vector<string> prev = combine(wordBreakUtil(rem), word); res.insert(res.end(), prev.begin(), prev.end()); } } // Store the subproblem // into the map mp[s] = res; return res;} // Master wordBreak function converts// the string vector to unordered_setvector<string> wordBreak(string s, vector<string>& wordDict){ // Clear the previous stored data mp.clear(); dict.clear(); dict.insert(wordDict.begin(), wordDict.end()); return wordBreakUtil(s);} // Driver Codeint main(){ vector<string> wordDict1 = { \"cat\", \"cats\", \"and\", \"sand\", \"dog\" }; printResult(wordBreak(\"catsanddog\", wordDict1)); return 0;}",
"e": 3406,
"s": 1138,
"text": null
},
{
"code": "import java.util.*;import java.io.*; // Java program for the above approachclass GFG{ // Unordered_map used for storing // the sentences the key String // can be broken into static TreeMap<String, ArrayList<String>> mp = new TreeMap<String, ArrayList<String>>(); // Unordered_set used // to store the dictionary. static TreeSet<String> dict = new TreeSet<String>(); // Utility function used for // printing the obtained result static void printResult(ArrayList<String> A) { for (int i = 0 ; i < A.size() ; i++){ System.out.println(A.get(i)); } } // Utility function for // appending new words // to already existing strings static ArrayList<String> combine(ArrayList<String> prev, String word){ // Loop to find the append String // which can be broken into for (int i = 0 ; i < prev.size() ; i++) { prev.set(i, prev.get(i) + \" \" + word); } return prev; } // Utility function for word Break static ArrayList<String> wordBreakUtil(String s) { // Condition to check if the // subproblem is already computed if (mp.containsKey(s)){ return mp.get(s); } ArrayList<String> res = new ArrayList<String>(); // If the whole word is a dictionary // word then directly append into // the result array for the String if (dict.contains(s)) res.add(s); // Loop to iterate over the substring for (int i = 1 ; i < s.length() ; i++) { String word = s.substring(i); // If the substring is present into // the dictionary then recurse for // other substring of the String if (dict.contains(word)) { String rem = s.substring(0, i); ArrayList<String> prev = combine(wordBreakUtil(rem), word); for(int j = 0 ; j < prev.size() ; j++){ res.add(prev.get(j)); } } } // Store the subproblem // into the map mp.put(s, res); return res; } // Master wordBreak function converts // the String vector to unordered_set static ArrayList<String> wordBreak(String s, ArrayList<String> wordDict) { // Clear the previous stored data mp.clear(); dict.clear(); dict.addAll(wordDict); return wordBreakUtil(s); } // Driver Code public static void main(String args[]) { ArrayList<String> wordDict1 = new ArrayList<String>( List.of(\"cat\", \"cats\", \"and\", \"sand\", \"dog\") ); printResult(wordBreak(\"catsanddog\", wordDict1)); }} // This code is contributed by subhamgoyal2014.",
"e": 5863,
"s": 3406,
"text": null
},
{
"code": "# Python3 implementation to break# a sequence into the words of# the dictionary # Unordered_map used for storing# the sentences the key string# can be broken intomp = dict() # Unordered_set used# to store the dictionary.dict_t = set() # Utility function used for# printing the obtained resultdef printResult(A): for i in range(len(A)): print(A[i]) # Utility function for# appending new words# to already existing stringsdef combine( prev, word): # Loop to find the append string # which can be broken into for i in range(len(prev)): prev[i] += \" \" + word; return prev; # Utility function for word Breakdef wordBreakUtil(s): # Condition to check if the # subproblem is already computed if (s in mp): return mp[s]; res = [] # If the whole word is a dictionary # word then directly append into # the result array for the string if (s in dict_t): res.append(s); # Loop to iterate over the substring for i in range(1, len(s)): word = s[i:]; # If the substring is present into # the dictionary then recurse for # other substring of the string if (word in dict_t): rem = s[:i] prev = combine(wordBreakUtil(rem), word); for i in prev: res.append(i) # Store the subproblem # into the map #res is an reference so we need to assign an reference to something if its keep on changing #res values changes after it start going through combine method #you can check if you had a doubt so here we just clone res x=[] for i in res: x.append(i) mp[s] = x; return res; # Master wordBreak function converts# the string vector to unordered_setdef wordBreak(s, wordDict): # Clear the previous stored data mp.clear(); dict_t.clear(); for i in wordDict: dict_t.add(i) return wordBreakUtil(s); # Driver Codeif __name__=='__main__': wordDict1 = [\"cat\", \"cats\", \"and\", \"sand\", \"dog\" ] printResult(wordBreak(\"catsanddog\", wordDict1)); # This code is contributed by rutvik_56",
"e": 8006,
"s": 5863,
"text": null
},
{
"code": "<script> // JavaScript implementation to break// a sequence into the words of// the dictionary // Unordered_map used for storing// the sentences the key string// can be broken intolet mp = new Map() // Unordered_set used// to store the dictionary.let dict_t = new Set() // Utility function used for// printing the obtained resultfunction printResult(A){ for(let i=0;i<A.length;i++) document.write(A[i],\"</br>\")}// Utility function for// pushing new words// to already existing stringsfunction combine(prev, word){ // Loop to find the push string // which can be broken into for (let i=0;i<prev.length;i++) prev[i] += \" \" + word; return prev;}// Utility function for word Breakfunction wordBreakUtil(s){ // Condition to check if the // subproblem is already computed if (mp.has(s)) return mp.get(s) let res = [] // If the whole word is a dictionary // word then directly push into // the result array for the string if (dict_t.has(s)) res.push(s); // Loop to iterate over the substring for(let i=1;i<s.length;i++){ let word = s.substring(i,) // If the substring is present into // the dictionary then recurse for // other substring of the string if (dict_t.has(word)){ let rem = s.substring(0,i) let prev = combine(wordBreakUtil(rem), word); for(let i of prev) res.push(i) } } // Store the subproblem // into the map // res is an reference so we need to assign an reference to something if its keep on changing // res values changes after it start going through combine method // you can check if you had a doubt so here we just clone res let x=[] for(let i of res) x.push(i) mp.set(s, x) return res} // Master wordBreak function converts// the string vector to unordered_setfunction wordBreak(s, wordDict){ // Clear the previous stored data mp.clear(); dict_t.clear(); for(let i of wordDict) dict_t.add(i) return wordBreakUtil(s);} // Driver Code let wordDict1 = [\"cat\", \"cats\", \"and\", \"sand\", \"dog\" ];printResult(wordBreak(\"catsanddog\", wordDict1)); // This code is contributed by shinjanpatra </script>",
"e": 10302,
"s": 8006,
"text": null
},
{
"code": null,
"e": 10328,
"s": 10302,
"text": "cat sand dog\ncats and dog"
},
{
"code": null,
"e": 10475,
"s": 10330,
"text": "Time Complexity: O(2^N), where N is the length of the given string.Auxiliary Space: O(S + N). where S is the sum of all characters of wordDict1."
},
{
"code": null,
"e": 10485,
"s": 10475,
"text": "rutvik_56"
},
{
"code": null,
"e": 10499,
"s": 10485,
"text": "purnaanrup100"
},
{
"code": null,
"e": 10513,
"s": 10499,
"text": "sumitgumber28"
},
{
"code": null,
"e": 10526,
"s": 10513,
"text": "simmytarika5"
},
{
"code": null,
"e": 10542,
"s": 10526,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 10555,
"s": 10542,
"text": "shinjanpatra"
},
{
"code": null,
"e": 10571,
"s": 10555,
"text": "subhamgoyal2014"
},
{
"code": null,
"e": 10582,
"s": 10571,
"text": "Algorithms"
},
{
"code": null,
"e": 10602,
"s": 10582,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 10612,
"s": 10602,
"text": "Recursion"
},
{
"code": null,
"e": 10632,
"s": 10612,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 10642,
"s": 10632,
"text": "Recursion"
},
{
"code": null,
"e": 10653,
"s": 10642,
"text": "Algorithms"
},
{
"code": null,
"e": 10751,
"s": 10653,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10776,
"s": 10751,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 10825,
"s": 10776,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 10863,
"s": 10825,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 10931,
"s": 10863,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 10982,
"s": 10931,
"text": "Understanding Time Complexity with Simple Examples"
},
{
"code": null,
"e": 11014,
"s": 10982,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 11044,
"s": 11014,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 11073,
"s": 11044,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 11100,
"s": 11073,
"text": "Subset Sum Problem | DP-25"
}
] |
Numpy MaskedArray.reshape() function | Python
|
03 Oct, 2019
numpy.MaskedArray.reshape() function is used to give a new shape to the masked array without changing its data.It returns a masked array containing the same data, but with a new shape. The result is a view on the original array; if this is not possible, a ValueError is raised.
Syntax : numpy.ma.reshape(shape, order)
Parameters:
shape:[ int or tuple of ints] The new shape should be compatible with the original shape.order : [‘C’, ‘F’, ‘A’, ‘K’, optional] By default, ‘C’ index order is used.–> The elements of a are read using this index order.–> ‘C’ means to index the elements in C-like order, with the last axis index changing fastest, back to the first axis index changing slowest.–> ‘F’ means to index the elements in Fortran-like index order, with the first index changing fastest, and the last index changing slowest.–> ‘A’ means to read the elements in Fortran-like index order if m is Fortran contiguous in memory, C-like order otherwise.–> ‘K’ means to read the elements in the order they occur in memory, except for reversing the data when strides are negative.
Return : [ reshaped_array] A new view on the array.
Code #1 :
# Python program explaining# numpy.MaskedArray.reshape() method # importing numpy as geek # and numpy.ma module as ma import numpy as geek import numpy.ma as ma # creating input array in_arr = geek.array([1, 2, 3, -1]) print ("Input array : ", in_arr) # Now we are creating a masked array. # by making third entry as invalid. mask_arr = ma.masked_array(in_arr, mask =[1, 0, 1, 0]) print ("Masked array : ", mask_arr) # applying MaskedArray.reshape methods to make # it a 2d masked arrayout_arr = mask_arr.reshape(2, 2) print ("Output 2D masked array : ", out_arr)
Input array : [ 1 2 3 -1]
Masked array : [-- 2 -- -1]
Output 2D masked array : [[-- 2]
[-- -1]]
Code #2 :
# Python program explaining# numpy.MaskedArray.reshape() method # importing numpy as geek # and numpy.ma module as ma import numpy as geek import numpy.ma as ma # creating input array in_arr = geek.array([[[ 2e8, 3e-5]], [[ -45.0, 2e5]]])print ("Input array : ", in_arr) # Now we are creating a masked array. # by making one entry as invalid. mask_arr = ma.masked_array(in_arr, mask =[[[ 1, 0]], [[ 0, 0]]]) print ("3D Masked array : ", mask_arr) # applying MaskedArray.reshape methods to make # it a 2d masked arrayout_arr = mask_arr.reshape(1, 4) print ("Output 2D masked array : ", out_arr) print() # applying MaskedArray.reshape methods to make # it a 1d masked arrayout_arr = mask_arr.reshape(4, ) print ("Output 1D masked array : ", out_arr)
Input array : [[[ 2.0e+08 3.0e-05]]
[[-4.5e+01 2.0e+05]]]
3D Masked array : [[[-- 3e-05]]
[[-45.0 200000.0]]]
Output 2D masked array : [[-- 3e-05 -45.0 200000.0]]
Output 1D masked array : [-- 3e-05 -45.0 200000.0]
Python numpy-arrayManipulation
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 | os.path.join() method
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
Introduction To PYTHON
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n03 Oct, 2019"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "numpy.MaskedArray.reshape() function is used to give a new shape to the masked array without changing its data.It returns a masked array containing the same data, but with a new shape. The result is a view on the original array; if this is not possible, a ValueError is raised."
},
{
"code": null,
"e": 346,
"s": 306,
"text": "Syntax : numpy.ma.reshape(shape, order)"
},
{
"code": null,
"e": 358,
"s": 346,
"text": "Parameters:"
},
{
"code": null,
"e": 1104,
"s": 358,
"text": "shape:[ int or tuple of ints] The new shape should be compatible with the original shape.order : [‘C’, ‘F’, ‘A’, ‘K’, optional] By default, ‘C’ index order is used.–> The elements of a are read using this index order.–> ‘C’ means to index the elements in C-like order, with the last axis index changing fastest, back to the first axis index changing slowest.–> ‘F’ means to index the elements in Fortran-like index order, with the first index changing fastest, and the last index changing slowest.–> ‘A’ means to read the elements in Fortran-like index order if m is Fortran contiguous in memory, C-like order otherwise.–> ‘K’ means to read the elements in the order they occur in memory, except for reversing the data when strides are negative."
},
{
"code": null,
"e": 1156,
"s": 1104,
"text": "Return : [ reshaped_array] A new view on the array."
},
{
"code": null,
"e": 1166,
"s": 1156,
"text": "Code #1 :"
},
{
"code": "# Python program explaining# numpy.MaskedArray.reshape() method # importing numpy as geek # and numpy.ma module as ma import numpy as geek import numpy.ma as ma # creating input array in_arr = geek.array([1, 2, 3, -1]) print (\"Input array : \", in_arr) # Now we are creating a masked array. # by making third entry as invalid. mask_arr = ma.masked_array(in_arr, mask =[1, 0, 1, 0]) print (\"Masked array : \", mask_arr) # applying MaskedArray.reshape methods to make # it a 2d masked arrayout_arr = mask_arr.reshape(2, 2) print (\"Output 2D masked array : \", out_arr) ",
"e": 1751,
"s": 1166,
"text": null
},
{
"code": null,
"e": 1854,
"s": 1751,
"text": "Input array : [ 1 2 3 -1]\nMasked array : [-- 2 -- -1]\nOutput 2D masked array : [[-- 2]\n [-- -1]]\n"
},
{
"code": null,
"e": 1866,
"s": 1856,
"text": "Code #2 :"
},
{
"code": "# Python program explaining# numpy.MaskedArray.reshape() method # importing numpy as geek # and numpy.ma module as ma import numpy as geek import numpy.ma as ma # creating input array in_arr = geek.array([[[ 2e8, 3e-5]], [[ -45.0, 2e5]]])print (\"Input array : \", in_arr) # Now we are creating a masked array. # by making one entry as invalid. mask_arr = ma.masked_array(in_arr, mask =[[[ 1, 0]], [[ 0, 0]]]) print (\"3D Masked array : \", mask_arr) # applying MaskedArray.reshape methods to make # it a 2d masked arrayout_arr = mask_arr.reshape(1, 4) print (\"Output 2D masked array : \", out_arr) print() # applying MaskedArray.reshape methods to make # it a 1d masked arrayout_arr = mask_arr.reshape(4, ) print (\"Output 1D masked array : \", out_arr) ",
"e": 2637,
"s": 1866,
"text": null
},
{
"code": null,
"e": 2863,
"s": 2637,
"text": "Input array : [[[ 2.0e+08 3.0e-05]]\n\n [[-4.5e+01 2.0e+05]]]\n3D Masked array : [[[-- 3e-05]]\n\n [[-45.0 200000.0]]]\nOutput 2D masked array : [[-- 3e-05 -45.0 200000.0]]\n\nOutput 1D masked array : [-- 3e-05 -45.0 200000.0]\n"
},
{
"code": null,
"e": 2894,
"s": 2863,
"text": "Python numpy-arrayManipulation"
},
{
"code": null,
"e": 2907,
"s": 2894,
"text": "Python-numpy"
},
{
"code": null,
"e": 2914,
"s": 2907,
"text": "Python"
},
{
"code": null,
"e": 3012,
"s": 2914,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3044,
"s": 3012,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3071,
"s": 3044,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3102,
"s": 3071,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 3123,
"s": 3102,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3179,
"s": 3123,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 3202,
"s": 3179,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3244,
"s": 3202,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 3286,
"s": 3244,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 3325,
"s": 3286,
"text": "Python | datetime.timedelta() function"
}
] |
Intuit Interview Experience for Summer Internship Off-Campus (2 months)
|
01 Sep, 2021
There were 2 Rounds on CV selection, 1 Online Coding Round and 2 Technical Rounds, and 1 HR Round.
Coding Round:
Total 4 questions were asked (I was able to solve 3 of them completely including the hard one). One was easy, two were medium, and last was hard.
Given a matrix of size N*N (empty) and k (number of operations). In each operation, you will be given two values r (rth row) and c (cth column) and you have to place ‘X’ in rth row cells and cth column cells. After each operation, you are required to print the number of empty cells in the matrix.Example:n = 5, k = 3
1st operation : r = 3, c = 2
2nd operation : r = 4, c = 4
3rd operation : r = 3, c = 5Output (Total empty cells after each operation):16
9
6There are N students and K toffees. Students can take toffees if both conditions satisfy:He/she must be able to take all the candies he/she wants.All his/her friends must to able to take all the candies they want to take.
Given a matrix of size N*N (empty) and k (number of operations). In each operation, you will be given two values r (rth row) and c (cth column) and you have to place ‘X’ in rth row cells and cth column cells. After each operation, you are required to print the number of empty cells in the matrix.Example:n = 5, k = 3
1st operation : r = 3, c = 2
2nd operation : r = 4, c = 4
3rd operation : r = 3, c = 5Output (Total empty cells after each operation):16
9
6
Example:
n = 5, k = 3
1st operation : r = 3, c = 2
2nd operation : r = 4, c = 4
3rd operation : r = 3, c = 5
Output (Total empty cells after each operation):
16
9
6
There are N students and K toffees. Students can take toffees if both conditions satisfy:He/she must be able to take all the candies he/she wants.All his/her friends must to able to take all the candies they want to take.
He/she must be able to take all the candies he/she wants.
All his/her friends must to able to take all the candies they want to take.
Technical Round 1: Based on Coding, Data Structure and Algorithm, DBMS, behaviour
Related to pointers (mainly pointer pointing to a 2D array) and address (in-depth)(https://www.geeksforgeeks.org/pointer-array-array-pointer/)https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x3116/1Practice Link: https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x3116/1Find all the triplets: https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1Practice Link: https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1DBMS queries and questions
Related to pointers (mainly pointer pointing to a 2D array) and address (in-depth)(https://www.geeksforgeeks.org/pointer-array-array-pointer/)
https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x3116/1Practice Link: https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x3116/1
Find all the triplets: https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1Practice Link: https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1
DBMS queries and questions
Technical Round 2: Based on Project, Coding, Data Structure, and Algorithm, OOP, DBMS, behaviour
Detailed discussion on projects like stacks and technologies used, the problem faced, how did you manage to make your app efficient, database structure and schemas, functional and non-functional requirements, security, scalability, etc.https://practice.geeksforgeeks.org/problems/print-anagrams-together/1What is a singleton class and how to make such a class in Java/C++.(https://www.geeksforgeeks.org/singleton-class-java/)What is multithreading and how to avoid multi-threads to access a resource at a time? (https://www.geeksforgeeks.org/synchronized-in-java/)What is Regex? How to efficiently find all the data (documents) in the database that don’t match the given Regex ?.What are the benefits of using Mongo DB and Firebase as databases (I told them that I have used Firebase and Firestore)?How to avoid compiler to do optimization for some certain resource. (https://www.geeksforgeeks.org/understanding-volatile-qualifier-in-c/)O(n) time and O(1) space without changing the relative position of elements. (https://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/)Practice Link: https://practice.geeksforgeeks.org/problems/array-of-alternate-ve-and-ve-nos1401/1How did you test your application? How have you applied unit testing to it?How did you optimize your React Application? (My answer was: using Lazy loading, dividing into modules, optimizing webpack, etc).Question on how Encryption is different than Hashing? (https://www.geeksforgeeks.org/difference-between-hashing-and-encryption/)What are the problems faced by React? (https://www.growth-rocket.com/blog/a-closer-look-at-client-side-server-side-rendering/)
Detailed discussion on projects like stacks and technologies used, the problem faced, how did you manage to make your app efficient, database structure and schemas, functional and non-functional requirements, security, scalability, etc.
https://practice.geeksforgeeks.org/problems/print-anagrams-together/1
What is a singleton class and how to make such a class in Java/C++.(https://www.geeksforgeeks.org/singleton-class-java/)
What is multithreading and how to avoid multi-threads to access a resource at a time? (https://www.geeksforgeeks.org/synchronized-in-java/)
What is Regex? How to efficiently find all the data (documents) in the database that don’t match the given Regex ?.
What are the benefits of using Mongo DB and Firebase as databases (I told them that I have used Firebase and Firestore)?
How to avoid compiler to do optimization for some certain resource. (https://www.geeksforgeeks.org/understanding-volatile-qualifier-in-c/)
O(n) time and O(1) space without changing the relative position of elements. (https://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/)Practice Link: https://practice.geeksforgeeks.org/problems/array-of-alternate-ve-and-ve-nos1401/1
How did you test your application? How have you applied unit testing to it?
How did you optimize your React Application? (My answer was: using Lazy loading, dividing into modules, optimizing webpack, etc).
Question on how Encryption is different than Hashing? (https://www.geeksforgeeks.org/difference-between-hashing-and-encryption/)
What are the problems faced by React? (https://www.growth-rocket.com/blog/a-closer-look-at-client-side-server-side-rendering/)
Conclusion: Interviewers mainly focus on how you approach the question rather than you solved the problem completely. They engross more on DSA and dev is the edge point if you had done it.
HR Round(Telephonic):
Questions like could have you done better in all previous rounds and how, what has been your greatest failure, what do you know about us or our company, and many more.This round was all about testing the candidate and what steps did I take up to tackle the above-mentioned problems.
Questions like could have you done better in all previous rounds and how, what has been your greatest failure, what do you know about us or our company, and many more.
This round was all about testing the candidate and what steps did I take up to tackle the above-mentioned problems.
Some more questions were asked. Be positive and aloud during the interview. Don’t be nervous and in rush to answer the question. Take your time. Interviewers are mainly nice and have a helping nature (in my case they were very nice, polite, helped me wherever I got stuck). Believe in yourself and always in God.
Thanks to GeeksforGeeks, HackerRank, HackerEarth, CodeChef, Codeforces.
Intuit
Marketing
Off-Campus
Internship
Interview Experiences
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Samsung R&D Bangalore (SRIB) Interview Experience | On- Campus for Internship 2021
Microsoft Interview Experience for SWE Intern
Zoho Interview Experience (Off-Campus ) 2022
Google STEP Interview Experience Internship 2022
Microsoft Interview Experience for SWE Intern (On-Campus)
Amazon Interview Questions
Google SWE Interview Experience (Google Online Coding Challenge) 2022
TCS Digital Interview Questions
Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022
Amazon Interview Experience for SDE 1
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n01 Sep, 2021"
},
{
"code": null,
"e": 151,
"s": 52,
"text": "There were 2 Rounds on CV selection, 1 Online Coding Round and 2 Technical Rounds, and 1 HR Round."
},
{
"code": null,
"e": 165,
"s": 151,
"text": "Coding Round:"
},
{
"code": null,
"e": 311,
"s": 165,
"text": "Total 4 questions were asked (I was able to solve 3 of them completely including the hard one). One was easy, two were medium, and last was hard."
},
{
"code": null,
"e": 993,
"s": 311,
"text": "Given a matrix of size N*N (empty) and k (number of operations). In each operation, you will be given two values r (rth row) and c (cth column) and you have to place ‘X’ in rth row cells and cth column cells. After each operation, you are required to print the number of empty cells in the matrix.Example:n = 5, k = 3\n1st operation : r = 3, c = 2 \n2nd operation : r = 4, c = 4\n3rd operation : r = 3, c = 5Output (Total empty cells after each operation):16\n9\n6There are N students and K toffees. Students can take toffees if both conditions satisfy:He/she must be able to take all the candies he/she wants.All his/her friends must to able to take all the candies they want to take."
},
{
"code": null,
"e": 1454,
"s": 993,
"text": "Given a matrix of size N*N (empty) and k (number of operations). In each operation, you will be given two values r (rth row) and c (cth column) and you have to place ‘X’ in rth row cells and cth column cells. After each operation, you are required to print the number of empty cells in the matrix.Example:n = 5, k = 3\n1st operation : r = 3, c = 2 \n2nd operation : r = 4, c = 4\n3rd operation : r = 3, c = 5Output (Total empty cells after each operation):16\n9\n6"
},
{
"code": null,
"e": 1463,
"s": 1454,
"text": "Example:"
},
{
"code": null,
"e": 1565,
"s": 1463,
"text": "n = 5, k = 3\n1st operation : r = 3, c = 2 \n2nd operation : r = 4, c = 4\n3rd operation : r = 3, c = 5"
},
{
"code": null,
"e": 1614,
"s": 1565,
"text": "Output (Total empty cells after each operation):"
},
{
"code": null,
"e": 1621,
"s": 1614,
"text": "16\n9\n6"
},
{
"code": null,
"e": 1843,
"s": 1621,
"text": "There are N students and K toffees. Students can take toffees if both conditions satisfy:He/she must be able to take all the candies he/she wants.All his/her friends must to able to take all the candies they want to take."
},
{
"code": null,
"e": 1901,
"s": 1843,
"text": "He/she must be able to take all the candies he/she wants."
},
{
"code": null,
"e": 1977,
"s": 1901,
"text": "All his/her friends must to able to take all the candies they want to take."
},
{
"code": null,
"e": 2059,
"s": 1977,
"text": "Technical Round 1: Based on Coding, Data Structure and Algorithm, DBMS, behaviour"
},
{
"code": null,
"e": 2589,
"s": 2059,
"text": "Related to pointers (mainly pointer pointing to a 2D array) and address (in-depth)(https://www.geeksforgeeks.org/pointer-array-array-pointer/)https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x3116/1Practice Link: https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x3116/1Find all the triplets: https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1Practice Link: https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1DBMS queries and questions"
},
{
"code": null,
"e": 2732,
"s": 2589,
"text": "Related to pointers (mainly pointer pointing to a 2D array) and address (in-depth)(https://www.geeksforgeeks.org/pointer-array-array-pointer/)"
},
{
"code": null,
"e": 2910,
"s": 2732,
"text": "https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x3116/1Practice Link: https://practice.geeksforgeeks.org/problems/first-and-last-occurrences-of-x3116/1"
},
{
"code": null,
"e": 3095,
"s": 2910,
"text": "Find all the triplets: https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1Practice Link: https://practice.geeksforgeeks.org/problems/find-triplets-with-zero-sum/1"
},
{
"code": null,
"e": 3122,
"s": 3095,
"text": "DBMS queries and questions"
},
{
"code": null,
"e": 3219,
"s": 3122,
"text": "Technical Round 2: Based on Project, Coding, Data Structure, and Algorithm, OOP, DBMS, behaviour"
},
{
"code": null,
"e": 4888,
"s": 3219,
"text": "Detailed discussion on projects like stacks and technologies used, the problem faced, how did you manage to make your app efficient, database structure and schemas, functional and non-functional requirements, security, scalability, etc.https://practice.geeksforgeeks.org/problems/print-anagrams-together/1What is a singleton class and how to make such a class in Java/C++.(https://www.geeksforgeeks.org/singleton-class-java/)What is multithreading and how to avoid multi-threads to access a resource at a time? (https://www.geeksforgeeks.org/synchronized-in-java/)What is Regex? How to efficiently find all the data (documents) in the database that don’t match the given Regex ?.What are the benefits of using Mongo DB and Firebase as databases (I told them that I have used Firebase and Firestore)?How to avoid compiler to do optimization for some certain resource. (https://www.geeksforgeeks.org/understanding-volatile-qualifier-in-c/)O(n) time and O(1) space without changing the relative position of elements. (https://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/)Practice Link: https://practice.geeksforgeeks.org/problems/array-of-alternate-ve-and-ve-nos1401/1How did you test your application? How have you applied unit testing to it?How did you optimize your React Application? (My answer was: using Lazy loading, dividing into modules, optimizing webpack, etc).Question on how Encryption is different than Hashing? (https://www.geeksforgeeks.org/difference-between-hashing-and-encryption/)What are the problems faced by React? (https://www.growth-rocket.com/blog/a-closer-look-at-client-side-server-side-rendering/)"
},
{
"code": null,
"e": 5125,
"s": 4888,
"text": "Detailed discussion on projects like stacks and technologies used, the problem faced, how did you manage to make your app efficient, database structure and schemas, functional and non-functional requirements, security, scalability, etc."
},
{
"code": null,
"e": 5195,
"s": 5125,
"text": "https://practice.geeksforgeeks.org/problems/print-anagrams-together/1"
},
{
"code": null,
"e": 5316,
"s": 5195,
"text": "What is a singleton class and how to make such a class in Java/C++.(https://www.geeksforgeeks.org/singleton-class-java/)"
},
{
"code": null,
"e": 5456,
"s": 5316,
"text": "What is multithreading and how to avoid multi-threads to access a resource at a time? (https://www.geeksforgeeks.org/synchronized-in-java/)"
},
{
"code": null,
"e": 5572,
"s": 5456,
"text": "What is Regex? How to efficiently find all the data (documents) in the database that don’t match the given Regex ?."
},
{
"code": null,
"e": 5693,
"s": 5572,
"text": "What are the benefits of using Mongo DB and Firebase as databases (I told them that I have used Firebase and Firestore)?"
},
{
"code": null,
"e": 5832,
"s": 5693,
"text": "How to avoid compiler to do optimization for some certain resource. (https://www.geeksforgeeks.org/understanding-volatile-qualifier-in-c/)"
},
{
"code": null,
"e": 6106,
"s": 5832,
"text": "O(n) time and O(1) space without changing the relative position of elements. (https://www.geeksforgeeks.org/rearrange-array-alternating-positive-negative-items-o1-extra-space/)Practice Link: https://practice.geeksforgeeks.org/problems/array-of-alternate-ve-and-ve-nos1401/1"
},
{
"code": null,
"e": 6182,
"s": 6106,
"text": "How did you test your application? How have you applied unit testing to it?"
},
{
"code": null,
"e": 6312,
"s": 6182,
"text": "How did you optimize your React Application? (My answer was: using Lazy loading, dividing into modules, optimizing webpack, etc)."
},
{
"code": null,
"e": 6441,
"s": 6312,
"text": "Question on how Encryption is different than Hashing? (https://www.geeksforgeeks.org/difference-between-hashing-and-encryption/)"
},
{
"code": null,
"e": 6568,
"s": 6441,
"text": "What are the problems faced by React? (https://www.growth-rocket.com/blog/a-closer-look-at-client-side-server-side-rendering/)"
},
{
"code": null,
"e": 6757,
"s": 6568,
"text": "Conclusion: Interviewers mainly focus on how you approach the question rather than you solved the problem completely. They engross more on DSA and dev is the edge point if you had done it."
},
{
"code": null,
"e": 6779,
"s": 6757,
"text": "HR Round(Telephonic):"
},
{
"code": null,
"e": 7062,
"s": 6779,
"text": "Questions like could have you done better in all previous rounds and how, what has been your greatest failure, what do you know about us or our company, and many more.This round was all about testing the candidate and what steps did I take up to tackle the above-mentioned problems."
},
{
"code": null,
"e": 7230,
"s": 7062,
"text": "Questions like could have you done better in all previous rounds and how, what has been your greatest failure, what do you know about us or our company, and many more."
},
{
"code": null,
"e": 7346,
"s": 7230,
"text": "This round was all about testing the candidate and what steps did I take up to tackle the above-mentioned problems."
},
{
"code": null,
"e": 7660,
"s": 7346,
"text": "Some more questions were asked. Be positive and aloud during the interview. Don’t be nervous and in rush to answer the question. Take your time. Interviewers are mainly nice and have a helping nature (in my case they were very nice, polite, helped me wherever I got stuck). Believe in yourself and always in God."
},
{
"code": null,
"e": 7732,
"s": 7660,
"text": "Thanks to GeeksforGeeks, HackerRank, HackerEarth, CodeChef, Codeforces."
},
{
"code": null,
"e": 7739,
"s": 7732,
"text": "Intuit"
},
{
"code": null,
"e": 7749,
"s": 7739,
"text": "Marketing"
},
{
"code": null,
"e": 7760,
"s": 7749,
"text": "Off-Campus"
},
{
"code": null,
"e": 7771,
"s": 7760,
"text": "Internship"
},
{
"code": null,
"e": 7793,
"s": 7771,
"text": "Interview Experiences"
},
{
"code": null,
"e": 7891,
"s": 7793,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7974,
"s": 7891,
"text": "Samsung R&D Bangalore (SRIB) Interview Experience | On- Campus for Internship 2021"
},
{
"code": null,
"e": 8020,
"s": 7974,
"text": "Microsoft Interview Experience for SWE Intern"
},
{
"code": null,
"e": 8065,
"s": 8020,
"text": "Zoho Interview Experience (Off-Campus ) 2022"
},
{
"code": null,
"e": 8114,
"s": 8065,
"text": "Google STEP Interview Experience Internship 2022"
},
{
"code": null,
"e": 8172,
"s": 8114,
"text": "Microsoft Interview Experience for SWE Intern (On-Campus)"
},
{
"code": null,
"e": 8199,
"s": 8172,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 8269,
"s": 8199,
"text": "Google SWE Interview Experience (Google Online Coding Challenge) 2022"
},
{
"code": null,
"e": 8301,
"s": 8269,
"text": "TCS Digital Interview Questions"
},
{
"code": null,
"e": 8374,
"s": 8301,
"text": "Samsung Interview Experience Research & Institute SRIB (Off-Campus) 2022"
}
] |
How do you set, clear, and toggle a bit in C/C++?
|
You can set clear and toggle bits using bitwise operators in C, C++, Python, and all other programming languages that support these operations. You also need to use the bitshift operator to get the bit to the right place.
To set a bit, we'll need to use the bitwise OR operator −
#include<iostream>
using namespace std;
int main() {
int i = 0, n;
// Enter bit to be set:
cin >> n;
i |= (1 << n); // Take OR of i and 1 shifted n positions
cout << i;
return 0;
}
If you enter 4, This will give the output −
16
because 16 is equivalent to 10000 in binary.
To clear a bit, we'll need to use the bitwise AND operator(&) and bitwise NOT operator(~) −
#include<iostream>
using namespace std;
int main() {
// i is 110 in binary
int i = 6, n;
// Enter bit to be cleared:
cin >> n;
i &= ~(1 << n); // Take OR of i and 1 shifted n positions negated
cout << i;
return 0;
}
If you enter 1, This will give the output −
4
because 110 becomes 100 which is equivalent to 4 in decimal.
To toggle a bit, we'll need to use the bitwise XOR operator(^) −
#include<iostream>
using namespace std;
int main() {
// i is 110 in binary
int i = 6, n;
// Enter bit to be toggled:
cin >> n;
i ^= (1 << n); // Take XOR of i and 1 shifted n positions
cout << i;
return 0;
}
If you enter 1, This will give the output −
4
because 110 becomes 100 which is equivalent to 4 in decimal.
|
[
{
"code": null,
"e": 1409,
"s": 1187,
"text": "You can set clear and toggle bits using bitwise operators in C, C++, Python, and all other programming languages that support these operations. You also need to use the bitshift operator to get the bit to the right place."
},
{
"code": null,
"e": 1467,
"s": 1409,
"text": "To set a bit, we'll need to use the bitwise OR operator −"
},
{
"code": null,
"e": 1670,
"s": 1467,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n int i = 0, n;\n \n // Enter bit to be set:\n cin >> n;\n i |= (1 << n); // Take OR of i and 1 shifted n positions\n cout << i;\n return 0;\n}"
},
{
"code": null,
"e": 1714,
"s": 1670,
"text": "If you enter 4, This will give the output −"
},
{
"code": null,
"e": 1717,
"s": 1714,
"text": "16"
},
{
"code": null,
"e": 1762,
"s": 1717,
"text": "because 16 is equivalent to 10000 in binary."
},
{
"code": null,
"e": 1854,
"s": 1762,
"text": "To clear a bit, we'll need to use the bitwise AND operator(&) and bitwise NOT operator(~) −"
},
{
"code": null,
"e": 2095,
"s": 1854,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n // i is 110 in binary\n int i = 6, n;\n \n // Enter bit to be cleared:\n cin >> n;\n i &= ~(1 << n); // Take OR of i and 1 shifted n positions negated\n cout << i;\n return 0;\n}"
},
{
"code": null,
"e": 2139,
"s": 2095,
"text": "If you enter 1, This will give the output −"
},
{
"code": null,
"e": 2141,
"s": 2139,
"text": "4"
},
{
"code": null,
"e": 2202,
"s": 2141,
"text": "because 110 becomes 100 which is equivalent to 4 in decimal."
},
{
"code": null,
"e": 2267,
"s": 2202,
"text": "To toggle a bit, we'll need to use the bitwise XOR operator(^) −"
},
{
"code": null,
"e": 2500,
"s": 2267,
"text": "#include<iostream>\nusing namespace std;\nint main() {\n // i is 110 in binary\n int i = 6, n;\n \n // Enter bit to be toggled:\n cin >> n;\n i ^= (1 << n); // Take XOR of i and 1 shifted n positions\n cout << i;\n return 0;\n}"
},
{
"code": null,
"e": 2544,
"s": 2500,
"text": "If you enter 1, This will give the output −"
},
{
"code": null,
"e": 2546,
"s": 2544,
"text": "4"
},
{
"code": null,
"e": 2607,
"s": 2546,
"text": "because 110 becomes 100 which is equivalent to 4 in decimal."
}
] |
Python program to repeat M characters of a string N times
|
04 Jan, 2021
In this article, the task is to write a Python program to repeat M characters of string N times.
Method 1:
Define a function that will take a word, m, n values as arguments.If M is greater than the length of the word. Set m value equal to the length of the wordNow store the characters needed to be repeated into a string named repeat_string using slicing.Initialize an empty string named as a resultConcatenate the repeat_string to result for n times.Now print the string.
Define a function that will take a word, m, n values as arguments.
If M is greater than the length of the word. Set m value equal to the length of the word
Now store the characters needed to be repeated into a string named repeat_string using slicing.
Initialize an empty string named as a result
Concatenate the repeat_string to result for n times.
Now print the string.
Below is the implementation:
Python3
def repeat(word, m, n): # if number of characters greater than length of word. # set number of characters = length of word if(m > len(word)): m = len(word) repeat_word = word[:m] result = "" for i in range(n): result = result+repeat_word print(result) # driver coderepeat("geeks", 2, 3)
Output:
gegege
Method 2:
Define a function which will take a word, m, n values as arguments.if M is greater than length of word. set m value equal to length of wordNow store the characters needed to be repeated into a string named repeat_string using slicing.Multiply the repeat_string with n.Now print the string.
Define a function which will take a word, m, n values as arguments.
if M is greater than length of word. set m value equal to length of word
Now store the characters needed to be repeated into a string named repeat_string using slicing.
Multiply the repeat_string with n.
Now print the string.
Python3
def repeat(word, m, n): # if number of characters greater than length of word. # set number of characters = length of word if(m > len(word)): m = len(word) repeat_word = word[:m] print(repeat_word*n) # driver coderepeat("geeks", 2, 3)
Output:
gegege
Picked
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jan, 2021"
},
{
"code": null,
"e": 125,
"s": 28,
"text": "In this article, the task is to write a Python program to repeat M characters of string N times."
},
{
"code": null,
"e": 135,
"s": 125,
"text": "Method 1:"
},
{
"code": null,
"e": 502,
"s": 135,
"text": "Define a function that will take a word, m, n values as arguments.If M is greater than the length of the word. Set m value equal to the length of the wordNow store the characters needed to be repeated into a string named repeat_string using slicing.Initialize an empty string named as a resultConcatenate the repeat_string to result for n times.Now print the string."
},
{
"code": null,
"e": 569,
"s": 502,
"text": "Define a function that will take a word, m, n values as arguments."
},
{
"code": null,
"e": 658,
"s": 569,
"text": "If M is greater than the length of the word. Set m value equal to the length of the word"
},
{
"code": null,
"e": 754,
"s": 658,
"text": "Now store the characters needed to be repeated into a string named repeat_string using slicing."
},
{
"code": null,
"e": 799,
"s": 754,
"text": "Initialize an empty string named as a result"
},
{
"code": null,
"e": 852,
"s": 799,
"text": "Concatenate the repeat_string to result for n times."
},
{
"code": null,
"e": 874,
"s": 852,
"text": "Now print the string."
},
{
"code": null,
"e": 903,
"s": 874,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 911,
"s": 903,
"text": "Python3"
},
{
"code": "def repeat(word, m, n): # if number of characters greater than length of word. # set number of characters = length of word if(m > len(word)): m = len(word) repeat_word = word[:m] result = \"\" for i in range(n): result = result+repeat_word print(result) # driver coderepeat(\"geeks\", 2, 3)",
"e": 1254,
"s": 911,
"text": null
},
{
"code": null,
"e": 1262,
"s": 1254,
"text": "Output:"
},
{
"code": null,
"e": 1269,
"s": 1262,
"text": "gegege"
},
{
"code": null,
"e": 1279,
"s": 1269,
"text": "Method 2:"
},
{
"code": null,
"e": 1569,
"s": 1279,
"text": "Define a function which will take a word, m, n values as arguments.if M is greater than length of word. set m value equal to length of wordNow store the characters needed to be repeated into a string named repeat_string using slicing.Multiply the repeat_string with n.Now print the string."
},
{
"code": null,
"e": 1637,
"s": 1569,
"text": "Define a function which will take a word, m, n values as arguments."
},
{
"code": null,
"e": 1710,
"s": 1637,
"text": "if M is greater than length of word. set m value equal to length of word"
},
{
"code": null,
"e": 1806,
"s": 1710,
"text": "Now store the characters needed to be repeated into a string named repeat_string using slicing."
},
{
"code": null,
"e": 1841,
"s": 1806,
"text": "Multiply the repeat_string with n."
},
{
"code": null,
"e": 1863,
"s": 1841,
"text": "Now print the string."
},
{
"code": null,
"e": 1871,
"s": 1863,
"text": "Python3"
},
{
"code": "def repeat(word, m, n): # if number of characters greater than length of word. # set number of characters = length of word if(m > len(word)): m = len(word) repeat_word = word[:m] print(repeat_word*n) # driver coderepeat(\"geeks\", 2, 3)",
"e": 2143,
"s": 1871,
"text": null
},
{
"code": null,
"e": 2151,
"s": 2143,
"text": "Output:"
},
{
"code": null,
"e": 2158,
"s": 2151,
"text": "gegege"
},
{
"code": null,
"e": 2165,
"s": 2158,
"text": "Picked"
},
{
"code": null,
"e": 2188,
"s": 2165,
"text": "Python string-programs"
},
{
"code": null,
"e": 2195,
"s": 2188,
"text": "Python"
},
{
"code": null,
"e": 2211,
"s": 2195,
"text": "Python Programs"
},
{
"code": null,
"e": 2309,
"s": 2211,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2351,
"s": 2309,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2373,
"s": 2351,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2399,
"s": 2373,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2431,
"s": 2399,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2460,
"s": 2431,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2503,
"s": 2460,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2525,
"s": 2503,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2564,
"s": 2525,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2602,
"s": 2564,
"text": "Python | Convert a list to dictionary"
}
] |
Program to convert first character uppercase in a sentence
|
21 Apr, 2022
Write a Java program to convert the first character uppercase in a sentence and if apart from the first character if any other character is in Uppercase then convert into Lowercase?
Examples:
Input : gEEKs
Output :Geeks
Input :GFG
Output :Gfg
Input : GeeksforGeeks
Output : Geeksforgeeks
Method 1:
C++
Java
Python3
C#
Javascript
// C++ program to convert// first character uppercase// in a sentence#include<bits/stdc++.h>using namespace std;string convert(string str){ for (int i = 0; i < str.length(); i++) { // If first character of a // word is found if (i == 0 && str[i] != ' ' || str[i] != ' ' && str[i - 1] == ' ') { // If it is in lower-case if (str[i] >= 'a' && str[i] <= 'z') { // Convert into Upper-case str[i] = (char)(str[i] - 'a' + 'A'); } } // If apart from first character // Any one is in Upper-case else if (str[i] >= 'A' && str[i] <= 'Z') // Convert into Lower-Case str[i] = (char)(str[i] + 'a' - 'A'); } return str;} // Driver codeint main(){ string str = "gEEks fOr GeeKs"; cout << (convert(str)); return 0;} // This code is contributed by Chitranayal
// Java program to convert first character// uppercase in a sentenceclass GFG { static String convert(String str) { // Create a char array of given String char ch[] = str.toCharArray(); for (int i = 0; i < str.length(); i++) { // If first character of a word is found if (i == 0 && ch[i] != ' ' || ch[i] != ' ' && ch[i - 1] == ' ') { // If it is in lower-case if (ch[i] >= 'a' && ch[i] <= 'z') { // Convert into Upper-case ch[i] = (char)(ch[i] - 'a' + 'A'); } } // If apart from first character // Any one is in Upper-case else if (ch[i] >= 'A' && ch[i] <= 'Z') // Convert into Lower-Case ch[i] = (char)(ch[i] + 'a' - 'A'); } // Convert the char array to equivalent String String st = new String(ch); return st; } public static void main(String[] args) { String str = "gEEks fOr GeeKs"; System.out.println(convert(str)); }}
# Python3 program to convert first character# uppercase in a sentencedef convert(s): # Create a char array of # given string ch = list(s) for i in range(len(s)): # If first character of a word is found if (i == 0 and ch[i] != ' ' or ch[i] != ' ' and ch[i - 1] == ' '): # If it is in lower-case if (ch[i] >= 'a' and ch[i] <= 'z'): # Convert into Upper-case ch[i] = chr(ord(ch[i]) - ord('a') + ord('A')) # If apart from first character # Any one is in Upper-case elif (ch[i] >= 'A' and ch[i] <= 'Z'): # Convert into Lower-Case ch[i] = chr(ord(ch[i]) + ord('a') - ord('A')) # Convert the char array # to equivalent string st = "".join(ch) return st; # Driver code if __name__=="__main__": s = "gEEks fOr GeeKs" print(convert(s)); # This code is contributed by rutvik_56
// C# program to convert first character// uppercase in a sentenceusing System; class GFG { static String convert(String str) { // Create a char array of // given String char []ch = str.ToCharArray(); for (int i = 0; i < str.Length; i++) { // If first character of a // word is found if (i == 0 && ch[i] != ' ' || ch[i] != ' ' && ch[i - 1] == ' ') { // If it is in lower-case if (ch[i] >= 'a' && ch[i] <= 'z') { // Convert into Upper-case ch[i] = (char)(ch[i] - 'a' + 'A'); } } // If apart from first character // Any one is in Upper-case else if (ch[i] >= 'A' && ch[i] <= 'Z') // Convert into Lower-Case ch[i] = (char)(ch[i] + 'a' - 'A'); } // Convert the char array to // equivalent String String st = new String(ch); return st; } // Driver code public static void Main() { String str = "gEEks fOr GeeKs"; Console.Write(convert(str)); }} // This code is contributed by Nitin Mittal.
<script>// Javascript program to convert first character// uppercase in a sentence function convert(str) { // Create a char array of given String let ch = str.split(""); for (let i = 0; i < str.length; i++) { // If first character of a word is found if (i == 0 && ch[i] != ' ' || ch[i] != ' ' && ch[i - 1] == ' ') { // If it is in lower-case if (ch[i] >= 'a' && ch[i] <= 'z') { // Convert into Upper-case ch[i] = String.fromCharCode(ch[i].charCodeAt(0) - 'a'.charCodeAt(0) + 'A'.charCodeAt(0)); } } // If apart from first character // Any one is in Upper-case else if (ch[i] >= 'A' && ch[i] <= 'Z') // Convert into Lower-Case ch[i] = String.fromCharCode(ch[i].charCodeAt(0) + 'a'.charCodeAt(0) - 'A'.charCodeAt(0)); } // Convert the char array to equivalent String let st = (ch).join(""); return st; } let str = "gEEks fOr GeeKs"; document.write(convert(str)); // This code is contributed by avanitrachhadiya2155</script>
Output:
Geeks For Geeks
Method 2: Using Java Inbuilt methods To capitalize each word, call the toLowerCase() method to put the string in lowercase format. Iterate the string, if any space if found in the previous iteration and the current element is not space then call the toUpperCase() method to put the first letter of the word in uppercase format and append the string in the buffer.
Below is the implementation:
Java
// Java Program to capitalize each word in a stringpublic class GFG { // Method to convert the string static String capitailizeWord(String str) { StringBuffer s = new StringBuffer(); // Declare a character of space // To identify that the next character is the starting // of a new word char ch = ' '; for (int i = 0; i < str.length(); i++) { // If previous character is space and current // character is not space then it shows that // current letter is the starting of the word if (ch == ' ' && str.charAt(i) != ' ') s.append(Character.toUpperCase(str.charAt(i))); else s.append(str.charAt(i)); ch = str.charAt(i); } // Return the string with trimming return s.toString().trim(); } // Driver Code public static void main(String args[]) { // Declare the string String s1 = "gEEks fOr GeeKs"; // Convert that string into lowercase s1 = s1.toLowerCase(); // Call the method to capitalize each word System.out.println(capitailizeWord(s1)); }}
Method 3 : Using Python3
Approach : We can create a list of all the words in a sentence (say string_array). After creating string_array, if we directly work upon that list and try to change the lowercase starting characters of words, we will get an error ” ‘str’ object does not support item assignment“. To avoid this we can create a list of ASCII values (say ascii_array) of characters corresponding to the characters in string_array.
We can easily work upon ascii_array and convert the starting lowercase characters of words to uppercase by simply subtracting 32 from their ASCII value. After changing the values in ascii_array, we convert each ASCII value in ascii_array to their corresponding characters by using chr() function. chr() function returns the character corresponding to the ASCII value passed in parameters. This way we will obtain a list of capitalized strings.
Below is the implementation of the above approach
Python3
# Python program to capitalize the# first character of each word in a sentence # Function definitiondef solve (st): ascii_array = [] # creating a list of ascii values # of all the characters in the sentence for i in range (0, len (st)): ascii_array.append (ord (st[i])) # check if the first character of # each word is a lowercase character. # To convert a lowercase character to an # uppercase character, we subtract 32 from # the ASCII value of lowercase character. if ascii_array[0] >= 97 and ascii_array[0] <= 122 : ascii_array[0] = ascii_array[0] - 32 # create an empty list which will store # the characters corresponding to the # ascii values in ascii_array newlist = [] newlist.append (chr (ascii_array[0])) for i in range (1, len (ascii_array)): # 32 is the ascii value for 'space' or ' '. # so we use this condition to check for # the next word in the sentence # as in a sentence we have space separated words if ascii_array[i] == 32: if ascii_array[i + 1] >= 97 and ascii_array[i+1] <= 122: ascii_array[i + 1] = ascii_array[i+1] - 32 newlist.append (chr (ascii_array[i])) # in the end, we return a string after # joining the values obtained in newlist return (''.join (newlist)) # Driver Codestring = 'geeks for geeks'result = solve (string)print (result)# This code is contributed by Kishan Mishra
Geeks For Geeks
nitin mittal
bilal-hungund
mishrakishan1
rutvik_56
ukasp
avanitrachhadiya2155
simmytarika5
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Stream 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": 52,
"s": 24,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 234,
"s": 52,
"text": "Write a Java program to convert the first character uppercase in a sentence and if apart from the first character if any other character is in Uppercase then convert into Lowercase?"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "Examples: "
},
{
"code": null,
"e": 344,
"s": 245,
"text": "Input : gEEKs\nOutput :Geeks\n\nInput :GFG\nOutput :Gfg\n\n\nInput : GeeksforGeeks\nOutput : Geeksforgeeks"
},
{
"code": null,
"e": 355,
"s": 344,
"text": "Method 1: "
},
{
"code": null,
"e": 359,
"s": 355,
"text": "C++"
},
{
"code": null,
"e": 364,
"s": 359,
"text": "Java"
},
{
"code": null,
"e": 372,
"s": 364,
"text": "Python3"
},
{
"code": null,
"e": 375,
"s": 372,
"text": "C#"
},
{
"code": null,
"e": 386,
"s": 375,
"text": "Javascript"
},
{
"code": "// C++ program to convert// first character uppercase// in a sentence#include<bits/stdc++.h>using namespace std;string convert(string str){ for (int i = 0; i < str.length(); i++) { // If first character of a // word is found if (i == 0 && str[i] != ' ' || str[i] != ' ' && str[i - 1] == ' ') { // If it is in lower-case if (str[i] >= 'a' && str[i] <= 'z') { // Convert into Upper-case str[i] = (char)(str[i] - 'a' + 'A'); } } // If apart from first character // Any one is in Upper-case else if (str[i] >= 'A' && str[i] <= 'Z') // Convert into Lower-Case str[i] = (char)(str[i] + 'a' - 'A'); } return str;} // Driver codeint main(){ string str = \"gEEks fOr GeeKs\"; cout << (convert(str)); return 0;} // This code is contributed by Chitranayal",
"e": 1236,
"s": 386,
"text": null
},
{
"code": "// Java program to convert first character// uppercase in a sentenceclass GFG { static String convert(String str) { // Create a char array of given String char ch[] = str.toCharArray(); for (int i = 0; i < str.length(); i++) { // If first character of a word is found if (i == 0 && ch[i] != ' ' || ch[i] != ' ' && ch[i - 1] == ' ') { // If it is in lower-case if (ch[i] >= 'a' && ch[i] <= 'z') { // Convert into Upper-case ch[i] = (char)(ch[i] - 'a' + 'A'); } } // If apart from first character // Any one is in Upper-case else if (ch[i] >= 'A' && ch[i] <= 'Z') // Convert into Lower-Case ch[i] = (char)(ch[i] + 'a' - 'A'); } // Convert the char array to equivalent String String st = new String(ch); return st; } public static void main(String[] args) { String str = \"gEEks fOr GeeKs\"; System.out.println(convert(str)); }}",
"e": 2355,
"s": 1236,
"text": null
},
{
"code": "# Python3 program to convert first character# uppercase in a sentencedef convert(s): # Create a char array of # given string ch = list(s) for i in range(len(s)): # If first character of a word is found if (i == 0 and ch[i] != ' ' or ch[i] != ' ' and ch[i - 1] == ' '): # If it is in lower-case if (ch[i] >= 'a' and ch[i] <= 'z'): # Convert into Upper-case ch[i] = chr(ord(ch[i]) - ord('a') + ord('A')) # If apart from first character # Any one is in Upper-case elif (ch[i] >= 'A' and ch[i] <= 'Z'): # Convert into Lower-Case ch[i] = chr(ord(ch[i]) + ord('a') - ord('A')) # Convert the char array # to equivalent string st = \"\".join(ch) return st; # Driver code if __name__==\"__main__\": s = \"gEEks fOr GeeKs\" print(convert(s)); # This code is contributed by rutvik_56",
"e": 3402,
"s": 2355,
"text": null
},
{
"code": "// C# program to convert first character// uppercase in a sentenceusing System; class GFG { static String convert(String str) { // Create a char array of // given String char []ch = str.ToCharArray(); for (int i = 0; i < str.Length; i++) { // If first character of a // word is found if (i == 0 && ch[i] != ' ' || ch[i] != ' ' && ch[i - 1] == ' ') { // If it is in lower-case if (ch[i] >= 'a' && ch[i] <= 'z') { // Convert into Upper-case ch[i] = (char)(ch[i] - 'a' + 'A'); } } // If apart from first character // Any one is in Upper-case else if (ch[i] >= 'A' && ch[i] <= 'Z') // Convert into Lower-Case ch[i] = (char)(ch[i] + 'a' - 'A'); } // Convert the char array to // equivalent String String st = new String(ch); return st; } // Driver code public static void Main() { String str = \"gEEks fOr GeeKs\"; Console.Write(convert(str)); }} // This code is contributed by Nitin Mittal.",
"e": 4662,
"s": 3402,
"text": null
},
{
"code": "<script>// Javascript program to convert first character// uppercase in a sentence function convert(str) { // Create a char array of given String let ch = str.split(\"\"); for (let i = 0; i < str.length; i++) { // If first character of a word is found if (i == 0 && ch[i] != ' ' || ch[i] != ' ' && ch[i - 1] == ' ') { // If it is in lower-case if (ch[i] >= 'a' && ch[i] <= 'z') { // Convert into Upper-case ch[i] = String.fromCharCode(ch[i].charCodeAt(0) - 'a'.charCodeAt(0) + 'A'.charCodeAt(0)); } } // If apart from first character // Any one is in Upper-case else if (ch[i] >= 'A' && ch[i] <= 'Z') // Convert into Lower-Case ch[i] = String.fromCharCode(ch[i].charCodeAt(0) + 'a'.charCodeAt(0) - 'A'.charCodeAt(0)); } // Convert the char array to equivalent String let st = (ch).join(\"\"); return st; } let str = \"gEEks fOr GeeKs\"; document.write(convert(str)); // This code is contributed by avanitrachhadiya2155</script>",
"e": 5887,
"s": 4662,
"text": null
},
{
"code": null,
"e": 5896,
"s": 5887,
"text": "Output: "
},
{
"code": null,
"e": 5912,
"s": 5896,
"text": "Geeks For Geeks"
},
{
"code": null,
"e": 6277,
"s": 5912,
"text": "Method 2: Using Java Inbuilt methods To capitalize each word, call the toLowerCase() method to put the string in lowercase format. Iterate the string, if any space if found in the previous iteration and the current element is not space then call the toUpperCase() method to put the first letter of the word in uppercase format and append the string in the buffer. "
},
{
"code": null,
"e": 6306,
"s": 6277,
"text": "Below is the implementation:"
},
{
"code": null,
"e": 6311,
"s": 6306,
"text": "Java"
},
{
"code": "// Java Program to capitalize each word in a stringpublic class GFG { // Method to convert the string static String capitailizeWord(String str) { StringBuffer s = new StringBuffer(); // Declare a character of space // To identify that the next character is the starting // of a new word char ch = ' '; for (int i = 0; i < str.length(); i++) { // If previous character is space and current // character is not space then it shows that // current letter is the starting of the word if (ch == ' ' && str.charAt(i) != ' ') s.append(Character.toUpperCase(str.charAt(i))); else s.append(str.charAt(i)); ch = str.charAt(i); } // Return the string with trimming return s.toString().trim(); } // Driver Code public static void main(String args[]) { // Declare the string String s1 = \"gEEks fOr GeeKs\"; // Convert that string into lowercase s1 = s1.toLowerCase(); // Call the method to capitalize each word System.out.println(capitailizeWord(s1)); }}",
"e": 7491,
"s": 6311,
"text": null
},
{
"code": null,
"e": 7517,
"s": 7491,
"text": "Method 3 : Using Python3 "
},
{
"code": null,
"e": 7929,
"s": 7517,
"text": "Approach : We can create a list of all the words in a sentence (say string_array). After creating string_array, if we directly work upon that list and try to change the lowercase starting characters of words, we will get an error ” ‘str’ object does not support item assignment“. To avoid this we can create a list of ASCII values (say ascii_array) of characters corresponding to the characters in string_array."
},
{
"code": null,
"e": 8373,
"s": 7929,
"text": "We can easily work upon ascii_array and convert the starting lowercase characters of words to uppercase by simply subtracting 32 from their ASCII value. After changing the values in ascii_array, we convert each ASCII value in ascii_array to their corresponding characters by using chr() function. chr() function returns the character corresponding to the ASCII value passed in parameters. This way we will obtain a list of capitalized strings."
},
{
"code": null,
"e": 8424,
"s": 8373,
"text": "Below is the implementation of the above approach "
},
{
"code": null,
"e": 8432,
"s": 8424,
"text": "Python3"
},
{
"code": "# Python program to capitalize the# first character of each word in a sentence # Function definitiondef solve (st): ascii_array = [] # creating a list of ascii values # of all the characters in the sentence for i in range (0, len (st)): ascii_array.append (ord (st[i])) # check if the first character of # each word is a lowercase character. # To convert a lowercase character to an # uppercase character, we subtract 32 from # the ASCII value of lowercase character. if ascii_array[0] >= 97 and ascii_array[0] <= 122 : ascii_array[0] = ascii_array[0] - 32 # create an empty list which will store # the characters corresponding to the # ascii values in ascii_array newlist = [] newlist.append (chr (ascii_array[0])) for i in range (1, len (ascii_array)): # 32 is the ascii value for 'space' or ' '. # so we use this condition to check for # the next word in the sentence # as in a sentence we have space separated words if ascii_array[i] == 32: if ascii_array[i + 1] >= 97 and ascii_array[i+1] <= 122: ascii_array[i + 1] = ascii_array[i+1] - 32 newlist.append (chr (ascii_array[i])) # in the end, we return a string after # joining the values obtained in newlist return (''.join (newlist)) # Driver Codestring = 'geeks for geeks'result = solve (string)print (result)# This code is contributed by Kishan Mishra",
"e": 9914,
"s": 8432,
"text": null
},
{
"code": null,
"e": 9930,
"s": 9914,
"text": "Geeks For Geeks"
},
{
"code": null,
"e": 9945,
"s": 9932,
"text": "nitin mittal"
},
{
"code": null,
"e": 9959,
"s": 9945,
"text": "bilal-hungund"
},
{
"code": null,
"e": 9973,
"s": 9959,
"text": "mishrakishan1"
},
{
"code": null,
"e": 9983,
"s": 9973,
"text": "rutvik_56"
},
{
"code": null,
"e": 9989,
"s": 9983,
"text": "ukasp"
},
{
"code": null,
"e": 10010,
"s": 9989,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 10023,
"s": 10010,
"text": "simmytarika5"
},
{
"code": null,
"e": 10028,
"s": 10023,
"text": "Java"
},
{
"code": null,
"e": 10042,
"s": 10028,
"text": "Java Programs"
},
{
"code": null,
"e": 10047,
"s": 10042,
"text": "Java"
},
{
"code": null,
"e": 10145,
"s": 10047,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10176,
"s": 10145,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 10195,
"s": 10176,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 10225,
"s": 10195,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 10243,
"s": 10225,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 10258,
"s": 10243,
"text": "Stream In Java"
},
{
"code": null,
"e": 10286,
"s": 10258,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 10312,
"s": 10286,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 10356,
"s": 10312,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 10390,
"s": 10356,
"text": "Convert Double to Integer in Java"
}
] |
Python PIL | GaussianBlur() method
|
14 Jul, 2019
PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method.
PIL.ImageFilter.GaussianBlur() method create Gaussian blur filter.
Syntax: PIL.ImageFilter.GaussianBlur(radius=5)
Parameters:radius – blur radius. Changing value of radius the different intensity of GaussianBlur image were obtain.
Returns type: An image.
Image Used:
# Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image object im1 = Image.open(r"C:\Users\System-Pc\Desktop\leave.JPG") # applying the Gaussian Blur filter im2 = im1.filter(ImageFilter.GaussianBlur(radius = 5)) im2.show()
Output:
radius:radius value used here is 2.
Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image object im1 = Image.open(r"C:\Users\System-Pc\Desktop\leave.JPG") # applying the Gaussian Blur filter im2 = im1.filter(ImageFilter.GaussianBlur(radius = 2)) im2.show()
Output:
Python-pil
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n14 Jul, 2019"
},
{
"code": null,
"e": 286,
"s": 53,
"text": "PIL is the Python Imaging Library which provides the python interpreter with image editing capabilities. The ImageFilter module contains definitions for a pre-defined set of filters, which can be used with the Image.filter() method."
},
{
"code": null,
"e": 353,
"s": 286,
"text": "PIL.ImageFilter.GaussianBlur() method create Gaussian blur filter."
},
{
"code": null,
"e": 400,
"s": 353,
"text": "Syntax: PIL.ImageFilter.GaussianBlur(radius=5)"
},
{
"code": null,
"e": 517,
"s": 400,
"text": "Parameters:radius – blur radius. Changing value of radius the different intensity of GaussianBlur image were obtain."
},
{
"code": null,
"e": 541,
"s": 517,
"text": "Returns type: An image."
},
{
"code": null,
"e": 553,
"s": 541,
"text": "Image Used:"
},
{
"code": " # Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image object im1 = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\leave.JPG\") # applying the Gaussian Blur filter im2 = im1.filter(ImageFilter.GaussianBlur(radius = 5)) im2.show() ",
"e": 843,
"s": 553,
"text": null
},
{
"code": null,
"e": 851,
"s": 843,
"text": "Output:"
},
{
"code": null,
"e": 887,
"s": 851,
"text": "radius:radius value used here is 2."
},
{
"code": "Importing Image and ImageFilter module from PIL package from PIL import Image, ImageFilter # creating a image object im1 = Image.open(r\"C:\\Users\\System-Pc\\Desktop\\leave.JPG\") # applying the Gaussian Blur filter im2 = im1.filter(ImageFilter.GaussianBlur(radius = 2)) im2.show() ",
"e": 1170,
"s": 887,
"text": null
},
{
"code": null,
"e": 1178,
"s": 1170,
"text": "Output:"
},
{
"code": null,
"e": 1189,
"s": 1178,
"text": "Python-pil"
},
{
"code": null,
"e": 1196,
"s": 1189,
"text": "Python"
}
] |
Natural Language Programming
|
14 Nov, 2019
Having programmed for many years in many languages, I often find myself thinking in English pseudo-code, then I translate my thoughts into whatever artificial syntax I’m working with at the time. So one day I thought, “Why not simply code at a natural language level and skip the translation step?” My elder son (also a programmer) and I talked it over, and we decided to test the theory. Specifically, we wanted to know:
1. Is it easier to program when you don’t have to translate your natural-language thoughts into an alternate syntax?
2. Can natural languages be parsed in a relatively “sloppy” manner (as humans apparently parse them) and still provide a stable enough environment for productive programming?
3. Can low-level programs (like compilers) be conveniently and efficiently written in high level languages (like English)?
And so we set about developing a Plain English compiler (in Plain English) in the interest of answering those questions. And we are happy to report that we can now answer each of those three questions, from direct experience, with a resounding, “Yes!”
The Theory
Our parser operates, we believe, something like the parsing centers in the human brain. Consider, for example, a father saying to his baby son...
“Want to suck on this bottle, little guy?”
...and the kid hears...
“blah, blah, SUCK, blah, blah, BOTTLE, blah, blah.”
...but he properly responds because he’s got a “picture” of a bottle in the right side of his head connected to the word “bottle” on the left side, and a pre-existing “skill” near the back of his neck connected to the term “suck.” In other words, the kid matches what he can with the pictures (types) and skills (routines) he’s accumulated, and simply disregards the rest. Our compiler does very much the same thing, with new pictures (types) and skills (routines) being defined — not by us, but — by the programmer, as he writes new application code.
The Practice
A typical type definition looks like this:
A polygon is a thing with some vertices.
Internally, the name “polygon” is now associated with a dynamically-allocated structure that contains a doubly-linked list of vertices. “Vertex” is defined elsewhere (before or after this definition) in a similar fashion; the plural is automatically understood.
A typical routine looks like this:
To append an x coord and a y coord to a polygon:
Create a vertex given the x and the y.
Append the vertex to the polygon’s vertices.
Note that formal names (proper nouns) are not required for parameters and variables. This, we believe, is a major insight. A real-world chair or table is never (in normal conversation) called “c” or “myTable” — we refer to such things simply as “the chair” or “the table”. Likewise here: “the vertex” and “the polygon” are the most natural names for these variables.
Note also that spaces are allowed in routine and variable names (like “x coord”). It’s surprising that all languages don’t support this feature; this is the 21st century, after all. Note also that “nicknames” are also allowed (such as “x” for “x coord”). And that possessives (“polygon’s vertices”) are used in a very natural way to reference fields within records.
Note, as well, that the word “given” could have been “using” or “with” or any other equivalent since our sloppy parsing focuses on the pictures (types) and skills (routines) needed for understanding, and ignores, as much as possible, the rest.
Like a Math Book
At the lowest level, things look like this:
To add a number to another number:
Intel $8B85080000008B008B9D0C0000000103.
Note that in this case we have both the highest and lowest of languages — English and machine code (in hexadecimal) — in a single routine. The insight here is that a program should be written primarily in a natural language, with snippets of code in more appropriate syntax as (and only as) required. Like a typical math book: mostly natural language with formula snippets interspersed.
We hope someday the technology will be extended, at the high end, to include Plain Spanish, and Plain French, and Plain German, etc; and at the low end to include “snippet parsers” for the most useful, domain-specific languages.
An Objection Answered
Now perhaps you’re thinking natural language programming is a silly idea. But have you considered the fact that most of the code in most programs does simple stuff like “move this over there” and “show that on the screen” — things that can be most conveniently and most naturally expressed in a natural language? Let’s consider an example we can examine in detail:
Our compiler — a sophisticated Plain-English-to-Executable-Machine-Code translator — has 3,050 imperative sentences in it.
1,306 of those (about 42%) are conditional statements, and at least half of those are trivial things like these:
If the item is not found, break.
If the compiler's abort flag is set, exit.
The remainder of those conditional statements are slightly more complex, but all of them fit on a single line. Here are a couple of the longer ones:
If the length is 4, attach $FF32 to the fragment's code; exit.
If the rider's token is any numeric literal, compile the literal given the rider; exit.
Of the remaining sentences:
272 (about 9%) are simple assignment statements:
Put the type name into the field's type name.
202 (about 7%) are just the infrastructure for various loops:
Loop.
Get a field from the type's fields.
[ other stuff here]
Repeat.
183 (6%) simply add something to the end of this or that list, like so:
Add the field to the type's fields.
164 (about 5%) are trivial statements used to return boolean results, start and stop various timers, show the program’s current status, and write interesting things to the compiler’s output listing.
Say no.
Say yes.
Set the variable's compiled flag.
Start the compiler's timer.
Stop the compiler's timer.
Show status "Compiling...".
List the globals in the compiler's listing.
119 (about 4%) advance the focus in the source code, sentences like:
Bump the rider.
Move the rider (code rules).
92 (about 3%) are used to create, destroy and keep internal indexes up to date, sentences like:
Create the type index using 7919 for the bucket count.
Index the type given the type's name.
Destroy the type index.
58 (about 2%) are used to find things in various lists:
Find a variable given the name.
37 (about 1%) are calls to various conversion routines:
Convert the rider's token to a ratio.
31 (about 1%) are used to generate actual machine code (plus those that appear in conditional statements, as above):
Attach $E8 and the address to the fragment.
And that accounts for 80% of the code in our compiler.
Only 57 of the remaining sentences (less than 2% of the whole) are mathematical in nature, a line here and there like these:
Add 4 to the routine's parameter size.
Subtract the length from the local's offset.
Multiply the type's scale by the base type's scale.
Calculate the length of the field's type.
Round the address up to the nearest multiple of 4096.
And the rest are not formulaic at all. Stuff like:
Copy the field into another field.
Append the fragment to the current routine's fragments.
Abort with "I was hoping for a definition but all I found was '" then the token.
Initialize the compiler.
Remove any trailing backslashes from the path name.
Reduce the monikette's type to a type for utility use.
Eliminate duplicate nicknames from the type's fields.
Prepend "original " to the term's name.
Extend the name with the rider's token.
Unquote the other string.
Read the source file's path into the source file's buffer.
Generate the literal's name.
Extract a file name from the compiler's abort path.
Write the compiler's exe to the compiler's exe path.
Swap the monikettes with the other monikettes.
Skip any leading noise in the substring.
Scrub the utility index.
Fill the compiler's exe with the null byte given the compiler's exe size.
Position the rider's token on the rider's source.
Pluralize the type's plural name.
Link.
Finalize the compiler.
Check for invalid optional info on the type.
And that’s why we say that most of what most programs do is easy stuff, stuff that can be conveniently expressed in a natural language. And that, in turn, is why we like programming in Plain English: the thoughts in our heads are typed in as Plain English “pseudo code” and, with a tweak here and there, that pseudo code actually compiles and runs. And is self-documenting, to boot.
Another Objection Answered
You may be thinking that natural language is just too verbose for programming. But is it really that bad? Let’s consider a couple of examples. In a traditional programming language, we might draw a box using a statement like this:
substring.draw ( box, color, source.text.font, source.text.alignment ) ;
Which is 10 words and 11 punctuation marks: 21 total elements.
The Plain English equivalent would be:
Draw the substring in the box with the color and the source's text's font and alignment.
Which is 16 words and 3 punctuation marks: 19 total elements.
Admittedly, the Plain English version requires a few more easy-to-type alphabetic characters (it’s difficult to say exactly how many since traditional coders put spaces in different places); but that’s a small price to pay for not having to learn (or think in) an artificial syntax.
Here’s another example:
if ( ! source.colorized ( ) ) color = black ;
Which is 5 words and 8 punctuation marks: 13 total elements.
Compared with the Plain English:
If the source is not colorized, put black into the color.
Which is 11 words and 2 punctuation marks: 13 total elements.
Again, it’s mostly a matter of whether you like to type words or (specialized) punctuation. And whether you like to think in two different syntactical and grammatical forms simultaneously. And whether you want your code to be self-documenting. And whether you want code that’s friendly for beginners. Andwhether you want to code in a language (like English) that will still be in common use 100 yearsfrom now. Personally, we think you may have lost some human perspective if you’ve come to think that “(!source.colorized())” is a good way of saying anything!
The Prototype
If you’re interested, you can download the whole shebang here:
www.osmosian.com/cal-4700.zip
It’s a small Windows program, less than a megabyte in size. But it’s a complete development environment, including a unique interface, a simplified file manager, an elegant text editor, a handy hexadecimal dumper, a native-code-generating compiler/linker, and even a wysiwyg page layout facility (that we used to produce the documentation). It is written entirely in Plain English. The source code (about 25,000 sentences) is included in the download. No installation is necessary; just unzip. Start with the “instructions.pdf” in the “documentation” directory and before you go ten pages you won’t just be writing “Hello, World!” to the screen, you’ll be re-compiling the entire thing in itself (in less than three seconds on a bottom-of-the-line machine from Walmart).
Thanks for your time and interest.
Gerry RzeppaGrand Negus of the Osmosian Order of Plain English Programmers
Dan RzeppaPrime Assembler of the Osmosian Order of Plain English Programmers
Akanksha_Rai
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
What is Hashing | A Complete Tutorial
How to Learn Data Science in 10 weeks?
GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?
Types of Software Testing
GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa
What is Data Structure: Types, Classifications and Applications
Roadmap to Learn JavaScript For Beginners
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Nov, 2019"
},
{
"code": null,
"e": 474,
"s": 52,
"text": "Having programmed for many years in many languages, I often find myself thinking in English pseudo-code, then I translate my thoughts into whatever artificial syntax I’m working with at the time. So one day I thought, “Why not simply code at a natural language level and skip the translation step?” My elder son (also a programmer) and I talked it over, and we decided to test the theory. Specifically, we wanted to know:"
},
{
"code": null,
"e": 591,
"s": 474,
"text": "1. Is it easier to program when you don’t have to translate your natural-language thoughts into an alternate syntax?"
},
{
"code": null,
"e": 766,
"s": 591,
"text": "2. Can natural languages be parsed in a relatively “sloppy” manner (as humans apparently parse them) and still provide a stable enough environment for productive programming?"
},
{
"code": null,
"e": 889,
"s": 766,
"text": "3. Can low-level programs (like compilers) be conveniently and efficiently written in high level languages (like English)?"
},
{
"code": null,
"e": 1141,
"s": 889,
"text": "And so we set about developing a Plain English compiler (in Plain English) in the interest of answering those questions. And we are happy to report that we can now answer each of those three questions, from direct experience, with a resounding, “Yes!”"
},
{
"code": null,
"e": 1152,
"s": 1141,
"text": "The Theory"
},
{
"code": null,
"e": 1298,
"s": 1152,
"text": "Our parser operates, we believe, something like the parsing centers in the human brain. Consider, for example, a father saying to his baby son..."
},
{
"code": null,
"e": 1341,
"s": 1298,
"text": "“Want to suck on this bottle, little guy?”"
},
{
"code": null,
"e": 1365,
"s": 1341,
"text": "...and the kid hears..."
},
{
"code": null,
"e": 1417,
"s": 1365,
"text": "“blah, blah, SUCK, blah, blah, BOTTLE, blah, blah.”"
},
{
"code": null,
"e": 1969,
"s": 1417,
"text": "...but he properly responds because he’s got a “picture” of a bottle in the right side of his head connected to the word “bottle” on the left side, and a pre-existing “skill” near the back of his neck connected to the term “suck.” In other words, the kid matches what he can with the pictures (types) and skills (routines) he’s accumulated, and simply disregards the rest. Our compiler does very much the same thing, with new pictures (types) and skills (routines) being defined — not by us, but — by the programmer, as he writes new application code."
},
{
"code": null,
"e": 1982,
"s": 1969,
"text": "The Practice"
},
{
"code": null,
"e": 2025,
"s": 1982,
"text": "A typical type definition looks like this:"
},
{
"code": null,
"e": 2066,
"s": 2025,
"text": "A polygon is a thing with some vertices."
},
{
"code": null,
"e": 2328,
"s": 2066,
"text": "Internally, the name “polygon” is now associated with a dynamically-allocated structure that contains a doubly-linked list of vertices. “Vertex” is defined elsewhere (before or after this definition) in a similar fashion; the plural is automatically understood."
},
{
"code": null,
"e": 2363,
"s": 2328,
"text": "A typical routine looks like this:"
},
{
"code": null,
"e": 2496,
"s": 2363,
"text": "To append an x coord and a y coord to a polygon:\nCreate a vertex given the x and the y.\nAppend the vertex to the polygon’s vertices."
},
{
"code": null,
"e": 2863,
"s": 2496,
"text": "Note that formal names (proper nouns) are not required for parameters and variables. This, we believe, is a major insight. A real-world chair or table is never (in normal conversation) called “c” or “myTable” — we refer to such things simply as “the chair” or “the table”. Likewise here: “the vertex” and “the polygon” are the most natural names for these variables."
},
{
"code": null,
"e": 3229,
"s": 2863,
"text": "Note also that spaces are allowed in routine and variable names (like “x coord”). It’s surprising that all languages don’t support this feature; this is the 21st century, after all. Note also that “nicknames” are also allowed (such as “x” for “x coord”). And that possessives (“polygon’s vertices”) are used in a very natural way to reference fields within records."
},
{
"code": null,
"e": 3473,
"s": 3229,
"text": "Note, as well, that the word “given” could have been “using” or “with” or any other equivalent since our sloppy parsing focuses on the pictures (types) and skills (routines) needed for understanding, and ignores, as much as possible, the rest."
},
{
"code": null,
"e": 3490,
"s": 3473,
"text": "Like a Math Book"
},
{
"code": null,
"e": 3534,
"s": 3490,
"text": "At the lowest level, things look like this:"
},
{
"code": null,
"e": 3610,
"s": 3534,
"text": "To add a number to another number:\nIntel $8B85080000008B008B9D0C0000000103."
},
{
"code": null,
"e": 3997,
"s": 3610,
"text": "Note that in this case we have both the highest and lowest of languages — English and machine code (in hexadecimal) — in a single routine. The insight here is that a program should be written primarily in a natural language, with snippets of code in more appropriate syntax as (and only as) required. Like a typical math book: mostly natural language with formula snippets interspersed."
},
{
"code": null,
"e": 4226,
"s": 3997,
"text": "We hope someday the technology will be extended, at the high end, to include Plain Spanish, and Plain French, and Plain German, etc; and at the low end to include “snippet parsers” for the most useful, domain-specific languages."
},
{
"code": null,
"e": 4248,
"s": 4226,
"text": "An Objection Answered"
},
{
"code": null,
"e": 4613,
"s": 4248,
"text": "Now perhaps you’re thinking natural language programming is a silly idea. But have you considered the fact that most of the code in most programs does simple stuff like “move this over there” and “show that on the screen” — things that can be most conveniently and most naturally expressed in a natural language? Let’s consider an example we can examine in detail:"
},
{
"code": null,
"e": 4736,
"s": 4613,
"text": "Our compiler — a sophisticated Plain-English-to-Executable-Machine-Code translator — has 3,050 imperative sentences in it."
},
{
"code": null,
"e": 4849,
"s": 4736,
"text": "1,306 of those (about 42%) are conditional statements, and at least half of those are trivial things like these:"
},
{
"code": null,
"e": 4925,
"s": 4849,
"text": "If the item is not found, break.\nIf the compiler's abort flag is set, exit."
},
{
"code": null,
"e": 5074,
"s": 4925,
"text": "The remainder of those conditional statements are slightly more complex, but all of them fit on a single line. Here are a couple of the longer ones:"
},
{
"code": null,
"e": 5225,
"s": 5074,
"text": "If the length is 4, attach $FF32 to the fragment's code; exit.\nIf the rider's token is any numeric literal, compile the literal given the rider; exit."
},
{
"code": null,
"e": 5253,
"s": 5225,
"text": "Of the remaining sentences:"
},
{
"code": null,
"e": 5302,
"s": 5253,
"text": "272 (about 9%) are simple assignment statements:"
},
{
"code": null,
"e": 5348,
"s": 5302,
"text": "Put the type name into the field's type name."
},
{
"code": null,
"e": 5410,
"s": 5348,
"text": "202 (about 7%) are just the infrastructure for various loops:"
},
{
"code": null,
"e": 5480,
"s": 5410,
"text": "Loop.\nGet a field from the type's fields.\n[ other stuff here]\nRepeat."
},
{
"code": null,
"e": 5552,
"s": 5480,
"text": "183 (6%) simply add something to the end of this or that list, like so:"
},
{
"code": null,
"e": 5588,
"s": 5552,
"text": "Add the field to the type's fields."
},
{
"code": null,
"e": 5787,
"s": 5588,
"text": "164 (about 5%) are trivial statements used to return boolean results, start and stop various timers, show the program’s current status, and write interesting things to the compiler’s output listing."
},
{
"code": null,
"e": 5965,
"s": 5787,
"text": "Say no.\nSay yes.\nSet the variable's compiled flag.\nStart the compiler's timer.\nStop the compiler's timer.\nShow status \"Compiling...\".\nList the globals in the compiler's listing."
},
{
"code": null,
"e": 6034,
"s": 5965,
"text": "119 (about 4%) advance the focus in the source code, sentences like:"
},
{
"code": null,
"e": 6079,
"s": 6034,
"text": "Bump the rider.\nMove the rider (code rules)."
},
{
"code": null,
"e": 6175,
"s": 6079,
"text": "92 (about 3%) are used to create, destroy and keep internal indexes up to date, sentences like:"
},
{
"code": null,
"e": 6292,
"s": 6175,
"text": "Create the type index using 7919 for the bucket count.\nIndex the type given the type's name.\nDestroy the type index."
},
{
"code": null,
"e": 6348,
"s": 6292,
"text": "58 (about 2%) are used to find things in various lists:"
},
{
"code": null,
"e": 6380,
"s": 6348,
"text": "Find a variable given the name."
},
{
"code": null,
"e": 6436,
"s": 6380,
"text": "37 (about 1%) are calls to various conversion routines:"
},
{
"code": null,
"e": 6474,
"s": 6436,
"text": "Convert the rider's token to a ratio."
},
{
"code": null,
"e": 6591,
"s": 6474,
"text": "31 (about 1%) are used to generate actual machine code (plus those that appear in conditional statements, as above):"
},
{
"code": null,
"e": 6635,
"s": 6591,
"text": "Attach $E8 and the address to the fragment."
},
{
"code": null,
"e": 6690,
"s": 6635,
"text": "And that accounts for 80% of the code in our compiler."
},
{
"code": null,
"e": 6815,
"s": 6690,
"text": "Only 57 of the remaining sentences (less than 2% of the whole) are mathematical in nature, a line here and there like these:"
},
{
"code": null,
"e": 7047,
"s": 6815,
"text": "Add 4 to the routine's parameter size.\nSubtract the length from the local's offset.\nMultiply the type's scale by the base type's scale.\nCalculate the length of the field's type.\nRound the address up to the nearest multiple of 4096."
},
{
"code": null,
"e": 7098,
"s": 7047,
"text": "And the rest are not formulaic at all. Stuff like:"
},
{
"code": null,
"e": 8100,
"s": 7098,
"text": "Copy the field into another field.\nAppend the fragment to the current routine's fragments.\nAbort with \"I was hoping for a definition but all I found was '\" then the token.\nInitialize the compiler.\nRemove any trailing backslashes from the path name.\nReduce the monikette's type to a type for utility use.\nEliminate duplicate nicknames from the type's fields.\nPrepend \"original \" to the term's name.\nExtend the name with the rider's token.\nUnquote the other string.\nRead the source file's path into the source file's buffer.\nGenerate the literal's name.\nExtract a file name from the compiler's abort path.\nWrite the compiler's exe to the compiler's exe path.\nSwap the monikettes with the other monikettes.\nSkip any leading noise in the substring.\nScrub the utility index.\nFill the compiler's exe with the null byte given the compiler's exe size.\nPosition the rider's token on the rider's source.\nPluralize the type's plural name.\nLink.\nFinalize the compiler.\nCheck for invalid optional info on the type."
},
{
"code": null,
"e": 8483,
"s": 8100,
"text": "And that’s why we say that most of what most programs do is easy stuff, stuff that can be conveniently expressed in a natural language. And that, in turn, is why we like programming in Plain English: the thoughts in our heads are typed in as Plain English “pseudo code” and, with a tweak here and there, that pseudo code actually compiles and runs. And is self-documenting, to boot."
},
{
"code": null,
"e": 8510,
"s": 8483,
"text": "Another Objection Answered"
},
{
"code": null,
"e": 8741,
"s": 8510,
"text": "You may be thinking that natural language is just too verbose for programming. But is it really that bad? Let’s consider a couple of examples. In a traditional programming language, we might draw a box using a statement like this:"
},
{
"code": null,
"e": 8814,
"s": 8741,
"text": "substring.draw ( box, color, source.text.font, source.text.alignment ) ;"
},
{
"code": null,
"e": 8877,
"s": 8814,
"text": "Which is 10 words and 11 punctuation marks: 21 total elements."
},
{
"code": null,
"e": 8916,
"s": 8877,
"text": "The Plain English equivalent would be:"
},
{
"code": null,
"e": 9005,
"s": 8916,
"text": "Draw the substring in the box with the color and the source's text's font and alignment."
},
{
"code": null,
"e": 9067,
"s": 9005,
"text": "Which is 16 words and 3 punctuation marks: 19 total elements."
},
{
"code": null,
"e": 9350,
"s": 9067,
"text": "Admittedly, the Plain English version requires a few more easy-to-type alphabetic characters (it’s difficult to say exactly how many since traditional coders put spaces in different places); but that’s a small price to pay for not having to learn (or think in) an artificial syntax."
},
{
"code": null,
"e": 9374,
"s": 9350,
"text": "Here’s another example:"
},
{
"code": null,
"e": 9420,
"s": 9374,
"text": "if ( ! source.colorized ( ) ) color = black ;"
},
{
"code": null,
"e": 9481,
"s": 9420,
"text": "Which is 5 words and 8 punctuation marks: 13 total elements."
},
{
"code": null,
"e": 9514,
"s": 9481,
"text": "Compared with the Plain English:"
},
{
"code": null,
"e": 9572,
"s": 9514,
"text": "If the source is not colorized, put black into the color."
},
{
"code": null,
"e": 9634,
"s": 9572,
"text": "Which is 11 words and 2 punctuation marks: 13 total elements."
},
{
"code": null,
"e": 10193,
"s": 9634,
"text": "Again, it’s mostly a matter of whether you like to type words or (specialized) punctuation. And whether you like to think in two different syntactical and grammatical forms simultaneously. And whether you want your code to be self-documenting. And whether you want code that’s friendly for beginners. Andwhether you want to code in a language (like English) that will still be in common use 100 yearsfrom now. Personally, we think you may have lost some human perspective if you’ve come to think that “(!source.colorized())” is a good way of saying anything!"
},
{
"code": null,
"e": 10207,
"s": 10193,
"text": "The Prototype"
},
{
"code": null,
"e": 10270,
"s": 10207,
"text": "If you’re interested, you can download the whole shebang here:"
},
{
"code": null,
"e": 10300,
"s": 10270,
"text": "www.osmosian.com/cal-4700.zip"
},
{
"code": null,
"e": 11071,
"s": 10300,
"text": "It’s a small Windows program, less than a megabyte in size. But it’s a complete development environment, including a unique interface, a simplified file manager, an elegant text editor, a handy hexadecimal dumper, a native-code-generating compiler/linker, and even a wysiwyg page layout facility (that we used to produce the documentation). It is written entirely in Plain English. The source code (about 25,000 sentences) is included in the download. No installation is necessary; just unzip. Start with the “instructions.pdf” in the “documentation” directory and before you go ten pages you won’t just be writing “Hello, World!” to the screen, you’ll be re-compiling the entire thing in itself (in less than three seconds on a bottom-of-the-line machine from Walmart)."
},
{
"code": null,
"e": 11106,
"s": 11071,
"text": "Thanks for your time and interest."
},
{
"code": null,
"e": 11181,
"s": 11106,
"text": "Gerry RzeppaGrand Negus of the Osmosian Order of Plain English Programmers"
},
{
"code": null,
"e": 11258,
"s": 11181,
"text": "Dan RzeppaPrime Assembler of the Osmosian Order of Plain English Programmers"
},
{
"code": null,
"e": 11271,
"s": 11258,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 11277,
"s": 11271,
"text": "GBlog"
},
{
"code": null,
"e": 11375,
"s": 11277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11400,
"s": 11375,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 11455,
"s": 11400,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 11492,
"s": 11455,
"text": "Geek Streak - 24 Days POTD Challenge"
},
{
"code": null,
"e": 11530,
"s": 11492,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 11569,
"s": 11530,
"text": "How to Learn Data Science in 10 weeks?"
},
{
"code": null,
"e": 11635,
"s": 11569,
"text": "GeeksforGeeks Jobathon - Are You Ready For This Hiring Challenge?"
},
{
"code": null,
"e": 11661,
"s": 11635,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 11732,
"s": 11661,
"text": "GeeksforGeeks Job-A-Thon Exclusive - Hiring Challenge For Amazon Alexa"
},
{
"code": null,
"e": 11796,
"s": 11732,
"text": "What is Data Structure: Types, Classifications and Applications"
}
] |
How to deal with “could not find function” error in R?
|
The error “could not find function” occurs due to the following reasons −
Function name is incorrect. Always remember that function names are case sensitive in
R.
Function name is incorrect. Always remember that function names are case sensitive in
R.
The package that contains the function was not installed. We have to install packages
in R once before using any function contained by them. It can be done as
install.packages("package_name")
The package that contains the function was not installed. We have to install packages
in R once before using any function contained by them. It can be done as
install.packages("package_name")
The package was not loaded before using the function. To use the function that is
contained in a package we need to load the package and it can be done as
library("package_name").
The package was not loaded before using the function. To use the function that is
contained in a package we need to load the package and it can be done as
library("package_name").
Version of R is older where the function you are using does not exist.
Version of R is older where the function you are using does not exist.
If you have installed and loaded many packages but forgot which package contains the
function you are using then you can do it by using getAnywhere
> library(ggplot2)
> library(BSDA)
Loading required package: lattice
Attaching package: ‘BSDA’
The following object is masked from ‘package:datasets’ −
Orange
> library(purrr)
> getAnywhere(ggplot)
A single object matching ‘ggplot’ was found
It was found in the following places
package:ggplot2
namespace:ggplot2
with value
function (data = NULL, mapping = aes(), ..., environment = parent.frame()){
UseMethod("ggplot")
}
<bytecode: 0x0000000011201848>
<environment: namespace:ggplot2>
Here we have loaded three packages, named ggplot2, BSDA, and purr. Suppose we
wanted to know which package contains ggplot function. So, we used getAnywhere and
it returns the package name as ggplot2.
You should make sure that you do not make the mistakes mentioned above. If you use an
older version of R but want to perform calculations using a function that is created for a
newer version then it would not be possible. But it can become possible if you use
package backports to make newly added functions available to older version of R. Also,
you need to find the list of function that need to be backported on the git repo of
backports. Just remember that R versions older than R3.0.0 are not compatible with
packages built for R3.0.0 and later versions.
|
[
{
"code": null,
"e": 1261,
"s": 1187,
"text": "The error “could not find function” occurs due to the following reasons −"
},
{
"code": null,
"e": 1350,
"s": 1261,
"text": "Function name is incorrect. Always remember that function names are case sensitive in\nR."
},
{
"code": null,
"e": 1439,
"s": 1350,
"text": "Function name is incorrect. Always remember that function names are case sensitive in\nR."
},
{
"code": null,
"e": 1631,
"s": 1439,
"text": "The package that contains the function was not installed. We have to install packages\nin R once before using any function contained by them. It can be done as\ninstall.packages(\"package_name\")"
},
{
"code": null,
"e": 1823,
"s": 1631,
"text": "The package that contains the function was not installed. We have to install packages\nin R once before using any function contained by them. It can be done as\ninstall.packages(\"package_name\")"
},
{
"code": null,
"e": 2003,
"s": 1823,
"text": "The package was not loaded before using the function. To use the function that is\ncontained in a package we need to load the package and it can be done as\nlibrary(\"package_name\")."
},
{
"code": null,
"e": 2183,
"s": 2003,
"text": "The package was not loaded before using the function. To use the function that is\ncontained in a package we need to load the package and it can be done as\nlibrary(\"package_name\")."
},
{
"code": null,
"e": 2254,
"s": 2183,
"text": "Version of R is older where the function you are using does not exist."
},
{
"code": null,
"e": 2325,
"s": 2254,
"text": "Version of R is older where the function you are using does not exist."
},
{
"code": null,
"e": 2473,
"s": 2325,
"text": "If you have installed and loaded many packages but forgot which package contains the\nfunction you are using then you can do it by using getAnywhere"
},
{
"code": null,
"e": 2568,
"s": 2473,
"text": "> library(ggplot2)\n> library(BSDA)\nLoading required package: lattice\nAttaching package: ‘BSDA’"
},
{
"code": null,
"e": 2625,
"s": 2568,
"text": "The following object is masked from ‘package:datasets’ −"
},
{
"code": null,
"e": 2632,
"s": 2625,
"text": "Orange"
},
{
"code": null,
"e": 2962,
"s": 2632,
"text": "> library(purrr)\n> getAnywhere(ggplot)\nA single object matching ‘ggplot’ was found\nIt was found in the following places\npackage:ggplot2\nnamespace:ggplot2\nwith value\nfunction (data = NULL, mapping = aes(), ..., environment = parent.frame()){\n UseMethod(\"ggplot\")\n}\n<bytecode: 0x0000000011201848>\n<environment: namespace:ggplot2>"
},
{
"code": null,
"e": 3163,
"s": 2962,
"text": "Here we have loaded three packages, named ggplot2, BSDA, and purr. Suppose we\nwanted to know which package contains ggplot function. So, we used getAnywhere and\nit returns the package name as ggplot2."
},
{
"code": null,
"e": 3723,
"s": 3163,
"text": "You should make sure that you do not make the mistakes mentioned above. If you use an\nolder version of R but want to perform calculations using a function that is created for a\nnewer version then it would not be possible. But it can become possible if you use\npackage backports to make newly added functions available to older version of R. Also,\nyou need to find the list of function that need to be backported on the git repo of\nbackports. Just remember that R versions older than R3.0.0 are not compatible with\npackages built for R3.0.0 and later versions."
}
] |
Object.assign() in JavaScript?
|
This method is used to copy one or more source objects to a target object. It invokes getters and setters since it uses both 'get' on the source and 'Set' on the target. It returns the target object which has properties and values copied from the target object. This method does not throw on null or undefined source values.
Object.assign(target, ...source objects);
It takes source objects and a target object as parameters and push the source objects into the target object and display the target object.
In the following example, the properties from the source objects "obj1", "obj2", and "obj3" were pushed into a target object "obj" and the target object is returned as the output.
<html>
<body>
<script>
var obj1 = { a: 10, b:20 };
var obj2 = { c: 30, d:40 };
var obj3 = { e: 50 };
var obj = Object.assign({}, obj1, obj2, obj3);
document.write(JSON.stringify(obj));
</script>
</body>
</html>
{"a":10,"b":20,"c":30,"d":40,"e":50}
In the following example, there are multiple instances of some of the properties of the objects. In this case the method Object.assign() takes the lastly assigned value of a property. For instance, in all the 3 objects "obj1", "obj2", and "obj3 property 'c' is common and assigned values such as 1,3 and 0 respectively. The value of property 'c' in obj3 overrides the other previously assigned values 1 and 3. So if we look at the output, property 'c' is assigned with a value 0.
<html>
<body>
<script>
var obj1 = { a: 10, b:20, c:1 };
var obj2 = { b: 30, d:10, c:3 };
var obj3 = { e: 60, d:70, c:0 };
var obj = Object.assign({}, obj1, obj2, obj3);
document.write(JSON.stringify(obj));
</script>
</body>
</html>
{"a":10,"b":30,"c":0,"d":70,"e":60}
|
[
{
"code": null,
"e": 1512,
"s": 1187,
"text": "This method is used to copy one or more source objects to a target object. It invokes getters and setters since it uses both 'get' on the source and 'Set' on the target. It returns the target object which has properties and values copied from the target object. This method does not throw on null or undefined source values."
},
{
"code": null,
"e": 1554,
"s": 1512,
"text": "Object.assign(target, ...source objects);"
},
{
"code": null,
"e": 1694,
"s": 1554,
"text": "It takes source objects and a target object as parameters and push the source objects into the target object and display the target object."
},
{
"code": null,
"e": 1875,
"s": 1694,
"text": "In the following example, the properties from the source objects \"obj1\", \"obj2\", and \"obj3\" were pushed into a target object \"obj\" and the target object is returned as the output."
},
{
"code": null,
"e": 2101,
"s": 1875,
"text": "<html>\n<body>\n<script>\n var obj1 = { a: 10, b:20 };\n var obj2 = { c: 30, d:40 };\n var obj3 = { e: 50 };\n var obj = Object.assign({}, obj1, obj2, obj3);\n document.write(JSON.stringify(obj));\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2138,
"s": 2101,
"text": "{\"a\":10,\"b\":20,\"c\":30,\"d\":40,\"e\":50}"
},
{
"code": null,
"e": 2618,
"s": 2138,
"text": "In the following example, there are multiple instances of some of the properties of the objects. In this case the method Object.assign() takes the lastly assigned value of a property. For instance, in all the 3 objects \"obj1\", \"obj2\", and \"obj3 property 'c' is common and assigned values such as 1,3 and 0 respectively. The value of property 'c' in obj3 overrides the other previously assigned values 1 and 3. So if we look at the output, property 'c' is assigned with a value 0."
},
{
"code": null,
"e": 2865,
"s": 2618,
"text": "<html>\n<body>\n<script>\n var obj1 = { a: 10, b:20, c:1 };\n var obj2 = { b: 30, d:10, c:3 };\n var obj3 = { e: 60, d:70, c:0 };\n var obj = Object.assign({}, obj1, obj2, obj3);\n document.write(JSON.stringify(obj));\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2901,
"s": 2865,
"text": "{\"a\":10,\"b\":30,\"c\":0,\"d\":70,\"e\":60}"
}
] |
SQL | Distinct Clause
|
11 Sep, 2020
The distinct keyword is used in conjunction with select keyword. It is helpful when there is a need of avoiding duplicate values present in any specific columns/table. When we use distinct keyword only the unique values are fetched.
Syntax :
SELECT DISTINCT column1, column2
FROM table_name
column1, column2 : Names of the fields of the table.
table_name : Table from where we want to fetch the records.
This query will return all the unique combinations of rows in the table with fields column1, column2.
NOTE: If distinct keyword is used with multiple columns, the distinct combination is displayed in the result set.
Table – Student
Queries
To fetch unique names from the NAME field –
SELECT DISTINCT NAME
FROM Student;
Output :
To fetch a unique combination of rows from the whole table –
SELECT DISTINCT *
FROM Student;
Output :
Note : Without the keyword distinct in both the above examples 6 records would have been fetched instead of 4, since in the original table there are 6 records with the duplicate values.
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.
Anshika Goyal
SQL-Clauses-Operators
Articles
DBMS
SQL
DBMS
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n11 Sep, 2020"
},
{
"code": null,
"e": 287,
"s": 53,
"text": "The distinct keyword is used in conjunction with select keyword. It is helpful when there is a need of avoiding duplicate values present in any specific columns/table. When we use distinct keyword only the unique values are fetched. "
},
{
"code": null,
"e": 297,
"s": 287,
"text": "Syntax : "
},
{
"code": null,
"e": 349,
"s": 297,
"text": "SELECT DISTINCT column1, column2 \nFROM table_name \n"
},
{
"code": null,
"e": 402,
"s": 349,
"text": "column1, column2 : Names of the fields of the table."
},
{
"code": null,
"e": 462,
"s": 402,
"text": "table_name : Table from where we want to fetch the records."
},
{
"code": null,
"e": 565,
"s": 462,
"text": "This query will return all the unique combinations of rows in the table with fields column1, column2. "
},
{
"code": null,
"e": 680,
"s": 565,
"text": "NOTE: If distinct keyword is used with multiple columns, the distinct combination is displayed in the result set. "
},
{
"code": null,
"e": 696,
"s": 680,
"text": "Table – Student"
},
{
"code": null,
"e": 704,
"s": 696,
"text": "Queries"
},
{
"code": null,
"e": 749,
"s": 704,
"text": "To fetch unique names from the NAME field – "
},
{
"code": null,
"e": 786,
"s": 749,
"text": "SELECT DISTINCT NAME \nFROM Student;\n"
},
{
"code": null,
"e": 796,
"s": 786,
"text": "Output : "
},
{
"code": null,
"e": 858,
"s": 796,
"text": "To fetch a unique combination of rows from the whole table – "
},
{
"code": null,
"e": 892,
"s": 858,
"text": "SELECT DISTINCT * \nFROM Student;\n"
},
{
"code": null,
"e": 903,
"s": 892,
"text": "Output : "
},
{
"code": null,
"e": 1089,
"s": 903,
"text": "Note : Without the keyword distinct in both the above examples 6 records would have been fetched instead of 4, since in the original table there are 6 records with the duplicate values."
},
{
"code": null,
"e": 1391,
"s": 1089,
"text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 1517,
"s": 1391,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 1531,
"s": 1517,
"text": "Anshika Goyal"
},
{
"code": null,
"e": 1553,
"s": 1531,
"text": "SQL-Clauses-Operators"
},
{
"code": null,
"e": 1562,
"s": 1553,
"text": "Articles"
},
{
"code": null,
"e": 1567,
"s": 1562,
"text": "DBMS"
},
{
"code": null,
"e": 1571,
"s": 1567,
"text": "SQL"
},
{
"code": null,
"e": 1576,
"s": 1571,
"text": "DBMS"
},
{
"code": null,
"e": 1580,
"s": 1576,
"text": "SQL"
}
] |
Lineplot using Seaborn in Python
|
21 Oct, 2021
Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides default styles and color palettes to make statistical plots more attractive. It is built on the top of the matplotlib library and is also closely integrated into the data structures from pandas.
Visual representation of a dataset must be chosen according to the dataset or the type of answer we want from the plot. Scatter plots are highly preferred for visualizing statistical relationships. But when it comes to data which is varying with time (or continuous variable), scatter plots are not a good choice. Instead, in Seaborn, lineplot() or relplot() with kind = ‘line’ must be preferred. Line plots give annotation to each of the points and plus helps in customizing markers, line style, and legends.
Syntax: seaborn.lineplot(x=None, y=None, hue=None, size=None, style=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, dashes=True, markers=None, style_order=None, units=None, estimator=’mean’, ci=95, n_boot=1000, seed=None, sort=True, err_style=’band’, err_kws=None, legend=’brief’, ax=None, **kwargs)Parameters: x, y: Input data variables; must be numeric. data: Dataframe where each column is a variable and each row is an observation. size: Grouping variable that will produce lines with different widths. style: Grouping variable that will produce lines with different dashes and/or markers.
Example 1: Let’s take an example of FMRI dataset. It is an example of time-series data, where variables are a function of time. This dataset is in-built available and can be accessed using load_dataset() and needs not to be downloaded separately.
Python3
# import librariesimport seaborn as sns # load datasetfmri = sns.load_dataset("fmri")
There can be multiple measurements of the same variable. So we can plot the mean of all the values of x and 95% confidence interval around the mean. This behavior of aggregation is by default in seaborn.
Python3
# plotting lineplot for signal with respect to timepoint# using relplot, kind = "line"# code added by devanshigupta1304sns.lineplot( x = "timepoint", y = "signal", data = fmri);
Output-
Example 2: Creating multiple line plot using hue parameters.
Python3
sns.lineplot( x = "timepoint", y = "signal", hue = "region", data = fmri);
Output:
Example 3: Creating multiple line plots using style parameters.
Python3
sns.lineplot( x = "timepoint", y = "signal", hue = "region", style = "event", data = fmri);
Output:
Example 4: Creating multiple line plots using size parameters. We can use size attributes to change the line pattern.
Python3
sns.lineplot( x = "timepoint", y = "signal", size = "event", data = fmri);
Output:
Example 5: Grouping data points on the basis of category, here as region and event. We can add them as hue and style semantics. This will change the line pattern by default.
Python3
# code added by devanshigupta1304# using relplot with kind = "line"# adding style and hue semanticsns.relplot( x = "timepoint", y = "signal", hue = "region", style = "event", kind = "line", data = fmri);
Output:
Example 6: We can also represent standard deviation instead of confidence interval at each time point, for a large dataset, as it can be very time-consuming.
Python3
# code added by devanshigupta1304# plotting lineplot for signal with respect to timepoint# using relplot, kind = "line"# using standard deviation instead of confidence intervalsns.relplot(x = "timepoint", y = "signal", kind = "line", ci = "sd", data = fmri);
Output –
Example 7: We can use style and hue with different columns in a data set.
Python3
# using lineplot with style = column_name# adding style and hue semanticsns.lineplot(x = "timepoint", y = "signal", hue = "subject",style = "event", data = fmri);
Output:
Example 8: Using palette attributes
Python3
# using lineplot# adding palette, style and hue semanticsns.lineplot( x = "timepoint", y = "signal", hue = "subject", style = "event", palette = "YlOrRd_r", data = fmri);
Output:
Example 9: Adding error bar in line plot using err_style attributes.
Python3
sns.lineplot( x = "timepoint", y = "signal", data = fmri, err_style="bars");
Output:
devanshigupta1304
kumar_satyam
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 324,
"s": 28,
"text": "Seaborn is an amazing visualization library for statistical graphics plotting in Python. It provides default styles and color palettes to make statistical plots more attractive. It is built on the top of the matplotlib library and is also closely integrated into the data structures from pandas."
},
{
"code": null,
"e": 834,
"s": 324,
"text": "Visual representation of a dataset must be chosen according to the dataset or the type of answer we want from the plot. Scatter plots are highly preferred for visualizing statistical relationships. But when it comes to data which is varying with time (or continuous variable), scatter plots are not a good choice. Instead, in Seaborn, lineplot() or relplot() with kind = ‘line’ must be preferred. Line plots give annotation to each of the points and plus helps in customizing markers, line style, and legends."
},
{
"code": null,
"e": 1488,
"s": 834,
"text": "Syntax: seaborn.lineplot(x=None, y=None, hue=None, size=None, style=None, data=None, palette=None, hue_order=None, hue_norm=None, sizes=None, size_order=None, size_norm=None, dashes=True, markers=None, style_order=None, units=None, estimator=’mean’, ci=95, n_boot=1000, seed=None, sort=True, err_style=’band’, err_kws=None, legend=’brief’, ax=None, **kwargs)Parameters: x, y: Input data variables; must be numeric. data: Dataframe where each column is a variable and each row is an observation. size: Grouping variable that will produce lines with different widths. style: Grouping variable that will produce lines with different dashes and/or markers. "
},
{
"code": null,
"e": 1736,
"s": 1488,
"text": "Example 1: Let’s take an example of FMRI dataset. It is an example of time-series data, where variables are a function of time. This dataset is in-built available and can be accessed using load_dataset() and needs not to be downloaded separately. "
},
{
"code": null,
"e": 1744,
"s": 1736,
"text": "Python3"
},
{
"code": "# import librariesimport seaborn as sns # load datasetfmri = sns.load_dataset(\"fmri\")",
"e": 1830,
"s": 1744,
"text": null
},
{
"code": null,
"e": 2035,
"s": 1830,
"text": "There can be multiple measurements of the same variable. So we can plot the mean of all the values of x and 95% confidence interval around the mean. This behavior of aggregation is by default in seaborn. "
},
{
"code": null,
"e": 2043,
"s": 2035,
"text": "Python3"
},
{
"code": "# plotting lineplot for signal with respect to timepoint# using relplot, kind = \"line\"# code added by devanshigupta1304sns.lineplot( x = \"timepoint\", y = \"signal\", data = fmri);",
"e": 2245,
"s": 2043,
"text": null
},
{
"code": null,
"e": 2253,
"s": 2245,
"text": "Output-"
},
{
"code": null,
"e": 2314,
"s": 2253,
"text": "Example 2: Creating multiple line plot using hue parameters."
},
{
"code": null,
"e": 2322,
"s": 2314,
"text": "Python3"
},
{
"code": "sns.lineplot( x = \"timepoint\", y = \"signal\", hue = \"region\", data = fmri);",
"e": 2433,
"s": 2322,
"text": null
},
{
"code": null,
"e": 2441,
"s": 2433,
"text": "Output:"
},
{
"code": null,
"e": 2505,
"s": 2441,
"text": "Example 3: Creating multiple line plots using style parameters."
},
{
"code": null,
"e": 2513,
"s": 2505,
"text": "Python3"
},
{
"code": "sns.lineplot( x = \"timepoint\", y = \"signal\", hue = \"region\", style = \"event\", data = fmri);",
"e": 2653,
"s": 2513,
"text": null
},
{
"code": null,
"e": 2661,
"s": 2653,
"text": "Output:"
},
{
"code": null,
"e": 2779,
"s": 2661,
"text": "Example 4: Creating multiple line plots using size parameters. We can use size attributes to change the line pattern."
},
{
"code": null,
"e": 2787,
"s": 2779,
"text": "Python3"
},
{
"code": "sns.lineplot( x = \"timepoint\", y = \"signal\", size = \"event\", data = fmri);",
"e": 2898,
"s": 2787,
"text": null
},
{
"code": null,
"e": 2906,
"s": 2898,
"text": "Output:"
},
{
"code": null,
"e": 3082,
"s": 2908,
"text": "Example 5: Grouping data points on the basis of category, here as region and event. We can add them as hue and style semantics. This will change the line pattern by default."
},
{
"code": null,
"e": 3090,
"s": 3082,
"text": "Python3"
},
{
"code": "# code added by devanshigupta1304# using relplot with kind = \"line\"# adding style and hue semanticsns.relplot( x = \"timepoint\", y = \"signal\", hue = \"region\", style = \"event\", kind = \"line\", data = fmri);",
"e": 3327,
"s": 3090,
"text": null
},
{
"code": null,
"e": 3336,
"s": 3327,
"text": "Output: "
},
{
"code": null,
"e": 3495,
"s": 3336,
"text": "Example 6: We can also represent standard deviation instead of confidence interval at each time point, for a large dataset, as it can be very time-consuming. "
},
{
"code": null,
"e": 3503,
"s": 3495,
"text": "Python3"
},
{
"code": "# code added by devanshigupta1304# plotting lineplot for signal with respect to timepoint# using relplot, kind = \"line\"# using standard deviation instead of confidence intervalsns.relplot(x = \"timepoint\", y = \"signal\", kind = \"line\", ci = \"sd\", data = fmri);",
"e": 3784,
"s": 3503,
"text": null
},
{
"code": null,
"e": 3794,
"s": 3784,
"text": "Output – "
},
{
"code": null,
"e": 3868,
"s": 3794,
"text": "Example 7: We can use style and hue with different columns in a data set."
},
{
"code": null,
"e": 3876,
"s": 3868,
"text": "Python3"
},
{
"code": "# using lineplot with style = column_name# adding style and hue semanticsns.lineplot(x = \"timepoint\", y = \"signal\", hue = \"subject\",style = \"event\", data = fmri);",
"e": 4063,
"s": 3876,
"text": null
},
{
"code": null,
"e": 4071,
"s": 4063,
"text": "Output:"
},
{
"code": null,
"e": 4107,
"s": 4071,
"text": "Example 8: Using palette attributes"
},
{
"code": null,
"e": 4115,
"s": 4107,
"text": "Python3"
},
{
"code": "# using lineplot# adding palette, style and hue semanticsns.lineplot( x = \"timepoint\", y = \"signal\", hue = \"subject\", style = \"event\", palette = \"YlOrRd_r\", data = fmri);",
"e": 4310,
"s": 4115,
"text": null
},
{
"code": null,
"e": 4318,
"s": 4310,
"text": "Output:"
},
{
"code": null,
"e": 4387,
"s": 4318,
"text": "Example 9: Adding error bar in line plot using err_style attributes."
},
{
"code": null,
"e": 4395,
"s": 4387,
"text": "Python3"
},
{
"code": "sns.lineplot( x = \"timepoint\", y = \"signal\", data = fmri, err_style=\"bars\");",
"e": 4508,
"s": 4395,
"text": null
},
{
"code": null,
"e": 4516,
"s": 4508,
"text": "Output:"
},
{
"code": null,
"e": 4534,
"s": 4516,
"text": "devanshigupta1304"
},
{
"code": null,
"e": 4547,
"s": 4534,
"text": "kumar_satyam"
},
{
"code": null,
"e": 4562,
"s": 4547,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 4569,
"s": 4562,
"text": "Python"
}
] |
Linked List | Set 2 (Inserting a node)
|
24 Jun, 2022
We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of linked list.
C++
C
Java
Python3
C#
Javascript
// A linked list node class Node { public: int data; Node *next; }; // This code is contributed by rathbhupendra
// A linked list nodestruct Node{ int data; struct Node *next;};
// Linked List Classclass LinkedList{ Node head; // head of list /* Node Class */ class Node { int data; Node next; // Constructor to create a new node Node(int d) {data = d; next = null; } }}
# Node classclass Node: # Function to initialize the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List classclass LinkedList: # Function to initialize the Linked List object def __init__(self): self.head = None
/* Linked list Node*/public class Node{ public int data; public Node next; public Node(int d) {data = d; next = null; }}
<script>// Linked List Class var head; // head of list /* Node Class */ class Node { // Constructor to create a new node constructor(d) { this.data = d; this.next = null; } }// This code is contributed by todaysgaurav </script>
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.
In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways 1) At the front of the linked list 2) After a given node. 3) At the end of the linked list.
Add a node at the front: (4 steps process) The new node is always added before the head of the given Linked List. And newly added node becomes the new head of the Linked List. For example, if the given Linked List is 10->15->20->25 and we add an item 5 at the front, then the Linked List becomes 5->10->15->20->25. Let us call the function that adds at the front of the list is push(). The push() must receive a pointer to the head pointer, because push must change the head pointer to point to the new node (See this)
Following are the 4 steps to add a node at the front.
C++
C
Java
Python3
C#
Javascript
/* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */void push(Node** head_ref, int new_data) { /* 1. allocate node */ Node* new_node = new Node(); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head */ new_node->next = (*head_ref); /* 4. move the head to point to the new node */ (*head_ref) = new_node; } // This code is contributed by rathbhupendra
/* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head */ new_node->next = (*head_ref); /* 4. move the head to point to the new node */ (*head_ref) = new_node;}
/* This function is in LinkedList class. Inserts a new Node at front of the list. This method is defined inside LinkedList class shown above */public void push(int new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;}
# This function is in LinkedList class# Function to insert a new node at the beginningdef push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node
/* Inserts a new Node at front of the list. */public void push(int new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;}
<script> /* This function is in LinkedList class. Inserts a new Node at front of the list. This method is defined inside LinkedList class shown above */ function push(new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} // This code contributed by Rajput-Ji </script>
We have a pointer to the head and we can directly attach a node and change the pointer. So the Time complexity of inserting a node at head position is O(1) as it does a constant amount of work.
Add a node after a given node: (5 steps process) We are given a pointer to a node, and the new node is inserted after the given node.
C++
C
Java
Python3
C#
Javascript
// Given a node prev_node, insert a// new node after the given// prev_nodevoid insertAfter(Node* prev_node, int new_data){ // 1. Check if the given prev_node is NULL if (prev_node == NULL) { cout << "The given previous node cannot be NULL"; return; } // 2. Allocate new node Node* new_node = new Node(); // 3. Put in the data new_node->data = new_data; // 4. Make next of new node as // next of prev_node new_node->next = prev_node->next; // 5. move the next of prev_node // as new_node prev_node->next = new_node;} // This code is contributed by anmolgautam818,// arkajyotibasak
/* Given a node prev_node, insert a new node after the givenprev_node */void insertAfter(struct Node* prev_node, int new_data){ /*1. check if the given prev_node is NULL */ if (prev_node == NULL) { printf("the given previous node cannot be NULL"); return; } /* 2. allocate new node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* 3. put in the data */ new_node->data = new_data; /* 4. Make next of new node as next of prev_node */ new_node->next = prev_node->next; /* 5. move the next of prev_node as new_node */ prev_node->next = new_node;}
/* This function is in LinkedList class.Inserts a new node after the given prev_node. This method isdefined inside LinkedList class shown above */public void insertAfter(Node prev_node, int new_data){ /* 1. Check if the given Node is null */ if (prev_node == null) { System.out.println( "The given previous node cannot be null"); return; } /* 2. Allocate the Node & 3. Put in the data*/ Node new_node = new Node(new_data); /* 4. Make next of new Node as next of prev_node */ new_node.next = prev_node.next; /* 5. make next of prev_node as new_node */ prev_node.next = new_node;}
# This function is in LinkedList class.# Inserts a new node after the given prev_node. This method is# defined inside LinkedList class shown above */ def insertAfter(self, prev_node, new_data): # 1. check if the given prev_node exists if prev_node is None: print("The given previous node must inLinkedList.") return # 2. Create new node & # 3. Put in the data new_node = Node(new_data) # 4. Make next of new Node as next of prev_node new_node.next = prev_node.next # 5. make next of prev_node as new_node prev_node.next = new_node
/* Inserts a new node after the given prev_node. */public void insertAfter(Node prev_node, int new_data){ /* 1. Check if the given Node is null */ if (prev_node == null) { Console.WriteLine("The given previous node" + " cannot be null"); return; } /* 2 & 3: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 4. Make next of new Node as next of prev_node */ new_node.next = prev_node.next; /* 5. make next of prev_node as new_node */ prev_node.next = new_node;}
<script> /* This function is in LinkedList class. Inserts a new node after the given prev_node. This method is defined inside LinkedList class shown above */function insertAfter(prev_node , new_data) { /* 1. Check if the given Node is null */ if (prev_node == null) { document.write("The given previous node cannot be null"); return; } /* 2. Allocate the Node & 3. Put in the data*/ var new_node = new Node(new_data); /* 4. Make next of new Node as next of prev_node */ new_node.next = prev_node.next; /* 5. make next of prev_node as new_node */ prev_node.next = new_node; } // This code is contributed by aashish1995 </script>
Time complexity of insertAfter() is O(n) as it depends on n where n is the size of the linked list
Space complexity: O(1) since using constant space to modify pointers
Add a node at the end: (6 steps process) The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head of it, we have to traverse the list till the end and then change the next to last node to a new node.
Following are the 6 steps to add node at the end.
C++
C
Java
Python3
C#
Javascript
// Given a reference (pointer to pointer) to the head // of a list and an int, appends a new node at the end void append(Node** head_ref, int new_data) { // 1. allocate node Node* new_node = new Node(); // Used in step 5 Node *last = *head_ref; // 2. Put in the data new_node->data = new_data; // 3. This new node is going to be // the last node, so make next of // it as NULL new_node->next = NULL; // 4. If the Linked List is empty, // then make the new node as head if (*head_ref == NULL) { *head_ref = new_node; return; } // 5. Else traverse till the last node while (last->next != NULL) { last = last->next; } // 6. Change the next of last node last->next = new_node; return; } // This code is contributed by anmolgautam818, arkajyotibasak
/* Given a reference (pointer to pointer) to the head of a list and an int, appends a new node at the end */void append(struct Node** head_ref, int new_data){ /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); struct Node *last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) last = last->next; /* 6. Change the next of last node */ last->next = new_node; return; }
/* Appends a new node at the end. This method is defined inside LinkedList class shown above */public void append(int new_data){ /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ Node new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; /* 5. Else traverse till the last node */ Node last = head; while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; return;}
# This function is defined in Linked List class# Appends a new node at the end. This method is# defined inside LinkedList class shown above def append(self, new_data): # 1. Create a new node # 2. Put in the data # 3. Set next as None new_node = Node(new_data) # 4. If the Linked List is empty, then make the # new node as head if self.head is None: self.head = new_node return # 5. Else traverse till the last node last = self.head while (last.next): last = last.next # 6. Change the next of last node last.next = new_node
/* Appends a new node at the end. This method is defined inside LinkedList class shown above */public void append(int new_data){ /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ Node new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; /* 5. Else traverse till the last node */ Node last = head; while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; return;}
<script> /* Appends a new node at the end. This method is defined inside LinkedList class shown above */ function append(new_data){ /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ var new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; /* 5. Else traverse till the last node */ var last = head; while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; return;} // This code contributed by aashish1995</script>
Time complexity of append is O(n) where n is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work. This method can also be optimized to work in O(1) by keeping an extra pointer to the tail of the linked list/
Following is a complete program that uses all of the above methods to create a linked list.
C++
C
Java
Python3
C#
Javascript
// A complete working C++ program to demonstrate // all insertion methods on Linked List #include <bits/stdc++.h>using namespace std; // A linked list node class Node { public: int data; Node *next; }; /* Given a reference (pointer to pointer)to the head of a list and an int, insertsa new node on the front of the list. */void push(Node** head_ref, int new_data) { /* 1. allocate node */ Node* new_node = new Node(); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head */ new_node->next = (*head_ref); /* 4. move the head to point to the new node */ (*head_ref) = new_node; } /* Given a node prev_node, insert a new node after the given prev_node */void insertAfter(Node* prev_node, int new_data) { /*1. check if the given prev_node is NULL */ if (prev_node == NULL) { cout<<"The given previous node cannot be NULL"; return; } /* 2. allocate new node */ Node* new_node = new Node(); /* 3. put in the data */ new_node->data = new_data; /* 4. Make next of new node as next of prev_node */ new_node->next = prev_node->next; /* 5. move the next of prev_node as new_node */ prev_node->next = new_node; } /* Given a reference (pointer to pointer) to the head of a list and an int, appends a new node at the end */void append(Node** head_ref, int new_data) { /* 1. allocate node */ Node* new_node = new Node(); Node *last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) { last = last->next; } /* 6. Change the next of last node */ last->next = new_node; return; } // This function prints contents of// linked list starting from head void printList(Node *node) { while (node != NULL) { cout<<" "<<node->data; node = node->next; } } /* Driver code*/int main() { /* Start with the empty list */ Node* head = NULL; // Insert 6. So linked list becomes 6->NULL append(&head, 6); // Insert 7 at the beginning. // So linked list becomes 7->6->NULL push(&head, 7); // Insert 1 at the beginning. // So linked list becomes 1->7->6->NULL push(&head, 1); // Insert 4 at the end. So // linked list becomes 1->7->6->4->NULL append(&head, 4); // Insert 8, after 7. So linked // list becomes 1->7->8->6->4->NULL insertAfter(head->next, 8); cout<<"Created Linked list is: "; printList(head); return 0; } // This code is contributed by rathbhupendra, arkajyotibasak
// A complete working C program to demonstrate all insertion methods// on Linked List#include <stdio.h>#include <stdlib.h> // A linked list nodestruct Node{ int data; struct Node *next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head */ new_node->next = (*head_ref); /* 4. move the head to point to the new node */ (*head_ref) = new_node;} /* Given a node prev_node, insert a new node after the given prev_node */void insertAfter(struct Node* prev_node, int new_data){ /*1. check if the given prev_node is NULL */ if (prev_node == NULL) { printf("the given previous node cannot be NULL"); return; } /* 2. allocate new node */ struct Node* new_node =(struct Node*) malloc(sizeof(struct Node)); /* 3. put in the data */ new_node->data = new_data; /* 4. Make next of new node as next of prev_node */ new_node->next = prev_node->next; /* 5. move the next of prev_node as new_node */ prev_node->next = new_node;} /* Given a reference (pointer to pointer) to the head of a list and an int, appends a new node at the end */void append(struct Node** head_ref, int new_data){ /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); struct Node *last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) last = last->next; /* 6. Change the next of last node */ last->next = new_node; return;} // This function prints contents of linked list starting from headvoid printList(struct Node *node){ while (node != NULL) { printf(" %d ", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; // Insert 6. So linked list becomes 6->NULL append(&head, 6); // Insert 7 at the beginning. So linked list becomes 7->6->NULL push(&head, 7); // Insert 1 at the beginning. So linked list becomes 1->7->6->NULL push(&head, 1); // Insert 4 at the end. So linked list becomes 1->7->6->4->NULL append(&head, 4); // Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL insertAfter(head->next, 8); printf("\n Created Linked list is: "); printList(head); return 0;}
// A complete working Java program to demonstrate all insertion methods// on linked listclass LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) {data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Inserts a new node after the given prev_node. */ public void insertAfter(Node prev_node, int new_data) { /* 1. Check if the given Node is null */ if (prev_node == null) { System.out.println("The given previous node cannot be null"); return; } /* 2 & 3: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 4. Make next of new Node as next of prev_node */ new_node.next = prev_node.next; /* 5. make next of prev_node as new_node */ prev_node.next = new_node; } /* Appends a new node at the end. This method is defined inside LinkedList class shown above */ public void append(int new_data) { /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ Node new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; /* 5. Else traverse till the last node */ Node last = head; while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; return; } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { System.out.print(tnode.data+" "); tnode = tnode.next; } } /* Driver program to test above functions. Ideally this function should be in a separate user class. It is kept here to keep code compact */ public static void main(String[] args) { /* Start with the empty list */ LinkedList llist = new LinkedList(); // Insert 6. So linked list becomes 6->NUllist llist.append(6); // Insert 7 at the beginning. So linked list becomes // 7->6->NUllist llist.push(7); // Insert 1 at the beginning. So linked list becomes // 1->7->6->NUllist llist.push(1); // Insert 4 at the end. So linked list becomes // 1->7->6->4->NUllist llist.append(4); // Insert 8, after 7. So linked list becomes // 1->7->8->6->4->NUllist llist.insertAfter(llist.head.next, 8); System.out.println("\nCreated Linked list is: "); llist.printList(); }}// This code is contributed by Rajat Mishra
# A complete working Python program to demonstrate all# insertion methods of linked list # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # This function is in LinkedList class. Inserts a # new node after the given prev_node. This method is # defined inside LinkedList class shown above */ def insertAfter(self, prev_node, new_data): # 1. check if the given prev_node exists if prev_node is None: print("The given previous node must inLinkedList.") return # 2. create new node & # Put in the data new_node = Node(new_data) # 4. Make next of new Node as next of prev_node new_node.next = prev_node.next # 5. make next of prev_node as new_node prev_node.next = new_node # This function is defined in Linked List class # Appends a new node at the end. This method is # defined inside LinkedList class shown above */ def append(self, new_data): # 1. Create a new node # 2. Put in the data # 3. Set next as None new_node = Node(new_data) # 4. If the Linked List is empty, then make the # new node as head if self.head is None: self.head = new_node return # 5. Else traverse till the last node last = self.head while (last.next): last = last.next # 6. Change the next of last node last.next = new_node # Utility function to print the linked list def printList(self): temp = self.head while (temp): print(temp.data,end=" ") temp = temp.next # Code execution starts hereif __name__=='__main__': # Start with the empty list llist = LinkedList() # Insert 6. So linked list becomes 6->None llist.append(6) # Insert 7 at the beginning. So linked list becomes 7->6->None llist.push(7); # Insert 1 at the beginning. So linked list becomes 1->7->6->None llist.push(1); # Insert 4 at the end. So linked list becomes 1->7->6->4->None llist.append(4) # Insert 8, after 7. So linked list becomes 1 -> 7-> 8-> 6-> 4-> None llist.insertAfter(llist.head.next, 8) print('Created linked list is: ') llist.printList() # This code is contributed by Manikantan Narasimhan
// A complete working C# program to demonstrate // all insertion methods on linked listusing System; class GFG{ public Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) {data = d; next = null;} } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Inserts a new node after the given prev_node. */ public void insertAfter(Node prev_node, int new_data) { /* 1. Check if the given Node is null */ if (prev_node == null) { Console.WriteLine("The given previous" + " node cannot be null"); return; } /* 2 & 3: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 4. Make next of new Node as next of prev_node */ new_node.next = prev_node.next; /* 5. make next of prev_node as new_node */ prev_node.next = new_node; } /* Appends a new node at the end. This method is defined inside LinkedList class shown above */ public void append(int new_data) { /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ Node new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; /* 5. Else traverse till the last node */ Node last = head; while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; return; } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { Console.Write(tnode.data + " "); tnode = tnode.next; } } // Driver Code public static void Main(String[] args) { /* Start with the empty list */ GFG llist = new GFG(); // Insert 6. So linked list becomes 6->NUllist llist.append(6); // Insert 7 at the beginning. // So linked list becomes 7->6->NUllist llist.push(7); // Insert 1 at the beginning. // So linked list becomes 1->7->6->NUllist llist.push(1); // Insert 4 at the end. So linked list becomes // 1->7->6->4->NUllist llist.append(4); // Insert 8, after 7. So linked list becomes // 1->7->8->6->4->NUllist llist.insertAfter(llist.head.next, 8); Console.Write("Created Linked list is: "); llist.printList(); }} // This code is contributed by Rajput-Ji
<script> // A complete working javascript program // to demonstrate all insertion methods// on linked list var head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Inserts a new node after the given prev_node. */ function insertAfter(prev_node , new_data) { /* 1. Check if the given Node is null */ if (prev_node == null) { document.write( "The given previous node cannot be null" ); return; } /* * 2 & 3: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 4. Make next of new Node as next of prev_node */ new_node.next = prev_node.next; /* 5. make next of prev_node as new_node */ prev_node.next = new_node; } /* * Appends a new node at the end. This method is defined inside LinkedList class * shown above */ function append(new_data) { /* * 1. Allocate the Node & 2. Put in the data 3. Set next as null */ var new_node = new Node(new_data); /* * 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* * 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; /* 5. Else traverse till the last node */ var last = head; while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; return; } /* * This function prints contents of linked list starting from the given node */ function printList() {var tnode = head; while (tnode != null) { document.write(tnode.data + " "); tnode = tnode.next; } } /* * Driver program to test above functions. Ideally this function should be in a * separate user class. It is kept here to keep code compact */ /* Start with the empty list */ // Insert 6. So linked list becomes 6->NUllist append(6); // Insert 7 at the beginning. So linked list becomes // 7->6->NUllist push(7); // Insert 1 at the beginning. So linked list becomes // 1->7->6->NUllist push(1); // Insert 4 at the end. So linked list becomes // 1->7->6->4->NUllist append(4); // Insert 8, after 7. So linked list becomes // 1->7->8->6->4->NUllist insertAfter(head.next, 8); document.write("\nCreated Linked list is: "); printList(); // This code contributed by gauravrajput1 </script>
Output:
Created Linked list is: 1 7 8 6 4
Time Complexity : O(n) Auxiliary Space : O(1)
However there is another method which uses constructor call inside the node class in order to minimize the memory allocation work. It also minimizes the number of lines of code.
C++
// Alternate method to declare the class in order to minimize the memory allocation work #include <iostream>using namespace std; class node {public: int data; node* next; node(int value) // A constructor is called here { data = value; // it automatic assigns the value to the data next = NULL; // next pointer is pointed to NULL }}; // function to insert a element at head positionvoid insertathead(node*& head, int val){ node* n = new node(val); n->next = head; head = n;} // function to insert a element at a specified positionvoid insertafter(node* head, int key, int val){ node* n = new node(val); if (key == head->data) { n->next = head->next; head->next = n; return; } node* temp = head; while (temp->data != key) { temp = temp->next; if (temp == NULL) { return; } } n->next = temp->next; temp->next = n;} // function to insert a element at the endvoid insertattail(node*& head, int val){ node* n = new node(val); if (head == NULL) { head = n; return; } node* temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = n;} // function to print the singly linked listvoid print(node*& head){ node* temp = head; while (temp != NULL) { cout << temp->data << " -> "; temp = temp->next; } cout << "NULL" << endl;} // main functionint main(){ node* head = NULL; //declaring an empty linked list insertathead(head, 1); insertathead(head, 2); cout << "After insertion at head: "; print(head); cout << endl; insertattail(head, 4); insertattail(head, 5); cout << "After insertion at tail: "; print(head); cout << endl; insertafter(head, 1, 2); insertafter(head, 5, 6); cout << "After insertion at a given position: "; print(head); cout << endl; return 0;} // contributed by divyanshmishra101010
After insertion at head: 2 -> 1 -> NULL
After insertion at tail: 2 -> 1 -> 4 -> 5 -> NULL
After insertion at a given position: 2 -> 1 -> 2 -> 4 -> 5 -> 6 -> NULL
Time Complexity : O(n) Auxiliary Space : O(1)
You may like to try Practice MCQ Questions on Linked List Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rathbhupendra
Rajput-Ji
anmolgautam818
todaysgaurav
aashish1995
GauravRajput1
simranarora5sos
arkajbasak121
simmytarika5
whoibrar
divyanshmishra101010
polymatir3j
TCS
Wipro
Linked List
Wipro
TCS
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 284,
"s": 52,
"text": "We have introduced Linked Lists in the previous post. We also created a simple linked list with 3 nodes and discussed linked list traversal.All programs discussed in this post consider the following representations of linked list. "
},
{
"code": null,
"e": 288,
"s": 284,
"text": "C++"
},
{
"code": null,
"e": 290,
"s": 288,
"text": "C"
},
{
"code": null,
"e": 295,
"s": 290,
"text": "Java"
},
{
"code": null,
"e": 303,
"s": 295,
"text": "Python3"
},
{
"code": null,
"e": 306,
"s": 303,
"text": "C#"
},
{
"code": null,
"e": 317,
"s": 306,
"text": "Javascript"
},
{
"code": "// A linked list node class Node { public: int data; Node *next; }; // This code is contributed by rathbhupendra",
"e": 441,
"s": 317,
"text": null
},
{
"code": "// A linked list nodestruct Node{ int data; struct Node *next;};",
"e": 508,
"s": 441,
"text": null
},
{
"code": "// Linked List Classclass LinkedList{ Node head; // head of list /* Node Class */ class Node { int data; Node next; // Constructor to create a new node Node(int d) {data = d; next = null; } }}",
"e": 758,
"s": 508,
"text": null
},
{
"code": "# Node classclass Node: # Function to initialize the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List classclass LinkedList: # Function to initialize the Linked List object def __init__(self): self.head = None",
"e": 1088,
"s": 758,
"text": null
},
{
"code": "/* Linked list Node*/public class Node{ public int data; public Node next; public Node(int d) {data = d; next = null; }}",
"e": 1218,
"s": 1088,
"text": null
},
{
"code": "<script>// Linked List Class var head; // head of list /* Node Class */ class Node { // Constructor to create a new node constructor(d) { this.data = d; this.next = null; } }// This code is contributed by todaysgaurav </script>",
"e": 1505,
"s": 1218,
"text": null
},
{
"code": null,
"e": 1514,
"s": 1505,
"text": "Chapters"
},
{
"code": null,
"e": 1541,
"s": 1514,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 1591,
"s": 1541,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 1614,
"s": 1591,
"text": "captions off, selected"
},
{
"code": null,
"e": 1622,
"s": 1614,
"text": "English"
},
{
"code": null,
"e": 1646,
"s": 1622,
"text": "This is a modal window."
},
{
"code": null,
"e": 1715,
"s": 1646,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 1737,
"s": 1715,
"text": "End of dialog window."
},
{
"code": null,
"e": 1937,
"s": 1737,
"text": "In this post, methods to insert a new node in linked list are discussed. A node can be added in three ways 1) At the front of the linked list 2) After a given node. 3) At the end of the linked list."
},
{
"code": null,
"e": 2458,
"s": 1937,
"text": "Add a node at the front: (4 steps process) The new node is always added before the head of the given Linked List. And newly added node becomes the new head of the Linked List. For example, if the given Linked List is 10->15->20->25 and we add an item 5 at the front, then the Linked List becomes 5->10->15->20->25. Let us call the function that adds at the front of the list is push(). The push() must receive a pointer to the head pointer, because push must change the head pointer to point to the new node (See this) "
},
{
"code": null,
"e": 2512,
"s": 2458,
"text": "Following are the 4 steps to add a node at the front."
},
{
"code": null,
"e": 2516,
"s": 2512,
"text": "C++"
},
{
"code": null,
"e": 2518,
"s": 2516,
"text": "C"
},
{
"code": null,
"e": 2523,
"s": 2518,
"text": "Java"
},
{
"code": null,
"e": 2531,
"s": 2523,
"text": "Python3"
},
{
"code": null,
"e": 2534,
"s": 2531,
"text": "C#"
},
{
"code": null,
"e": 2545,
"s": 2534,
"text": "Javascript"
},
{
"code": "/* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */void push(Node** head_ref, int new_data) { /* 1. allocate node */ Node* new_node = new Node(); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head */ new_node->next = (*head_ref); /* 4. move the head to point to the new node */ (*head_ref) = new_node; } // This code is contributed by rathbhupendra",
"e": 3039,
"s": 2545,
"text": null
},
{
"code": "/* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head */ new_node->next = (*head_ref); /* 4. move the head to point to the new node */ (*head_ref) = new_node;}",
"e": 3537,
"s": 3039,
"text": null
},
{
"code": "/* This function is in LinkedList class. Inserts a new Node at front of the list. This method is defined inside LinkedList class shown above */public void push(int new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;}",
"e": 3959,
"s": 3537,
"text": null
},
{
"code": "# This function is in LinkedList class# Function to insert a new node at the beginningdef push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node",
"e": 4317,
"s": 3959,
"text": null
},
{
"code": "/* Inserts a new Node at front of the list. */public void push(int new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;}",
"e": 4638,
"s": 4317,
"text": null
},
{
"code": "<script> /* This function is in LinkedList class. Inserts a new Node at front of the list. This method is defined inside LinkedList class shown above */ function push(new_data){ /* 1 & 2: Allocate the Node & Put in the data*/ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} // This code contributed by Rajput-Ji </script>",
"e": 5119,
"s": 4638,
"text": null
},
{
"code": null,
"e": 5313,
"s": 5119,
"text": "We have a pointer to the head and we can directly attach a node and change the pointer. So the Time complexity of inserting a node at head position is O(1) as it does a constant amount of work."
},
{
"code": null,
"e": 5448,
"s": 5313,
"text": "Add a node after a given node: (5 steps process) We are given a pointer to a node, and the new node is inserted after the given node. "
},
{
"code": null,
"e": 5452,
"s": 5448,
"text": "C++"
},
{
"code": null,
"e": 5454,
"s": 5452,
"text": "C"
},
{
"code": null,
"e": 5459,
"s": 5454,
"text": "Java"
},
{
"code": null,
"e": 5467,
"s": 5459,
"text": "Python3"
},
{
"code": null,
"e": 5470,
"s": 5467,
"text": "C#"
},
{
"code": null,
"e": 5481,
"s": 5470,
"text": "Javascript"
},
{
"code": "// Given a node prev_node, insert a// new node after the given// prev_nodevoid insertAfter(Node* prev_node, int new_data){ // 1. Check if the given prev_node is NULL if (prev_node == NULL) { cout << \"The given previous node cannot be NULL\"; return; } // 2. Allocate new node Node* new_node = new Node(); // 3. Put in the data new_node->data = new_data; // 4. Make next of new node as // next of prev_node new_node->next = prev_node->next; // 5. move the next of prev_node // as new_node prev_node->next = new_node;} // This code is contributed by anmolgautam818,// arkajyotibasak",
"e": 6125,
"s": 5481,
"text": null
},
{
"code": "/* Given a node prev_node, insert a new node after the givenprev_node */void insertAfter(struct Node* prev_node, int new_data){ /*1. check if the given prev_node is NULL */ if (prev_node == NULL) { printf(\"the given previous node cannot be NULL\"); return; } /* 2. allocate new node */ struct Node* new_node = (struct Node*)malloc(sizeof(struct Node)); /* 3. put in the data */ new_node->data = new_data; /* 4. Make next of new node as next of prev_node */ new_node->next = prev_node->next; /* 5. move the next of prev_node as new_node */ prev_node->next = new_node;}",
"e": 6754,
"s": 6125,
"text": null
},
{
"code": "/* This function is in LinkedList class.Inserts a new node after the given prev_node. This method isdefined inside LinkedList class shown above */public void insertAfter(Node prev_node, int new_data){ /* 1. Check if the given Node is null */ if (prev_node == null) { System.out.println( \"The given previous node cannot be null\"); return; } /* 2. Allocate the Node & 3. Put in the data*/ Node new_node = new Node(new_data); /* 4. Make next of new Node as next of prev_node */ new_node.next = prev_node.next; /* 5. make next of prev_node as new_node */ prev_node.next = new_node;}",
"e": 7394,
"s": 6754,
"text": null
},
{
"code": "# This function is in LinkedList class.# Inserts a new node after the given prev_node. This method is# defined inside LinkedList class shown above */ def insertAfter(self, prev_node, new_data): # 1. check if the given prev_node exists if prev_node is None: print(\"The given previous node must inLinkedList.\") return # 2. Create new node & # 3. Put in the data new_node = Node(new_data) # 4. Make next of new Node as next of prev_node new_node.next = prev_node.next # 5. make next of prev_node as new_node prev_node.next = new_node",
"e": 7977,
"s": 7394,
"text": null
},
{
"code": "/* Inserts a new node after the given prev_node. */public void insertAfter(Node prev_node, int new_data){ /* 1. Check if the given Node is null */ if (prev_node == null) { Console.WriteLine(\"The given previous node\" + \" cannot be null\"); return; } /* 2 & 3: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 4. Make next of new Node as next of prev_node */ new_node.next = prev_node.next; /* 5. make next of prev_node as new_node */ prev_node.next = new_node;}",
"e": 8582,
"s": 7977,
"text": null
},
{
"code": "<script> /* This function is in LinkedList class. Inserts a new node after the given prev_node. This method is defined inside LinkedList class shown above */function insertAfter(prev_node , new_data) { /* 1. Check if the given Node is null */ if (prev_node == null) { document.write(\"The given previous node cannot be null\"); return; } /* 2. Allocate the Node & 3. Put in the data*/ var new_node = new Node(new_data); /* 4. Make next of new Node as next of prev_node */ new_node.next = prev_node.next; /* 5. make next of prev_node as new_node */ prev_node.next = new_node; } // This code is contributed by aashish1995 </script>",
"e": 9277,
"s": 8582,
"text": null
},
{
"code": null,
"e": 9376,
"s": 9277,
"text": "Time complexity of insertAfter() is O(n) as it depends on n where n is the size of the linked list"
},
{
"code": null,
"e": 9445,
"s": 9376,
"text": "Space complexity: O(1) since using constant space to modify pointers"
},
{
"code": null,
"e": 9865,
"s": 9445,
"text": "Add a node at the end: (6 steps process) The new node is always added after the last node of the given Linked List. For example if the given Linked List is 5->10->15->20->25 and we add an item 30 at the end, then the Linked List becomes 5->10->15->20->25->30. Since a Linked List is typically represented by the head of it, we have to traverse the list till the end and then change the next to last node to a new node. "
},
{
"code": null,
"e": 9915,
"s": 9865,
"text": "Following are the 6 steps to add node at the end."
},
{
"code": null,
"e": 9919,
"s": 9915,
"text": "C++"
},
{
"code": null,
"e": 9921,
"s": 9919,
"text": "C"
},
{
"code": null,
"e": 9926,
"s": 9921,
"text": "Java"
},
{
"code": null,
"e": 9934,
"s": 9926,
"text": "Python3"
},
{
"code": null,
"e": 9937,
"s": 9934,
"text": "C#"
},
{
"code": null,
"e": 9948,
"s": 9937,
"text": "Javascript"
},
{
"code": "// Given a reference (pointer to pointer) to the head // of a list and an int, appends a new node at the end void append(Node** head_ref, int new_data) { // 1. allocate node Node* new_node = new Node(); // Used in step 5 Node *last = *head_ref; // 2. Put in the data new_node->data = new_data; // 3. This new node is going to be // the last node, so make next of // it as NULL new_node->next = NULL; // 4. If the Linked List is empty, // then make the new node as head if (*head_ref == NULL) { *head_ref = new_node; return; } // 5. Else traverse till the last node while (last->next != NULL) { last = last->next; } // 6. Change the next of last node last->next = new_node; return; } // This code is contributed by anmolgautam818, arkajyotibasak",
"e": 10847,
"s": 9948,
"text": null
},
{
"code": "/* Given a reference (pointer to pointer) to the head of a list and an int, appends a new node at the end */void append(struct Node** head_ref, int new_data){ /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); struct Node *last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) last = last->next; /* 6. Change the next of last node */ last->next = new_node; return; }",
"e": 11694,
"s": 10847,
"text": null
},
{
"code": "/* Appends a new node at the end. This method is defined inside LinkedList class shown above */public void append(int new_data){ /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ Node new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; /* 5. Else traverse till the last node */ Node last = head; while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; return;}",
"e": 12434,
"s": 11694,
"text": null
},
{
"code": "# This function is defined in Linked List class# Appends a new node at the end. This method is# defined inside LinkedList class shown above def append(self, new_data): # 1. Create a new node # 2. Put in the data # 3. Set next as None new_node = Node(new_data) # 4. If the Linked List is empty, then make the # new node as head if self.head is None: self.head = new_node return # 5. Else traverse till the last node last = self.head while (last.next): last = last.next # 6. Change the next of last node last.next = new_node",
"e": 13089,
"s": 12434,
"text": null
},
{
"code": "/* Appends a new node at the end. This method is defined inside LinkedList class shown above */public void append(int new_data){ /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ Node new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; /* 5. Else traverse till the last node */ Node last = head; while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; return;}",
"e": 13812,
"s": 13089,
"text": null
},
{
"code": "<script> /* Appends a new node at the end. This method is defined inside LinkedList class shown above */ function append(new_data){ /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ var new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; /* 5. Else traverse till the last node */ var last = head; while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; return;} // This code contributed by aashish1995</script>",
"e": 14604,
"s": 13812,
"text": null
},
{
"code": null,
"e": 14868,
"s": 14604,
"text": "Time complexity of append is O(n) where n is the number of nodes in the linked list. Since there is a loop from head to end, the function does O(n) work. This method can also be optimized to work in O(1) by keeping an extra pointer to the tail of the linked list/"
},
{
"code": null,
"e": 14960,
"s": 14868,
"text": "Following is a complete program that uses all of the above methods to create a linked list."
},
{
"code": null,
"e": 14964,
"s": 14960,
"text": "C++"
},
{
"code": null,
"e": 14966,
"s": 14964,
"text": "C"
},
{
"code": null,
"e": 14971,
"s": 14966,
"text": "Java"
},
{
"code": null,
"e": 14979,
"s": 14971,
"text": "Python3"
},
{
"code": null,
"e": 14982,
"s": 14979,
"text": "C#"
},
{
"code": null,
"e": 14993,
"s": 14982,
"text": "Javascript"
},
{
"code": "// A complete working C++ program to demonstrate // all insertion methods on Linked List #include <bits/stdc++.h>using namespace std; // A linked list node class Node { public: int data; Node *next; }; /* Given a reference (pointer to pointer)to the head of a list and an int, insertsa new node on the front of the list. */void push(Node** head_ref, int new_data) { /* 1. allocate node */ Node* new_node = new Node(); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head */ new_node->next = (*head_ref); /* 4. move the head to point to the new node */ (*head_ref) = new_node; } /* Given a node prev_node, insert a new node after the given prev_node */void insertAfter(Node* prev_node, int new_data) { /*1. check if the given prev_node is NULL */ if (prev_node == NULL) { cout<<\"The given previous node cannot be NULL\"; return; } /* 2. allocate new node */ Node* new_node = new Node(); /* 3. put in the data */ new_node->data = new_data; /* 4. Make next of new node as next of prev_node */ new_node->next = prev_node->next; /* 5. move the next of prev_node as new_node */ prev_node->next = new_node; } /* Given a reference (pointer to pointer) to the head of a list and an int, appends a new node at the end */void append(Node** head_ref, int new_data) { /* 1. allocate node */ Node* new_node = new Node(); Node *last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) { last = last->next; } /* 6. Change the next of last node */ last->next = new_node; return; } // This function prints contents of// linked list starting from head void printList(Node *node) { while (node != NULL) { cout<<\" \"<<node->data; node = node->next; } } /* Driver code*/int main() { /* Start with the empty list */ Node* head = NULL; // Insert 6. So linked list becomes 6->NULL append(&head, 6); // Insert 7 at the beginning. // So linked list becomes 7->6->NULL push(&head, 7); // Insert 1 at the beginning. // So linked list becomes 1->7->6->NULL push(&head, 1); // Insert 4 at the end. So // linked list becomes 1->7->6->4->NULL append(&head, 4); // Insert 8, after 7. So linked // list becomes 1->7->8->6->4->NULL insertAfter(head->next, 8); cout<<\"Created Linked list is: \"; printList(head); return 0; } // This code is contributed by rathbhupendra, arkajyotibasak",
"e": 17983,
"s": 14993,
"text": null
},
{
"code": "// A complete working C program to demonstrate all insertion methods// on Linked List#include <stdio.h>#include <stdlib.h> // A linked list nodestruct Node{ int data; struct Node *next;}; /* Given a reference (pointer to pointer) to the head of a list and an int, inserts a new node on the front of the list. */void push(struct Node** head_ref, int new_data){ /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); /* 2. put in the data */ new_node->data = new_data; /* 3. Make next of new node as head */ new_node->next = (*head_ref); /* 4. move the head to point to the new node */ (*head_ref) = new_node;} /* Given a node prev_node, insert a new node after the given prev_node */void insertAfter(struct Node* prev_node, int new_data){ /*1. check if the given prev_node is NULL */ if (prev_node == NULL) { printf(\"the given previous node cannot be NULL\"); return; } /* 2. allocate new node */ struct Node* new_node =(struct Node*) malloc(sizeof(struct Node)); /* 3. put in the data */ new_node->data = new_data; /* 4. Make next of new node as next of prev_node */ new_node->next = prev_node->next; /* 5. move the next of prev_node as new_node */ prev_node->next = new_node;} /* Given a reference (pointer to pointer) to the head of a list and an int, appends a new node at the end */void append(struct Node** head_ref, int new_data){ /* 1. allocate node */ struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); struct Node *last = *head_ref; /* used in step 5*/ /* 2. put in the data */ new_node->data = new_data; /* 3. This new node is going to be the last node, so make next of it as NULL*/ new_node->next = NULL; /* 4. If the Linked List is empty, then make the new node as head */ if (*head_ref == NULL) { *head_ref = new_node; return; } /* 5. Else traverse till the last node */ while (last->next != NULL) last = last->next; /* 6. Change the next of last node */ last->next = new_node; return;} // This function prints contents of linked list starting from headvoid printList(struct Node *node){ while (node != NULL) { printf(\" %d \", node->data); node = node->next; }} /* Driver program to test above functions*/int main(){ /* Start with the empty list */ struct Node* head = NULL; // Insert 6. So linked list becomes 6->NULL append(&head, 6); // Insert 7 at the beginning. So linked list becomes 7->6->NULL push(&head, 7); // Insert 1 at the beginning. So linked list becomes 1->7->6->NULL push(&head, 1); // Insert 4 at the end. So linked list becomes 1->7->6->4->NULL append(&head, 4); // Insert 8, after 7. So linked list becomes 1->7->8->6->4->NULL insertAfter(head->next, 8); printf(\"\\n Created Linked list is: \"); printList(head); return 0;}",
"e": 20929,
"s": 17983,
"text": null
},
{
"code": "// A complete working Java program to demonstrate all insertion methods// on linked listclass LinkedList{ Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) {data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Inserts a new node after the given prev_node. */ public void insertAfter(Node prev_node, int new_data) { /* 1. Check if the given Node is null */ if (prev_node == null) { System.out.println(\"The given previous node cannot be null\"); return; } /* 2 & 3: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 4. Make next of new Node as next of prev_node */ new_node.next = prev_node.next; /* 5. make next of prev_node as new_node */ prev_node.next = new_node; } /* Appends a new node at the end. This method is defined inside LinkedList class shown above */ public void append(int new_data) { /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ Node new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; /* 5. Else traverse till the last node */ Node last = head; while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; return; } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { System.out.print(tnode.data+\" \"); tnode = tnode.next; } } /* Driver program to test above functions. Ideally this function should be in a separate user class. It is kept here to keep code compact */ public static void main(String[] args) { /* Start with the empty list */ LinkedList llist = new LinkedList(); // Insert 6. So linked list becomes 6->NUllist llist.append(6); // Insert 7 at the beginning. So linked list becomes // 7->6->NUllist llist.push(7); // Insert 1 at the beginning. So linked list becomes // 1->7->6->NUllist llist.push(1); // Insert 4 at the end. So linked list becomes // 1->7->6->4->NUllist llist.append(4); // Insert 8, after 7. So linked list becomes // 1->7->8->6->4->NUllist llist.insertAfter(llist.head.next, 8); System.out.println(\"\\nCreated Linked list is: \"); llist.printList(); }}// This code is contributed by Rajat Mishra",
"e": 24270,
"s": 20929,
"text": null
},
{
"code": "# A complete working Python program to demonstrate all# insertion methods of linked list # Node classclass Node: # Function to initialise the node object def __init__(self, data): self.data = data # Assign data self.next = None # Initialize next as null # Linked List class contains a Node objectclass LinkedList: # Function to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): # 1 & 2: Allocate the Node & # Put in the data new_node = Node(new_data) # 3. Make next of new Node as head new_node.next = self.head # 4. Move the head to point to new Node self.head = new_node # This function is in LinkedList class. Inserts a # new node after the given prev_node. This method is # defined inside LinkedList class shown above */ def insertAfter(self, prev_node, new_data): # 1. check if the given prev_node exists if prev_node is None: print(\"The given previous node must inLinkedList.\") return # 2. create new node & # Put in the data new_node = Node(new_data) # 4. Make next of new Node as next of prev_node new_node.next = prev_node.next # 5. make next of prev_node as new_node prev_node.next = new_node # This function is defined in Linked List class # Appends a new node at the end. This method is # defined inside LinkedList class shown above */ def append(self, new_data): # 1. Create a new node # 2. Put in the data # 3. Set next as None new_node = Node(new_data) # 4. If the Linked List is empty, then make the # new node as head if self.head is None: self.head = new_node return # 5. Else traverse till the last node last = self.head while (last.next): last = last.next # 6. Change the next of last node last.next = new_node # Utility function to print the linked list def printList(self): temp = self.head while (temp): print(temp.data,end=\" \") temp = temp.next # Code execution starts hereif __name__=='__main__': # Start with the empty list llist = LinkedList() # Insert 6. So linked list becomes 6->None llist.append(6) # Insert 7 at the beginning. So linked list becomes 7->6->None llist.push(7); # Insert 1 at the beginning. So linked list becomes 1->7->6->None llist.push(1); # Insert 4 at the end. So linked list becomes 1->7->6->4->None llist.append(4) # Insert 8, after 7. So linked list becomes 1 -> 7-> 8-> 6-> 4-> None llist.insertAfter(llist.head.next, 8) print('Created linked list is: ') llist.printList() # This code is contributed by Manikantan Narasimhan",
"e": 27213,
"s": 24270,
"text": null
},
{
"code": "// A complete working C# program to demonstrate // all insertion methods on linked listusing System; class GFG{ public Node head; // head of list /* Linked list Node*/ public class Node { public int data; public Node next; public Node(int d) {data = d; next = null;} } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Inserts a new node after the given prev_node. */ public void insertAfter(Node prev_node, int new_data) { /* 1. Check if the given Node is null */ if (prev_node == null) { Console.WriteLine(\"The given previous\" + \" node cannot be null\"); return; } /* 2 & 3: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 4. Make next of new Node as next of prev_node */ new_node.next = prev_node.next; /* 5. make next of prev_node as new_node */ prev_node.next = new_node; } /* Appends a new node at the end. This method is defined inside LinkedList class shown above */ public void append(int new_data) { /* 1. Allocate the Node & 2. Put in the data 3. Set next as null */ Node new_node = new Node(new_data); /* 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; /* 5. Else traverse till the last node */ Node last = head; while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; return; } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { Console.Write(tnode.data + \" \"); tnode = tnode.next; } } // Driver Code public static void Main(String[] args) { /* Start with the empty list */ GFG llist = new GFG(); // Insert 6. So linked list becomes 6->NUllist llist.append(6); // Insert 7 at the beginning. // So linked list becomes 7->6->NUllist llist.push(7); // Insert 1 at the beginning. // So linked list becomes 1->7->6->NUllist llist.push(1); // Insert 4 at the end. So linked list becomes // 1->7->6->4->NUllist llist.append(4); // Insert 8, after 7. So linked list becomes // 1->7->8->6->4->NUllist llist.insertAfter(llist.head.next, 8); Console.Write(\"Created Linked list is: \"); llist.printList(); }} // This code is contributed by Rajput-Ji",
"e": 30461,
"s": 27213,
"text": null
},
{
"code": "<script> // A complete working javascript program // to demonstrate all insertion methods// on linked list var head; // head of list /* Linked list Node */ class Node { constructor(val) { this.data = val; this.next = null; } } /* Inserts a new Node at front of the list. */ function push(new_data) { /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Inserts a new node after the given prev_node. */ function insertAfter(prev_node , new_data) { /* 1. Check if the given Node is null */ if (prev_node == null) { document.write( \"The given previous node cannot be null\" ); return; } /* * 2 & 3: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 4. Make next of new Node as next of prev_node */ new_node.next = prev_node.next; /* 5. make next of prev_node as new_node */ prev_node.next = new_node; } /* * Appends a new node at the end. This method is defined inside LinkedList class * shown above */ function append(new_data) { /* * 1. Allocate the Node & 2. Put in the data 3. Set next as null */ var new_node = new Node(new_data); /* * 4. If the Linked List is empty, then make the new node as head */ if (head == null) { head = new Node(new_data); return; } /* * 4. This new node is going to be the last node, so make next of it as null */ new_node.next = null; /* 5. Else traverse till the last node */ var last = head; while (last.next != null) last = last.next; /* 6. Change the next of last node */ last.next = new_node; return; } /* * This function prints contents of linked list starting from the given node */ function printList() {var tnode = head; while (tnode != null) { document.write(tnode.data + \" \"); tnode = tnode.next; } } /* * Driver program to test above functions. Ideally this function should be in a * separate user class. It is kept here to keep code compact */ /* Start with the empty list */ // Insert 6. So linked list becomes 6->NUllist append(6); // Insert 7 at the beginning. So linked list becomes // 7->6->NUllist push(7); // Insert 1 at the beginning. So linked list becomes // 1->7->6->NUllist push(1); // Insert 4 at the end. So linked list becomes // 1->7->6->4->NUllist append(4); // Insert 8, after 7. So linked list becomes // 1->7->8->6->4->NUllist insertAfter(head.next, 8); document.write(\"\\nCreated Linked list is: \"); printList(); // This code contributed by gauravrajput1 </script>",
"e": 33730,
"s": 30461,
"text": null
},
{
"code": null,
"e": 33738,
"s": 33730,
"text": "Output:"
},
{
"code": null,
"e": 33778,
"s": 33738,
"text": " Created Linked list is: 1 7 8 6 4"
},
{
"code": null,
"e": 33825,
"s": 33778,
"text": "Time Complexity : O(n) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 34003,
"s": 33825,
"text": "However there is another method which uses constructor call inside the node class in order to minimize the memory allocation work. It also minimizes the number of lines of code."
},
{
"code": null,
"e": 34007,
"s": 34003,
"text": "C++"
},
{
"code": "// Alternate method to declare the class in order to minimize the memory allocation work #include <iostream>using namespace std; class node {public: int data; node* next; node(int value) // A constructor is called here { data = value; // it automatic assigns the value to the data next = NULL; // next pointer is pointed to NULL }}; // function to insert a element at head positionvoid insertathead(node*& head, int val){ node* n = new node(val); n->next = head; head = n;} // function to insert a element at a specified positionvoid insertafter(node* head, int key, int val){ node* n = new node(val); if (key == head->data) { n->next = head->next; head->next = n; return; } node* temp = head; while (temp->data != key) { temp = temp->next; if (temp == NULL) { return; } } n->next = temp->next; temp->next = n;} // function to insert a element at the endvoid insertattail(node*& head, int val){ node* n = new node(val); if (head == NULL) { head = n; return; } node* temp = head; while (temp->next != NULL) { temp = temp->next; } temp->next = n;} // function to print the singly linked listvoid print(node*& head){ node* temp = head; while (temp != NULL) { cout << temp->data << \" -> \"; temp = temp->next; } cout << \"NULL\" << endl;} // main functionint main(){ node* head = NULL; //declaring an empty linked list insertathead(head, 1); insertathead(head, 2); cout << \"After insertion at head: \"; print(head); cout << endl; insertattail(head, 4); insertattail(head, 5); cout << \"After insertion at tail: \"; print(head); cout << endl; insertafter(head, 1, 2); insertafter(head, 5, 6); cout << \"After insertion at a given position: \"; print(head); cout << endl; return 0;} // contributed by divyanshmishra101010",
"e": 36052,
"s": 34007,
"text": null
},
{
"code": null,
"e": 36216,
"s": 36052,
"text": "After insertion at head: 2 -> 1 -> NULL\n\nAfter insertion at tail: 2 -> 1 -> 4 -> 5 -> NULL\n\nAfter insertion at a given position: 2 -> 1 -> 2 -> 4 -> 5 -> 6 -> NULL"
},
{
"code": null,
"e": 36263,
"s": 36216,
"text": "Time Complexity : O(n) Auxiliary Space : O(1) "
},
{
"code": null,
"e": 36447,
"s": 36263,
"text": "You may like to try Practice MCQ Questions on Linked List Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 36461,
"s": 36447,
"text": "rathbhupendra"
},
{
"code": null,
"e": 36471,
"s": 36461,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 36486,
"s": 36471,
"text": "anmolgautam818"
},
{
"code": null,
"e": 36499,
"s": 36486,
"text": "todaysgaurav"
},
{
"code": null,
"e": 36511,
"s": 36499,
"text": "aashish1995"
},
{
"code": null,
"e": 36525,
"s": 36511,
"text": "GauravRajput1"
},
{
"code": null,
"e": 36541,
"s": 36525,
"text": "simranarora5sos"
},
{
"code": null,
"e": 36555,
"s": 36541,
"text": "arkajbasak121"
},
{
"code": null,
"e": 36568,
"s": 36555,
"text": "simmytarika5"
},
{
"code": null,
"e": 36577,
"s": 36568,
"text": "whoibrar"
},
{
"code": null,
"e": 36598,
"s": 36577,
"text": "divyanshmishra101010"
},
{
"code": null,
"e": 36610,
"s": 36598,
"text": "polymatir3j"
},
{
"code": null,
"e": 36614,
"s": 36610,
"text": "TCS"
},
{
"code": null,
"e": 36620,
"s": 36614,
"text": "Wipro"
},
{
"code": null,
"e": 36632,
"s": 36620,
"text": "Linked List"
},
{
"code": null,
"e": 36638,
"s": 36632,
"text": "Wipro"
},
{
"code": null,
"e": 36642,
"s": 36638,
"text": "TCS"
},
{
"code": null,
"e": 36654,
"s": 36642,
"text": "Linked List"
}
] |
TCS Placement Paper | Email Writing Question 10
|
21 May, 2019
Pre-requisite: Procedure to E-mail WritingThis is a TCS model placement email-writing question. It covers the important directions along with a sample solution to the question.
Directions:
Use all the phrases given.Minimum words should be 70 otherwise your email cannot be validated.Addressing and signing should be done as in the question given.Common grammatical rules, punctuation should be according to standard English.You can use your own phrases along with the phrases given.
Use all the phrases given.
Minimum words should be 70 otherwise your email cannot be validated.
Addressing and signing should be done as in the question given.
Common grammatical rules, punctuation should be according to standard English.
You can use your own phrases along with the phrases given.
Question:As your company is doing good business and expanding, your company is relocating its office to a new address. Using the following phrases, write an email with a minimum of 70 words and a maximum of 100 words to your customer informing the change in address.
Phrases:
near outer ring road - shifting to - bigger office space - November 10 -
change in telephone number - new address is provided below - fourth floor -
Cessna Business Park.
Solution – Sample E-mail:
Dear All,It gives a pleasure in announcing the expansion of this company, a sign of growing business and increasing clientele. For a better productivity result, we are relocating the company and shifting to a bigger office space from November 10th onwards. New facilities and amenities shall be installed along with modern state of art amenities. There has been a change in telephone number along with the new address is provided below:Fourth Floor, Cessna Business Park(Near Outer Ring Road), Noida.Phone: 1234567890Please make a note of this to serve our clients better.Thanks and Regards
Note: You can write your own versions of e-mail keeping in mind the points needed to be taken care of while an e-mail. Refer Procedure to E-mail Writing.
interview-preparation
placement preparation
TCS
Placements
TCS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 May, 2019"
},
{
"code": null,
"e": 229,
"s": 52,
"text": "Pre-requisite: Procedure to E-mail WritingThis is a TCS model placement email-writing question. It covers the important directions along with a sample solution to the question."
},
{
"code": null,
"e": 241,
"s": 229,
"text": "Directions:"
},
{
"code": null,
"e": 535,
"s": 241,
"text": "Use all the phrases given.Minimum words should be 70 otherwise your email cannot be validated.Addressing and signing should be done as in the question given.Common grammatical rules, punctuation should be according to standard English.You can use your own phrases along with the phrases given."
},
{
"code": null,
"e": 562,
"s": 535,
"text": "Use all the phrases given."
},
{
"code": null,
"e": 631,
"s": 562,
"text": "Minimum words should be 70 otherwise your email cannot be validated."
},
{
"code": null,
"e": 695,
"s": 631,
"text": "Addressing and signing should be done as in the question given."
},
{
"code": null,
"e": 774,
"s": 695,
"text": "Common grammatical rules, punctuation should be according to standard English."
},
{
"code": null,
"e": 833,
"s": 774,
"text": "You can use your own phrases along with the phrases given."
},
{
"code": null,
"e": 1100,
"s": 833,
"text": "Question:As your company is doing good business and expanding, your company is relocating its office to a new address. Using the following phrases, write an email with a minimum of 70 words and a maximum of 100 words to your customer informing the change in address."
},
{
"code": null,
"e": 1109,
"s": 1100,
"text": "Phrases:"
},
{
"code": null,
"e": 1282,
"s": 1109,
"text": "near outer ring road - shifting to - bigger office space - November 10 -\nchange in telephone number - new address is provided below - fourth floor - \nCessna Business Park.\n"
},
{
"code": null,
"e": 1308,
"s": 1282,
"text": "Solution – Sample E-mail:"
},
{
"code": null,
"e": 1899,
"s": 1308,
"text": "Dear All,It gives a pleasure in announcing the expansion of this company, a sign of growing business and increasing clientele. For a better productivity result, we are relocating the company and shifting to a bigger office space from November 10th onwards. New facilities and amenities shall be installed along with modern state of art amenities. There has been a change in telephone number along with the new address is provided below:Fourth Floor, Cessna Business Park(Near Outer Ring Road), Noida.Phone: 1234567890Please make a note of this to serve our clients better.Thanks and Regards"
},
{
"code": null,
"e": 2053,
"s": 1899,
"text": "Note: You can write your own versions of e-mail keeping in mind the points needed to be taken care of while an e-mail. Refer Procedure to E-mail Writing."
},
{
"code": null,
"e": 2075,
"s": 2053,
"text": "interview-preparation"
},
{
"code": null,
"e": 2097,
"s": 2075,
"text": "placement preparation"
},
{
"code": null,
"e": 2101,
"s": 2097,
"text": "TCS"
},
{
"code": null,
"e": 2112,
"s": 2101,
"text": "Placements"
},
{
"code": null,
"e": 2116,
"s": 2112,
"text": "TCS"
}
] |
Packet Capturing using JnetPcap in Java
|
27 Feb, 2019
What is JnetPcap?
JnetPcap is an open-source Java library.It is java wrapper for all libpcap library native calls.It can be used to capture both live as well as offline data.Decoding packets is a special feature of Jnetpcap.For processing packets, you need pcap files which can be generated by using Wireshark.
JnetPcap is an open-source Java library.
It is java wrapper for all libpcap library native calls.
It can be used to capture both live as well as offline data.
Decoding packets is a special feature of Jnetpcap.
For processing packets, you need pcap files which can be generated by using Wireshark.
JNETPCAP Installation Steps:
For Windows: (x64)Download and Install the latest stable version of JRE and JDK for Windows 64 bits.Download and Install the latest stable version of Eclipse for Windows 64 bit.Download stable release of jNetPcap (for 64 bit Windows) from http://jnetpcap.com/download.Extract .rar file.After extraction, copy its data link library (jnetpcap.dll) to the system32 folder with administrative permission.Now open Eclipse, create the project. right click on the project, go to properties, go to java buildpath, click on Add External jars and provide the path to jnetpcap.jar.Write a program and run.
Download and Install the latest stable version of JRE and JDK for Windows 64 bits.Download and Install the latest stable version of Eclipse for Windows 64 bit.Download stable release of jNetPcap (for 64 bit Windows) from http://jnetpcap.com/download.Extract .rar file.After extraction, copy its data link library (jnetpcap.dll) to the system32 folder with administrative permission.Now open Eclipse, create the project. right click on the project, go to properties, go to java buildpath, click on Add External jars and provide the path to jnetpcap.jar.Write a program and run.
Download and Install the latest stable version of JRE and JDK for Windows 64 bits.
Download and Install the latest stable version of Eclipse for Windows 64 bit.
Download stable release of jNetPcap (for 64 bit Windows) from http://jnetpcap.com/download.
Extract .rar file.
After extraction, copy its data link library (jnetpcap.dll) to the system32 folder with administrative permission.
Now open Eclipse, create the project. right click on the project, go to properties, go to java build
path, click on Add External jars and provide the path to jnetpcap.jar.
Write a program and run.
For Linux: (x64)Prefer Ubuntu 14.04 or 16, .04 (Stable release). It contains java as default with OS installation.Install eclipse-full which will automatically install the latest supported java if it is not found. (from the command line or from software centre)Install g++ and libpcap-dev (from the command line as it does not comes in the software center if itnot an updated one).Download stable release of jNetPcap (for 64 bit Linux) from http://jnetpcap.com/download.Extract .rar file.After extraction, copy libjnetpcap.so and libjnetpcap-pcap100.so in /usr/lib/ (as sudo).Now open Eclipse, create the project. right click on the project, go to properties, go to java buildpath, click on Add External jars and provide the path to jnetpcap.jar.Write a program and run.
Prefer Ubuntu 14.04 or 16, .04 (Stable release). It contains java as default with OS installation.Install eclipse-full which will automatically install the latest supported java if it is not found. (from the command line or from software centre)Install g++ and libpcap-dev (from the command line as it does not comes in the software center if itnot an updated one).Download stable release of jNetPcap (for 64 bit Linux) from http://jnetpcap.com/download.Extract .rar file.After extraction, copy libjnetpcap.so and libjnetpcap-pcap100.so in /usr/lib/ (as sudo).Now open Eclipse, create the project. right click on the project, go to properties, go to java buildpath, click on Add External jars and provide the path to jnetpcap.jar.Write a program and run.
Prefer Ubuntu 14.04 or 16, .04 (Stable release). It contains java as default with OS installation.
Install eclipse-full which will automatically install the latest supported java if it is not found. (from the command line or from software centre)
Install g++ and libpcap-dev (from the command line as it does not comes in the software center if itnot an updated one).
Download stable release of jNetPcap (for 64 bit Linux) from http://jnetpcap.com/download.
Extract .rar file.
After extraction, copy libjnetpcap.so and libjnetpcap-pcap100.so in /usr/lib/ (as sudo).
Now open Eclipse, create the project. right click on the project, go to properties, go to java buildpath, click on Add External jars and provide the path to jnetpcap.jar.
Write a program and run.
What are pcap files?
Pcap stands for Packet Capture. It is used to capture network traffic. These pcap files can be read by applications such as tcpdump, wireshark, etc
Input: In this program, we will pass the folder name having pcap file as input.Output: The program will count the total number of packets in each pcap file.
First we will generate three pcap files from a live network using wireshark
Folder_having_pcap_file
From the above screenshot, we can see that we have 3 pcap files inside abc folder.
On opening these pcap files we can see:
3.pcap3.pcapTotal number of packets inside 3.pcap = 2330 2.pcap2.pcapTotal number of packets inside 2.pcap = 3361 1.pcap1.pcapTotal number of packets inside 1.pcap = 502 Now let’s deploy the above approach using java in any IDE :source_code
3.pcap3.pcapTotal number of packets inside 3.pcap = 2330
3.pcap
Total number of packets inside 3.pcap = 2330
2.pcap2.pcapTotal number of packets inside 2.pcap = 3361
2.pcap
Total number of packets inside 2.pcap = 3361
1.pcap1.pcapTotal number of packets inside 1.pcap = 502 Now let’s deploy the above approach using java in any IDE :source_code
1.pcap
Total number of packets inside 1.pcap = 502
Now let’s deploy the above approach using java in any IDE :
source_code
Source Code
// Counting the number of packets in pcap files. // User defined packagepackage jnt; import java.io.File;import org.jnetpcap.Pcap;import org.jnetpcap.packet.JPacket;import org.jnetpcap.packet.JPacketHandler; public class PacketCounter { // Path of the folder having pcap files // generated by Wireshark(change accordingly) static String folderpath = "/home/folder_where_you_have_pcap_files"; static double count = 0; static double globalcount = 0; // main function starts here public static void main(String[] args) { // Making the object of a file // and giving that object address // of the pcap folder File file = new File(folderpath); // Making file array which is used // to access each file // inside the folder one-by-one File[] files = file.listFiles(); // Accessing each file // one-by-one of files array for (File f : files) { // Getting each pcap file name String FILENAME = folderpath + f.getName(); // StringBuilder is used to get // error messages in case // if any error occurs StringBuilder errbuf = new StringBuilder(); // Making Pcap object an opening pcap file // in offline mode and passing pcap filename // and StringBuilder object to the function Pcap pcap = Pcap.openOffline(FILENAME, errbuf); // Here pcap object is used to start a loop // for capturing each packet of an // each pcap file(as a pcap file can // have many packets) one at a time, here -1 // indicates eof(end of file) i.e // until every packet is captured execute the // loop, we can also give some value // instead of -1 which will indicate the // number of packets to execute // in each pcap file pcap.loop(-1, new JPacketHandler() { // nextPacket is override function // of JPacketHandler( Handler which is // use to receive fully decoded packets) public void nextPacket(JPacket packet, StringBuilder errbuf) { // counter to count the number of packet // in each pcap file count++; } }, errbuf); System.out.println("File : " + f.getName() + " Number of Packets : " + count); // Global counter to count the total number // of packets in all pcap file globalcount = globalcount + count; count = 0; } System.out.println("Total Packets in folder : " + globalcount); }}
Output:
First Example:Input: “/home/abc/”(Folder’s name hardcoded in the program)Output: File : 1.pcap Number of Packets : 502.0File : 3.pcap Number of Packets : 2330.0File : 2.pcap Number of Packets : 3361.0Total Packets in folder : 6193.0
Second Example:Input: “/home/abc/”(Folder’s name hardcoded in the program)Output: File : tcp.pcap Number of Packets : 10.0File : http11.pcap Number of Packets : 9.0File : to_be_evaluated.pcap Number of Packets : 100.0File : abcd.pcapng Number of Packets : 2.0File : ACKStormAttack.pcap Number of Packets : 63.0Total Packets in folder : 184.0
Computer Networks
Java
Java
Computer Networks
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n27 Feb, 2019"
},
{
"code": null,
"e": 70,
"s": 52,
"text": "What is JnetPcap?"
},
{
"code": null,
"e": 363,
"s": 70,
"text": "JnetPcap is an open-source Java library.It is java wrapper for all libpcap library native calls.It can be used to capture both live as well as offline data.Decoding packets is a special feature of Jnetpcap.For processing packets, you need pcap files which can be generated by using Wireshark."
},
{
"code": null,
"e": 404,
"s": 363,
"text": "JnetPcap is an open-source Java library."
},
{
"code": null,
"e": 461,
"s": 404,
"text": "It is java wrapper for all libpcap library native calls."
},
{
"code": null,
"e": 522,
"s": 461,
"text": "It can be used to capture both live as well as offline data."
},
{
"code": null,
"e": 573,
"s": 522,
"text": "Decoding packets is a special feature of Jnetpcap."
},
{
"code": null,
"e": 660,
"s": 573,
"text": "For processing packets, you need pcap files which can be generated by using Wireshark."
},
{
"code": null,
"e": 689,
"s": 660,
"text": "JNETPCAP Installation Steps:"
},
{
"code": null,
"e": 1284,
"s": 689,
"text": "For Windows: (x64)Download and Install the latest stable version of JRE and JDK for Windows 64 bits.Download and Install the latest stable version of Eclipse for Windows 64 bit.Download stable release of jNetPcap (for 64 bit Windows) from http://jnetpcap.com/download.Extract .rar file.After extraction, copy its data link library (jnetpcap.dll) to the system32 folder with administrative permission.Now open Eclipse, create the project. right click on the project, go to properties, go to java buildpath, click on Add External jars and provide the path to jnetpcap.jar.Write a program and run."
},
{
"code": null,
"e": 1861,
"s": 1284,
"text": "Download and Install the latest stable version of JRE and JDK for Windows 64 bits.Download and Install the latest stable version of Eclipse for Windows 64 bit.Download stable release of jNetPcap (for 64 bit Windows) from http://jnetpcap.com/download.Extract .rar file.After extraction, copy its data link library (jnetpcap.dll) to the system32 folder with administrative permission.Now open Eclipse, create the project. right click on the project, go to properties, go to java buildpath, click on Add External jars and provide the path to jnetpcap.jar.Write a program and run."
},
{
"code": null,
"e": 1944,
"s": 1861,
"text": "Download and Install the latest stable version of JRE and JDK for Windows 64 bits."
},
{
"code": null,
"e": 2022,
"s": 1944,
"text": "Download and Install the latest stable version of Eclipse for Windows 64 bit."
},
{
"code": null,
"e": 2114,
"s": 2022,
"text": "Download stable release of jNetPcap (for 64 bit Windows) from http://jnetpcap.com/download."
},
{
"code": null,
"e": 2133,
"s": 2114,
"text": "Extract .rar file."
},
{
"code": null,
"e": 2248,
"s": 2133,
"text": "After extraction, copy its data link library (jnetpcap.dll) to the system32 folder with administrative permission."
},
{
"code": null,
"e": 2349,
"s": 2248,
"text": "Now open Eclipse, create the project. right click on the project, go to properties, go to java build"
},
{
"code": null,
"e": 2420,
"s": 2349,
"text": "path, click on Add External jars and provide the path to jnetpcap.jar."
},
{
"code": null,
"e": 2445,
"s": 2420,
"text": "Write a program and run."
},
{
"code": null,
"e": 3216,
"s": 2445,
"text": "For Linux: (x64)Prefer Ubuntu 14.04 or 16, .04 (Stable release). It contains java as default with OS installation.Install eclipse-full which will automatically install the latest supported java if it is not found. (from the command line or from software centre)Install g++ and libpcap-dev (from the command line as it does not comes in the software center if itnot an updated one).Download stable release of jNetPcap (for 64 bit Linux) from http://jnetpcap.com/download.Extract .rar file.After extraction, copy libjnetpcap.so and libjnetpcap-pcap100.so in /usr/lib/ (as sudo).Now open Eclipse, create the project. right click on the project, go to properties, go to java buildpath, click on Add External jars and provide the path to jnetpcap.jar.Write a program and run."
},
{
"code": null,
"e": 3971,
"s": 3216,
"text": "Prefer Ubuntu 14.04 or 16, .04 (Stable release). It contains java as default with OS installation.Install eclipse-full which will automatically install the latest supported java if it is not found. (from the command line or from software centre)Install g++ and libpcap-dev (from the command line as it does not comes in the software center if itnot an updated one).Download stable release of jNetPcap (for 64 bit Linux) from http://jnetpcap.com/download.Extract .rar file.After extraction, copy libjnetpcap.so and libjnetpcap-pcap100.so in /usr/lib/ (as sudo).Now open Eclipse, create the project. right click on the project, go to properties, go to java buildpath, click on Add External jars and provide the path to jnetpcap.jar.Write a program and run."
},
{
"code": null,
"e": 4070,
"s": 3971,
"text": "Prefer Ubuntu 14.04 or 16, .04 (Stable release). It contains java as default with OS installation."
},
{
"code": null,
"e": 4218,
"s": 4070,
"text": "Install eclipse-full which will automatically install the latest supported java if it is not found. (from the command line or from software centre)"
},
{
"code": null,
"e": 4339,
"s": 4218,
"text": "Install g++ and libpcap-dev (from the command line as it does not comes in the software center if itnot an updated one)."
},
{
"code": null,
"e": 4429,
"s": 4339,
"text": "Download stable release of jNetPcap (for 64 bit Linux) from http://jnetpcap.com/download."
},
{
"code": null,
"e": 4448,
"s": 4429,
"text": "Extract .rar file."
},
{
"code": null,
"e": 4537,
"s": 4448,
"text": "After extraction, copy libjnetpcap.so and libjnetpcap-pcap100.so in /usr/lib/ (as sudo)."
},
{
"code": null,
"e": 4708,
"s": 4537,
"text": "Now open Eclipse, create the project. right click on the project, go to properties, go to java buildpath, click on Add External jars and provide the path to jnetpcap.jar."
},
{
"code": null,
"e": 4733,
"s": 4708,
"text": "Write a program and run."
},
{
"code": null,
"e": 4754,
"s": 4733,
"text": "What are pcap files?"
},
{
"code": null,
"e": 4902,
"s": 4754,
"text": "Pcap stands for Packet Capture. It is used to capture network traffic. These pcap files can be read by applications such as tcpdump, wireshark, etc"
},
{
"code": null,
"e": 5059,
"s": 4902,
"text": "Input: In this program, we will pass the folder name having pcap file as input.Output: The program will count the total number of packets in each pcap file."
},
{
"code": null,
"e": 5135,
"s": 5059,
"text": "First we will generate three pcap files from a live network using wireshark"
},
{
"code": null,
"e": 5159,
"s": 5135,
"text": "Folder_having_pcap_file"
},
{
"code": null,
"e": 5242,
"s": 5159,
"text": "From the above screenshot, we can see that we have 3 pcap files inside abc folder."
},
{
"code": null,
"e": 5282,
"s": 5242,
"text": "On opening these pcap files we can see:"
},
{
"code": null,
"e": 5523,
"s": 5282,
"text": "3.pcap3.pcapTotal number of packets inside 3.pcap = 2330 2.pcap2.pcapTotal number of packets inside 2.pcap = 3361 1.pcap1.pcapTotal number of packets inside 1.pcap = 502 Now let’s deploy the above approach using java in any IDE :source_code"
},
{
"code": null,
"e": 5581,
"s": 5523,
"text": "3.pcap3.pcapTotal number of packets inside 3.pcap = 2330 "
},
{
"code": null,
"e": 5588,
"s": 5581,
"text": "3.pcap"
},
{
"code": null,
"e": 5634,
"s": 5588,
"text": "Total number of packets inside 3.pcap = 2330 "
},
{
"code": null,
"e": 5692,
"s": 5634,
"text": "2.pcap2.pcapTotal number of packets inside 2.pcap = 3361 "
},
{
"code": null,
"e": 5699,
"s": 5692,
"text": "2.pcap"
},
{
"code": null,
"e": 5745,
"s": 5699,
"text": "Total number of packets inside 2.pcap = 3361 "
},
{
"code": null,
"e": 5872,
"s": 5745,
"text": "1.pcap1.pcapTotal number of packets inside 1.pcap = 502 Now let’s deploy the above approach using java in any IDE :source_code"
},
{
"code": null,
"e": 5879,
"s": 5872,
"text": "1.pcap"
},
{
"code": null,
"e": 5924,
"s": 5879,
"text": "Total number of packets inside 1.pcap = 502 "
},
{
"code": null,
"e": 5984,
"s": 5924,
"text": "Now let’s deploy the above approach using java in any IDE :"
},
{
"code": null,
"e": 5996,
"s": 5984,
"text": "source_code"
},
{
"code": null,
"e": 6008,
"s": 5996,
"text": "Source Code"
},
{
"code": "// Counting the number of packets in pcap files. // User defined packagepackage jnt; import java.io.File;import org.jnetpcap.Pcap;import org.jnetpcap.packet.JPacket;import org.jnetpcap.packet.JPacketHandler; public class PacketCounter { // Path of the folder having pcap files // generated by Wireshark(change accordingly) static String folderpath = \"/home/folder_where_you_have_pcap_files\"; static double count = 0; static double globalcount = 0; // main function starts here public static void main(String[] args) { // Making the object of a file // and giving that object address // of the pcap folder File file = new File(folderpath); // Making file array which is used // to access each file // inside the folder one-by-one File[] files = file.listFiles(); // Accessing each file // one-by-one of files array for (File f : files) { // Getting each pcap file name String FILENAME = folderpath + f.getName(); // StringBuilder is used to get // error messages in case // if any error occurs StringBuilder errbuf = new StringBuilder(); // Making Pcap object an opening pcap file // in offline mode and passing pcap filename // and StringBuilder object to the function Pcap pcap = Pcap.openOffline(FILENAME, errbuf); // Here pcap object is used to start a loop // for capturing each packet of an // each pcap file(as a pcap file can // have many packets) one at a time, here -1 // indicates eof(end of file) i.e // until every packet is captured execute the // loop, we can also give some value // instead of -1 which will indicate the // number of packets to execute // in each pcap file pcap.loop(-1, new JPacketHandler() { // nextPacket is override function // of JPacketHandler( Handler which is // use to receive fully decoded packets) public void nextPacket(JPacket packet, StringBuilder errbuf) { // counter to count the number of packet // in each pcap file count++; } }, errbuf); System.out.println(\"File : \" + f.getName() + \" Number of Packets : \" + count); // Global counter to count the total number // of packets in all pcap file globalcount = globalcount + count; count = 0; } System.out.println(\"Total Packets in folder : \" + globalcount); }}",
"e": 8912,
"s": 6008,
"text": null
},
{
"code": null,
"e": 8920,
"s": 8912,
"text": "Output:"
},
{
"code": null,
"e": 9153,
"s": 8920,
"text": "First Example:Input: “/home/abc/”(Folder’s name hardcoded in the program)Output: File : 1.pcap Number of Packets : 502.0File : 3.pcap Number of Packets : 2330.0File : 2.pcap Number of Packets : 3361.0Total Packets in folder : 6193.0"
},
{
"code": null,
"e": 9495,
"s": 9153,
"text": "Second Example:Input: “/home/abc/”(Folder’s name hardcoded in the program)Output: File : tcp.pcap Number of Packets : 10.0File : http11.pcap Number of Packets : 9.0File : to_be_evaluated.pcap Number of Packets : 100.0File : abcd.pcapng Number of Packets : 2.0File : ACKStormAttack.pcap Number of Packets : 63.0Total Packets in folder : 184.0"
},
{
"code": null,
"e": 9513,
"s": 9495,
"text": "Computer Networks"
},
{
"code": null,
"e": 9518,
"s": 9513,
"text": "Java"
},
{
"code": null,
"e": 9523,
"s": 9518,
"text": "Java"
},
{
"code": null,
"e": 9541,
"s": 9523,
"text": "Computer Networks"
}
] |
list front() function in C++ STL
|
24 Jun, 2022
The list::front() is a built-in function in C++ STL which is used to return a reference to the first element in a list container. Unlike the list::begin() function, this function returns a direct reference to the first element in the list container. Syntax:
list_name.front()
Parameters: This function does not accept any parameter, it simply returns a reference to the first element in the list container. Return Value: This function returns a direct reference to the first element in the list container. Exception: This function creates an undefined behavior when used with an empty list container. Below program illustrates the list::front() function.
CPP
// CPP program to illustrate the// list::front() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // get the first element using front() int ele = demoList.front(); // Print the first element cout << ele; return 0;}
10
Note: This function works in constant time complexity.
Time complexity: O(1)
Auxiliary Space: O(n) where n is size of the list
kumargaurav97520
CPP-Functions
cpp-list
STL
C++
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Sorting a vector in C++
Polymorphism in C++
std::string class in C++
Friend class and function in C++
Pair in C++ Standard Template Library (STL)
Queue in C++ Standard Template Library (STL)
Unordered Sets in C++ Standard Template Library
std::find in C++
List in C++ Standard Template Library (STL)
Inline Functions in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n24 Jun, 2022"
},
{
"code": null,
"e": 311,
"s": 52,
"text": "The list::front() is a built-in function in C++ STL which is used to return a reference to the first element in a list container. Unlike the list::begin() function, this function returns a direct reference to the first element in the list container. Syntax: "
},
{
"code": null,
"e": 330,
"s": 311,
"text": "list_name.front() "
},
{
"code": null,
"e": 710,
"s": 330,
"text": "Parameters: This function does not accept any parameter, it simply returns a reference to the first element in the list container. Return Value: This function returns a direct reference to the first element in the list container. Exception: This function creates an undefined behavior when used with an empty list container. Below program illustrates the list::front() function. "
},
{
"code": null,
"e": 714,
"s": 710,
"text": "CPP"
},
{
"code": "// CPP program to illustrate the// list::front() function#include <bits/stdc++.h>using namespace std; int main(){ // Creating a list list<int> demoList; // Add elements to the List demoList.push_back(10); demoList.push_back(20); demoList.push_back(30); demoList.push_back(40); // get the first element using front() int ele = demoList.front(); // Print the first element cout << ele; return 0;}",
"e": 1149,
"s": 714,
"text": null
},
{
"code": null,
"e": 1152,
"s": 1149,
"text": "10"
},
{
"code": null,
"e": 1207,
"s": 1152,
"text": "Note: This function works in constant time complexity."
},
{
"code": null,
"e": 1229,
"s": 1207,
"text": "Time complexity: O(1)"
},
{
"code": null,
"e": 1279,
"s": 1229,
"text": "Auxiliary Space: O(n) where n is size of the list"
},
{
"code": null,
"e": 1296,
"s": 1279,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 1310,
"s": 1296,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1319,
"s": 1310,
"text": "cpp-list"
},
{
"code": null,
"e": 1323,
"s": 1319,
"text": "STL"
},
{
"code": null,
"e": 1327,
"s": 1323,
"text": "C++"
},
{
"code": null,
"e": 1331,
"s": 1327,
"text": "STL"
},
{
"code": null,
"e": 1335,
"s": 1331,
"text": "CPP"
},
{
"code": null,
"e": 1433,
"s": 1335,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1457,
"s": 1433,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1477,
"s": 1457,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 1502,
"s": 1477,
"text": "std::string class in C++"
},
{
"code": null,
"e": 1535,
"s": 1502,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 1579,
"s": 1535,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1624,
"s": 1579,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1672,
"s": 1624,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1689,
"s": 1672,
"text": "std::find in C++"
},
{
"code": null,
"e": 1733,
"s": 1689,
"text": "List in C++ Standard Template Library (STL)"
}
] |
Ford-Fulkerson Algorithm for Maximum Flow Problem
|
21 Jun, 2022
Given a graph which represents a flow network where every edge has a capacity. Also given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with following constraints:
Flow on an edge doesn’t exceed the given capacity of the edge.
Incoming flow is equal to outgoing flow for every vertex except s and t.
For example, consider the following graph from CLRS book.
The maximum possible flow in the above graph is 23.
Prerequisite : Max Flow Problem Introduction
Ford-Fulkerson Algorithm
The following is simple idea of Ford-Fulkerson algorithm:
Start with initial flow as 0.While there is a augmenting path from source to sink. Add this path-flow to flow.Return flow.
Start with initial flow as 0.
While there is a augmenting path from source to sink. Add this path-flow to flow.
Add this path-flow to flow.
Return flow.
Time Complexity: Time complexity of the above algorithm is O(max_flow * E). We run a loop while there is an augmenting path. In worst case, we may add 1 unit flow in every iteration. Therefore the time complexity becomes O(max_flow * E).
How to implement the above simple algorithm? Let us first define the concept of Residual Graph which is needed for understanding the implementation.
Residual Graph of a flow network is a graph which indicates additional possible flow. If there is a path from source to sink in residual graph, then it is possible to add flow. Every edge of a residual graph has a value called residual capacity which is equal to original capacity of the edge minus current flow. Residual capacity is basically the current capacity of the edge.
Let us now talk about implementation details. Residual capacity is 0 if there is no edge between two vertices of residual graph. We can initialize the residual graph as original graph as there is no initial flow and initially residual capacity is equal to original capacity. To find an augmenting path, we can either do a BFS or DFS of the residual graph. We have used BFS in below implementation. Using BFS, we can find out if there is a path from source to sink. BFS also builds parent[] array. Using the parent[] array, we traverse through the found path and find possible flow through this path by finding minimum residual capacity along the path. We later add the found path flow to overall flow.
The important thing is, we need to update residual capacities in the residual graph. We subtract path flow from all edges along the path and we add path flow along the reverse edges We need to add path flow along reverse edges because may later need to send flow in reverse direction (See following link for example).https://www.geeksforgeeks.org/max-flow-problem-introduction/
Below is the implementation of Ford-Fulkerson algorithm. To keep things simple, graph is represented as a 2D matrix.
C++
Java
Python
C#
Javascript
// C++ program for implementation of Ford Fulkerson// algorithm#include <iostream>#include <limits.h>#include <queue>#include <string.h>using namespace std; // Number of vertices in given graph#define V 6 /* Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path */bool bfs(int rGraph[V][V], int s, int t, int parent[]){ // Create a visited array and mark all vertices as not // visited bool visited[V]; memset(visited, 0, sizeof(visited)); // Create a queue, enqueue source vertex and mark source // vertex as visited queue<int> q; q.push(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (!q.empty()) { int u = q.front(); q.pop(); for (int v = 0; v < V; v++) { if (visited[v] == false && rGraph[u][v] > 0) { // If we find a connection to the sink node, // then there is no point in BFS anymore We // just have to set its parent and can return // true if (v == t) { parent[v] = u; return true; } q.push(v); parent[v] = u; visited[v] = true; } } } // We didn't reach sink in BFS starting from source, so // return false return false;} // Returns the maximum flow from s to t in the given graphint fordFulkerson(int graph[V][V], int s, int t){ int u, v; // Create a residual graph and fill the residual graph // with given capacities in the original graph as // residual capacities in residual graph int rGraph[V] [V]; // Residual graph where rGraph[i][j] // indicates residual capacity of edge // from i to j (if there is an edge. If // rGraph[i][j] is 0, then there is not) for (u = 0; u < V; u++) for (v = 0; v < V; v++) rGraph[u][v] = graph[u][v]; int parent[V]; // This array is filled by BFS and to // store path int max_flow = 0; // There is no flow initially // Augment the flow while there is path from source to // sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edges along // the path filled by BFS. Or we can say find the // maximum flow through the path found. int path_flow = INT_MAX; for (v = t; v != s; v = parent[v]) { u = parent[v]; path_flow = min(path_flow, rGraph[u][v]); } // update residual capacities of the edges and // reverse edges along the path for (v = t; v != s; v = parent[v]) { u = parent[v]; rGraph[u][v] -= path_flow; rGraph[v][u] += path_flow; } // Add path flow to overall flow max_flow += path_flow; } // Return the overall flow return max_flow;} // Driver program to test above functionsint main(){ // Let us create a graph shown in the above example int graph[V][V] = { { 0, 16, 13, 0, 0, 0 }, { 0, 0, 10, 12, 0, 0 }, { 0, 4, 0, 0, 14, 0 }, { 0, 0, 9, 0, 0, 20 }, { 0, 0, 0, 7, 0, 4 }, { 0, 0, 0, 0, 0, 0 } }; cout << "The maximum possible flow is " << fordFulkerson(graph, 0, 5); return 0;}
// Java program for implementation of Ford Fulkerson// algorithmimport java.io.*;import java.lang.*;import java.util.*;import java.util.LinkedList; class MaxFlow { static final int V = 6; // Number of vertices in graph /* Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path */ boolean bfs(int rGraph[][], int s, int t, int parent[]) { // Create a visited array and mark all vertices as // not visited boolean visited[] = new boolean[V]; for (int i = 0; i < V; ++i) visited[i] = false; // Create a queue, enqueue source vertex and mark // source vertex as visited LinkedList<Integer> queue = new LinkedList<Integer>(); queue.add(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (queue.size() != 0) { int u = queue.poll(); for (int v = 0; v < V; v++) { if (visited[v] == false && rGraph[u][v] > 0) { // If we find a connection to the sink // node, then there is no point in BFS // anymore We just have to set its parent // and can return true if (v == t) { parent[v] = u; return true; } queue.add(v); parent[v] = u; visited[v] = true; } } } // We didn't reach sink in BFS starting from source, // so return false return false; } // Returns the maximum flow from s to t in the given // graph int fordFulkerson(int graph[][], int s, int t) { int u, v; // Create a residual graph and fill the residual // graph with given capacities in the original graph // as residual capacities in residual graph // Residual graph where rGraph[i][j] indicates // residual capacity of edge from i to j (if there // is an edge. If rGraph[i][j] is 0, then there is // not) int rGraph[][] = new int[V][V]; for (u = 0; u < V; u++) for (v = 0; v < V; v++) rGraph[u][v] = graph[u][v]; // This array is filled by BFS and to store path int parent[] = new int[V]; int max_flow = 0; // There is no flow initially // Augment the flow while there is path from source // to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes // along the path filled by BFS. Or we can say // find the maximum flow through the path found. int path_flow = Integer.MAX_VALUE; for (v = t; v != s; v = parent[v]) { u = parent[v]; path_flow = Math.min(path_flow, rGraph[u][v]); } // update residual capacities of the edges and // reverse edges along the path for (v = t; v != s; v = parent[v]) { u = parent[v]; rGraph[u][v] -= path_flow; rGraph[v][u] += path_flow; } // Add path flow to overall flow max_flow += path_flow; } // Return the overall flow return max_flow; } // Driver program to test above functions public static void main(String[] args) throws java.lang.Exception { // Let us create a graph shown in the above example int graph[][] = new int[][] { { 0, 16, 13, 0, 0, 0 }, { 0, 0, 10, 12, 0, 0 }, { 0, 4, 0, 0, 14, 0 }, { 0, 0, 9, 0, 0, 20 }, { 0, 0, 0, 7, 0, 4 }, { 0, 0, 0, 0, 0, 0 } }; MaxFlow m = new MaxFlow(); System.out.println("The maximum possible flow is " + m.fordFulkerson(graph, 0, 5)); }}
# Python program for implementation# of Ford Fulkerson algorithmfrom collections import defaultdict # This class represents a directed graph# using adjacency matrix representationclass Graph: def __init__(self, graph): self.graph = graph # residual graph self. ROW = len(graph) # self.COL = len(gr[0]) '''Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path ''' def BFS(self, s, t, parent): # Mark all the vertices as not visited visited = [False]*(self.ROW) # Create a queue for BFS queue = [] # Mark the source node as visited and enqueue it queue.append(s) visited[s] = True # Standard BFS Loop while queue: # Dequeue a vertex from queue and print it u = queue.pop(0) # Get all adjacent vertices of the dequeued vertex u # If a adjacent has not been visited, then mark it # visited and enqueue it for ind, val in enumerate(self.graph[u]): if visited[ind] == False and val > 0: # If we find a connection to the sink node, # then there is no point in BFS anymore # We just have to set its parent and can return true queue.append(ind) visited[ind] = True parent[ind] = u if ind == t: return True # We didn't reach sink in BFS starting # from source, so return false return False # Returns the maximum flow from s to t in the given graph def FordFulkerson(self, source, sink): # This array is filled by BFS and to store path parent = [-1]*(self.ROW) max_flow = 0 # There is no flow initially # Augment the flow while there is path from source to sink while self.BFS(source, sink, parent) : # Find minimum residual capacity of the edges along the # path filled by BFS. Or we can say find the maximum flow # through the path found. path_flow = float("Inf") s = sink while(s != source): path_flow = min (path_flow, self.graph[parent[s]][s]) s = parent[s] # Add path flow to overall flow max_flow += path_flow # update residual capacities of the edges and reverse edges # along the path v = sink while(v != source): u = parent[v] self.graph[u][v] -= path_flow self.graph[v][u] += path_flow v = parent[v] return max_flow # Create a graph given in the above diagram graph = [[0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0]] g = Graph(graph) source = 0; sink = 5 print ("The maximum possible flow is %d " % g.FordFulkerson(source, sink)) # This code is contributed by Neelam Yadav
// C# program for implementation// of Ford Fulkerson algorithmusing System;using System.Collections.Generic; public class MaxFlow { static readonly int V = 6; // Number of vertices in // graph /* Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path */ bool bfs(int[, ] rGraph, int s, int t, int[] parent) { // Create a visited array and mark // all vertices as not visited bool[] visited = new bool[V]; for (int i = 0; i < V; ++i) visited[i] = false; // Create a queue, enqueue source vertex and mark // source vertex as visited List<int> queue = new List<int>(); queue.Add(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (queue.Count != 0) { int u = queue[0]; queue.RemoveAt(0); for (int v = 0; v < V; v++) { if (visited[v] == false && rGraph[u, v] > 0) { // If we find a connection to the sink // node, then there is no point in BFS // anymore We just have to set its parent // and can return true if (v == t) { parent[v] = u; return true; } queue.Add(v); parent[v] = u; visited[v] = true; } } } // We didn't reach sink in BFS starting from source, // so return false return false; } // Returns the maximum flow // from s to t in the given graph int fordFulkerson(int[, ] graph, int s, int t) { int u, v; // Create a residual graph and fill // the residual graph with given // capacities in the original graph as // residual capacities in residual graph // Residual graph where rGraph[i,j] // indicates residual capacity of // edge from i to j (if there is an // edge. If rGraph[i,j] is 0, then // there is not) int[, ] rGraph = new int[V, V]; for (u = 0; u < V; u++) for (v = 0; v < V; v++) rGraph[u, v] = graph[u, v]; // This array is filled by BFS and to store path int[] parent = new int[V]; int max_flow = 0; // There is no flow initially // Augment the flow while there is path from source // to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes // along the path filled by BFS. Or we can say // find the maximum flow through the path found. int path_flow = int.MaxValue; for (v = t; v != s; v = parent[v]) { u = parent[v]; path_flow = Math.Min(path_flow, rGraph[u, v]); } // update residual capacities of the edges and // reverse edges along the path for (v = t; v != s; v = parent[v]) { u = parent[v]; rGraph[u, v] -= path_flow; rGraph[v, u] += path_flow; } // Add path flow to overall flow max_flow += path_flow; } // Return the overall flow return max_flow; } // Driver code public static void Main() { // Let us create a graph shown in the above example int[, ] graph = new int[, ] { { 0, 16, 13, 0, 0, 0 }, { 0, 0, 10, 12, 0, 0 }, { 0, 4, 0, 0, 14, 0 }, { 0, 0, 9, 0, 0, 20 }, { 0, 0, 0, 7, 0, 4 }, { 0, 0, 0, 0, 0, 0 } }; MaxFlow m = new MaxFlow(); Console.WriteLine("The maximum possible flow is " + m.fordFulkerson(graph, 0, 5)); }} /* This code contributed by PrinciRaj1992 */
<script> // Javascript program for implementation of Ford// Fulkerson algorithm // Number of vertices in graphlet V = 6; // Returns true if there is a path from source// 's' to sink 't' in residual graph. Also// fills parent[] to store the pathfunction bfs(rGraph, s, t, parent){ // Create a visited array and mark all // vertices as not visited let visited = new Array(V); for(let i = 0; i < V; ++i) visited[i] = false; // Create a queue, enqueue source vertex // and mark source vertex as visited let queue = []; queue.push(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (queue.length != 0) { let u = queue.shift(); for(let v = 0; v < V; v++) { if (visited[v] == false && rGraph[u][v] > 0) { // If we find a connection to the sink // node, then there is no point in BFS // anymore We just have to set its parent // and can return true if (v == t) { parent[v] = u; return true; } queue.push(v); parent[v] = u; visited[v] = true; } } } // We didn't reach sink in BFS starting // from source, so return false return false;} // Returns the maximum flow from s to t in// the given graphfunction fordFulkerson(graph, s, t){ let u, v; // Create a residual graph and fill the // residual graph with given capacities // in the original graph as residual // capacities in residual graph // Residual graph where rGraph[i][j] // indicates residual capacity of edge // from i to j (if there is an edge. // If rGraph[i][j] is 0, then there is // not) let rGraph = new Array(V); for(u = 0; u < V; u++) { rGraph[u] = new Array(V); for(v = 0; v < V; v++) rGraph[u][v] = graph[u][v]; } // This array is filled by BFS and to store path let parent = new Array(V); // There is no flow initially let max_flow = 0; // Augment the flow while there // is path from source to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes // along the path filled by BFS. Or we can say // find the maximum flow through the path found. let path_flow = Number.MAX_VALUE; for(v = t; v != s; v = parent[v]) { u = parent[v]; path_flow = Math.min(path_flow, rGraph[u][v]); } // Update residual capacities of the edges and // reverse edges along the path for(v = t; v != s; v = parent[v]) { u = parent[v]; rGraph[u][v] -= path_flow; rGraph[v][u] += path_flow; } // Add path flow to overall flow max_flow += path_flow; } // Return the overall flow return max_flow;} // Driver code // Let us create a graph shown in the above examplelet graph = [ [ 0, 16, 13, 0, 0, 0 ], [ 0, 0, 10, 12, 0, 0 ], [ 0, 4, 0, 0, 14, 0 ], [ 0, 0, 9, 0, 0, 20 ], [ 0, 0, 0, 7, 0, 4 ], [ 0, 0, 0, 0, 0, 0 ] ];document.write("The maximum possible flow is " + fordFulkerson(graph, 0, 5)); // This code is contributed by avanitrachhadiya2155 </script>
The maximum possible flow is 23
The above implementation of Ford Fulkerson Algorithm is called Edmonds-Karp Algorithm. The idea of Edmonds-Karp is to use BFS in Ford Fulkerson implementation as BFS always picks a path with minimum number of edges. When BFS is used, the worst case time complexity can be reduced to O(VE2). The above implementation uses adjacency matrix representation though where BFS takes O(V2) time, the time complexity of the above implementation is O(EV3) (Refer CLRS book for proof of time complexity)
This is an important problem as it arises in many practical situations. Examples include, maximizing the transportation with given traffic limits, maximizing packet flow in computer networks.Dinc’s Algorithm for Max-Flow.
Exercise: Modify the above implementation so that it that runs in O(VE2) time.
S3Reuis
princiraj1992
lukasz1908
eyenpix
avanitrachhadiya2155
varshagumber28
simmytarika5
hardikkoriintern
Max-Flow
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 264,
"s": 52,
"text": "Given a graph which represents a flow network where every edge has a capacity. Also given two vertices source ‘s’ and sink ‘t’ in the graph, find the maximum possible flow from s to t with following constraints:"
},
{
"code": null,
"e": 327,
"s": 264,
"text": "Flow on an edge doesn’t exceed the given capacity of the edge."
},
{
"code": null,
"e": 400,
"s": 327,
"text": "Incoming flow is equal to outgoing flow for every vertex except s and t."
},
{
"code": null,
"e": 459,
"s": 400,
"text": "For example, consider the following graph from CLRS book. "
},
{
"code": null,
"e": 512,
"s": 459,
"text": "The maximum possible flow in the above graph is 23. "
},
{
"code": null,
"e": 557,
"s": 512,
"text": "Prerequisite : Max Flow Problem Introduction"
},
{
"code": null,
"e": 583,
"s": 557,
"text": "Ford-Fulkerson Algorithm "
},
{
"code": null,
"e": 642,
"s": 583,
"text": " The following is simple idea of Ford-Fulkerson algorithm:"
},
{
"code": null,
"e": 765,
"s": 642,
"text": "Start with initial flow as 0.While there is a augmenting path from source to sink. Add this path-flow to flow.Return flow."
},
{
"code": null,
"e": 795,
"s": 765,
"text": "Start with initial flow as 0."
},
{
"code": null,
"e": 877,
"s": 795,
"text": "While there is a augmenting path from source to sink. Add this path-flow to flow."
},
{
"code": null,
"e": 905,
"s": 877,
"text": "Add this path-flow to flow."
},
{
"code": null,
"e": 918,
"s": 905,
"text": "Return flow."
},
{
"code": null,
"e": 1156,
"s": 918,
"text": "Time Complexity: Time complexity of the above algorithm is O(max_flow * E). We run a loop while there is an augmenting path. In worst case, we may add 1 unit flow in every iteration. Therefore the time complexity becomes O(max_flow * E)."
},
{
"code": null,
"e": 1306,
"s": 1156,
"text": "How to implement the above simple algorithm? Let us first define the concept of Residual Graph which is needed for understanding the implementation. "
},
{
"code": null,
"e": 1685,
"s": 1306,
"text": "Residual Graph of a flow network is a graph which indicates additional possible flow. If there is a path from source to sink in residual graph, then it is possible to add flow. Every edge of a residual graph has a value called residual capacity which is equal to original capacity of the edge minus current flow. Residual capacity is basically the current capacity of the edge. "
},
{
"code": null,
"e": 2388,
"s": 1685,
"text": "Let us now talk about implementation details. Residual capacity is 0 if there is no edge between two vertices of residual graph. We can initialize the residual graph as original graph as there is no initial flow and initially residual capacity is equal to original capacity. To find an augmenting path, we can either do a BFS or DFS of the residual graph. We have used BFS in below implementation. Using BFS, we can find out if there is a path from source to sink. BFS also builds parent[] array. Using the parent[] array, we traverse through the found path and find possible flow through this path by finding minimum residual capacity along the path. We later add the found path flow to overall flow. "
},
{
"code": null,
"e": 2766,
"s": 2388,
"text": "The important thing is, we need to update residual capacities in the residual graph. We subtract path flow from all edges along the path and we add path flow along the reverse edges We need to add path flow along reverse edges because may later need to send flow in reverse direction (See following link for example).https://www.geeksforgeeks.org/max-flow-problem-introduction/"
},
{
"code": null,
"e": 2884,
"s": 2766,
"text": "Below is the implementation of Ford-Fulkerson algorithm. To keep things simple, graph is represented as a 2D matrix. "
},
{
"code": null,
"e": 2888,
"s": 2884,
"text": "C++"
},
{
"code": null,
"e": 2893,
"s": 2888,
"text": "Java"
},
{
"code": null,
"e": 2900,
"s": 2893,
"text": "Python"
},
{
"code": null,
"e": 2903,
"s": 2900,
"text": "C#"
},
{
"code": null,
"e": 2914,
"s": 2903,
"text": "Javascript"
},
{
"code": "// C++ program for implementation of Ford Fulkerson// algorithm#include <iostream>#include <limits.h>#include <queue>#include <string.h>using namespace std; // Number of vertices in given graph#define V 6 /* Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path */bool bfs(int rGraph[V][V], int s, int t, int parent[]){ // Create a visited array and mark all vertices as not // visited bool visited[V]; memset(visited, 0, sizeof(visited)); // Create a queue, enqueue source vertex and mark source // vertex as visited queue<int> q; q.push(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (!q.empty()) { int u = q.front(); q.pop(); for (int v = 0; v < V; v++) { if (visited[v] == false && rGraph[u][v] > 0) { // If we find a connection to the sink node, // then there is no point in BFS anymore We // just have to set its parent and can return // true if (v == t) { parent[v] = u; return true; } q.push(v); parent[v] = u; visited[v] = true; } } } // We didn't reach sink in BFS starting from source, so // return false return false;} // Returns the maximum flow from s to t in the given graphint fordFulkerson(int graph[V][V], int s, int t){ int u, v; // Create a residual graph and fill the residual graph // with given capacities in the original graph as // residual capacities in residual graph int rGraph[V] [V]; // Residual graph where rGraph[i][j] // indicates residual capacity of edge // from i to j (if there is an edge. If // rGraph[i][j] is 0, then there is not) for (u = 0; u < V; u++) for (v = 0; v < V; v++) rGraph[u][v] = graph[u][v]; int parent[V]; // This array is filled by BFS and to // store path int max_flow = 0; // There is no flow initially // Augment the flow while there is path from source to // sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edges along // the path filled by BFS. Or we can say find the // maximum flow through the path found. int path_flow = INT_MAX; for (v = t; v != s; v = parent[v]) { u = parent[v]; path_flow = min(path_flow, rGraph[u][v]); } // update residual capacities of the edges and // reverse edges along the path for (v = t; v != s; v = parent[v]) { u = parent[v]; rGraph[u][v] -= path_flow; rGraph[v][u] += path_flow; } // Add path flow to overall flow max_flow += path_flow; } // Return the overall flow return max_flow;} // Driver program to test above functionsint main(){ // Let us create a graph shown in the above example int graph[V][V] = { { 0, 16, 13, 0, 0, 0 }, { 0, 0, 10, 12, 0, 0 }, { 0, 4, 0, 0, 14, 0 }, { 0, 0, 9, 0, 0, 20 }, { 0, 0, 0, 7, 0, 4 }, { 0, 0, 0, 0, 0, 0 } }; cout << \"The maximum possible flow is \" << fordFulkerson(graph, 0, 5); return 0;}",
"e": 6280,
"s": 2914,
"text": null
},
{
"code": "// Java program for implementation of Ford Fulkerson// algorithmimport java.io.*;import java.lang.*;import java.util.*;import java.util.LinkedList; class MaxFlow { static final int V = 6; // Number of vertices in graph /* Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path */ boolean bfs(int rGraph[][], int s, int t, int parent[]) { // Create a visited array and mark all vertices as // not visited boolean visited[] = new boolean[V]; for (int i = 0; i < V; ++i) visited[i] = false; // Create a queue, enqueue source vertex and mark // source vertex as visited LinkedList<Integer> queue = new LinkedList<Integer>(); queue.add(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (queue.size() != 0) { int u = queue.poll(); for (int v = 0; v < V; v++) { if (visited[v] == false && rGraph[u][v] > 0) { // If we find a connection to the sink // node, then there is no point in BFS // anymore We just have to set its parent // and can return true if (v == t) { parent[v] = u; return true; } queue.add(v); parent[v] = u; visited[v] = true; } } } // We didn't reach sink in BFS starting from source, // so return false return false; } // Returns the maximum flow from s to t in the given // graph int fordFulkerson(int graph[][], int s, int t) { int u, v; // Create a residual graph and fill the residual // graph with given capacities in the original graph // as residual capacities in residual graph // Residual graph where rGraph[i][j] indicates // residual capacity of edge from i to j (if there // is an edge. If rGraph[i][j] is 0, then there is // not) int rGraph[][] = new int[V][V]; for (u = 0; u < V; u++) for (v = 0; v < V; v++) rGraph[u][v] = graph[u][v]; // This array is filled by BFS and to store path int parent[] = new int[V]; int max_flow = 0; // There is no flow initially // Augment the flow while there is path from source // to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes // along the path filled by BFS. Or we can say // find the maximum flow through the path found. int path_flow = Integer.MAX_VALUE; for (v = t; v != s; v = parent[v]) { u = parent[v]; path_flow = Math.min(path_flow, rGraph[u][v]); } // update residual capacities of the edges and // reverse edges along the path for (v = t; v != s; v = parent[v]) { u = parent[v]; rGraph[u][v] -= path_flow; rGraph[v][u] += path_flow; } // Add path flow to overall flow max_flow += path_flow; } // Return the overall flow return max_flow; } // Driver program to test above functions public static void main(String[] args) throws java.lang.Exception { // Let us create a graph shown in the above example int graph[][] = new int[][] { { 0, 16, 13, 0, 0, 0 }, { 0, 0, 10, 12, 0, 0 }, { 0, 4, 0, 0, 14, 0 }, { 0, 0, 9, 0, 0, 20 }, { 0, 0, 0, 7, 0, 4 }, { 0, 0, 0, 0, 0, 0 } }; MaxFlow m = new MaxFlow(); System.out.println(\"The maximum possible flow is \" + m.fordFulkerson(graph, 0, 5)); }}",
"e": 10251,
"s": 6280,
"text": null
},
{
"code": "# Python program for implementation# of Ford Fulkerson algorithmfrom collections import defaultdict # This class represents a directed graph# using adjacency matrix representationclass Graph: def __init__(self, graph): self.graph = graph # residual graph self. ROW = len(graph) # self.COL = len(gr[0]) '''Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path ''' def BFS(self, s, t, parent): # Mark all the vertices as not visited visited = [False]*(self.ROW) # Create a queue for BFS queue = [] # Mark the source node as visited and enqueue it queue.append(s) visited[s] = True # Standard BFS Loop while queue: # Dequeue a vertex from queue and print it u = queue.pop(0) # Get all adjacent vertices of the dequeued vertex u # If a adjacent has not been visited, then mark it # visited and enqueue it for ind, val in enumerate(self.graph[u]): if visited[ind] == False and val > 0: # If we find a connection to the sink node, # then there is no point in BFS anymore # We just have to set its parent and can return true queue.append(ind) visited[ind] = True parent[ind] = u if ind == t: return True # We didn't reach sink in BFS starting # from source, so return false return False # Returns the maximum flow from s to t in the given graph def FordFulkerson(self, source, sink): # This array is filled by BFS and to store path parent = [-1]*(self.ROW) max_flow = 0 # There is no flow initially # Augment the flow while there is path from source to sink while self.BFS(source, sink, parent) : # Find minimum residual capacity of the edges along the # path filled by BFS. Or we can say find the maximum flow # through the path found. path_flow = float(\"Inf\") s = sink while(s != source): path_flow = min (path_flow, self.graph[parent[s]][s]) s = parent[s] # Add path flow to overall flow max_flow += path_flow # update residual capacities of the edges and reverse edges # along the path v = sink while(v != source): u = parent[v] self.graph[u][v] -= path_flow self.graph[v][u] += path_flow v = parent[v] return max_flow # Create a graph given in the above diagram graph = [[0, 16, 13, 0, 0, 0], [0, 0, 10, 12, 0, 0], [0, 4, 0, 0, 14, 0], [0, 0, 9, 0, 0, 20], [0, 0, 0, 7, 0, 4], [0, 0, 0, 0, 0, 0]] g = Graph(graph) source = 0; sink = 5 print (\"The maximum possible flow is %d \" % g.FordFulkerson(source, sink)) # This code is contributed by Neelam Yadav",
"e": 13369,
"s": 10251,
"text": null
},
{
"code": "// C# program for implementation// of Ford Fulkerson algorithmusing System;using System.Collections.Generic; public class MaxFlow { static readonly int V = 6; // Number of vertices in // graph /* Returns true if there is a path from source 's' to sink 't' in residual graph. Also fills parent[] to store the path */ bool bfs(int[, ] rGraph, int s, int t, int[] parent) { // Create a visited array and mark // all vertices as not visited bool[] visited = new bool[V]; for (int i = 0; i < V; ++i) visited[i] = false; // Create a queue, enqueue source vertex and mark // source vertex as visited List<int> queue = new List<int>(); queue.Add(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (queue.Count != 0) { int u = queue[0]; queue.RemoveAt(0); for (int v = 0; v < V; v++) { if (visited[v] == false && rGraph[u, v] > 0) { // If we find a connection to the sink // node, then there is no point in BFS // anymore We just have to set its parent // and can return true if (v == t) { parent[v] = u; return true; } queue.Add(v); parent[v] = u; visited[v] = true; } } } // We didn't reach sink in BFS starting from source, // so return false return false; } // Returns the maximum flow // from s to t in the given graph int fordFulkerson(int[, ] graph, int s, int t) { int u, v; // Create a residual graph and fill // the residual graph with given // capacities in the original graph as // residual capacities in residual graph // Residual graph where rGraph[i,j] // indicates residual capacity of // edge from i to j (if there is an // edge. If rGraph[i,j] is 0, then // there is not) int[, ] rGraph = new int[V, V]; for (u = 0; u < V; u++) for (v = 0; v < V; v++) rGraph[u, v] = graph[u, v]; // This array is filled by BFS and to store path int[] parent = new int[V]; int max_flow = 0; // There is no flow initially // Augment the flow while there is path from source // to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes // along the path filled by BFS. Or we can say // find the maximum flow through the path found. int path_flow = int.MaxValue; for (v = t; v != s; v = parent[v]) { u = parent[v]; path_flow = Math.Min(path_flow, rGraph[u, v]); } // update residual capacities of the edges and // reverse edges along the path for (v = t; v != s; v = parent[v]) { u = parent[v]; rGraph[u, v] -= path_flow; rGraph[v, u] += path_flow; } // Add path flow to overall flow max_flow += path_flow; } // Return the overall flow return max_flow; } // Driver code public static void Main() { // Let us create a graph shown in the above example int[, ] graph = new int[, ] { { 0, 16, 13, 0, 0, 0 }, { 0, 0, 10, 12, 0, 0 }, { 0, 4, 0, 0, 14, 0 }, { 0, 0, 9, 0, 0, 20 }, { 0, 0, 0, 7, 0, 4 }, { 0, 0, 0, 0, 0, 0 } }; MaxFlow m = new MaxFlow(); Console.WriteLine(\"The maximum possible flow is \" + m.fordFulkerson(graph, 0, 5)); }} /* This code contributed by PrinciRaj1992 */",
"e": 17310,
"s": 13369,
"text": null
},
{
"code": "<script> // Javascript program for implementation of Ford// Fulkerson algorithm // Number of vertices in graphlet V = 6; // Returns true if there is a path from source// 's' to sink 't' in residual graph. Also// fills parent[] to store the pathfunction bfs(rGraph, s, t, parent){ // Create a visited array and mark all // vertices as not visited let visited = new Array(V); for(let i = 0; i < V; ++i) visited[i] = false; // Create a queue, enqueue source vertex // and mark source vertex as visited let queue = []; queue.push(s); visited[s] = true; parent[s] = -1; // Standard BFS Loop while (queue.length != 0) { let u = queue.shift(); for(let v = 0; v < V; v++) { if (visited[v] == false && rGraph[u][v] > 0) { // If we find a connection to the sink // node, then there is no point in BFS // anymore We just have to set its parent // and can return true if (v == t) { parent[v] = u; return true; } queue.push(v); parent[v] = u; visited[v] = true; } } } // We didn't reach sink in BFS starting // from source, so return false return false;} // Returns the maximum flow from s to t in// the given graphfunction fordFulkerson(graph, s, t){ let u, v; // Create a residual graph and fill the // residual graph with given capacities // in the original graph as residual // capacities in residual graph // Residual graph where rGraph[i][j] // indicates residual capacity of edge // from i to j (if there is an edge. // If rGraph[i][j] is 0, then there is // not) let rGraph = new Array(V); for(u = 0; u < V; u++) { rGraph[u] = new Array(V); for(v = 0; v < V; v++) rGraph[u][v] = graph[u][v]; } // This array is filled by BFS and to store path let parent = new Array(V); // There is no flow initially let max_flow = 0; // Augment the flow while there // is path from source to sink while (bfs(rGraph, s, t, parent)) { // Find minimum residual capacity of the edhes // along the path filled by BFS. Or we can say // find the maximum flow through the path found. let path_flow = Number.MAX_VALUE; for(v = t; v != s; v = parent[v]) { u = parent[v]; path_flow = Math.min(path_flow, rGraph[u][v]); } // Update residual capacities of the edges and // reverse edges along the path for(v = t; v != s; v = parent[v]) { u = parent[v]; rGraph[u][v] -= path_flow; rGraph[v][u] += path_flow; } // Add path flow to overall flow max_flow += path_flow; } // Return the overall flow return max_flow;} // Driver code // Let us create a graph shown in the above examplelet graph = [ [ 0, 16, 13, 0, 0, 0 ], [ 0, 0, 10, 12, 0, 0 ], [ 0, 4, 0, 0, 14, 0 ], [ 0, 0, 9, 0, 0, 20 ], [ 0, 0, 0, 7, 0, 4 ], [ 0, 0, 0, 0, 0, 0 ] ];document.write(\"The maximum possible flow is \" + fordFulkerson(graph, 0, 5)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 20792,
"s": 17310,
"text": null
},
{
"code": null,
"e": 20824,
"s": 20792,
"text": "The maximum possible flow is 23"
},
{
"code": null,
"e": 21317,
"s": 20824,
"text": "The above implementation of Ford Fulkerson Algorithm is called Edmonds-Karp Algorithm. The idea of Edmonds-Karp is to use BFS in Ford Fulkerson implementation as BFS always picks a path with minimum number of edges. When BFS is used, the worst case time complexity can be reduced to O(VE2). The above implementation uses adjacency matrix representation though where BFS takes O(V2) time, the time complexity of the above implementation is O(EV3) (Refer CLRS book for proof of time complexity)"
},
{
"code": null,
"e": 21539,
"s": 21317,
"text": "This is an important problem as it arises in many practical situations. Examples include, maximizing the transportation with given traffic limits, maximizing packet flow in computer networks.Dinc’s Algorithm for Max-Flow."
},
{
"code": null,
"e": 21618,
"s": 21539,
"text": "Exercise: Modify the above implementation so that it that runs in O(VE2) time."
},
{
"code": null,
"e": 21626,
"s": 21618,
"text": "S3Reuis"
},
{
"code": null,
"e": 21640,
"s": 21626,
"text": "princiraj1992"
},
{
"code": null,
"e": 21651,
"s": 21640,
"text": "lukasz1908"
},
{
"code": null,
"e": 21659,
"s": 21651,
"text": "eyenpix"
},
{
"code": null,
"e": 21680,
"s": 21659,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 21695,
"s": 21680,
"text": "varshagumber28"
},
{
"code": null,
"e": 21708,
"s": 21695,
"text": "simmytarika5"
},
{
"code": null,
"e": 21725,
"s": 21708,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 21734,
"s": 21725,
"text": "Max-Flow"
},
{
"code": null,
"e": 21740,
"s": 21734,
"text": "Graph"
},
{
"code": null,
"e": 21746,
"s": 21740,
"text": "Graph"
}
] |
ImageButton in Kotlin
|
28 Mar, 2022
Android ImageButton is a user interface widget which is used to display a button having image and to perform exactly like button when we click on it but here, we add an image on Image button instead of text. There are different types of buttons available in android like ImageButton, ToggleButton etc.
We can add an image to the button simply by using attribute android:src in activity_main.xml file or by using setImageResource() method.
In android, we can create ImageButton control in two ways either manually or programmatically.
First we create a new project by following the below steps:
Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish.
Click on File, then New => New Project.
After that include the Kotlin support and click on next.
Select the minimum SDK as per convenience and click next button.
Then select the Empty activity => next => finish.
In this file, we include the Edittext and ImageButton and set their attributes like id, layout_width, hint etc.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/linear_layout"> <EditText android:id="@+id/Num1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="50dp" android:ems="10" android:hint= "Enter first number"/> <EditText android:id="@+id/Num2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="50dp" android:ems="10" android:hint= "Enter second number"/> <ImageButton android:id="@+id/imageBtn" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="100dp" android:src="@android:drawable/btn_plus" /></LinearLayout>
Modify the strings.xml file to add application name
XML
<resources> <string name="app_name">ImageButtonInKotlin</string></resources>
First of all, we declare two variables num1 and num2 for both edittext and access them using the ids.
val num1 = findViewById(R.id.Num1)
val num2 = findViewById(R.id.Num2)
then, we declare variable imgbtn for the ImageButton and set the OnCLickListener to check the filled is empty or not
val imgbtn = findViewById(R.id.imageBtn)
imgbtn.setOnClickListener {
if (num1.text.toString().isEmpty() || num2.text.toString().isEmpty()) {
Toast.makeText(applicationContext,
"Enter both numbers", Toast.LENGTH_SHORT).show()
}
Kotlin
package com.geeksforgeeks.myfirstkotlinapp import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport android.widget.EditTextimport android.widget.ImageButtonimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val num1 = findViewById<EditText>(R.id.Num1) val num2 = findViewById<EditText>(R.id.Num2) val imgbtn = findViewById<ImageButton>(R.id.imageBtn) imgbtn.setOnClickListener { if (num1.text.toString().isEmpty() || num2.text.toString().isEmpty()) { Toast.makeText(applicationContext, "Enter both numbers", Toast.LENGTH_SHORT).show() } else { val num1 = Integer.parseInt(num1.text.toString()) val num2 = Integer.parseInt(num2.text.toString()) Toast.makeText(applicationContext, "Sum of the numbers = " + (num1 + num2), Toast.LENGTH_SHORT).show() } } }}
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.geeksforgeeks.myfirstkotlinapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity></application> </manifest>
ayushpandey3july
Android-Button
Kotlin Android
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Mar, 2022"
},
{
"code": null,
"e": 330,
"s": 28,
"text": "Android ImageButton is a user interface widget which is used to display a button having image and to perform exactly like button when we click on it but here, we add an image on Image button instead of text. There are different types of buttons available in android like ImageButton, ToggleButton etc."
},
{
"code": null,
"e": 467,
"s": 330,
"text": "We can add an image to the button simply by using attribute android:src in activity_main.xml file or by using setImageResource() method."
},
{
"code": null,
"e": 562,
"s": 467,
"text": "In android, we can create ImageButton control in two ways either manually or programmatically."
},
{
"code": null,
"e": 622,
"s": 562,
"text": "First we create a new project by following the below steps:"
},
{
"code": null,
"e": 831,
"s": 622,
"text": "Click on File, then New => New Project.After that include the Kotlin support and click on next.Select the minimum SDK as per convenience and click next button.Then select the Empty activity => next => finish."
},
{
"code": null,
"e": 871,
"s": 831,
"text": "Click on File, then New => New Project."
},
{
"code": null,
"e": 928,
"s": 871,
"text": "After that include the Kotlin support and click on next."
},
{
"code": null,
"e": 993,
"s": 928,
"text": "Select the minimum SDK as per convenience and click next button."
},
{
"code": null,
"e": 1043,
"s": 993,
"text": "Then select the Empty activity => next => finish."
},
{
"code": null,
"e": 1155,
"s": 1043,
"text": "In this file, we include the Edittext and ImageButton and set their attributes like id, layout_width, hint etc."
},
{
"code": null,
"e": 1159,
"s": 1155,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:orientation=\"vertical\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:id=\"@+id/linear_layout\"> <EditText android:id=\"@+id/Num1\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"50dp\" android:ems=\"10\" android:hint= \"Enter first number\"/> <EditText android:id=\"@+id/Num2\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"50dp\" android:ems=\"10\" android:hint= \"Enter second number\"/> <ImageButton android:id=\"@+id/imageBtn\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_marginLeft=\"100dp\" android:src=\"@android:drawable/btn_plus\" /></LinearLayout>",
"e": 2146,
"s": 1159,
"text": null
},
{
"code": null,
"e": 2198,
"s": 2146,
"text": "Modify the strings.xml file to add application name"
},
{
"code": null,
"e": 2202,
"s": 2198,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">ImageButtonInKotlin</string></resources>",
"e": 2282,
"s": 2202,
"text": null
},
{
"code": null,
"e": 2384,
"s": 2282,
"text": "First of all, we declare two variables num1 and num2 for both edittext and access them using the ids."
},
{
"code": null,
"e": 2455,
"s": 2384,
"text": "val num1 = findViewById(R.id.Num1)\nval num2 = findViewById(R.id.Num2)\n"
},
{
"code": null,
"e": 2572,
"s": 2455,
"text": "then, we declare variable imgbtn for the ImageButton and set the OnCLickListener to check the filled is empty or not"
},
{
"code": null,
"e": 2834,
"s": 2572,
"text": "val imgbtn = findViewById(R.id.imageBtn)\n imgbtn.setOnClickListener {\n if (num1.text.toString().isEmpty() || num2.text.toString().isEmpty()) {\n Toast.makeText(applicationContext,\n \"Enter both numbers\", Toast.LENGTH_SHORT).show()\n }\n"
},
{
"code": null,
"e": 2841,
"s": 2834,
"text": "Kotlin"
},
{
"code": "package com.geeksforgeeks.myfirstkotlinapp import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport android.widget.EditTextimport android.widget.ImageButtonimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val num1 = findViewById<EditText>(R.id.Num1) val num2 = findViewById<EditText>(R.id.Num2) val imgbtn = findViewById<ImageButton>(R.id.imageBtn) imgbtn.setOnClickListener { if (num1.text.toString().isEmpty() || num2.text.toString().isEmpty()) { Toast.makeText(applicationContext, \"Enter both numbers\", Toast.LENGTH_SHORT).show() } else { val num1 = Integer.parseInt(num1.text.toString()) val num2 = Integer.parseInt(num2.text.toString()) Toast.makeText(applicationContext, \"Sum of the numbers = \" + (num1 + num2), Toast.LENGTH_SHORT).show() } } }}",
"e": 3976,
"s": 2841,
"text": null
},
{
"code": null,
"e": 3980,
"s": 3976,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"package=\"com.geeksforgeeks.myfirstkotlinapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity></application> </manifest>",
"e": 4635,
"s": 3980,
"text": null
},
{
"code": null,
"e": 4654,
"s": 4637,
"text": "ayushpandey3july"
},
{
"code": null,
"e": 4669,
"s": 4654,
"text": "Android-Button"
},
{
"code": null,
"e": 4684,
"s": 4669,
"text": "Kotlin Android"
},
{
"code": null,
"e": 4692,
"s": 4684,
"text": "Android"
},
{
"code": null,
"e": 4699,
"s": 4692,
"text": "Kotlin"
},
{
"code": null,
"e": 4707,
"s": 4699,
"text": "Android"
}
] |
Python | Farthest point on horizontal lines in 2D plane
|
27 Aug, 2019
Sometimes, while in competitive programming, we might be facing a problem which is of geometry domain and works with x-y coordinate system. The list of tuple can be used to store the same. And along with this, there might be a problem in which we need point with max value of x axis with similar y axis i.e farthest point on horizontal lines. Let’s discuss certain ways to discuss this problem.
Method : Using list comprehension + max()This is a generic brute force method applied to get the max x axis point for common y axis, made as 1 liner using list comprehension. The max() is used to find the max of x axis element.
# Python3 code to demonstrate working of# Farthest point on horizontal lines in 2D plane# Using list comprehension + max()from collections import defaultdict # initializing listtest_list = [(1, 6), (4, 6), (2, 6), (6, 8), (1, 8), (2, 9)] # printing original listprint("The original list is : " + str(test_list)) # Using list comprehension + max()# Farthest point on horizontal lines in 2D planetemp = defaultdict(list)for key, val in test_list: temp[val].append(key)res = [(key, val) for key, val in test_list if max(temp[val]) == key] # Printing resultprint("The list after filtering just maximum points on lines : " + str(res))
The original list is : [(1, 6), (4, 6), (2, 6), (6, 8), (1, 8), (2, 9)]
The list after filtering just maximum points on lines : [(4, 6), (6, 8), (2, 9)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Aug, 2019"
},
{
"code": null,
"e": 423,
"s": 28,
"text": "Sometimes, while in competitive programming, we might be facing a problem which is of geometry domain and works with x-y coordinate system. The list of tuple can be used to store the same. And along with this, there might be a problem in which we need point with max value of x axis with similar y axis i.e farthest point on horizontal lines. Let’s discuss certain ways to discuss this problem."
},
{
"code": null,
"e": 651,
"s": 423,
"text": "Method : Using list comprehension + max()This is a generic brute force method applied to get the max x axis point for common y axis, made as 1 liner using list comprehension. The max() is used to find the max of x axis element."
},
{
"code": "# Python3 code to demonstrate working of# Farthest point on horizontal lines in 2D plane# Using list comprehension + max()from collections import defaultdict # initializing listtest_list = [(1, 6), (4, 6), (2, 6), (6, 8), (1, 8), (2, 9)] # printing original listprint(\"The original list is : \" + str(test_list)) # Using list comprehension + max()# Farthest point on horizontal lines in 2D planetemp = defaultdict(list)for key, val in test_list: temp[val].append(key)res = [(key, val) for key, val in test_list if max(temp[val]) == key] # Printing resultprint(\"The list after filtering just maximum points on lines : \" + str(res))",
"e": 1289,
"s": 651,
"text": null
},
{
"code": null,
"e": 1443,
"s": 1289,
"text": "The original list is : [(1, 6), (4, 6), (2, 6), (6, 8), (1, 8), (2, 9)]\nThe list after filtering just maximum points on lines : [(4, 6), (6, 8), (2, 9)]\n"
},
{
"code": null,
"e": 1464,
"s": 1443,
"text": "Python list-programs"
},
{
"code": null,
"e": 1471,
"s": 1464,
"text": "Python"
},
{
"code": null,
"e": 1487,
"s": 1471,
"text": "Python Programs"
}
] |
Draw smiling face emoji using Turtle in Python
|
07 Oct, 2020
Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle. To move turtle, there are some functions i.e forward(), backward(), etc.
In this article, we will see how to draw a smiling face emoji using the Turtle module.
Following steps are used :
Import turtle.
Make objects.
Draw a circle and fill yellow color.
Draw eyes with two circles and fill white and black color respectively.
Draw circle for nose and fill black color.
Draw semi circle for mouth.
Draw semi circle for tongue and fill red color.
Below is the implementation :
Python3
# Python program to draw smile# face emoji using turtleimport turtle # turtle objectpen = turtle.Turtle() # function for creation of eyedef eye(col, rad): pen.down() pen.fillcolor(col) pen.begin_fill() pen.circle(rad) pen.end_fill() pen.up() # draw facepen.fillcolor('yellow')pen.begin_fill()pen.circle(100)pen.end_fill()pen.up() # draw eyespen.goto(-40, 120)eye('white', 15)pen.goto(-37, 125)eye('black', 5)pen.goto(40, 120)eye('white', 15)pen.goto(40, 125)eye('black', 5) # draw nosepen.goto(0, 75)eye('black', 8) # draw mouthpen.goto(-40, 85)pen.down()pen.right(90)pen.circle(40, 180)pen.up() # draw tonguepen.goto(-10, 45)pen.down()pen.right(180)pen.fillcolor('red')pen.begin_fill()pen.circle(10, 180)pen.end_fill()pen.hideturtle()
smiling face
2. Let’s draw a different smiling emoji which is drawn above just to understand it better.
Following steps are used :
Import turtle.
Define pen size and pen width.
Draw a circle .
Draw eyes with two circles and fill red color respectively.
Draw triangle for nose ..
Draw semi circle for mouth.
Below is the implementation for the same:-
Python3
#import moduleimport turtle #define pen sizeturtle.pensize (5) #define pen colorturtle.pencolor ("Blue") #for outer bigger circleturtle.fillcolor ("red")turtle.penup ()turtle.goto (0, -200)turtle.pendown ()turtle.circle (200) #for eyesturtle.penup ()turtle.goto (-100,50)turtle.pendown ()turtle.begin_fill ()turtle.circle (17.5)turtle.end_fill ()turtle.penup ()turtle.goto (100,50)turtle.pendown ()turtle.begin_fill ()turtle.circle (17.5)turtle.end_fill () #for noseturtle.penup ()turtle.goto (0,50)turtle.pendown ()turtle.circle (-70, steps=3) # for smileturtle.penup ()turtle.goto (-100, -70)turtle.pendown ()turtle.right (90)turtle.circle (100,180)turtle.mainloop ()
Output:
pulkitagarwal03pulkit
Python-projects
Python-turtle
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n07 Oct, 2020"
},
{
"code": null,
"e": 292,
"s": 54,
"text": "Turtle is an inbuilt module in Python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle. To move turtle, there are some functions i.e forward(), backward(), etc."
},
{
"code": null,
"e": 379,
"s": 292,
"text": "In this article, we will see how to draw a smiling face emoji using the Turtle module."
},
{
"code": null,
"e": 406,
"s": 379,
"text": "Following steps are used :"
},
{
"code": null,
"e": 421,
"s": 406,
"text": "Import turtle."
},
{
"code": null,
"e": 435,
"s": 421,
"text": "Make objects."
},
{
"code": null,
"e": 472,
"s": 435,
"text": "Draw a circle and fill yellow color."
},
{
"code": null,
"e": 544,
"s": 472,
"text": "Draw eyes with two circles and fill white and black color respectively."
},
{
"code": null,
"e": 587,
"s": 544,
"text": "Draw circle for nose and fill black color."
},
{
"code": null,
"e": 615,
"s": 587,
"text": "Draw semi circle for mouth."
},
{
"code": null,
"e": 663,
"s": 615,
"text": "Draw semi circle for tongue and fill red color."
},
{
"code": null,
"e": 694,
"s": 663,
"text": "Below is the implementation :"
},
{
"code": null,
"e": 702,
"s": 694,
"text": "Python3"
},
{
"code": "# Python program to draw smile# face emoji using turtleimport turtle # turtle objectpen = turtle.Turtle() # function for creation of eyedef eye(col, rad): pen.down() pen.fillcolor(col) pen.begin_fill() pen.circle(rad) pen.end_fill() pen.up() # draw facepen.fillcolor('yellow')pen.begin_fill()pen.circle(100)pen.end_fill()pen.up() # draw eyespen.goto(-40, 120)eye('white', 15)pen.goto(-37, 125)eye('black', 5)pen.goto(40, 120)eye('white', 15)pen.goto(40, 125)eye('black', 5) # draw nosepen.goto(0, 75)eye('black', 8) # draw mouthpen.goto(-40, 85)pen.down()pen.right(90)pen.circle(40, 180)pen.up() # draw tonguepen.goto(-10, 45)pen.down()pen.right(180)pen.fillcolor('red')pen.begin_fill()pen.circle(10, 180)pen.end_fill()pen.hideturtle()",
"e": 1457,
"s": 702,
"text": null
},
{
"code": null,
"e": 1470,
"s": 1457,
"text": "smiling face"
},
{
"code": null,
"e": 1561,
"s": 1470,
"text": "2. Let’s draw a different smiling emoji which is drawn above just to understand it better."
},
{
"code": null,
"e": 1588,
"s": 1561,
"text": "Following steps are used :"
},
{
"code": null,
"e": 1603,
"s": 1588,
"text": "Import turtle."
},
{
"code": null,
"e": 1634,
"s": 1603,
"text": "Define pen size and pen width."
},
{
"code": null,
"e": 1650,
"s": 1634,
"text": "Draw a circle ."
},
{
"code": null,
"e": 1710,
"s": 1650,
"text": "Draw eyes with two circles and fill red color respectively."
},
{
"code": null,
"e": 1736,
"s": 1710,
"text": "Draw triangle for nose .."
},
{
"code": null,
"e": 1764,
"s": 1736,
"text": "Draw semi circle for mouth."
},
{
"code": null,
"e": 1807,
"s": 1764,
"text": "Below is the implementation for the same:-"
},
{
"code": null,
"e": 1815,
"s": 1807,
"text": "Python3"
},
{
"code": "#import moduleimport turtle #define pen sizeturtle.pensize (5) #define pen colorturtle.pencolor (\"Blue\") #for outer bigger circleturtle.fillcolor (\"red\")turtle.penup ()turtle.goto (0, -200)turtle.pendown ()turtle.circle (200) #for eyesturtle.penup ()turtle.goto (-100,50)turtle.pendown ()turtle.begin_fill ()turtle.circle (17.5)turtle.end_fill ()turtle.penup ()turtle.goto (100,50)turtle.pendown ()turtle.begin_fill ()turtle.circle (17.5)turtle.end_fill () #for noseturtle.penup ()turtle.goto (0,50)turtle.pendown ()turtle.circle (-70, steps=3) # for smileturtle.penup ()turtle.goto (-100, -70)turtle.pendown ()turtle.right (90)turtle.circle (100,180)turtle.mainloop ()",
"e": 2485,
"s": 1815,
"text": null
},
{
"code": null,
"e": 2493,
"s": 2485,
"text": "Output:"
},
{
"code": null,
"e": 2515,
"s": 2493,
"text": "pulkitagarwal03pulkit"
},
{
"code": null,
"e": 2531,
"s": 2515,
"text": "Python-projects"
},
{
"code": null,
"e": 2545,
"s": 2531,
"text": "Python-turtle"
},
{
"code": null,
"e": 2552,
"s": 2545,
"text": "Python"
}
] |
Weiler Atherton – Polygon Clipping Algorithm
|
26 Aug, 2019
Weiler Atherton Polygon Clipping Algorithm is an algorithm made to allow clipping of even concave algorithms to be possible. Unlike Sutherland – Hodgman polygon clipping algorithm, this algorithm is able to clip concave polygons without leaving any residue behind.
1. First make a list of all intersection points namely i1, i2, i3, ...
2. Classify those intersection points as entering or exiting.
3. Now, make two lists, one for the clipping polygon, and the other
for the clipped polygon.
4. Fill both the lists up in such a way that the intersection points
lie between the correct vertices of each of the polygon. That is
the clipping polygon list is filled up with all the vertices of
the clipping polygon along with the intersecting points lying
between the corresponding vertices.
5. Now, start at the 'to be clipped' polygon's list.
6. Choose the first intersection point which has been labelled as
an entering point. Follow the points in the list (looping back to
the top of the list, in case the list ends) and keep on pushing
them into a vector or something similar of the sorts. Keep on following
the list until an exiting intersection point is found.
7. Now switch the list to the 'polygon that is clipping' list, and find
the exiting the intersection that was previously encountered. Now keep
on following the points in this list (similar to how we followed the
previous list) until the entering intersection point is found (the
one that was found in the previous 'to be clipped' polygon's list).
8. This vector now formed by pushing all the encountered points in the
two lists, is now the clipped polygon (one of the many clipped
polygons if any of the clipping polygons is concave).
9. Repeat this clipping procedure (i.e. from step 5) until all the
entering intersection points have been visited once.
1. Finding all the intersection points and grouping themHere, let there be a polygon ABCD and another polygon VWXYZ. Let ABCD be the clipping polygon and let VWXYZ be the clipped polygon.So, we can find the intersection points using any method. For example, we can find the intersecting points separately and then find for each intersecting point find if it is entering or leaving, or, we can use Cyrus Beck and find all the intersecting points and also get if a point is entering or exiting. Refer Cyrus Beck for more information on this algorithm.
2. Making and filling of two listsNow, we make two lists. One for the clipping polygon and one for the clipped polygon.Now this is how we fill it:
3. Running of the algorithmWe start at the clipped polygon’s list, i.e. VWXYZ.Now, we find the first intersecting point that is entering. Hence we choose i1.From here we begin the making of the list of vertices (or vector) to make a clipped sub-polygon.According to the given example, i1 Y i2 is a clipped sub-polygon.Similarly, we get:i0 V i3 as another sub-polygon also.
Hence, we were able to get two sub-polygons as a result of this polygon clipping, which involved a concave polygon, which resulted in:Similarly, this clipping works for convex polygons.
This polygon clipping algorithm does not work for self – intersecting polygons, although some methods have been proposed to be able to solve this issue also, and have successfully worked.
Let V1V2V3V4V5V6 be the clipping window and P1 P2 P3 P4 P5 P6 be the polygon.Now, here is how the algorithm will operate.Two lists are generated, one for the clipping window, and the other for the polygon. We will start from the polygon’s list. (Note that the polygon’s list only contains the polygon’s vertices and the intersections and similarly for the clipping window’s list.)
So, according to the algorithm, the first polygon to be formed will be i2 i3 i8 i1
Then the next subpolygon, i4 i5 i6 i7.
The output will look like:
K. Weiler and P. Atherton. 1988. Hidden surface removal using polygon area sorting. In Tutorial: computer graphics; image synthesis, Kenneth I. Joy, Charles W. Grant, Nelson L. Max, and Lansing Hatfield (Eds.). Computer Science Press, Inc., New York, NY, USA 209-217.
Source: https://www.cs.drexel.edu/~david/Classes/CS430/HWs/p214-weiler.pdf
For implementation of Weiler Atherton, check Implementation
Advanced Computer Subject
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Markov Decision Process
Basics of API Testing Using Postman
Copying Files to and from Docker Containers
Getting Started with System Design
Principal Component Analysis with Python
Python | Implementation of Polynomial Regression
How to create a REST API using Java Spring Boot
Monolithic vs Microservices architecture
OpenCV - Overview
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Aug, 2019"
},
{
"code": null,
"e": 293,
"s": 28,
"text": "Weiler Atherton Polygon Clipping Algorithm is an algorithm made to allow clipping of even concave algorithms to be possible. Unlike Sutherland – Hodgman polygon clipping algorithm, this algorithm is able to clip concave polygons without leaving any residue behind."
},
{
"code": null,
"e": 1932,
"s": 293,
"text": " 1. First make a list of all intersection points namely i1, i2, i3, ...\n 2. Classify those intersection points as entering or exiting.\n 3. Now, make two lists, one for the clipping polygon, and the other \n for the clipped polygon.\n 4. Fill both the lists up in such a way that the intersection points \n lie between the correct vertices of each of the polygon. That is \n the clipping polygon list is filled up with all the vertices of \n the clipping polygon along with the intersecting points lying \n between the corresponding vertices.\n 5. Now, start at the 'to be clipped' polygon's list.\n 6. Choose the first intersection point which has been labelled as \n an entering point. Follow the points in the list (looping back to \n the top of the list, in case the list ends) and keep on pushing \n them into a vector or something similar of the sorts. Keep on following\n the list until an exiting intersection point is found.\n 7. Now switch the list to the 'polygon that is clipping' list, and find\n the exiting the intersection that was previously encountered. Now keep\n on following the points in this list (similar to how we followed the\n previous list) until the entering intersection point is found (the \n one that was found in the previous 'to be clipped' polygon's list).\n 8. This vector now formed by pushing all the encountered points in the \n two lists, is now the clipped polygon (one of the many clipped \n polygons if any of the clipping polygons is concave).\n 9. Repeat this clipping procedure (i.e. from step 5) until all the \n entering intersection points have been visited once.\n"
},
{
"code": null,
"e": 2482,
"s": 1932,
"text": "1. Finding all the intersection points and grouping themHere, let there be a polygon ABCD and another polygon VWXYZ. Let ABCD be the clipping polygon and let VWXYZ be the clipped polygon.So, we can find the intersection points using any method. For example, we can find the intersecting points separately and then find for each intersecting point find if it is entering or leaving, or, we can use Cyrus Beck and find all the intersecting points and also get if a point is entering or exiting. Refer Cyrus Beck for more information on this algorithm."
},
{
"code": null,
"e": 2629,
"s": 2482,
"text": "2. Making and filling of two listsNow, we make two lists. One for the clipping polygon and one for the clipped polygon.Now this is how we fill it:"
},
{
"code": null,
"e": 3002,
"s": 2629,
"text": "3. Running of the algorithmWe start at the clipped polygon’s list, i.e. VWXYZ.Now, we find the first intersecting point that is entering. Hence we choose i1.From here we begin the making of the list of vertices (or vector) to make a clipped sub-polygon.According to the given example, i1 Y i2 is a clipped sub-polygon.Similarly, we get:i0 V i3 as another sub-polygon also."
},
{
"code": null,
"e": 3188,
"s": 3002,
"text": "Hence, we were able to get two sub-polygons as a result of this polygon clipping, which involved a concave polygon, which resulted in:Similarly, this clipping works for convex polygons."
},
{
"code": null,
"e": 3376,
"s": 3188,
"text": "This polygon clipping algorithm does not work for self – intersecting polygons, although some methods have been proposed to be able to solve this issue also, and have successfully worked."
},
{
"code": null,
"e": 3757,
"s": 3376,
"text": "Let V1V2V3V4V5V6 be the clipping window and P1 P2 P3 P4 P5 P6 be the polygon.Now, here is how the algorithm will operate.Two lists are generated, one for the clipping window, and the other for the polygon. We will start from the polygon’s list. (Note that the polygon’s list only contains the polygon’s vertices and the intersections and similarly for the clipping window’s list.)"
},
{
"code": null,
"e": 3840,
"s": 3757,
"text": "So, according to the algorithm, the first polygon to be formed will be i2 i3 i8 i1"
},
{
"code": null,
"e": 3879,
"s": 3840,
"text": "Then the next subpolygon, i4 i5 i6 i7."
},
{
"code": null,
"e": 3906,
"s": 3879,
"text": "The output will look like:"
},
{
"code": null,
"e": 4174,
"s": 3906,
"text": "K. Weiler and P. Atherton. 1988. Hidden surface removal using polygon area sorting. In Tutorial: computer graphics; image synthesis, Kenneth I. Joy, Charles W. Grant, Nelson L. Max, and Lansing Hatfield (Eds.). Computer Science Press, Inc., New York, NY, USA 209-217."
},
{
"code": null,
"e": 4249,
"s": 4174,
"text": "Source: https://www.cs.drexel.edu/~david/Classes/CS430/HWs/p214-weiler.pdf"
},
{
"code": null,
"e": 4309,
"s": 4249,
"text": "For implementation of Weiler Atherton, check Implementation"
},
{
"code": null,
"e": 4335,
"s": 4309,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 4433,
"s": 4335,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4469,
"s": 4433,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 4493,
"s": 4469,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 4529,
"s": 4493,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 4573,
"s": 4529,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 4608,
"s": 4573,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 4649,
"s": 4608,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 4698,
"s": 4649,
"text": "Python | Implementation of Polynomial Regression"
},
{
"code": null,
"e": 4746,
"s": 4698,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 4787,
"s": 4746,
"text": "Monolithic vs Microservices architecture"
}
] |
Python program to print Emojis
|
11 Feb, 2022
There are multiple ways we can print the Emojis in Python. Let’s see how to print Emojis with Unicodes, CLDR names and emoji module. Using Unicodes: Every emoji has a Unicode associated with it. Emojis also have a CLDR short name, which can also be used. From the list of unicodes, replace “+” with “000”. For example – “U+1F600” will become “U0001F600” and prefix the unicode with “\” and print it.
Python3
# grinning faceprint("\U0001f600") # grinning squinting faceprint("\U0001F606") # rolling on the floor laughingprint("\U0001F923")
Output:
Using CLDR short name:
Python3
# grinning faceprint("\N{grinning face}") # slightly smiling faceprint("\N{slightly smiling face}") # winking faceprint("\N{winking face}")
Output:
Using emoji module: Emojis can also be implemented by using the emoji module provided in Python. To install it run the following in the terminal.
pip install emoji
emojize() function requires the CLDR short name to be passed in it as the parameter. It then returns the corresponding emoji. Replace the spaces with underscore in the CLDR short name.
Python3
# import emoji moduleimport emoji print(emoji.emojize(":grinning_face_with_big_eyes:"))print(emoji.emojize(":winking_face_with_tongue:"))print(emoji.emojize(":zipper-mouth_face:"))
Output:
demojize() function converts the emoji passed into its corresponding CLDR short name.
Below is a list of some common emoji Unicodes with their CLDR short names:
varshagumber28
sumitgumber28
python-utility
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 453,
"s": 52,
"text": "There are multiple ways we can print the Emojis in Python. Let’s see how to print Emojis with Unicodes, CLDR names and emoji module. Using Unicodes: Every emoji has a Unicode associated with it. Emojis also have a CLDR short name, which can also be used. From the list of unicodes, replace “+” with “000”. For example – “U+1F600” will become “U0001F600” and prefix the unicode with “\\” and print it. "
},
{
"code": null,
"e": 461,
"s": 453,
"text": "Python3"
},
{
"code": "# grinning faceprint(\"\\U0001f600\") # grinning squinting faceprint(\"\\U0001F606\") # rolling on the floor laughingprint(\"\\U0001F923\")",
"e": 592,
"s": 461,
"text": null
},
{
"code": null,
"e": 602,
"s": 592,
"text": "Output: "
},
{
"code": null,
"e": 629,
"s": 602,
"text": " Using CLDR short name: "
},
{
"code": null,
"e": 637,
"s": 629,
"text": "Python3"
},
{
"code": "# grinning faceprint(\"\\N{grinning face}\") # slightly smiling faceprint(\"\\N{slightly smiling face}\") # winking faceprint(\"\\N{winking face}\")",
"e": 777,
"s": 637,
"text": null
},
{
"code": null,
"e": 787,
"s": 777,
"text": "Output: "
},
{
"code": null,
"e": 936,
"s": 787,
"text": " Using emoji module: Emojis can also be implemented by using the emoji module provided in Python. To install it run the following in the terminal. "
},
{
"code": null,
"e": 954,
"s": 936,
"text": "pip install emoji"
},
{
"code": null,
"e": 1140,
"s": 954,
"text": "emojize() function requires the CLDR short name to be passed in it as the parameter. It then returns the corresponding emoji. Replace the spaces with underscore in the CLDR short name. "
},
{
"code": null,
"e": 1148,
"s": 1140,
"text": "Python3"
},
{
"code": "# import emoji moduleimport emoji print(emoji.emojize(\":grinning_face_with_big_eyes:\"))print(emoji.emojize(\":winking_face_with_tongue:\"))print(emoji.emojize(\":zipper-mouth_face:\"))",
"e": 1330,
"s": 1148,
"text": null
},
{
"code": null,
"e": 1340,
"s": 1330,
"text": "Output: "
},
{
"code": null,
"e": 1430,
"s": 1340,
"text": " demojize() function converts the emoji passed into its corresponding CLDR short name. "
},
{
"code": null,
"e": 1507,
"s": 1430,
"text": " Below is a list of some common emoji Unicodes with their CLDR short names:"
},
{
"code": null,
"e": 1526,
"s": 1511,
"text": "varshagumber28"
},
{
"code": null,
"e": 1540,
"s": 1526,
"text": "sumitgumber28"
},
{
"code": null,
"e": 1555,
"s": 1540,
"text": "python-utility"
},
{
"code": null,
"e": 1562,
"s": 1555,
"text": "Python"
},
{
"code": null,
"e": 1578,
"s": 1562,
"text": "Python Programs"
}
] |
Why “0” is not equal to false in if condition in JavaScript ?
|
28 Jun, 2019
The reason behind this behavior is that JavaScript treats non-empty string as true. First, “0” is converted into its boolean value, by automatic type conversion which is true. Therefore, if statement executes.
Example: This example illustrates why “0” is not equal to false in if() condition.
<script> // JavaScript script to demonstrate // why “0” is not equal to false in // ‘if’ condition function GFG() { // Print type of "0" document.write(typeof "0" + "</br>"); // Print boolean value of "0" document.write(Boolean("0") + "</br>"); // Boolean value of "0" is true so // 'if' part will execute if("0") { document.write("if part executed"); } else { document.write("else part executed"); } } // Driver code GFG(); </script>
Output:
string
true
if part executed
JavaScript-Misc
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Roadmap to Learn JavaScript For Beginners
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Difference Between PUT and PATCH Request
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 fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2019"
},
{
"code": null,
"e": 238,
"s": 28,
"text": "The reason behind this behavior is that JavaScript treats non-empty string as true. First, “0” is converted into its boolean value, by automatic type conversion which is true. Therefore, if statement executes."
},
{
"code": null,
"e": 321,
"s": 238,
"text": "Example: This example illustrates why “0” is not equal to false in if() condition."
},
{
"code": "<script> // JavaScript script to demonstrate // why “0” is not equal to false in // ‘if’ condition function GFG() { // Print type of \"0\" document.write(typeof \"0\" + \"</br>\"); // Print boolean value of \"0\" document.write(Boolean(\"0\") + \"</br>\"); // Boolean value of \"0\" is true so // 'if' part will execute if(\"0\") { document.write(\"if part executed\"); } else { document.write(\"else part executed\"); } } // Driver code GFG(); </script> ",
"e": 931,
"s": 321,
"text": null
},
{
"code": null,
"e": 939,
"s": 931,
"text": "Output:"
},
{
"code": null,
"e": 969,
"s": 939,
"text": "string\ntrue\nif part executed\n"
},
{
"code": null,
"e": 985,
"s": 969,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 996,
"s": 985,
"text": "JavaScript"
},
{
"code": null,
"e": 1013,
"s": 996,
"text": "Web Technologies"
},
{
"code": null,
"e": 1040,
"s": 1013,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1138,
"s": 1040,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1199,
"s": 1138,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1241,
"s": 1199,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 1313,
"s": 1241,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1353,
"s": 1313,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1394,
"s": 1353,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1427,
"s": 1394,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1489,
"s": 1427,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1550,
"s": 1489,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1593,
"s": 1550,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to check whether a number is in the range[low, high] using one comparison ?
|
22 Jun, 2022
This is simple, but interesting programming puzzle. Given three integers, low, high and x such that high >= low. How to check if x lies in range [low, high] or not using single comparison. For example, if range is [10, 100] and number is 30, then output is true and if the number is 5, then output is false for same range. A simple solution is compare x with low and high
C++
#include <iostream>using namespace std; // Returns true if x is in range [low..high], else false bool inRange(unsigned low, unsigned high, unsigned x) { return (low <= x && x <= high); } int main() { inRange(10, 100, 30)? cout << "Yes\n": cout <<"No\n"; inRange(10, 100, 5)? cout << "Yes\n": cout <<"No\n"; }
Output:
Yes
No
The above solution does two comparisons,
Can we do the same task using one comparison?
We strongly recommend you to minimize your browser and try this yourself first.The idea is to compare “x-low” with “high-x”. x is in range [low, high] if and only if x is greater than or equal to low and smaller than or equal to high.
CPP
#include <iostream>using namespace std; // Returns true if x is in range [low..high], else falsebool inRange(unsigned low, unsigned high, unsigned x){ return ((x-low) <= (high-low));} int main(){ inRange(10, 100, 30)? cout << "Yes\n": cout <<"No\n"; inRange(10, 100, 5)? cout << "Yes\n": cout <<"No\n";}
Output:
Yes
No
How does this work for [10, 100] and x = 5? When we subtract 10 from 5, we get -5 which is considered as UNIT_MAX-4 in unsigned int form. UNIT_MAX is maximum possible unsigned int value. The assumption here is, numbers are stored in 2’s complement form. In 2’s complement form, -1 represents UINT_MAX, -2 represents UINT_MAX-1,..etc.Thanks to Utkarsh for suggesting this solution. A Solution that works for negative numbers also The idea is to multiply (x-low) and (x-high). If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range. Else not. Thanks to eva for suggesting this method.
CPP
#include <iostream>using namespace std; // Returns true if x is in range [low..high], else falsebool inRange(int low, int high, int x){ return ((x-high)*(x-low) <= 0);} int main(){ inRange(10, 100, 30)? cout << "Yes\n": cout <<"No\n"; inRange(10, 100, 5)? cout << "Yes\n": cout <<"No\n";}
Output:
Yes
No
Time Complexity: O(1)Auxiliary Space: O(1)
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above
jit_t
kalrap615
hasani
cpp-puzzle
C Language
C++
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++
Different Methods to Reverse a String in C++
Left Shift and Right Shift Operators in C/C++
std::string class in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n22 Jun, 2022"
},
{
"code": null,
"e": 425,
"s": 52,
"text": "This is simple, but interesting programming puzzle. Given three integers, low, high and x such that high >= low. How to check if x lies in range [low, high] or not using single comparison. For example, if range is [10, 100] and number is 30, then output is true and if the number is 5, then output is false for same range. A simple solution is compare x with low and high "
},
{
"code": null,
"e": 429,
"s": 425,
"text": "C++"
},
{
"code": "#include <iostream>using namespace std; // Returns true if x is in range [low..high], else false bool inRange(unsigned low, unsigned high, unsigned x) { return (low <= x && x <= high); } int main() { inRange(10, 100, 30)? cout << \"Yes\\n\": cout <<\"No\\n\"; inRange(10, 100, 5)? cout << \"Yes\\n\": cout <<\"No\\n\"; }",
"e": 805,
"s": 429,
"text": null
},
{
"code": null,
"e": 814,
"s": 805,
"text": "Output: "
},
{
"code": null,
"e": 821,
"s": 814,
"text": "Yes\nNo"
},
{
"code": null,
"e": 917,
"s": 823,
"text": " The above solution does two comparisons, \n Can we do the same task using one comparison? "
},
{
"code": null,
"e": 1154,
"s": 917,
"text": "We strongly recommend you to minimize your browser and try this yourself first.The idea is to compare “x-low” with “high-x”. x is in range [low, high] if and only if x is greater than or equal to low and smaller than or equal to high. "
},
{
"code": null,
"e": 1158,
"s": 1154,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; // Returns true if x is in range [low..high], else falsebool inRange(unsigned low, unsigned high, unsigned x){ return ((x-low) <= (high-low));} int main(){ inRange(10, 100, 30)? cout << \"Yes\\n\": cout <<\"No\\n\"; inRange(10, 100, 5)? cout << \"Yes\\n\": cout <<\"No\\n\";}",
"e": 1477,
"s": 1158,
"text": null
},
{
"code": null,
"e": 1486,
"s": 1477,
"text": "Output: "
},
{
"code": null,
"e": 1493,
"s": 1486,
"text": "Yes\nNo"
},
{
"code": null,
"e": 2253,
"s": 1493,
"text": "How does this work for [10, 100] and x = 5? When we subtract 10 from 5, we get -5 which is considered as UNIT_MAX-4 in unsigned int form. UNIT_MAX is maximum possible unsigned int value. The assumption here is, numbers are stored in 2’s complement form. In 2’s complement form, -1 represents UINT_MAX, -2 represents UINT_MAX-1,..etc.Thanks to Utkarsh for suggesting this solution. A Solution that works for negative numbers also The idea is to multiply (x-low) and (x-high). If x is in range, then it must be greater than or equal to low, i.e., (x-low) >= 0. And must be smaller than or equal to high i.e., (high – x) <= 0. So if result of the multiplication is less than or equal to 0, then x is in range. Else not. Thanks to eva for suggesting this method. "
},
{
"code": null,
"e": 2257,
"s": 2253,
"text": "CPP"
},
{
"code": "#include <iostream>using namespace std; // Returns true if x is in range [low..high], else falsebool inRange(int low, int high, int x){ return ((x-high)*(x-low) <= 0);} int main(){ inRange(10, 100, 30)? cout << \"Yes\\n\": cout <<\"No\\n\"; inRange(10, 100, 5)? cout << \"Yes\\n\": cout <<\"No\\n\";}",
"e": 2560,
"s": 2257,
"text": null
},
{
"code": null,
"e": 2569,
"s": 2560,
"text": "Output: "
},
{
"code": null,
"e": 2576,
"s": 2569,
"text": "Yes\nNo"
},
{
"code": null,
"e": 2620,
"s": 2576,
"text": " Time Complexity: O(1)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 2745,
"s": 2620,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above "
},
{
"code": null,
"e": 2751,
"s": 2745,
"text": "jit_t"
},
{
"code": null,
"e": 2761,
"s": 2751,
"text": "kalrap615"
},
{
"code": null,
"e": 2768,
"s": 2761,
"text": "hasani"
},
{
"code": null,
"e": 2779,
"s": 2768,
"text": "cpp-puzzle"
},
{
"code": null,
"e": 2790,
"s": 2779,
"text": "C Language"
},
{
"code": null,
"e": 2794,
"s": 2790,
"text": "C++"
},
{
"code": null,
"e": 2798,
"s": 2794,
"text": "CPP"
},
{
"code": null,
"e": 2896,
"s": 2798,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2913,
"s": 2896,
"text": "Substring in C++"
},
{
"code": null,
"e": 2948,
"s": 2913,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 2993,
"s": 2948,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 3039,
"s": 2993,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 3064,
"s": 3039,
"text": "std::string class in C++"
},
{
"code": null,
"e": 3082,
"s": 3064,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 3125,
"s": 3082,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 3171,
"s": 3125,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 3214,
"s": 3171,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Doing XGBoost hyper-parameter tuning the smart way — Part 1 of 2 | by Mateo Restrepo | Towards Data Science
|
In this post and the next, we will look at one of the trickiest and most critical problems in Machine Learning (ML): Hyper-parameter tuning. After reviewing what hyper-parameters, or hyper-params for short, are and how they differ from plain vanilla learnable parameters, we introduce three general purpose discrete optimization algorithms aimed at search for the optimal hyper-param combination: grid-search, coordinate descent and genetic algorithms. We report on the results of an experiment in which we use each of these to come up with good hyperparameters on an example ML problem taken from Kaggle. Although we focus on optimizing XGBoost hyper-parameters in our experiment, pretty much all of what we will present applies to any other advanced ML algorithms.
The most powerful ML algorithms are famous for picking up patterns and regularities in the data by automatically tuning thousands (or even millions) of so-called “learnable” parameters. For instance, in tree-based models (decision trees, random forests, XGBoost), the learnable parameters are the choice of decision variables at each node and the numeric thresholds used to decide whether to take the left or right branch when generating predictions. In neural networks, the learnable parameters are the weights used on each connection to amplify or negate the activation from a previous layer into the next one.
Learnable parameters are, however, only part of the story. In fact, they are the easy part. The more flexible and powerful an algorithm is, the more design decisions and adjustable hyper-parameters it will have. These are parameters specified by “hand” to the algo and fixed throughout a training pass. Further, the algo typically does not include any logic to optimize them for us. In tree-based models, hyper-parameters include things like the maximum depth of the tree, the number of trees to grow, the number of variables to consider when building each tree, the minimum number of samples on a leaf, the fraction of observations used to build a tree, and a few others. For neural networks, the list includes the number of hidden layers, the size (and shape) of each layer, the choice of activation function, the drop-out rate and the L1/L2 regularization constants.
From a computational point of view, supervised ML boils down to minimizing a certain loss function (e.g. the MSE or the classification error) that depends on the data training input data (Xt, Yt), the learnable params which we denote by a, and the hyper-params. The crucial observation here is that this minimization is done by letting only the learnable parameters vary, while holding the data and the hyper-params constant. To choose the optimal set of hyper-params, the usual approach is to perform cross-validation. Given a hyper-param vector h, its quality is assessed by evaluating the loss function on a held-out set of validation data using the best set of learnable parameters, a*, for that value of h. Symbolically, we have
Introducing the Hyper-Parameter Grid
One important thing to note about hyper-parameters is that, often, they take on discrete values, with notable exceptions being things like drop-out rates or regularization constants. Thus, for practical reasons and to avoid the complexities involved in doing hybrid continuous-discrete optimization, most approaches to hyper-parameter tuning start off by discretizing the ranges of all hyper-parameters in question. For example, for our XGBoost experiments below we will fine-tune five hyperparameters. The ranges of possible values that we will consider for each are as follows:
{"learning_rate" : [0.05, 0.10, 0.15, 0.20, 0.25, 0.30 ] , "max_depth" : [ 3, 4, 5, 6, 8, 10, 12, 15], "min_child_weight" : [ 1, 3, 5, 7 ], "gamma" : [ 0.0, 0.1, 0.2 , 0.3, 0.4 ], "colsample_bytree" : [ 0.3, 0.4, 0.5 , 0.7 ] }
For an explanation of what each of these means in the context of XGBost we refer the reader to this post.
Notice that despite having limited the range for the (continuous) learning_rate hyper-parameter to only six values, that of max_depth to 8, and so forth, there are 6 x 8 x 4 x 5 x 4 = 3840 possible combinations of hyper parameters. This discrete subspace of all possible hyper-parameters is called the hyper-parameter grid. In what follows, we will use the vector notation symbol h = [h0, h1, ..., hp] to denote any such combination, that is, any point in the grid.
Exhaustive grid search (GS) is nothing other than the brute force approach that scans the whole grid of hyper-param combinations h in some order, computes the cross-validation loss for each one and finds the optimal h* in this manner. Generally, the use of lexicographic ordering, that is, the dictionary order imposed on hyper-param vectors, is discouraged and a different order should be considered. The reason is that with lexicographic ordering there is a high chance that the search will focus on a rather uninteresting part of the search space for a rather long time. An interesting alternative is scanning the whole grid in a fully randomized way that is, according to a random permutation of the whole grid . With this type of search, it is likely that one encounters close-to-optimal regions of the hyper-param space early on. We show some evidence of this in the example below.
Coordinate descent (CD) is one of the simplest optimization algorithms. It’s an iterative algorithm, similar to gradient descent, but even simpler! The basic idea is that, at each iteration, only one of the coordinate directions of our search vector h is altered. To pick which one, we examine each coordinate direction turn and minimize the objective function by varying that coordinate and leaving all the other constant. Then we pick the direction that yields the most improvement. The algorithm stops when none of the directions yields any improvement. To learn all the details we refer the reader to the Wikipedia article.
The main advantage of this simple approach is that it is easily adaptable to the fully discrete case for which the arbitrary directions given by gradient descent cannot be easily used. We provide an implementation here.
Genetic algorithms (GAs) are a whole class of optimization algorithms of rather general applicability and are particularly well adapted for high-dimensional discrete search spaces. A genetic algorithm tries to mimic nature by simulating a population of feasible solutions to a(n optimization) problem as they evolve through several generations and survival of the fittest is enforced. There are two basic mechanisms for generating a new generation from the previous one. One is cross-breeding in which two individuals (feasible solutions) are combined to produce two offspring. The other one is mutation. With a given mutation probability, any individual can change any of their params to another valid value. Survival of the fittest is enforced by letting fitter individuals cross-breed with higher probability than less fit individuals. The fitness of an individual is of course the negative of the loss function.For the whole details we refer the reader to Wikipedia or to AIMA, Part II Chapter 4. Our own implementation is available here.
To get a feeling for each of the hyper-param optimization approaches mentioned above, we performed an experiment using actual data taken from the Home Credit Default Risk binary-classification competition, currently being held on Kaggle. We only considered the application_(train|test) data sets and performed a rather minimal data preparation step (see function prepare_data here). Further, to keep training and validation times short and allow for full exploration of the hyper-param space in a reasonable time, we sub-sampled the training set, keeping only 4% of the records (approx. 12,000). For validation, we used a separate 3.2% of the records (approx. 10,000). Even with this small amount of data, a single round of training and validation takes around 3 seconds, for a given set of hyper-params, which is not negligible considering that we intend to scan the whole hyper-param grid. For the reasons just mentioned, the cross-validation AUC values we get are not competitive with the ones at the top of the leader board, which surely are making use of all available records in all data sets provided by the competition.
As mentioned before, we chose XGBoost as our machine-learning architecture. Due to the outstanding accuracy obtained by XGBoost, as well as its computational performance, it is perhaps the most popular choice among Kagglers and many other ML practitioners for purely “tabular” problems such as this one.
Now, for each of the three hyper-param tuning methods mentioned above, we ran 10,000 independent trials. Each trial first resets the random seed to a new value, then initializes the hyper-param vector to a random value from our grid, and then proceeds to generate a sequence of hyper-param vectors following the optimization algorithm being tested. When testing GS, the trial just goes through hyper-param vectors according to a random permutation of the whole grid. With CD, the generated hyper-param vectors are all the ones tried out in intermediate evaluations of the CD algorithm. When CD gets stuck at a local optimum, it gets restarted to a new initial vector uniformly at random. With the genetic algo, the hyper-param vectors are the ones contained in the “DNA” of every individual generated in every successive generation.
By the way, we were able to run these many trials despite the cost of each CV-loss evaluation thanks to a technique called memoization (https://en.wikipedia.org/wiki/Memoization). Essentially, once the CV-loss of a hyper-param vector was evaluated for the first time, we kept it in a look-up table shared among the three methods and never had to re-evaluate it again.
While running each trial, we keep a log of all the hyper-param vectors tried and their corresponding cross-validation losses. The following plots show the behavior of a typical trial, for each of the three methods, The y-axis shows the negative of the CV loss, which in this case is just the CV_AUC metric which we are maximizing. The X-axis keeps track of “time”, that is, the total number CV-AUC evaluations up to a point.
The orange “envelope” line keeps track of the “running best,” which is the best AUC value seen among all function evaluations prior to a point. In a sense, this line is all we care about, as every method will always return the best of all hyper-param vectors evaluated and not simply the last one. Notice how different all three methods look at this level. GS succeeds in gradually maximizing the AUC by mere chance. The deliberate “effort” that coordinate descent and the genetic algorithm make in finding progressively better values is apparent from their plots as well.
However, one randomized trial does not tell the whole story. Let’s look at the “envelope” lines for each of 30 independent trials of each of the three methods.
Interesting... The envelope lines of the grid-search and genetic algos quickly cluster towards the top, unlike the CD one... This means that, with high probability, almost all trials of GS and genetic are likely to give near optimal solutions quicker than CD. On the other hand, the overall best solution is achieved around function evaluation #40 by one of the CD trials, and we don’t see the same for the other methods. Also coordinate descent beats the other two methods after function evaluation #100 or so, in that all of the 30 trials are nearly optimal and show a much smaller variance!
Let’s look at a final plot. What if we take the 10% percentile of the running-best AUC among all 10000 trials? This number is interesting because it gives us a sense of how the running-best of most trials evolves as a function of the number of evaluations. Another way to put it is that it gives us a 90% confidence bound on the worst we can expect from each method. Here it is:
Aha! This is more compelling evidence of what was mentioned above as it tells us that,with probability at least 90%, a randomized trial of coordinate descent will have seen, by CV-AUC evaluation #90, a hyper-param vector with an AUC of around 0.740 or better, whereas the corresponding value for GS is only around 0.738. This might seem like a minor difference, but it is quite significant as far as ML metrics go. Perhaps more telling than that is the fact that, up until the point it plateaus, the CD curve in the plot above has a distinctly higher slope than the GS curve.
The GA, on the other hand, seems to be dominated by GS throughout. This perhaps shouldn’t surprise us. On the one hand GA’s depend on several adjustable parameters (which would be hyper-hyper-parameters in our formulation) such as generation size, mutation rate, ordering of the instance variables to build a DNA sequence and the function linking AUC to the probability of cross-breading. For our experiment, we only tried a couple of settings for these. It is likely that with different settings GA would have beat GS. On the other hand, it’s known (see, for instance AIMA , at the end of page 148 ) that genetic algorithms work best when there are contiguous blocks of genes (hyper-params in our case) for which there are certain combinations of values that work better on average. It is not clear if this is the case in for the rather arbitrary ordering of XGBoost hyper-params that we have chosen.
In this post we clarified the distinction between params and hyper-params in the context of supervised ML and showed, through an experiment, that optimizing over hyper-params can be a tricky and costly business, in terms of computing time and electricity. We see, however, that there are approaches such as coordinate descent that go beyond plain vanilla grid search in terms of speed and quality of the discovered hyper-param vectors.
Stay tuned for a second post in this series in which we shall try out three other optimization approaches: Bayesian optimization, HyperOpt and auto-tune.
|
[
{
"code": null,
"e": 939,
"s": 172,
"text": "In this post and the next, we will look at one of the trickiest and most critical problems in Machine Learning (ML): Hyper-parameter tuning. After reviewing what hyper-parameters, or hyper-params for short, are and how they differ from plain vanilla learnable parameters, we introduce three general purpose discrete optimization algorithms aimed at search for the optimal hyper-param combination: grid-search, coordinate descent and genetic algorithms. We report on the results of an experiment in which we use each of these to come up with good hyperparameters on an example ML problem taken from Kaggle. Although we focus on optimizing XGBoost hyper-parameters in our experiment, pretty much all of what we will present applies to any other advanced ML algorithms."
},
{
"code": null,
"e": 1552,
"s": 939,
"text": "The most powerful ML algorithms are famous for picking up patterns and regularities in the data by automatically tuning thousands (or even millions) of so-called “learnable” parameters. For instance, in tree-based models (decision trees, random forests, XGBoost), the learnable parameters are the choice of decision variables at each node and the numeric thresholds used to decide whether to take the left or right branch when generating predictions. In neural networks, the learnable parameters are the weights used on each connection to amplify or negate the activation from a previous layer into the next one."
},
{
"code": null,
"e": 2422,
"s": 1552,
"text": "Learnable parameters are, however, only part of the story. In fact, they are the easy part. The more flexible and powerful an algorithm is, the more design decisions and adjustable hyper-parameters it will have. These are parameters specified by “hand” to the algo and fixed throughout a training pass. Further, the algo typically does not include any logic to optimize them for us. In tree-based models, hyper-parameters include things like the maximum depth of the tree, the number of trees to grow, the number of variables to consider when building each tree, the minimum number of samples on a leaf, the fraction of observations used to build a tree, and a few others. For neural networks, the list includes the number of hidden layers, the size (and shape) of each layer, the choice of activation function, the drop-out rate and the L1/L2 regularization constants."
},
{
"code": null,
"e": 3156,
"s": 2422,
"text": "From a computational point of view, supervised ML boils down to minimizing a certain loss function (e.g. the MSE or the classification error) that depends on the data training input data (Xt, Yt), the learnable params which we denote by a, and the hyper-params. The crucial observation here is that this minimization is done by letting only the learnable parameters vary, while holding the data and the hyper-params constant. To choose the optimal set of hyper-params, the usual approach is to perform cross-validation. Given a hyper-param vector h, its quality is assessed by evaluating the loss function on a held-out set of validation data using the best set of learnable parameters, a*, for that value of h. Symbolically, we have"
},
{
"code": null,
"e": 3193,
"s": 3156,
"text": "Introducing the Hyper-Parameter Grid"
},
{
"code": null,
"e": 3773,
"s": 3193,
"text": "One important thing to note about hyper-parameters is that, often, they take on discrete values, with notable exceptions being things like drop-out rates or regularization constants. Thus, for practical reasons and to avoid the complexities involved in doing hybrid continuous-discrete optimization, most approaches to hyper-parameter tuning start off by discretizing the ranges of all hyper-parameters in question. For example, for our XGBoost experiments below we will fine-tune five hyperparameters. The ranges of possible values that we will consider for each are as follows:"
},
{
"code": null,
"e": 4021,
"s": 3773,
"text": "{\"learning_rate\" : [0.05, 0.10, 0.15, 0.20, 0.25, 0.30 ] , \"max_depth\" : [ 3, 4, 5, 6, 8, 10, 12, 15], \"min_child_weight\" : [ 1, 3, 5, 7 ], \"gamma\" : [ 0.0, 0.1, 0.2 , 0.3, 0.4 ], \"colsample_bytree\" : [ 0.3, 0.4, 0.5 , 0.7 ] }"
},
{
"code": null,
"e": 4127,
"s": 4021,
"text": "For an explanation of what each of these means in the context of XGBost we refer the reader to this post."
},
{
"code": null,
"e": 4593,
"s": 4127,
"text": "Notice that despite having limited the range for the (continuous) learning_rate hyper-parameter to only six values, that of max_depth to 8, and so forth, there are 6 x 8 x 4 x 5 x 4 = 3840 possible combinations of hyper parameters. This discrete subspace of all possible hyper-parameters is called the hyper-parameter grid. In what follows, we will use the vector notation symbol h = [h0, h1, ..., hp] to denote any such combination, that is, any point in the grid."
},
{
"code": null,
"e": 5481,
"s": 4593,
"text": "Exhaustive grid search (GS) is nothing other than the brute force approach that scans the whole grid of hyper-param combinations h in some order, computes the cross-validation loss for each one and finds the optimal h* in this manner. Generally, the use of lexicographic ordering, that is, the dictionary order imposed on hyper-param vectors, is discouraged and a different order should be considered. The reason is that with lexicographic ordering there is a high chance that the search will focus on a rather uninteresting part of the search space for a rather long time. An interesting alternative is scanning the whole grid in a fully randomized way that is, according to a random permutation of the whole grid . With this type of search, it is likely that one encounters close-to-optimal regions of the hyper-param space early on. We show some evidence of this in the example below."
},
{
"code": null,
"e": 6109,
"s": 5481,
"text": "Coordinate descent (CD) is one of the simplest optimization algorithms. It’s an iterative algorithm, similar to gradient descent, but even simpler! The basic idea is that, at each iteration, only one of the coordinate directions of our search vector h is altered. To pick which one, we examine each coordinate direction turn and minimize the objective function by varying that coordinate and leaving all the other constant. Then we pick the direction that yields the most improvement. The algorithm stops when none of the directions yields any improvement. To learn all the details we refer the reader to the Wikipedia article."
},
{
"code": null,
"e": 6329,
"s": 6109,
"text": "The main advantage of this simple approach is that it is easily adaptable to the fully discrete case for which the arbitrary directions given by gradient descent cannot be easily used. We provide an implementation here."
},
{
"code": null,
"e": 7372,
"s": 6329,
"text": "Genetic algorithms (GAs) are a whole class of optimization algorithms of rather general applicability and are particularly well adapted for high-dimensional discrete search spaces. A genetic algorithm tries to mimic nature by simulating a population of feasible solutions to a(n optimization) problem as they evolve through several generations and survival of the fittest is enforced. There are two basic mechanisms for generating a new generation from the previous one. One is cross-breeding in which two individuals (feasible solutions) are combined to produce two offspring. The other one is mutation. With a given mutation probability, any individual can change any of their params to another valid value. Survival of the fittest is enforced by letting fitter individuals cross-breed with higher probability than less fit individuals. The fitness of an individual is of course the negative of the loss function.For the whole details we refer the reader to Wikipedia or to AIMA, Part II Chapter 4. Our own implementation is available here."
},
{
"code": null,
"e": 8500,
"s": 7372,
"text": "To get a feeling for each of the hyper-param optimization approaches mentioned above, we performed an experiment using actual data taken from the Home Credit Default Risk binary-classification competition, currently being held on Kaggle. We only considered the application_(train|test) data sets and performed a rather minimal data preparation step (see function prepare_data here). Further, to keep training and validation times short and allow for full exploration of the hyper-param space in a reasonable time, we sub-sampled the training set, keeping only 4% of the records (approx. 12,000). For validation, we used a separate 3.2% of the records (approx. 10,000). Even with this small amount of data, a single round of training and validation takes around 3 seconds, for a given set of hyper-params, which is not negligible considering that we intend to scan the whole hyper-param grid. For the reasons just mentioned, the cross-validation AUC values we get are not competitive with the ones at the top of the leader board, which surely are making use of all available records in all data sets provided by the competition."
},
{
"code": null,
"e": 8804,
"s": 8500,
"text": "As mentioned before, we chose XGBoost as our machine-learning architecture. Due to the outstanding accuracy obtained by XGBoost, as well as its computational performance, it is perhaps the most popular choice among Kagglers and many other ML practitioners for purely “tabular” problems such as this one."
},
{
"code": null,
"e": 9637,
"s": 8804,
"text": "Now, for each of the three hyper-param tuning methods mentioned above, we ran 10,000 independent trials. Each trial first resets the random seed to a new value, then initializes the hyper-param vector to a random value from our grid, and then proceeds to generate a sequence of hyper-param vectors following the optimization algorithm being tested. When testing GS, the trial just goes through hyper-param vectors according to a random permutation of the whole grid. With CD, the generated hyper-param vectors are all the ones tried out in intermediate evaluations of the CD algorithm. When CD gets stuck at a local optimum, it gets restarted to a new initial vector uniformly at random. With the genetic algo, the hyper-param vectors are the ones contained in the “DNA” of every individual generated in every successive generation."
},
{
"code": null,
"e": 10005,
"s": 9637,
"text": "By the way, we were able to run these many trials despite the cost of each CV-loss evaluation thanks to a technique called memoization (https://en.wikipedia.org/wiki/Memoization). Essentially, once the CV-loss of a hyper-param vector was evaluated for the first time, we kept it in a look-up table shared among the three methods and never had to re-evaluate it again."
},
{
"code": null,
"e": 10430,
"s": 10005,
"text": "While running each trial, we keep a log of all the hyper-param vectors tried and their corresponding cross-validation losses. The following plots show the behavior of a typical trial, for each of the three methods, The y-axis shows the negative of the CV loss, which in this case is just the CV_AUC metric which we are maximizing. The X-axis keeps track of “time”, that is, the total number CV-AUC evaluations up to a point."
},
{
"code": null,
"e": 11003,
"s": 10430,
"text": "The orange “envelope” line keeps track of the “running best,” which is the best AUC value seen among all function evaluations prior to a point. In a sense, this line is all we care about, as every method will always return the best of all hyper-param vectors evaluated and not simply the last one. Notice how different all three methods look at this level. GS succeeds in gradually maximizing the AUC by mere chance. The deliberate “effort” that coordinate descent and the genetic algorithm make in finding progressively better values is apparent from their plots as well."
},
{
"code": null,
"e": 11163,
"s": 11003,
"text": "However, one randomized trial does not tell the whole story. Let’s look at the “envelope” lines for each of 30 independent trials of each of the three methods."
},
{
"code": null,
"e": 11757,
"s": 11163,
"text": "Interesting... The envelope lines of the grid-search and genetic algos quickly cluster towards the top, unlike the CD one... This means that, with high probability, almost all trials of GS and genetic are likely to give near optimal solutions quicker than CD. On the other hand, the overall best solution is achieved around function evaluation #40 by one of the CD trials, and we don’t see the same for the other methods. Also coordinate descent beats the other two methods after function evaluation #100 or so, in that all of the 30 trials are nearly optimal and show a much smaller variance!"
},
{
"code": null,
"e": 12136,
"s": 11757,
"text": "Let’s look at a final plot. What if we take the 10% percentile of the running-best AUC among all 10000 trials? This number is interesting because it gives us a sense of how the running-best of most trials evolves as a function of the number of evaluations. Another way to put it is that it gives us a 90% confidence bound on the worst we can expect from each method. Here it is:"
},
{
"code": null,
"e": 12712,
"s": 12136,
"text": "Aha! This is more compelling evidence of what was mentioned above as it tells us that,with probability at least 90%, a randomized trial of coordinate descent will have seen, by CV-AUC evaluation #90, a hyper-param vector with an AUC of around 0.740 or better, whereas the corresponding value for GS is only around 0.738. This might seem like a minor difference, but it is quite significant as far as ML metrics go. Perhaps more telling than that is the fact that, up until the point it plateaus, the CD curve in the plot above has a distinctly higher slope than the GS curve."
},
{
"code": null,
"e": 13614,
"s": 12712,
"text": "The GA, on the other hand, seems to be dominated by GS throughout. This perhaps shouldn’t surprise us. On the one hand GA’s depend on several adjustable parameters (which would be hyper-hyper-parameters in our formulation) such as generation size, mutation rate, ordering of the instance variables to build a DNA sequence and the function linking AUC to the probability of cross-breading. For our experiment, we only tried a couple of settings for these. It is likely that with different settings GA would have beat GS. On the other hand, it’s known (see, for instance AIMA , at the end of page 148 ) that genetic algorithms work best when there are contiguous blocks of genes (hyper-params in our case) for which there are certain combinations of values that work better on average. It is not clear if this is the case in for the rather arbitrary ordering of XGBoost hyper-params that we have chosen."
},
{
"code": null,
"e": 14050,
"s": 13614,
"text": "In this post we clarified the distinction between params and hyper-params in the context of supervised ML and showed, through an experiment, that optimizing over hyper-params can be a tricky and costly business, in terms of computing time and electricity. We see, however, that there are approaches such as coordinate descent that go beyond plain vanilla grid search in terms of speed and quality of the discovered hyper-param vectors."
}
] |
How to remove the digits after the decimal point in axis ticks in Matplotlib?
|
To remove the digits after the decimal point in axis ticks in Matplotlib, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Set the figure size and adjust the padding between and around the subplots.
Create x and y data points using numpy.
Create x and y data points using numpy.
Create a figure and a set of subplots.
Create a figure and a set of subplots.
To set the xtick labels only in digits, we can use x.astype(int) method.
To set the xtick labels only in digits, we can use x.astype(int) method.
To display the figure, use show() method.
To display the figure, use show() method.
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.array([1.110, 2.110, 4.110, 5.901, 6.00, 7.90, 8.90])
y = np.array([2.110, 1.110, 3.110, 9.00, 4.001, 2.095, 5.890])
fig, ax = plt.subplots()
ax.plot(x, y)
ax.set_xticklabels(x.astype(int))
plt.show()
|
[
{
"code": null,
"e": 1170,
"s": 1062,
"text": "To remove the digits after the decimal point in axis ticks in Matplotlib, we can take the following steps −"
},
{
"code": null,
"e": 1246,
"s": 1170,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1322,
"s": 1246,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1362,
"s": 1322,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1402,
"s": 1362,
"text": "Create x and y data points using numpy."
},
{
"code": null,
"e": 1441,
"s": 1402,
"text": "Create a figure and a set of subplots."
},
{
"code": null,
"e": 1480,
"s": 1441,
"text": "Create a figure and a set of subplots."
},
{
"code": null,
"e": 1553,
"s": 1480,
"text": "To set the xtick labels only in digits, we can use x.astype(int) method."
},
{
"code": null,
"e": 1626,
"s": 1553,
"text": "To set the xtick labels only in digits, we can use x.astype(int) method."
},
{
"code": null,
"e": 1668,
"s": 1626,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1710,
"s": 1668,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 2062,
"s": 1710,
"text": "import matplotlib.pyplot as plt\nimport numpy as np\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nx = np.array([1.110, 2.110, 4.110, 5.901, 6.00, 7.90, 8.90])\ny = np.array([2.110, 1.110, 3.110, 9.00, 4.001, 2.095, 5.890])\n\nfig, ax = plt.subplots()\n\nax.plot(x, y)\n\nax.set_xticklabels(x.astype(int))\n\nplt.show()"
}
] |
Batch Script - String Concatenation
|
You can use the set operator to concatenate two strings or a string and a character, or two characters. Following is a simple example which shows how to use string concatenation.
@echo off
SET a = Hello
SET b = World
SET c=%a% and %b%
echo %c%
The above command produces the following output.
Hello and World
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2348,
"s": 2169,
"text": "You can use the set operator to concatenate two strings or a string and a character, or two characters. Following is a simple example which shows how to use string concatenation."
},
{
"code": null,
"e": 2417,
"s": 2348,
"text": "@echo off \nSET a = Hello \nSET b = World \nSET c=%a% and %b% \necho %c%"
},
{
"code": null,
"e": 2466,
"s": 2417,
"text": "The above command produces the following output."
},
{
"code": null,
"e": 2483,
"s": 2466,
"text": "Hello and World\n"
},
{
"code": null,
"e": 2490,
"s": 2483,
"text": " Print"
},
{
"code": null,
"e": 2501,
"s": 2490,
"text": " Add Notes"
}
] |
C++ Program To Merge K Sorted Linked Lists - Set 1 - GeeksforGeeks
|
03 Jan, 2022
Given K sorted linked lists of size N each, merge them and print the sorted output.
Examples:
Input: k = 3, n = 4
list1 = 1->3->5->7->NULL
list2 = 2->4->6->8->NULL
list3 = 0->9->10->11->NULL
Output: 0->1->2->3->4->5->6->7->8->9->10->11
Merged lists in a sorted order
where every element is greater
than the previous element.
Input: k = 3, n = 3
list1 = 1->3->7->NULL
list2 = 2->4->8->NULL
list3 = 9->10->11->NULL
Output: 1->2->3->4->7->8->9->10->11
Merged lists in a sorted order
where every element is greater
than the previous element.
Method 1 (Simple):
Approach: A Simple Solution is to initialize the result as the first list. Now traverse all lists starting from the second list. Insert every node of the currently traversed list into result in a sorted way.
C++
// C++ program to merge k sorted// linked lists of size n each#include <bits/stdc++.h>using namespace std; // A Linked List nodestruct Node { int data; Node* next;}; /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} // The main function that takes an // array of lists arr[0..last] and // generates the sorted outputNode* mergeKLists(Node* arr[], int last){ // Traverse form second list to last for (int i = 1; i <= last; i++) { while (true) { // Head of both the lists, // 0 and ith list. Node *head_0 = arr[0], *head_i = arr[i]; // Break if list ended if (head_i == NULL) break; // Smaller than first element if (head_0->data >= head_i->data) { arr[i] = head_i->next; head_i->next = head_0; arr[0] = head_i; } else // Traverse the first list while (head_0->next != NULL) { // Smaller than next element if (head_0->next->data >= head_i->data) { arr[i] = head_i->next; head_i->next = head_0->next; head_0->next = head_i; break; } // go to next node head_0 = head_0->next; // if last node if (head_0->next == NULL) { arr[i] = head_i->next; head_i->next = NULL; head_0->next = head_i; head_0->next->next = NULL; break; } } } } return arr[0];} // Utility function to create // a new node.Node* newNode(int data){ struct Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Driver codeint main(){ // Number of linked lists int k = 3; // Number of elements in each list int n = 4; // an array of pointers storing the // head nodes of the linked lists Node* arr[k]; arr[0] = newNode(1); arr[0]->next = newNode(3); arr[0]->next->next = newNode(5); arr[0]->next->next->next = newNode(7); arr[1] = newNode(2); arr[1]->next = newNode(4); arr[1]->next->next = newNode(6); arr[1]->next->next->next = newNode(8); arr[2] = newNode(0); arr[2]->next = newNode(9); arr[2]->next->next = newNode(10); arr[2]->next->next->next = newNode(11); // Merge all lists Node* head = mergeKLists(arr, k - 1); printList(head); return 0;}
Output:
0 1 2 3 4 5 6 7 8 9 10 11
Complexity Analysis:
Time complexity: O(nk2)
Auxiliary Space: O(1). As no extra space is required.
Method 2: Min Heap. A Better solution is to use Min Heap-based solution which is discussed here for arrays. The time complexity of this solution would be O(nk Log k)Method 3: Divide and Conquer. In this post, Divide and Conquer approach is discussed. This approach doesn’t require extra space for heap and works in O(nk Log k)It is known that merging of two linked lists can be done in O(n) time and O(n) space.
The idea is to pair up K lists and merge each pair in linear time using O(n) space.After the first cycle, K/2 lists are left each of size 2*N. After the second cycle, K/4 lists are left each of size 4*N and so on.Repeat the procedure until we have only one list left.
The idea is to pair up K lists and merge each pair in linear time using O(n) space.
After the first cycle, K/2 lists are left each of size 2*N. After the second cycle, K/4 lists are left each of size 4*N and so on.
Repeat the procedure until we have only one list left.
Below is the implementation of the above idea.
C++
// C++ program to merge k sorted// linked lists of size n each#include <bits/stdc++.h>using namespace std; // A Linked List nodestruct Node { int data; Node* next;}; /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { printf("%d ", node->data); node = node->next; }} /* Takes two lists sorted in increasing order, and merge their nodes together to make one big sorted list. Below function takes O(n) extra space for recursive calls, */Node* SortedMerge(Node* a, Node* b){ Node* result = NULL; // Base cases if (a == NULL) return (b); else if (b == NULL) return (a); // Pick either a or b, and recur if (a->data <= b->data) { result = a; result->next = SortedMerge(a->next, b); } else { result = b; result->next = SortedMerge(a, b->next); } return result;} // The main function that takes an // array of lists arr[0..last] and // generates the sorted outputNode* mergeKLists(Node* arr[], int last){ // Repeat until only one list is left while (last != 0) { int i = 0, j = last; // (i, j) forms a pair while (i < j) { // merge List i with List j and // store merged list in List i arr[i] = SortedMerge(arr[i], arr[j]); // consider next pair i++, j--; // If all pairs are merged, update // last if (i >= j) last = j; } } return arr[0];} // Utility function to create // a new node.Node* newNode(int data){ struct Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Driver codeint main(){ // Number of linked lists int k = 3; // Number of elements in // each list int n = 4; // An array of pointers storing // the head nodes of the linked lists Node* arr[k]; arr[0] = newNode(1); arr[0]->next = newNode(3); arr[0]->next->next = newNode(5); arr[0]->next->next->next = newNode(7); arr[1] = newNode(2); arr[1]->next = newNode(4); arr[1]->next->next = newNode(6); arr[1]->next->next->next = newNode(8); arr[2] = newNode(0); arr[2]->next = newNode(9); arr[2]->next->next = newNode(10); arr[2]->next->next->next = newNode(11); // Merge all lists Node* head = mergeKLists(arr, k - 1); printList(head); return 0;}
Output:
0 1 2 3 4 5 6 7 8 9 10 11
Complexity Analysis:
Assuming N(n*k) is the total number of nodes, n is the size of each linked list, and k is the total number of linked lists.
Time Complexity: O(N*log k) or O(n*k*log k)As outer while loop in function mergeKLists() runs log k times and every time it processes n*k elements.
Auxiliary Space: O(N) or O(n*k)Because recursion is used in SortedMerge() and to merge the final 2 linked lists of size N/2, N recursive calls will be made.
Please refer complete article on Merge K sorted linked lists | Set 1 for more details!
Amazon
Merge Sort
VMWare
C++ Programs
Heap
Linked List
VMWare
Amazon
Linked List
Heap
Merge Sort
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Passing a function as a parameter in C++
Program to implement Singly Linked List in C++ using class
Const keyword in C++
cout in C++
Dynamic _Cast in C++
HeapSort
Binary Heap
Huffman Coding | Greedy Algo-3
K'th Smallest/Largest Element in Unsorted Array | Set 1
k largest(or smallest) elements in an array
|
[
{
"code": null,
"e": 24606,
"s": 24578,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 24690,
"s": 24606,
"text": "Given K sorted linked lists of size N each, merge them and print the sorted output."
},
{
"code": null,
"e": 24701,
"s": 24690,
"text": "Examples: "
},
{
"code": null,
"e": 25154,
"s": 24701,
"text": "Input: k = 3, n = 4\nlist1 = 1->3->5->7->NULL\nlist2 = 2->4->6->8->NULL\nlist3 = 0->9->10->11->NULL\n\nOutput: 0->1->2->3->4->5->6->7->8->9->10->11\nMerged lists in a sorted order \nwhere every element is greater \nthan the previous element.\n\nInput: k = 3, n = 3\nlist1 = 1->3->7->NULL\nlist2 = 2->4->8->NULL\nlist3 = 9->10->11->NULL\n\nOutput: 1->2->3->4->7->8->9->10->11\nMerged lists in a sorted order \nwhere every element is greater \nthan the previous element."
},
{
"code": null,
"e": 25173,
"s": 25154,
"text": "Method 1 (Simple):"
},
{
"code": null,
"e": 25383,
"s": 25173,
"text": "Approach: A Simple Solution is to initialize the result as the first list. Now traverse all lists starting from the second list. Insert every node of the currently traversed list into result in a sorted way. "
},
{
"code": null,
"e": 25387,
"s": 25383,
"text": "C++"
},
{
"code": "// C++ program to merge k sorted// linked lists of size n each#include <bits/stdc++.h>using namespace std; // A Linked List nodestruct Node { int data; Node* next;}; /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} // The main function that takes an // array of lists arr[0..last] and // generates the sorted outputNode* mergeKLists(Node* arr[], int last){ // Traverse form second list to last for (int i = 1; i <= last; i++) { while (true) { // Head of both the lists, // 0 and ith list. Node *head_0 = arr[0], *head_i = arr[i]; // Break if list ended if (head_i == NULL) break; // Smaller than first element if (head_0->data >= head_i->data) { arr[i] = head_i->next; head_i->next = head_0; arr[0] = head_i; } else // Traverse the first list while (head_0->next != NULL) { // Smaller than next element if (head_0->next->data >= head_i->data) { arr[i] = head_i->next; head_i->next = head_0->next; head_0->next = head_i; break; } // go to next node head_0 = head_0->next; // if last node if (head_0->next == NULL) { arr[i] = head_i->next; head_i->next = NULL; head_0->next = head_i; head_0->next->next = NULL; break; } } } } return arr[0];} // Utility function to create // a new node.Node* newNode(int data){ struct Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Driver codeint main(){ // Number of linked lists int k = 3; // Number of elements in each list int n = 4; // an array of pointers storing the // head nodes of the linked lists Node* arr[k]; arr[0] = newNode(1); arr[0]->next = newNode(3); arr[0]->next->next = newNode(5); arr[0]->next->next->next = newNode(7); arr[1] = newNode(2); arr[1]->next = newNode(4); arr[1]->next->next = newNode(6); arr[1]->next->next->next = newNode(8); arr[2] = newNode(0); arr[2]->next = newNode(9); arr[2]->next->next = newNode(10); arr[2]->next->next->next = newNode(11); // Merge all lists Node* head = mergeKLists(arr, k - 1); printList(head); return 0;}",
"e": 28290,
"s": 25387,
"text": null
},
{
"code": null,
"e": 28298,
"s": 28290,
"text": "Output:"
},
{
"code": null,
"e": 28324,
"s": 28298,
"text": "0 1 2 3 4 5 6 7 8 9 10 11"
},
{
"code": null,
"e": 28346,
"s": 28324,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 28370,
"s": 28346,
"text": "Time complexity: O(nk2)"
},
{
"code": null,
"e": 28424,
"s": 28370,
"text": "Auxiliary Space: O(1). As no extra space is required."
},
{
"code": null,
"e": 28837,
"s": 28424,
"text": "Method 2: Min Heap. A Better solution is to use Min Heap-based solution which is discussed here for arrays. The time complexity of this solution would be O(nk Log k)Method 3: Divide and Conquer. In this post, Divide and Conquer approach is discussed. This approach doesn’t require extra space for heap and works in O(nk Log k)It is known that merging of two linked lists can be done in O(n) time and O(n) space. "
},
{
"code": null,
"e": 29105,
"s": 28837,
"text": "The idea is to pair up K lists and merge each pair in linear time using O(n) space.After the first cycle, K/2 lists are left each of size 2*N. After the second cycle, K/4 lists are left each of size 4*N and so on.Repeat the procedure until we have only one list left."
},
{
"code": null,
"e": 29189,
"s": 29105,
"text": "The idea is to pair up K lists and merge each pair in linear time using O(n) space."
},
{
"code": null,
"e": 29320,
"s": 29189,
"text": "After the first cycle, K/2 lists are left each of size 2*N. After the second cycle, K/4 lists are left each of size 4*N and so on."
},
{
"code": null,
"e": 29375,
"s": 29320,
"text": "Repeat the procedure until we have only one list left."
},
{
"code": null,
"e": 29423,
"s": 29375,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 29427,
"s": 29423,
"text": "C++"
},
{
"code": "// C++ program to merge k sorted// linked lists of size n each#include <bits/stdc++.h>using namespace std; // A Linked List nodestruct Node { int data; Node* next;}; /* Function to print nodes in a given linked list */void printList(Node* node){ while (node != NULL) { printf(\"%d \", node->data); node = node->next; }} /* Takes two lists sorted in increasing order, and merge their nodes together to make one big sorted list. Below function takes O(n) extra space for recursive calls, */Node* SortedMerge(Node* a, Node* b){ Node* result = NULL; // Base cases if (a == NULL) return (b); else if (b == NULL) return (a); // Pick either a or b, and recur if (a->data <= b->data) { result = a; result->next = SortedMerge(a->next, b); } else { result = b; result->next = SortedMerge(a, b->next); } return result;} // The main function that takes an // array of lists arr[0..last] and // generates the sorted outputNode* mergeKLists(Node* arr[], int last){ // Repeat until only one list is left while (last != 0) { int i = 0, j = last; // (i, j) forms a pair while (i < j) { // merge List i with List j and // store merged list in List i arr[i] = SortedMerge(arr[i], arr[j]); // consider next pair i++, j--; // If all pairs are merged, update // last if (i >= j) last = j; } } return arr[0];} // Utility function to create // a new node.Node* newNode(int data){ struct Node* temp = new Node; temp->data = data; temp->next = NULL; return temp;} // Driver codeint main(){ // Number of linked lists int k = 3; // Number of elements in // each list int n = 4; // An array of pointers storing // the head nodes of the linked lists Node* arr[k]; arr[0] = newNode(1); arr[0]->next = newNode(3); arr[0]->next->next = newNode(5); arr[0]->next->next->next = newNode(7); arr[1] = newNode(2); arr[1]->next = newNode(4); arr[1]->next->next = newNode(6); arr[1]->next->next->next = newNode(8); arr[2] = newNode(0); arr[2]->next = newNode(9); arr[2]->next->next = newNode(10); arr[2]->next->next->next = newNode(11); // Merge all lists Node* head = mergeKLists(arr, k - 1); printList(head); return 0;}",
"e": 31911,
"s": 29427,
"text": null
},
{
"code": null,
"e": 31919,
"s": 31911,
"text": "Output:"
},
{
"code": null,
"e": 31945,
"s": 31919,
"text": "0 1 2 3 4 5 6 7 8 9 10 11"
},
{
"code": null,
"e": 31967,
"s": 31945,
"text": "Complexity Analysis: "
},
{
"code": null,
"e": 32091,
"s": 31967,
"text": "Assuming N(n*k) is the total number of nodes, n is the size of each linked list, and k is the total number of linked lists."
},
{
"code": null,
"e": 32239,
"s": 32091,
"text": "Time Complexity: O(N*log k) or O(n*k*log k)As outer while loop in function mergeKLists() runs log k times and every time it processes n*k elements."
},
{
"code": null,
"e": 32396,
"s": 32239,
"text": "Auxiliary Space: O(N) or O(n*k)Because recursion is used in SortedMerge() and to merge the final 2 linked lists of size N/2, N recursive calls will be made."
},
{
"code": null,
"e": 32483,
"s": 32396,
"text": "Please refer complete article on Merge K sorted linked lists | Set 1 for more details!"
},
{
"code": null,
"e": 32490,
"s": 32483,
"text": "Amazon"
},
{
"code": null,
"e": 32501,
"s": 32490,
"text": "Merge Sort"
},
{
"code": null,
"e": 32508,
"s": 32501,
"text": "VMWare"
},
{
"code": null,
"e": 32521,
"s": 32508,
"text": "C++ Programs"
},
{
"code": null,
"e": 32526,
"s": 32521,
"text": "Heap"
},
{
"code": null,
"e": 32538,
"s": 32526,
"text": "Linked List"
},
{
"code": null,
"e": 32545,
"s": 32538,
"text": "VMWare"
},
{
"code": null,
"e": 32552,
"s": 32545,
"text": "Amazon"
},
{
"code": null,
"e": 32564,
"s": 32552,
"text": "Linked List"
},
{
"code": null,
"e": 32569,
"s": 32564,
"text": "Heap"
},
{
"code": null,
"e": 32580,
"s": 32569,
"text": "Merge Sort"
},
{
"code": null,
"e": 32678,
"s": 32580,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32719,
"s": 32678,
"text": "Passing a function as a parameter in C++"
},
{
"code": null,
"e": 32778,
"s": 32719,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 32799,
"s": 32778,
"text": "Const keyword in C++"
},
{
"code": null,
"e": 32811,
"s": 32799,
"text": "cout in C++"
},
{
"code": null,
"e": 32832,
"s": 32811,
"text": "Dynamic _Cast in C++"
},
{
"code": null,
"e": 32841,
"s": 32832,
"text": "HeapSort"
},
{
"code": null,
"e": 32853,
"s": 32841,
"text": "Binary Heap"
},
{
"code": null,
"e": 32884,
"s": 32853,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 32940,
"s": 32884,
"text": "K'th Smallest/Largest Element in Unsorted Array | Set 1"
}
] |
C# | How to remove the element from the specified index of the List - GeeksforGeeks
|
01 Feb, 2019
List<T>.RemoveAt (Int32) Method is used to remove the element at the specified index of the List<T>.
Properties of List:
It is different from the arrays. A list can be resized dynamically but arrays cannot.
List class can accept null as a valid value for reference types and it also allows duplicate elements.
If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element.
Syntax:
public void RemoveAt (int index);
Parameters:
index: It is the zero-based starting index of the element which is to be removed.count: It is the number of the elements which is to be removed.
Exceptions: This method will give ArgumentOutOfRangeException if the index is less than 0 or equal to or greater than Count.
Below programs illustrate the use of List<T>.RemoveAt (Int32) Method:
Example 1:
// C# Program to remove the element at// the specified index of the List<T>using System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(17); firstlist.Add(19); firstlist.Add(21); firstlist.Add(9); firstlist.Add(75); firstlist.Add(19); firstlist.Add(73); Console.WriteLine("Elements Present in List:\n"); int p = 0; // Displaying the elements of List foreach(int k in firstlist) { Console.Write("At Position {0}: ", p); Console.WriteLine(k); p++; } Console.WriteLine(" "); // removing the element at index 3 Console.WriteLine("Removing the element at index 3\n"); // 9 will remove from the List // and 75 will come at index 3 firstlist.RemoveAt(3); int p1 = 0; // Displaying the elements of List foreach(int n in firstlist) { Console.Write("At Position {0}: ", p1); Console.WriteLine(n); p1++; } }}
Output:
Elements Present in List:
At Position 0: 17
At Position 1: 19
At Position 2: 21
At Position 3: 9
At Position 4: 75
At Position 5: 19
At Position 6: 73
Removing the element at index 3
At Position 0: 17
At Position 1: 19
At Position 2: 21
At Position 3: 75
At Position 4: 19
At Position 5: 73
Example 2:
// C# Program to remove the element at// the specified index of the List<T>using System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(17); firstlist.Add(19); firstlist.Add(21); firstlist.Add(9); firstlist.Add(75); firstlist.Add(19); firstlist.Add(73); Console.WriteLine("Elements Present in List:\n"); int p = 0; // Displaying the elements of List foreach(int k in firstlist) { Console.Write("At Position {0}: ", p); Console.WriteLine(k); p++; } Console.WriteLine(" "); // removing the element at index 3 Console.WriteLine("Removing the element at index 3\n"); // taking negative index // it will give error as index // cannot be less than 0 firstlist.RemoveAt(-1); int p1 = 0; // Displaying the elements of List foreach(int n in firstlist) { Console.Write("At Position {0}: ", p1); Console.WriteLine(n); p1++; } }}
Runtime Error:
Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index
Output:
Elements Present in List:
At Position 0: 17
At Position 1: 19
At Position 2: 21
At Position 3: 9
At Position 4: 75
At Position 5: 19
At Position 6: 73
Removing the element at index 3
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removeat?view=netframework-4.7.2
CSharp-Collections-Namespace
CSharp-Generic-List
CSharp-Generic-Namespace
CSharp-method
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
C# | Method Overriding
C# Dictionary with examples
Difference between Ref and Out keywords in C#
C# | Delegates
Top 50 C# Interview Questions & Answers
Introduction to .NET Framework
C# | Constructors
Extension Method in C#
C# | Class and Object
C# | Abstract Classes
|
[
{
"code": null,
"e": 24379,
"s": 24351,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 24480,
"s": 24379,
"text": "List<T>.RemoveAt (Int32) Method is used to remove the element at the specified index of the List<T>."
},
{
"code": null,
"e": 24500,
"s": 24480,
"text": "Properties of List:"
},
{
"code": null,
"e": 24586,
"s": 24500,
"text": "It is different from the arrays. A list can be resized dynamically but arrays cannot."
},
{
"code": null,
"e": 24689,
"s": 24586,
"text": "List class can accept null as a valid value for reference types and it also allows duplicate elements."
},
{
"code": null,
"e": 24913,
"s": 24689,
"text": "If the Count becomes equals to Capacity then the capacity of the List increases automatically by reallocating the internal array. The existing elements will be copied to the new array before the addition of the new element."
},
{
"code": null,
"e": 24921,
"s": 24913,
"text": "Syntax:"
},
{
"code": null,
"e": 24955,
"s": 24921,
"text": "public void RemoveAt (int index);"
},
{
"code": null,
"e": 24967,
"s": 24955,
"text": "Parameters:"
},
{
"code": null,
"e": 25112,
"s": 24967,
"text": "index: It is the zero-based starting index of the element which is to be removed.count: It is the number of the elements which is to be removed."
},
{
"code": null,
"e": 25237,
"s": 25112,
"text": "Exceptions: This method will give ArgumentOutOfRangeException if the index is less than 0 or equal to or greater than Count."
},
{
"code": null,
"e": 25307,
"s": 25237,
"text": "Below programs illustrate the use of List<T>.RemoveAt (Int32) Method:"
},
{
"code": null,
"e": 25318,
"s": 25307,
"text": "Example 1:"
},
{
"code": "// C# Program to remove the element at// the specified index of the List<T>using System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(17); firstlist.Add(19); firstlist.Add(21); firstlist.Add(9); firstlist.Add(75); firstlist.Add(19); firstlist.Add(73); Console.WriteLine(\"Elements Present in List:\\n\"); int p = 0; // Displaying the elements of List foreach(int k in firstlist) { Console.Write(\"At Position {0}: \", p); Console.WriteLine(k); p++; } Console.WriteLine(\" \"); // removing the element at index 3 Console.WriteLine(\"Removing the element at index 3\\n\"); // 9 will remove from the List // and 75 will come at index 3 firstlist.RemoveAt(3); int p1 = 0; // Displaying the elements of List foreach(int n in firstlist) { Console.Write(\"At Position {0}: \", p1); Console.WriteLine(n); p1++; } }}",
"e": 26602,
"s": 25318,
"text": null
},
{
"code": null,
"e": 26610,
"s": 26602,
"text": "Output:"
},
{
"code": null,
"e": 26906,
"s": 26610,
"text": "Elements Present in List:\n\nAt Position 0: 17\nAt Position 1: 19\nAt Position 2: 21\nAt Position 3: 9\nAt Position 4: 75\nAt Position 5: 19\nAt Position 6: 73\n \nRemoving the element at index 3\n\nAt Position 0: 17\nAt Position 1: 19\nAt Position 2: 21\nAt Position 3: 75\nAt Position 4: 19\nAt Position 5: 73\n"
},
{
"code": null,
"e": 26917,
"s": 26906,
"text": "Example 2:"
},
{
"code": "// C# Program to remove the element at// the specified index of the List<T>using System;using System.Collections;using System.Collections.Generic; class Geeks { // Main Method public static void Main(String[] args) { // Creating an List<T> of Integers List<int> firstlist = new List<int>(); // Adding elements to List firstlist.Add(17); firstlist.Add(19); firstlist.Add(21); firstlist.Add(9); firstlist.Add(75); firstlist.Add(19); firstlist.Add(73); Console.WriteLine(\"Elements Present in List:\\n\"); int p = 0; // Displaying the elements of List foreach(int k in firstlist) { Console.Write(\"At Position {0}: \", p); Console.WriteLine(k); p++; } Console.WriteLine(\" \"); // removing the element at index 3 Console.WriteLine(\"Removing the element at index 3\\n\"); // taking negative index // it will give error as index // cannot be less than 0 firstlist.RemoveAt(-1); int p1 = 0; // Displaying the elements of List foreach(int n in firstlist) { Console.Write(\"At Position {0}: \", p1); Console.WriteLine(n); p1++; } }}",
"e": 28228,
"s": 26917,
"text": null
},
{
"code": null,
"e": 28243,
"s": 28228,
"text": "Runtime Error:"
},
{
"code": null,
"e": 28407,
"s": 28243,
"text": "Unhandled Exception:System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the size of the collection.Parameter name: index"
},
{
"code": null,
"e": 28415,
"s": 28407,
"text": "Output:"
},
{
"code": null,
"e": 28603,
"s": 28415,
"text": "Elements Present in List:\n\nAt Position 0: 17\nAt Position 1: 19\nAt Position 2: 21\nAt Position 3: 9\nAt Position 4: 75\nAt Position 5: 19\nAt Position 6: 73\n \nRemoving the element at index 3\n\n"
},
{
"code": null,
"e": 28614,
"s": 28603,
"text": "Reference:"
},
{
"code": null,
"e": 28725,
"s": 28614,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.removeat?view=netframework-4.7.2"
},
{
"code": null,
"e": 28754,
"s": 28725,
"text": "CSharp-Collections-Namespace"
},
{
"code": null,
"e": 28774,
"s": 28754,
"text": "CSharp-Generic-List"
},
{
"code": null,
"e": 28799,
"s": 28774,
"text": "CSharp-Generic-Namespace"
},
{
"code": null,
"e": 28813,
"s": 28799,
"text": "CSharp-method"
},
{
"code": null,
"e": 28816,
"s": 28813,
"text": "C#"
},
{
"code": null,
"e": 28914,
"s": 28816,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28923,
"s": 28914,
"text": "Comments"
},
{
"code": null,
"e": 28936,
"s": 28923,
"text": "Old Comments"
},
{
"code": null,
"e": 28959,
"s": 28936,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 28987,
"s": 28959,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 29033,
"s": 28987,
"text": "Difference between Ref and Out keywords in C#"
},
{
"code": null,
"e": 29048,
"s": 29033,
"text": "C# | Delegates"
},
{
"code": null,
"e": 29088,
"s": 29048,
"text": "Top 50 C# Interview Questions & Answers"
},
{
"code": null,
"e": 29119,
"s": 29088,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 29137,
"s": 29119,
"text": "C# | Constructors"
},
{
"code": null,
"e": 29160,
"s": 29137,
"text": "Extension Method in C#"
},
{
"code": null,
"e": 29182,
"s": 29160,
"text": "C# | Class and Object"
}
] |
Cyberpunk Style with Matplotlib. Futuristic neon glow for your next data... | by Dominik Haitz | Towards Data Science
|
Futuristic neon glow for your next data visualization.
Update 2020–03–29: There’s now a Python package to conveniently apply this style, see here. Install viapip install mplcyberpunk
Let’s make up some numbers, put them in a Pandas dataframe and plot them:
import pandas as pdimport matplotlib.pyplot as pltdf = pd.DataFrame({'A': [1, 3, 9, 5, 2, 1, 1], 'B': [4, 5, 5, 7, 9, 8, 6]})df.plot(marker='o')plt.show()
Not bad, but somewhat ordinary. Let’s customize it by using Seaborn’s dark style, as well as changing background and font colors:
plt.style.use("seaborn-dark")for param in ['figure.facecolor', 'axes.facecolor', 'savefig.facecolor']: plt.rcParams[param] = '#212946' # bluish dark greyfor param in ['text.color', 'axes.labelcolor', 'xtick.color', 'ytick.color']: plt.rcParams[param] = '0.9' # very light greyax.grid(color='#2A3459') # bluish dark grey, but slightly lighter than background
It looks more interesting now, but we need our colors to shine more against the dark background:
fig, ax = plt.subplots()colors = [ '#08F7FE', # teal/cyan '#FE53BB', # pink '#F5D300', # yellow '#00ff41', # matrix green]df.plot(marker='o', ax=ax, color=colors)
Now, how to get that neon look? To make it shine, we redraw the lines multiple times, with low alpha value and slighty increasing linewidth. The overlap creates the glow effect.
n_lines = 10diff_linewidth = 1.05alpha_value = 0.03for n in range(1, n_lines+1): df.plot(marker='o', linewidth=2+(diff_linewidth*n), alpha=alpha_value, legend=False, ax=ax, color=colors)
For some more fine tuning, we color the area below the line (via ax.fill_between) and adjust the axis limits.
Here’s the full code:
import pandas as pdimport matplotlib.pyplot as pltplt.style.use("dark_background")for param in ['text.color', 'axes.labelcolor', 'xtick.color', 'ytick.color']: plt.rcParams[param] = '0.9' # very light greyfor param in ['figure.facecolor', 'axes.facecolor', 'savefig.facecolor']: plt.rcParams[param] = '#212946' # bluish dark greycolors = [ '#08F7FE', # teal/cyan '#FE53BB', # pink '#F5D300', # yellow '#00ff41', # matrix green]df = pd.DataFrame({'A': [1, 3, 9, 5, 2, 1, 1], 'B': [4, 5, 5, 7, 9, 8, 6]})fig, ax = plt.subplots()df.plot(marker='o', color=colors, ax=ax)# Redraw the data with low alpha and slighty increased linewidth:n_shades = 10diff_linewidth = 1.05alpha_value = 0.3 / n_shadesfor n in range(1, n_shades+1): df.plot(marker='o', linewidth=2+(diff_linewidth*n), alpha=alpha_value, legend=False, ax=ax, color=colors)# Color the areas below the lines:for column, color in zip(df, colors): ax.fill_between(x=df.index, y1=df[column].values, y2=[0] * len(df), color=color, alpha=0.1)ax.grid(color='#2A3459')ax.set_xlim([ax.get_xlim()[0] - 0.2, ax.get_xlim()[1] + 0.2]) # to not have the markers cut offax.set_ylim(0)plt.show()
If this helps you or if you have constructive criticism, I’d be happy to hear about it! Please contact me via here or here. Thanks!
|
[
{
"code": null,
"e": 227,
"s": 172,
"text": "Futuristic neon glow for your next data visualization."
},
{
"code": null,
"e": 355,
"s": 227,
"text": "Update 2020–03–29: There’s now a Python package to conveniently apply this style, see here. Install viapip install mplcyberpunk"
},
{
"code": null,
"e": 429,
"s": 355,
"text": "Let’s make up some numbers, put them in a Pandas dataframe and plot them:"
},
{
"code": null,
"e": 602,
"s": 429,
"text": "import pandas as pdimport matplotlib.pyplot as pltdf = pd.DataFrame({'A': [1, 3, 9, 5, 2, 1, 1], 'B': [4, 5, 5, 7, 9, 8, 6]})df.plot(marker='o')plt.show()"
},
{
"code": null,
"e": 732,
"s": 602,
"text": "Not bad, but somewhat ordinary. Let’s customize it by using Seaborn’s dark style, as well as changing background and font colors:"
},
{
"code": null,
"e": 1099,
"s": 732,
"text": "plt.style.use(\"seaborn-dark\")for param in ['figure.facecolor', 'axes.facecolor', 'savefig.facecolor']: plt.rcParams[param] = '#212946' # bluish dark greyfor param in ['text.color', 'axes.labelcolor', 'xtick.color', 'ytick.color']: plt.rcParams[param] = '0.9' # very light greyax.grid(color='#2A3459') # bluish dark grey, but slightly lighter than background"
},
{
"code": null,
"e": 1196,
"s": 1099,
"text": "It looks more interesting now, but we need our colors to shine more against the dark background:"
},
{
"code": null,
"e": 1374,
"s": 1196,
"text": "fig, ax = plt.subplots()colors = [ '#08F7FE', # teal/cyan '#FE53BB', # pink '#F5D300', # yellow '#00ff41', # matrix green]df.plot(marker='o', ax=ax, color=colors)"
},
{
"code": null,
"e": 1552,
"s": 1374,
"text": "Now, how to get that neon look? To make it shine, we redraw the lines multiple times, with low alpha value and slighty increasing linewidth. The overlap creates the glow effect."
},
{
"code": null,
"e": 1797,
"s": 1552,
"text": "n_lines = 10diff_linewidth = 1.05alpha_value = 0.03for n in range(1, n_lines+1): df.plot(marker='o', linewidth=2+(diff_linewidth*n), alpha=alpha_value, legend=False, ax=ax, color=colors)"
},
{
"code": null,
"e": 1907,
"s": 1797,
"text": "For some more fine tuning, we color the area below the line (via ax.fill_between) and adjust the axis limits."
},
{
"code": null,
"e": 1929,
"s": 1907,
"text": "Here’s the full code:"
},
{
"code": null,
"e": 3245,
"s": 1929,
"text": "import pandas as pdimport matplotlib.pyplot as pltplt.style.use(\"dark_background\")for param in ['text.color', 'axes.labelcolor', 'xtick.color', 'ytick.color']: plt.rcParams[param] = '0.9' # very light greyfor param in ['figure.facecolor', 'axes.facecolor', 'savefig.facecolor']: plt.rcParams[param] = '#212946' # bluish dark greycolors = [ '#08F7FE', # teal/cyan '#FE53BB', # pink '#F5D300', # yellow '#00ff41', # matrix green]df = pd.DataFrame({'A': [1, 3, 9, 5, 2, 1, 1], 'B': [4, 5, 5, 7, 9, 8, 6]})fig, ax = plt.subplots()df.plot(marker='o', color=colors, ax=ax)# Redraw the data with low alpha and slighty increased linewidth:n_shades = 10diff_linewidth = 1.05alpha_value = 0.3 / n_shadesfor n in range(1, n_shades+1): df.plot(marker='o', linewidth=2+(diff_linewidth*n), alpha=alpha_value, legend=False, ax=ax, color=colors)# Color the areas below the lines:for column, color in zip(df, colors): ax.fill_between(x=df.index, y1=df[column].values, y2=[0] * len(df), color=color, alpha=0.1)ax.grid(color='#2A3459')ax.set_xlim([ax.get_xlim()[0] - 0.2, ax.get_xlim()[1] + 0.2]) # to not have the markers cut offax.set_ylim(0)plt.show()"
}
] |
Find the sum of medians of all odd length subarrays - GeeksforGeeks
|
14 Jan, 2022
Given an array arr[] of size N, the task is to find the sum of medians of all sub-array of odd-length.
Examples:
Input: arr[] = {4, 2, 5, 1}Output: 18Explanation : Sub-Arrays of odd length and their medians are :
[4] -> Median is 4
[4, 2, 5] -> Median is 4
[2] -> Median is 2
[2, 5, 1] -> Median is 2
[5] -> Median is 5
[1] -> Median is 1
Their sum = 4 + 4+ 2 + 2 + 5 +1 = 18
Input: arr[] = {1, 2}Output: 3
Pre-requisites: Median of Stream of Running Integers using STL
Naive Approach: Generate each and every sub-array. If the length of the sub-array is odd, then sort the sub-array and return the middle element.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find sum of medians// of all odd-length subarraysint solve(vector<int> arr){ int ans = 0; int n = arr.size(); // Loop to calculate the sum for(int i = 0; i < n; i++) { vector<int> new_arr; for(int j = i; j < n; j++) { new_arr.push_back(arr[j]); // Odd length subarray if ((new_arr.size() % 2) == 1) { sort(new_arr.begin(), new_arr.end()); int mid = new_arr.size() / 2; ans += new_arr[mid]; } } } return ans;} // Driver Codeint main(){ vector<int> arr = { 4, 2, 5, 1 }; cout << solve(arr);} // This code is contributed by Samim Hossain Mondal.
// Java program for the above approachimport java.util.*; class GFG { // Function to find sum of medians // of all odd-length subarrays static int solve(int[] arr) { int ans = 0; int n = arr.length; // Loop to calculate the sum for (int i = 0; i < n; i++) { List<Integer> new_arr = new LinkedList<Integer>(); for (int j = i; j < n; j++) { new_arr.add(arr[j]); // Odd length subarray if ((new_arr.size() % 2) == 1) { Collections.sort(new_arr); int mid = new_arr.size() / 2; ans += new_arr.get(mid); } } } return ans; } // Driver Code public static void main(String[] args) { int[] arr = { 4, 2, 5, 1 }; System.out.println(solve(arr)); }}// This code is contributed by 29AjayKumar
# Python program for the above approach # Function to find sum of medians# of all odd-length subarraysdef solve(arr): ans = 0 n = len(arr) # Loop to calculate the sum for i in range(n): new_arr = [] for j in range(i, n, 1): new_arr.append(arr[j]) # Odd length subarray if (len(new_arr)) % 2 == 1: new_arr.sort() mid = len(new_arr)//2 ans += new_arr[mid] return (ans) # Driver Codeif __name__ == "__main__": arr = [4, 2, 5, 1] print(solve(arr))
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find sum of medians // of all odd-length subarrays static int solve(int[] arr) { int ans = 0; int n = arr.Length; // Loop to calculate the sum for (int i = 0; i < n; i++) { List<int> new_arr = new List<int>(); for (int j = i; j < n; j++) { new_arr.Add(arr[j]); // Odd length subarray if ((new_arr.Count % 2) == 1) { new_arr.Sort(); int mid = new_arr.Count / 2; ans += new_arr[mid]; } } } return ans; } // Driver Code public static void Main() { int[] arr = { 4, 2, 5, 1 }; Console.Write(solve(arr)); }} // This code is contributed by Saurabh Jaiswal
<script> // javascript program for the above approach // Function to find sum of medians // of all odd-length subarrays function solve(arr) { var ans = 0; var n = arr.length; // Loop to calculate the sum for (var i = 0; i < n; i++) { var new_arr= new Array(); for (var j = i; j < n; j++) { new_arr.push(arr[j]); // Odd length subarray if ((new_arr.length % 2) == 1) { new_arr.sort(); var mid = Math.floor(new_arr.length / 2); // document.write(mid); ans += new_arr[mid]; } } } return ans; } // Driver Codevar arr = [ 4, 2, 5, 1 ];document.write(solve(arr)); // This code is contributed by shikhasingrajput</script>
18
Time Complexity: O(N3 * Log(N)) Auxiliary Space: O(N)
Note: Instead of sorting array each time, which costs (N*logN), insertion sort can be applied. But still, overall Time Complexity will be O(N3).
Efficient Approach: The median of the sorted array is the value separating the higher half from the lower half in the array. For finding out the median, we only need the middle element, rather than the entire sorted array. The approach of Median of Stream of Running Integers can be applied over here. Follow the steps mentioned below
Use max and min heaps to calculate the running median.Traverse each and every element in the array.While creating a new subarray, add an element into the heaps and return median if the size is odd else return 0.Max_heap is used to store lower half elements such that the maximum element is at the top and min_heap is used to store higher half elements such that the minimum element is at the top.The difference between both the heaps should not be greater than one, and one extra element is always placed in max_heap.
Use max and min heaps to calculate the running median.
Traverse each and every element in the array.
While creating a new subarray, add an element into the heaps and return median if the size is odd else return 0.
Max_heap is used to store lower half elements such that the maximum element is at the top and min_heap is used to store higher half elements such that the minimum element is at the top.
The difference between both the heaps should not be greater than one, and one extra element is always placed in max_heap.
Note: Here max_heap is implemented using min_heap, by just negating the values so that the maximum negative element can be popped.
Below is the implementation of the above approach:
Python3
# Python program for the above approachfrom heapq import heappush as push, heappop as pop # Find the sum of medians of odd-length# subarrays class find_median(): # Constructor to declare two heaps def __init__(self): # Store lower half elements such that # maximum element is at top self.max_heap = [] # Store higher half elements such that # minimum element is at top self.min_heap = [] def add(self, val): # len(max_heap) == 0 or curr_element # smaller than max_heap top if (len(self.max_heap) == 0 or self.max_heap[0] > val): push(self.max_heap, -val) else: push(self.min_heap, val) # If size of max_heap + 1 greater # than min_heap if (len(self.max_heap)+1 > len(self.min_heap)): val = pop(self.max_heap) push(self.min_heap, -val) # If size of min_heap # greater than max_heap if (len(self.min_heap) > len(self.max_heap)): val = pop(self.min_heap) push(self.max_heap, -val) # Finally if sum of sizes is odd, # return median if (len(self.min_heap) + len(self.max_heap)) % 2 == 1: return (-self.max_heap[0]) # Else return 0 else: return 0 # Function to calculate the sum# of all odd length subarraysdef solve(arr): ans = 0 # Size of the array n = len(arr) for i in range(n): # Create an object # of class find_median obj = find_median() for j in range(i, n, 1): # Add value to the heaps # using object val = obj.add(arr[j]) ans += val return (ans) # Driver Codeif __name__ == "__main__": arr = [4, 2, 5, 1] print(solve(arr))
18
Time Complexity: O(N2 * Log(N)) Auxiliary Space: O(N)
29AjayKumar
_saurabh_jaiswal
samim2000
sumitgumber28
shikhasingrajput
avtarkumar719
nnr223442
median-finding
subarray
Arrays
Heap
Mathematical
Sorting
Arrays
Mathematical
Sorting
Heap
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Next Greater Element
Find Second largest element in an array
Window Sliding Technique
k largest(or smallest) elements in an array
Count pairs with given sum
HeapSort
Binary Heap
Huffman Coding | Greedy Algo-3
k largest(or smallest) elements in an array
Building Heap from Array
|
[
{
"code": null,
"e": 24553,
"s": 24525,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 24656,
"s": 24553,
"text": "Given an array arr[] of size N, the task is to find the sum of medians of all sub-array of odd-length."
},
{
"code": null,
"e": 24666,
"s": 24656,
"text": "Examples:"
},
{
"code": null,
"e": 24766,
"s": 24666,
"text": "Input: arr[] = {4, 2, 5, 1}Output: 18Explanation : Sub-Arrays of odd length and their medians are :"
},
{
"code": null,
"e": 24786,
"s": 24766,
"text": "[4] -> Median is 4"
},
{
"code": null,
"e": 24812,
"s": 24786,
"text": "[4, 2, 5] -> Median is 4"
},
{
"code": null,
"e": 24832,
"s": 24812,
"text": "[2] -> Median is 2"
},
{
"code": null,
"e": 24858,
"s": 24832,
"text": "[2, 5, 1] -> Median is 2"
},
{
"code": null,
"e": 24878,
"s": 24858,
"text": "[5] -> Median is 5"
},
{
"code": null,
"e": 24898,
"s": 24878,
"text": "[1] -> Median is 1"
},
{
"code": null,
"e": 24935,
"s": 24898,
"text": "Their sum = 4 + 4+ 2 + 2 + 5 +1 = 18"
},
{
"code": null,
"e": 24966,
"s": 24935,
"text": "Input: arr[] = {1, 2}Output: 3"
},
{
"code": null,
"e": 25029,
"s": 24966,
"text": "Pre-requisites: Median of Stream of Running Integers using STL"
},
{
"code": null,
"e": 25174,
"s": 25029,
"text": "Naive Approach: Generate each and every sub-array. If the length of the sub-array is odd, then sort the sub-array and return the middle element."
},
{
"code": null,
"e": 25226,
"s": 25174,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25230,
"s": 25226,
"text": "C++"
},
{
"code": null,
"e": 25235,
"s": 25230,
"text": "Java"
},
{
"code": null,
"e": 25243,
"s": 25235,
"text": "Python3"
},
{
"code": null,
"e": 25246,
"s": 25243,
"text": "C#"
},
{
"code": null,
"e": 25257,
"s": 25246,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find sum of medians// of all odd-length subarraysint solve(vector<int> arr){ int ans = 0; int n = arr.size(); // Loop to calculate the sum for(int i = 0; i < n; i++) { vector<int> new_arr; for(int j = i; j < n; j++) { new_arr.push_back(arr[j]); // Odd length subarray if ((new_arr.size() % 2) == 1) { sort(new_arr.begin(), new_arr.end()); int mid = new_arr.size() / 2; ans += new_arr[mid]; } } } return ans;} // Driver Codeint main(){ vector<int> arr = { 4, 2, 5, 1 }; cout << solve(arr);} // This code is contributed by Samim Hossain Mondal.",
"e": 26066,
"s": 25257,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*; class GFG { // Function to find sum of medians // of all odd-length subarrays static int solve(int[] arr) { int ans = 0; int n = arr.length; // Loop to calculate the sum for (int i = 0; i < n; i++) { List<Integer> new_arr = new LinkedList<Integer>(); for (int j = i; j < n; j++) { new_arr.add(arr[j]); // Odd length subarray if ((new_arr.size() % 2) == 1) { Collections.sort(new_arr); int mid = new_arr.size() / 2; ans += new_arr.get(mid); } } } return ans; } // Driver Code public static void main(String[] args) { int[] arr = { 4, 2, 5, 1 }; System.out.println(solve(arr)); }}// This code is contributed by 29AjayKumar",
"e": 26975,
"s": 26066,
"text": null
},
{
"code": "# Python program for the above approach # Function to find sum of medians# of all odd-length subarraysdef solve(arr): ans = 0 n = len(arr) # Loop to calculate the sum for i in range(n): new_arr = [] for j in range(i, n, 1): new_arr.append(arr[j]) # Odd length subarray if (len(new_arr)) % 2 == 1: new_arr.sort() mid = len(new_arr)//2 ans += new_arr[mid] return (ans) # Driver Codeif __name__ == \"__main__\": arr = [4, 2, 5, 1] print(solve(arr)) ",
"e": 27598,
"s": 26975,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find sum of medians // of all odd-length subarrays static int solve(int[] arr) { int ans = 0; int n = arr.Length; // Loop to calculate the sum for (int i = 0; i < n; i++) { List<int> new_arr = new List<int>(); for (int j = i; j < n; j++) { new_arr.Add(arr[j]); // Odd length subarray if ((new_arr.Count % 2) == 1) { new_arr.Sort(); int mid = new_arr.Count / 2; ans += new_arr[mid]; } } } return ans; } // Driver Code public static void Main() { int[] arr = { 4, 2, 5, 1 }; Console.Write(solve(arr)); }} // This code is contributed by Saurabh Jaiswal",
"e": 28361,
"s": 27598,
"text": null
},
{
"code": "<script> // javascript program for the above approach // Function to find sum of medians // of all odd-length subarrays function solve(arr) { var ans = 0; var n = arr.length; // Loop to calculate the sum for (var i = 0; i < n; i++) { var new_arr= new Array(); for (var j = i; j < n; j++) { new_arr.push(arr[j]); // Odd length subarray if ((new_arr.length % 2) == 1) { new_arr.sort(); var mid = Math.floor(new_arr.length / 2); // document.write(mid); ans += new_arr[mid]; } } } return ans; } // Driver Codevar arr = [ 4, 2, 5, 1 ];document.write(solve(arr)); // This code is contributed by shikhasingrajput</script>",
"e": 29226,
"s": 28361,
"text": null
},
{
"code": null,
"e": 29229,
"s": 29226,
"text": "18"
},
{
"code": null,
"e": 29284,
"s": 29229,
"text": "Time Complexity: O(N3 * Log(N)) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 29429,
"s": 29284,
"text": "Note: Instead of sorting array each time, which costs (N*logN), insertion sort can be applied. But still, overall Time Complexity will be O(N3)."
},
{
"code": null,
"e": 29765,
"s": 29429,
"text": "Efficient Approach: The median of the sorted array is the value separating the higher half from the lower half in the array. For finding out the median, we only need the middle element, rather than the entire sorted array. The approach of Median of Stream of Running Integers can be applied over here. Follow the steps mentioned below "
},
{
"code": null,
"e": 30283,
"s": 29765,
"text": "Use max and min heaps to calculate the running median.Traverse each and every element in the array.While creating a new subarray, add an element into the heaps and return median if the size is odd else return 0.Max_heap is used to store lower half elements such that the maximum element is at the top and min_heap is used to store higher half elements such that the minimum element is at the top.The difference between both the heaps should not be greater than one, and one extra element is always placed in max_heap."
},
{
"code": null,
"e": 30338,
"s": 30283,
"text": "Use max and min heaps to calculate the running median."
},
{
"code": null,
"e": 30384,
"s": 30338,
"text": "Traverse each and every element in the array."
},
{
"code": null,
"e": 30497,
"s": 30384,
"text": "While creating a new subarray, add an element into the heaps and return median if the size is odd else return 0."
},
{
"code": null,
"e": 30683,
"s": 30497,
"text": "Max_heap is used to store lower half elements such that the maximum element is at the top and min_heap is used to store higher half elements such that the minimum element is at the top."
},
{
"code": null,
"e": 30805,
"s": 30683,
"text": "The difference between both the heaps should not be greater than one, and one extra element is always placed in max_heap."
},
{
"code": null,
"e": 30936,
"s": 30805,
"text": "Note: Here max_heap is implemented using min_heap, by just negating the values so that the maximum negative element can be popped."
},
{
"code": null,
"e": 30989,
"s": 30936,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 30997,
"s": 30989,
"text": "Python3"
},
{
"code": "# Python program for the above approachfrom heapq import heappush as push, heappop as pop # Find the sum of medians of odd-length# subarrays class find_median(): # Constructor to declare two heaps def __init__(self): # Store lower half elements such that # maximum element is at top self.max_heap = [] # Store higher half elements such that # minimum element is at top self.min_heap = [] def add(self, val): # len(max_heap) == 0 or curr_element # smaller than max_heap top if (len(self.max_heap) == 0 or self.max_heap[0] > val): push(self.max_heap, -val) else: push(self.min_heap, val) # If size of max_heap + 1 greater # than min_heap if (len(self.max_heap)+1 > len(self.min_heap)): val = pop(self.max_heap) push(self.min_heap, -val) # If size of min_heap # greater than max_heap if (len(self.min_heap) > len(self.max_heap)): val = pop(self.min_heap) push(self.max_heap, -val) # Finally if sum of sizes is odd, # return median if (len(self.min_heap) + len(self.max_heap)) % 2 == 1: return (-self.max_heap[0]) # Else return 0 else: return 0 # Function to calculate the sum# of all odd length subarraysdef solve(arr): ans = 0 # Size of the array n = len(arr) for i in range(n): # Create an object # of class find_median obj = find_median() for j in range(i, n, 1): # Add value to the heaps # using object val = obj.add(arr[j]) ans += val return (ans) # Driver Codeif __name__ == \"__main__\": arr = [4, 2, 5, 1] print(solve(arr))",
"e": 32848,
"s": 30997,
"text": null
},
{
"code": null,
"e": 32851,
"s": 32848,
"text": "18"
},
{
"code": null,
"e": 32906,
"s": 32851,
"text": "Time Complexity: O(N2 * Log(N)) Auxiliary Space: O(N)"
},
{
"code": null,
"e": 32918,
"s": 32906,
"text": "29AjayKumar"
},
{
"code": null,
"e": 32935,
"s": 32918,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 32945,
"s": 32935,
"text": "samim2000"
},
{
"code": null,
"e": 32959,
"s": 32945,
"text": "sumitgumber28"
},
{
"code": null,
"e": 32976,
"s": 32959,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 32990,
"s": 32976,
"text": "avtarkumar719"
},
{
"code": null,
"e": 33000,
"s": 32990,
"text": "nnr223442"
},
{
"code": null,
"e": 33015,
"s": 33000,
"text": "median-finding"
},
{
"code": null,
"e": 33024,
"s": 33015,
"text": "subarray"
},
{
"code": null,
"e": 33031,
"s": 33024,
"text": "Arrays"
},
{
"code": null,
"e": 33036,
"s": 33031,
"text": "Heap"
},
{
"code": null,
"e": 33049,
"s": 33036,
"text": "Mathematical"
},
{
"code": null,
"e": 33057,
"s": 33049,
"text": "Sorting"
},
{
"code": null,
"e": 33064,
"s": 33057,
"text": "Arrays"
},
{
"code": null,
"e": 33077,
"s": 33064,
"text": "Mathematical"
},
{
"code": null,
"e": 33085,
"s": 33077,
"text": "Sorting"
},
{
"code": null,
"e": 33090,
"s": 33085,
"text": "Heap"
},
{
"code": null,
"e": 33188,
"s": 33090,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33197,
"s": 33188,
"text": "Comments"
},
{
"code": null,
"e": 33210,
"s": 33197,
"text": "Old Comments"
},
{
"code": null,
"e": 33231,
"s": 33210,
"text": "Next Greater Element"
},
{
"code": null,
"e": 33271,
"s": 33231,
"text": "Find Second largest element in an array"
},
{
"code": null,
"e": 33296,
"s": 33271,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 33340,
"s": 33296,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 33367,
"s": 33340,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 33376,
"s": 33367,
"text": "HeapSort"
},
{
"code": null,
"e": 33388,
"s": 33376,
"text": "Binary Heap"
},
{
"code": null,
"e": 33419,
"s": 33388,
"text": "Huffman Coding | Greedy Algo-3"
},
{
"code": null,
"e": 33463,
"s": 33419,
"text": "k largest(or smallest) elements in an array"
}
] |
Image Manipulation Using Quadtrees
|
09 Feb, 2018
Quadtrees are an effective method to store and locate data of points in a two-dimensional plane. Another effective use of quadtrees is in the field of image manipulation.
Unlike in storage of points, in image manipulation we get a complete quadtree with the leaf nodes consisting of individual pixels of the image. Due to this, we can utilize an array to store the nodes of the tree. This leads to less memory needed (compared to linked representation) for processing.
The lowest level of the quadtree would contain N nodes equivalent to the number of pixels in the image. The next level would contain N / 4 nodes.Thus, the total number of nodes necessary can be found by: N + N / 4 + N / 16 + ... + 1.To get an upperbound we can use sum of geometric progression to infinityNodes = N / (1 – 1 / 4) = 4 / 3 * NThis is the size of the array necessary.Thus, the amount of memory needed is O(N)
class Point(object): def __init__(self, x, y): self.x = x self.y = yclass Pixel(object): def __init__(self, color = [0, 0, 0], topLeft = Point(0, 0), bottomRight = Point(0, 0)): self.R = color[0] self.G = color[1] self.B = color[2] self.topLeft = topLeft self.bottomRight = bottomRight
The above code in Python shown demonstrates the class definition of a pixel.
InsertionUnlike in a classic quadtree, for image manipulation, we can insert all the nodes in O(N) time complexity.First, we insert all the leaf nodes directly into the last N positions of the array. The following code snippet demonstrates this:
# Store leaves into arraycount = 0for i in range(image.size[0] - 1, 0, -2): for j in range(image.size[1] - 1, 0, -2): self.tree[self.size - 1 - 4 * count] = Pixel(self.image[i, j], Point(i, j), Point(i, j)) self.tree[self.size - 2 - 4 * count] = Pixel(self.image[i, j - 1], Point(i, j - 1), Point(i, j - 1)) self.tree[self.size - 3 - 4 * count] = Pixel(self.image[i - 1, j], Point(i - 1, j), Point(i - 1, j)) self.tree[self.size - 4 - 4 * count] = Pixel(self.image[i - 1, j - 1], Point(i - 1, j - 1), Point(i - 1, j - 1)) count += 1
In the above snippet, self.tree is the array of nodes, self.size is the total size of the array, and self.image is the pixels of the image, count is used to traverse the tree.
For nodes that aren’t leaves, the R, G, B values are calculated by taking the average of the values of the children.The topLeft and bottomRight are obtained by taking the maximum and minimum values of the x and y of the children.
# Calculate and create parent nodesfor i in range(self.size - 4 * count - 1, -1, -1): self.tree[i] = Pixel( [(self.tree[4 * i + 1].R + self.tree[4 * i + 2].R + self.tree[4 * i + 3].R + self.tree[4 * i + 4].R) / 4, (self.tree[4 * i + 1].G + self.tree[4 * i + 2].G + self.tree[4 * i + 3].G + self.tree[4 * i + 4].G) / 4, (self.tree[4 * i + 1].B + self.tree[4 * i + 2].B + self.tree[4 * i + 3].B + self.tree[4 * i + 4].B) / 4], self.tree[4 * i + 1].topLeft, self.tree[4 * i + 4].bottomRight)
Here we can see, we take the values of R, G, B of the four children, and we divide by 4, thus getting the average.
Calculation of these values happen in O(1) time assuming values of the children are known. Since we are moving in reverse order, the values of the children are computed before that of parents.Thus insertion occurs in O(N).
Application in Image ManipulationLet us say we wish to convert a high quality image to a thumbnail. Once we have created a quadtree for the image, by selecting a height of the quadtree we can select the quality of the image we obtain. If the height is equal to the height of the quadtree, then we retain the original image. At lower heights, we obtain images of lesser quality.
In case we do not wish to reduce the quality of the image, we can try to compress the image by what is known as “pruning”. In this, leafs with colours close to that of their parents are removed. This is continuously done until no further leaves can be removed. The lowest level is then taken to form the image, using only leaf nodes. While this does not reduce the quality of the image drastically, it can lead to a small compression of the image.
Complete Code:
from PIL import Imageimport mathclass Point(object): def __init__(self, x, y): self.x = x self.y = y class Pixel(object): def __init__(self, color = [0, 0, 0], topLeft = Point(0, 0), bottomRight = Point(0, 0)): self.R = color[0] self.G = color[1] self.B = color[2] self.topLeft = topLeft self.bottomRight = bottomRight class quadtree(): def __init__(self, image): # Total number of nodes of tree self.size = 0 # Store image pixelmap self.image = image.load() # Array of nodes self.tree = [] self.x = image.size[0] self.y = image.size[1] # Total number of leaf nodes size = image.size[0] * image.size[1] # Count number of nodes while(size >= 1): self.size += size size /= 4 size = image.size[0] * image.size[1] # Initialize array elements for i in range(0, self.size): self.tree.append(Pixel()) # Store leaves into array count = 0 for i in range(image.size[0] - 1, 0, -2): for j in range(image.size[1] - 1, 0, -2): self.tree[self.size - 1 - 4 * count] = Pixel(self.image[i, j], Point(i, j), Point(i, j)) self.tree[self.size - 2 - 4 * count] = Pixel(self.image[i, j - 1], Point(i, j - 1), Point(i, j - 1)) self.tree[self.size - 3 - 4 * count] = Pixel(self.image[i - 1, j], Point(i - 1, j), Point(i - 1, j)) self.tree[self.size - 4 - 4 * count] = Pixel(self.image[i - 1, j - 1], Point(i - 1, j - 1), Point(i - 1, j - 1)) count += 1 # Calculate and create parent nodes for i in range(self.size - 4 * count - 1, -1, -1): self.tree[i] = Pixel( [(self.tree[4 * i + 1].R + self.tree[4 * i + 2].R + self.tree[4 * i + 3].R + self.tree[4 * i + 4].R) / 4, (self.tree[4 * i + 1].G + self.tree[4 * i + 2].G + self.tree[4 * i + 3].G + self.tree[4 * i + 4].G) / 4, (self.tree[4 * i + 1].B + self.tree[4 * i + 2].B + self.tree[4 * i + 3].B + self.tree[4 * i + 4].B) / 4], self.tree[4 * i + 1].topLeft, self.tree[4 * i + 4].bottomRight) def disp(self, level): start = 0 # Calculate position of starting node of height for i in range(0, level): start = 4 * start + 1 # Invalid height given if (start > self.size): return # Create a new image img = Image.new("RGB", (self.x, self.y), "black") pixels = img.load() # Move from starting to last node on given height for i in self.tree[start : 4 * start]: x1 = i.topLeft.x y1 = i.topLeft.y x2 = i.bottomRight.x y2 = i.bottomRight.y for x in range(x1, x2 + 1): for y in range(y1, y2 + 1): # Set colour pixels[x, y] = (i.R, i.G, i.B) # Display image img.show()
This article is contributed by Aditya Kamath. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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.
Image-Processing
Advanced Data Structure
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Feb, 2018"
},
{
"code": null,
"e": 223,
"s": 52,
"text": "Quadtrees are an effective method to store and locate data of points in a two-dimensional plane. Another effective use of quadtrees is in the field of image manipulation."
},
{
"code": null,
"e": 521,
"s": 223,
"text": "Unlike in storage of points, in image manipulation we get a complete quadtree with the leaf nodes consisting of individual pixels of the image. Due to this, we can utilize an array to store the nodes of the tree. This leads to less memory needed (compared to linked representation) for processing."
},
{
"code": null,
"e": 943,
"s": 521,
"text": "The lowest level of the quadtree would contain N nodes equivalent to the number of pixels in the image. The next level would contain N / 4 nodes.Thus, the total number of nodes necessary can be found by: N + N / 4 + N / 16 + ... + 1.To get an upperbound we can use sum of geometric progression to infinityNodes = N / (1 – 1 / 4) = 4 / 3 * NThis is the size of the array necessary.Thus, the amount of memory needed is O(N)"
},
{
"code": "class Point(object): def __init__(self, x, y): self.x = x self.y = yclass Pixel(object): def __init__(self, color = [0, 0, 0], topLeft = Point(0, 0), bottomRight = Point(0, 0)): self.R = color[0] self.G = color[1] self.B = color[2] self.topLeft = topLeft self.bottomRight = bottomRight",
"e": 1308,
"s": 943,
"text": null
},
{
"code": null,
"e": 1385,
"s": 1308,
"text": "The above code in Python shown demonstrates the class definition of a pixel."
},
{
"code": null,
"e": 1631,
"s": 1385,
"text": "InsertionUnlike in a classic quadtree, for image manipulation, we can insert all the nodes in O(N) time complexity.First, we insert all the leaf nodes directly into the last N positions of the array. The following code snippet demonstrates this:"
},
{
"code": "# Store leaves into arraycount = 0for i in range(image.size[0] - 1, 0, -2): for j in range(image.size[1] - 1, 0, -2): self.tree[self.size - 1 - 4 * count] = Pixel(self.image[i, j], Point(i, j), Point(i, j)) self.tree[self.size - 2 - 4 * count] = Pixel(self.image[i, j - 1], Point(i, j - 1), Point(i, j - 1)) self.tree[self.size - 3 - 4 * count] = Pixel(self.image[i - 1, j], Point(i - 1, j), Point(i - 1, j)) self.tree[self.size - 4 - 4 * count] = Pixel(self.image[i - 1, j - 1], Point(i - 1, j - 1), Point(i - 1, j - 1)) count += 1",
"e": 2329,
"s": 1631,
"text": null
},
{
"code": null,
"e": 2505,
"s": 2329,
"text": "In the above snippet, self.tree is the array of nodes, self.size is the total size of the array, and self.image is the pixels of the image, count is used to traverse the tree."
},
{
"code": null,
"e": 2735,
"s": 2505,
"text": "For nodes that aren’t leaves, the R, G, B values are calculated by taking the average of the values of the children.The topLeft and bottomRight are obtained by taking the maximum and minimum values of the x and y of the children."
},
{
"code": "# Calculate and create parent nodesfor i in range(self.size - 4 * count - 1, -1, -1): self.tree[i] = Pixel( [(self.tree[4 * i + 1].R + self.tree[4 * i + 2].R + self.tree[4 * i + 3].R + self.tree[4 * i + 4].R) / 4, (self.tree[4 * i + 1].G + self.tree[4 * i + 2].G + self.tree[4 * i + 3].G + self.tree[4 * i + 4].G) / 4, (self.tree[4 * i + 1].B + self.tree[4 * i + 2].B + self.tree[4 * i + 3].B + self.tree[4 * i + 4].B) / 4], self.tree[4 * i + 1].topLeft, self.tree[4 * i + 4].bottomRight)",
"e": 3264,
"s": 2735,
"text": null
},
{
"code": null,
"e": 3379,
"s": 3264,
"text": "Here we can see, we take the values of R, G, B of the four children, and we divide by 4, thus getting the average."
},
{
"code": null,
"e": 3602,
"s": 3379,
"text": "Calculation of these values happen in O(1) time assuming values of the children are known. Since we are moving in reverse order, the values of the children are computed before that of parents.Thus insertion occurs in O(N)."
},
{
"code": null,
"e": 3980,
"s": 3602,
"text": "Application in Image ManipulationLet us say we wish to convert a high quality image to a thumbnail. Once we have created a quadtree for the image, by selecting a height of the quadtree we can select the quality of the image we obtain. If the height is equal to the height of the quadtree, then we retain the original image. At lower heights, we obtain images of lesser quality."
},
{
"code": null,
"e": 4428,
"s": 3980,
"text": "In case we do not wish to reduce the quality of the image, we can try to compress the image by what is known as “pruning”. In this, leafs with colours close to that of their parents are removed. This is continuously done until no further leaves can be removed. The lowest level is then taken to form the image, using only leaf nodes. While this does not reduce the quality of the image drastically, it can lead to a small compression of the image."
},
{
"code": null,
"e": 4443,
"s": 4428,
"text": "Complete Code:"
},
{
"code": "from PIL import Imageimport mathclass Point(object): def __init__(self, x, y): self.x = x self.y = y class Pixel(object): def __init__(self, color = [0, 0, 0], topLeft = Point(0, 0), bottomRight = Point(0, 0)): self.R = color[0] self.G = color[1] self.B = color[2] self.topLeft = topLeft self.bottomRight = bottomRight class quadtree(): def __init__(self, image): # Total number of nodes of tree self.size = 0 # Store image pixelmap self.image = image.load() # Array of nodes self.tree = [] self.x = image.size[0] self.y = image.size[1] # Total number of leaf nodes size = image.size[0] * image.size[1] # Count number of nodes while(size >= 1): self.size += size size /= 4 size = image.size[0] * image.size[1] # Initialize array elements for i in range(0, self.size): self.tree.append(Pixel()) # Store leaves into array count = 0 for i in range(image.size[0] - 1, 0, -2): for j in range(image.size[1] - 1, 0, -2): self.tree[self.size - 1 - 4 * count] = Pixel(self.image[i, j], Point(i, j), Point(i, j)) self.tree[self.size - 2 - 4 * count] = Pixel(self.image[i, j - 1], Point(i, j - 1), Point(i, j - 1)) self.tree[self.size - 3 - 4 * count] = Pixel(self.image[i - 1, j], Point(i - 1, j), Point(i - 1, j)) self.tree[self.size - 4 - 4 * count] = Pixel(self.image[i - 1, j - 1], Point(i - 1, j - 1), Point(i - 1, j - 1)) count += 1 # Calculate and create parent nodes for i in range(self.size - 4 * count - 1, -1, -1): self.tree[i] = Pixel( [(self.tree[4 * i + 1].R + self.tree[4 * i + 2].R + self.tree[4 * i + 3].R + self.tree[4 * i + 4].R) / 4, (self.tree[4 * i + 1].G + self.tree[4 * i + 2].G + self.tree[4 * i + 3].G + self.tree[4 * i + 4].G) / 4, (self.tree[4 * i + 1].B + self.tree[4 * i + 2].B + self.tree[4 * i + 3].B + self.tree[4 * i + 4].B) / 4], self.tree[4 * i + 1].topLeft, self.tree[4 * i + 4].bottomRight) def disp(self, level): start = 0 # Calculate position of starting node of height for i in range(0, level): start = 4 * start + 1 # Invalid height given if (start > self.size): return # Create a new image img = Image.new(\"RGB\", (self.x, self.y), \"black\") pixels = img.load() # Move from starting to last node on given height for i in self.tree[start : 4 * start]: x1 = i.topLeft.x y1 = i.topLeft.y x2 = i.bottomRight.x y2 = i.bottomRight.y for x in range(x1, x2 + 1): for y in range(y1, y2 + 1): # Set colour pixels[x, y] = (i.R, i.G, i.B) # Display image img.show()",
"e": 7699,
"s": 4443,
"text": null
},
{
"code": null,
"e": 8000,
"s": 7699,
"text": "This article is contributed by Aditya Kamath. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 8125,
"s": 8000,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 8142,
"s": 8125,
"text": "Image-Processing"
},
{
"code": null,
"e": 8166,
"s": 8142,
"text": "Advanced Data Structure"
}
] |
CSS | fill-opacity Property
|
28 Nov, 2019
The fill-opacity property is used to set the opacity of the paint server that is applied to the shape.
Syntax:
fill-opacity: [0-1] | <percentage>
Property Values:
Value between 0 and 1: It is used to set the opacity of the fill-in decimal values. The value 0 means that the fill is completely transparent and invisible. The value 1 means that the fill is fully opaque and visible. A decimal value between these two values would give a semi-transparent fill.Example:<!DOCTYPE html><html><head> <title> CSS | fill-opacity </title> <style> .opacity1 { /* completely visible fill */ fill-opacity: 1.0; fill: green; } .opacity2 { fill-opacity: 0.5; fill: green; } .opacity3 { fill-opacity: 0.25; fill: green; } .opacity4 { /* completely transparent fill */ fill-opacity: 0; fill: green; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | fill-opacity </b> <div class="container"> <svg height="250px" width="500px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <circle class="opacity1" cx="100" cy="100" r="50"/> <circle class="opacity2" cx="250" cy="100" r="50"/> <circle class="opacity3" cx="400" cy="100" r="50"/> <circle class="opacity4" cx="400" cy="100" r="50"/> </svg> </div></body></html>Output:
Example:
<!DOCTYPE html><html><head> <title> CSS | fill-opacity </title> <style> .opacity1 { /* completely visible fill */ fill-opacity: 1.0; fill: green; } .opacity2 { fill-opacity: 0.5; fill: green; } .opacity3 { fill-opacity: 0.25; fill: green; } .opacity4 { /* completely transparent fill */ fill-opacity: 0; fill: green; } </style></head><body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | fill-opacity </b> <div class="container"> <svg height="250px" width="500px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <circle class="opacity1" cx="100" cy="100" r="50"/> <circle class="opacity2" cx="250" cy="100" r="50"/> <circle class="opacity3" cx="400" cy="100" r="50"/> <circle class="opacity4" cx="400" cy="100" r="50"/> </svg> </div></body></html>
Output:
percentage: It is used to set the opacity of the fill in percentage values. A value of 0% means that the fill is completely transparent and invisible. A value of 100% means that the fill is fully opaque and visible. A percentage value between these two values would give a semi-transparent fill.Example:<!DOCTYPE html><html><head> <title> CSS | fill-opacity </title> <style> .opacity1 { /* completely visible fill */ fill-opacity: 100%; fill: green; } .opacity2 { fill-opacity: 50%; fill: green; } .opacity3 { fill-opacity: 25%; fill: green; } .opacity4 { /* completely transparent fill */ fill-opacity: 0%; fill: green; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | fill-opacity </b> <div class="container"> <svg height="250px" width="500px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect class="opacity1" x="25" y="10" height="150" width="100"/> <rect class="opacity2" x="175" y="10" height="150" width="100"/> <rect class="opacity3" x="325" y="10" height="150" width="100"/> <rect class="opacity4" x="325" y="10" height="150" width="100"/> </svg> </div></body></html>Output:
Example:
<!DOCTYPE html><html><head> <title> CSS | fill-opacity </title> <style> .opacity1 { /* completely visible fill */ fill-opacity: 100%; fill: green; } .opacity2 { fill-opacity: 50%; fill: green; } .opacity3 { fill-opacity: 25%; fill: green; } .opacity4 { /* completely transparent fill */ fill-opacity: 0%; fill: green; } </style></head> <body> <h1 style="color: green"> GeeksforGeeks </h1> <b> CSS | fill-opacity </b> <div class="container"> <svg height="250px" width="500px" xmlns="http://www.w3.org/2000/svg" version="1.1"> <rect class="opacity1" x="25" y="10" height="150" width="100"/> <rect class="opacity2" x="175" y="10" height="150" width="100"/> <rect class="opacity3" x="325" y="10" height="150" width="100"/> <rect class="opacity4" x="325" y="10" height="150" width="100"/> </svg> </div></body></html>
Output:
Supported Browsers: The browser supported by fill-opacity property are listed below:
Chrome
Firefox
Safari
Opera
Internet Explorer 9
CSS-Properties
CSS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Nov, 2019"
},
{
"code": null,
"e": 131,
"s": 28,
"text": "The fill-opacity property is used to set the opacity of the paint server that is applied to the shape."
},
{
"code": null,
"e": 139,
"s": 131,
"text": "Syntax:"
},
{
"code": null,
"e": 174,
"s": 139,
"text": "fill-opacity: [0-1] | <percentage>"
},
{
"code": null,
"e": 191,
"s": 174,
"text": "Property Values:"
},
{
"code": null,
"e": 1445,
"s": 191,
"text": "Value between 0 and 1: It is used to set the opacity of the fill-in decimal values. The value 0 means that the fill is completely transparent and invisible. The value 1 means that the fill is fully opaque and visible. A decimal value between these two values would give a semi-transparent fill.Example:<!DOCTYPE html><html><head> <title> CSS | fill-opacity </title> <style> .opacity1 { /* completely visible fill */ fill-opacity: 1.0; fill: green; } .opacity2 { fill-opacity: 0.5; fill: green; } .opacity3 { fill-opacity: 0.25; fill: green; } .opacity4 { /* completely transparent fill */ fill-opacity: 0; fill: green; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | fill-opacity </b> <div class=\"container\"> <svg height=\"250px\" width=\"500px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <circle class=\"opacity1\" cx=\"100\" cy=\"100\" r=\"50\"/> <circle class=\"opacity2\" cx=\"250\" cy=\"100\" r=\"50\"/> <circle class=\"opacity3\" cx=\"400\" cy=\"100\" r=\"50\"/> <circle class=\"opacity4\" cx=\"400\" cy=\"100\" r=\"50\"/> </svg> </div></body></html>Output:"
},
{
"code": null,
"e": 1454,
"s": 1445,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | fill-opacity </title> <style> .opacity1 { /* completely visible fill */ fill-opacity: 1.0; fill: green; } .opacity2 { fill-opacity: 0.5; fill: green; } .opacity3 { fill-opacity: 0.25; fill: green; } .opacity4 { /* completely transparent fill */ fill-opacity: 0; fill: green; } </style></head><body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | fill-opacity </b> <div class=\"container\"> <svg height=\"250px\" width=\"500px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <circle class=\"opacity1\" cx=\"100\" cy=\"100\" r=\"50\"/> <circle class=\"opacity2\" cx=\"250\" cy=\"100\" r=\"50\"/> <circle class=\"opacity3\" cx=\"400\" cy=\"100\" r=\"50\"/> <circle class=\"opacity4\" cx=\"400\" cy=\"100\" r=\"50\"/> </svg> </div></body></html>",
"e": 2399,
"s": 1454,
"text": null
},
{
"code": null,
"e": 2407,
"s": 2399,
"text": "Output:"
},
{
"code": null,
"e": 3719,
"s": 2407,
"text": "percentage: It is used to set the opacity of the fill in percentage values. A value of 0% means that the fill is completely transparent and invisible. A value of 100% means that the fill is fully opaque and visible. A percentage value between these two values would give a semi-transparent fill.Example:<!DOCTYPE html><html><head> <title> CSS | fill-opacity </title> <style> .opacity1 { /* completely visible fill */ fill-opacity: 100%; fill: green; } .opacity2 { fill-opacity: 50%; fill: green; } .opacity3 { fill-opacity: 25%; fill: green; } .opacity4 { /* completely transparent fill */ fill-opacity: 0%; fill: green; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | fill-opacity </b> <div class=\"container\"> <svg height=\"250px\" width=\"500px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect class=\"opacity1\" x=\"25\" y=\"10\" height=\"150\" width=\"100\"/> <rect class=\"opacity2\" x=\"175\" y=\"10\" height=\"150\" width=\"100\"/> <rect class=\"opacity3\" x=\"325\" y=\"10\" height=\"150\" width=\"100\"/> <rect class=\"opacity4\" x=\"325\" y=\"10\" height=\"150\" width=\"100\"/> </svg> </div></body></html>Output:"
},
{
"code": null,
"e": 3728,
"s": 3719,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><head> <title> CSS | fill-opacity </title> <style> .opacity1 { /* completely visible fill */ fill-opacity: 100%; fill: green; } .opacity2 { fill-opacity: 50%; fill: green; } .opacity3 { fill-opacity: 25%; fill: green; } .opacity4 { /* completely transparent fill */ fill-opacity: 0%; fill: green; } </style></head> <body> <h1 style=\"color: green\"> GeeksforGeeks </h1> <b> CSS | fill-opacity </b> <div class=\"container\"> <svg height=\"250px\" width=\"500px\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\"> <rect class=\"opacity1\" x=\"25\" y=\"10\" height=\"150\" width=\"100\"/> <rect class=\"opacity2\" x=\"175\" y=\"10\" height=\"150\" width=\"100\"/> <rect class=\"opacity3\" x=\"325\" y=\"10\" height=\"150\" width=\"100\"/> <rect class=\"opacity4\" x=\"325\" y=\"10\" height=\"150\" width=\"100\"/> </svg> </div></body></html>",
"e": 4730,
"s": 3728,
"text": null
},
{
"code": null,
"e": 4738,
"s": 4730,
"text": "Output:"
},
{
"code": null,
"e": 4823,
"s": 4738,
"text": "Supported Browsers: The browser supported by fill-opacity property are listed below:"
},
{
"code": null,
"e": 4830,
"s": 4823,
"text": "Chrome"
},
{
"code": null,
"e": 4838,
"s": 4830,
"text": "Firefox"
},
{
"code": null,
"e": 4845,
"s": 4838,
"text": "Safari"
},
{
"code": null,
"e": 4851,
"s": 4845,
"text": "Opera"
},
{
"code": null,
"e": 4871,
"s": 4851,
"text": "Internet Explorer 9"
},
{
"code": null,
"e": 4886,
"s": 4871,
"text": "CSS-Properties"
},
{
"code": null,
"e": 4890,
"s": 4886,
"text": "CSS"
},
{
"code": null,
"e": 4907,
"s": 4890,
"text": "Web Technologies"
}
] |
Set Axis Limits of Plot in R
|
23 Aug, 2021
In this article, we will be looking at the approach to set the axis limits of the plot in R programming language.
Axis limit of the plot basically refers to the scaling of the x-axis and the y-axis of the given plot.
In this approach to set the axis limits of the given plot, the user here just simply use the xlim argument with the required parameters to set the limits of the x-axis limits and use the ylim argument with the required parameters to set the limits of the y-axis limits in the plot function of the R programming language to set the axis limits of the plot given.
Plot function: This is a Generic function for plotting R objects.
Syntax: plot(x, y,xlim,ylim ...)
Arguments:
x: the x coordinates of points in the plot.
y: the y coordinates of points in the plot.
xlim: Set or query x-axis limits
ylim: Set or query y-axis limits
In this example, we will be setting up the limits of the x-axis from -20 to 20 of the given plot of 10 data points in it using the xlim argument of the plot function in the R programming language.
R
x = c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1)y = c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6) plot(x, y, xlim = c(-20, 20))
Output:
In this example, we will be setting up the limits of the y-axis from -20 to 20 of the given plot of 10 data points in it using the ylim argument of the plot function in the R programming language.
R
x = c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1)y = c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6) plot(x, y, ylim = c(-20, 20))
Output:
In this example, we will be setting up the limits of the x-axis and y-axis from -20 to 20 of the given plot of 10 data points in it using the xlim and ylim argument of the plot function in the R programming language.
R
x = c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1)y = c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6) plot(x, y, xlim = c(-20, 20), ylim = c(-20, 20))
Output:
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Aug, 2021"
},
{
"code": null,
"e": 143,
"s": 28,
"text": "In this article, we will be looking at the approach to set the axis limits of the plot in R programming language. "
},
{
"code": null,
"e": 246,
"s": 143,
"text": "Axis limit of the plot basically refers to the scaling of the x-axis and the y-axis of the given plot."
},
{
"code": null,
"e": 608,
"s": 246,
"text": "In this approach to set the axis limits of the given plot, the user here just simply use the xlim argument with the required parameters to set the limits of the x-axis limits and use the ylim argument with the required parameters to set the limits of the y-axis limits in the plot function of the R programming language to set the axis limits of the plot given."
},
{
"code": null,
"e": 674,
"s": 608,
"text": "Plot function: This is a Generic function for plotting R objects."
},
{
"code": null,
"e": 707,
"s": 674,
"text": "Syntax: plot(x, y,xlim,ylim ...)"
},
{
"code": null,
"e": 718,
"s": 707,
"text": "Arguments:"
},
{
"code": null,
"e": 762,
"s": 718,
"text": "x: the x coordinates of points in the plot."
},
{
"code": null,
"e": 806,
"s": 762,
"text": "y: the y coordinates of points in the plot."
},
{
"code": null,
"e": 839,
"s": 806,
"text": "xlim: Set or query x-axis limits"
},
{
"code": null,
"e": 872,
"s": 839,
"text": "ylim: Set or query y-axis limits"
},
{
"code": null,
"e": 1069,
"s": 872,
"text": "In this example, we will be setting up the limits of the x-axis from -20 to 20 of the given plot of 10 data points in it using the xlim argument of the plot function in the R programming language."
},
{
"code": null,
"e": 1071,
"s": 1069,
"text": "R"
},
{
"code": "x = c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1)y = c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6) plot(x, y, xlim = c(-20, 20))",
"e": 1175,
"s": 1071,
"text": null
},
{
"code": null,
"e": 1183,
"s": 1175,
"text": "Output:"
},
{
"code": null,
"e": 1380,
"s": 1183,
"text": "In this example, we will be setting up the limits of the y-axis from -20 to 20 of the given plot of 10 data points in it using the ylim argument of the plot function in the R programming language."
},
{
"code": null,
"e": 1382,
"s": 1380,
"text": "R"
},
{
"code": "x = c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1)y = c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6) plot(x, y, ylim = c(-20, 20))",
"e": 1486,
"s": 1382,
"text": null
},
{
"code": null,
"e": 1494,
"s": 1486,
"text": "Output:"
},
{
"code": null,
"e": 1711,
"s": 1494,
"text": "In this example, we will be setting up the limits of the x-axis and y-axis from -20 to 20 of the given plot of 10 data points in it using the xlim and ylim argument of the plot function in the R programming language."
},
{
"code": null,
"e": 1713,
"s": 1711,
"text": "R"
},
{
"code": "x = c(4, 9, 5, 6, 10, 2, 3, 7, 8, 1)y = c(9, 4, 3, 1, 5, 2, 8, 10, 7, 6) plot(x, y, xlim = c(-20, 20), ylim = c(-20, 20))",
"e": 1840,
"s": 1713,
"text": null
},
{
"code": null,
"e": 1848,
"s": 1840,
"text": "Output:"
},
{
"code": null,
"e": 1855,
"s": 1848,
"text": "Picked"
},
{
"code": null,
"e": 1864,
"s": 1855,
"text": "R-Charts"
},
{
"code": null,
"e": 1873,
"s": 1864,
"text": "R-Graphs"
},
{
"code": null,
"e": 1881,
"s": 1873,
"text": "R-plots"
},
{
"code": null,
"e": 1892,
"s": 1881,
"text": "R Language"
}
] |
How to use Grid Component in ReactJS?
|
18 Jan, 2021
The Material Design responsive layout grid adapts to screen size and orientation, ensuring consistency across layouts. Material UI for React has this component available for us and it is very easy to integrate. We can the Grid component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:
npm install @material-ui/core
Project Structure: It will look like the following.
Project Structure
App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
Javascript
import React from 'react';import { makeStyles, createStyles, Theme } from '@material-ui/core/styles';import Paper from '@material-ui/core/Paper';import Grid from '@material-ui/core/Grid'; const useStyles = makeStyles((theme: Theme) => createStyles({ paper: { padding: theme.spacing(2), textAlign: 'center', color: theme.palette.text.secondary, }, root: { flexGrow: 1, }, }),); export default function FullWidthGrid() { const classes = useStyles(); return ( <div style={{ width: '90%', backgroundColor: 'green', padding: '10px' }}> <Grid container spacing={3}> <Grid item xs={12}> <Paper className={classes.paper}> GEEKSFORGEEKS ---> GRID COMPONENT DEMO </Paper> </Grid> <Grid item xs={6} sm={3}> <Paper className={classes.paper}>1/4 Size</Paper> </Grid> <Grid item xs={6} sm={3}> <Paper className={classes.paper}>1/4 Size</Paper> </Grid> <Grid item xs={6} sm={3}> <Paper className={classes.paper}>1/4 Size</Paper> </Grid> <Grid item xs={6} sm={3}> <Paper className={classes.paper}>1/4 Size</Paper> </Grid> <Grid item xs={12} sm={6}> <Paper className={classes.paper}>1/2 Size</Paper> </Grid> <Grid item xs={12} sm={6}> <Paper className={classes.paper}>1/2 Size</Paper> </Grid> <Grid item xs={12}> <Paper className={classes.paper}>Full Size</Paper> </Grid> </Grid> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
JavaScript
ReactJS
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jan, 2021"
},
{
"code": null,
"e": 306,
"s": 28,
"text": "The Material Design responsive layout grid adapts to screen size and orientation, ensuring consistency across layouts. Material UI for React has this component available for us and it is very easy to integrate. We can the Grid component in ReactJS using the following approach."
},
{
"code": null,
"e": 356,
"s": 306,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 420,
"s": 356,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 452,
"s": 420,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 552,
"s": 452,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 566,
"s": 552,
"text": "cd foldername"
},
{
"code": null,
"e": 675,
"s": 566,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command:"
},
{
"code": null,
"e": 705,
"s": 675,
"text": "npm install @material-ui/core"
},
{
"code": null,
"e": 757,
"s": 705,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 775,
"s": 757,
"text": "Project Structure"
},
{
"code": null,
"e": 904,
"s": 775,
"text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 915,
"s": 904,
"text": "Javascript"
},
{
"code": "import React from 'react';import { makeStyles, createStyles, Theme } from '@material-ui/core/styles';import Paper from '@material-ui/core/Paper';import Grid from '@material-ui/core/Grid'; const useStyles = makeStyles((theme: Theme) => createStyles({ paper: { padding: theme.spacing(2), textAlign: 'center', color: theme.palette.text.secondary, }, root: { flexGrow: 1, }, }),); export default function FullWidthGrid() { const classes = useStyles(); return ( <div style={{ width: '90%', backgroundColor: 'green', padding: '10px' }}> <Grid container spacing={3}> <Grid item xs={12}> <Paper className={classes.paper}> GEEKSFORGEEKS ---> GRID COMPONENT DEMO </Paper> </Grid> <Grid item xs={6} sm={3}> <Paper className={classes.paper}>1/4 Size</Paper> </Grid> <Grid item xs={6} sm={3}> <Paper className={classes.paper}>1/4 Size</Paper> </Grid> <Grid item xs={6} sm={3}> <Paper className={classes.paper}>1/4 Size</Paper> </Grid> <Grid item xs={6} sm={3}> <Paper className={classes.paper}>1/4 Size</Paper> </Grid> <Grid item xs={12} sm={6}> <Paper className={classes.paper}>1/2 Size</Paper> </Grid> <Grid item xs={12} sm={6}> <Paper className={classes.paper}>1/2 Size</Paper> </Grid> <Grid item xs={12}> <Paper className={classes.paper}>Full Size</Paper> </Grid> </Grid> </div> );}",
"e": 2470,
"s": 915,
"text": null
},
{
"code": null,
"e": 2583,
"s": 2470,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2593,
"s": 2583,
"text": "npm start"
},
{
"code": null,
"e": 2692,
"s": 2593,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2703,
"s": 2692,
"text": "JavaScript"
},
{
"code": null,
"e": 2711,
"s": 2703,
"text": "ReactJS"
},
{
"code": null,
"e": 2730,
"s": 2711,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2747,
"s": 2730,
"text": "Web Technologies"
}
] |
Python | Decimal normalize() method
|
17 Sep, 2019
Decimal#normalize() : normalize() is a Decimal class method which returns the simplest form of the Decimal value.
Syntax: Decimal.normalize()
Parameter: Decimal values
Return: the simplest form of the Decimal value.
Code #1 : Example for normalize() method
# Python Program explaining # normalize() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal('0.142857') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.normalize() methodprint ("\n\nDecimal a with normalize() method : ", a.normalize()) print ("Decimal b with normalize() method : ", b.normalize())
Output :
Decimal value a : -1
Decimal value b : 0.142857
Decimal a with normalize() method : -1
Decimal b with normalize() method : 0.142857
Code #2 : Example for normalize() method
# Python Program explaining # normalize() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('-3.14') b = Decimal('321e + 5') # printing Decimal valuesprint ("Decimal value a : ", a)print ("Decimal value b : ", b) # Using Decimal.normalize() methodprint ("\n\nDecimal a with normalize() method : ", a.normalize()) print ("Decimal b with normalize() method : ", b.normalize())
Output :
Decimal value a : -3.14
Decimal value b : 3.21E+7
Decimal a with normalize() method : -3.14
Decimal b with normalize() method : 3.21E+7
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Convert integer to string in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Sep, 2019"
},
{
"code": null,
"e": 142,
"s": 28,
"text": "Decimal#normalize() : normalize() is a Decimal class method which returns the simplest form of the Decimal value."
},
{
"code": null,
"e": 251,
"s": 142,
"text": "Syntax: Decimal.normalize()\n\nParameter: Decimal values\n\nReturn: the simplest form of the Decimal value. \n"
},
{
"code": null,
"e": 292,
"s": 251,
"text": "Code #1 : Example for normalize() method"
},
{
"code": "# Python Program explaining # normalize() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal(-1) b = Decimal('0.142857') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.normalize() methodprint (\"\\n\\nDecimal a with normalize() method : \", a.normalize()) print (\"Decimal b with normalize() method : \", b.normalize())",
"e": 718,
"s": 292,
"text": null
},
{
"code": null,
"e": 727,
"s": 718,
"text": "Output :"
},
{
"code": null,
"e": 867,
"s": 727,
"text": "Decimal value a : -1\nDecimal value b : 0.142857\n\n\nDecimal a with normalize() method : -1\nDecimal b with normalize() method : 0.142857\n\n"
},
{
"code": null,
"e": 908,
"s": 867,
"text": "Code #2 : Example for normalize() method"
},
{
"code": "# Python Program explaining # normalize() method # loading decimal libraryfrom decimal import * # Initializing a decimal valuea = Decimal('-3.14') b = Decimal('321e + 5') # printing Decimal valuesprint (\"Decimal value a : \", a)print (\"Decimal value b : \", b) # Using Decimal.normalize() methodprint (\"\\n\\nDecimal a with normalize() method : \", a.normalize()) print (\"Decimal b with normalize() method : \", b.normalize())",
"e": 1339,
"s": 908,
"text": null
},
{
"code": null,
"e": 1348,
"s": 1339,
"text": "Output :"
},
{
"code": null,
"e": 1492,
"s": 1348,
"text": "Decimal value a : -3.14\nDecimal value b : 3.21E+7\n\n\nDecimal a with normalize() method : -3.14\nDecimal b with normalize() method : 3.21E+7\n\n"
},
{
"code": null,
"e": 1509,
"s": 1492,
"text": "Python-Functions"
},
{
"code": null,
"e": 1516,
"s": 1509,
"text": "Python"
},
{
"code": null,
"e": 1614,
"s": 1516,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1632,
"s": 1614,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1674,
"s": 1632,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1696,
"s": 1674,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1731,
"s": 1696,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1757,
"s": 1731,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1789,
"s": 1757,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1818,
"s": 1789,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1848,
"s": 1818,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 1875,
"s": 1848,
"text": "Python Classes and Objects"
}
] |
GATE | GATE CS 2013 | Question 17
|
28 Jun, 2021
Which of the following statements is/are FALSE?
1. For every non-deterministic Turing machine,
there exists an equivalent deterministic Turing machine.
2. Turing recognizable languages are closed under union
and complementation.
3. Turing decidable languages are closed under intersection
and complementation.
4. Turing recognizable languages are closed under union
and intersection.
(A) 1 and 4 only(B) 1 and 3 only(C) 2 only(D) 3 onlyAnswer: (C)Explanation: A recognizer of a language is a machine that recognizes that language.A decider of a language is a machine that decides that language.
Both types of machine halt in the Accept state on strings that are in the languageA Decider also halts if the string is not in the languageA Recogizer MAY or MAY NOT halt on strings that are not in the language
On all input:A Decider MUST halt (in Accept or Reject state)A Recogizer MAY or MAY NOT halt on some strings (Q: Which ones?)
A language is Turing-decidable (or decidable) if some Turing machine decides it. Aka Recursive Language.
A language is Turing-recognizable if some Turing machine recognizes it. Aka Recursively Enumerable Language.
Source: http://www.radford.edu/~nokie/classes/420/Chap3-Langs.html
Recursive (Turing Decidable) languages are closed under followingKleene star, concatenation, union, intersection, complement and set difference.
Recursively enumerable language are closed under Kleene star, concatenation, union, intersection. They are NOT closed under complement or set difference.Quiz of this Question
GATE-CS-2013
GATE-GATE CS 2013
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": 76,
"s": 28,
"text": "Which of the following statements is/are FALSE?"
},
{
"code": null,
"e": 429,
"s": 76,
"text": "1. For every non-deterministic Turing machine, \n there exists an equivalent deterministic Turing machine.\n2. Turing recognizable languages are closed under union \n and complementation.\n3. Turing decidable languages are closed under intersection \n and complementation.\n4. Turing recognizable languages are closed under union \n and intersection. "
},
{
"code": null,
"e": 640,
"s": 429,
"text": "(A) 1 and 4 only(B) 1 and 3 only(C) 2 only(D) 3 onlyAnswer: (C)Explanation: A recognizer of a language is a machine that recognizes that language.A decider of a language is a machine that decides that language."
},
{
"code": null,
"e": 851,
"s": 640,
"text": "Both types of machine halt in the Accept state on strings that are in the languageA Decider also halts if the string is not in the languageA Recogizer MAY or MAY NOT halt on strings that are not in the language"
},
{
"code": null,
"e": 976,
"s": 851,
"text": "On all input:A Decider MUST halt (in Accept or Reject state)A Recogizer MAY or MAY NOT halt on some strings (Q: Which ones?)"
},
{
"code": null,
"e": 1081,
"s": 976,
"text": "A language is Turing-decidable (or decidable) if some Turing machine decides it. Aka Recursive Language."
},
{
"code": null,
"e": 1190,
"s": 1081,
"text": "A language is Turing-recognizable if some Turing machine recognizes it. Aka Recursively Enumerable Language."
},
{
"code": null,
"e": 1257,
"s": 1190,
"text": "Source: http://www.radford.edu/~nokie/classes/420/Chap3-Langs.html"
},
{
"code": null,
"e": 1402,
"s": 1257,
"text": "Recursive (Turing Decidable) languages are closed under followingKleene star, concatenation, union, intersection, complement and set difference."
},
{
"code": null,
"e": 1577,
"s": 1402,
"text": "Recursively enumerable language are closed under Kleene star, concatenation, union, intersection. They are NOT closed under complement or set difference.Quiz of this Question"
},
{
"code": null,
"e": 1590,
"s": 1577,
"text": "GATE-CS-2013"
},
{
"code": null,
"e": 1608,
"s": 1590,
"text": "GATE-GATE CS 2013"
},
{
"code": null,
"e": 1613,
"s": 1608,
"text": "GATE"
}
] |
StringBuilder length() in Java with Examples
|
15 Oct, 2018
The length() method of StringBuilder class returns the number of character the StringBuilder object contains. The length of the sequence of characters currently represented by this StringBuilder object is returned by this method.
Syntax:
public int length()
Return Value: This method returns length of sequence of characters contained by StringBuilder object.
Below programs demonstrate the length() method of StringBuilder Class:
Example 1:
// Java program to demonstrate// the length() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("WelcomeGeeks"); // print string System.out.println("String = " + str.toString()); // get length of StringBuilder object int length = str.length(); // print length System.out.println("length of String = " + length); }}
String = WelcomeGeeks
length of String = 12
Example 2:
// Java program to demonstrate// the length() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder("India is Great"); // print string System.out.println("String = " + str.toString()); // get length of StringBuilder object int length = str.length(); // print length System.out.println("length of String = " + length); }}
String = India is Great
length of String = 14
Reference:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#length()
java-basics
Java-Functions
Java-StringBuilder
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Multidimensional Arrays in Java
Collections in Java
Stream In Java
Set in Java
Initializing a List in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Oct, 2018"
},
{
"code": null,
"e": 258,
"s": 28,
"text": "The length() method of StringBuilder class returns the number of character the StringBuilder object contains. The length of the sequence of characters currently represented by this StringBuilder object is returned by this method."
},
{
"code": null,
"e": 266,
"s": 258,
"text": "Syntax:"
},
{
"code": null,
"e": 286,
"s": 266,
"text": "public int length()"
},
{
"code": null,
"e": 388,
"s": 286,
"text": "Return Value: This method returns length of sequence of characters contained by StringBuilder object."
},
{
"code": null,
"e": 459,
"s": 388,
"text": "Below programs demonstrate the length() method of StringBuilder Class:"
},
{
"code": null,
"e": 470,
"s": 459,
"text": "Example 1:"
},
{
"code": "// Java program to demonstrate// the length() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"WelcomeGeeks\"); // print string System.out.println(\"String = \" + str.toString()); // get length of StringBuilder object int length = str.length(); // print length System.out.println(\"length of String = \" + length); }}",
"e": 1057,
"s": 470,
"text": null
},
{
"code": null,
"e": 1102,
"s": 1057,
"text": "String = WelcomeGeeks\nlength of String = 12\n"
},
{
"code": null,
"e": 1113,
"s": 1102,
"text": "Example 2:"
},
{
"code": "// Java program to demonstrate// the length() Method. class GFG { public static void main(String[] args) { // create a StringBuilder object // with a String pass as parameter StringBuilder str = new StringBuilder(\"India is Great\"); // print string System.out.println(\"String = \" + str.toString()); // get length of StringBuilder object int length = str.length(); // print length System.out.println(\"length of String = \" + length); }}",
"e": 1702,
"s": 1113,
"text": null
},
{
"code": null,
"e": 1749,
"s": 1702,
"text": "String = India is Great\nlength of String = 14\n"
},
{
"code": null,
"e": 1840,
"s": 1749,
"text": "Reference:https://docs.oracle.com/javase/10/docs/api/java/lang/StringBuilder.html#length()"
},
{
"code": null,
"e": 1852,
"s": 1840,
"text": "java-basics"
},
{
"code": null,
"e": 1867,
"s": 1852,
"text": "Java-Functions"
},
{
"code": null,
"e": 1886,
"s": 1867,
"text": "Java-StringBuilder"
},
{
"code": null,
"e": 1899,
"s": 1886,
"text": "Java-Strings"
},
{
"code": null,
"e": 1904,
"s": 1899,
"text": "Java"
},
{
"code": null,
"e": 1917,
"s": 1904,
"text": "Java-Strings"
},
{
"code": null,
"e": 1922,
"s": 1917,
"text": "Java"
},
{
"code": null,
"e": 2020,
"s": 1922,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2071,
"s": 2020,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 2102,
"s": 2071,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 2121,
"s": 2102,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 2151,
"s": 2121,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 2169,
"s": 2151,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 2201,
"s": 2169,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 2221,
"s": 2201,
"text": "Collections in Java"
},
{
"code": null,
"e": 2236,
"s": 2221,
"text": "Stream In Java"
},
{
"code": null,
"e": 2248,
"s": 2236,
"text": "Set in Java"
}
] |
Size of the smallest subset with maximum Bitwise OR
|
28 Jun, 2022
Given an array of positive integers. The task is to find the size of the smallest subset such that the Bitwise OR of that set is Maximum possible.
Examples:
Input : arr[] = {5, 1, 3, 4, 2}
Output : 2
7 is the maximum value possible of OR,
5|2 = 7 and 5|3 = 7
Input : arr[] = {2, 6, 2, 8, 4, 5}
Output : 3
15 is the maximum value of OR and set
elements are 8, 6, 5
Source: Sprinklr on Campus Internship
Doing bitwise OR of a number with some value does not decrease its value. It either keeps the value same or increases. If we take a closer look at the problem we can notice that the maximum OR value that we can get is by doing bitwise OR of all array elements. But this includes all elements and here want to know the smallest subset. So we do the following. I) Find bitwise OR of all array elements. This is the OR we are looking for. II) Now we need to find the smallest subset with this bitwise OR. This problem is similar to the subset-sum problem, We can solve it in two ways :
We generate all subsets and return the smallest size with given ORWe use Dynamic Programming to solve the problem. This solution is going to be very similar to Maximum size subset with given sum
We generate all subsets and return the smallest size with given OR
We use Dynamic Programming to solve the problem. This solution is going to be very similar to Maximum size subset with given sum
The time complexity of the 1st solution is O(2n) and time complexity of the Dynamic Programming solution is O(OR * n) where OR is OR of all array elements and n is the size of the input array.
Using Method 1 : (generating all subsets and return the smallest size with given OR)
C++
Java
Python3
C#
Javascript
// CPP Code for above approach#include <bits/stdc++.h>using namespace std; // Compute bitwise or of all elements// in array of size szint OR(int data[], int sz){ int mOR = 0; for (int i = 0; i < sz; ++i) { mOR |= data[i]; } return mOR;} // calculate the size of// minimum subset with maximum orint minSubset(int data[], int sz,int maxOR){ // store the minimum size of // the subset with maximum OR int minSZ=sz; // generates all subsets for(int mask=0;mask<(1<<sz);mask++) { // stores the size of the current subset int curSZ=0; // stores the OR of all the elements // in the current subset int curOR=0; for(int i=0;i<sz;i++) { if(mask&(1<<i)) { curSZ++; curOR|=data[i]; } } if(curOR==maxOR) minSZ=min(minSZ,curSZ); } return minSZ;} // Driver codeint main(){ int data[] = { 5, 1, 3, 4, 2 }; int sz = sizeof(data) / sizeof(0); int maxOR = OR(data, sz); // Function Call cout << minSubset(data, sz,maxOR) << '\n' ;}
// Java Program for above approachimport java.io.*;import java.util.*; class Solution{ // Compute bitwise or of all elements // in array of size sz private static int OR(int[] arr) { int mOR = 0; for (int i = 0; i < arr.length; ++i) { mOR |= arr[i]; } return mOR; } // Recursively calculating the size of // minimum subset with maximum or private static int maxSubset(int[] arr, int i, int curOr, int curSize, int maxOr) { // If i is arr.length if (i == arr.length) { // If curOr is equal to maxOr if (curOr == maxOr) { return curSize; } // Return arr.length else { return arr.length; } } // Try the current element in the subset int take = maxSubset(arr, i + 1, curOr | arr[i], curSize + 1, maxOr); // Skip the current element int notTake = maxSubset(arr, i + 1, curOr, curSize, maxOr); // Return minimum of take and notTake return Math.min(take, notTake); } // Driver Code public static void main(String[] args) { int[] data = {5, 1, 3, 4, 2}; int maxOr = OR(data); // Function Call int maxSubsetSize = maxSubset(data, 0, 0, 0, maxOr); System.out.println(maxSubsetSize); }} // Code contributed by Abdelaziz EROUI
# Python3 Code for above approach # Compute bitwise or of all elements# in array of size szdef OR(data, sz): mOR = 0 for i in range(sz) : mOR |= data[i] return mOR # calculate the size of# minimum subset with maximum ordef minSubset(data, sz,maxOR): # store the minimum size of # the subset with maximum OR minSZ=sz # generates all subsets for mask in range(1<<sz): # stores the size of the current subset curSZ=0 # stores the OR of all the elements # in the current subset curOR=0 for i in range(sz): if(mask&(1<<i)): curSZ+=1 curOR|=data[i] if(curOR==maxOR): minSZ=min(minSZ,curSZ) return minSZ # Driver codeif __name__ == '__main__': data =[5, 1, 3, 4, 2] sz = len(data) maxOR = OR(data, sz) # Function Call print(minSubset(data, sz,maxOR))
// C# Program for above approachusing System;class Solution{ // Compute bitwise or of all elements // in array of size sz private static int OR(int[] arr) { int mOR = 0; for (int i = 0; i < arr.Length; ++i) { mOR |= arr[i]; } return mOR; } // Recursively calculating the size of // minimum subset with maximum or private static int maxSubset(int[] arr, int i, int curOr, int curSize, int maxOr) { // If i is arr.length if (i == arr.Length) { // If curOr is equal to maxOr if (curOr == maxOr) { return curSize; } // Return arr.length else { return arr.Length; } } // Try the current element in the subset int take = maxSubset(arr, i + 1, curOr | arr[i], curSize + 1, maxOr); // Skip the current element int notTake = maxSubset(arr, i + 1, curOr, curSize, maxOr); // Return minimum of take and notTake return Math.Min(take, notTake); } // Driver Code static void Main() { int[] data = {5, 1, 3, 4, 2}; int maxOr = OR(data); // Function Call int maxSubsetSize = maxSubset(data, 0, 0, 0, maxOr); Console.WriteLine(maxSubsetSize); }} // This code is contributed by SoumikMondal
<script> // JavaScript Program for above approach // Compute bitwise or of all elements // in array of size szfunction OR(arr){ let mOR = 0; for (let i = 0; i < arr.length; ++i) { mOR |= arr[i]; } return mOR;} // Recursively calculating the size of // minimum subset with maximum orfunction maxSubset(arr,i,curOr,curSize,maxOr){ // If i is arr.length if (i == arr.length) { // If curOr is equal to maxOr if (curOr == maxOr) { return curSize; } // Return arr.length else { return arr.length; } } // Try the current element in the subset let take = maxSubset(arr, i + 1, curOr | arr[i], curSize + 1, maxOr); // Skip the current element let notTake = maxSubset(arr, i + 1, curOr, curSize, maxOr); // Return minimum of take and notTake return Math.min(take, notTake);} // Driver Codelet data=[5, 1, 3, 4, 2];let maxOr = OR(data); // Function Calllet maxSubsetSize = maxSubset(data, 0, 0, 0, maxOr);document.write(maxSubsetSize); // This code is contributed by rag2127 </script>
2
Time complexity: O(2n)Auxiliary Space: O(n)
Using Method 2:
We first find the OR of all elements of given array.Now we need to find the smallest subset with this bitwise OR.
To do so, use the similar DP approach as given in the subset sum problem. count[i][j] denotes the minimum size subset till ith element whose OR is j.
C++
Java
Python3
Javascript
// CPP Code for above approach#include <bits/stdc++.h>using namespace std; // Compute bitwise or of all elements// in array of size szint OR(int data[], int sz){ int mOR = 0; for (int i = 0; i < sz; ++i) { mOR |= data[i]; } return mOR;} // calculate the size of// minimum subset with maximum orint minSubset(int data[], int sz, int maxOR){ // count table where // count[i][j] => minimum size subset till ith element // whose OR is j vector<vector<int> > count(sz + 1, vector<int>(maxOR + 1, 1e9)); count[0][0] = 0; for (int i = 0; i < sz; i++) { for (int j = 0; j <= maxOR; j++) { // Do not consider ith element. count[i + 1][j] = min(count[i + 1][j], count[i][j]); // Consider the ith element. if (count[i][j] != 1e9) { count[i + 1][j | data[i]] = min( count[i + 1][j | data[i]], count[i][j] + 1); } } } return count[sz][maxOR];} // Driver codeint main(){ int data[] = { 5, 1, 3, 4, 2 }; int sz = sizeof(data) / sizeof(0); int maxOR = OR(data, sz); // Function Call cout << minSubset(data, sz, maxOR) << '\n';}
/*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG { // Java Code for above approach // Compute bitwise or of all elements // in array of size sz static int OR(int data[], int sz) { int mOR = 0; for (int i = 0; i < sz; ++i) { mOR |= data[i]; } return mOR; } // calculate the size of // minimum subset with maximum or static int minSubset(int data[], int sz, int maxOR) { // count table where // count[i][j] => minimum size subset till ith element // whose OR is j int count[][] = new int[sz + 1][maxOR + 1]; for(int i=0;i<sz+1;i++){ Arrays.fill(count[i],1000000000); } count[0][0] = 0; for (int i = 0; i < sz; i++) { for (int j = 0; j <= maxOR; j++) { // Do not consider ith element. count[i + 1][j] = Math.min(count[i + 1][j], count[i][j]); // Consider the ith element. if (count[i][j] != 1000000000) { count[i + 1][j | data[i]] = Math.min( count[i + 1][j | data[i]], count[i][j] + 1); } } } return count[sz][maxOR]; } /* Driver program to test above function*/ public static void main(String args[]) { int data[] = { 5, 1, 3, 4, 2 }; int sz = data.length; int maxOR = OR(data, sz); // Function Call System.out.println(minSubset(data, sz, maxOR)); }} // This code is contributed by shinjanpatra.
# Python3 Code for above approach # Compute bitwise or of all elements# in array of size szdef OR(data, sz): mOR = 0 for i in range(sz): mOR |= data[i] return mOR # calculate the size of# minimum subset with maximum ordef minSubset(data, sz, maxOR): # count table where # count[i][j] => minimum size subset till ith element # whose OR is j count=[[1e9 for _ in range(maxOR+1)]for _ in range(sz+1)] count[0][0] = 0 for i in range(sz) : for j in range(maxOR) : # Do not consider ith element. count[i + 1][j] = min(count[i + 1][j], count[i][j]) # Consider the ith element. if (count[i][j] != 1e9) : count[i + 1][j | data[i]] = min( count[i + 1][j | data[i]], count[i][j] + 1) return count[sz][maxOR] # Driver codeif __name__ == '__main__': data = [5, 1, 3, 4, 2] sz = len(data) maxOR = OR(data, sz) # Function Call print(minSubset(data, sz, maxOR))
<script> // JavaScript Code for above approach // Compute bitwise or of all elements// in array of size szfunction OR(data, sz){ let mOR = 0 for(let i=0;i<sz;i++) mOR |= data[i] return mOR} // calculate the size of// minimum subset with maximum orfunction minSubset(data, sz, maxOR){ // count table where // count[i][j] => minimum size subset till ith element // whose OR is j let count = new Array(sz+1).fill(0).map(()=>new Array(maxOR+1).fill(1e9)); count[0][0] = 0 for(let i=0;i<sz;i++){ for(let j=0;j<maxOR;j++){ // Do not consider ith element. count[i + 1][j] = Math.min(count[i + 1][j], count[i][j]) // Consider the ith element. if (count[i][j] != 1e9) count[i + 1][j | data[i]] = Math.min( count[i + 1][j | data[i]], count[i][j] + 1) } } return count[sz][maxOR]} // Driver code let data = [5, 1, 3, 4, 2]let sz = data.lengthlet maxOR = OR(data, sz) // Function Calldocument.write(minSubset(data, sz, maxOR),"</br>") // This code is contributed by shinjanpatra </script>
2
Time complexity: O(n*maxOR) where n is the size of the array and maxOR is the maximum or that can be obtained.Auxiliary Space: O(n*maxOR)
Sach_Code
ankthon
SURENDRA_GANGWAR
ukasp
singhadhiraj001
AbdelazizEroui
SoumikMondal
rag2127
pankajsharmagfg
kk773572498
ashutoshsinghgeeksforgeeks
amartyaghoshgfg
shinjanpatra
Bitwise-OR
Sprinklr
subset
Algorithms
Arrays
Dynamic Programming
Sprinklr
Arrays
Dynamic Programming
subset
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 202,
"s": 54,
"text": "Given an array of positive integers. The task is to find the size of the smallest subset such that the Bitwise OR of that set is Maximum possible. "
},
{
"code": null,
"e": 213,
"s": 202,
"text": "Examples: "
},
{
"code": null,
"e": 423,
"s": 213,
"text": "Input : arr[] = {5, 1, 3, 4, 2}\nOutput : 2\n7 is the maximum value possible of OR, \n5|2 = 7 and 5|3 = 7\n\nInput : arr[] = {2, 6, 2, 8, 4, 5}\nOutput : 3\n15 is the maximum value of OR and set\nelements are 8, 6, 5 "
},
{
"code": null,
"e": 462,
"s": 423,
"text": "Source: Sprinklr on Campus Internship "
},
{
"code": null,
"e": 1046,
"s": 462,
"text": "Doing bitwise OR of a number with some value does not decrease its value. It either keeps the value same or increases. If we take a closer look at the problem we can notice that the maximum OR value that we can get is by doing bitwise OR of all array elements. But this includes all elements and here want to know the smallest subset. So we do the following. I) Find bitwise OR of all array elements. This is the OR we are looking for. II) Now we need to find the smallest subset with this bitwise OR. This problem is similar to the subset-sum problem, We can solve it in two ways : "
},
{
"code": null,
"e": 1241,
"s": 1046,
"text": "We generate all subsets and return the smallest size with given ORWe use Dynamic Programming to solve the problem. This solution is going to be very similar to Maximum size subset with given sum"
},
{
"code": null,
"e": 1308,
"s": 1241,
"text": "We generate all subsets and return the smallest size with given OR"
},
{
"code": null,
"e": 1437,
"s": 1308,
"text": "We use Dynamic Programming to solve the problem. This solution is going to be very similar to Maximum size subset with given sum"
},
{
"code": null,
"e": 1631,
"s": 1437,
"text": "The time complexity of the 1st solution is O(2n) and time complexity of the Dynamic Programming solution is O(OR * n) where OR is OR of all array elements and n is the size of the input array. "
},
{
"code": null,
"e": 1717,
"s": 1631,
"text": "Using Method 1 : (generating all subsets and return the smallest size with given OR) "
},
{
"code": null,
"e": 1721,
"s": 1717,
"text": "C++"
},
{
"code": null,
"e": 1726,
"s": 1721,
"text": "Java"
},
{
"code": null,
"e": 1734,
"s": 1726,
"text": "Python3"
},
{
"code": null,
"e": 1737,
"s": 1734,
"text": "C#"
},
{
"code": null,
"e": 1748,
"s": 1737,
"text": "Javascript"
},
{
"code": "// CPP Code for above approach#include <bits/stdc++.h>using namespace std; // Compute bitwise or of all elements// in array of size szint OR(int data[], int sz){ int mOR = 0; for (int i = 0; i < sz; ++i) { mOR |= data[i]; } return mOR;} // calculate the size of// minimum subset with maximum orint minSubset(int data[], int sz,int maxOR){ // store the minimum size of // the subset with maximum OR int minSZ=sz; // generates all subsets for(int mask=0;mask<(1<<sz);mask++) { // stores the size of the current subset int curSZ=0; // stores the OR of all the elements // in the current subset int curOR=0; for(int i=0;i<sz;i++) { if(mask&(1<<i)) { curSZ++; curOR|=data[i]; } } if(curOR==maxOR) minSZ=min(minSZ,curSZ); } return minSZ;} // Driver codeint main(){ int data[] = { 5, 1, 3, 4, 2 }; int sz = sizeof(data) / sizeof(0); int maxOR = OR(data, sz); // Function Call cout << minSubset(data, sz,maxOR) << '\\n' ;}",
"e": 2835,
"s": 1748,
"text": null
},
{
"code": "// Java Program for above approachimport java.io.*;import java.util.*; class Solution{ // Compute bitwise or of all elements // in array of size sz private static int OR(int[] arr) { int mOR = 0; for (int i = 0; i < arr.length; ++i) { mOR |= arr[i]; } return mOR; } // Recursively calculating the size of // minimum subset with maximum or private static int maxSubset(int[] arr, int i, int curOr, int curSize, int maxOr) { // If i is arr.length if (i == arr.length) { // If curOr is equal to maxOr if (curOr == maxOr) { return curSize; } // Return arr.length else { return arr.length; } } // Try the current element in the subset int take = maxSubset(arr, i + 1, curOr | arr[i], curSize + 1, maxOr); // Skip the current element int notTake = maxSubset(arr, i + 1, curOr, curSize, maxOr); // Return minimum of take and notTake return Math.min(take, notTake); } // Driver Code public static void main(String[] args) { int[] data = {5, 1, 3, 4, 2}; int maxOr = OR(data); // Function Call int maxSubsetSize = maxSubset(data, 0, 0, 0, maxOr); System.out.println(maxSubsetSize); }} // Code contributed by Abdelaziz EROUI",
"e": 4224,
"s": 2835,
"text": null
},
{
"code": "# Python3 Code for above approach # Compute bitwise or of all elements# in array of size szdef OR(data, sz): mOR = 0 for i in range(sz) : mOR |= data[i] return mOR # calculate the size of# minimum subset with maximum ordef minSubset(data, sz,maxOR): # store the minimum size of # the subset with maximum OR minSZ=sz # generates all subsets for mask in range(1<<sz): # stores the size of the current subset curSZ=0 # stores the OR of all the elements # in the current subset curOR=0 for i in range(sz): if(mask&(1<<i)): curSZ+=1 curOR|=data[i] if(curOR==maxOR): minSZ=min(minSZ,curSZ) return minSZ # Driver codeif __name__ == '__main__': data =[5, 1, 3, 4, 2] sz = len(data) maxOR = OR(data, sz) # Function Call print(minSubset(data, sz,maxOR))",
"e": 5163,
"s": 4224,
"text": null
},
{
"code": "// C# Program for above approachusing System;class Solution{ // Compute bitwise or of all elements // in array of size sz private static int OR(int[] arr) { int mOR = 0; for (int i = 0; i < arr.Length; ++i) { mOR |= arr[i]; } return mOR; } // Recursively calculating the size of // minimum subset with maximum or private static int maxSubset(int[] arr, int i, int curOr, int curSize, int maxOr) { // If i is arr.length if (i == arr.Length) { // If curOr is equal to maxOr if (curOr == maxOr) { return curSize; } // Return arr.length else { return arr.Length; } } // Try the current element in the subset int take = maxSubset(arr, i + 1, curOr | arr[i], curSize + 1, maxOr); // Skip the current element int notTake = maxSubset(arr, i + 1, curOr, curSize, maxOr); // Return minimum of take and notTake return Math.Min(take, notTake); } // Driver Code static void Main() { int[] data = {5, 1, 3, 4, 2}; int maxOr = OR(data); // Function Call int maxSubsetSize = maxSubset(data, 0, 0, 0, maxOr); Console.WriteLine(maxSubsetSize); }} // This code is contributed by SoumikMondal",
"e": 6511,
"s": 5163,
"text": null
},
{
"code": "<script> // JavaScript Program for above approach // Compute bitwise or of all elements // in array of size szfunction OR(arr){ let mOR = 0; for (let i = 0; i < arr.length; ++i) { mOR |= arr[i]; } return mOR;} // Recursively calculating the size of // minimum subset with maximum orfunction maxSubset(arr,i,curOr,curSize,maxOr){ // If i is arr.length if (i == arr.length) { // If curOr is equal to maxOr if (curOr == maxOr) { return curSize; } // Return arr.length else { return arr.length; } } // Try the current element in the subset let take = maxSubset(arr, i + 1, curOr | arr[i], curSize + 1, maxOr); // Skip the current element let notTake = maxSubset(arr, i + 1, curOr, curSize, maxOr); // Return minimum of take and notTake return Math.min(take, notTake);} // Driver Codelet data=[5, 1, 3, 4, 2];let maxOr = OR(data); // Function Calllet maxSubsetSize = maxSubset(data, 0, 0, 0, maxOr);document.write(maxSubsetSize); // This code is contributed by rag2127 </script>",
"e": 7706,
"s": 6511,
"text": null
},
{
"code": null,
"e": 7708,
"s": 7706,
"text": "2"
},
{
"code": null,
"e": 7753,
"s": 7708,
"text": "Time complexity: O(2n)Auxiliary Space: O(n) "
},
{
"code": null,
"e": 7770,
"s": 7753,
"text": "Using Method 2: "
},
{
"code": null,
"e": 7885,
"s": 7770,
"text": " We first find the OR of all elements of given array.Now we need to find the smallest subset with this bitwise OR."
},
{
"code": null,
"e": 8035,
"s": 7885,
"text": "To do so, use the similar DP approach as given in the subset sum problem. count[i][j] denotes the minimum size subset till ith element whose OR is j."
},
{
"code": null,
"e": 8039,
"s": 8035,
"text": "C++"
},
{
"code": null,
"e": 8044,
"s": 8039,
"text": "Java"
},
{
"code": null,
"e": 8052,
"s": 8044,
"text": "Python3"
},
{
"code": null,
"e": 8063,
"s": 8052,
"text": "Javascript"
},
{
"code": "// CPP Code for above approach#include <bits/stdc++.h>using namespace std; // Compute bitwise or of all elements// in array of size szint OR(int data[], int sz){ int mOR = 0; for (int i = 0; i < sz; ++i) { mOR |= data[i]; } return mOR;} // calculate the size of// minimum subset with maximum orint minSubset(int data[], int sz, int maxOR){ // count table where // count[i][j] => minimum size subset till ith element // whose OR is j vector<vector<int> > count(sz + 1, vector<int>(maxOR + 1, 1e9)); count[0][0] = 0; for (int i = 0; i < sz; i++) { for (int j = 0; j <= maxOR; j++) { // Do not consider ith element. count[i + 1][j] = min(count[i + 1][j], count[i][j]); // Consider the ith element. if (count[i][j] != 1e9) { count[i + 1][j | data[i]] = min( count[i + 1][j | data[i]], count[i][j] + 1); } } } return count[sz][maxOR];} // Driver codeint main(){ int data[] = { 5, 1, 3, 4, 2 }; int sz = sizeof(data) / sizeof(0); int maxOR = OR(data, sz); // Function Call cout << minSubset(data, sz, maxOR) << '\\n';}",
"e": 9248,
"s": 8063,
"text": null
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*;import java.util.*; class GFG { // Java Code for above approach // Compute bitwise or of all elements // in array of size sz static int OR(int data[], int sz) { int mOR = 0; for (int i = 0; i < sz; ++i) { mOR |= data[i]; } return mOR; } // calculate the size of // minimum subset with maximum or static int minSubset(int data[], int sz, int maxOR) { // count table where // count[i][j] => minimum size subset till ith element // whose OR is j int count[][] = new int[sz + 1][maxOR + 1]; for(int i=0;i<sz+1;i++){ Arrays.fill(count[i],1000000000); } count[0][0] = 0; for (int i = 0; i < sz; i++) { for (int j = 0; j <= maxOR; j++) { // Do not consider ith element. count[i + 1][j] = Math.min(count[i + 1][j], count[i][j]); // Consider the ith element. if (count[i][j] != 1000000000) { count[i + 1][j | data[i]] = Math.min( count[i + 1][j | data[i]], count[i][j] + 1); } } } return count[sz][maxOR]; } /* Driver program to test above function*/ public static void main(String args[]) { int data[] = { 5, 1, 3, 4, 2 }; int sz = data.length; int maxOR = OR(data, sz); // Function Call System.out.println(minSubset(data, sz, maxOR)); }} // This code is contributed by shinjanpatra.",
"e": 10652,
"s": 9248,
"text": null
},
{
"code": "# Python3 Code for above approach # Compute bitwise or of all elements# in array of size szdef OR(data, sz): mOR = 0 for i in range(sz): mOR |= data[i] return mOR # calculate the size of# minimum subset with maximum ordef minSubset(data, sz, maxOR): # count table where # count[i][j] => minimum size subset till ith element # whose OR is j count=[[1e9 for _ in range(maxOR+1)]for _ in range(sz+1)] count[0][0] = 0 for i in range(sz) : for j in range(maxOR) : # Do not consider ith element. count[i + 1][j] = min(count[i + 1][j], count[i][j]) # Consider the ith element. if (count[i][j] != 1e9) : count[i + 1][j | data[i]] = min( count[i + 1][j | data[i]], count[i][j] + 1) return count[sz][maxOR] # Driver codeif __name__ == '__main__': data = [5, 1, 3, 4, 2] sz = len(data) maxOR = OR(data, sz) # Function Call print(minSubset(data, sz, maxOR))",
"e": 11676,
"s": 10652,
"text": null
},
{
"code": "<script> // JavaScript Code for above approach // Compute bitwise or of all elements// in array of size szfunction OR(data, sz){ let mOR = 0 for(let i=0;i<sz;i++) mOR |= data[i] return mOR} // calculate the size of// minimum subset with maximum orfunction minSubset(data, sz, maxOR){ // count table where // count[i][j] => minimum size subset till ith element // whose OR is j let count = new Array(sz+1).fill(0).map(()=>new Array(maxOR+1).fill(1e9)); count[0][0] = 0 for(let i=0;i<sz;i++){ for(let j=0;j<maxOR;j++){ // Do not consider ith element. count[i + 1][j] = Math.min(count[i + 1][j], count[i][j]) // Consider the ith element. if (count[i][j] != 1e9) count[i + 1][j | data[i]] = Math.min( count[i + 1][j | data[i]], count[i][j] + 1) } } return count[sz][maxOR]} // Driver code let data = [5, 1, 3, 4, 2]let sz = data.lengthlet maxOR = OR(data, sz) // Function Calldocument.write(minSubset(data, sz, maxOR),\"</br>\") // This code is contributed by shinjanpatra </script>",
"e": 12800,
"s": 11676,
"text": null
},
{
"code": null,
"e": 12802,
"s": 12800,
"text": "2"
},
{
"code": null,
"e": 12941,
"s": 12802,
"text": "Time complexity: O(n*maxOR) where n is the size of the array and maxOR is the maximum or that can be obtained.Auxiliary Space: O(n*maxOR) "
},
{
"code": null,
"e": 12951,
"s": 12941,
"text": "Sach_Code"
},
{
"code": null,
"e": 12959,
"s": 12951,
"text": "ankthon"
},
{
"code": null,
"e": 12976,
"s": 12959,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 12982,
"s": 12976,
"text": "ukasp"
},
{
"code": null,
"e": 12998,
"s": 12982,
"text": "singhadhiraj001"
},
{
"code": null,
"e": 13013,
"s": 12998,
"text": "AbdelazizEroui"
},
{
"code": null,
"e": 13026,
"s": 13013,
"text": "SoumikMondal"
},
{
"code": null,
"e": 13034,
"s": 13026,
"text": "rag2127"
},
{
"code": null,
"e": 13050,
"s": 13034,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 13062,
"s": 13050,
"text": "kk773572498"
},
{
"code": null,
"e": 13089,
"s": 13062,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 13105,
"s": 13089,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 13118,
"s": 13105,
"text": "shinjanpatra"
},
{
"code": null,
"e": 13129,
"s": 13118,
"text": "Bitwise-OR"
},
{
"code": null,
"e": 13138,
"s": 13129,
"text": "Sprinklr"
},
{
"code": null,
"e": 13145,
"s": 13138,
"text": "subset"
},
{
"code": null,
"e": 13156,
"s": 13145,
"text": "Algorithms"
},
{
"code": null,
"e": 13163,
"s": 13156,
"text": "Arrays"
},
{
"code": null,
"e": 13183,
"s": 13163,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 13192,
"s": 13183,
"text": "Sprinklr"
},
{
"code": null,
"e": 13199,
"s": 13192,
"text": "Arrays"
},
{
"code": null,
"e": 13219,
"s": 13199,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 13226,
"s": 13219,
"text": "subset"
},
{
"code": null,
"e": 13237,
"s": 13226,
"text": "Algorithms"
}
] |
Python | Pandas Index.value_counts()
|
23 Nov, 2021
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas Index.value_counts() function returns object containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element. Excludes NA values by default.
Syntax: Index.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)Parameters : normalize : If True then the object returned will contain the relative frequencies of the unique values. sort : Sort by values ascending : Sort in ascending order bins : Rather than count values, group them into half-open bins, a convenience for pd.cut, only works with numeric data dropna : Don’t include counts of NaN.Returns : counts : Series
Example #1: Use Index.value_counts() function to count the number of unique values in the given Index.
Python3
# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Harry', 'Mike', 'Arther', 'Nick', 'Harry', 'Arther'], name ='Student') # Print the Indexprint(idx)
Output :
Index(['Harry', 'Mike', 'Arther', 'Nick', 'Harry', 'Arther'], dtype='object', name='Student')
Let’s find the count of all unique values in the index.
Python3
# find the count of unique values in the indexidx.value_counts()
Output :
Harry 2
Arther 2
Nick 1
Mike 1
Name: Student, dtype: int64
The function has returned the count of all unique values in the given index. Notice the object returned by the function contains the occurrence of the values in descending order. Example #2: Use Index.value_counts() function to find the count of all unique values in the given index.
Python3
# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([21, 10, 30, 40, 50, 10, 50]) # Print the Indexprint(idx)
Output :
Int64Index([21, 10, 30, 40, 50, 10, 50], dtype='int64')
Let’s count the occurrence of all the unique values in the Index.
Python3
# for finding the count of all# unique values in the index.idx.value_counts()
Output :
10 2
50 2
30 1
21 1
40 1
dtype: int64
The function has returned the count of all unique values in the index.
gopalsakhwala18
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 503,
"s": 53,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier.Pandas Index.value_counts() function returns object containing counts of unique values. The resulting object will be in descending order so that the first element is the most frequently-occurring element. Excludes NA values by default. "
},
{
"code": null,
"e": 959,
"s": 503,
"text": "Syntax: Index.value_counts(normalize=False, sort=True, ascending=False, bins=None, dropna=True)Parameters : normalize : If True then the object returned will contain the relative frequencies of the unique values. sort : Sort by values ascending : Sort in ascending order bins : Rather than count values, group them into half-open bins, a convenience for pd.cut, only works with numeric data dropna : Don’t include counts of NaN.Returns : counts : Series "
},
{
"code": null,
"e": 1063,
"s": 959,
"text": "Example #1: Use Index.value_counts() function to count the number of unique values in the given Index. "
},
{
"code": null,
"e": 1071,
"s": 1063,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index(['Harry', 'Mike', 'Arther', 'Nick', 'Harry', 'Arther'], name ='Student') # Print the Indexprint(idx)",
"e": 1266,
"s": 1071,
"text": null
},
{
"code": null,
"e": 1276,
"s": 1266,
"text": "Output : "
},
{
"code": null,
"e": 1370,
"s": 1276,
"text": "Index(['Harry', 'Mike', 'Arther', 'Nick', 'Harry', 'Arther'], dtype='object', name='Student')"
},
{
"code": null,
"e": 1427,
"s": 1370,
"text": "Let’s find the count of all unique values in the index. "
},
{
"code": null,
"e": 1435,
"s": 1427,
"text": "Python3"
},
{
"code": "# find the count of unique values in the indexidx.value_counts()",
"e": 1500,
"s": 1435,
"text": null
},
{
"code": null,
"e": 1510,
"s": 1500,
"text": "Output : "
},
{
"code": null,
"e": 1586,
"s": 1510,
"text": "Harry 2\nArther 2\nNick 1\nMike 1\nName: Student, dtype: int64"
},
{
"code": null,
"e": 1872,
"s": 1586,
"text": "The function has returned the count of all unique values in the given index. Notice the object returned by the function contains the occurrence of the values in descending order. Example #2: Use Index.value_counts() function to find the count of all unique values in the given index."
},
{
"code": null,
"e": 1880,
"s": 1872,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # Creating the indexidx = pd.Index([21, 10, 30, 40, 50, 10, 50]) # Print the Indexprint(idx)",
"e": 2017,
"s": 1880,
"text": null
},
{
"code": null,
"e": 2027,
"s": 2017,
"text": "Output : "
},
{
"code": null,
"e": 2083,
"s": 2027,
"text": "Int64Index([21, 10, 30, 40, 50, 10, 50], dtype='int64')"
},
{
"code": null,
"e": 2149,
"s": 2083,
"text": "Let’s count the occurrence of all the unique values in the Index."
},
{
"code": null,
"e": 2157,
"s": 2149,
"text": "Python3"
},
{
"code": "# for finding the count of all# unique values in the index.idx.value_counts()",
"e": 2235,
"s": 2157,
"text": null
},
{
"code": null,
"e": 2245,
"s": 2235,
"text": "Output : "
},
{
"code": null,
"e": 2298,
"s": 2245,
"text": "10 2\n50 2\n30 1\n21 1\n40 1\ndtype: int64"
},
{
"code": null,
"e": 2369,
"s": 2298,
"text": "The function has returned the count of all unique values in the index."
},
{
"code": null,
"e": 2385,
"s": 2369,
"text": "gopalsakhwala18"
},
{
"code": null,
"e": 2408,
"s": 2385,
"text": "Python pandas-indexing"
},
{
"code": null,
"e": 2422,
"s": 2408,
"text": "Python-pandas"
},
{
"code": null,
"e": 2429,
"s": 2422,
"text": "Python"
}
] |
Java String concat() with examples
|
27 Oct, 2021
The Java String concat() method concatenates one string to the end of another string. This method returns a string with the value of the string passed into the method, appended to the end of the string. Consider the below illustration:
Illustration:
Input: String 1 : abc
String 2 : def
String n-1 : ...
String n : xyz
Output: abcdef...xyz
Syntax:
public String concat(String anostr)
Parameter: A string to be concatenated at the end of the other string
Return: Concatenated(combined) string
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.
Example:
java
// Java program to Illustrate Working of concat() method// with Strings// By explicitly assigning result // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input string 1 String s = "Hello "; // Custom input string 2 s = s.concat("World"); // Explicitly assigning result by // Combining(adding, concatenating strings) // using concat() method // Print and display combined string System.out.println(s); }}
Hello World
Example 2:
java
// Java program to Illustrate Working of concat() method// in strings where we are sequentially// adding multiple strings as we need // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Custom string 1 String str1 = "Computer-"; // Custom string 2 String str2 = "-Science"; // Combining above strings by // passing one string as an argument String str3 = str1.concat(str2); // Print and display temporary combined string System.out.println(str3); String str4 = "-Portal"; String str5 = str3.concat(str4); System.out.println(str5); }}
Computer--Science
Computer--Science-Portal
As perceived from the code we can do as many times as we want to concatenate strings bypassing older strings with new strings to be contaminated as a parameter and storing the resultant string in String datatype.
Akanksha_Rai
solankimayank
adnanirshad158
Java-Functions
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n27 Oct, 2021"
},
{
"code": null,
"e": 289,
"s": 53,
"text": "The Java String concat() method concatenates one string to the end of another string. This method returns a string with the value of the string passed into the method, appended to the end of the string. Consider the below illustration:"
},
{
"code": null,
"e": 303,
"s": 289,
"text": "Illustration:"
},
{
"code": null,
"e": 432,
"s": 303,
"text": "Input: String 1 : abc\n String 2 : def\n String n-1 : ...\n String n : xyz\nOutput: abcdef...xyz "
},
{
"code": null,
"e": 440,
"s": 432,
"text": "Syntax:"
},
{
"code": null,
"e": 479,
"s": 440,
"text": "public String concat(String anostr) "
},
{
"code": null,
"e": 549,
"s": 479,
"text": "Parameter: A string to be concatenated at the end of the other string"
},
{
"code": null,
"e": 589,
"s": 549,
"text": "Return: Concatenated(combined) string "
},
{
"code": null,
"e": 598,
"s": 589,
"text": "Chapters"
},
{
"code": null,
"e": 625,
"s": 598,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 675,
"s": 625,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 698,
"s": 675,
"text": "captions off, selected"
},
{
"code": null,
"e": 706,
"s": 698,
"text": "English"
},
{
"code": null,
"e": 730,
"s": 706,
"text": "This is a modal window."
},
{
"code": null,
"e": 799,
"s": 730,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 821,
"s": 799,
"text": "End of dialog window."
},
{
"code": null,
"e": 830,
"s": 821,
"text": "Example:"
},
{
"code": null,
"e": 835,
"s": 830,
"text": "java"
},
{
"code": "// Java program to Illustrate Working of concat() method// with Strings// By explicitly assigning result // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input string 1 String s = \"Hello \"; // Custom input string 2 s = s.concat(\"World\"); // Explicitly assigning result by // Combining(adding, concatenating strings) // using concat() method // Print and display combined string System.out.println(s); }}",
"e": 1372,
"s": 835,
"text": null
},
{
"code": null,
"e": 1384,
"s": 1372,
"text": "Hello World"
},
{
"code": null,
"e": 1395,
"s": 1384,
"text": "Example 2:"
},
{
"code": null,
"e": 1400,
"s": 1395,
"text": "java"
},
{
"code": "// Java program to Illustrate Working of concat() method// in strings where we are sequentially// adding multiple strings as we need // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Custom string 1 String str1 = \"Computer-\"; // Custom string 2 String str2 = \"-Science\"; // Combining above strings by // passing one string as an argument String str3 = str1.concat(str2); // Print and display temporary combined string System.out.println(str3); String str4 = \"-Portal\"; String str5 = str3.concat(str4); System.out.println(str5); }}",
"e": 2086,
"s": 1400,
"text": null
},
{
"code": null,
"e": 2129,
"s": 2086,
"text": "Computer--Science\nComputer--Science-Portal"
},
{
"code": null,
"e": 2342,
"s": 2129,
"text": "As perceived from the code we can do as many times as we want to concatenate strings bypassing older strings with new strings to be contaminated as a parameter and storing the resultant string in String datatype."
},
{
"code": null,
"e": 2355,
"s": 2342,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 2369,
"s": 2355,
"text": "solankimayank"
},
{
"code": null,
"e": 2384,
"s": 2369,
"text": "adnanirshad158"
},
{
"code": null,
"e": 2399,
"s": 2384,
"text": "Java-Functions"
},
{
"code": null,
"e": 2412,
"s": 2399,
"text": "Java-Strings"
},
{
"code": null,
"e": 2417,
"s": 2412,
"text": "Java"
},
{
"code": null,
"e": 2430,
"s": 2417,
"text": "Java-Strings"
},
{
"code": null,
"e": 2435,
"s": 2430,
"text": "Java"
}
] |
TCL script to find sum of n natural numbers using looping statements
|
26 Apr, 2021
In this article, we will discuss the overview of TCL script and will cover the TCL script to find the sum of n natural numbers using looping statements with the help of an example. Let’s discuss it one by one.
Pre-requisite –You can go through this article to understand a few basics through this link. https://www.geeksforgeeks.org/basics-of-ns2-and-otcltcl-script/.
Overview :We will understand the syntax of the while loop and for loop in Tool Command Language with a simple example. In this example, we will first use the while loop to find the sum of the first n natural numbers, and then we will see how to use for loop to accomplish the same. We will also compare the syntax with a familiar language to understand it better.
While-loop implementation :We will discuss the implementation steps as follows.
Step-1 :The first step is to read a number from the user after prompting to do so. To read the number we use gets, and we use puts to give a prompt.
puts "Enter a number"
gets stdin b
Step-2 :Our next step is to initialize the sum to 0 and the iteration variable, i to 0. After this, we can have the while loop implementation of the code.
set sum 0
set i 0
while {$i<=$b} {
set sum [expr $sum+$i]
incr i
}
Note – The syntax of the while loop must be exactly as shown above. If you neglect the spaces or type the opening curly brace in a new line, the result will be an error.
Step-3 :The implementation of the while loop specified above would like the following in C programming as follows.
sum=0;
i=0;
while(i<=b)
{
sum=sum+i;
i++;
}
Step-4 :Finally, the whole code and output are as follows.Code –
puts "Enter a number"
gets stdin b
set sum 0
set i 0
while {$i<=$b} {
set sum [expr $sum+$i]
incr i
}
puts "The sum of first $b natural numbers is $sum"
Output :
For-loop implementation :We will discuss the implementation steps as follows.
Step-1 :The first 2 lines of code are the same as in the while loop. So, let’s look at the for loop implementation part.
set sum 0
for {set i 1} {$i<=$b} {incr i} {
set sum [expr $sum+$i]
}
Note – The syntax of for loop must be exactly as shown above. If you neglect the spaces or type the opening curly brace in a new line, the result will be an error.
Step-2 :The implementation of the for loop specified above would like the following in C programming as follows.
sum=0;
for(i=1;i<=n;i++)
{
sum=sum+i;
}
Step-3 :Finally, let’s view the entire code and its output as follows.Code –
puts "Enter a number"
gets stdin b
set sum 0
for {set i 1} {$i<=$b} {incr i} {
set sum [expr $sum+$i]
}
puts "The sum of first $b natural numbers is $sum"
Output :
loop
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": "\n26 Apr, 2021"
},
{
"code": null,
"e": 238,
"s": 28,
"text": "In this article, we will discuss the overview of TCL script and will cover the TCL script to find the sum of n natural numbers using looping statements with the help of an example. Let’s discuss it one by one."
},
{
"code": null,
"e": 396,
"s": 238,
"text": "Pre-requisite –You can go through this article to understand a few basics through this link. https://www.geeksforgeeks.org/basics-of-ns2-and-otcltcl-script/."
},
{
"code": null,
"e": 761,
"s": 396,
"text": "Overview :We will understand the syntax of the while loop and for loop in Tool Command Language with a simple example. In this example, we will first use the while loop to find the sum of the first n natural numbers, and then we will see how to use for loop to accomplish the same. We will also compare the syntax with a familiar language to understand it better. "
},
{
"code": null,
"e": 841,
"s": 761,
"text": "While-loop implementation :We will discuss the implementation steps as follows."
},
{
"code": null,
"e": 990,
"s": 841,
"text": "Step-1 :The first step is to read a number from the user after prompting to do so. To read the number we use gets, and we use puts to give a prompt."
},
{
"code": null,
"e": 1025,
"s": 990,
"text": "puts \"Enter a number\"\ngets stdin b"
},
{
"code": null,
"e": 1180,
"s": 1025,
"text": "Step-2 :Our next step is to initialize the sum to 0 and the iteration variable, i to 0. After this, we can have the while loop implementation of the code."
},
{
"code": null,
"e": 1249,
"s": 1180,
"text": "set sum 0\nset i 0\nwhile {$i<=$b} {\n set sum [expr $sum+$i]\n incr i\n}"
},
{
"code": null,
"e": 1419,
"s": 1249,
"text": "Note – The syntax of the while loop must be exactly as shown above. If you neglect the spaces or type the opening curly brace in a new line, the result will be an error."
},
{
"code": null,
"e": 1535,
"s": 1419,
"text": "Step-3 :The implementation of the while loop specified above would like the following in C programming as follows. "
},
{
"code": null,
"e": 1581,
"s": 1535,
"text": "sum=0;\ni=0;\nwhile(i<=b)\n{\nsum=sum+i;\ni++; \n}"
},
{
"code": null,
"e": 1646,
"s": 1581,
"text": "Step-4 :Finally, the whole code and output are as follows.Code –"
},
{
"code": null,
"e": 1801,
"s": 1646,
"text": "puts \"Enter a number\"\ngets stdin b\nset sum 0\nset i 0\nwhile {$i<=$b} {\n set sum [expr $sum+$i]\n incr i\n}\nputs \"The sum of first $b natural numbers is $sum\""
},
{
"code": null,
"e": 1810,
"s": 1801,
"text": "Output :"
},
{
"code": null,
"e": 1888,
"s": 1810,
"text": "For-loop implementation :We will discuss the implementation steps as follows."
},
{
"code": null,
"e": 2009,
"s": 1888,
"text": "Step-1 :The first 2 lines of code are the same as in the while loop. So, let’s look at the for loop implementation part."
},
{
"code": null,
"e": 2078,
"s": 2009,
"text": "set sum 0\nfor {set i 1} {$i<=$b} {incr i} {\nset sum [expr $sum+$i]\n}"
},
{
"code": null,
"e": 2242,
"s": 2078,
"text": "Note – The syntax of for loop must be exactly as shown above. If you neglect the spaces or type the opening curly brace in a new line, the result will be an error."
},
{
"code": null,
"e": 2355,
"s": 2242,
"text": "Step-2 :The implementation of the for loop specified above would like the following in C programming as follows."
},
{
"code": null,
"e": 2395,
"s": 2355,
"text": "sum=0;\nfor(i=1;i<=n;i++)\n{\nsum=sum+i;\n}"
},
{
"code": null,
"e": 2472,
"s": 2395,
"text": "Step-3 :Finally, let’s view the entire code and its output as follows.Code –"
},
{
"code": null,
"e": 2627,
"s": 2472,
"text": "puts \"Enter a number\"\ngets stdin b\nset sum 0\nfor {set i 1} {$i<=$b} {incr i} {\nset sum [expr $sum+$i]\n}\nputs \"The sum of first $b natural numbers is $sum\""
},
{
"code": null,
"e": 2636,
"s": 2627,
"text": "Output :"
},
{
"code": null,
"e": 2641,
"s": 2636,
"text": "loop"
},
{
"code": null,
"e": 2659,
"s": 2641,
"text": "Computer Networks"
},
{
"code": null,
"e": 2677,
"s": 2659,
"text": "Computer Networks"
}
] |
Barplot using seaborn in Python
|
10 Jun, 2021
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 to the data structures from pandas.
seaborn.barplot() method is used to draw a barplot. A bar plot represents an estimate of central tendency for a numeric variable with the height of each rectangle and provides some indication of the uncertainty around that estimate using error bars.
Syntax : seaborn.barplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, estimator=<function mean at 0x7fa4c4f67940>, ci=95, n_boot=1000, units=None, seed=None, orient=None, color=None, palette=None, saturation=0.75, errcolor=’.26′, errwidth=None, capsize=None, dodge=True, ax=None, **kwargs)Parameters : This method is accepting the following parameters that are described below :
x, y : This parameter take names of variables in data or vector data, Inputs for plotting long-form data.
hue : (optional) This parameter take column name for colour encoding.
data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-form.
color : (optional) This parameter take matplotlib color, Color for all of the elements, or seed for a gradient palette.
Returns : Returns the Axes object with the plot drawn onto it.
Grouping variables in Seaborn barplot with different attributes
Example 1: Draw a set of vertical bar plots grouped by a categorical variable. Creating a simple bar plot using seaborn.
Syntax:
seaborn.barplot( x, y, data)
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplotsns.barplot(x = 'class', y = 'fare', data = df) # Show the plotplt.show()
Output :
Example 2: Draw a set of vertical bars with nested grouping by two variables.
Creating a bar plot using hue parameter with two variables.
Syntax:
seaborn.barplot( x, y, data, hue)
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplotsns.barplot(x = 'class', y = 'fare', hue = 'sex', data = df) # Show the plotplt.show()
Output :
Example 3: shows a Horizontal barplot.
exchange the data variable instead of two data variables then it means that the axis denotes each of these data variables as an axis.
X denotes an x-axis and y denote a y-axis.
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # fare v / s class horizontal barplotsns.barplot(x = 'fare', y = 'class', hue = 'sex', data = df) # Show the plotplt.show()
Output :
Example 4: Plot all bars in a given order.
Control barplot order by passing an explicit order.
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplot in given ordersns.barplot(x = 'class', y = 'fare', data = df, order = ["Third", "Second", "First"]) # Show the plotplt.show()
Output :
Example 5: Plot all bars in a single color using color attributes.
Color for all of the elements.
Syntax:
seaborn.barplot( x, y, data, color)
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplot with same coloursns.barplot(x = 'class', y = 'fare', data = df, color = "salmon") # Show the plotplt.show()
Output :
Example 6: barplot without error bars using ci attributes.
We will use None it means no bootstrapping will be performed, and error bars will not be drawn
Syntax:
seaborn.barplot( x, y, data, ci)
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplot# without error barssns.barplot(x = 'class', y = 'fare', data = df, ci = None) # Show the plotplt.show()
Output :
Example 7: Colors to use for the different levels of the hue variable using palette.
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 barplot with different colormap values.
Syntax:
seaborn.barplot( x, y, data, palette=”color_name”)
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') sns.barplot(x = 'class', y = 'fare', hue = 'sex', data = df, palette='pastel') # Show the plotplt.show()
Output:
Possible values of palette are:
Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r,
GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r,
Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r,
Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1,
Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr,
YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r,
cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth,
gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern,
Example 8: Using the statistical function NumPy.median and NumPy.mean to estimate within each categorical bin.
Python3
# importing the required libraryimport seaborn as snsfrom numpy import medianimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') sns.barplot(x = 'class', y = 'fare', hue = 'sex', data = df, estimator=median) # Show the plotplt.show()
Output:
For Numpy.mean:
Python3
from numpy import meansns.barplot(x = 'class', y = 'fare', hue = 'sex', data = df, estimator=mean)
Output:
Example 9: Using the saturation parameter.
The proportion of the original saturation to draw colors at. Large patches often look better with slightly desaturated colors, but set this to 1 if you want the plot colors to perfectly match the input color spec.
Syntax:
seaborn.barplot( x, y, data, saturation)
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') sns.barplot(x = 'class', y = 'fare', hue = 'sex', data = df,saturation = 0.1) # Show the plotplt.show()
Output:
Example 10: Use matplotlib.axes.Axes.bar() parameters to control the style.
We can set Width of the gray lines that frame the plot elements using linewidth. Whenever we increase linewidth than the point also will increase automatically.
Syntax:
seaborn.barplot(x, y, data, linewidth, edgecolor)
Python3
# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') sns.barplot(x="class", y="fare", data=df, linewidth=2.5, facecolor=(1, 1, 1, 0), errcolor=".2", edgecolor=".2")
Output:
kumar_satyam
surinderdawra388
Python-Seaborn
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n10 Jun, 2021"
},
{
"code": null,
"e": 350,
"s": 52,
"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 to the data structures from pandas. "
},
{
"code": null,
"e": 602,
"s": 350,
"text": "seaborn.barplot() method is used to draw a barplot. A bar plot represents an estimate of central tendency for a numeric variable with the height of each rectangle and provides some indication of the uncertainty around that estimate using error bars. "
},
{
"code": null,
"e": 1003,
"s": 602,
"text": "Syntax : seaborn.barplot(x=None, y=None, hue=None, data=None, order=None, hue_order=None, estimator=<function mean at 0x7fa4c4f67940>, ci=95, n_boot=1000, units=None, seed=None, orient=None, color=None, palette=None, saturation=0.75, errcolor=’.26′, errwidth=None, capsize=None, dodge=True, ax=None, **kwargs)Parameters : This method is accepting the following parameters that are described below : "
},
{
"code": null,
"e": 1109,
"s": 1003,
"text": "x, y : This parameter take names of variables in data or vector data, Inputs for plotting long-form data."
},
{
"code": null,
"e": 1179,
"s": 1109,
"text": "hue : (optional) This parameter take column name for colour encoding."
},
{
"code": null,
"e": 1375,
"s": 1179,
"text": "data : (optional) This parameter take DataFrame, array, or list of arrays, Dataset for plotting. If x and y are absent, this is interpreted as wide-form. Otherwise it is expected to be long-form."
},
{
"code": null,
"e": 1495,
"s": 1375,
"text": "color : (optional) This parameter take matplotlib color, Color for all of the elements, or seed for a gradient palette."
},
{
"code": null,
"e": 1560,
"s": 1495,
"text": "Returns : Returns the Axes object with the plot drawn onto it. "
},
{
"code": null,
"e": 1625,
"s": 1560,
"text": "Grouping variables in Seaborn barplot with different attributes "
},
{
"code": null,
"e": 1747,
"s": 1625,
"text": "Example 1: Draw a set of vertical bar plots grouped by a categorical variable. Creating a simple bar plot using seaborn."
},
{
"code": null,
"e": 1755,
"s": 1747,
"text": "Syntax:"
},
{
"code": null,
"e": 1784,
"s": 1755,
"text": "seaborn.barplot( x, y, data)"
},
{
"code": null,
"e": 1792,
"s": 1784,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplotsns.barplot(x = 'class', y = 'fare', data = df) # Show the plotplt.show()",
"e": 2057,
"s": 1792,
"text": null
},
{
"code": null,
"e": 2068,
"s": 2057,
"text": "Output : "
},
{
"code": null,
"e": 2147,
"s": 2068,
"text": "Example 2: Draw a set of vertical bars with nested grouping by two variables. "
},
{
"code": null,
"e": 2207,
"s": 2147,
"text": "Creating a bar plot using hue parameter with two variables."
},
{
"code": null,
"e": 2215,
"s": 2207,
"text": "Syntax:"
},
{
"code": null,
"e": 2250,
"s": 2215,
"text": "seaborn.barplot( x, y, data, hue) "
},
{
"code": null,
"e": 2258,
"s": 2250,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplotsns.barplot(x = 'class', y = 'fare', hue = 'sex', data = df) # Show the plotplt.show()",
"e": 2536,
"s": 2258,
"text": null
},
{
"code": null,
"e": 2547,
"s": 2536,
"text": "Output : "
},
{
"code": null,
"e": 2587,
"s": 2547,
"text": "Example 3: shows a Horizontal barplot. "
},
{
"code": null,
"e": 2721,
"s": 2587,
"text": "exchange the data variable instead of two data variables then it means that the axis denotes each of these data variables as an axis."
},
{
"code": null,
"e": 2765,
"s": 2721,
"text": "X denotes an x-axis and y denote a y-axis. "
},
{
"code": null,
"e": 2773,
"s": 2765,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # fare v / s class horizontal barplotsns.barplot(x = 'fare', y = 'class', hue = 'sex', data = df) # Show the plotplt.show()",
"e": 3062,
"s": 2773,
"text": null
},
{
"code": null,
"e": 3073,
"s": 3062,
"text": "Output : "
},
{
"code": null,
"e": 3117,
"s": 3073,
"text": "Example 4: Plot all bars in a given order. "
},
{
"code": null,
"e": 3169,
"s": 3117,
"text": "Control barplot order by passing an explicit order."
},
{
"code": null,
"e": 3177,
"s": 3169,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplot in given ordersns.barplot(x = 'class', y = 'fare', data = df, order = [\"Third\", \"Second\", \"First\"]) # Show the plotplt.show()",
"e": 3506,
"s": 3177,
"text": null
},
{
"code": null,
"e": 3517,
"s": 3506,
"text": "Output : "
},
{
"code": null,
"e": 3585,
"s": 3517,
"text": "Example 5: Plot all bars in a single color using color attributes. "
},
{
"code": null,
"e": 3616,
"s": 3585,
"text": "Color for all of the elements."
},
{
"code": null,
"e": 3624,
"s": 3616,
"text": "Syntax:"
},
{
"code": null,
"e": 3660,
"s": 3624,
"text": "seaborn.barplot( x, y, data, color)"
},
{
"code": null,
"e": 3668,
"s": 3660,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplot with same coloursns.barplot(x = 'class', y = 'fare', data = df, color = \"salmon\") # Show the plotplt.show()",
"e": 3967,
"s": 3668,
"text": null
},
{
"code": null,
"e": 3978,
"s": 3967,
"text": "Output : "
},
{
"code": null,
"e": 4038,
"s": 3978,
"text": "Example 6: barplot without error bars using ci attributes. "
},
{
"code": null,
"e": 4133,
"s": 4038,
"text": "We will use None it means no bootstrapping will be performed, and error bars will not be drawn"
},
{
"code": null,
"e": 4141,
"s": 4133,
"text": "Syntax:"
},
{
"code": null,
"e": 4174,
"s": 4141,
"text": "seaborn.barplot( x, y, data, ci)"
},
{
"code": null,
"e": 4182,
"s": 4174,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') # class v / s fare barplot# without error barssns.barplot(x = 'class', y = 'fare', data = df, ci = None) # Show the plotplt.show()",
"e": 4478,
"s": 4182,
"text": null
},
{
"code": null,
"e": 4489,
"s": 4478,
"text": "Output : "
},
{
"code": null,
"e": 4574,
"s": 4489,
"text": "Example 7: Colors to use for the different levels of the hue variable using palette."
},
{
"code": null,
"e": 4764,
"s": 4574,
"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 barplot with different colormap values."
},
{
"code": null,
"e": 4772,
"s": 4764,
"text": "Syntax:"
},
{
"code": null,
"e": 4823,
"s": 4772,
"text": "seaborn.barplot( x, y, data, palette=”color_name”)"
},
{
"code": null,
"e": 4831,
"s": 4823,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') sns.barplot(x = 'class', y = 'fare', hue = 'sex', data = df, palette='pastel') # Show the plotplt.show()",
"e": 5112,
"s": 4831,
"text": null
},
{
"code": null,
"e": 5120,
"s": 5112,
"text": "Output:"
},
{
"code": null,
"e": 5152,
"s": 5120,
"text": "Possible values of palette are:"
},
{
"code": null,
"e": 5262,
"s": 5152,
"text": "Accent, Accent_r, Blues, Blues_r, BrBG, BrBG_r, BuGn, BuGn_r, BuPu, BuPu_r, CMRmap, CMRmap_r, Dark2, Dark2_r,"
},
{
"code": null,
"e": 5376,
"s": 5262,
"text": "GnBu, GnBu_r, Greens, Greens_r, Greys, Greys_r, OrRd, OrRd_r, Oranges, Oranges_r, PRGn, PRGn_r, Paired, Paired_r,"
},
{
"code": null,
"e": 5490,
"s": 5376,
"text": "Pastel1, Pastel1_r, Pastel2, Pastel2_r, PiYG, PiYG_r, PuBu, PuBuGn, PuBuGn_r, PuBu_r, PuOr, PuOr_r, PuRd, PuRd_r,"
},
{
"code": null,
"e": 5608,
"s": 5490,
"text": "Purples, Purples_r, RdBu, RdBu_r, RdGy, RdGy_r, RdPu, RdPu_r, RdYlBu, RdYlBu_r, RdYlGn, RdYlGn_r, Reds, Reds_r, Set1,"
},
{
"code": null,
"e": 5724,
"s": 5608,
"text": "Set1_r, Set2, Set2_r, Set3, Set3_r, Spectral, Spectral_r, Wistia, Wistia_r, YlGn, YlGnBu, YlGnBu_r, YlGn_r, YlOrBr,"
},
{
"code": null,
"e": 5844,
"s": 5724,
"text": "YlOrBr_r, YlOrRd, YlOrRd_r, afmhot, afmhot_r, autumn, autumn_r, binary, binary_r, bone, bone_r, brg, brg_r, bwr, bwr_r,"
},
{
"code": null,
"e": 5968,
"s": 5844,
"text": "cividis, cividis_r, cool, cool_r, coolwarm, coolwarm_r, copper, copper_r, cubehelix, cubehelix_r, flag, flag_r, gist_earth,"
},
{
"code": null,
"e": 6097,
"s": 5968,
"text": "gist_earth_r, gist_gray, gist_gray_r, gist_heat, gist_heat_r, gist_ncar, gist_ncar_r, gist_rainbow, gist_rainbow_r, gist_stern, "
},
{
"code": null,
"e": 6208,
"s": 6097,
"text": "Example 8: Using the statistical function NumPy.median and NumPy.mean to estimate within each categorical bin."
},
{
"code": null,
"e": 6216,
"s": 6208,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsfrom numpy import medianimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') sns.barplot(x = 'class', y = 'fare', hue = 'sex', data = df, estimator=median) # Show the plotplt.show()",
"e": 6510,
"s": 6216,
"text": null
},
{
"code": null,
"e": 6518,
"s": 6510,
"text": "Output:"
},
{
"code": null,
"e": 6534,
"s": 6518,
"text": "For Numpy.mean:"
},
{
"code": null,
"e": 6542,
"s": 6534,
"text": "Python3"
},
{
"code": "from numpy import meansns.barplot(x = 'class', y = 'fare', hue = 'sex', data = df, estimator=mean)",
"e": 6641,
"s": 6542,
"text": null
},
{
"code": null,
"e": 6649,
"s": 6641,
"text": "Output:"
},
{
"code": null,
"e": 6692,
"s": 6649,
"text": "Example 9: Using the saturation parameter."
},
{
"code": null,
"e": 6907,
"s": 6692,
"text": " The proportion of the original saturation to draw colors at. Large patches often look better with slightly desaturated colors, but set this to 1 if you want the plot colors to perfectly match the input color spec."
},
{
"code": null,
"e": 6915,
"s": 6907,
"text": "Syntax:"
},
{
"code": null,
"e": 6956,
"s": 6915,
"text": "seaborn.barplot( x, y, data, saturation)"
},
{
"code": null,
"e": 6964,
"s": 6956,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') sns.barplot(x = 'class', y = 'fare', hue = 'sex', data = df,saturation = 0.1) # Show the plotplt.show()",
"e": 7233,
"s": 6964,
"text": null
},
{
"code": null,
"e": 7241,
"s": 7233,
"text": "Output:"
},
{
"code": null,
"e": 7317,
"s": 7241,
"text": "Example 10: Use matplotlib.axes.Axes.bar() parameters to control the style."
},
{
"code": null,
"e": 7478,
"s": 7317,
"text": "We can set Width of the gray lines that frame the plot elements using linewidth. Whenever we increase linewidth than the point also will increase automatically."
},
{
"code": null,
"e": 7486,
"s": 7478,
"text": "Syntax:"
},
{
"code": null,
"e": 7536,
"s": 7486,
"text": "seaborn.barplot(x, y, data, linewidth, edgecolor)"
},
{
"code": null,
"e": 7544,
"s": 7536,
"text": "Python3"
},
{
"code": "# importing the required libraryimport seaborn as snsimport matplotlib.pyplot as plt # read a titanic.csv file# from seaborn librarydf = sns.load_dataset('titanic') sns.barplot(x=\"class\", y=\"fare\", data=df, linewidth=2.5, facecolor=(1, 1, 1, 0), errcolor=\".2\", edgecolor=\".2\")",
"e": 7853,
"s": 7544,
"text": null
},
{
"code": null,
"e": 7861,
"s": 7853,
"text": "Output:"
},
{
"code": null,
"e": 7876,
"s": 7863,
"text": "kumar_satyam"
},
{
"code": null,
"e": 7893,
"s": 7876,
"text": "surinderdawra388"
},
{
"code": null,
"e": 7908,
"s": 7893,
"text": "Python-Seaborn"
},
{
"code": null,
"e": 7915,
"s": 7908,
"text": "Python"
}
] |
PostgreSQL – Upsert
|
01 Feb, 2021
The UPSERT statement is a DBMS feature that allows a DML statement’s author to either insert a row or if the row already exists, UPDATE that existing row instead. That is why the action is known as UPSERT (simply a mix of Update and Insert).To achieve the functionality of UPSERT, PostgreSQL uses the INSERT ON CONFLICT statement.
INSERT INTO table_name(column_list)
VALUES(value_list)
ON CONFLICT target action;
If we analyze the above syntax:
The target can be :
(column_name) – any column name.ON CONSTRAINT constraint_name – where the constraint name could be the name of the UNIQUE constraint. WHERE predicate – a WHERE clause with a boolean condition.
(column_name) – any column name.
ON CONSTRAINT constraint_name – where the constraint name could be the name of the UNIQUE constraint.
WHERE predicate – a WHERE clause with a boolean condition.
The action can be :
DO NOTHING – If the row already exists in the table, then do nothing.DO UPDATE SET columnA = valueA, .... WHERE condition – update some fields in the table depending upon the condition.
DO NOTHING – If the row already exists in the table, then do nothing.
DO UPDATE SET columnA = valueA, .... WHERE condition – update some fields in the table depending upon the condition.
First, we create a sample table using the below commands to perform examples:
CREATE TABLE employees (
employee_id serial PRIMARY KEY,
full_name VARCHAR NOT NULL,
manager_id INT
);
Then we insert data into our employee table as follows:
INSERT INTO employees (
employee_id,
full_name,
manager_id
)
VALUES
(1, 'M.S Dhoni', NULL),
(2, 'Sachin Tendulkar', 1),
(3, 'R. Sharma', 1),
(4, 'S. Raina', 1),
(5, 'B. Kumar', 1),
(6, 'Y. Singh', 2),
(7, 'Virender Sehwag ', 2),
(8, 'Ajinkya Rahane', 2),
(9, 'Shikhar Dhawan', 2),
(10, 'Mohammed Shami', 3),
(11, 'Shreyas Iyer', 3),
(12, 'Mayank Agarwal', 3),
(13, 'K. L. Rahul', 3),
(14, 'Hardik Pandya', 4),
(15, 'Dinesh Karthik', 4),
(16, 'Jasprit Bumrah', 7),
(17, 'Kuldeep Yadav', 7),
(18, 'Yuzvendra Chahal', 8),
(19, 'Rishabh Pant', 8),
(20, 'Sanju Samson', 8);
The table is:
The below query is used to change the name of employee_id 6 (if such an employee exists) from Y. Singh to Yuvraj Singh or insert the record if such an employee does not exist.
insert into employees(employee_id,full_name)
values(6,'Yuvraj Singh')
on conflict(employee_id)
do
update set full_name=EXCLUDED.full_name;
To check the changes to the table, we use the following query:
select * from employees;
Output:
In this example, we tried to use the UPDATE clause as the action of the INSERT statement to update the name of the employee with ID 6 if the employee exists.
The below query is used to insert an employee with employee id 18 with the name ‘W. Sundar’ and manager id ‘6’ (if no record exists) but do nothing, in case, such a record is already present in the table.
insert into employees(employee_id,full_name,manager_id)
values(18,'W. Sundar',6)
on conflict (employee_id)
do nothing;
To check the changes to the table, we use the following query:
select * from employees;
Output:
In this example, nothing was changed in the table because employee with employee id 18 already exists and the action is to do nothing.
The below query is used to insert an employee with employee id 21 with the name ‘W. Sundar’ and manager id ‘6’ ( if no record exists ) but do nothing, in case, such a record is already present in the table.
insert into employees(employee_id,full_name,manager_id)
values(21,'W. Sundar',6)
on conflict (employee_id)
do nothing;
To check the changes to the table, we use the following query:
select * from employees;
Output:
In this example, a new record was inserted into the table as no existing employee was present in the table with employee id 21.
Picked
Technical Scripter 2020
PostgreSQL
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
PostgreSQL - Psql commands
PostgreSQL - Change Column Type
PostgreSQL - For Loops
PostgreSQL - LIMIT with OFFSET clause
PostgreSQL - Function Returning A Table
PostgreSQL - ARRAY_AGG() Function
PostgreSQL - Copy Table
PostgreSQL - DROP INDEX
How to use PostgreSQL Database in Django?
PostgreSQL - Identity Column
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2021"
},
{
"code": null,
"e": 359,
"s": 28,
"text": "The UPSERT statement is a DBMS feature that allows a DML statement’s author to either insert a row or if the row already exists, UPDATE that existing row instead. That is why the action is known as UPSERT (simply a mix of Update and Insert).To achieve the functionality of UPSERT, PostgreSQL uses the INSERT ON CONFLICT statement."
},
{
"code": null,
"e": 443,
"s": 359,
"text": "INSERT INTO table_name(column_list) \nVALUES(value_list)\nON CONFLICT target action;"
},
{
"code": null,
"e": 475,
"s": 443,
"text": "If we analyze the above syntax:"
},
{
"code": null,
"e": 495,
"s": 475,
"text": "The target can be :"
},
{
"code": null,
"e": 689,
"s": 495,
"text": "(column_name) – any column name.ON CONSTRAINT constraint_name – where the constraint name could be the name of the UNIQUE constraint. WHERE predicate – a WHERE clause with a boolean condition."
},
{
"code": null,
"e": 722,
"s": 689,
"text": "(column_name) – any column name."
},
{
"code": null,
"e": 824,
"s": 722,
"text": "ON CONSTRAINT constraint_name – where the constraint name could be the name of the UNIQUE constraint."
},
{
"code": null,
"e": 885,
"s": 824,
"text": " WHERE predicate – a WHERE clause with a boolean condition."
},
{
"code": null,
"e": 905,
"s": 885,
"text": "The action can be :"
},
{
"code": null,
"e": 1092,
"s": 905,
"text": "DO NOTHING – If the row already exists in the table, then do nothing.DO UPDATE SET columnA = valueA, .... WHERE condition – update some fields in the table depending upon the condition. "
},
{
"code": null,
"e": 1162,
"s": 1092,
"text": "DO NOTHING – If the row already exists in the table, then do nothing."
},
{
"code": null,
"e": 1280,
"s": 1162,
"text": "DO UPDATE SET columnA = valueA, .... WHERE condition – update some fields in the table depending upon the condition. "
},
{
"code": null,
"e": 1358,
"s": 1280,
"text": "First, we create a sample table using the below commands to perform examples:"
},
{
"code": null,
"e": 1464,
"s": 1358,
"text": "CREATE TABLE employees (\n employee_id serial PRIMARY KEY,\n full_name VARCHAR NOT NULL,\n manager_id INT\n);"
},
{
"code": null,
"e": 1520,
"s": 1464,
"text": "Then we insert data into our employee table as follows:"
},
{
"code": null,
"e": 2112,
"s": 1520,
"text": "INSERT INTO employees (\n employee_id,\n full_name,\n manager_id\n)\nVALUES\n (1, 'M.S Dhoni', NULL),\n (2, 'Sachin Tendulkar', 1),\n (3, 'R. Sharma', 1),\n (4, 'S. Raina', 1),\n (5, 'B. Kumar', 1),\n (6, 'Y. Singh', 2),\n (7, 'Virender Sehwag ', 2),\n (8, 'Ajinkya Rahane', 2),\n (9, 'Shikhar Dhawan', 2),\n (10, 'Mohammed Shami', 3),\n (11, 'Shreyas Iyer', 3),\n (12, 'Mayank Agarwal', 3),\n (13, 'K. L. Rahul', 3),\n (14, 'Hardik Pandya', 4),\n (15, 'Dinesh Karthik', 4),\n (16, 'Jasprit Bumrah', 7),\n (17, 'Kuldeep Yadav', 7),\n (18, 'Yuzvendra Chahal', 8),\n (19, 'Rishabh Pant', 8),\n (20, 'Sanju Samson', 8);"
},
{
"code": null,
"e": 2126,
"s": 2112,
"text": "The table is:"
},
{
"code": null,
"e": 2302,
"s": 2126,
"text": "The below query is used to change the name of employee_id 6 (if such an employee exists) from Y. Singh to Yuvraj Singh or insert the record if such an employee does not exist."
},
{
"code": null,
"e": 2442,
"s": 2302,
"text": "insert into employees(employee_id,full_name)\nvalues(6,'Yuvraj Singh')\non conflict(employee_id)\ndo\nupdate set full_name=EXCLUDED.full_name; "
},
{
"code": null,
"e": 2505,
"s": 2442,
"text": "To check the changes to the table, we use the following query:"
},
{
"code": null,
"e": 2530,
"s": 2505,
"text": "select * from employees;"
},
{
"code": null,
"e": 2538,
"s": 2530,
"text": "Output:"
},
{
"code": null,
"e": 2697,
"s": 2538,
"text": "In this example, we tried to use the UPDATE clause as the action of the INSERT statement to update the name of the employee with ID 6 if the employee exists. "
},
{
"code": null,
"e": 2904,
"s": 2697,
"text": "The below query is used to insert an employee with employee id 18 with the name ‘W. Sundar’ and manager id ‘6’ (if no record exists) but do nothing, in case, such a record is already present in the table. "
},
{
"code": null,
"e": 3023,
"s": 2904,
"text": "insert into employees(employee_id,full_name,manager_id)\nvalues(18,'W. Sundar',6)\non conflict (employee_id)\ndo nothing;"
},
{
"code": null,
"e": 3086,
"s": 3023,
"text": "To check the changes to the table, we use the following query:"
},
{
"code": null,
"e": 3111,
"s": 3086,
"text": "select * from employees;"
},
{
"code": null,
"e": 3119,
"s": 3111,
"text": "Output:"
},
{
"code": null,
"e": 3255,
"s": 3119,
"text": "In this example, nothing was changed in the table because employee with employee id 18 already exists and the action is to do nothing. "
},
{
"code": null,
"e": 3463,
"s": 3255,
"text": "The below query is used to insert an employee with employee id 21 with the name ‘W. Sundar’ and manager id ‘6’ ( if no record exists ) but do nothing, in case, such a record is already present in the table. "
},
{
"code": null,
"e": 3583,
"s": 3463,
"text": "insert into employees(employee_id,full_name,manager_id)\nvalues(21,'W. Sundar',6)\non conflict (employee_id)\ndo nothing; "
},
{
"code": null,
"e": 3646,
"s": 3583,
"text": "To check the changes to the table, we use the following query:"
},
{
"code": null,
"e": 3671,
"s": 3646,
"text": "select * from employees;"
},
{
"code": null,
"e": 3679,
"s": 3671,
"text": "Output:"
},
{
"code": null,
"e": 3808,
"s": 3679,
"text": "In this example, a new record was inserted into the table as no existing employee was present in the table with employee id 21. "
},
{
"code": null,
"e": 3815,
"s": 3808,
"text": "Picked"
},
{
"code": null,
"e": 3839,
"s": 3815,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3850,
"s": 3839,
"text": "PostgreSQL"
},
{
"code": null,
"e": 3869,
"s": 3850,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3967,
"s": 3869,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3994,
"s": 3967,
"text": "PostgreSQL - Psql commands"
},
{
"code": null,
"e": 4026,
"s": 3994,
"text": "PostgreSQL - Change Column Type"
},
{
"code": null,
"e": 4049,
"s": 4026,
"text": "PostgreSQL - For Loops"
},
{
"code": null,
"e": 4087,
"s": 4049,
"text": "PostgreSQL - LIMIT with OFFSET clause"
},
{
"code": null,
"e": 4127,
"s": 4087,
"text": "PostgreSQL - Function Returning A Table"
},
{
"code": null,
"e": 4161,
"s": 4127,
"text": "PostgreSQL - ARRAY_AGG() Function"
},
{
"code": null,
"e": 4185,
"s": 4161,
"text": "PostgreSQL - Copy Table"
},
{
"code": null,
"e": 4209,
"s": 4185,
"text": "PostgreSQL - DROP INDEX"
},
{
"code": null,
"e": 4251,
"s": 4209,
"text": "How to use PostgreSQL Database in Django?"
}
] |
How to Install cx_oracle in Python on Windows?
|
22 Sep, 2021
The cx_oracle package is used to connect with the Oracle database using python. In this, article, we will look into the process of installing the cx_oracle package on Windows.
The only thing that you need for installing the Scrapy module on Windows are:
Python
PIP or Conda (depending upon user preference)
If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command:
conda install cx_oracle
Type y for yes when prompted.
You will get a similar message once the installation is complete:
Make sure you follow the best practices for installation using conda as:
Use an environment for installation rather than in the base environment using the below command:
conda create -n my-env
conda activate my-env
Note: If your preferred method of installation is conda-forge, use the below command:
conda config --env --add channels conda-forge
To verify if Pywin32 has been successfully installed in your system run the below command in Anaconda Powershell Prompt:
conda list cx_oracle
You’ll get the below message if the installation is complete:
If you want the installation to be done through PIP, open up the Command Prompt and use the below command:
pip install cx_oracle
You will get a similar message once the installation is complete:
To verify if the cx_oracle package has been successfully installed in your system run the below command in Command Prompt:
python -m pip show cx_oracle
You’ll get the below message if the installation is complete:
how-to-install
Picked
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 204,
"s": 28,
"text": "The cx_oracle package is used to connect with the Oracle database using python. In this, article, we will look into the process of installing the cx_oracle package on Windows."
},
{
"code": null,
"e": 282,
"s": 204,
"text": "The only thing that you need for installing the Scrapy module on Windows are:"
},
{
"code": null,
"e": 290,
"s": 282,
"text": "Python "
},
{
"code": null,
"e": 336,
"s": 290,
"text": "PIP or Conda (depending upon user preference)"
},
{
"code": null,
"e": 458,
"s": 336,
"text": "If you want the installation to be done through conda, open up the Anaconda Powershell Prompt and use the below command:"
},
{
"code": null,
"e": 482,
"s": 458,
"text": "conda install cx_oracle"
},
{
"code": null,
"e": 512,
"s": 482,
"text": "Type y for yes when prompted."
},
{
"code": null,
"e": 578,
"s": 512,
"text": "You will get a similar message once the installation is complete:"
},
{
"code": null,
"e": 651,
"s": 578,
"text": "Make sure you follow the best practices for installation using conda as:"
},
{
"code": null,
"e": 748,
"s": 651,
"text": "Use an environment for installation rather than in the base environment using the below command:"
},
{
"code": null,
"e": 793,
"s": 748,
"text": "conda create -n my-env\nconda activate my-env"
},
{
"code": null,
"e": 879,
"s": 793,
"text": "Note: If your preferred method of installation is conda-forge, use the below command:"
},
{
"code": null,
"e": 925,
"s": 879,
"text": "conda config --env --add channels conda-forge"
},
{
"code": null,
"e": 1046,
"s": 925,
"text": "To verify if Pywin32 has been successfully installed in your system run the below command in Anaconda Powershell Prompt:"
},
{
"code": null,
"e": 1068,
"s": 1046,
"text": "conda list cx_oracle "
},
{
"code": null,
"e": 1130,
"s": 1068,
"text": "You’ll get the below message if the installation is complete:"
},
{
"code": null,
"e": 1238,
"s": 1130,
"text": "If you want the installation to be done through PIP, open up the Command Prompt and use the below command:"
},
{
"code": null,
"e": 1260,
"s": 1238,
"text": "pip install cx_oracle"
},
{
"code": null,
"e": 1326,
"s": 1260,
"text": "You will get a similar message once the installation is complete:"
},
{
"code": null,
"e": 1449,
"s": 1326,
"text": "To verify if the cx_oracle package has been successfully installed in your system run the below command in Command Prompt:"
},
{
"code": null,
"e": 1479,
"s": 1449,
"text": "python -m pip show cx_oracle "
},
{
"code": null,
"e": 1541,
"s": 1479,
"text": "You’ll get the below message if the installation is complete:"
},
{
"code": null,
"e": 1556,
"s": 1541,
"text": "how-to-install"
},
{
"code": null,
"e": 1563,
"s": 1556,
"text": "Picked"
},
{
"code": null,
"e": 1570,
"s": 1563,
"text": "How To"
},
{
"code": null,
"e": 1589,
"s": 1570,
"text": "Installation Guide"
}
] |
EOF, getc() and feof() in C
|
28 May, 2017
In C/C++, getc() returns EOF when end of file is reached. getc() also returns EOF when it fails. So, only comparing the value returned by getc() with EOF is not sufficient to check for actual end of file. To solve this problem, C provides feof() which returns non-zero value only if end of file has reached, otherwise it returns 0.For example, consider the following C program to print contents of file test.txt on screen. In the program, returned value of getc() is compared with EOF first, then there is another check using feof(). By putting this check, we make sure that the program prints “End of file reached” only if end of file is reached. And if getc() returns EOF due to any other reason, then the program prints “Something went wrong”
#include <stdio.h> int main(){ FILE *fp = fopen("test.txt", "r"); int ch = getc(fp); while (ch != EOF) { /* display contents of file on screen */ putchar(ch); ch = getc(fp); } if (feof(fp)) printf("\n End of file reached."); else printf("\n Something went wrong."); fclose(fp); getchar(); return 0;}
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-File Handling
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Different Methods to Reverse a String in C++
std::string class in C++
Unordered Sets in C++ Standard Template Library
What is the purpose of a function prototype?
Enumeration (or enum) in C
C Language Introduction
Operators in C / C++
Power Function in C/C++
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 May, 2017"
},
{
"code": null,
"e": 798,
"s": 52,
"text": "In C/C++, getc() returns EOF when end of file is reached. getc() also returns EOF when it fails. So, only comparing the value returned by getc() with EOF is not sufficient to check for actual end of file. To solve this problem, C provides feof() which returns non-zero value only if end of file has reached, otherwise it returns 0.For example, consider the following C program to print contents of file test.txt on screen. In the program, returned value of getc() is compared with EOF first, then there is another check using feof(). By putting this check, we make sure that the program prints “End of file reached” only if end of file is reached. And if getc() returns EOF due to any other reason, then the program prints “Something went wrong”"
},
{
"code": "#include <stdio.h> int main(){ FILE *fp = fopen(\"test.txt\", \"r\"); int ch = getc(fp); while (ch != EOF) { /* display contents of file on screen */ putchar(ch); ch = getc(fp); } if (feof(fp)) printf(\"\\n End of file reached.\"); else printf(\"\\n Something went wrong.\"); fclose(fp); getchar(); return 0;}",
"e": 1142,
"s": 798,
"text": null
},
{
"code": null,
"e": 1267,
"s": 1142,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 1283,
"s": 1267,
"text": "C-File Handling"
},
{
"code": null,
"e": 1294,
"s": 1283,
"text": "C Language"
},
{
"code": null,
"e": 1392,
"s": 1294,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1409,
"s": 1392,
"text": "Substring in C++"
},
{
"code": null,
"e": 1431,
"s": 1409,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 1476,
"s": 1431,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 1501,
"s": 1476,
"text": "std::string class in C++"
},
{
"code": null,
"e": 1549,
"s": 1501,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1594,
"s": 1549,
"text": "What is the purpose of a function prototype?"
},
{
"code": null,
"e": 1621,
"s": 1594,
"text": "Enumeration (or enum) in C"
},
{
"code": null,
"e": 1645,
"s": 1621,
"text": "C Language Introduction"
},
{
"code": null,
"e": 1666,
"s": 1645,
"text": "Operators in C / C++"
}
] |
Reading QR codes using Node.js
|
12 Feb, 2021
When we are working with Node.js to build any application, we might want our apps to interact with external apps or payment gateways that provide QR codes to communicate the information. In this article, we will see how we can decode a QR code in our node.js applications.
Let’s set up our workspace by executing these commands:
Creating directory:
npm init -y
mkdir src
cd src
nano app.js
Installing packages:
We need to install an npm package in order to work ahead.
To work with the qrcode-reader, we also need an image parser. Jimp Module is used for image parsing.
npm install qrcode-reader jimp
Suppose we have an image of a QR code in the same directory as our source code. We need the data embedded in the image.
First import all the packages in app.js
var Jimp = require("jimp");
var fs = require('fs')
var QrCode = require('qrcode-reader');
Now we need to load our QR code:
// Read the image and create a buffer
// (Here image.png is our QR code)
var buffer = fs.readFileSync(__dirname + '/image.png');
Parse the image using Jimp module and use decode() method of qrcode-reader package:
// Parse the image
Jimp.read(buffer, function(err, image) {
if (err) {
console.error(err);
}
let qrcode = new qrCode();
qrcode.callback = function(err, value) {
if (err) {
console.error(err);
}
console.log(value.result);
};
qrcode.decode(image.bitmap);
});
Here we can read the data that is in string format.
Index.js
Javascript
//Importing jimp modulevar Jimp = require("jimp");// Importing filesystem modulevar fs = require('fs')// Importing qrcode-reader modulevar qrCode = require('qrcode-reader'); // Read the image and create a buffer// (Here image.png is our QR code)var buffer = fs.readFileSync(__dirname + '/image.png'); // Parse the image using Jimp.read() methodJimp.read(buffer, function(err, image) { if (err) { console.error(err); } // Creating an instance of qrcode-reader module let qrcode = new qrCode(); qrcode.callback = function(err, value) { if (err) { console.error(err); } // Printing the decrypted value console.log(value.result); }; // Decoding the QR code qrcode.decode(image.bitmap);});
Run index.js file using the following command:
node index.js
Output:
Output data
mridulmanochagfg
Node.js-Misc
JavaScript
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Feb, 2021"
},
{
"code": null,
"e": 302,
"s": 28,
"text": "When we are working with Node.js to build any application, we might want our apps to interact with external apps or payment gateways that provide QR codes to communicate the information. In this article, we will see how we can decode a QR code in our node.js applications. "
},
{
"code": null,
"e": 358,
"s": 302,
"text": "Let’s set up our workspace by executing these commands:"
},
{
"code": null,
"e": 378,
"s": 358,
"text": "Creating directory:"
},
{
"code": null,
"e": 419,
"s": 378,
"text": "npm init -y\nmkdir src\ncd src\nnano app.js"
},
{
"code": null,
"e": 440,
"s": 419,
"text": "Installing packages:"
},
{
"code": null,
"e": 498,
"s": 440,
"text": "We need to install an npm package in order to work ahead."
},
{
"code": null,
"e": 599,
"s": 498,
"text": "To work with the qrcode-reader, we also need an image parser. Jimp Module is used for image parsing."
},
{
"code": null,
"e": 630,
"s": 599,
"text": "npm install qrcode-reader jimp"
},
{
"code": null,
"e": 750,
"s": 630,
"text": "Suppose we have an image of a QR code in the same directory as our source code. We need the data embedded in the image."
},
{
"code": null,
"e": 790,
"s": 750,
"text": "First import all the packages in app.js"
},
{
"code": null,
"e": 880,
"s": 790,
"text": "var Jimp = require(\"jimp\");\nvar fs = require('fs')\nvar QrCode = require('qrcode-reader');"
},
{
"code": null,
"e": 913,
"s": 880,
"text": "Now we need to load our QR code:"
},
{
"code": null,
"e": 1044,
"s": 913,
"text": "// Read the image and create a buffer \n// (Here image.png is our QR code)\nvar buffer = fs.readFileSync(__dirname + '/image.png');"
},
{
"code": null,
"e": 1128,
"s": 1044,
"text": "Parse the image using Jimp module and use decode() method of qrcode-reader package:"
},
{
"code": null,
"e": 1444,
"s": 1128,
"text": "// Parse the image \nJimp.read(buffer, function(err, image) {\n if (err) {\n console.error(err);\n }\n let qrcode = new qrCode();\n qrcode.callback = function(err, value) {\n if (err) {\n console.error(err);\n }\n console.log(value.result);\n };\n qrcode.decode(image.bitmap);\n});"
},
{
"code": null,
"e": 1496,
"s": 1444,
"text": "Here we can read the data that is in string format."
},
{
"code": null,
"e": 1505,
"s": 1496,
"text": "Index.js"
},
{
"code": null,
"e": 1516,
"s": 1505,
"text": "Javascript"
},
{
"code": "//Importing jimp modulevar Jimp = require(\"jimp\");// Importing filesystem modulevar fs = require('fs')// Importing qrcode-reader modulevar qrCode = require('qrcode-reader'); // Read the image and create a buffer// (Here image.png is our QR code)var buffer = fs.readFileSync(__dirname + '/image.png'); // Parse the image using Jimp.read() methodJimp.read(buffer, function(err, image) { if (err) { console.error(err); } // Creating an instance of qrcode-reader module let qrcode = new qrCode(); qrcode.callback = function(err, value) { if (err) { console.error(err); } // Printing the decrypted value console.log(value.result); }; // Decoding the QR code qrcode.decode(image.bitmap);});",
"e": 2271,
"s": 1516,
"text": null
},
{
"code": null,
"e": 2319,
"s": 2271,
"text": "Run index.js file using the following command: "
},
{
"code": null,
"e": 2333,
"s": 2319,
"text": "node index.js"
},
{
"code": null,
"e": 2341,
"s": 2333,
"text": "Output:"
},
{
"code": null,
"e": 2354,
"s": 2341,
"text": "Output data "
},
{
"code": null,
"e": 2371,
"s": 2354,
"text": "mridulmanochagfg"
},
{
"code": null,
"e": 2384,
"s": 2371,
"text": "Node.js-Misc"
},
{
"code": null,
"e": 2395,
"s": 2384,
"text": "JavaScript"
},
{
"code": null,
"e": 2403,
"s": 2395,
"text": "Node.js"
},
{
"code": null,
"e": 2420,
"s": 2403,
"text": "Web Technologies"
}
] |
How to use Facebook Graph API and extract data using Python! | by Ravi Ranjan | Towards Data Science
|
Hi all,
This is my second story on Medium.com. I have moved on from struggling to code to being a bit comfortable since the first story. I wrote a Python code to extract publicly available data on Facebook. Let’s dive into it.
Getting the Access Token:
To be able to extract data from Facebook using a python code you need to register as a developer on Facebook and then have an access token. Here are the steps for it.
Go to link developers.facebook.com, create an account there.Go to link developers.facebook.com/tools/explorer.Go to “My apps” drop down in the top right corner and select “add a new app”. Choose a display name and a category and then “Create App ID”.Again get back to the same link developers.facebook.com/tools/explorer. You will see “Graph API Explorer” below “My Apps” in the top right corner. From “Graph API Explorer” drop down, select your app.Then, select “Get Token”. From this drop down, select “Get User Access Token”. Select permissions from the menu that appears and then select “Get Access Token.”Go to link developers.facebook.com/tools/accesstoken. Select “Debug” corresponding to “User Token”. Go to “Extend Token Access”. This will ensure that your token does not expire every two hours.
Go to link developers.facebook.com, create an account there.
Go to link developers.facebook.com/tools/explorer.
Go to “My apps” drop down in the top right corner and select “add a new app”. Choose a display name and a category and then “Create App ID”.
Again get back to the same link developers.facebook.com/tools/explorer. You will see “Graph API Explorer” below “My Apps” in the top right corner. From “Graph API Explorer” drop down, select your app.
Then, select “Get Token”. From this drop down, select “Get User Access Token”. Select permissions from the menu that appears and then select “Get Access Token.”
Go to link developers.facebook.com/tools/accesstoken. Select “Debug” corresponding to “User Token”. Go to “Extend Token Access”. This will ensure that your token does not expire every two hours.
Python Code to Access Facebook Public Data:
Go to link https://developers.facebook.com/docs/graph-api if want to collect data on anything that is available publicly. See https://developers.facebook.com/docs/graph-api/reference/v2.7/. From this documentation, choose any field you want from which you want to extract data such as “groups” or “pages” etc. Go to examples of codes after having selected these and then select “facebook graph api” and you will get hints on how to extract information. This blog is primarily on getting events data.
First of all, import ‘urllib3’, ‘facebook’, ‘requests’ if they are already available. If not, download these libraries. Define a variable token and set its value to what you got above as “User Access Token”.
token= ‘aiufniqaefncqiuhfencioaeusKJBNfljabicnlkjshniuwnscslkjjndfi’
Getting list of Events:
Now to find information on events for any search term say “Poetry” and limiting those events’ number to 10000:
graph = facebook.GraphAPI(access_token=token, version = 2.7)events = graph.request(‘/search?q=Poetry&type=event&limit=10000’)
This will give a dictionary of all the events that have been created on Facebook and has string “Poetry” in its name. To get the list of events, do:
eventList = events[‘data’]
Extracting all information for a event from the list of events extracted above:
Get the EventID of the first event in the list by
eventid = eventList[1][‘id’]
For this EventID, get all information and set few variables which will be used later by:
event1 = graph.get_object(id=eventid, fields=’attending_count,can_guests_invite,category,cover,declined_count,description,end_time,guest_list_enabled,interested_count,is_canceled,is_page_owned,is_viewer_admin,maybe_count,noreply_count,owner,parent_group,place,ticket_uri,timezone,type,updated_time’)attenderscount = event1[‘attending_count’]declinerscount = event1[‘declined_count’]interestedcount = event1[‘interested_count’]maybecount = event1[‘maybe_count’]noreplycount = event1[‘noreply_count’]
Getting the list of all those who are attending an event and converting the response into json format:
attenders = requests.get(“https://graph.facebook.com/v2.7/"+eventid+"/attending?access_token="+token+”&limit=”+str(attenderscount)) attenders_json = attenders.json()
Getting the admins of the event:
admins = requests.get(“https://graph.facebook.com/v2.7/"+eventid+"/admins?access_token="+token)admins_json = admins.json()
And similarly you can extract other information such as photos/videos/feed of that event if you want.
Go to https://developers.facebook.com/docs/graph-api/reference/event/ and see “Edges” part in the documentation. See image
Now, let’s say, you want to have a list of all those who are interested in the event, click on ‘interested’ green word here. This will open up a new page:
Select ‘Graph API Explorer’ here. This will open a new page:
Here, in place of {event-id}, put the id of the event, like this:
Hit submit. Also, on the same page, you will find below ‘get code’ option
Select it to see the code. Select ‘curl’ in the pop up that appears and then get the same output in the python code, write it with requests.get as it has been shown in above examples.
Hope this helps those who are beginning to work with facebook graph API. I will be happy to hear your suggestions/questions/feedback.
If you found this blog of any value to you and if you are into cryptocurrencies and if you are generous, consider sending some ripples to the following address:
Destination Tag: 5973413
Wallet Address: rLdinLq5CJood9wdjY9ZCdgycK8KGevkUj
There are too many ifs in the above statement. Send only if all the three are true! Cryptocurrencies FTW!
|
[
{
"code": null,
"e": 179,
"s": 171,
"text": "Hi all,"
},
{
"code": null,
"e": 398,
"s": 179,
"text": "This is my second story on Medium.com. I have moved on from struggling to code to being a bit comfortable since the first story. I wrote a Python code to extract publicly available data on Facebook. Let’s dive into it."
},
{
"code": null,
"e": 424,
"s": 398,
"text": "Getting the Access Token:"
},
{
"code": null,
"e": 591,
"s": 424,
"text": "To be able to extract data from Facebook using a python code you need to register as a developer on Facebook and then have an access token. Here are the steps for it."
},
{
"code": null,
"e": 1396,
"s": 591,
"text": "Go to link developers.facebook.com, create an account there.Go to link developers.facebook.com/tools/explorer.Go to “My apps” drop down in the top right corner and select “add a new app”. Choose a display name and a category and then “Create App ID”.Again get back to the same link developers.facebook.com/tools/explorer. You will see “Graph API Explorer” below “My Apps” in the top right corner. From “Graph API Explorer” drop down, select your app.Then, select “Get Token”. From this drop down, select “Get User Access Token”. Select permissions from the menu that appears and then select “Get Access Token.”Go to link developers.facebook.com/tools/accesstoken. Select “Debug” corresponding to “User Token”. Go to “Extend Token Access”. This will ensure that your token does not expire every two hours."
},
{
"code": null,
"e": 1457,
"s": 1396,
"text": "Go to link developers.facebook.com, create an account there."
},
{
"code": null,
"e": 1508,
"s": 1457,
"text": "Go to link developers.facebook.com/tools/explorer."
},
{
"code": null,
"e": 1649,
"s": 1508,
"text": "Go to “My apps” drop down in the top right corner and select “add a new app”. Choose a display name and a category and then “Create App ID”."
},
{
"code": null,
"e": 1850,
"s": 1649,
"text": "Again get back to the same link developers.facebook.com/tools/explorer. You will see “Graph API Explorer” below “My Apps” in the top right corner. From “Graph API Explorer” drop down, select your app."
},
{
"code": null,
"e": 2011,
"s": 1850,
"text": "Then, select “Get Token”. From this drop down, select “Get User Access Token”. Select permissions from the menu that appears and then select “Get Access Token.”"
},
{
"code": null,
"e": 2206,
"s": 2011,
"text": "Go to link developers.facebook.com/tools/accesstoken. Select “Debug” corresponding to “User Token”. Go to “Extend Token Access”. This will ensure that your token does not expire every two hours."
},
{
"code": null,
"e": 2250,
"s": 2206,
"text": "Python Code to Access Facebook Public Data:"
},
{
"code": null,
"e": 2750,
"s": 2250,
"text": "Go to link https://developers.facebook.com/docs/graph-api if want to collect data on anything that is available publicly. See https://developers.facebook.com/docs/graph-api/reference/v2.7/. From this documentation, choose any field you want from which you want to extract data such as “groups” or “pages” etc. Go to examples of codes after having selected these and then select “facebook graph api” and you will get hints on how to extract information. This blog is primarily on getting events data."
},
{
"code": null,
"e": 2958,
"s": 2750,
"text": "First of all, import ‘urllib3’, ‘facebook’, ‘requests’ if they are already available. If not, download these libraries. Define a variable token and set its value to what you got above as “User Access Token”."
},
{
"code": null,
"e": 3027,
"s": 2958,
"text": "token= ‘aiufniqaefncqiuhfencioaeusKJBNfljabicnlkjshniuwnscslkjjndfi’"
},
{
"code": null,
"e": 3051,
"s": 3027,
"text": "Getting list of Events:"
},
{
"code": null,
"e": 3162,
"s": 3051,
"text": "Now to find information on events for any search term say “Poetry” and limiting those events’ number to 10000:"
},
{
"code": null,
"e": 3288,
"s": 3162,
"text": "graph = facebook.GraphAPI(access_token=token, version = 2.7)events = graph.request(‘/search?q=Poetry&type=event&limit=10000’)"
},
{
"code": null,
"e": 3437,
"s": 3288,
"text": "This will give a dictionary of all the events that have been created on Facebook and has string “Poetry” in its name. To get the list of events, do:"
},
{
"code": null,
"e": 3464,
"s": 3437,
"text": "eventList = events[‘data’]"
},
{
"code": null,
"e": 3544,
"s": 3464,
"text": "Extracting all information for a event from the list of events extracted above:"
},
{
"code": null,
"e": 3594,
"s": 3544,
"text": "Get the EventID of the first event in the list by"
},
{
"code": null,
"e": 3623,
"s": 3594,
"text": "eventid = eventList[1][‘id’]"
},
{
"code": null,
"e": 3712,
"s": 3623,
"text": "For this EventID, get all information and set few variables which will be used later by:"
},
{
"code": null,
"e": 4211,
"s": 3712,
"text": "event1 = graph.get_object(id=eventid, fields=’attending_count,can_guests_invite,category,cover,declined_count,description,end_time,guest_list_enabled,interested_count,is_canceled,is_page_owned,is_viewer_admin,maybe_count,noreply_count,owner,parent_group,place,ticket_uri,timezone,type,updated_time’)attenderscount = event1[‘attending_count’]declinerscount = event1[‘declined_count’]interestedcount = event1[‘interested_count’]maybecount = event1[‘maybe_count’]noreplycount = event1[‘noreply_count’]"
},
{
"code": null,
"e": 4314,
"s": 4211,
"text": "Getting the list of all those who are attending an event and converting the response into json format:"
},
{
"code": null,
"e": 4480,
"s": 4314,
"text": "attenders = requests.get(“https://graph.facebook.com/v2.7/\"+eventid+\"/attending?access_token=\"+token+”&limit=”+str(attenderscount)) attenders_json = attenders.json()"
},
{
"code": null,
"e": 4513,
"s": 4480,
"text": "Getting the admins of the event:"
},
{
"code": null,
"e": 4636,
"s": 4513,
"text": "admins = requests.get(“https://graph.facebook.com/v2.7/\"+eventid+\"/admins?access_token=\"+token)admins_json = admins.json()"
},
{
"code": null,
"e": 4738,
"s": 4636,
"text": "And similarly you can extract other information such as photos/videos/feed of that event if you want."
},
{
"code": null,
"e": 4861,
"s": 4738,
"text": "Go to https://developers.facebook.com/docs/graph-api/reference/event/ and see “Edges” part in the documentation. See image"
},
{
"code": null,
"e": 5016,
"s": 4861,
"text": "Now, let’s say, you want to have a list of all those who are interested in the event, click on ‘interested’ green word here. This will open up a new page:"
},
{
"code": null,
"e": 5077,
"s": 5016,
"text": "Select ‘Graph API Explorer’ here. This will open a new page:"
},
{
"code": null,
"e": 5143,
"s": 5077,
"text": "Here, in place of {event-id}, put the id of the event, like this:"
},
{
"code": null,
"e": 5217,
"s": 5143,
"text": "Hit submit. Also, on the same page, you will find below ‘get code’ option"
},
{
"code": null,
"e": 5401,
"s": 5217,
"text": "Select it to see the code. Select ‘curl’ in the pop up that appears and then get the same output in the python code, write it with requests.get as it has been shown in above examples."
},
{
"code": null,
"e": 5535,
"s": 5401,
"text": "Hope this helps those who are beginning to work with facebook graph API. I will be happy to hear your suggestions/questions/feedback."
},
{
"code": null,
"e": 5696,
"s": 5535,
"text": "If you found this blog of any value to you and if you are into cryptocurrencies and if you are generous, consider sending some ripples to the following address:"
},
{
"code": null,
"e": 5721,
"s": 5696,
"text": "Destination Tag: 5973413"
},
{
"code": null,
"e": 5772,
"s": 5721,
"text": "Wallet Address: rLdinLq5CJood9wdjY9ZCdgycK8KGevkUj"
}
] |
How to Set Up a PostgreSQL Database on Amazon RDS | by Elizabeth Ter Sahakyan | Towards Data Science
|
PostgreSQL is an open source object-relational database system that uses the SQL language for interactions and maintenance. It has been proven to be a highly scalable database solution because it allows you to manage terabytes of data and can handle many concurrent users. PostgreSQL is also ACID-compliant to ensure validity in the event of errors.
You should opt for a PostgreSQL database when you need to create relational databases, where data is organized into one or more tables of columns and rows using a unique key identifying each row. The rows in one table are usually linked to rows in other tables with that unique key.
While there are many places to host your PostgreSQL database, this article focuses specifically on hosting your database on Amazon Relational Database Service (Amazon RDS). Amazon RDS allows for setup of relational databases in the AWS cloud and it’s very easy to use.
If you’re just getting started with all the AWS services, hopefully you’ll find this helpful! For the majority of this article, I will go through the PostgreSQL setup on AWS and then I go over how to do some other useful database operations. If you already have your database set up, feel free to skip around! ⏭⏭
What is covered in this article:
How to create a PostgreSQL database in Amazon RDS
How to connect to a PostgreSQL database externally
How to create a table in a database using SQL
How to insert data into a table in a database using SQL
How to delete a table in a database using SQL
To create your Postgres database in AWS, first sign into your account and search RDS in the AWS Management Console. Click Databases on the left sidebar and you will be taken to a page that looks like this.
Click the orange Create database button on the top right and now you can get started on selecting options for your new database.
Select Standard Create so you can customize the database configuration.
We’re creating a Postgres database so select PostgreSQL and leave the default version 11.5-R1.
I went with the free tier since we’re testing!
You can either change the DB instance identifier and Master username or leave them as defaults. I changed mine to test-db and and left the default username postgres. You can also either have Amazon RDS generate a password for you, or you can specify your own. In this case, I specified my own.
The DB instance class determines the computation and memory capacity of an Amazon RDS DB instance. The DB instance class you need depends on your processing power and memory requirements (Amazon documentation)
This is where you want to select an instance that meets your memory requirements. For the free tier, we only have Burstable classes as an option and I left this part on the default db.t2.micro.
This is where you’ll specify the storage requirements for your database. You also have the option to enable storage autoscaling so your database is dynamic and scales automatically 🙂
Again, I just left the defaults, for storage type, allocated storage, maximum storage threshold, and left enable storage autoscaling checked ✅
This option is to create a standby database in case of an outage so that your database is always up and functioning. The option is unavailable on the free tier.
This is where you’ll specify the following connectivity configurations:
VPC — the VPC that defines the virtual networking environment for this DB instance
Subnet group — the subnet group that defines which subnets and IP ranges the DB instance can use
Public accessibility — whether the database is publicly accessible
VPC security group — the security groups that will allow incoming traffic outside your VPC
Availability zone — improves high availability by isolating failures from other Availability Zones
Database port — the TCP/IP port that the DB instance will use for application connections
I left all defaults except for the Publicly accessible section, which I changed to Yes so that my database will be accessible outside of the VPC, like from a Jupyter notebook.
In this section you can choose how you’d like to authenticate your database credentials from the following options:
Password authentication — Manage your database user credentials through your DB engine’s native password authentication features.
Password and IAM database authentication — Manage your database user credentials through your DB engine’s native password authentication features and IAM users and roles.
Password and Kerberos authentication — Manage your database user credentials through your DB engine’s native password authentication features and an AWS Managed Microsoft AD created with AWS Directory Service. This way, you can centrally store and manage user credentials, instead of individually for each DB instance.
Let’s go with Password authentication.
Finally, click create database on the bottom to start creating your database and you should see the following messages on your page. It will take a couple minutes!
Download the Jupyter notebook to follow along
We’ll be using the psycopg2 library to connect to the postgres database locally in a Jupyter notebook (you can also connect from your IDE or terminal). Go ahead and install psycopg2 using !pip install psycopg2-binary and then you can run the following code to connect.
NOTE: For POSTGRES_DBNAME, it never actually works when I put the real database name, in this case I named it test-db, and I have to put postgres instead. If it ends up not working with your given database name, try the default postgres and it will probably work.
import psycopg2 as ps# define credentials credentials = {'POSTGRES_ADDRESS' : '', # change to your endpoint 'POSTGRES_PORT' : '', # change to your port 'POSTGRES_USERNAME' : '', # change to your username 'POSTGRES_PASSWORD' : '', # change to your password 'POSTGRES_DBNAME' : ''} # change to your db name# create connection and cursor conn = ps.connect(host=credentials['POSTGRES_ADDRESS'], database=credentials['POSTGRES_DBNAME'], user=credentials['POSTGRES_USERNAME'], password=credentials['POSTGRES_PASSWORD'], port=credentials['POSTGRES_PORT'])cur = conn.cursor()
If you don’t get an error, you’ve successfully connected to your postgres database! 🎊
Now that you’ve successfully created a postgres database, let’s get a table in there.
First, verify what is in your database — there should be nothing. You can check using the following code which returns an empty list.
query = """SELECT * FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema';"""cur.execute(query)cur.fetchall()
Note: if you skipped parts of this article, make sure you’ve connected to the database first (see above) 😀
You can create your first table by running the following code:
cur.execute("""CREATE TABLE table_1 (column_1 integer, column_2 float, column_3 varchar(50), column_4 boolean);""")# Commit table creationconn.commit()
This creates a table named table_1 with 4columns. I’ve included some of the common SQL datatypes so you can change those up to the datatypes for your table.
If we run the code above that checks for tables in our database, we get the following response where we can see that our table_1 is now in the database:
[(‘public’, ‘table_1’, ‘postgres’, None, False, False, False, False)]
Bonus: if you want to systematically create a bunch of tables given a list of table names, you can use the following code:
table_list = [] # a list of string table namesfor table_name in table_list: cur.execute("""CREATE TABLE {table_name} (column_1 float, column_2 float, column_3 float, column_4 float);""".format(table_name=table_name))# Commit table creationconn.commit()
Now that you have a table in your postgres database, you can get started on inputting your data.
To insert one line of data, run the following code:
data = [1, 2.2, 'three', True]insert_query = """INSERT INTO table_8 (column_1, column_2, column_3, column_4) VALUES (%s, %s, %s, %s);"""# execute insertcur.execute(insert_query, data) # commit data insertconn.commit()
I put my data into a list, making sure that the datatypes match whatever was selected for the columns in my table. Make sure to customize the table you’re creating to match the datatypes that you’ll be inserting. Then I wrote my query to insert that list into the table, executed it, and commited that to the table. If you don’t commit the execution, your data will not save to the table.
Verify that the data was saved by fetching the data from the table:
The select statement returns the data that we inserted so we know it worked!
To insert many lines of data into the table, run the following code:
data = [[5, 5.5, 'five', True], [5, 5.5, 'five', True], [5, 5.5, 'five', True]]insert_query = """INSERT INTO table_1 (column_1, column_2, column_3, column_4) VALUES (%s, %s, %s, %s);"""# execute multiple insertscur.executemany(insert_query, data) # commit data insertconn.commit()
The difference here is that the variable data is a list of lists containing the data to be inserted. We also use cur.executemany instead of cur.execute to iterate through our data list and insert all of the inputs.
Again you can verify that three new rows of data were inserted using the simple select statement:
Now you can see that the select statement returns the 3 new rows that were added using the previous insert statement.
You’ll eventually want to delete this testing table and start your real work — or you probably messed something up like I always do 🙃
Delete or drop a table in a postgres database using the SQL command DROP TABLE:
cur.execute("""DROP TABLE table_1""")conn.commit()
Make sure you actually commit otherwise your table won’t get deleted! Verify the tables that your database contains using the code we previously used to check.
That’s it! Now you can set up your own PostgreSQL database on AWS, create tables, add data, and drop any tables you don’t need. If you follow the tutorials and catch any errors, please let me know so I can fix it!
You can also manage your PostgreSQL using a better user interface. I recommend pgAdmin, which can be downloaded for free here.
This article will eventually become part of a series of articles from lessons I learned with my team while working on a project called Cryptolytic (article will be written about this soon and linked here). It’s the guide we wish we had when working on the project.
The notebook containing all the code used in this article can be found here which is inside the repo of our Cryptolytic project — so if you’re curious, check it out!
Find me on twitter @elizabethets or connect with me on LinkedIn!
|
[
{
"code": null,
"e": 522,
"s": 172,
"text": "PostgreSQL is an open source object-relational database system that uses the SQL language for interactions and maintenance. It has been proven to be a highly scalable database solution because it allows you to manage terabytes of data and can handle many concurrent users. PostgreSQL is also ACID-compliant to ensure validity in the event of errors."
},
{
"code": null,
"e": 805,
"s": 522,
"text": "You should opt for a PostgreSQL database when you need to create relational databases, where data is organized into one or more tables of columns and rows using a unique key identifying each row. The rows in one table are usually linked to rows in other tables with that unique key."
},
{
"code": null,
"e": 1074,
"s": 805,
"text": "While there are many places to host your PostgreSQL database, this article focuses specifically on hosting your database on Amazon Relational Database Service (Amazon RDS). Amazon RDS allows for setup of relational databases in the AWS cloud and it’s very easy to use."
},
{
"code": null,
"e": 1387,
"s": 1074,
"text": "If you’re just getting started with all the AWS services, hopefully you’ll find this helpful! For the majority of this article, I will go through the PostgreSQL setup on AWS and then I go over how to do some other useful database operations. If you already have your database set up, feel free to skip around! ⏭⏭"
},
{
"code": null,
"e": 1420,
"s": 1387,
"text": "What is covered in this article:"
},
{
"code": null,
"e": 1470,
"s": 1420,
"text": "How to create a PostgreSQL database in Amazon RDS"
},
{
"code": null,
"e": 1521,
"s": 1470,
"text": "How to connect to a PostgreSQL database externally"
},
{
"code": null,
"e": 1567,
"s": 1521,
"text": "How to create a table in a database using SQL"
},
{
"code": null,
"e": 1623,
"s": 1567,
"text": "How to insert data into a table in a database using SQL"
},
{
"code": null,
"e": 1669,
"s": 1623,
"text": "How to delete a table in a database using SQL"
},
{
"code": null,
"e": 1875,
"s": 1669,
"text": "To create your Postgres database in AWS, first sign into your account and search RDS in the AWS Management Console. Click Databases on the left sidebar and you will be taken to a page that looks like this."
},
{
"code": null,
"e": 2004,
"s": 1875,
"text": "Click the orange Create database button on the top right and now you can get started on selecting options for your new database."
},
{
"code": null,
"e": 2076,
"s": 2004,
"text": "Select Standard Create so you can customize the database configuration."
},
{
"code": null,
"e": 2171,
"s": 2076,
"text": "We’re creating a Postgres database so select PostgreSQL and leave the default version 11.5-R1."
},
{
"code": null,
"e": 2218,
"s": 2171,
"text": "I went with the free tier since we’re testing!"
},
{
"code": null,
"e": 2512,
"s": 2218,
"text": "You can either change the DB instance identifier and Master username or leave them as defaults. I changed mine to test-db and and left the default username postgres. You can also either have Amazon RDS generate a password for you, or you can specify your own. In this case, I specified my own."
},
{
"code": null,
"e": 2722,
"s": 2512,
"text": "The DB instance class determines the computation and memory capacity of an Amazon RDS DB instance. The DB instance class you need depends on your processing power and memory requirements (Amazon documentation)"
},
{
"code": null,
"e": 2916,
"s": 2722,
"text": "This is where you want to select an instance that meets your memory requirements. For the free tier, we only have Burstable classes as an option and I left this part on the default db.t2.micro."
},
{
"code": null,
"e": 3099,
"s": 2916,
"text": "This is where you’ll specify the storage requirements for your database. You also have the option to enable storage autoscaling so your database is dynamic and scales automatically 🙂"
},
{
"code": null,
"e": 3242,
"s": 3099,
"text": "Again, I just left the defaults, for storage type, allocated storage, maximum storage threshold, and left enable storage autoscaling checked ✅"
},
{
"code": null,
"e": 3403,
"s": 3242,
"text": "This option is to create a standby database in case of an outage so that your database is always up and functioning. The option is unavailable on the free tier."
},
{
"code": null,
"e": 3475,
"s": 3403,
"text": "This is where you’ll specify the following connectivity configurations:"
},
{
"code": null,
"e": 3558,
"s": 3475,
"text": "VPC — the VPC that defines the virtual networking environment for this DB instance"
},
{
"code": null,
"e": 3655,
"s": 3558,
"text": "Subnet group — the subnet group that defines which subnets and IP ranges the DB instance can use"
},
{
"code": null,
"e": 3722,
"s": 3655,
"text": "Public accessibility — whether the database is publicly accessible"
},
{
"code": null,
"e": 3813,
"s": 3722,
"text": "VPC security group — the security groups that will allow incoming traffic outside your VPC"
},
{
"code": null,
"e": 3912,
"s": 3813,
"text": "Availability zone — improves high availability by isolating failures from other Availability Zones"
},
{
"code": null,
"e": 4002,
"s": 3912,
"text": "Database port — the TCP/IP port that the DB instance will use for application connections"
},
{
"code": null,
"e": 4178,
"s": 4002,
"text": "I left all defaults except for the Publicly accessible section, which I changed to Yes so that my database will be accessible outside of the VPC, like from a Jupyter notebook."
},
{
"code": null,
"e": 4294,
"s": 4178,
"text": "In this section you can choose how you’d like to authenticate your database credentials from the following options:"
},
{
"code": null,
"e": 4424,
"s": 4294,
"text": "Password authentication — Manage your database user credentials through your DB engine’s native password authentication features."
},
{
"code": null,
"e": 4595,
"s": 4424,
"text": "Password and IAM database authentication — Manage your database user credentials through your DB engine’s native password authentication features and IAM users and roles."
},
{
"code": null,
"e": 4914,
"s": 4595,
"text": "Password and Kerberos authentication — Manage your database user credentials through your DB engine’s native password authentication features and an AWS Managed Microsoft AD created with AWS Directory Service. This way, you can centrally store and manage user credentials, instead of individually for each DB instance."
},
{
"code": null,
"e": 4953,
"s": 4914,
"text": "Let’s go with Password authentication."
},
{
"code": null,
"e": 5117,
"s": 4953,
"text": "Finally, click create database on the bottom to start creating your database and you should see the following messages on your page. It will take a couple minutes!"
},
{
"code": null,
"e": 5163,
"s": 5117,
"text": "Download the Jupyter notebook to follow along"
},
{
"code": null,
"e": 5432,
"s": 5163,
"text": "We’ll be using the psycopg2 library to connect to the postgres database locally in a Jupyter notebook (you can also connect from your IDE or terminal). Go ahead and install psycopg2 using !pip install psycopg2-binary and then you can run the following code to connect."
},
{
"code": null,
"e": 5696,
"s": 5432,
"text": "NOTE: For POSTGRES_DBNAME, it never actually works when I put the real database name, in this case I named it test-db, and I have to put postgres instead. If it ends up not working with your given database name, try the default postgres and it will probably work."
},
{
"code": null,
"e": 6391,
"s": 5696,
"text": "import psycopg2 as ps# define credentials credentials = {'POSTGRES_ADDRESS' : '', # change to your endpoint 'POSTGRES_PORT' : '', # change to your port 'POSTGRES_USERNAME' : '', # change to your username 'POSTGRES_PASSWORD' : '', # change to your password 'POSTGRES_DBNAME' : ''} # change to your db name# create connection and cursor conn = ps.connect(host=credentials['POSTGRES_ADDRESS'], database=credentials['POSTGRES_DBNAME'], user=credentials['POSTGRES_USERNAME'], password=credentials['POSTGRES_PASSWORD'], port=credentials['POSTGRES_PORT'])cur = conn.cursor()"
},
{
"code": null,
"e": 6477,
"s": 6391,
"text": "If you don’t get an error, you’ve successfully connected to your postgres database! 🎊"
},
{
"code": null,
"e": 6563,
"s": 6477,
"text": "Now that you’ve successfully created a postgres database, let’s get a table in there."
},
{
"code": null,
"e": 6697,
"s": 6563,
"text": "First, verify what is in your database — there should be nothing. You can check using the following code which returns an empty list."
},
{
"code": null,
"e": 6873,
"s": 6697,
"text": "query = \"\"\"SELECT * FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema';\"\"\"cur.execute(query)cur.fetchall()"
},
{
"code": null,
"e": 6980,
"s": 6873,
"text": "Note: if you skipped parts of this article, make sure you’ve connected to the database first (see above) 😀"
},
{
"code": null,
"e": 7043,
"s": 6980,
"text": "You can create your first table by running the following code:"
},
{
"code": null,
"e": 7256,
"s": 7043,
"text": "cur.execute(\"\"\"CREATE TABLE table_1 (column_1 integer, column_2 float, column_3 varchar(50), column_4 boolean);\"\"\")# Commit table creationconn.commit()"
},
{
"code": null,
"e": 7413,
"s": 7256,
"text": "This creates a table named table_1 with 4columns. I’ve included some of the common SQL datatypes so you can change those up to the datatypes for your table."
},
{
"code": null,
"e": 7566,
"s": 7413,
"text": "If we run the code above that checks for tables in our database, we get the following response where we can see that our table_1 is now in the database:"
},
{
"code": null,
"e": 7636,
"s": 7566,
"text": "[(‘public’, ‘table_1’, ‘postgres’, None, False, False, False, False)]"
},
{
"code": null,
"e": 7759,
"s": 7636,
"text": "Bonus: if you want to systematically create a bunch of tables given a list of table names, you can use the following code:"
},
{
"code": null,
"e": 8075,
"s": 7759,
"text": "table_list = [] # a list of string table namesfor table_name in table_list: cur.execute(\"\"\"CREATE TABLE {table_name} (column_1 float, column_2 float, column_3 float, column_4 float);\"\"\".format(table_name=table_name))# Commit table creationconn.commit()"
},
{
"code": null,
"e": 8172,
"s": 8075,
"text": "Now that you have a table in your postgres database, you can get started on inputting your data."
},
{
"code": null,
"e": 8224,
"s": 8172,
"text": "To insert one line of data, run the following code:"
},
{
"code": null,
"e": 8489,
"s": 8224,
"text": "data = [1, 2.2, 'three', True]insert_query = \"\"\"INSERT INTO table_8 (column_1, column_2, column_3, column_4) VALUES (%s, %s, %s, %s);\"\"\"# execute insertcur.execute(insert_query, data) # commit data insertconn.commit()"
},
{
"code": null,
"e": 8878,
"s": 8489,
"text": "I put my data into a list, making sure that the datatypes match whatever was selected for the columns in my table. Make sure to customize the table you’re creating to match the datatypes that you’ll be inserting. Then I wrote my query to insert that list into the table, executed it, and commited that to the table. If you don’t commit the execution, your data will not save to the table."
},
{
"code": null,
"e": 8946,
"s": 8878,
"text": "Verify that the data was saved by fetching the data from the table:"
},
{
"code": null,
"e": 9023,
"s": 8946,
"text": "The select statement returns the data that we inserted so we know it worked!"
},
{
"code": null,
"e": 9092,
"s": 9023,
"text": "To insert many lines of data into the table, run the following code:"
},
{
"code": null,
"e": 9420,
"s": 9092,
"text": "data = [[5, 5.5, 'five', True], [5, 5.5, 'five', True], [5, 5.5, 'five', True]]insert_query = \"\"\"INSERT INTO table_1 (column_1, column_2, column_3, column_4) VALUES (%s, %s, %s, %s);\"\"\"# execute multiple insertscur.executemany(insert_query, data) # commit data insertconn.commit()"
},
{
"code": null,
"e": 9635,
"s": 9420,
"text": "The difference here is that the variable data is a list of lists containing the data to be inserted. We also use cur.executemany instead of cur.execute to iterate through our data list and insert all of the inputs."
},
{
"code": null,
"e": 9733,
"s": 9635,
"text": "Again you can verify that three new rows of data were inserted using the simple select statement:"
},
{
"code": null,
"e": 9851,
"s": 9733,
"text": "Now you can see that the select statement returns the 3 new rows that were added using the previous insert statement."
},
{
"code": null,
"e": 9985,
"s": 9851,
"text": "You’ll eventually want to delete this testing table and start your real work — or you probably messed something up like I always do 🙃"
},
{
"code": null,
"e": 10065,
"s": 9985,
"text": "Delete or drop a table in a postgres database using the SQL command DROP TABLE:"
},
{
"code": null,
"e": 10116,
"s": 10065,
"text": "cur.execute(\"\"\"DROP TABLE table_1\"\"\")conn.commit()"
},
{
"code": null,
"e": 10276,
"s": 10116,
"text": "Make sure you actually commit otherwise your table won’t get deleted! Verify the tables that your database contains using the code we previously used to check."
},
{
"code": null,
"e": 10490,
"s": 10276,
"text": "That’s it! Now you can set up your own PostgreSQL database on AWS, create tables, add data, and drop any tables you don’t need. If you follow the tutorials and catch any errors, please let me know so I can fix it!"
},
{
"code": null,
"e": 10617,
"s": 10490,
"text": "You can also manage your PostgreSQL using a better user interface. I recommend pgAdmin, which can be downloaded for free here."
},
{
"code": null,
"e": 10882,
"s": 10617,
"text": "This article will eventually become part of a series of articles from lessons I learned with my team while working on a project called Cryptolytic (article will be written about this soon and linked here). It’s the guide we wish we had when working on the project."
},
{
"code": null,
"e": 11048,
"s": 10882,
"text": "The notebook containing all the code used in this article can be found here which is inside the repo of our Cryptolytic project — so if you’re curious, check it out!"
}
] |
How to build an MLOps pipeline for hyperparameter tuning in Vertex AI | by Lak Lakshmanan | Towards Data Science
|
When you design a machine learning model, there are a number of hyperparameters — learning rate, batch size, number of layers/nodes in the neural network, number of buckets, number of embedding dimensions, etc. that you essentially guess. There is usually a 2-10% improvement to be had over the initial guess by finding optimal values of these hyperparameters. (Of course, this depends on how bad your initial guess was, but I’ll assume you made somewhat educated guesses).
In an earlier article, I suggested that you use Jupyter notebooks for experimentation, but move to a normal Python file once things stabilize. Doing so separates out the responsibilities between ML development and MLOps. So, let’s say you have done that and your model training file exists as model.py and your pipeline orchestrator as train_on_vertexai.py. You might find it helpful to use the code in the two links to follow along as you read the article.
The first step is to make the hyperparameters command-line parameters to your model. For example, in model.py, we might do:
parser.add_argument( '--nembeds', help='Embedding dimension for categorical variables', type=int, default=3 )
Note that the initial guess for the variable is the default value. This allows your training script to continue working as it did before. Then, you set the variable from the command-line parameters for use by the training script:
args = parser.parse_args()...NEMBEDS = args['nembeds']
Do this for all the hyperparameters you might ever want to tune now, or in the future. A good practice is to never have any hardcoded values in model.py — everything there needs to be an input parameter.
Typically, your training run will involve training on the full dataset and then evaluating on the full test dataset. Doing a complete training run for hyperparameter tuning is expensive, wasteful, and wrong. Why?
Expensive: The point of hyperparameter tuning is to obtain the best set of parameters, not to obtain the best possible model. Once you find the best of parameters, you will then train a model with those parameters to completion. Therefore, there is no need to carry out a trial to completion. You just need to train it until you know which trial is likely to end up better.
Wasteful: Under the assumption that your training curves are well-behaved, a better set of parameters will be better throughout the training process, and you can stop the training well before it starts to converge. Use your training budget to do more trials, not to run those trials longer.
Wrong: You don’t want to evaluate the hyperparameter tuning on the test dataset. You want to compare performance on the validation dataset. Just make sure that the validation dataset is large enough for you to do this comparison between trial models meaningfully.
The way I do these modifications is to add two options to my model.py: one to train for a shorter time and another to skip the full evaluation:
NUM_EXAMPLES = args['num_examples']SKIP_FULL_EVAL = args['skip_full_eval']...steps_per_epoch = NUM_EXAMPLES // train_batch_sizeepochs = NUM_EPOCHSeval_dataset = read_dataset(eval_data_pattern, eval_batch_size, tf.estimator.ModeKeys.EVAL, num_eval_examples)model.fit(train_dataset, validation_data=eval_dataset, epochs=NUM_EPOCHS, steps_per_epoch=steps_per_epoch, callbacks=[cp_callback, HpCallback()])...if not SKIP_FULL_EVAL: test_dataset = read_dataset(test_data_pattern, eval_batch_size, tf.estimator.ModeKeys.TEST, None) final_metrics = model.evaluate(test_dataset) ...else: logging.info("Skipping evaluation on full test dataset")
What’s the deal with steps_per_epoch and NUM_EXAMPLES? Note the x-axis in the graph above. It’s not epochs — it’s the number of examples. While it’s pretty wasteful to train on the full dataset, it can be helpful to get the same number of intermediate metrics that you would get with the full amount of training (I’ll explain why in the next step). Because you will also be hyperparameter tuning the batch size, the best way to do this is to use Virtual Epochs (see the Machine Learning Design Patterns book: Checkpoints for details). Steps-per-epoch is how we get virtual epochs on large datasets.
Write out metrics during the training process. Don’t just wait until the end. If you do this, then Vertex AI will also help you save you costs by cutting short unproductive trials.
In Keras, to write out metrics during training you can use a callback. This is what that looks like:
METRIC = 'val_rmse'hpt = hypertune.HyperTune()class HpCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): if logs and METRIC in logs: logging.info("Epoch {}: {} = {}".format(epoch, METRIC, logs[METRIC])) hpt.report_hyperparameter_tuning_metric(hyperparameter_metric_tag=METRIC, metric_value=logs[METRIC], global_step=epoch)...history = model.fit(train_dataset, ... callbacks=[cp_callback, HpCallback()])
I’m using the cloudml-hypertune package to simplify the writing of metrics in a form that the TensorFlow ecosystem (TensorBoard, Vizier, etc.) can understand.
Now that you have modified model.py to make it easy to do hyperparameter tuning, the MLOps people can tune your model anytime they notice it drifting.
There are two steps in the orchestration code (in train_on_vertexai.py):
(4a) Create a Vertex AI CustomJob to call your model.py with the right parameters:
tf_version = '2-' + tf.__version__[2:3] train_image = "us-docker.pkg.dev/vertex-ai/training/tf-gpu.{}:latest".format(tf_version) model_display_name = '{}-{}'.format(ENDPOINT_NAME, timestamp) trial_job = aiplatform.CustomJob.from_local_script( display_name='train-{}'.format(model_display_name), script_path="model.py", container_uri=train_image, args=[ '--bucket', BUCKET, '--skip_full_eval', # no need to evaluate on test data '--num_epochs', '10', '--num_examples', '500000' # 1/10 actual size ], requirements=['cloudml-hypertune'], # hpt replica_count=1, machine_type='n1-standard-4', # See https://cloud.google.com/vertex-ai/docs/general/locations#accelerators accelerator_type=aip.AcceleratorType.NVIDIA_TESLA_T4.name, accelerator_count=1, )
(4b) Create and run a hyperparameter tuning job that will use the above job as an individual trial:
hparam_job = aiplatform.HyperparameterTuningJob( # See https://googleapis.dev/python/aiplatform/latest/aiplatform.html# display_name='hparam-{}'.format(model_display_name), custom_job=trial_job, metric_spec={'val_rmse': 'minimize'}, parameter_spec={ "train_batch_size": hpt.IntegerParameterSpec(min=16, max=256, scale='log'), "nbuckets": hpt.IntegerParameterSpec(min=5, max=10, scale='linear'), "dnn_hidden_units": hpt.CategoricalParameterSpec(values=["64,16", "64,16,4", "64,64,64,8", "256,64,16"]) }, max_trial_count=4 if develop_mode else 10, parallel_trial_count=2, search_algorithm=None, # Bayesian )
Note that I am specifying the metric here to match the METRIC in my model.py and that I’m specifying ranges for the parameters.
By default, the hyperparameter tuning service in Vertex AI (called Vizier) will use Bayesian Optimization, but you can change the algorithm to GridSearch if you want.
Once you launch the hyperparameter tuning job, you can look at the Vertex AI section of the GCP console to see the parameters come in.
You’ll see something like this:
Once you determine the best set of parameters, take the best set of parameters and then run the training job to completion. That will give you the model to deploy.
We can automate this as well, of course:
best = sorted(hparam_job.trials, key=lambda x: x.final_measurement.metrics[0].value)[0] logging.info('Best trial: {}'.format(best)) best_params = [] for param in best.parameters: best_params.append('--{}'.format(param.parameter_id)) best_params.append(param.value) # run the best trial to completion model = train_custom_model(data_set, timestamp, develop_mode, extra_args=best_params)
Again, separation of responsibilities between the data scientist (deciding what the parameters are, that can be optimized) and the MLOps engineer (deciding when to retune the model) is made easier through Vertex AI.
Enjoy!
Giving Vertex AI, the New Unified ML Platform on Google Cloud, a Spin:Why do we need it, how good is the code-free ML training, really, and what does all this mean for data science jobs?How to Deploy a TensorFlow Model to Vertex AI: Working with saved models and endpoints in Vertex AIDeveloping and Deploying a Machine Learning Model on Vertex AI using Python: Write training pipelines that will make your MLOps team happyHow to build an MLOps pipeline for hyperparameter tuning in Vertex AI:Best practices to set up your model and orchestrator for hyperparameter tuning
Giving Vertex AI, the New Unified ML Platform on Google Cloud, a Spin:Why do we need it, how good is the code-free ML training, really, and what does all this mean for data science jobs?
How to Deploy a TensorFlow Model to Vertex AI: Working with saved models and endpoints in Vertex AI
Developing and Deploying a Machine Learning Model on Vertex AI using Python: Write training pipelines that will make your MLOps team happy
How to build an MLOps pipeline for hyperparameter tuning in Vertex AI:Best practices to set up your model and orchestrator for hyperparameter tuning
|
[
{
"code": null,
"e": 646,
"s": 172,
"text": "When you design a machine learning model, there are a number of hyperparameters — learning rate, batch size, number of layers/nodes in the neural network, number of buckets, number of embedding dimensions, etc. that you essentially guess. There is usually a 2-10% improvement to be had over the initial guess by finding optimal values of these hyperparameters. (Of course, this depends on how bad your initial guess was, but I’ll assume you made somewhat educated guesses)."
},
{
"code": null,
"e": 1104,
"s": 646,
"text": "In an earlier article, I suggested that you use Jupyter notebooks for experimentation, but move to a normal Python file once things stabilize. Doing so separates out the responsibilities between ML development and MLOps. So, let’s say you have done that and your model training file exists as model.py and your pipeline orchestrator as train_on_vertexai.py. You might find it helpful to use the code in the two links to follow along as you read the article."
},
{
"code": null,
"e": 1228,
"s": 1104,
"text": "The first step is to make the hyperparameters command-line parameters to your model. For example, in model.py, we might do:"
},
{
"code": null,
"e": 1369,
"s": 1228,
"text": "parser.add_argument( '--nembeds', help='Embedding dimension for categorical variables', type=int, default=3 )"
},
{
"code": null,
"e": 1599,
"s": 1369,
"text": "Note that the initial guess for the variable is the default value. This allows your training script to continue working as it did before. Then, you set the variable from the command-line parameters for use by the training script:"
},
{
"code": null,
"e": 1654,
"s": 1599,
"text": "args = parser.parse_args()...NEMBEDS = args['nembeds']"
},
{
"code": null,
"e": 1858,
"s": 1654,
"text": "Do this for all the hyperparameters you might ever want to tune now, or in the future. A good practice is to never have any hardcoded values in model.py — everything there needs to be an input parameter."
},
{
"code": null,
"e": 2071,
"s": 1858,
"text": "Typically, your training run will involve training on the full dataset and then evaluating on the full test dataset. Doing a complete training run for hyperparameter tuning is expensive, wasteful, and wrong. Why?"
},
{
"code": null,
"e": 2445,
"s": 2071,
"text": "Expensive: The point of hyperparameter tuning is to obtain the best set of parameters, not to obtain the best possible model. Once you find the best of parameters, you will then train a model with those parameters to completion. Therefore, there is no need to carry out a trial to completion. You just need to train it until you know which trial is likely to end up better."
},
{
"code": null,
"e": 2736,
"s": 2445,
"text": "Wasteful: Under the assumption that your training curves are well-behaved, a better set of parameters will be better throughout the training process, and you can stop the training well before it starts to converge. Use your training budget to do more trials, not to run those trials longer."
},
{
"code": null,
"e": 3000,
"s": 2736,
"text": "Wrong: You don’t want to evaluate the hyperparameter tuning on the test dataset. You want to compare performance on the validation dataset. Just make sure that the validation dataset is large enough for you to do this comparison between trial models meaningfully."
},
{
"code": null,
"e": 3144,
"s": 3000,
"text": "The way I do these modifications is to add two options to my model.py: one to train for a shorter time and another to skip the full evaluation:"
},
{
"code": null,
"e": 3919,
"s": 3144,
"text": "NUM_EXAMPLES = args['num_examples']SKIP_FULL_EVAL = args['skip_full_eval']...steps_per_epoch = NUM_EXAMPLES // train_batch_sizeepochs = NUM_EPOCHSeval_dataset = read_dataset(eval_data_pattern, eval_batch_size, tf.estimator.ModeKeys.EVAL, num_eval_examples)model.fit(train_dataset, validation_data=eval_dataset, epochs=NUM_EPOCHS, steps_per_epoch=steps_per_epoch, callbacks=[cp_callback, HpCallback()])...if not SKIP_FULL_EVAL: test_dataset = read_dataset(test_data_pattern, eval_batch_size, tf.estimator.ModeKeys.TEST, None) final_metrics = model.evaluate(test_dataset) ...else: logging.info(\"Skipping evaluation on full test dataset\")"
},
{
"code": null,
"e": 4518,
"s": 3919,
"text": "What’s the deal with steps_per_epoch and NUM_EXAMPLES? Note the x-axis in the graph above. It’s not epochs — it’s the number of examples. While it’s pretty wasteful to train on the full dataset, it can be helpful to get the same number of intermediate metrics that you would get with the full amount of training (I’ll explain why in the next step). Because you will also be hyperparameter tuning the batch size, the best way to do this is to use Virtual Epochs (see the Machine Learning Design Patterns book: Checkpoints for details). Steps-per-epoch is how we get virtual epochs on large datasets."
},
{
"code": null,
"e": 4699,
"s": 4518,
"text": "Write out metrics during the training process. Don’t just wait until the end. If you do this, then Vertex AI will also help you save you costs by cutting short unproductive trials."
},
{
"code": null,
"e": 4800,
"s": 4699,
"text": "In Keras, to write out metrics during training you can use a callback. This is what that looks like:"
},
{
"code": null,
"e": 5319,
"s": 4800,
"text": "METRIC = 'val_rmse'hpt = hypertune.HyperTune()class HpCallback(tf.keras.callbacks.Callback): def on_epoch_end(self, epoch, logs=None): if logs and METRIC in logs: logging.info(\"Epoch {}: {} = {}\".format(epoch, METRIC, logs[METRIC])) hpt.report_hyperparameter_tuning_metric(hyperparameter_metric_tag=METRIC, metric_value=logs[METRIC], global_step=epoch)...history = model.fit(train_dataset, ... callbacks=[cp_callback, HpCallback()])"
},
{
"code": null,
"e": 5478,
"s": 5319,
"text": "I’m using the cloudml-hypertune package to simplify the writing of metrics in a form that the TensorFlow ecosystem (TensorBoard, Vizier, etc.) can understand."
},
{
"code": null,
"e": 5629,
"s": 5478,
"text": "Now that you have modified model.py to make it easy to do hyperparameter tuning, the MLOps people can tune your model anytime they notice it drifting."
},
{
"code": null,
"e": 5702,
"s": 5629,
"text": "There are two steps in the orchestration code (in train_on_vertexai.py):"
},
{
"code": null,
"e": 5785,
"s": 5702,
"text": "(4a) Create a Vertex AI CustomJob to call your model.py with the right parameters:"
},
{
"code": null,
"e": 6670,
"s": 5785,
"text": " tf_version = '2-' + tf.__version__[2:3] train_image = \"us-docker.pkg.dev/vertex-ai/training/tf-gpu.{}:latest\".format(tf_version) model_display_name = '{}-{}'.format(ENDPOINT_NAME, timestamp) trial_job = aiplatform.CustomJob.from_local_script( display_name='train-{}'.format(model_display_name), script_path=\"model.py\", container_uri=train_image, args=[ '--bucket', BUCKET, '--skip_full_eval', # no need to evaluate on test data '--num_epochs', '10', '--num_examples', '500000' # 1/10 actual size ], requirements=['cloudml-hypertune'], # hpt replica_count=1, machine_type='n1-standard-4', # See https://cloud.google.com/vertex-ai/docs/general/locations#accelerators accelerator_type=aip.AcceleratorType.NVIDIA_TESLA_T4.name, accelerator_count=1, )"
},
{
"code": null,
"e": 6770,
"s": 6670,
"text": "(4b) Create and run a hyperparameter tuning job that will use the above job as an individual trial:"
},
{
"code": null,
"e": 7479,
"s": 6770,
"text": " hparam_job = aiplatform.HyperparameterTuningJob( # See https://googleapis.dev/python/aiplatform/latest/aiplatform.html# display_name='hparam-{}'.format(model_display_name), custom_job=trial_job, metric_spec={'val_rmse': 'minimize'}, parameter_spec={ \"train_batch_size\": hpt.IntegerParameterSpec(min=16, max=256, scale='log'), \"nbuckets\": hpt.IntegerParameterSpec(min=5, max=10, scale='linear'), \"dnn_hidden_units\": hpt.CategoricalParameterSpec(values=[\"64,16\", \"64,16,4\", \"64,64,64,8\", \"256,64,16\"]) }, max_trial_count=4 if develop_mode else 10, parallel_trial_count=2, search_algorithm=None, # Bayesian )"
},
{
"code": null,
"e": 7607,
"s": 7479,
"text": "Note that I am specifying the metric here to match the METRIC in my model.py and that I’m specifying ranges for the parameters."
},
{
"code": null,
"e": 7774,
"s": 7607,
"text": "By default, the hyperparameter tuning service in Vertex AI (called Vizier) will use Bayesian Optimization, but you can change the algorithm to GridSearch if you want."
},
{
"code": null,
"e": 7909,
"s": 7774,
"text": "Once you launch the hyperparameter tuning job, you can look at the Vertex AI section of the GCP console to see the parameters come in."
},
{
"code": null,
"e": 7941,
"s": 7909,
"text": "You’ll see something like this:"
},
{
"code": null,
"e": 8105,
"s": 7941,
"text": "Once you determine the best set of parameters, take the best set of parameters and then run the training job to completion. That will give you the model to deploy."
},
{
"code": null,
"e": 8146,
"s": 8105,
"text": "We can automate this as well, of course:"
},
{
"code": null,
"e": 8579,
"s": 8146,
"text": " best = sorted(hparam_job.trials, key=lambda x: x.final_measurement.metrics[0].value)[0] logging.info('Best trial: {}'.format(best)) best_params = [] for param in best.parameters: best_params.append('--{}'.format(param.parameter_id)) best_params.append(param.value) # run the best trial to completion model = train_custom_model(data_set, timestamp, develop_mode, extra_args=best_params)"
},
{
"code": null,
"e": 8795,
"s": 8579,
"text": "Again, separation of responsibilities between the data scientist (deciding what the parameters are, that can be optimized) and the MLOps engineer (deciding when to retune the model) is made easier through Vertex AI."
},
{
"code": null,
"e": 8802,
"s": 8795,
"text": "Enjoy!"
},
{
"code": null,
"e": 9374,
"s": 8802,
"text": "Giving Vertex AI, the New Unified ML Platform on Google Cloud, a Spin:Why do we need it, how good is the code-free ML training, really, and what does all this mean for data science jobs?How to Deploy a TensorFlow Model to Vertex AI: Working with saved models and endpoints in Vertex AIDeveloping and Deploying a Machine Learning Model on Vertex AI using Python: Write training pipelines that will make your MLOps team happyHow to build an MLOps pipeline for hyperparameter tuning in Vertex AI:Best practices to set up your model and orchestrator for hyperparameter tuning"
},
{
"code": null,
"e": 9561,
"s": 9374,
"text": "Giving Vertex AI, the New Unified ML Platform on Google Cloud, a Spin:Why do we need it, how good is the code-free ML training, really, and what does all this mean for data science jobs?"
},
{
"code": null,
"e": 9661,
"s": 9561,
"text": "How to Deploy a TensorFlow Model to Vertex AI: Working with saved models and endpoints in Vertex AI"
},
{
"code": null,
"e": 9800,
"s": 9661,
"text": "Developing and Deploying a Machine Learning Model on Vertex AI using Python: Write training pipelines that will make your MLOps team happy"
}
] |
Analyzing E-Scooter Activity through Visualization and Machine learning in Python | by Himanshu Agarwal | Towards Data Science
|
According to the recently published 2019 TomTom Traffic Index report, traffic congestion increased in 239 out of 416 cities (57%) worldwide. In the US alone, the traffic congestion level was at +20% among the major cities. Meaning, a trip will take 20% more time than it would during the city’s baseline uncongested conditions. Los Angeles tops the list with +42% and then New York city at +37%. Not to mention the environmental impacts it will have due to the higher emissions.
With the above being said, people are using alternative ways to commute such as carpooling, biking, public transit or a combination of either of those. One such alternative is E-Scooter. E-Scooters are fairly new to the market and mainly target the “last mile” part of a commute.
One such company is Bird. For those of you unfamiliar with the company, Bird operates dockless scooters in more than 100 cities worldwide. There are various models of scooters and I personally rode two of them during my field exploration trip to Washington D.C. Rides are inexpensive, and unless you have a terrible balance, riding this should be very easy.
Scooters are usually installed with lots of sensors that leads to large amounts of data being generated and hence makes for an interesting data exploration.
I set out with the following questions in mind:
1. What is the spread of e-scooters in and around Washington D.C.?
2. What is the average trip distance? Does usage depend on the day and time of the week? The latter seems intuitive but still needs to be proved.
3. What can I learn about the behavior of customers using the scooters?
4. Can I use the findings from above to generate insights?
Certain states require companies to have an open-data policy. But there is none for Washington D.C. Hence Bird does not a publicly accessible API for D.C., but one individual, who goes by ubahnverleih on Github, managed to hack together and develop one. ubahnverleih has developed APIs for multiple other ride sharing companies, so if you’re looking to work on any such data, check out his Github.
Washington, D.C. and its surrounding areas span roughly about 100 square miles. In order to cover the whole region, I carefully chose 49 different coordinate points (roughly 36 sq. mile in area) such that pinging these points in the API, returns me data of all the scooters in the region. Methodology I used for this can be found here.
That was the first part of the task. It was, however, missing one element: time. I wanted to study scooter usage over time, and not merely how scooters were geographically distributed in one instance.
To capture scooter usage over time, I hacked together a script which ran every 5mins and collected scooter data for all the above mentioned coordinate points. I kept this program running for a period of 1.5 months (48 days) resulting in roughly about ~8M data points.
There were a number of technical challenges with the API wrangling phase of the project, and while I won’t list them all, I think it’s informative to mention one in particular, to illustrate the kinds of challenges that arise anytime you try to gather data in the wild:
I had written a script that collected data throughout the day and the night. After initiating the collection process, I noticed the program had crashed for two mornings straight.
My first instinct was to assume it to be due to a bug in the code, but even after examining it, no light was shed into what might be causing the snag.
I then went through the collected data and noticed a pattern, the last API call every night before the crash would always be for sometime before 12am (of the next day). Didn’t provide any insight to the issue at the time but it was a small clue towards learning about the cause of the issue. After a lot of tinkering and unsuccessful test runs with the code, I decided to sit through the night to witness the breakdown myself.
That approach, and the hacky detective work that followed, led me to discover that the API wasn’t returning anything from 12am-4am every night but started working once it was past 4am. Companies often run maintenance runs on their systems, some more frequently than others, and that could be one explanation for that. Anyway, after knowing that, it was an easy fix in that I added a small section to my script that accounted for that nightly event. But it was surely a challenging diagnosis.
With the data now collected regularly, I created a PostgreSQL database to organize and manage the data better. Added another section to the script to do the same from my Jupyter notebook.
After going through the above steps and overcoming challenges, below is what the resulting data looked like.
Each row consists of all the pertinent information for one individual scooter.
For example, going through the first row in the snapshot above, the scooter ‘3db0f8a8–72ed-4d4b-aff8-f0f2de53c875’, is of model type ‘bd’, and was located at (38.927739,-77.097905) on 10/3/19 at 4:00:53 AM and had a battery level of 42, meaning, it would run for another5069 units (about 6 miles, based on the scale from the data).
There are some empty and redundant fields, which weren’t useful and hence weren’t considered for my analysis.
Below is an overview of the approach I took towards answering the above posed questions.
I have gone through the results towards the end of the post.
Data cleaning.Creating dataset of scooter trips from the collected data, and using it to study usage and activity but also aide in further analysis.Defining rules for detecting when scooters are stationary and when moving, in order to analyze and compare usage activity.Feature engineering using the above said rules and clustering on scooter locations to track cluster centers.
Data cleaning.
Creating dataset of scooter trips from the collected data, and using it to study usage and activity but also aide in further analysis.
Defining rules for detecting when scooters are stationary and when moving, in order to analyze and compare usage activity.
Feature engineering using the above said rules and clustering on scooter locations to track cluster centers.
For the sake of this blog post, I will be focusing more on the approach and results and not go too much into the code behind it. I’ll be showing certain sections of code if needed. Full code can be found on my GitHub here.
Two fold:
A. Fixing data types.
B. Creating a datetime feature to allow for slicing and dicing the data.
I created a helper function to do the above for us..
def fix_dtypes(df): int_cols = [‘battery_level’, ‘estimated_range’] float_cols = [‘latitude’, ‘longitude’] df = df.astype({col: ‘int32’ for col in int_cols}) df = df.astype({col: ‘float32’ for col in float_cols}) #Combining date, time column to datetime df[‘date_time’] = df[‘Date’].map(str) + “ “ + df[“Time”].map(str) df[‘date_time’] = pd.to_datetime(df[‘date_time’]) return dfdf_scootsbydate = df_multiple_days.groupby(‘Date’ [‘id’].nunique()df_scootsbydate.mean()[Out]: 5337.555555555556So, on any given day, there are about 5338 scooters spread throughout the D.C. region.
The raw data is essentially a series of snapshots taken each time the API is pinged. Each ping would essentially return data for all available scooters present at that moment of time.
At a very simple level, one can think of a flip book animation. Just like how each page is a snapshot and all pages put together shows us the entire sequence from start to the end, with first page showing the start of a sequence and last page showing the end of a sequence. Similarly, the first API call would show time & location of scooters at the start of the day and the last API call would show it for end of the day.
Below is a snippet of the resulting data and how I accomplished it.
Without going into too much technicality, (‘latitude_first, longitude_first) , are the coordinates of the scooter when it was put into operation at ‘date_time_min’ date & time, and, (‘latitude_last, longitude_last) are the coordinates when it was taken out of operation at ‘date_time_max’ date & time.
‘time_diff_hrs’ : Total operating hours of the scooter for the day. Which was calculated as just ‘date_time_max’ — ‘date_time_min’ .
Calculating distance travelled (‘distance_miles'):
‘distance_miles’ : Distance covered by a scooter in a day (in miles).
From the above, we have (‘latitude_first’, ‘longitude_first’) and (‘latitude_last’, ‘longitude_last’) for each scooter. Now we need to calculate the distance between these two locations. There are a couple of ways to calculate distance between two points. But here, since we are dealing with GPS coordinates, we use Haversine distance for our calculations. Haversine takes the Earth’s spherical shape into account where formulas like Euclidean distance don’t and hence why Haversine is appropriate to use in this case.
There are some good Python packages out there that do that. I used this resource to build a helper function to do that job for me.
At this point, we have a dataset of scooter trips for each day of the 1.5 months the data was collected. We can now analyze the usage and movement of scooters. But it wasn’t as straightforward as just filtering down scooters based on the distance feature, in other words, subsetting data to select only those scooters whose ‘distance_miles’ was 0.
Stationary : Scooter is considered stationary if it met ‘Cond_1’ and 'Cond_2'. Non-stationary : Scooter is considered to be non-stationary (or in a trip) if it doesn’t meet ‘Cond_2’ but meets ‘Cond_3’ . That is, if the ‘distance_miles’ is greater than 0.5 miles and ‘battery_diff’ is less than 50 (explanation given below).
There were a few challenges and I go over them as I explain the three conditions I used to recognize if a scooter was stationary/non-stationary:
1. Cond_1: The ‘time_diff’ should be greater than 4hrs. There were are lot of instances when scooters would just appear for a brief time during the day and disappear for days after that. Could be due to various reasons such as repairs, maintenance etc. This article validates that in some way. The disappearance of scooters doesn’t really count as scooter usage activity and hence weren’t counted towards our analysis. This rule enabled the focus to be on scooters that would “surely” be stationary. 2. Cond_2: ‘distance_miles’ should be less than 0.5miles. One would guess that for a scooter to be deemed stationary, all you need is for the distance feature to be zero, right? Well, the data had a few inconsistencies in that, we noticed instances where scooters were shown to have moved really small distances, less than a few yards or so. A few yards doesn’t really count as a “trip”, so we kept the threshold at 0.5 to avoid taking these scooter movements in our analysis.
3. Cond_3: ‘battery_diff’ should be less than 50. This was a sneaky one, as this was realized after a couple of iterations of the analysis. There were occasions when scooters, after they were taken out for charging, were placed back into a completely different location than to the one they were picked up from. Our initial analysis counted this as scooter movement but after recognizing this irregularity, using this condition helped us avoid making that mistake. 50 was a good threshold because the battery level would change drastically in such situations, for e.g. a scooter with a battery level of 10 was taken out for charging and placed back with a battery level of 100. The difference in battery level in this case will be 90. This condition would rightly recognize this irregularity and not count this scooter towards our analysis.
Feature engineered the original dataset, using rules explained above, into subsets of combinations of stationary / non stationary, and weekdays / weekends.
Below is a snapshot showing some statistics for stationary scooters..
As you can see from the above, there are a pleothera of scooters available around a certain point. In order to generate insights we need to understand the overall movement of scooters rather than focus on individuals. We used K-Means and HDBSCAN clustering methods to achieve that.
We’ve done all the preparation work, now it’s time for the results...
Of course, the number of scooters available will vary over time, but my goal here was just to get a high level understanding of the extent to which Bird had deployed scooters throughout the region.
So, on average, there were about 5338 scooters spread throughout D.C., which is a lot more than I had initially expected.
Tackling the first part of the question.. the average trip distance was approximately 1.88miles.
Curious about verifying my finding, I went about searching any report or article on the web and as it turns out, my finding was pretty close to this report (link below) published online...
“The average length of a Bird trip is 1.6 miles”
This is pretty close, considering this was only based on 1.5 months of data.
Second part... comparing usage activity across different days...
Where 0 — Monday, 1 — Tuesday and so on.
As we can see from above, usage on weekdays seem to be more, slightly, than usage on the weekends.
Which honestly surprised me because I was assuming the scooters to be used more for recreational purposes, and hence more activity on the weekends.
But from my results above, weekday activity seems to be more than weekend. This suggests that people might be using scooters more for commuting purposes. Maybe getting to and from work.
Which, when thought about, can make sense considering the traffic in D.C. region. People could be using scooters to cover their “last-mile” after stepping out of a metro/bus station.
I was able to validate my theory when I came across this report that Bird had published about its scooter usage in D.C...
“....50% of riders reported that they use Bird to get to and from work. But riders are also connecting to public transportation — 29% of riders use Bird to connect to D.C. Metro and the bus...” — Bird
What better way to understand something than to visualize it? I used this cool package in Python called folium whereby you can build custom visualizations on real world maps.
Due to the volume of scooters present and their movements, plotting individual scooters and their movements would just congest a map and make it difficult to interpret. I used the cool heatmapwithtime plugin on folium to draw heatmaps to achieve that. As you all may very well know about a heatmap, the darker the colors, the more the concentration, in this case scooters.
To do this, I clustered scooters based on their geo-coordinates and then visualized these clusters through different periods of time. This will give me a good understanding of the overall movements. I used K-Means and HDBSCAN clustering algorithms to do this and then I compared the results for different situations as shown below.
The images above represent a heartbeat-like pattern of Washington D.C.
The 8am-10am slot on weekdays shows heavy usage, simmers down towards the noon slot but picks up again towards the evening in the 4pm-6pm slot.
The activity is lesser on weekends than on weekdays but follows a similar usage pattern as the weekdays.
On any given day, the activity is concentrated towards the downtown region in the early part of the day and spreads to regions surrounding the downtown towards the latter part of the day. Representing the commuting behavior of the users.
The usage data and insights from above can be used to find the most used routes and using that, public transportation services such as buses, metros etc. can be improved. The routes can be clustered and then ranked based on popularity.
The density of usage can be cross-referenced to population density based on demographic and resources can be focused towards those that rank high on both of these fronts.
Comments or Questions? Please email me at: himanshu.agarwal20792@gmail.com or reach out on LinkedIn
|
[
{
"code": null,
"e": 651,
"s": 172,
"text": "According to the recently published 2019 TomTom Traffic Index report, traffic congestion increased in 239 out of 416 cities (57%) worldwide. In the US alone, the traffic congestion level was at +20% among the major cities. Meaning, a trip will take 20% more time than it would during the city’s baseline uncongested conditions. Los Angeles tops the list with +42% and then New York city at +37%. Not to mention the environmental impacts it will have due to the higher emissions."
},
{
"code": null,
"e": 931,
"s": 651,
"text": "With the above being said, people are using alternative ways to commute such as carpooling, biking, public transit or a combination of either of those. One such alternative is E-Scooter. E-Scooters are fairly new to the market and mainly target the “last mile” part of a commute."
},
{
"code": null,
"e": 1289,
"s": 931,
"text": "One such company is Bird. For those of you unfamiliar with the company, Bird operates dockless scooters in more than 100 cities worldwide. There are various models of scooters and I personally rode two of them during my field exploration trip to Washington D.C. Rides are inexpensive, and unless you have a terrible balance, riding this should be very easy."
},
{
"code": null,
"e": 1446,
"s": 1289,
"text": "Scooters are usually installed with lots of sensors that leads to large amounts of data being generated and hence makes for an interesting data exploration."
},
{
"code": null,
"e": 1494,
"s": 1446,
"text": "I set out with the following questions in mind:"
},
{
"code": null,
"e": 1561,
"s": 1494,
"text": "1. What is the spread of e-scooters in and around Washington D.C.?"
},
{
"code": null,
"e": 1707,
"s": 1561,
"text": "2. What is the average trip distance? Does usage depend on the day and time of the week? The latter seems intuitive but still needs to be proved."
},
{
"code": null,
"e": 1779,
"s": 1707,
"text": "3. What can I learn about the behavior of customers using the scooters?"
},
{
"code": null,
"e": 1838,
"s": 1779,
"text": "4. Can I use the findings from above to generate insights?"
},
{
"code": null,
"e": 2236,
"s": 1838,
"text": "Certain states require companies to have an open-data policy. But there is none for Washington D.C. Hence Bird does not a publicly accessible API for D.C., but one individual, who goes by ubahnverleih on Github, managed to hack together and develop one. ubahnverleih has developed APIs for multiple other ride sharing companies, so if you’re looking to work on any such data, check out his Github."
},
{
"code": null,
"e": 2572,
"s": 2236,
"text": "Washington, D.C. and its surrounding areas span roughly about 100 square miles. In order to cover the whole region, I carefully chose 49 different coordinate points (roughly 36 sq. mile in area) such that pinging these points in the API, returns me data of all the scooters in the region. Methodology I used for this can be found here."
},
{
"code": null,
"e": 2773,
"s": 2572,
"text": "That was the first part of the task. It was, however, missing one element: time. I wanted to study scooter usage over time, and not merely how scooters were geographically distributed in one instance."
},
{
"code": null,
"e": 3041,
"s": 2773,
"text": "To capture scooter usage over time, I hacked together a script which ran every 5mins and collected scooter data for all the above mentioned coordinate points. I kept this program running for a period of 1.5 months (48 days) resulting in roughly about ~8M data points."
},
{
"code": null,
"e": 3311,
"s": 3041,
"text": "There were a number of technical challenges with the API wrangling phase of the project, and while I won’t list them all, I think it’s informative to mention one in particular, to illustrate the kinds of challenges that arise anytime you try to gather data in the wild:"
},
{
"code": null,
"e": 3490,
"s": 3311,
"text": "I had written a script that collected data throughout the day and the night. After initiating the collection process, I noticed the program had crashed for two mornings straight."
},
{
"code": null,
"e": 3641,
"s": 3490,
"text": "My first instinct was to assume it to be due to a bug in the code, but even after examining it, no light was shed into what might be causing the snag."
},
{
"code": null,
"e": 4068,
"s": 3641,
"text": "I then went through the collected data and noticed a pattern, the last API call every night before the crash would always be for sometime before 12am (of the next day). Didn’t provide any insight to the issue at the time but it was a small clue towards learning about the cause of the issue. After a lot of tinkering and unsuccessful test runs with the code, I decided to sit through the night to witness the breakdown myself."
},
{
"code": null,
"e": 4560,
"s": 4068,
"text": "That approach, and the hacky detective work that followed, led me to discover that the API wasn’t returning anything from 12am-4am every night but started working once it was past 4am. Companies often run maintenance runs on their systems, some more frequently than others, and that could be one explanation for that. Anyway, after knowing that, it was an easy fix in that I added a small section to my script that accounted for that nightly event. But it was surely a challenging diagnosis."
},
{
"code": null,
"e": 4748,
"s": 4560,
"text": "With the data now collected regularly, I created a PostgreSQL database to organize and manage the data better. Added another section to the script to do the same from my Jupyter notebook."
},
{
"code": null,
"e": 4857,
"s": 4748,
"text": "After going through the above steps and overcoming challenges, below is what the resulting data looked like."
},
{
"code": null,
"e": 4936,
"s": 4857,
"text": "Each row consists of all the pertinent information for one individual scooter."
},
{
"code": null,
"e": 5268,
"s": 4936,
"text": "For example, going through the first row in the snapshot above, the scooter ‘3db0f8a8–72ed-4d4b-aff8-f0f2de53c875’, is of model type ‘bd’, and was located at (38.927739,-77.097905) on 10/3/19 at 4:00:53 AM and had a battery level of 42, meaning, it would run for another5069 units (about 6 miles, based on the scale from the data)."
},
{
"code": null,
"e": 5378,
"s": 5268,
"text": "There are some empty and redundant fields, which weren’t useful and hence weren’t considered for my analysis."
},
{
"code": null,
"e": 5467,
"s": 5378,
"text": "Below is an overview of the approach I took towards answering the above posed questions."
},
{
"code": null,
"e": 5528,
"s": 5467,
"text": "I have gone through the results towards the end of the post."
},
{
"code": null,
"e": 5907,
"s": 5528,
"text": "Data cleaning.Creating dataset of scooter trips from the collected data, and using it to study usage and activity but also aide in further analysis.Defining rules for detecting when scooters are stationary and when moving, in order to analyze and compare usage activity.Feature engineering using the above said rules and clustering on scooter locations to track cluster centers."
},
{
"code": null,
"e": 5922,
"s": 5907,
"text": "Data cleaning."
},
{
"code": null,
"e": 6057,
"s": 5922,
"text": "Creating dataset of scooter trips from the collected data, and using it to study usage and activity but also aide in further analysis."
},
{
"code": null,
"e": 6180,
"s": 6057,
"text": "Defining rules for detecting when scooters are stationary and when moving, in order to analyze and compare usage activity."
},
{
"code": null,
"e": 6289,
"s": 6180,
"text": "Feature engineering using the above said rules and clustering on scooter locations to track cluster centers."
},
{
"code": null,
"e": 6512,
"s": 6289,
"text": "For the sake of this blog post, I will be focusing more on the approach and results and not go too much into the code behind it. I’ll be showing certain sections of code if needed. Full code can be found on my GitHub here."
},
{
"code": null,
"e": 6522,
"s": 6512,
"text": "Two fold:"
},
{
"code": null,
"e": 6544,
"s": 6522,
"text": "A. Fixing data types."
},
{
"code": null,
"e": 6617,
"s": 6544,
"text": "B. Creating a datetime feature to allow for slicing and dicing the data."
},
{
"code": null,
"e": 6670,
"s": 6617,
"text": "I created a helper function to do the above for us.."
},
{
"code": null,
"e": 7248,
"s": 6670,
"text": "def fix_dtypes(df): int_cols = [‘battery_level’, ‘estimated_range’] float_cols = [‘latitude’, ‘longitude’] df = df.astype({col: ‘int32’ for col in int_cols}) df = df.astype({col: ‘float32’ for col in float_cols}) #Combining date, time column to datetime df[‘date_time’] = df[‘Date’].map(str) + “ “ + df[“Time”].map(str) df[‘date_time’] = pd.to_datetime(df[‘date_time’]) return dfdf_scootsbydate = df_multiple_days.groupby(‘Date’ [‘id’].nunique()df_scootsbydate.mean()[Out]: 5337.555555555556So, on any given day, there are about 5338 scooters spread throughout the D.C. region."
},
{
"code": null,
"e": 7432,
"s": 7248,
"text": "The raw data is essentially a series of snapshots taken each time the API is pinged. Each ping would essentially return data for all available scooters present at that moment of time."
},
{
"code": null,
"e": 7855,
"s": 7432,
"text": "At a very simple level, one can think of a flip book animation. Just like how each page is a snapshot and all pages put together shows us the entire sequence from start to the end, with first page showing the start of a sequence and last page showing the end of a sequence. Similarly, the first API call would show time & location of scooters at the start of the day and the last API call would show it for end of the day."
},
{
"code": null,
"e": 7923,
"s": 7855,
"text": "Below is a snippet of the resulting data and how I accomplished it."
},
{
"code": null,
"e": 8225,
"s": 7923,
"text": "Without going into too much technicality, (‘latitude_first, longitude_first) , are the coordinates of the scooter when it was put into operation at ‘date_time_min’ date & time, and, (‘latitude_last, longitude_last) are the coordinates when it was taken out of operation at ‘date_time_max’ date & time."
},
{
"code": null,
"e": 8358,
"s": 8225,
"text": "‘time_diff_hrs’ : Total operating hours of the scooter for the day. Which was calculated as just ‘date_time_max’ — ‘date_time_min’ ."
},
{
"code": null,
"e": 8409,
"s": 8358,
"text": "Calculating distance travelled (‘distance_miles'):"
},
{
"code": null,
"e": 8479,
"s": 8409,
"text": "‘distance_miles’ : Distance covered by a scooter in a day (in miles)."
},
{
"code": null,
"e": 8998,
"s": 8479,
"text": "From the above, we have (‘latitude_first’, ‘longitude_first’) and (‘latitude_last’, ‘longitude_last’) for each scooter. Now we need to calculate the distance between these two locations. There are a couple of ways to calculate distance between two points. But here, since we are dealing with GPS coordinates, we use Haversine distance for our calculations. Haversine takes the Earth’s spherical shape into account where formulas like Euclidean distance don’t and hence why Haversine is appropriate to use in this case."
},
{
"code": null,
"e": 9129,
"s": 8998,
"text": "There are some good Python packages out there that do that. I used this resource to build a helper function to do that job for me."
},
{
"code": null,
"e": 9477,
"s": 9129,
"text": "At this point, we have a dataset of scooter trips for each day of the 1.5 months the data was collected. We can now analyze the usage and movement of scooters. But it wasn’t as straightforward as just filtering down scooters based on the distance feature, in other words, subsetting data to select only those scooters whose ‘distance_miles’ was 0."
},
{
"code": null,
"e": 9801,
"s": 9477,
"text": "Stationary : Scooter is considered stationary if it met ‘Cond_1’ and 'Cond_2'. Non-stationary : Scooter is considered to be non-stationary (or in a trip) if it doesn’t meet ‘Cond_2’ but meets ‘Cond_3’ . That is, if the ‘distance_miles’ is greater than 0.5 miles and ‘battery_diff’ is less than 50 (explanation given below)."
},
{
"code": null,
"e": 9946,
"s": 9801,
"text": "There were a few challenges and I go over them as I explain the three conditions I used to recognize if a scooter was stationary/non-stationary:"
},
{
"code": null,
"e": 10923,
"s": 9946,
"text": "1. Cond_1: The ‘time_diff’ should be greater than 4hrs. There were are lot of instances when scooters would just appear for a brief time during the day and disappear for days after that. Could be due to various reasons such as repairs, maintenance etc. This article validates that in some way. The disappearance of scooters doesn’t really count as scooter usage activity and hence weren’t counted towards our analysis. This rule enabled the focus to be on scooters that would “surely” be stationary. 2. Cond_2: ‘distance_miles’ should be less than 0.5miles. One would guess that for a scooter to be deemed stationary, all you need is for the distance feature to be zero, right? Well, the data had a few inconsistencies in that, we noticed instances where scooters were shown to have moved really small distances, less than a few yards or so. A few yards doesn’t really count as a “trip”, so we kept the threshold at 0.5 to avoid taking these scooter movements in our analysis."
},
{
"code": null,
"e": 11764,
"s": 10923,
"text": "3. Cond_3: ‘battery_diff’ should be less than 50. This was a sneaky one, as this was realized after a couple of iterations of the analysis. There were occasions when scooters, after they were taken out for charging, were placed back into a completely different location than to the one they were picked up from. Our initial analysis counted this as scooter movement but after recognizing this irregularity, using this condition helped us avoid making that mistake. 50 was a good threshold because the battery level would change drastically in such situations, for e.g. a scooter with a battery level of 10 was taken out for charging and placed back with a battery level of 100. The difference in battery level in this case will be 90. This condition would rightly recognize this irregularity and not count this scooter towards our analysis."
},
{
"code": null,
"e": 11920,
"s": 11764,
"text": "Feature engineered the original dataset, using rules explained above, into subsets of combinations of stationary / non stationary, and weekdays / weekends."
},
{
"code": null,
"e": 11990,
"s": 11920,
"text": "Below is a snapshot showing some statistics for stationary scooters.."
},
{
"code": null,
"e": 12272,
"s": 11990,
"text": "As you can see from the above, there are a pleothera of scooters available around a certain point. In order to generate insights we need to understand the overall movement of scooters rather than focus on individuals. We used K-Means and HDBSCAN clustering methods to achieve that."
},
{
"code": null,
"e": 12342,
"s": 12272,
"text": "We’ve done all the preparation work, now it’s time for the results..."
},
{
"code": null,
"e": 12540,
"s": 12342,
"text": "Of course, the number of scooters available will vary over time, but my goal here was just to get a high level understanding of the extent to which Bird had deployed scooters throughout the region."
},
{
"code": null,
"e": 12662,
"s": 12540,
"text": "So, on average, there were about 5338 scooters spread throughout D.C., which is a lot more than I had initially expected."
},
{
"code": null,
"e": 12759,
"s": 12662,
"text": "Tackling the first part of the question.. the average trip distance was approximately 1.88miles."
},
{
"code": null,
"e": 12948,
"s": 12759,
"text": "Curious about verifying my finding, I went about searching any report or article on the web and as it turns out, my finding was pretty close to this report (link below) published online..."
},
{
"code": null,
"e": 12997,
"s": 12948,
"text": "“The average length of a Bird trip is 1.6 miles”"
},
{
"code": null,
"e": 13074,
"s": 12997,
"text": "This is pretty close, considering this was only based on 1.5 months of data."
},
{
"code": null,
"e": 13139,
"s": 13074,
"text": "Second part... comparing usage activity across different days..."
},
{
"code": null,
"e": 13180,
"s": 13139,
"text": "Where 0 — Monday, 1 — Tuesday and so on."
},
{
"code": null,
"e": 13279,
"s": 13180,
"text": "As we can see from above, usage on weekdays seem to be more, slightly, than usage on the weekends."
},
{
"code": null,
"e": 13427,
"s": 13279,
"text": "Which honestly surprised me because I was assuming the scooters to be used more for recreational purposes, and hence more activity on the weekends."
},
{
"code": null,
"e": 13613,
"s": 13427,
"text": "But from my results above, weekday activity seems to be more than weekend. This suggests that people might be using scooters more for commuting purposes. Maybe getting to and from work."
},
{
"code": null,
"e": 13796,
"s": 13613,
"text": "Which, when thought about, can make sense considering the traffic in D.C. region. People could be using scooters to cover their “last-mile” after stepping out of a metro/bus station."
},
{
"code": null,
"e": 13918,
"s": 13796,
"text": "I was able to validate my theory when I came across this report that Bird had published about its scooter usage in D.C..."
},
{
"code": null,
"e": 14119,
"s": 13918,
"text": "“....50% of riders reported that they use Bird to get to and from work. But riders are also connecting to public transportation — 29% of riders use Bird to connect to D.C. Metro and the bus...” — Bird"
},
{
"code": null,
"e": 14294,
"s": 14119,
"text": "What better way to understand something than to visualize it? I used this cool package in Python called folium whereby you can build custom visualizations on real world maps."
},
{
"code": null,
"e": 14667,
"s": 14294,
"text": "Due to the volume of scooters present and their movements, plotting individual scooters and their movements would just congest a map and make it difficult to interpret. I used the cool heatmapwithtime plugin on folium to draw heatmaps to achieve that. As you all may very well know about a heatmap, the darker the colors, the more the concentration, in this case scooters."
},
{
"code": null,
"e": 14999,
"s": 14667,
"text": "To do this, I clustered scooters based on their geo-coordinates and then visualized these clusters through different periods of time. This will give me a good understanding of the overall movements. I used K-Means and HDBSCAN clustering algorithms to do this and then I compared the results for different situations as shown below."
},
{
"code": null,
"e": 15070,
"s": 14999,
"text": "The images above represent a heartbeat-like pattern of Washington D.C."
},
{
"code": null,
"e": 15214,
"s": 15070,
"text": "The 8am-10am slot on weekdays shows heavy usage, simmers down towards the noon slot but picks up again towards the evening in the 4pm-6pm slot."
},
{
"code": null,
"e": 15319,
"s": 15214,
"text": "The activity is lesser on weekends than on weekdays but follows a similar usage pattern as the weekdays."
},
{
"code": null,
"e": 15557,
"s": 15319,
"text": "On any given day, the activity is concentrated towards the downtown region in the early part of the day and spreads to regions surrounding the downtown towards the latter part of the day. Representing the commuting behavior of the users."
},
{
"code": null,
"e": 15793,
"s": 15557,
"text": "The usage data and insights from above can be used to find the most used routes and using that, public transportation services such as buses, metros etc. can be improved. The routes can be clustered and then ranked based on popularity."
},
{
"code": null,
"e": 15964,
"s": 15793,
"text": "The density of usage can be cross-referenced to population density based on demographic and resources can be focused towards those that rank high on both of these fronts."
}
] |
TextDecoder and TextEncoder in Javascript?
|
TextEncoder is used to convert a given string to utf-8 standard. It retunes an Uint8Array from the string.
TextDecoder is used to covert a stream of bytes into a stream of code points. It can decode UTF-8 , ISO-8859-2, KOI8-R, GBK etc.
Following is the code for TextDecoder and TextEncoder in JavaScript −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
.result,.sample {
font-size: 18px;
font-weight: 500;
color: rebeccapurple;
}
.result {
color: red;
}
</style>
</head>
<body>
<h1>TextDecoder and TextEncoder in Javascript</h1>
<div class="sample"></div>
<button class="Btn">ENCODE STRING</button>
<div class="result"></div>
<h3>Click on the above button to encode the above string</h3>
<div class="sample"></div>
<button class="Btn">Decode STRING</button>
<div class="result"></div>
<h3>Click on the above button to decode the above string</h3>
<script>
let BtnEle = document.querySelectorAll(".Btn");
let sampleEle = document.querySelectorAll(".sample");
let resEle = document.querySelectorAll(".result");
let str = "Hello world";
let str1 = new Uint8Array([119, 111, 114, 108, 100]);
sampleEle[0].innerHTML = str;
sampleEle[1].innerHTML = str1;
BtnEle[0].addEventListener("click", () => {
let textEncoder = new TextEncoder();
resEle[0].innerHTML += "Encoded String = " + textEncoder.encode(str) + "<br>";
});
BtnEle[1].addEventListener("click", () => {
let textDecoder = new TextDecoder();
resEle[1].innerHTML += "Decoded String = " + textDecoder.decode(str1) + "<br>";
});
</script>
</body>
</html>
The above code will produce the following output −
On clicking the ‘ENCODE STRING’ button −
On clicking the ‘Decode STRING’ button −
|
[
{
"code": null,
"e": 1169,
"s": 1062,
"text": "TextEncoder is used to convert a given string to utf-8 standard. It retunes an Uint8Array from the string."
},
{
"code": null,
"e": 1298,
"s": 1169,
"text": "TextDecoder is used to covert a stream of bytes into a stream of code points. It can decode UTF-8 , ISO-8859-2, KOI8-R, GBK etc."
},
{
"code": null,
"e": 1368,
"s": 1298,
"text": "Following is the code for TextDecoder and TextEncoder in JavaScript −"
},
{
"code": null,
"e": 1379,
"s": 1368,
"text": " Live Demo"
},
{
"code": null,
"e": 2876,
"s": 1379,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .result,.sample {\n font-size: 18px;\n font-weight: 500;\n color: rebeccapurple;\n }\n .result {\n color: red;\n }\n</style>\n</head>\n<body>\n<h1>TextDecoder and TextEncoder in Javascript</h1>\n<div class=\"sample\"></div>\n<button class=\"Btn\">ENCODE STRING</button>\n<div class=\"result\"></div>\n<h3>Click on the above button to encode the above string</h3>\n<div class=\"sample\"></div>\n<button class=\"Btn\">Decode STRING</button>\n<div class=\"result\"></div>\n<h3>Click on the above button to decode the above string</h3>\n<script>\n let BtnEle = document.querySelectorAll(\".Btn\");\n let sampleEle = document.querySelectorAll(\".sample\");\n let resEle = document.querySelectorAll(\".result\");\n let str = \"Hello world\";\n let str1 = new Uint8Array([119, 111, 114, 108, 100]);\n sampleEle[0].innerHTML = str;\n sampleEle[1].innerHTML = str1;\n BtnEle[0].addEventListener(\"click\", () => {\n let textEncoder = new TextEncoder();\n resEle[0].innerHTML += \"Encoded String = \" + textEncoder.encode(str) + \"<br>\";\n });\n BtnEle[1].addEventListener(\"click\", () => {\n let textDecoder = new TextDecoder();\n resEle[1].innerHTML += \"Decoded String = \" + textDecoder.decode(str1) + \"<br>\";\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2927,
"s": 2876,
"text": "The above code will produce the following output −"
},
{
"code": null,
"e": 2968,
"s": 2927,
"text": "On clicking the ‘ENCODE STRING’ button −"
},
{
"code": null,
"e": 3009,
"s": 2968,
"text": "On clicking the ‘Decode STRING’ button −"
}
] |
How to convert left linear grammar to right linear grammar?
|
Regular grammar describes a regular language. It consists of four components, which are as follows −
G = (N, E, P, S)
Where,
N: finite set of non-terminal symbols,
N: finite set of non-terminal symbols,
E: a finite set of terminal symbols,
E: a finite set of terminal symbols,
P: a set of production rules, each of one is in the forms
P: a set of production rules, each of one is in the forms
S → aB
S → aB
S → a
S → a
S → ∈,
S → ∈,
S ∈ N is the start symbol.
S ∈ N is the start symbol.
The above grammar can be of two forms −
Right Linear Regular Grammar
Right Linear Regular Grammar
Left Linear Regular Grammar
Left Linear Regular Grammar
Now, let us see the steps to convert left linear grammar to right linear grammar −
Consider a left linear grammar as given below −
S→ Sa|Abc
A→ Sa|Ab|a
Step 1 − We will convert the given left linear grammar to finite automata.
Step 2 − We will now interchange the initial and final state.
Step 3 − Now we will reverse the direction of all transactions.
Step 4 − We will construct the regular grammar for the above finite automata which will be right linear grammar, as shown below −
C→aA
A→bA|cb
S→aS
Consider another example
The given left linear grammar is −
S→S10|S11|B|e
B→B0|0
First eliminate non-deterministic of grammar
S→SA|B|e
A→10|11
B→B0|0
So, the right linear grammar is −
S→BS’|S’
S’→e|10S’|11S’
B→0B’
B’→0B’|e
|
[
{
"code": null,
"e": 1163,
"s": 1062,
"text": "Regular grammar describes a regular language. It consists of four components, which are as follows −"
},
{
"code": null,
"e": 1180,
"s": 1163,
"text": "G = (N, E, P, S)"
},
{
"code": null,
"e": 1187,
"s": 1180,
"text": "Where,"
},
{
"code": null,
"e": 1226,
"s": 1187,
"text": "N: finite set of non-terminal symbols,"
},
{
"code": null,
"e": 1265,
"s": 1226,
"text": "N: finite set of non-terminal symbols,"
},
{
"code": null,
"e": 1302,
"s": 1265,
"text": "E: a finite set of terminal symbols,"
},
{
"code": null,
"e": 1339,
"s": 1302,
"text": "E: a finite set of terminal symbols,"
},
{
"code": null,
"e": 1397,
"s": 1339,
"text": "P: a set of production rules, each of one is in the forms"
},
{
"code": null,
"e": 1455,
"s": 1397,
"text": "P: a set of production rules, each of one is in the forms"
},
{
"code": null,
"e": 1462,
"s": 1455,
"text": "S → aB"
},
{
"code": null,
"e": 1469,
"s": 1462,
"text": "S → aB"
},
{
"code": null,
"e": 1475,
"s": 1469,
"text": "S → a"
},
{
"code": null,
"e": 1481,
"s": 1475,
"text": "S → a"
},
{
"code": null,
"e": 1488,
"s": 1481,
"text": "S → ∈,"
},
{
"code": null,
"e": 1495,
"s": 1488,
"text": "S → ∈,"
},
{
"code": null,
"e": 1522,
"s": 1495,
"text": "S ∈ N is the start symbol."
},
{
"code": null,
"e": 1549,
"s": 1522,
"text": "S ∈ N is the start symbol."
},
{
"code": null,
"e": 1589,
"s": 1549,
"text": "The above grammar can be of two forms −"
},
{
"code": null,
"e": 1618,
"s": 1589,
"text": "Right Linear Regular Grammar"
},
{
"code": null,
"e": 1647,
"s": 1618,
"text": "Right Linear Regular Grammar"
},
{
"code": null,
"e": 1675,
"s": 1647,
"text": "Left Linear Regular Grammar"
},
{
"code": null,
"e": 1703,
"s": 1675,
"text": "Left Linear Regular Grammar"
},
{
"code": null,
"e": 1786,
"s": 1703,
"text": "Now, let us see the steps to convert left linear grammar to right linear grammar −"
},
{
"code": null,
"e": 1834,
"s": 1786,
"text": "Consider a left linear grammar as given below −"
},
{
"code": null,
"e": 1855,
"s": 1834,
"text": "S→ Sa|Abc\nA→ Sa|Ab|a"
},
{
"code": null,
"e": 1930,
"s": 1855,
"text": "Step 1 − We will convert the given left linear grammar to finite automata."
},
{
"code": null,
"e": 1992,
"s": 1930,
"text": "Step 2 − We will now interchange the initial and final state."
},
{
"code": null,
"e": 2056,
"s": 1992,
"text": "Step 3 − Now we will reverse the direction of all transactions."
},
{
"code": null,
"e": 2186,
"s": 2056,
"text": "Step 4 − We will construct the regular grammar for the above finite automata which will be right linear grammar, as shown below −"
},
{
"code": null,
"e": 2204,
"s": 2186,
"text": "C→aA\nA→bA|cb\nS→aS"
},
{
"code": null,
"e": 2229,
"s": 2204,
"text": "Consider another example"
},
{
"code": null,
"e": 2264,
"s": 2229,
"text": "The given left linear grammar is −"
},
{
"code": null,
"e": 2285,
"s": 2264,
"text": "S→S10|S11|B|e\nB→B0|0"
},
{
"code": null,
"e": 2330,
"s": 2285,
"text": "First eliminate non-deterministic of grammar"
},
{
"code": null,
"e": 2354,
"s": 2330,
"text": "S→SA|B|e\nA→10|11\nB→B0|0"
},
{
"code": null,
"e": 2388,
"s": 2354,
"text": "So, the right linear grammar is −"
},
{
"code": null,
"e": 2427,
"s": 2388,
"text": "S→BS’|S’\nS’→e|10S’|11S’\nB→0B’\nB’→0B’|e"
}
] |
ES6 - Maps and Sets
|
ES6 introduces two new data structures − maps and sets. Let us learn about them in detail.
A map is an ordered collection of key-value pairs. Maps are similar to objects. However, there are some differences between maps and objects. These are listed below −
The syntax for Map is given below −
let map = new Map([iterable])
let map = new Map()
The following example creates a map using an iterable constructor −
<script>
let andy = {ename:"Andrel"},
varun = {ename:"Varun"},
prijin = {ename:"Prijin"}
let empJobs = new Map([
[andy,'Software Architect'],
[varun,'Developer']]
);
console.log(empJobs)
</script>
The output of the above code is as shown below −
{{...} => "Software Architect", {...} => "Developer"}
The size property can be used to determine the number of values stored in the map.
The syntax for checking the size of the map is given below −
map_name.size
<script>
let daysMap = new Map();
daysMap.set('1', 'Monday');
daysMap.set('2', 'Tuesday');
daysMap.set('3', 'Wednesday');
console.log(daysMap.size);
</script>
The output of the above code is as shown below −
3
Following are some common methods that can be used to manipulate maps −
Adds key and value to map
Returns value if key is matched
Returns true if an element with the specified key exists; else returns false
Returns an iterator that contains the keys for each element in the map object
Returns an iterator that contains the values for each element in the map object
Returns an iterator that contains the key-value pairs for each element in the Map
Removes the specified element from a Map object
WeakMap is a small subset of map. Keys are weakly referenced, so it can be non-primitive only. If there are no reference to the object keys, it will be subject to garbage collection.
not iterable
every key is object type
The WeakMap will allow garbage collection if the key has no reference.
The syntax for WeakMap is stated below −
new WeakMap([iterable])
<script>
let emp = new WeakMap();
emp.set(10,'Sachin');// TypeError as keys should be object
</script>
<script>
let empMap = new WeakMap();
// emp.set(10,'Sachin');// Error as keys should be object
let e1= {ename:'Kiran'},
e2 = {ename:'Kannan'},
e3 = {ename:'Mohtashim'}
empMap.set(e1,1001);
empMap.set(e2,1002);
empMap.set(e3,1003);
console.log(empMap)
console.log(empMap.get(e2))
console.log(empMap.has(e2))
empMap.delete(e1)
console.log(empMap)
</script>
The output of the above code is as mentioned below −
{{...} => 1002, {...} => 1003, {...} => 1001}
1002
true
{{...} => 1002, {...} => 1003}
A set is an unordered collection of unique values. This data structure can contain values of primitive and object types.
The syntax for Set is given below −
new Set([iterable])
new Set()
<script>
let names = new Set(['A','B','C','D']);
console.log(names)
</script>
The output of the above code is as given below −
{"A", "B", "C", "D"}
The size property of the Set object can be used to query the number of elements in the Set.
The syntax for checking the size of a set is mentioned below −
set.size
<script>
let names = new Set(['A','B','C','D']);
console.log(names.size)
</script>
The output of the above code is as given below −
4
We can use the forEach and for..of loops to iterate through a Set. This is shown in the example below −
<script>
let names= new Set(['A','B','C','D']);
//iterate using forEach
console.log('forEach')
names.forEach(n=>console.log(n))
console.log('for of..')
//iterate using for..of
for(let n of names){
console.log(n)
}
</script>
The output of the above code is as mentioned below −
forEach
A
B
C
D
for of..
A
B
C
D
The following methods can be used to manipulate a set −
Adds an element to the Set
Returns true if element found; else returns false
Delete specific element from the Set
Clears all elements from the Set
A Weakset holds objects weakly, that means object stored in a WeakSet are subject to garbage collection, if they are not referenced. WeakSets are not iterable and do not have the get method.
<script>
let e1 = {ename:'A'}
let e2 ={ename:'B'}
let e3 ={ename:'C'}
let emps = new WeakSet();
emps.add(e1);
emps.add(e2)
.add(e3);
console.log(emps)
console.log(emps.has(e1))
emps.delete(e1);
console.log(emps)
</script>
The output of the above code will be as mentioned below −
WeakSet {{...}, {...}, {...}}
true
WeakSet {{...}, {...}}
32 Lectures
3.5 hours
Sharad Kumar
40 Lectures
5 hours
Richa Maheshwari
16 Lectures
1 hours
Anadi Sharma
50 Lectures
6.5 hours
Gowthami Swarna
14 Lectures
1 hours
Deepti Trivedi
31 Lectures
1.5 hours
Shweta
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2368,
"s": 2277,
"text": "ES6 introduces two new data structures − maps and sets. Let us learn about them in detail."
},
{
"code": null,
"e": 2535,
"s": 2368,
"text": "A map is an ordered collection of key-value pairs. Maps are similar to objects. However, there are some differences between maps and objects. These are listed below −"
},
{
"code": null,
"e": 2571,
"s": 2535,
"text": "The syntax for Map is given below −"
},
{
"code": null,
"e": 2622,
"s": 2571,
"text": "let map = new Map([iterable])\nlet map = new Map()\n"
},
{
"code": null,
"e": 2690,
"s": 2622,
"text": "The following example creates a map using an iterable constructor −"
},
{
"code": null,
"e": 2918,
"s": 2690,
"text": "<script>\n let andy = {ename:\"Andrel\"},\n varun = {ename:\"Varun\"},\n prijin = {ename:\"Prijin\"}\n let empJobs = new Map([\n [andy,'Software Architect'],\n [varun,'Developer']]\n );\n console.log(empJobs)\n</script>\n"
},
{
"code": null,
"e": 2967,
"s": 2918,
"text": "The output of the above code is as shown below −"
},
{
"code": null,
"e": 3022,
"s": 2967,
"text": "{{...} => \"Software Architect\", {...} => \"Developer\"}\n"
},
{
"code": null,
"e": 3105,
"s": 3022,
"text": "The size property can be used to determine the number of values stored in the map."
},
{
"code": null,
"e": 3166,
"s": 3105,
"text": "The syntax for checking the size of the map is given below −"
},
{
"code": null,
"e": 3181,
"s": 3166,
"text": "map_name.size\n"
},
{
"code": null,
"e": 3356,
"s": 3181,
"text": "<script>\n let daysMap = new Map();\n daysMap.set('1', 'Monday');\n daysMap.set('2', 'Tuesday');\n daysMap.set('3', 'Wednesday');\n console.log(daysMap.size);\n</script>\n"
},
{
"code": null,
"e": 3405,
"s": 3356,
"text": "The output of the above code is as shown below −"
},
{
"code": null,
"e": 3408,
"s": 3405,
"text": "3\n"
},
{
"code": null,
"e": 3480,
"s": 3408,
"text": "Following are some common methods that can be used to manipulate maps −"
},
{
"code": null,
"e": 3506,
"s": 3480,
"text": "Adds key and value to map"
},
{
"code": null,
"e": 3538,
"s": 3506,
"text": "Returns value if key is matched"
},
{
"code": null,
"e": 3615,
"s": 3538,
"text": "Returns true if an element with the specified key exists; else returns false"
},
{
"code": null,
"e": 3693,
"s": 3615,
"text": "Returns an iterator that contains the keys for each element in the map object"
},
{
"code": null,
"e": 3773,
"s": 3693,
"text": "Returns an iterator that contains the values for each element in the map object"
},
{
"code": null,
"e": 3855,
"s": 3773,
"text": "Returns an iterator that contains the key-value pairs for each element in the Map"
},
{
"code": null,
"e": 3903,
"s": 3855,
"text": "Removes the specified element from a Map object"
},
{
"code": null,
"e": 4086,
"s": 3903,
"text": "WeakMap is a small subset of map. Keys are weakly referenced, so it can be non-primitive only. If there are no reference to the object keys, it will be subject to garbage collection."
},
{
"code": null,
"e": 4099,
"s": 4086,
"text": "not iterable"
},
{
"code": null,
"e": 4124,
"s": 4099,
"text": "every key is object type"
},
{
"code": null,
"e": 4195,
"s": 4124,
"text": "The WeakMap will allow garbage collection if the key has no reference."
},
{
"code": null,
"e": 4236,
"s": 4195,
"text": "The syntax for WeakMap is stated below −"
},
{
"code": null,
"e": 4261,
"s": 4236,
"text": "new WeakMap([iterable])\n"
},
{
"code": null,
"e": 4370,
"s": 4261,
"text": "<script>\n let emp = new WeakMap();\n emp.set(10,'Sachin');// TypeError as keys should be object\n</script>"
},
{
"code": null,
"e": 4772,
"s": 4370,
"text": "<script>\n let empMap = new WeakMap();\n // emp.set(10,'Sachin');// Error as keys should be object\n let e1= {ename:'Kiran'},\n e2 = {ename:'Kannan'},\n e3 = {ename:'Mohtashim'}\n\n empMap.set(e1,1001);\n empMap.set(e2,1002);\n empMap.set(e3,1003);\n\n console.log(empMap)\n console.log(empMap.get(e2))\n console.log(empMap.has(e2))\n empMap.delete(e1)\n console.log(empMap)\n</script>"
},
{
"code": null,
"e": 4825,
"s": 4772,
"text": "The output of the above code is as mentioned below −"
},
{
"code": null,
"e": 4913,
"s": 4825,
"text": "{{...} => 1002, {...} => 1003, {...} => 1001}\n1002\ntrue\n{{...} => 1002, {...} => 1003}\n"
},
{
"code": null,
"e": 5034,
"s": 4913,
"text": "A set is an unordered collection of unique values. This data structure can contain values of primitive and object types."
},
{
"code": null,
"e": 5070,
"s": 5034,
"text": "The syntax for Set is given below −"
},
{
"code": null,
"e": 5101,
"s": 5070,
"text": "new Set([iterable])\nnew Set()\n"
},
{
"code": null,
"e": 5185,
"s": 5101,
"text": "<script>\n let names = new Set(['A','B','C','D']);\n console.log(names)\n</script>"
},
{
"code": null,
"e": 5234,
"s": 5185,
"text": "The output of the above code is as given below −"
},
{
"code": null,
"e": 5256,
"s": 5234,
"text": "{\"A\", \"B\", \"C\", \"D\"}\n"
},
{
"code": null,
"e": 5348,
"s": 5256,
"text": "The size property of the Set object can be used to query the number of elements in the Set."
},
{
"code": null,
"e": 5411,
"s": 5348,
"text": "The syntax for checking the size of a set is mentioned below −"
},
{
"code": null,
"e": 5421,
"s": 5411,
"text": "set.size\n"
},
{
"code": null,
"e": 5510,
"s": 5421,
"text": "<script>\n let names = new Set(['A','B','C','D']);\n console.log(names.size)\n</script>"
},
{
"code": null,
"e": 5559,
"s": 5510,
"text": "The output of the above code is as given below −"
},
{
"code": null,
"e": 5562,
"s": 5559,
"text": "4\n"
},
{
"code": null,
"e": 5666,
"s": 5562,
"text": "We can use the forEach and for..of loops to iterate through a Set. This is shown in the example below −"
},
{
"code": null,
"e": 5930,
"s": 5666,
"text": "<script>\n let names= new Set(['A','B','C','D']);\n //iterate using forEach\n console.log('forEach')\n names.forEach(n=>console.log(n))\n \n console.log('for of..')\n \n //iterate using for..of\n for(let n of names){\n console.log(n)\n }\n</script> "
},
{
"code": null,
"e": 5983,
"s": 5930,
"text": "The output of the above code is as mentioned below −"
},
{
"code": null,
"e": 6017,
"s": 5983,
"text": "forEach\nA\nB\nC\nD\nfor of..\nA\nB\nC\nD\n"
},
{
"code": null,
"e": 6073,
"s": 6017,
"text": "The following methods can be used to manipulate a set −"
},
{
"code": null,
"e": 6100,
"s": 6073,
"text": "Adds an element to the Set"
},
{
"code": null,
"e": 6150,
"s": 6100,
"text": "Returns true if element found; else returns false"
},
{
"code": null,
"e": 6187,
"s": 6150,
"text": "Delete specific element from the Set"
},
{
"code": null,
"e": 6220,
"s": 6187,
"text": "Clears all elements from the Set"
},
{
"code": null,
"e": 6411,
"s": 6220,
"text": "A Weakset holds objects weakly, that means object stored in a WeakSet are subject to garbage collection, if they are not referenced. WeakSets are not iterable and do not have the get method."
},
{
"code": null,
"e": 6669,
"s": 6411,
"text": "<script>\n\n let e1 = {ename:'A'}\n let e2 ={ename:'B'}\n let e3 ={ename:'C'}\n\n let emps = new WeakSet();\n emps.add(e1);\n emps.add(e2)\n .add(e3);\n\n console.log(emps)\n console.log(emps.has(e1))\n emps.delete(e1);\n console.log(emps)\n</script>"
},
{
"code": null,
"e": 6727,
"s": 6669,
"text": "The output of the above code will be as mentioned below −"
},
{
"code": null,
"e": 6786,
"s": 6727,
"text": "WeakSet {{...}, {...}, {...}}\ntrue\nWeakSet {{...}, {...}}\n"
},
{
"code": null,
"e": 6821,
"s": 6786,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 6835,
"s": 6821,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 6868,
"s": 6835,
"text": "\n 40 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 6886,
"s": 6868,
"text": " Richa Maheshwari"
},
{
"code": null,
"e": 6919,
"s": 6886,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6933,
"s": 6919,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 6968,
"s": 6933,
"text": "\n 50 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 6985,
"s": 6968,
"text": " Gowthami Swarna"
},
{
"code": null,
"e": 7018,
"s": 6985,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 7034,
"s": 7018,
"text": " Deepti Trivedi"
},
{
"code": null,
"e": 7069,
"s": 7034,
"text": "\n 31 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7077,
"s": 7069,
"text": " Shweta"
},
{
"code": null,
"e": 7084,
"s": 7077,
"text": " Print"
},
{
"code": null,
"e": 7095,
"s": 7084,
"text": " Add Notes"
}
] |
Count occurences of a given word in a 2-d array | Practice | GeeksforGeeks
|
Find the number of occurrences of a given search word in a 2d-Array of characters where the word can go up, down, left, right and around 90 degree bends.
Example 1:
Input:
R = 4, C = 5
mat = {{S,N,B,S,N},
{B,A,K,E,A},
{B,K,B,B,K},
{S,E,B,S,E}}
target = SNAKES
Output:
3
Explanation:
S N B S N
B A K E A
B K B B K
S E B S E
Total occurrence of the word is 3
and denoted by color.
Example 2:
Input:
R = 3, C = 3
mat = {{c,a,t},
{a,t,c},
{c,t,a}}
target = cat
Output:
5
Explanation: Same explanation
as first example.
Your task:
You don’t need to read input or print anything. Your task is to complete the function findOccurrence() which takes the mat contaning N*M 2-d array of character and target as input parameters and returns thethe number of occurrences of target.
Expected Time Complexity: O(R*C*22*len), Where len is length of target String.
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ len ≤ 15
1 ≤ R, C ≤ 50
0
ra98530441 month ago
class Solution{ int[] di={1,-1,0,0}; int[] dj={0,0,1,-1}; public int findOccurrence(char mat[][], String target) { // Write your code here int count=0; boolean[][] visited=new boolean[mat.length][mat[0].length]; for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { if(mat[i][j]==target.charAt(0)) { // System.out.println(i+"-"+j+" "+findOccurrence(mat,i,j,target,0,visited)); count+=findOccurrence(mat,i,j,target,0,visited); } } } return count; } int findOccurrence(char mat[][],int i,int j,String target,int k,boolean[][] visited) { if(k==target.length()-1) return 1; visited[i][j]=true; int count=0; for(int l=0;l<4;l++) { int newi=i+di[l]; int newj=j+dj[l]; if(newi>=0 && newi<mat.length && newj>=0 && newj<mat[0].length && mat[newi][newj]==target.charAt(k+1) && !visited[newi][newj]) { count+=findOccurrence(mat,newi,newj,target,k+1,visited); } } visited[i][j]=false; return count; }}
How to find the time complexity of this solution?
0
surajchauhan72472019731 month ago
Easy c++ colution
class Solution{ int count = 0; void dfs(vector<vector<char>>&mat, vector<vector<int>>&visited,int row, int col, string tar, string str, int x,int i,int j) { if(i >=row || j>=col || i < 0 || j < 0 || visited[i][j] == 1 || mat[i][j] != tar[x]) return; visited[i][j] = 1; str += mat[i][j]; if(str == tar) { count++; return; } if(i+1 < row && i+1 >=0 && j>=0 && j < col && visited[i+1][j] == 0 && mat[i+1][j] == tar[x+1]){ dfs(mat,visited,row,col,tar,str,x+1,i+1,j); visited[i+1][j] = 0; } if(i-1 < row && i-1 >=0 && j>=0 && j < col && visited[i-1][j] == 0 && mat[i-1][j] == tar[x+1]){ dfs(mat,visited,row,col,tar,str,x+1,i-1,j); visited[i-1][j] = 0; } if(i < row && i >=0 && j+1>=0 && j+1 < col && visited[i][j+1] == 0 && mat[i][j+1] == tar[x+1]){ dfs(mat,visited,row,col,tar,str,x+1,i,j+1); visited[i][j+1] = 0; } if(i < row && i >=0 && j-1>=0 && j-1 < col && visited[i][j-1] == 0 && mat[i][j-1] == tar[x+1]){ dfs(mat,visited,row,col,tar,str,x+1,i,j-1); visited[i][j-1] = 0; } } public: int findOccurrence(vector<vector<char> > &mat, string target){ int row = mat.size(); int col = mat[0].size(); count = 0; for(int i=0;i<row;i++) { for(int j=0;j<col;j++) { if(target[0] == mat[i][j]) { vector<vector<int>>visited(row, vector<int>(col, 0)); string str = ""; dfs(mat,visited,row,col,target,str,0,i,j); } } } return count; }};
+1
aloksinghbais022 months ago
C++ solution using dfs having time complexity as O(n*m*2^(2*|target|)) and space complexity as O(N*M) is as follows :-
Execution Time :- 0.6 / 3.2 sec
bool isValid(int x,int y,int n,int m,vector<vector<char>> &mat,vector<vector<bool>> &vis,char ch){ if(x < 0 || x >= n || y < 0 || y >= m) return (false); if(vis[x][y] || mat[x][y] != ch) return (false); return (true); } void dfs(int x,int y,int n,int m,vector<vector<char>> &mat,vector<vector<bool>> &vis,string &target,int i,int &cnt){ if(i == target.length()){ cnt++; return; } int dx[] = {-1,0,1,0}; int dy[] = {0,1,0,-1}; for(int j = 0; j < 4; j++){ int nx = x + dx[j]; int ny = y + dy[j]; if(isValid(nx,ny,n,m,mat,vis,target[i])){ vis[nx][ny] = true; dfs(nx,ny,n,m,mat,vis,target,i+1,cnt); vis[nx][ny] = false; } } } int findOccurrence(vector<vector<char> > &mat, string target){ int n = mat.size(), m = mat[0].size(); int ans = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(mat[i][j] == target[0]){ vector<vector<bool>> vis(n,vector<bool>(m,false)); int cnt = 0; vis[i][j] = true; dfs(i,j,n,m,mat,vis,target,1,cnt); ans += cnt; } } } return (ans); }
0
haritasboy12053 months ago
C++ Solution:
int helper(string target,int i,int j,vector<vector<char> > &mat, int row,int col,int idx)
{
int count = 0;
if(i >= 0 && i <= row && j >= 0 && j <= col && target[idx] == mat[i][j])
{
char temp = target[idx];
idx += 1;
mat[i][j] = 0;
if(target[idx] == 0)
count = 1;
else
{
count += helper(target,i,j+1,mat,row,col,idx);
count += helper(target,i,j-1,mat,row,col,idx);
count += helper(target,i+1,j,mat,row,col,idx);
count += helper(target,i-1,j,mat,row,col,idx);
}
mat[i][j] = temp;
}
return count;
}
int findOccurrence(vector<vector<char> > &mat, string target){
int count = 0;
for(int i=0;i<mat.size();i++)
{
for(int j=0;j<mat[0].size();j++)
{
count += helper(target,i,j,mat,mat.size()-1,mat[0].size()-1,0);
}
}
return count;
}
0
ramanshusingh19997 months ago
Solution below (C++):
class Solution{
public:
int search(string target, int r, int c, vector<vector<char> > &mat, int row_max, int col_max, int idx)
{
int found = 0;
if (r >= 0 && r <= row_max && c >= 0 && c <= col_max && target[idx] == mat[r][c])
{
char temp = target[idx];
idx += 1;
mat[r][c] = 0;
if (target[idx] == 0)
{
found = 1;
}
else
{
found += search(target, r, c + 1, mat, row_max, col_max, idx);
found += search(target, r, c - 1, mat, row_max, col_max, idx);
found += search(target, r + 1, c, mat, row_max, col_max, idx);
found += search(target, r - 1, c, mat, row_max, col_max, idx);
}
mat[r][c] = temp;
}
return found;
}
int findOccurrence(vector<vector<char> > &mat, string target){
int found = 0, i, j;
for(i = 0; i < mat.size(); i++)
{
for(j = 0; j < mat[0].size(); j++)
{
found += search(target, i, j, mat, mat.size() - 1, mat[0].size() - 1, 0);
}
}
return found;
}
};
-1
itsmohitmk997 months ago
Exception in thread "main" java.lang.NullPointerException at java.base/java.util.StringTokenizer.<init>(StringTokenizer.java:199) at java.base/java.util.StringTokenizer.<init>(StringTokenizer.java:236) at GFG$FastReader.next(File.java:19) at GFG.main(File.java:53)
sc.nextLine() is to be removed from input
0
segerrlonewolf7 months ago
Receiving this exception while submission, something screwed in the input console for this problem
Exception in thread "main" java.lang.NumberFormatException: For input string: "n" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.parseInt(Integer.java:770) at GFG$FastReader.nextInt(File.java:31) at GFG.main(File.java:42)
0
Rishabh Singh7 months ago
Rishabh Singh
Can anyone tell me why my code is giving wrong answerclass Solution{ public: int solve(int i,int j,int R,int C,vector<vector<char> > &matrix,string target,int index) { int found=0; if(i>=0&&j>=0&&i<r&&j<c&&target[index]==matrix[i][j]) {="" char="" temp="target[index];" index++;="" matrix[i][j]="0;" if(index="=target.length())" return="" 1;="" else="" {="" found+="solve(i-1,j,R,C,matrix,target,index);" found+="solve(i+1,j,R,C,matrix,target,index);" found+="solve(i,j-1,R,C,matrix,target,index);" found+="solve(i,j+1,R,C,matrix,target,index);" }="" matrix[i][j]="temp;" }="" return="" found;="" }="" int="" findoccurrence(vector<vector<char=""> > &matrix, string target){ int R=matrix.size(); int C=matrix[0].size(); int ans=0; for(int i=0;i<r;i++) {="" for(int="" j="0;j<C;j++)" {="" ans+="solve(i,j,R,C,matrix,target,0);" }="" }="" return="" ans;="" }="" };="">
0
Devang8 months ago
Devang
C++ using lambdas
class Solution { public: const int d[5] = {0, -1, 0, 1, 0}; int findOccurrence(vector<vector<char> > &grid, string target) { int m = grid.size(), n = grid[0].size(); int count = 0; function<int(int, int,="" int)=""> dfs = [&](int i, int j, int idx) { if( i < 0 or j < 0 or i >= m or j >= n or grid[i][j] != target[idx] ) return 0; int count = 0; if(idx == target.size() - 1) return 1; char ch = grid[i][j]; grid[i][j] = '#'; for(int k = 0; k < 4; k++) { int ni = i + d[k], nj = j + d[k+1]; count += dfs( ni, nj, idx + 1 ); } grid[i][j] = ch; return count; }; for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) count += dfs(i, j, 0); return count; }};
0
dhruv amin9 months ago
dhruv amin
Why can't we use DP here?dp[row][col][index]?
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": 381,
"s": 226,
"text": "Find the number of occurrences of a given search word in a 2d-Array of characters where the word can go up, down, left, right and around 90 degree bends."
},
{
"code": null,
"e": 393,
"s": 381,
"text": "\nExample 1:"
},
{
"code": null,
"e": 631,
"s": 393,
"text": "Input: \nR = 4, C = 5\nmat = {{S,N,B,S,N},\n {B,A,K,E,A},\n {B,K,B,B,K},\n {S,E,B,S,E}}\ntarget = SNAKES\nOutput:\n3\nExplanation: \nS N B S N\nB A K E A\nB K B B K\nS E B S E\nTotal occurrence of the word is 3\nand denoted by color.\n"
},
{
"code": null,
"e": 642,
"s": 631,
"text": "Example 2:"
},
{
"code": null,
"e": 783,
"s": 642,
"text": "Input:\nR = 3, C = 3 \nmat = {{c,a,t},\n {a,t,c},\n {c,t,a}}\ntarget = cat\nOutput:\n5\nExplanation: Same explanation\nas first example.\n"
},
{
"code": null,
"e": 1038,
"s": 783,
"text": "\nYour task:\nYou don’t need to read input or print anything. Your task is to complete the function findOccurrence() which takes the mat contaning N*M 2-d array of character and target as input parameters and returns thethe number of occurrences of target."
},
{
"code": null,
"e": 1149,
"s": 1038,
"text": "\nExpected Time Complexity: O(R*C*22*len), Where len is length of target String.\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1190,
"s": 1149,
"text": "\nConstraints:\n1 ≤ len ≤ 15\n1 ≤ R, C ≤ 50"
},
{
"code": null,
"e": 1192,
"s": 1190,
"text": "0"
},
{
"code": null,
"e": 1213,
"s": 1192,
"text": "ra98530441 month ago"
},
{
"code": null,
"e": 2402,
"s": 1213,
"text": "class Solution{ int[] di={1,-1,0,0}; int[] dj={0,0,1,-1}; public int findOccurrence(char mat[][], String target) { // Write your code here int count=0; boolean[][] visited=new boolean[mat.length][mat[0].length]; for(int i=0;i<mat.length;i++) { for(int j=0;j<mat[0].length;j++) { if(mat[i][j]==target.charAt(0)) { // System.out.println(i+\"-\"+j+\" \"+findOccurrence(mat,i,j,target,0,visited)); count+=findOccurrence(mat,i,j,target,0,visited); } } } return count; } int findOccurrence(char mat[][],int i,int j,String target,int k,boolean[][] visited) { if(k==target.length()-1) return 1; visited[i][j]=true; int count=0; for(int l=0;l<4;l++) { int newi=i+di[l]; int newj=j+dj[l]; if(newi>=0 && newi<mat.length && newj>=0 && newj<mat[0].length && mat[newi][newj]==target.charAt(k+1) && !visited[newi][newj]) { count+=findOccurrence(mat,newi,newj,target,k+1,visited); } } visited[i][j]=false; return count; }}"
},
{
"code": null,
"e": 2452,
"s": 2402,
"text": "How to find the time complexity of this solution?"
},
{
"code": null,
"e": 2454,
"s": 2452,
"text": "0"
},
{
"code": null,
"e": 2488,
"s": 2454,
"text": "surajchauhan72472019731 month ago"
},
{
"code": null,
"e": 2506,
"s": 2488,
"text": "Easy c++ colution"
},
{
"code": null,
"e": 4206,
"s": 2506,
"text": "class Solution{ int count = 0; void dfs(vector<vector<char>>&mat, vector<vector<int>>&visited,int row, int col, string tar, string str, int x,int i,int j) { if(i >=row || j>=col || i < 0 || j < 0 || visited[i][j] == 1 || mat[i][j] != tar[x]) return; visited[i][j] = 1; str += mat[i][j]; if(str == tar) { count++; return; } if(i+1 < row && i+1 >=0 && j>=0 && j < col && visited[i+1][j] == 0 && mat[i+1][j] == tar[x+1]){ dfs(mat,visited,row,col,tar,str,x+1,i+1,j); visited[i+1][j] = 0; } if(i-1 < row && i-1 >=0 && j>=0 && j < col && visited[i-1][j] == 0 && mat[i-1][j] == tar[x+1]){ dfs(mat,visited,row,col,tar,str,x+1,i-1,j); visited[i-1][j] = 0; } if(i < row && i >=0 && j+1>=0 && j+1 < col && visited[i][j+1] == 0 && mat[i][j+1] == tar[x+1]){ dfs(mat,visited,row,col,tar,str,x+1,i,j+1); visited[i][j+1] = 0; } if(i < row && i >=0 && j-1>=0 && j-1 < col && visited[i][j-1] == 0 && mat[i][j-1] == tar[x+1]){ dfs(mat,visited,row,col,tar,str,x+1,i,j-1); visited[i][j-1] = 0; } } public: int findOccurrence(vector<vector<char> > &mat, string target){ int row = mat.size(); int col = mat[0].size(); count = 0; for(int i=0;i<row;i++) { for(int j=0;j<col;j++) { if(target[0] == mat[i][j]) { vector<vector<int>>visited(row, vector<int>(col, 0)); string str = \"\"; dfs(mat,visited,row,col,target,str,0,i,j); } } } return count; }};"
},
{
"code": null,
"e": 4209,
"s": 4206,
"text": "+1"
},
{
"code": null,
"e": 4237,
"s": 4209,
"text": "aloksinghbais022 months ago"
},
{
"code": null,
"e": 4357,
"s": 4237,
"text": "C++ solution using dfs having time complexity as O(n*m*2^(2*|target|)) and space complexity as O(N*M) is as follows :- "
},
{
"code": null,
"e": 4391,
"s": 4359,
"text": "Execution Time :- 0.6 / 3.2 sec"
},
{
"code": null,
"e": 5719,
"s": 4393,
"text": "bool isValid(int x,int y,int n,int m,vector<vector<char>> &mat,vector<vector<bool>> &vis,char ch){ if(x < 0 || x >= n || y < 0 || y >= m) return (false); if(vis[x][y] || mat[x][y] != ch) return (false); return (true); } void dfs(int x,int y,int n,int m,vector<vector<char>> &mat,vector<vector<bool>> &vis,string &target,int i,int &cnt){ if(i == target.length()){ cnt++; return; } int dx[] = {-1,0,1,0}; int dy[] = {0,1,0,-1}; for(int j = 0; j < 4; j++){ int nx = x + dx[j]; int ny = y + dy[j]; if(isValid(nx,ny,n,m,mat,vis,target[i])){ vis[nx][ny] = true; dfs(nx,ny,n,m,mat,vis,target,i+1,cnt); vis[nx][ny] = false; } } } int findOccurrence(vector<vector<char> > &mat, string target){ int n = mat.size(), m = mat[0].size(); int ans = 0; for(int i = 0; i < n; i++){ for(int j = 0; j < m; j++){ if(mat[i][j] == target[0]){ vector<vector<bool>> vis(n,vector<bool>(m,false)); int cnt = 0; vis[i][j] = true; dfs(i,j,n,m,mat,vis,target,1,cnt); ans += cnt; } } } return (ans); }"
},
{
"code": null,
"e": 5721,
"s": 5719,
"text": "0"
},
{
"code": null,
"e": 5748,
"s": 5721,
"text": "haritasboy12053 months ago"
},
{
"code": null,
"e": 6813,
"s": 5748,
"text": " C++ Solution: \n int helper(string target,int i,int j,vector<vector<char> > &mat, int row,int col,int idx)\n {\n int count = 0;\n if(i >= 0 && i <= row && j >= 0 && j <= col && target[idx] == mat[i][j])\n {\n char temp = target[idx];\n idx += 1;\n \n mat[i][j] = 0;\n if(target[idx] == 0)\n count = 1;\n else\n {\n count += helper(target,i,j+1,mat,row,col,idx);\n count += helper(target,i,j-1,mat,row,col,idx);\n count += helper(target,i+1,j,mat,row,col,idx);\n count += helper(target,i-1,j,mat,row,col,idx);\n }\n \n mat[i][j] = temp;\n }\n return count;\n }\n int findOccurrence(vector<vector<char> > &mat, string target){\n int count = 0;\n for(int i=0;i<mat.size();i++)\n {\n for(int j=0;j<mat[0].size();j++)\n {\n count += helper(target,i,j,mat,mat.size()-1,mat[0].size()-1,0);\n }\n }\n return count;\n }"
},
{
"code": null,
"e": 6815,
"s": 6813,
"text": "0"
},
{
"code": null,
"e": 6845,
"s": 6815,
"text": "ramanshusingh19997 months ago"
},
{
"code": null,
"e": 6867,
"s": 6845,
"text": "Solution below (C++):"
},
{
"code": null,
"e": 8067,
"s": 6867,
"text": "class Solution{\n public:\n int search(string target, int r, int c, vector<vector<char> > &mat, int row_max, int col_max, int idx)\n {\n int found = 0;\n \n if (r >= 0 && r <= row_max && c >= 0 && c <= col_max && target[idx] == mat[r][c])\n {\n char temp = target[idx];\n idx += 1;\n \n mat[r][c] = 0;\n \n if (target[idx] == 0)\n {\n found = 1;\n }\n else\n {\n found += search(target, r, c + 1, mat, row_max, col_max, idx);\n found += search(target, r, c - 1, mat, row_max, col_max, idx);\n found += search(target, r + 1, c, mat, row_max, col_max, idx);\n found += search(target, r - 1, c, mat, row_max, col_max, idx);\n }\n mat[r][c] = temp;\n }\n return found;\n }\n int findOccurrence(vector<vector<char> > &mat, string target){\n int found = 0, i, j;\n for(i = 0; i < mat.size(); i++)\n {\n for(j = 0; j < mat[0].size(); j++)\n {\n found += search(target, i, j, mat, mat.size() - 1, mat[0].size() - 1, 0);\n }\n }\n return found;\n }\n};"
},
{
"code": null,
"e": 8070,
"s": 8067,
"text": "-1"
},
{
"code": null,
"e": 8095,
"s": 8070,
"text": "itsmohitmk997 months ago"
},
{
"code": null,
"e": 8360,
"s": 8095,
"text": "Exception in thread \"main\" java.lang.NullPointerException at java.base/java.util.StringTokenizer.<init>(StringTokenizer.java:199) at java.base/java.util.StringTokenizer.<init>(StringTokenizer.java:236) at GFG$FastReader.next(File.java:19) at GFG.main(File.java:53)"
},
{
"code": null,
"e": 8404,
"s": 8362,
"text": "sc.nextLine() is to be removed from input"
},
{
"code": null,
"e": 8406,
"s": 8404,
"text": "0"
},
{
"code": null,
"e": 8433,
"s": 8406,
"text": "segerrlonewolf7 months ago"
},
{
"code": null,
"e": 8532,
"s": 8433,
"text": "Receiving this exception while submission, something screwed in the input console for this problem"
},
{
"code": null,
"e": 8887,
"s": 8532,
"text": "Exception in thread \"main\" java.lang.NumberFormatException: For input string: \"n\" at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.base/java.lang.Integer.parseInt(Integer.java:652) at java.base/java.lang.Integer.parseInt(Integer.java:770) at GFG$FastReader.nextInt(File.java:31) at GFG.main(File.java:42)"
},
{
"code": null,
"e": 8889,
"s": 8887,
"text": "0"
},
{
"code": null,
"e": 8915,
"s": 8889,
"text": "Rishabh Singh7 months ago"
},
{
"code": null,
"e": 8929,
"s": 8915,
"text": "Rishabh Singh"
},
{
"code": null,
"e": 9849,
"s": 8929,
"text": "Can anyone tell me why my code is giving wrong answerclass Solution{ public: int solve(int i,int j,int R,int C,vector<vector<char> > &matrix,string target,int index) { int found=0; if(i>=0&&j>=0&&i<r&&j<c&&target[index]==matrix[i][j]) {=\"\" char=\"\" temp=\"target[index];\" index++;=\"\" matrix[i][j]=\"0;\" if(index=\"=target.length())\" return=\"\" 1;=\"\" else=\"\" {=\"\" found+=\"solve(i-1,j,R,C,matrix,target,index);\" found+=\"solve(i+1,j,R,C,matrix,target,index);\" found+=\"solve(i,j-1,R,C,matrix,target,index);\" found+=\"solve(i,j+1,R,C,matrix,target,index);\" }=\"\" matrix[i][j]=\"temp;\" }=\"\" return=\"\" found;=\"\" }=\"\" int=\"\" findoccurrence(vector<vector<char=\"\"> > &matrix, string target){ int R=matrix.size(); int C=matrix[0].size(); int ans=0; for(int i=0;i<r;i++) {=\"\" for(int=\"\" j=\"0;j<C;j++)\" {=\"\" ans+=\"solve(i,j,R,C,matrix,target,0);\" }=\"\" }=\"\" return=\"\" ans;=\"\" }=\"\" };=\"\">"
},
{
"code": null,
"e": 9851,
"s": 9849,
"text": "0"
},
{
"code": null,
"e": 9870,
"s": 9851,
"text": "Devang8 months ago"
},
{
"code": null,
"e": 9877,
"s": 9870,
"text": "Devang"
},
{
"code": null,
"e": 9895,
"s": 9877,
"text": "C++ using lambdas"
},
{
"code": null,
"e": 10774,
"s": 9895,
"text": "class Solution { public: const int d[5] = {0, -1, 0, 1, 0}; int findOccurrence(vector<vector<char> > &grid, string target) { int m = grid.size(), n = grid[0].size(); int count = 0; function<int(int, int,=\"\" int)=\"\"> dfs = [&](int i, int j, int idx) { if( i < 0 or j < 0 or i >= m or j >= n or grid[i][j] != target[idx] ) return 0; int count = 0; if(idx == target.size() - 1) return 1; char ch = grid[i][j]; grid[i][j] = '#'; for(int k = 0; k < 4; k++) { int ni = i + d[k], nj = j + d[k+1]; count += dfs( ni, nj, idx + 1 ); } grid[i][j] = ch; return count; }; for(int i = 0; i < m; i++) for(int j = 0; j < n; j++) count += dfs(i, j, 0); return count; }};"
},
{
"code": null,
"e": 10776,
"s": 10774,
"text": "0"
},
{
"code": null,
"e": 10799,
"s": 10776,
"text": "dhruv amin9 months ago"
},
{
"code": null,
"e": 10810,
"s": 10799,
"text": "dhruv amin"
},
{
"code": null,
"e": 10856,
"s": 10810,
"text": "Why can't we use DP here?dp[row][col][index]?"
},
{
"code": null,
"e": 11002,
"s": 10856,
"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": 11038,
"s": 11002,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 11048,
"s": 11038,
"text": "\nProblem\n"
},
{
"code": null,
"e": 11058,
"s": 11048,
"text": "\nContest\n"
},
{
"code": null,
"e": 11121,
"s": 11058,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 11269,
"s": 11121,
"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": 11477,
"s": 11269,
"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": 11583,
"s": 11477,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Program to print the pattern "GFG" - GeeksforGeeks
|
13 Oct, 2021
In this article, given the value of n(length of the alphabet) and k(width of the alphabet) we will learn how to print the pattern “GFG” using stars and white-spaces. Examples:
INPUT: n=7, k=5
OUTPUT:
***** ***** *****
* * *
* * *
* ** ***** * ***
* * * * *
* * * * *
***** * *****
INPUT: n=11, k=7
OUTPUT:
******* ******* *******
* * *
* * *
* * *
* * *
* ***** ******* * *****
* * * * *
* * * * *
* * * * *
* * * * *
******* * *******
C++
Java
Python3
C#
PHP
Javascript
#include <iostream> using namespace std; // Function to print the pattern "GFG"void print1(int n, int k) { int i, j; for (i = 0; i < n; i++) { cout << "\n"; for (j = 0; j < (3 * k + 2); j++) { if ((i == 0 && j != k && /*For printing the upper portion of the pattern "GFG"*/ j != 2 * k + 1) || ((i == n / 2) && (j > 1) && (j != k) && (j != 2 * k + 1) && /* for printing the middle portion of the pattern "GFG" */ (j != 2 * k + 3)) || ((i == n - 1) && (j != k) && /* for printing the lower portion of the pattern "GFG" */ ((j <= k) || (j > 2 * k + 1))) || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) || ((j == k - 1 || j == 3 * k + 1) && (i > n / 2))) cout << "*"; // printing * wherever required else cout << " "; // printing space wherever required } }} // Driver codeint main() { int n = 7; // the length of the pattern "GFG" int k = 5; // the width of the pattern "GFG" print1(n, k);}
import java.util.Scanner; public class PatternGFG // create a Class named PatternGFG{ // Function to print the pattern "GFG" private static void print(int n, int k) { for (int i = 0; i < n; i++) { System.out.println(); for (int j = 0; j < (3 * k + 2); j++) { // For printing the upper portion of // the pattern "GFG" if ((i == 0 && j != k && j != 2 * k + 1) || ((i == n / 2) && (j > 1) && (j != k) && // for printing the middle portion of // the pattern "GFG" (j != 2 * k + 1) && (j != 2 * k + 3)) || ((i == n - 1) && (j != k) && // for printing the lower portion of // the pattern "GFG" ((j <= k) || (j > 2 * k + 1))) || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) || ((j == k - 1 || j == 3 * k + 1) && (i > n / 2))) // printing * wherever required System.out.print("*"); else System.out.print(" "); // printing space wherever required } } } // Driver code public static void main(String[] args) { int n = 7, k = 5; // length and width of the pattern print(n, k); }}
# Python Program to print# the pattern “GFG”import math # Function to print the# pattern "GFG"def print1(n, k) : for i in range(0, n) : print ("\n") for j in range(0, (3 * k + 2)) : if ((i == 0 and j != k and # For printing the # upper portion of # the pattern "GFG" j != 2 * k + 1) or ((i == math.floor(n / 2)) and (j > 1) and (j != k) and (j != 2 * k + 1) and # for printing the # middle portion of # the pattern "GFG" (j != 2 * k + 3)) or ((i == n - 1) and (j != k) and # for printing the # lower portion of # the pattern "GFG" ((j <= k) or (j > 2 * k + 1))) or (j == 0) or (j == k + 1) or (j == (2 * k + 2)) or ((j ==k - 1 or j == 3 * k + 1) and (i > math.floor(n / 2)))) : # printing * where # ever required print ("*", end = "") else : # printing space # wherever required print (" ", end = "") # Driver code # the length of the# pattern "GFG"n = 7 # the width of the# pattern "GFG"k = 5 print1(n, k) # This code is contributed# by Manish Shaw(manishshaw1)
// C# code for printing pattern.using System; public class GFG { // Function to print the pattern "GFG" private static void print(int n, int k) { for (int i = 0; i < n; i++) { Console.WriteLine(); for (int j = 0; j < (3 * k + 2); j++) { // For printing the upper portion of // the pattern "GFG" if ((i == 0 && j != k && j != 2 * k + 1) || ((i == n / 2) && (j > 1) && (j != k) && // for printing the middle portion of // the pattern "GFG" (j != 2 * k + 1) && (j != 2 * k + 3)) || ((i == n - 1) && (j != k) && // for printing the lower portion of // the pattern "GFG" ((j <= k) || (j > 2 * k + 1))) || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) || ((j == k - 1 || j == 3 * k + 1) && (i > n / 2))) // printing * wherever required Console.Write("*"); else Console.Write(" "); } } } // Driver code public static void Main() { // length and width of the pattern int n = 7, k = 5; print(n, k); }} // This code is contributed by vt_m.
<?php// PHP Program to print// the pattern “GFG” // Function to print the// pattern "GFG"function print1($n, $k) { for ($i = 0; $i < $n; $i++) { echo "\n"; for ($j = 0; $j < (3 * $k + 2); $j++) { if (($i == 0 && $j != $k && // For printing the upper portion // of the pattern "GFG" $j != 2 * $k + 1) || (($i == floor($n / 2)) && ($j > 1) && ($j != $k) && ($j != 2 * $k + 1) && /* for printing the middle portion of the pattern "GFG" */ ($j != 2 * $k + 3)) || (($i == $n - 1) && ($j != $k) && /* for printing the lower portion of the pattern "GFG" */ (($j <= $k) || ($j > 2 * $k + 1))) || ($j == 0) || ($j == $k + 1) || ($j == (2 * $k + 2)) || (($j ==$k - 1 || $j == 3 * $k + 1) && ($i > floor($n / 2)))) // printing * wherever required echo "*"; else // printing space wherever required echo " "; }}} // Driver code// the length of the pattern "GFG"$n = 7; // the width of the pattern "GFG"$k = 5; print1($n, $k); // This code is contributed by Sam007?>
<script>// Javascript implementation for the above approach // Function to print the pattern "GFG"function print1(n, k) { var i, j; for (i = 0; i < n; i++) { document.write("<br>"); for (j = 0; j < (3 * k + 2); j++) { if ((i == 0 && j != k && /*For printing the upper portion of the pattern "GFG"*/ j != 2 * k + 1) || ((i == n / 2) && (j > 1) && (j != k) && (j != 2 * k + 1) && /* for printing the middle portion of the pattern "GFG" */ (j != 2 * k + 3)) || ((i == n - 1) && (j != k) && /* for printing the lower portion of the pattern "GFG" */ ((j <= k) || (j > 2 * k + 1))) || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) || ((j == k - 1 || j == 3 * k + 1) && (i > n / 2))) document.write("*"); // printing * wherever required else document.write(" "," "); // printing space wherever required } }} // Driver codevar n = 7; // the length of the pattern "GFG"var k = 5; // the width of the pattern "GFG"print1(n, k); // This code is contributed by Shubham Singh</script>
Output :
***** ***** *****
* * *
* * *
* ** ***** * ***
* * * * *
* * * * *
***** * *****
Sam007
manishshaw1
SHUBHAMSINGH10
saurabh1990aror
pattern-printing
School Programming
pattern-printing
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Constructors in Java
Exceptions in Java
Ternary Operator in Python
Inline Functions in C++
Destructors in C++
Exception Handling in C++
Difference between Abstract Class and Interface in Java
Python Exception Handling
'this' pointer in C++
Pure Virtual Functions and Abstract Classes in C++
|
[
{
"code": null,
"e": 24206,
"s": 24178,
"text": "\n13 Oct, 2021"
},
{
"code": null,
"e": 24384,
"s": 24206,
"text": "In this article, given the value of n(length of the alphabet) and k(width of the alphabet) we will learn how to print the pattern “GFG” using stars and white-spaces. Examples: "
},
{
"code": null,
"e": 24803,
"s": 24384,
"text": "INPUT: n=7, k=5\nOUTPUT:\n***** ***** *****\n* * *\n* * *\n* ** ***** * ***\n* * * * *\n* * * * *\n***** * *****\n\nINPUT: n=11, k=7\nOUTPUT:\n******* ******* *******\n* * *\n* * *\n* * *\n* * *\n* ***** ******* * *****\n* * * * *\n* * * * *\n* * * * *\n* * * * *\n******* * *******"
},
{
"code": null,
"e": 24809,
"s": 24805,
"text": "C++"
},
{
"code": null,
"e": 24814,
"s": 24809,
"text": "Java"
},
{
"code": null,
"e": 24822,
"s": 24814,
"text": "Python3"
},
{
"code": null,
"e": 24825,
"s": 24822,
"text": "C#"
},
{
"code": null,
"e": 24829,
"s": 24825,
"text": "PHP"
},
{
"code": null,
"e": 24840,
"s": 24829,
"text": "Javascript"
},
{
"code": "#include <iostream> using namespace std; // Function to print the pattern \"GFG\"void print1(int n, int k) { int i, j; for (i = 0; i < n; i++) { cout << \"\\n\"; for (j = 0; j < (3 * k + 2); j++) { if ((i == 0 && j != k && /*For printing the upper portion of the pattern \"GFG\"*/ j != 2 * k + 1) || ((i == n / 2) && (j > 1) && (j != k) && (j != 2 * k + 1) && /* for printing the middle portion of the pattern \"GFG\" */ (j != 2 * k + 3)) || ((i == n - 1) && (j != k) && /* for printing the lower portion of the pattern \"GFG\" */ ((j <= k) || (j > 2 * k + 1))) || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) || ((j == k - 1 || j == 3 * k + 1) && (i > n / 2))) cout << \"*\"; // printing * wherever required else cout << \" \"; // printing space wherever required } }} // Driver codeint main() { int n = 7; // the length of the pattern \"GFG\" int k = 5; // the width of the pattern \"GFG\" print1(n, k);}",
"e": 25939,
"s": 24840,
"text": null
},
{
"code": "import java.util.Scanner; public class PatternGFG // create a Class named PatternGFG{ // Function to print the pattern \"GFG\" private static void print(int n, int k) { for (int i = 0; i < n; i++) { System.out.println(); for (int j = 0; j < (3 * k + 2); j++) { // For printing the upper portion of // the pattern \"GFG\" if ((i == 0 && j != k && j != 2 * k + 1) || ((i == n / 2) && (j > 1) && (j != k) && // for printing the middle portion of // the pattern \"GFG\" (j != 2 * k + 1) && (j != 2 * k + 3)) || ((i == n - 1) && (j != k) && // for printing the lower portion of // the pattern \"GFG\" ((j <= k) || (j > 2 * k + 1))) || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) || ((j == k - 1 || j == 3 * k + 1) && (i > n / 2))) // printing * wherever required System.out.print(\"*\"); else System.out.print(\" \"); // printing space wherever required } } } // Driver code public static void main(String[] args) { int n = 7, k = 5; // length and width of the pattern print(n, k); }}",
"e": 27126,
"s": 25939,
"text": null
},
{
"code": "# Python Program to print# the pattern “GFG”import math # Function to print the# pattern \"GFG\"def print1(n, k) : for i in range(0, n) : print (\"\\n\") for j in range(0, (3 * k + 2)) : if ((i == 0 and j != k and # For printing the # upper portion of # the pattern \"GFG\" j != 2 * k + 1) or ((i == math.floor(n / 2)) and (j > 1) and (j != k) and (j != 2 * k + 1) and # for printing the # middle portion of # the pattern \"GFG\" (j != 2 * k + 3)) or ((i == n - 1) and (j != k) and # for printing the # lower portion of # the pattern \"GFG\" ((j <= k) or (j > 2 * k + 1))) or (j == 0) or (j == k + 1) or (j == (2 * k + 2)) or ((j ==k - 1 or j == 3 * k + 1) and (i > math.floor(n / 2)))) : # printing * where # ever required print (\"*\", end = \"\") else : # printing space # wherever required print (\" \", end = \"\") # Driver code # the length of the# pattern \"GFG\"n = 7 # the width of the# pattern \"GFG\"k = 5 print1(n, k) # This code is contributed# by Manish Shaw(manishshaw1)",
"e": 28592,
"s": 27126,
"text": null
},
{
"code": "// C# code for printing pattern.using System; public class GFG { // Function to print the pattern \"GFG\" private static void print(int n, int k) { for (int i = 0; i < n; i++) { Console.WriteLine(); for (int j = 0; j < (3 * k + 2); j++) { // For printing the upper portion of // the pattern \"GFG\" if ((i == 0 && j != k && j != 2 * k + 1) || ((i == n / 2) && (j > 1) && (j != k) && // for printing the middle portion of // the pattern \"GFG\" (j != 2 * k + 1) && (j != 2 * k + 3)) || ((i == n - 1) && (j != k) && // for printing the lower portion of // the pattern \"GFG\" ((j <= k) || (j > 2 * k + 1))) || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) || ((j == k - 1 || j == 3 * k + 1) && (i > n / 2))) // printing * wherever required Console.Write(\"*\"); else Console.Write(\" \"); } } } // Driver code public static void Main() { // length and width of the pattern int n = 7, k = 5; print(n, k); }} // This code is contributed by vt_m.",
"e": 30065,
"s": 28592,
"text": null
},
{
"code": "<?php// PHP Program to print// the pattern “GFG” // Function to print the// pattern \"GFG\"function print1($n, $k) { for ($i = 0; $i < $n; $i++) { echo \"\\n\"; for ($j = 0; $j < (3 * $k + 2); $j++) { if (($i == 0 && $j != $k && // For printing the upper portion // of the pattern \"GFG\" $j != 2 * $k + 1) || (($i == floor($n / 2)) && ($j > 1) && ($j != $k) && ($j != 2 * $k + 1) && /* for printing the middle portion of the pattern \"GFG\" */ ($j != 2 * $k + 3)) || (($i == $n - 1) && ($j != $k) && /* for printing the lower portion of the pattern \"GFG\" */ (($j <= $k) || ($j > 2 * $k + 1))) || ($j == 0) || ($j == $k + 1) || ($j == (2 * $k + 2)) || (($j ==$k - 1 || $j == 3 * $k + 1) && ($i > floor($n / 2)))) // printing * wherever required echo \"*\"; else // printing space wherever required echo \" \"; }}} // Driver code// the length of the pattern \"GFG\"$n = 7; // the width of the pattern \"GFG\"$k = 5; print1($n, $k); // This code is contributed by Sam007?>",
"e": 31217,
"s": 30065,
"text": null
},
{
"code": "<script>// Javascript implementation for the above approach // Function to print the pattern \"GFG\"function print1(n, k) { var i, j; for (i = 0; i < n; i++) { document.write(\"<br>\"); for (j = 0; j < (3 * k + 2); j++) { if ((i == 0 && j != k && /*For printing the upper portion of the pattern \"GFG\"*/ j != 2 * k + 1) || ((i == n / 2) && (j > 1) && (j != k) && (j != 2 * k + 1) && /* for printing the middle portion of the pattern \"GFG\" */ (j != 2 * k + 3)) || ((i == n - 1) && (j != k) && /* for printing the lower portion of the pattern \"GFG\" */ ((j <= k) || (j > 2 * k + 1))) || (j == 0) || (j == k + 1) || (j == (2 * k + 2)) || ((j == k - 1 || j == 3 * k + 1) && (i > n / 2))) document.write(\"*\"); // printing * wherever required else document.write(\" \",\" \"); // printing space wherever required } }} // Driver codevar n = 7; // the length of the pattern \"GFG\"var k = 5; // the width of the pattern \"GFG\"print1(n, k); // This code is contributed by Shubham Singh</script>",
"e": 32396,
"s": 31217,
"text": null
},
{
"code": null,
"e": 32407,
"s": 32396,
"text": "Output : "
},
{
"code": null,
"e": 32525,
"s": 32407,
"text": "***** ***** *****\n* * *\n* * *\n* ** ***** * ***\n* * * * *\n* * * * *\n***** * *****"
},
{
"code": null,
"e": 32534,
"s": 32527,
"text": "Sam007"
},
{
"code": null,
"e": 32546,
"s": 32534,
"text": "manishshaw1"
},
{
"code": null,
"e": 32561,
"s": 32546,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 32577,
"s": 32561,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 32594,
"s": 32577,
"text": "pattern-printing"
},
{
"code": null,
"e": 32613,
"s": 32594,
"text": "School Programming"
},
{
"code": null,
"e": 32630,
"s": 32613,
"text": "pattern-printing"
},
{
"code": null,
"e": 32728,
"s": 32630,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32737,
"s": 32728,
"text": "Comments"
},
{
"code": null,
"e": 32750,
"s": 32737,
"text": "Old Comments"
},
{
"code": null,
"e": 32771,
"s": 32750,
"text": "Constructors in Java"
},
{
"code": null,
"e": 32790,
"s": 32771,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 32817,
"s": 32790,
"text": "Ternary Operator in Python"
},
{
"code": null,
"e": 32841,
"s": 32817,
"text": "Inline Functions in C++"
},
{
"code": null,
"e": 32860,
"s": 32841,
"text": "Destructors in C++"
},
{
"code": null,
"e": 32886,
"s": 32860,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 32942,
"s": 32886,
"text": "Difference between Abstract Class and Interface in Java"
},
{
"code": null,
"e": 32968,
"s": 32942,
"text": "Python Exception Handling"
},
{
"code": null,
"e": 32990,
"s": 32968,
"text": "'this' pointer in C++"
}
] |
Replace 0 with NA in R DataFrame - GeeksforGeeks
|
31 Aug, 2021
In this article, we are going to discuss how to replace 0 with NA values in dataframe in R Programming Language.
NA stands for Null values which can represent Null data / Null elements in a dataframe. The task can be achieved by first defining a dataframe that contains 0 as values. Then we can replace 0 with NA by using index operator [].
Syntax:
dataframe[dataframe== 0] = NA
where,
dataframe is the input dataframe
In index we are checking if the value is 0, if it is 0 then we are replacing it as NA
Example: Replacing 0 with NA for integer data
R
# create a dataframe with 0 # along with numeric values and displaydata=data.frame(column1=c(1,2,3,0,0), column2=c(0,1,0,2,0)) # Actual datadata # replace 0 with NAdata[data==0]=NA print("===============") # displaydata
Output:
Example: R program to create a dataframe with strings along with 0 and replace 0 with NA
R
# create a dataframe with 0 # along with string values and displaydata=data.frame(column1=c("sravan","Bobby","ojaswi",0,0), column2=c(0,"Rohith",0,"Gnanesh",0)) # Actual datadata # replace 0 with NAdata[data==0]=NA print("===============") # displaydata
Output:
adnanirshad158
Picked
R DataFrame-Programs
R-DataFrame
R Language
R Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Change Color of Bars in Barchart using ggplot2 in R
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to Change Axis Scales in R Plots?
Replace Specific Characters in String in R
How to Split Column Into Multiple Columns in R DataFrame?
Replace Specific Characters in String in R
How to filter R DataFrame by values in a column?
How to filter R dataframe by multiple conditions?
Convert Matrix to Dataframe in R
|
[
{
"code": null,
"e": 26597,
"s": 26569,
"text": "\n31 Aug, 2021"
},
{
"code": null,
"e": 26710,
"s": 26597,
"text": "In this article, we are going to discuss how to replace 0 with NA values in dataframe in R Programming Language."
},
{
"code": null,
"e": 26938,
"s": 26710,
"text": "NA stands for Null values which can represent Null data / Null elements in a dataframe. The task can be achieved by first defining a dataframe that contains 0 as values. Then we can replace 0 with NA by using index operator []."
},
{
"code": null,
"e": 26946,
"s": 26938,
"text": "Syntax:"
},
{
"code": null,
"e": 26976,
"s": 26946,
"text": "dataframe[dataframe== 0] = NA"
},
{
"code": null,
"e": 26983,
"s": 26976,
"text": "where,"
},
{
"code": null,
"e": 27016,
"s": 26983,
"text": "dataframe is the input dataframe"
},
{
"code": null,
"e": 27102,
"s": 27016,
"text": "In index we are checking if the value is 0, if it is 0 then we are replacing it as NA"
},
{
"code": null,
"e": 27148,
"s": 27102,
"text": "Example: Replacing 0 with NA for integer data"
},
{
"code": null,
"e": 27150,
"s": 27148,
"text": "R"
},
{
"code": "# create a dataframe with 0 # along with numeric values and displaydata=data.frame(column1=c(1,2,3,0,0), column2=c(0,1,0,2,0)) # Actual datadata # replace 0 with NAdata[data==0]=NA print(\"===============\") # displaydata",
"e": 27385,
"s": 27150,
"text": null
},
{
"code": null,
"e": 27393,
"s": 27385,
"text": "Output:"
},
{
"code": null,
"e": 27482,
"s": 27393,
"text": "Example: R program to create a dataframe with strings along with 0 and replace 0 with NA"
},
{
"code": null,
"e": 27484,
"s": 27482,
"text": "R"
},
{
"code": "# create a dataframe with 0 # along with string values and displaydata=data.frame(column1=c(\"sravan\",\"Bobby\",\"ojaswi\",0,0), column2=c(0,\"Rohith\",0,\"Gnanesh\",0)) # Actual datadata # replace 0 with NAdata[data==0]=NA print(\"===============\") # displaydata",
"e": 27753,
"s": 27484,
"text": null
},
{
"code": null,
"e": 27761,
"s": 27753,
"text": "Output:"
},
{
"code": null,
"e": 27776,
"s": 27761,
"text": "adnanirshad158"
},
{
"code": null,
"e": 27783,
"s": 27776,
"text": "Picked"
},
{
"code": null,
"e": 27804,
"s": 27783,
"text": "R DataFrame-Programs"
},
{
"code": null,
"e": 27816,
"s": 27804,
"text": "R-DataFrame"
},
{
"code": null,
"e": 27827,
"s": 27816,
"text": "R Language"
},
{
"code": null,
"e": 27838,
"s": 27827,
"text": "R Programs"
},
{
"code": null,
"e": 27936,
"s": 27838,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27988,
"s": 27936,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 28023,
"s": 27988,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 28081,
"s": 28023,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28119,
"s": 28081,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 28162,
"s": 28119,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28220,
"s": 28162,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 28263,
"s": 28220,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 28312,
"s": 28263,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 28362,
"s": 28312,
"text": "How to filter R dataframe by multiple conditions?"
}
] |
Seven Clean Steps To Reshape Your Data With Pandas Or How I Use Python Where Excel Fails | by Tich Mangono | Towards Data Science
|
A few weeks ago, a colleague sent me a spreadsheet with data on a public health intervention, consisting of many tabs, one tab per organization. The task was to develop a flexible dashboard to explore this data. The problem was that the data was in wide format, but we needed a long format. Before, this would have been just another manual task of copy-and-paste and other dreadfully long and repetitive tasks, but I decided to use Python’s Pandas library to automate this task so I set to work developing the script. Within 30 minutes, I had flexible, reusable code which later saved me hours of unnecessary manual labor!
I would like to share with you my process in case it comes up in your own work. I will also show some tricks and explain the approach in detail. Of course, I have sanitized the data and generated dummy numbers for privacy, but the format and concepts to be tackled remain the same. Here’s a road map of what we will do with Pandas:
Set up the environment and load the dataInvestigate the dataParse the different data tabsStandardize existing columns and create new onesClean up the data using “apply” and “lambda” functionsReshape the data from wide to long by pivoting on multi-level indices and stackingConcatenate and save the final results back to Excel
Set up the environment and load the data
Investigate the data
Parse the different data tabs
Standardize existing columns and create new ones
Clean up the data using “apply” and “lambda” functions
Reshape the data from wide to long by pivoting on multi-level indices and stacking
Concatenate and save the final results back to Excel
We will also wrap this up into a neat function that can be reused to automate this task and save time. I have posted the code and data on my github account. Also, check out my blog for more ideas on Machine Learning, Python and Public Health. Let’s begin!
As advertised, we only need one Python library to execute this task: Pandas! Our data is an Excel file with several tabs. I like using the ExcelFile object functionality of Pandas as opposed to the read command because it handles multi-tab spreadsheets very well.
# Import the relevant libraries...# By the way, I am using Python 3import pandas as pd# Load the raw data using the ExcelFile objectdata = pd.ExcelFile('reshaping_data.xlsx')
We have four tabs in the file, each representing data from a single organization.
# First, see the sheetnames availabledata.sheet_namesOutput: ['ABC_inc', 'HIJ_inc', 'OPQ_inc', 'XYZ_inc']
Parsing the first tab for ABC_inc organization, we can see that the format needs a little work before we can use it as a standard data frame. The data contains the targets of a public health intervention. We can see that our column header names start in row 6, and we have information about the location (district, province); entities involved (partner, funding source); and target year (2017 to 2020). Notice also how row 7 has additional information on the target age group for this intervention for each year in the data. The main body of data starts from row 8 down.
# Take a peek at the first 10 rows of the first tabdata.parse(sheetname='ABC_inc', skiprows=0).head(10)
Make a list of your target tab names. In our case we want all of them. However, if you only wanted say 2 of these for analyses, then you could easily specify a different list.
tabnames = data.sheet_names
Since the tabs have a similar format, we will use only one them for this demonstration. At the end we will combine all the steps into a single, re-usable function and use iteration to apply the function to all the target tabs. We will then concatenate and save the results. So, parse the tab into a data frame, df, skipping the useless empty rows at the top. I always use “data.head()” to check my result and make sure my code did what I expected.
i = 0df = data.parse(sheetname=tabnames[i], skiprows=7)df.head(2)
Make a list of the default columns. We will throw away some but also strip the rest of them for information to be used for new column names. We will need to retain our information on the particular year, age-group and organization.
# make a list of the header row and strip up to the 4th letter. This is the location and year informationcols1 = list(df.columns)cols1 = [str(x)[:4] for x in cols1]# make another list of the first row,this is the age group information# we need to preserve this information in the column name when we reshape the data cols2 = list(df.iloc[0,:])cols2 = [str(x) for x in cols2]# now join the two lists to make a combined column name which preserves our location, year and age-group informationcols = [x+"_"+y for x,y in zip(cols1,cols2)]# Assign new column names to the dataframedf.columns = colsdf.head(1)
# Drop empty columns, Rename the useful columns# Note when you drop, you should specify axis=1 for columns and axis=0 for rowsdf = df.drop(["Unna_nan"], axis=1).iloc[1:,:].rename(columns= {'dist_nan':'district', 'prov_nan': 'province', 'part_nan':'partner', 'fund_nan':'financing_source'})df.head(2)
# Engineer a new column for the organization, grab this name from the excel tab name# This should read 'ABC inc' if executed correctlydf['main_organization'] = tabnames[i].split("_")[0] + " "+ tabnames[i].split("_")[1]df.main_organization.head(2)Output:1 ABC inc2 ABC incName: main_organization, dtype: object
Let’s pause and look at the structure of our dataframe so far.
df.info()
We see that we have 29 columns in all. However, currently, all of them have the “object” data type and we know some of them should have a numeric data type. We also have redundant “Total” columns. Notice that the column names still retain multiple levels of information, i.e. the year and the age-group to which the data in that particular column belongs! This is one of the key aspects of this exercise as we will see in the next step. Before that, let’s clean up a little bit...
Let’s remove more redundant columns and change the data types.
# Make lists of the columns which need attention and use this as reference to execute# You will notice that I use list comprehension every time I generate an iterable like a list or dictionary# This is really amazing python functionality and I never want to go back to the old looping way of doing this!to_remove = [c for c in df.columns if "Total" in c] # redundantto_change = [c for c in df.columns if "yrs" in c] # numeric# drop unwanted columns# Notice that you need to specify inplace, otherwise pandas will return the data frame instead of changing it in placedf.drop(to_remove, axis=1, inplace= True) # Change the target column data typesfor c in to_change: df[c] = df[c].apply(lambda x: pd.to_numeric(x))
See the changes:
df.info()
Looks like it worked!
Now, on to my favorite part — reshaping the data! This functionality gives you so much power when it comes to data.It’s one that I use so often for data cleaning and manipulation given the popularity of spreadsheets and survey-type data in my work. To me reshaping data literally feels like the data is clay and I am molding it with my very hands :). So, we will use pivoting on strategic indices and then use stacking to achieve the shape we want. Currently, the data is in a wide format, but we need to change it to long format so that we can easily transfer it to Excel where long formats lend themselves to quick pivot tables and dashboard creation very easily.
# First, select the columns to use for a multi-level index. This depends on your data# Generally, you want all the identifier columns to be included in the multi-index # For this dataset, this is every non-numeric columnidx =['district','province','partner','financing_source','main_organization']# Then pivot the dataset based on this multi-level index multi_indexed_df = df.set_index(idx)multi_indexed_df.head(2)
After pivoting the data frame on our strategically engineered multi-level index, we will now stack all the numerical columns. This will give us the flexibility to reshape the data back to whatever level we want afterwards, just like an Excel pivot table.
# Stack the columns to achieve the baseline long format for the datastacked_df = multi_indexed_df.stack(dropna=False)stacked_df.head(25) # check out the results!
Mind. Blown! Exactly how I felt when I saw this for the first time too.
# Now do a reset to disband the multi-level index, we only needed it to pivot our data during the reshapelong_df = stacked_df.reset_index()long_df.head(3)
Notice that the “level_5” column contains two pieces of information. This was deliberately done from the beginning so as not to lose any information along the way as we drop some columns and rows. Now, lets use string manipulation to separate these and delete any redundancies after that.
# Make series of lists which split year from target age-group# the .str attribute is how you manipulate the data frame objects and columns with strings in themcol_str = long_df.level_5.str.split("_") col_str.head(3)Output:0 [2017, 10-14yrs]1 [2017, 15-29yrs]2 [2017, 30+yrs]Name: level_5, dtype: object# engineer the columns we want, one columns takes the first item in col_str and another columns takes the second long_df['target_year'] = [x[0] for x in col_str] long_df['target_age'] = [x[1] for x in col_str]long_df['target_quantity'] = long_df[0] # rename this columnlong_df.head(2)
# drop the now redundant columnsdf_final = long_df.drop(['level_5', 0], axis=1)df_final.head(2)
Now we have all the ingredients we need, we can define a function to automate the reshape, use iteration to apply this function to any number of tabs we want and then finally save this to our spreadsheet of choice! Notice that in the function I combine the shapes and add an assertion to check that the inputs are correct, but it mostly the same code.
# Now define a function for doing the reshapedef ReshapeFunc(excel_obj, i): """ Takes in an excel file object with multiple tabs in a wide format, and a specified index of the tab to be parsed and reshaped. Returns a data frame of the specified tab reshaped to long format""" tabnames = data.sheet_names assert i < len(tabnames), "Your tab index exceeds the number of available tabs, try a lower number" # parse and clean columns df = excel_obj.parse(sheetname=tabnames[i], skiprows=7) cols1 = [str(x)[:4] for x in list(df.columns)] cols2 = [str(x) for x in list(df.iloc[0,:])] cols = [x+"_"+y for x,y in zip(cols1,cols2)] df.columns = cols df = df.drop(["Unna_nan"], axis=1).iloc[1:,:].rename(columns={'dist_nan':'district', 'prov_nan': 'province', 'part_nan':'partner', 'fund_nan':'financing_source'}) # new columns, drop some and change data type df['main_organization'] = tabnames[i].split("_")[0] + " "+ tabnames[i].split("_")[1] df.drop([c for c in df.columns if "Total" in c], axis=1, inplace= True) for c in [c for c in df.columns if "yrs" in c]: df[c] = df[c].apply(lambda x: pd.to_numeric(x)) # reshape - indexing, pivoting and stacking idx = ['district','province', 'partner','financing_source','main_organization'] multi_indexed_df = df.set_index(idx) stacked_df = multi_indexed_df.stack(dropna=False) long_df = stacked_df.reset_index() # clean up and finalize col_str = long_df.level_5.str.split("_") long_df['target_year'] = [x[0] for x in col_str] long_df['target_age'] = [x[1] for x in col_str] long_df['target_quantity'] = long_df[0] # rename this column df_final = long_df.drop(['level_5', 0], axis=1) return df_final
Run the function
# Check that our function works:check_df = ReshapeFunc(data, 2)check_df.head(2)
Cool! Now use the function to make a data frame for each tab, put them all in a list, concatenate them into one single data frame and save it back to Excel.
dfs_list = [ReshapeFunc(data, i) for i in range(4)]concat_dfs = pd.concat(dfs_list)concat_dfs.to_excel("reshaping_result_long_format.xlsx")
This long format can now be easily used for pivot tables and making dashboard charts and analysis by pivoting on any combination of the descriptive, non-numeric columns and aggregating the numeric columns. Mission complete. Happy Coding!
|
[
{
"code": null,
"e": 670,
"s": 47,
"text": "A few weeks ago, a colleague sent me a spreadsheet with data on a public health intervention, consisting of many tabs, one tab per organization. The task was to develop a flexible dashboard to explore this data. The problem was that the data was in wide format, but we needed a long format. Before, this would have been just another manual task of copy-and-paste and other dreadfully long and repetitive tasks, but I decided to use Python’s Pandas library to automate this task so I set to work developing the script. Within 30 minutes, I had flexible, reusable code which later saved me hours of unnecessary manual labor!"
},
{
"code": null,
"e": 1002,
"s": 670,
"text": "I would like to share with you my process in case it comes up in your own work. I will also show some tricks and explain the approach in detail. Of course, I have sanitized the data and generated dummy numbers for privacy, but the format and concepts to be tackled remain the same. Here’s a road map of what we will do with Pandas:"
},
{
"code": null,
"e": 1328,
"s": 1002,
"text": "Set up the environment and load the dataInvestigate the dataParse the different data tabsStandardize existing columns and create new onesClean up the data using “apply” and “lambda” functionsReshape the data from wide to long by pivoting on multi-level indices and stackingConcatenate and save the final results back to Excel"
},
{
"code": null,
"e": 1369,
"s": 1328,
"text": "Set up the environment and load the data"
},
{
"code": null,
"e": 1390,
"s": 1369,
"text": "Investigate the data"
},
{
"code": null,
"e": 1420,
"s": 1390,
"text": "Parse the different data tabs"
},
{
"code": null,
"e": 1469,
"s": 1420,
"text": "Standardize existing columns and create new ones"
},
{
"code": null,
"e": 1524,
"s": 1469,
"text": "Clean up the data using “apply” and “lambda” functions"
},
{
"code": null,
"e": 1607,
"s": 1524,
"text": "Reshape the data from wide to long by pivoting on multi-level indices and stacking"
},
{
"code": null,
"e": 1660,
"s": 1607,
"text": "Concatenate and save the final results back to Excel"
},
{
"code": null,
"e": 1916,
"s": 1660,
"text": "We will also wrap this up into a neat function that can be reused to automate this task and save time. I have posted the code and data on my github account. Also, check out my blog for more ideas on Machine Learning, Python and Public Health. Let’s begin!"
},
{
"code": null,
"e": 2180,
"s": 1916,
"text": "As advertised, we only need one Python library to execute this task: Pandas! Our data is an Excel file with several tabs. I like using the ExcelFile object functionality of Pandas as opposed to the read command because it handles multi-tab spreadsheets very well."
},
{
"code": null,
"e": 2355,
"s": 2180,
"text": "# Import the relevant libraries...# By the way, I am using Python 3import pandas as pd# Load the raw data using the ExcelFile objectdata = pd.ExcelFile('reshaping_data.xlsx')"
},
{
"code": null,
"e": 2437,
"s": 2355,
"text": "We have four tabs in the file, each representing data from a single organization."
},
{
"code": null,
"e": 2543,
"s": 2437,
"text": "# First, see the sheetnames availabledata.sheet_namesOutput: ['ABC_inc', 'HIJ_inc', 'OPQ_inc', 'XYZ_inc']"
},
{
"code": null,
"e": 3114,
"s": 2543,
"text": "Parsing the first tab for ABC_inc organization, we can see that the format needs a little work before we can use it as a standard data frame. The data contains the targets of a public health intervention. We can see that our column header names start in row 6, and we have information about the location (district, province); entities involved (partner, funding source); and target year (2017 to 2020). Notice also how row 7 has additional information on the target age group for this intervention for each year in the data. The main body of data starts from row 8 down."
},
{
"code": null,
"e": 3218,
"s": 3114,
"text": "# Take a peek at the first 10 rows of the first tabdata.parse(sheetname='ABC_inc', skiprows=0).head(10)"
},
{
"code": null,
"e": 3394,
"s": 3218,
"text": "Make a list of your target tab names. In our case we want all of them. However, if you only wanted say 2 of these for analyses, then you could easily specify a different list."
},
{
"code": null,
"e": 3422,
"s": 3394,
"text": "tabnames = data.sheet_names"
},
{
"code": null,
"e": 3870,
"s": 3422,
"text": "Since the tabs have a similar format, we will use only one them for this demonstration. At the end we will combine all the steps into a single, re-usable function and use iteration to apply the function to all the target tabs. We will then concatenate and save the results. So, parse the tab into a data frame, df, skipping the useless empty rows at the top. I always use “data.head()” to check my result and make sure my code did what I expected."
},
{
"code": null,
"e": 3936,
"s": 3870,
"text": "i = 0df = data.parse(sheetname=tabnames[i], skiprows=7)df.head(2)"
},
{
"code": null,
"e": 4168,
"s": 3936,
"text": "Make a list of the default columns. We will throw away some but also strip the rest of them for information to be used for new column names. We will need to retain our information on the particular year, age-group and organization."
},
{
"code": null,
"e": 4772,
"s": 4168,
"text": "# make a list of the header row and strip up to the 4th letter. This is the location and year informationcols1 = list(df.columns)cols1 = [str(x)[:4] for x in cols1]# make another list of the first row,this is the age group information# we need to preserve this information in the column name when we reshape the data cols2 = list(df.iloc[0,:])cols2 = [str(x) for x in cols2]# now join the two lists to make a combined column name which preserves our location, year and age-group informationcols = [x+\"_\"+y for x,y in zip(cols1,cols2)]# Assign new column names to the dataframedf.columns = colsdf.head(1)"
},
{
"code": null,
"e": 5220,
"s": 4772,
"text": "# Drop empty columns, Rename the useful columns# Note when you drop, you should specify axis=1 for columns and axis=0 for rowsdf = df.drop([\"Unna_nan\"], axis=1).iloc[1:,:].rename(columns= {'dist_nan':'district', 'prov_nan': 'province', 'part_nan':'partner', 'fund_nan':'financing_source'})df.head(2)"
},
{
"code": null,
"e": 5536,
"s": 5220,
"text": "# Engineer a new column for the organization, grab this name from the excel tab name# This should read 'ABC inc' if executed correctlydf['main_organization'] = tabnames[i].split(\"_\")[0] + \" \"+ tabnames[i].split(\"_\")[1]df.main_organization.head(2)Output:1 ABC inc2 ABC incName: main_organization, dtype: object"
},
{
"code": null,
"e": 5599,
"s": 5536,
"text": "Let’s pause and look at the structure of our dataframe so far."
},
{
"code": null,
"e": 5609,
"s": 5599,
"text": "df.info()"
},
{
"code": null,
"e": 6090,
"s": 5609,
"text": "We see that we have 29 columns in all. However, currently, all of them have the “object” data type and we know some of them should have a numeric data type. We also have redundant “Total” columns. Notice that the column names still retain multiple levels of information, i.e. the year and the age-group to which the data in that particular column belongs! This is one of the key aspects of this exercise as we will see in the next step. Before that, let’s clean up a little bit..."
},
{
"code": null,
"e": 6153,
"s": 6090,
"text": "Let’s remove more redundant columns and change the data types."
},
{
"code": null,
"e": 6869,
"s": 6153,
"text": "# Make lists of the columns which need attention and use this as reference to execute# You will notice that I use list comprehension every time I generate an iterable like a list or dictionary# This is really amazing python functionality and I never want to go back to the old looping way of doing this!to_remove = [c for c in df.columns if \"Total\" in c] # redundantto_change = [c for c in df.columns if \"yrs\" in c] # numeric# drop unwanted columns# Notice that you need to specify inplace, otherwise pandas will return the data frame instead of changing it in placedf.drop(to_remove, axis=1, inplace= True) # Change the target column data typesfor c in to_change: df[c] = df[c].apply(lambda x: pd.to_numeric(x))"
},
{
"code": null,
"e": 6886,
"s": 6869,
"text": "See the changes:"
},
{
"code": null,
"e": 6896,
"s": 6886,
"text": "df.info()"
},
{
"code": null,
"e": 6918,
"s": 6896,
"text": "Looks like it worked!"
},
{
"code": null,
"e": 7584,
"s": 6918,
"text": "Now, on to my favorite part — reshaping the data! This functionality gives you so much power when it comes to data.It’s one that I use so often for data cleaning and manipulation given the popularity of spreadsheets and survey-type data in my work. To me reshaping data literally feels like the data is clay and I am molding it with my very hands :). So, we will use pivoting on strategic indices and then use stacking to achieve the shape we want. Currently, the data is in a wide format, but we need to change it to long format so that we can easily transfer it to Excel where long formats lend themselves to quick pivot tables and dashboard creation very easily."
},
{
"code": null,
"e": 7999,
"s": 7584,
"text": "# First, select the columns to use for a multi-level index. This depends on your data# Generally, you want all the identifier columns to be included in the multi-index # For this dataset, this is every non-numeric columnidx =['district','province','partner','financing_source','main_organization']# Then pivot the dataset based on this multi-level index multi_indexed_df = df.set_index(idx)multi_indexed_df.head(2)"
},
{
"code": null,
"e": 8254,
"s": 7999,
"text": "After pivoting the data frame on our strategically engineered multi-level index, we will now stack all the numerical columns. This will give us the flexibility to reshape the data back to whatever level we want afterwards, just like an Excel pivot table."
},
{
"code": null,
"e": 8416,
"s": 8254,
"text": "# Stack the columns to achieve the baseline long format for the datastacked_df = multi_indexed_df.stack(dropna=False)stacked_df.head(25) # check out the results!"
},
{
"code": null,
"e": 8488,
"s": 8416,
"text": "Mind. Blown! Exactly how I felt when I saw this for the first time too."
},
{
"code": null,
"e": 8643,
"s": 8488,
"text": "# Now do a reset to disband the multi-level index, we only needed it to pivot our data during the reshapelong_df = stacked_df.reset_index()long_df.head(3)"
},
{
"code": null,
"e": 8932,
"s": 8643,
"text": "Notice that the “level_5” column contains two pieces of information. This was deliberately done from the beginning so as not to lose any information along the way as we drop some columns and rows. Now, lets use string manipulation to separate these and delete any redundancies after that."
},
{
"code": null,
"e": 9528,
"s": 8932,
"text": "# Make series of lists which split year from target age-group# the .str attribute is how you manipulate the data frame objects and columns with strings in themcol_str = long_df.level_5.str.split(\"_\") col_str.head(3)Output:0 [2017, 10-14yrs]1 [2017, 15-29yrs]2 [2017, 30+yrs]Name: level_5, dtype: object# engineer the columns we want, one columns takes the first item in col_str and another columns takes the second long_df['target_year'] = [x[0] for x in col_str] long_df['target_age'] = [x[1] for x in col_str]long_df['target_quantity'] = long_df[0] # rename this columnlong_df.head(2)"
},
{
"code": null,
"e": 9624,
"s": 9528,
"text": "# drop the now redundant columnsdf_final = long_df.drop(['level_5', 0], axis=1)df_final.head(2)"
},
{
"code": null,
"e": 9976,
"s": 9624,
"text": "Now we have all the ingredients we need, we can define a function to automate the reshape, use iteration to apply this function to any number of tabs we want and then finally save this to our spreadsheet of choice! Notice that in the function I combine the shapes and add an assertion to check that the inputs are correct, but it mostly the same code."
},
{
"code": null,
"e": 11855,
"s": 9976,
"text": "# Now define a function for doing the reshapedef ReshapeFunc(excel_obj, i): \"\"\" Takes in an excel file object with multiple tabs in a wide format, and a specified index of the tab to be parsed and reshaped. Returns a data frame of the specified tab reshaped to long format\"\"\" tabnames = data.sheet_names assert i < len(tabnames), \"Your tab index exceeds the number of available tabs, try a lower number\" # parse and clean columns df = excel_obj.parse(sheetname=tabnames[i], skiprows=7) cols1 = [str(x)[:4] for x in list(df.columns)] cols2 = [str(x) for x in list(df.iloc[0,:])] cols = [x+\"_\"+y for x,y in zip(cols1,cols2)] df.columns = cols df = df.drop([\"Unna_nan\"], axis=1).iloc[1:,:].rename(columns={'dist_nan':'district', 'prov_nan': 'province', 'part_nan':'partner', 'fund_nan':'financing_source'}) # new columns, drop some and change data type df['main_organization'] = tabnames[i].split(\"_\")[0] + \" \"+ tabnames[i].split(\"_\")[1] df.drop([c for c in df.columns if \"Total\" in c], axis=1, inplace= True) for c in [c for c in df.columns if \"yrs\" in c]: df[c] = df[c].apply(lambda x: pd.to_numeric(x)) # reshape - indexing, pivoting and stacking idx = ['district','province', 'partner','financing_source','main_organization'] multi_indexed_df = df.set_index(idx) stacked_df = multi_indexed_df.stack(dropna=False) long_df = stacked_df.reset_index() # clean up and finalize col_str = long_df.level_5.str.split(\"_\") long_df['target_year'] = [x[0] for x in col_str] long_df['target_age'] = [x[1] for x in col_str] long_df['target_quantity'] = long_df[0] # rename this column df_final = long_df.drop(['level_5', 0], axis=1) return df_final"
},
{
"code": null,
"e": 11872,
"s": 11855,
"text": "Run the function"
},
{
"code": null,
"e": 11952,
"s": 11872,
"text": "# Check that our function works:check_df = ReshapeFunc(data, 2)check_df.head(2)"
},
{
"code": null,
"e": 12109,
"s": 11952,
"text": "Cool! Now use the function to make a data frame for each tab, put them all in a list, concatenate them into one single data frame and save it back to Excel."
},
{
"code": null,
"e": 12250,
"s": 12109,
"text": "dfs_list = [ReshapeFunc(data, i) for i in range(4)]concat_dfs = pd.concat(dfs_list)concat_dfs.to_excel(\"reshaping_result_long_format.xlsx\")"
}
] |
Bootstrap 5 Alerts - GeeksforGeeks
|
05 May, 2022
Bootstrap 5 is the latest major release of Bootstrap where the UI has been revamped and various changes have been made. Alerts provide contextual feedback messages for typical user actions with a handful of available and flexible alert messages. Bootstrap allows showing these alert messages on the website using predefined classes. Each of the classes has different colors associated with them.
Syntax:
<div class="alert alert-type"> Contents of the alert... <div>
Types: There are eight types of alerts available in Bootstrap 5. The classes of these alerts are given below:
alert-primary
alert-secondary
alert-success
alert-danger
alert-warning
alert-info
alert-light
alert-dark
Example 1: This example shows the first four types of Alerts in Bootstrap 5.
HTML
<!DOCTYPE html><html><head> <title> Bootstrap 5 | Alerts </title> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"></head><body> <div style="text-align: center; width:600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> </div> <div id="canvas" style="width: 600px; height: 200px; margin: 20px;"> <div class="alert alert-primary" role="alert"> GeeksforGeeks </div> <div class="alert alert-secondary" role="alert"> GeeksforGeeks </div> <div class="alert alert-success" role="alert"> GeeksforGeeks </div> <div class="alert alert-danger" role="alert"> GeeksforGeeks </div> </div></body></html>
Output:
Example 2: This example shows the next four types of Alerts in Bootstrap 5.
HTML
<!DOCTYPE html><html><head> <title> Bootstrap 5 | Alerts </title> <!-- Load Bootstrap --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css"></head><body> <div style="text-align: center; width: 600px;"> <h1 style="color: green;"> GeeksforGeeks </h1> </div> <div id="canvas" style="width: 600px; height: 200px; margin: 20px;"> <div class="alert alert-warning" role="alert"> GeeksforGeeks </div> <div class="alert alert-info" role="alert"> GeeksforGeeks </div> <div class="alert alert-light" role="alert"> GeeksforGeeks </div> <div class="alert alert-dark" role="alert"> GeeksforGeeks </div> </div></body></html>
Output:
blalverma92
sahilintern
Bootstrap-Misc
Bootstrap
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Form validation using jQuery
How to change navigation bar color in Bootstrap ?
How to pass data into a bootstrap modal?
How to align navbar items to the right in Bootstrap 4 ?
How to Show Images on Click using HTML ?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
|
[
{
"code": null,
"e": 28538,
"s": 28510,
"text": "\n05 May, 2022"
},
{
"code": null,
"e": 28934,
"s": 28538,
"text": "Bootstrap 5 is the latest major release of Bootstrap where the UI has been revamped and various changes have been made. Alerts provide contextual feedback messages for typical user actions with a handful of available and flexible alert messages. Bootstrap allows showing these alert messages on the website using predefined classes. Each of the classes has different colors associated with them."
},
{
"code": null,
"e": 28942,
"s": 28934,
"text": "Syntax:"
},
{
"code": null,
"e": 29004,
"s": 28942,
"text": "<div class=\"alert alert-type\"> Contents of the alert... <div>"
},
{
"code": null,
"e": 29114,
"s": 29004,
"text": "Types: There are eight types of alerts available in Bootstrap 5. The classes of these alerts are given below:"
},
{
"code": null,
"e": 29128,
"s": 29114,
"text": "alert-primary"
},
{
"code": null,
"e": 29144,
"s": 29128,
"text": "alert-secondary"
},
{
"code": null,
"e": 29158,
"s": 29144,
"text": "alert-success"
},
{
"code": null,
"e": 29171,
"s": 29158,
"text": "alert-danger"
},
{
"code": null,
"e": 29185,
"s": 29171,
"text": "alert-warning"
},
{
"code": null,
"e": 29196,
"s": 29185,
"text": "alert-info"
},
{
"code": null,
"e": 29208,
"s": 29196,
"text": "alert-light"
},
{
"code": null,
"e": 29219,
"s": 29208,
"text": "alert-dark"
},
{
"code": null,
"e": 29296,
"s": 29219,
"text": "Example 1: This example shows the first four types of Alerts in Bootstrap 5."
},
{
"code": null,
"e": 29301,
"s": 29296,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title> Bootstrap 5 | Alerts </title> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\"></head><body> <div style=\"text-align: center; width:600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> </div> <div id=\"canvas\" style=\"width: 600px; height: 200px; margin: 20px;\"> <div class=\"alert alert-primary\" role=\"alert\"> GeeksforGeeks </div> <div class=\"alert alert-secondary\" role=\"alert\"> GeeksforGeeks </div> <div class=\"alert alert-success\" role=\"alert\"> GeeksforGeeks </div> <div class=\"alert alert-danger\" role=\"alert\"> GeeksforGeeks </div> </div></body></html>",
"e": 30159,
"s": 29301,
"text": null
},
{
"code": null,
"e": 30167,
"s": 30159,
"text": "Output:"
},
{
"code": null,
"e": 30243,
"s": 30167,
"text": "Example 2: This example shows the next four types of Alerts in Bootstrap 5."
},
{
"code": null,
"e": 30248,
"s": 30243,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <title> Bootstrap 5 | Alerts </title> <!-- Load Bootstrap --> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css\"></head><body> <div style=\"text-align: center; width: 600px;\"> <h1 style=\"color: green;\"> GeeksforGeeks </h1> </div> <div id=\"canvas\" style=\"width: 600px; height: 200px; margin: 20px;\"> <div class=\"alert alert-warning\" role=\"alert\"> GeeksforGeeks </div> <div class=\"alert alert-info\" role=\"alert\"> GeeksforGeeks </div> <div class=\"alert alert-light\" role=\"alert\"> GeeksforGeeks </div> <div class=\"alert alert-dark\" role=\"alert\"> GeeksforGeeks </div> </div></body></html>",
"e": 31100,
"s": 30248,
"text": null
},
{
"code": null,
"e": 31108,
"s": 31100,
"text": "Output:"
},
{
"code": null,
"e": 31120,
"s": 31108,
"text": "blalverma92"
},
{
"code": null,
"e": 31132,
"s": 31120,
"text": "sahilintern"
},
{
"code": null,
"e": 31147,
"s": 31132,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 31157,
"s": 31147,
"text": "Bootstrap"
},
{
"code": null,
"e": 31174,
"s": 31157,
"text": "Web Technologies"
},
{
"code": null,
"e": 31272,
"s": 31174,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31301,
"s": 31272,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 31351,
"s": 31301,
"text": "How to change navigation bar color in Bootstrap ?"
},
{
"code": null,
"e": 31392,
"s": 31351,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 31448,
"s": 31392,
"text": "How to align navbar items to the right in Bootstrap 4 ?"
},
{
"code": null,
"e": 31489,
"s": 31448,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 31529,
"s": 31489,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 31562,
"s": 31529,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31607,
"s": 31562,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31650,
"s": 31607,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Neural Network Calibration with Keras | by Marco Cerliani | Towards Data Science
|
The concept of probability is very common in the machine learning field. In classification tasks, probabilities are the output scores of almost every predictive model together with the relative labels. Show them together is more informative than providing only a raw classification report. In this way, we use probabilities as confidence scores to approximate the uncertainty of our model predictions. This is a common practice and reflects how we reason.
The problem is that our algorithms aren’t intelligent enough to provide probabilities in the form of trustable confidence scores. They tend to not calibrate results, i.e. they overestimate or underestimate probabilities if we compare them with the expected accuracy. This results in misleading reliability, corrupting our decision policy.
In this post, we want to play with probabilities facing the problem of neural network calibration. As we’ll see, build a calibrated model is not obvious and we must take care during its development. We operate the adequate technique to calibrate scores in a real classification problem to not get kicked in auto auctions where the risk is to purchase a ‘lemon’.
The dataset is collected from Kaggle, from a past competition ‘Don’t Get Kicked!’. The challenge of this competition is to predict if the car purchased at the Auction is a Kick (bad buy). Kicked cars often result when there are serious issues or some other unforeseen problems on vehicles, causing high costs to dealers. We have to figure out which cars have a higher risk of being kick, providing real value to dealerships. The problem can be carried out as a binary classification task (good or bad buy?).
The variables at our disposal are a mix of categorical and numerical:
We operate a standard preprocessing: NaNs values are filled with medians (for numerical) and ‘unknown’ class (for categorical). The numerical variables are then standard scaled and the categorical are ordinally encoded.
The model, used to predict if our purchase is a good deal, is a feed-forward neural network with categorical embeddings. The categorical embeddings are connected at the second level, while in the final parts we maintain the separation among raw output layer (logits) and activation (softmax) for probability computation. This little trick will be useful for us when we’ll have to calibrate our model.
def get_model(cat_feat, emb_dim=8): def get_embed(inp, size, emb_dim, name): emb = Embedding(size, emb_dim)(inp) emb = Flatten(name=name)(emb) return emb inp_dense = Input(shape=len(num_)) embs, inps = [], [inp_dense] x = Dense(128, activation='relu')(inp_dense) for f in cat_feat: inp = Input((1,), name=f+'_inp') embs.append(get_embed(inp, cat_[f]+1, emb_dim, f)) inps.append(inp) x = Concatenate()([x]+embs) x = BatchNormalization()(x) x = Dropout(0.3)(x) x = Dense(64, activation='relu')(x) x = Dropout(0.3)(x) x = Dense(32, activation='relu')(x) logits = Dense(2, name='logits')(x) out = Activation('softmax')(logits) model = Model(inps, out) model.compile(optimizer='adam', loss ='categorical_crossentropy', metrics=[tf.keras.metrics.AUC()]) return model
We separate our initial dataset in train, validation, and test. The validation will be firstly used for network tuning and in the second stage to fit the temperature scale coefficient for the calibration procedure. After fitting we achieve 0.90% accuracy with great precision on the test data, which is better than a random model that classifies all cars as a good deal.
As we can see, our model can grant good performance on unseen data. But how reliable this result is? The advantage of predicting well-calibrated probabilities is that we can be confident if the predicted probability is close to 1 or 0, and not so confident otherwise. In our case, if not, our classifier may over-predict similar cars as ‘lemon’ which may result in decisions to not buy cars which are actually in good condition.
By definition, a model is perfectly calibrated if, for any probability value p, correspond a prediction of a class with an accuracy level of p*100 %. To check if our classifier is well-calibrated all we need to do is a plot! At the same time, produce calibrated probabilities is very simple as applying a post-process technique.
The first step is to plot the reliability diagram, where we can compare the expected accuracy versus prediction confidences. The fraction of positives and mean predicted value are calculated, for convenience reasons, per equal-width groups/bins. This can be computed for binary or multiclass problems and results in a curve for each class.
The optimal situation is when we have a perfect linear relationship between the computed probability and the fraction of positives (blue dashed line). In our case, our neural network tends to respectively overestimate and underestimate a little the probabilities of the two classes in the middle. We can quantify the goodness of calibration with a proper index, the so-called Expected Calibration Error (ECE), that is the weighted (proportion of samples in each bin) average of the difference between expected accuracy and prediction confidence (the lower the better).
We can adjust the ECE by applying a technique, which is an extension of Temperature scaling, known as Platt scaling. The neural network outputs a vector known as logits. Platt scaling simply divides the logits vector by a learned scalar parameter T, before passing it through a softmax function to get class probabilities.
Practically speaking with few lines of code, we can build our function to compute the Temperature scaling. The scaling factor T is learned on a predefined validation set, where we try to minimize a mean cost function (in TensorFlow: tf.nn.softmax_cross_entropy_with_logits). The inputs and output will be respectively our logits, scaled with the learnable T, and the true output in the form of dummy vectors. The train is computed classically with the stochastic gradient descent method.
In the end, the ECE score on the scaled probability records an improvement in both the classes. As we can also see above on the new reliability diagrams, we can produce better-calibrated probabilities.
In this post, we’ve examined a post-process technique to calibrate the probabilities of our neural network and let it, when it’ possible (not always temperature scaling is effective), a more trustable instrument. It’s a very simple trick applicable anywhere, which became useful if we care about the probabilities our model computes to make a decision.
CHECK MY GITHUB REPO
Keep in touch: Linkedin
REFERENCES
StellarGraph — Machine Learning on Graphs
On Calibration of Modern Neural Networks: Chuan Guo, Geoff Pleiss, Yu Sun, Kilian Q. Weinberger
|
[
{
"code": null,
"e": 628,
"s": 172,
"text": "The concept of probability is very common in the machine learning field. In classification tasks, probabilities are the output scores of almost every predictive model together with the relative labels. Show them together is more informative than providing only a raw classification report. In this way, we use probabilities as confidence scores to approximate the uncertainty of our model predictions. This is a common practice and reflects how we reason."
},
{
"code": null,
"e": 967,
"s": 628,
"text": "The problem is that our algorithms aren’t intelligent enough to provide probabilities in the form of trustable confidence scores. They tend to not calibrate results, i.e. they overestimate or underestimate probabilities if we compare them with the expected accuracy. This results in misleading reliability, corrupting our decision policy."
},
{
"code": null,
"e": 1329,
"s": 967,
"text": "In this post, we want to play with probabilities facing the problem of neural network calibration. As we’ll see, build a calibrated model is not obvious and we must take care during its development. We operate the adequate technique to calibrate scores in a real classification problem to not get kicked in auto auctions where the risk is to purchase a ‘lemon’."
},
{
"code": null,
"e": 1837,
"s": 1329,
"text": "The dataset is collected from Kaggle, from a past competition ‘Don’t Get Kicked!’. The challenge of this competition is to predict if the car purchased at the Auction is a Kick (bad buy). Kicked cars often result when there are serious issues or some other unforeseen problems on vehicles, causing high costs to dealers. We have to figure out which cars have a higher risk of being kick, providing real value to dealerships. The problem can be carried out as a binary classification task (good or bad buy?)."
},
{
"code": null,
"e": 1907,
"s": 1837,
"text": "The variables at our disposal are a mix of categorical and numerical:"
},
{
"code": null,
"e": 2127,
"s": 1907,
"text": "We operate a standard preprocessing: NaNs values are filled with medians (for numerical) and ‘unknown’ class (for categorical). The numerical variables are then standard scaled and the categorical are ordinally encoded."
},
{
"code": null,
"e": 2528,
"s": 2127,
"text": "The model, used to predict if our purchase is a good deal, is a feed-forward neural network with categorical embeddings. The categorical embeddings are connected at the second level, while in the final parts we maintain the separation among raw output layer (logits) and activation (softmax) for probability computation. This little trick will be useful for us when we’ll have to calibrate our model."
},
{
"code": null,
"e": 3455,
"s": 2528,
"text": "def get_model(cat_feat, emb_dim=8): def get_embed(inp, size, emb_dim, name): emb = Embedding(size, emb_dim)(inp) emb = Flatten(name=name)(emb) return emb inp_dense = Input(shape=len(num_)) embs, inps = [], [inp_dense] x = Dense(128, activation='relu')(inp_dense) for f in cat_feat: inp = Input((1,), name=f+'_inp') embs.append(get_embed(inp, cat_[f]+1, emb_dim, f)) inps.append(inp) x = Concatenate()([x]+embs) x = BatchNormalization()(x) x = Dropout(0.3)(x) x = Dense(64, activation='relu')(x) x = Dropout(0.3)(x) x = Dense(32, activation='relu')(x) logits = Dense(2, name='logits')(x) out = Activation('softmax')(logits) model = Model(inps, out) model.compile(optimizer='adam', loss ='categorical_crossentropy', metrics=[tf.keras.metrics.AUC()]) return model"
},
{
"code": null,
"e": 3826,
"s": 3455,
"text": "We separate our initial dataset in train, validation, and test. The validation will be firstly used for network tuning and in the second stage to fit the temperature scale coefficient for the calibration procedure. After fitting we achieve 0.90% accuracy with great precision on the test data, which is better than a random model that classifies all cars as a good deal."
},
{
"code": null,
"e": 4255,
"s": 3826,
"text": "As we can see, our model can grant good performance on unseen data. But how reliable this result is? The advantage of predicting well-calibrated probabilities is that we can be confident if the predicted probability is close to 1 or 0, and not so confident otherwise. In our case, if not, our classifier may over-predict similar cars as ‘lemon’ which may result in decisions to not buy cars which are actually in good condition."
},
{
"code": null,
"e": 4584,
"s": 4255,
"text": "By definition, a model is perfectly calibrated if, for any probability value p, correspond a prediction of a class with an accuracy level of p*100 %. To check if our classifier is well-calibrated all we need to do is a plot! At the same time, produce calibrated probabilities is very simple as applying a post-process technique."
},
{
"code": null,
"e": 4924,
"s": 4584,
"text": "The first step is to plot the reliability diagram, where we can compare the expected accuracy versus prediction confidences. The fraction of positives and mean predicted value are calculated, for convenience reasons, per equal-width groups/bins. This can be computed for binary or multiclass problems and results in a curve for each class."
},
{
"code": null,
"e": 5493,
"s": 4924,
"text": "The optimal situation is when we have a perfect linear relationship between the computed probability and the fraction of positives (blue dashed line). In our case, our neural network tends to respectively overestimate and underestimate a little the probabilities of the two classes in the middle. We can quantify the goodness of calibration with a proper index, the so-called Expected Calibration Error (ECE), that is the weighted (proportion of samples in each bin) average of the difference between expected accuracy and prediction confidence (the lower the better)."
},
{
"code": null,
"e": 5816,
"s": 5493,
"text": "We can adjust the ECE by applying a technique, which is an extension of Temperature scaling, known as Platt scaling. The neural network outputs a vector known as logits. Platt scaling simply divides the logits vector by a learned scalar parameter T, before passing it through a softmax function to get class probabilities."
},
{
"code": null,
"e": 6304,
"s": 5816,
"text": "Practically speaking with few lines of code, we can build our function to compute the Temperature scaling. The scaling factor T is learned on a predefined validation set, where we try to minimize a mean cost function (in TensorFlow: tf.nn.softmax_cross_entropy_with_logits). The inputs and output will be respectively our logits, scaled with the learnable T, and the true output in the form of dummy vectors. The train is computed classically with the stochastic gradient descent method."
},
{
"code": null,
"e": 6506,
"s": 6304,
"text": "In the end, the ECE score on the scaled probability records an improvement in both the classes. As we can also see above on the new reliability diagrams, we can produce better-calibrated probabilities."
},
{
"code": null,
"e": 6859,
"s": 6506,
"text": "In this post, we’ve examined a post-process technique to calibrate the probabilities of our neural network and let it, when it’ possible (not always temperature scaling is effective), a more trustable instrument. It’s a very simple trick applicable anywhere, which became useful if we care about the probabilities our model computes to make a decision."
},
{
"code": null,
"e": 6880,
"s": 6859,
"text": "CHECK MY GITHUB REPO"
},
{
"code": null,
"e": 6904,
"s": 6880,
"text": "Keep in touch: Linkedin"
},
{
"code": null,
"e": 6915,
"s": 6904,
"text": "REFERENCES"
},
{
"code": null,
"e": 6957,
"s": 6915,
"text": "StellarGraph — Machine Learning on Graphs"
}
] |
Classifying data using Support Vector Machines(SVMs) in R - GeeksforGeeks
|
26 Oct, 2021
In machine learning, Support vector machines (SVM) are supervised learning models with associated learning algorithms that analyze data used for classification and regression analysis. It is mostly used in classification problems. In this algorithm, each data item is plotted as a point in n-dimensional space (where n is a number of features), with the value of each feature being the value of a particular coordinate. Then, classification is performed by finding the hyper-plane that best differentiates the two classes. In addition to performing linear classification, SVMs can efficiently perform a non-linear classification, implicitly mapping their inputs into high-dimensional feature spaces.
A Support Vector Machine (SVM) is a discriminative classifier formally defined by a separating hyperplane. In other words, given labeled training data (supervised learning), the algorithm outputs an optimal hyperplane that categorizes new examples.The most important question that arises while using SVM is how to decide the right hyperplane. Consider the following scenarios:
Scenario 1: In this scenario, there are three hyperplanes called A, B, C. Now the problem is to identify the right hyper-plane which best differentiates the stars and the circles.
The thumb rule to be known, before finding the right hyperplane, to classify star and circle is that the hyperplane should be selected which segregate two classes better.In this case, B classifies star and circle better, hence it is a right hyperplane.
Scenario 2: Now take another Scenario where all three planes are segregating classes well. Now the question arises of how to identify the right plane in this situation.
In such scenarios, calculate the margin which is the distance between the nearest data point and hyper-plane. The plane has the maximum distance will be considered as the right hyperplane to classify the classes better.Here C is having the maximum margin and hence it will be considered as a right hyperplane.
Above are some scenarios to identify the right hyper-plane.Note: For details on Classifying using SVM in Python, refer to Classifying data using Support Vector Machines(SVMs) in Python
Here, an example is taken by importing a dataset of Social network aids from file Social.csvThe implementation is explained in the following steps:
Importing the dataset
R
# Importing the datasetdataset = read.csv('Social_Network_Ads.csv')dataset = dataset[3:5]
Output:
Selecting columns 3-5 This is done for ease of computation and implementation (to keep the example simple).
R
# Taking columns 3-5dataset = dataset[3:5]
Output:
Encoding the target feature
R
# Encoding the target feature as factordataset$Purchased = factor(dataset$Purchased, levels = c(0, 1))
Output:
Splitting the dataset
R
# Splitting the dataset into the Training set and Test setinstall.packages('caTools')library(caTools) set.seed(123)split = sample.split(dataset$Purchased, SplitRatio = 0.75) training_set = subset(dataset, split == TRUE)test_set = subset(dataset, split == FALSE)
Output: Splitter
Splitter
Training dataset
Test dataset
Feature Scaling
R
# Feature Scalingtraining_set[-3] = scale(training_set[-3])test_set[-3] = scale(test_set[-3])
Output: Feature scaled training dataset
Feature scaled training dataset
Feature scaled test dataset
Fitting SVM to the training set
R
# Fitting SVM to the Training setinstall.packages('e1071')library(e1071) classifier = svm(formula = Purchased ~ ., data = training_set, type = 'C-classification', kernel = 'linear')
Output: Classifier detailed
Classifier detailed
Classifier in nutshell
Predicting the test set result
R
# Predicting the Test set resultsy_pred = predict(classifier, newdata = test_set[-3])
Output:
Making Confusion Matrix
R
# Making the Confusion Matrixcm = table(test_set[, 3], y_pred)
Output:
Visualizing the Training set results
R
# installing library ElemStatLearnlibrary(ElemStatLearn) # Plotting the training data set resultsset = training_setX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01) grid_set = expand.grid(X1, X2)colnames(grid_set) = c('Age', 'EstimatedSalary')y_grid = predict(classifier, newdata = grid_set) plot(set[, -3], main = 'SVM (Training set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2)) contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE) points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'coral1', 'aquamarine')) points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))
Output:
Visualizing the Test set results
R
set = test_setX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01) grid_set = expand.grid(X1, X2)colnames(grid_set) = c('Age', 'EstimatedSalary')y_grid = predict(classifier, newdata = grid_set) plot(set[, -3], main = 'SVM (Test set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2)) contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE) points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'coral1', 'aquamarine')) points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))
Output:
Since in the result, a hyper-plane has been found in the Training set result and verified to be the best one in the Test set result. Hence, SVM has been successfully implemented in R.
marcosarcticseal
Advanced Computer Subject
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Copying Files to and from Docker Containers
Principal Component Analysis with Python
Fuzzy Logic | Introduction
How to create a REST API using Java Spring Boot
Classifying data using Support Vector Machines(SVMs) in Python
Agents in Artificial Intelligence
Search Algorithms in AI
Elbow Method for optimal value of k in KMeans
Support Vector Machine Algorithm
Activation functions in Neural Networks
|
[
{
"code": null,
"e": 24228,
"s": 24200,
"text": "\n26 Oct, 2021"
},
{
"code": null,
"e": 24929,
"s": 24228,
"text": "In machine learning, Support vector machines (SVM) are supervised learning models with associated learning algorithms that analyze data used for classification and regression analysis. It is mostly used in classification problems. In this algorithm, each data item is plotted as a point in n-dimensional space (where n is a number of features), with the value of each feature being the value of a particular coordinate. Then, classification is performed by finding the hyper-plane that best differentiates the two classes. In addition to performing linear classification, SVMs can efficiently perform a non-linear classification, implicitly mapping their inputs into high-dimensional feature spaces. "
},
{
"code": null,
"e": 25307,
"s": 24929,
"text": "A Support Vector Machine (SVM) is a discriminative classifier formally defined by a separating hyperplane. In other words, given labeled training data (supervised learning), the algorithm outputs an optimal hyperplane that categorizes new examples.The most important question that arises while using SVM is how to decide the right hyperplane. Consider the following scenarios: "
},
{
"code": null,
"e": 25488,
"s": 25307,
"text": "Scenario 1: In this scenario, there are three hyperplanes called A, B, C. Now the problem is to identify the right hyper-plane which best differentiates the stars and the circles. "
},
{
"code": null,
"e": 25743,
"s": 25488,
"text": "The thumb rule to be known, before finding the right hyperplane, to classify star and circle is that the hyperplane should be selected which segregate two classes better.In this case, B classifies star and circle better, hence it is a right hyperplane. "
},
{
"code": null,
"e": 25913,
"s": 25743,
"text": "Scenario 2: Now take another Scenario where all three planes are segregating classes well. Now the question arises of how to identify the right plane in this situation. "
},
{
"code": null,
"e": 26225,
"s": 25913,
"text": "In such scenarios, calculate the margin which is the distance between the nearest data point and hyper-plane. The plane has the maximum distance will be considered as the right hyperplane to classify the classes better.Here C is having the maximum margin and hence it will be considered as a right hyperplane. "
},
{
"code": null,
"e": 26411,
"s": 26225,
"text": "Above are some scenarios to identify the right hyper-plane.Note: For details on Classifying using SVM in Python, refer to Classifying data using Support Vector Machines(SVMs) in Python "
},
{
"code": null,
"e": 26560,
"s": 26411,
"text": "Here, an example is taken by importing a dataset of Social network aids from file Social.csvThe implementation is explained in the following steps: "
},
{
"code": null,
"e": 26583,
"s": 26560,
"text": "Importing the dataset "
},
{
"code": null,
"e": 26585,
"s": 26583,
"text": "R"
},
{
"code": "# Importing the datasetdataset = read.csv('Social_Network_Ads.csv')dataset = dataset[3:5]",
"e": 26675,
"s": 26585,
"text": null
},
{
"code": null,
"e": 26684,
"s": 26675,
"text": "Output: "
},
{
"code": null,
"e": 26795,
"s": 26686,
"text": "Selecting columns 3-5 This is done for ease of computation and implementation (to keep the example simple). "
},
{
"code": null,
"e": 26797,
"s": 26795,
"text": "R"
},
{
"code": "# Taking columns 3-5dataset = dataset[3:5]",
"e": 26840,
"s": 26797,
"text": null
},
{
"code": null,
"e": 26850,
"s": 26840,
"text": "Output: "
},
{
"code": null,
"e": 26881,
"s": 26852,
"text": "Encoding the target feature "
},
{
"code": null,
"e": 26883,
"s": 26881,
"text": "R"
},
{
"code": "# Encoding the target feature as factordataset$Purchased = factor(dataset$Purchased, levels = c(0, 1))",
"e": 26986,
"s": 26883,
"text": null
},
{
"code": null,
"e": 26995,
"s": 26986,
"text": "Output: "
},
{
"code": null,
"e": 27020,
"s": 26997,
"text": "Splitting the dataset "
},
{
"code": null,
"e": 27022,
"s": 27020,
"text": "R"
},
{
"code": "# Splitting the dataset into the Training set and Test setinstall.packages('caTools')library(caTools) set.seed(123)split = sample.split(dataset$Purchased, SplitRatio = 0.75) training_set = subset(dataset, split == TRUE)test_set = subset(dataset, split == FALSE)",
"e": 27284,
"s": 27022,
"text": null
},
{
"code": null,
"e": 27302,
"s": 27284,
"text": "Output: Splitter "
},
{
"code": null,
"e": 27312,
"s": 27302,
"text": "Splitter "
},
{
"code": null,
"e": 27332,
"s": 27314,
"text": "Training dataset "
},
{
"code": null,
"e": 27348,
"s": 27334,
"text": "Test dataset "
},
{
"code": null,
"e": 27367,
"s": 27350,
"text": "Feature Scaling "
},
{
"code": null,
"e": 27369,
"s": 27367,
"text": "R"
},
{
"code": "# Feature Scalingtraining_set[-3] = scale(training_set[-3])test_set[-3] = scale(test_set[-3])",
"e": 27463,
"s": 27369,
"text": null
},
{
"code": null,
"e": 27504,
"s": 27463,
"text": "Output: Feature scaled training dataset "
},
{
"code": null,
"e": 27537,
"s": 27504,
"text": "Feature scaled training dataset "
},
{
"code": null,
"e": 27568,
"s": 27539,
"text": "Feature scaled test dataset "
},
{
"code": null,
"e": 27603,
"s": 27570,
"text": "Fitting SVM to the training set "
},
{
"code": null,
"e": 27605,
"s": 27603,
"text": "R"
},
{
"code": "# Fitting SVM to the Training setinstall.packages('e1071')library(e1071) classifier = svm(formula = Purchased ~ ., data = training_set, type = 'C-classification', kernel = 'linear')",
"e": 27835,
"s": 27605,
"text": null
},
{
"code": null,
"e": 27864,
"s": 27835,
"text": "Output: Classifier detailed "
},
{
"code": null,
"e": 27885,
"s": 27864,
"text": "Classifier detailed "
},
{
"code": null,
"e": 27911,
"s": 27887,
"text": "Classifier in nutshell "
},
{
"code": null,
"e": 27945,
"s": 27913,
"text": "Predicting the test set result "
},
{
"code": null,
"e": 27947,
"s": 27945,
"text": "R"
},
{
"code": "# Predicting the Test set resultsy_pred = predict(classifier, newdata = test_set[-3])",
"e": 28033,
"s": 27947,
"text": null
},
{
"code": null,
"e": 28042,
"s": 28033,
"text": "Output: "
},
{
"code": null,
"e": 28069,
"s": 28044,
"text": "Making Confusion Matrix "
},
{
"code": null,
"e": 28071,
"s": 28069,
"text": "R"
},
{
"code": "# Making the Confusion Matrixcm = table(test_set[, 3], y_pred)",
"e": 28134,
"s": 28071,
"text": null
},
{
"code": null,
"e": 28143,
"s": 28134,
"text": "Output: "
},
{
"code": null,
"e": 28183,
"s": 28145,
"text": "Visualizing the Training set results "
},
{
"code": null,
"e": 28185,
"s": 28183,
"text": "R"
},
{
"code": "# installing library ElemStatLearnlibrary(ElemStatLearn) # Plotting the training data set resultsset = training_setX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01) grid_set = expand.grid(X1, X2)colnames(grid_set) = c('Age', 'EstimatedSalary')y_grid = predict(classifier, newdata = grid_set) plot(set[, -3], main = 'SVM (Training set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2)) contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE) points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'coral1', 'aquamarine')) points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))",
"e": 28903,
"s": 28185,
"text": null
},
{
"code": null,
"e": 28912,
"s": 28903,
"text": "Output: "
},
{
"code": null,
"e": 28948,
"s": 28914,
"text": "Visualizing the Test set results "
},
{
"code": null,
"e": 28950,
"s": 28948,
"text": "R"
},
{
"code": "set = test_setX1 = seq(min(set[, 1]) - 1, max(set[, 1]) + 1, by = 0.01)X2 = seq(min(set[, 2]) - 1, max(set[, 2]) + 1, by = 0.01) grid_set = expand.grid(X1, X2)colnames(grid_set) = c('Age', 'EstimatedSalary')y_grid = predict(classifier, newdata = grid_set) plot(set[, -3], main = 'SVM (Test set)', xlab = 'Age', ylab = 'Estimated Salary', xlim = range(X1), ylim = range(X2)) contour(X1, X2, matrix(as.numeric(y_grid), length(X1), length(X2)), add = TRUE) points(grid_set, pch = '.', col = ifelse(y_grid == 1, 'coral1', 'aquamarine')) points(set, pch = 21, bg = ifelse(set[, 3] == 1, 'green4', 'red3'))",
"e": 29559,
"s": 28950,
"text": null
},
{
"code": null,
"e": 29568,
"s": 29559,
"text": "Output: "
},
{
"code": null,
"e": 29755,
"s": 29570,
"text": "Since in the result, a hyper-plane has been found in the Training set result and verified to be the best one in the Test set result. Hence, SVM has been successfully implemented in R. "
},
{
"code": null,
"e": 29772,
"s": 29755,
"text": "marcosarcticseal"
},
{
"code": null,
"e": 29798,
"s": 29772,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 29815,
"s": 29798,
"text": "Machine Learning"
},
{
"code": null,
"e": 29832,
"s": 29815,
"text": "Machine Learning"
},
{
"code": null,
"e": 29930,
"s": 29832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29974,
"s": 29930,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 30015,
"s": 29974,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 30042,
"s": 30015,
"text": "Fuzzy Logic | Introduction"
},
{
"code": null,
"e": 30090,
"s": 30042,
"text": "How to create a REST API using Java Spring Boot"
},
{
"code": null,
"e": 30153,
"s": 30090,
"text": "Classifying data using Support Vector Machines(SVMs) in Python"
},
{
"code": null,
"e": 30187,
"s": 30153,
"text": "Agents in Artificial Intelligence"
},
{
"code": null,
"e": 30211,
"s": 30187,
"text": "Search Algorithms in AI"
},
{
"code": null,
"e": 30257,
"s": 30211,
"text": "Elbow Method for optimal value of k in KMeans"
},
{
"code": null,
"e": 30290,
"s": 30257,
"text": "Support Vector Machine Algorithm"
}
] |
newScheduledThreadPool Method
|
A scheduled thread pool can be obtainted by calling the static newScheduledThreadPool() method of Executors class.
ExecutorService executor = Executors.newScheduledThreadPool(1);
The following TestThread program shows usage of newScheduledThreadPool method in thread based environment.
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
public class TestThread {
public static void main(final String[] arguments) throws InterruptedException {
final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
final ScheduledFuture<?> beepHandler =
scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS);
scheduler.schedule(new Runnable() {
@Override
public void run() {
beepHandler.cancel(true);
scheduler.shutdown();
}
}, 10, TimeUnit.SECONDS);
}
static class BeepTask implements Runnable {
public void run() {
System.out.println("beep");
}
}
}
This will produce the following result.
beep
beep
beep
beep
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": 2772,
"s": 2657,
"text": "A scheduled thread pool can be obtainted by calling the static newScheduledThreadPool() method of Executors class."
},
{
"code": null,
"e": 2837,
"s": 2772,
"text": "ExecutorService executor = Executors.newScheduledThreadPool(1);\n"
},
{
"code": null,
"e": 2944,
"s": 2837,
"text": "The following TestThread program shows usage of newScheduledThreadPool method in thread based environment."
},
{
"code": null,
"e": 3794,
"s": 2944,
"text": "import java.util.concurrent.Executors;\nimport java.util.concurrent.ScheduledExecutorService;\nimport java.util.concurrent.ScheduledFuture;\nimport java.util.concurrent.TimeUnit;\n\npublic class TestThread {\n\n public static void main(final String[] arguments) throws InterruptedException {\n final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);\n\n final ScheduledFuture<?> beepHandler = \n scheduler.scheduleAtFixedRate(new BeepTask(), 2, 2, TimeUnit.SECONDS);\n\n scheduler.schedule(new Runnable() {\n\n @Override\n public void run() {\n beepHandler.cancel(true);\n scheduler.shutdown();\t\t\t\n }\n }, 10, TimeUnit.SECONDS);\n } \n\n static class BeepTask implements Runnable {\n\n public void run() {\n System.out.println(\"beep\"); \n }\n }\n}"
},
{
"code": null,
"e": 3834,
"s": 3794,
"text": "This will produce the following result."
},
{
"code": null,
"e": 3855,
"s": 3834,
"text": "beep\nbeep\nbeep\nbeep\n"
},
{
"code": null,
"e": 3888,
"s": 3855,
"text": "\n 16 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3904,
"s": 3888,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3937,
"s": 3904,
"text": "\n 19 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 3953,
"s": 3937,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3988,
"s": 3953,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 4002,
"s": 3988,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4036,
"s": 4002,
"text": "\n 126 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4050,
"s": 4036,
"text": " Tushar Kale"
},
{
"code": null,
"e": 4087,
"s": 4050,
"text": "\n 119 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 4102,
"s": 4087,
"text": " Monica Mittal"
},
{
"code": null,
"e": 4135,
"s": 4102,
"text": "\n 76 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 4154,
"s": 4135,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 4161,
"s": 4154,
"text": " Print"
},
{
"code": null,
"e": 4172,
"s": 4161,
"text": " Add Notes"
}
] |
Transforming Data in Python with Pandas Melt | by Jake Huneycutt | Towards Data Science
|
The World Bank hosts one of the richest sources of data on the Interwebs. This data has many practical applications such as forecasting economic growth or predicting poverty with machine learning. I recently used this data to create a few Tableau visualizations on Sub-Saharan African GDP per capita growth (annualized growth, cumulative growth).
There was a big roadblock along the way, however. My World Bank data didn’t work with Tableau. Tableau is better designed for database style formatting than the typical formatting you see in Excel for financial and economic data.
I had to transform the data to make it work in Tableau. One way to do this in Python is with Pandas Melt. Pd.melt allows you to ‘unpivot’ data from a ‘wide format’ into a ‘long format’, perfect for my task taking ‘wide format’ economic data with each column representing a year, and turning it into ‘long format’ data with each row representing a data point.
Getting the Data
Before I jump into the coding, I want to show you how to access the data. If you only want to know about pandas.melt, feel free to skip down to the next section (“Transforming with Pandas Melt”). If you want to do the full tutorial (taking World Bank data and making a Tableau animation), the first step is to go to the World Bank Open Data website.
There are many different ways to access the GDP per capita data. You could click on ‘browse by indicator’ (see the orange box in the image below) on the main page, then scroll down to the ‘Economy & Growth’ section, where you’ll find a few GDP per capita measures.
Alternatively, you can start typing in the measure you want in the search bar.
For my analysis, I did annualized and cumulative per capita GDP growth; both measures require a bit more complexity, so let’s simplify and focus instead on ‘GDP per capita growth (annual %)’. Once you select your category, you’ll get world data. You can click on ‘Map’ to see the data by country and year. We need to go to ‘DataBank’ to explore this data directly.
We’ll end up with a complex screen that looks something like the image below:
There are some frustrations dealing with World Bank data. If you’re following along, I recommend trying to do something simpler than I did with Sub-Saharan African growth. Instead, focus on South America, which has fewer countries.
First we need to ‘unselect all.’ We’ll then select a handful of South American countries: Argentina, Brazil, Chile, Peru, and Venezuela. Feel free to add the others to your dataset, as well, if you’d like a fuller presentation (Paraguay, Uraguay, Bolivia, Ecuador, Colombia, Guyana, Suriname). Now look at ‘Time’ and make sure all years from 2000–2016 are checked.
Find ‘download options’ in the upper right-hand corner of the screen and download the Excel file. We have a big jumble of data that looks something like this:
The problem is that Tableau wants a database style format. We need our data to look more like this:
Note that the difference is that instead of having columns for each individual year, the database-style formatting has an individual row for each country and date.
Before we use pandas.melt, we need to first clean up our data a bit. Let’s delete useless columns such as ‘Series Name’, ‘Series Code’, and ‘Country Code.’ We also need to change the dates to the mm/dd/yyyy format. We can do this in Python, but normally, it’s easier to just type in 12/31/yyyy (type in the year for “yyyy”) for the first two years and then use Excel’s fill command to do the rest. Finally, delete the source data at the bottom (“Data from Database”, “Last Updated”). Now we’re ready to transform the data with Python.
Transforming with Pandas Melt
First off, we need to import Pandas and the dataset. This will depend on your file location, but your code should look something like this.
import pandas as pddf = pd.read_excel('C:\PlaceYourDataComesFrom\data.xlsx', sheetname='data')print(df.head())
Use df.head() to make sure your data loaded properly. Now, we’ll use pd.melt to reformat it.
d = pd.melt(df, 'Country Name', var_name='Date', value_name='GDPperCapGrowth%')print(d.head())
The final step is to generate a new Excel file with our transformed output.
d.to_excel(r'C:\PlaceYouWantYourDataToGo\output.xlsx', sheet_name='GDPperCapGr', index=False)
Now, the transformed data should work well in Tableau.
A Little Bit o’ Tableau
Since this is a Pandas Melt tutorial, I won’t spend too much time on Tableau, but if you want to see how your map will look, you first need Tableau on your computer. You can download the free version at the Tableau Public website.
Open up Tableau Public. Connect to an Excel file. Load your transformed Excel data. Click on ‘Sheet 1’ at the bottom of Tableau and you should see your data.
In the “Dimensions” section, you’ll see “Country Name.” Drag that to the big box in the middle of your screen (‘drop here’). Glance down at the “Measures” section and you’ll see “GDPperCapGr%”. Drag that to the “Color” box. Find “Date” in the “Dimensions” section and drag it into the “Filter” box. Select “All” for years.
Now, go to “Date” again and drag it into the “Pages” box above “Filter.” You’ll see a new box appear on the far right of the screen (I have highlighted it in the image below, enclosed in a black box.) Push the forward button and you’ll get a nifty animation of GDP per Capita growth by year. Add “Country Name” and “GDPperCapGr%” to the “Label” box to add labels.
Now you have a simple (though, not yet elegant) Tableau animation to play around with.
Conclusions
Pandas Melt is a very powerful tool for transforming data. It’s particularly useful if you if you deal with lots of wide-style economic and financial data; and need it in a more database friendly long-style format.
|
[
{
"code": null,
"e": 394,
"s": 47,
"text": "The World Bank hosts one of the richest sources of data on the Interwebs. This data has many practical applications such as forecasting economic growth or predicting poverty with machine learning. I recently used this data to create a few Tableau visualizations on Sub-Saharan African GDP per capita growth (annualized growth, cumulative growth)."
},
{
"code": null,
"e": 624,
"s": 394,
"text": "There was a big roadblock along the way, however. My World Bank data didn’t work with Tableau. Tableau is better designed for database style formatting than the typical formatting you see in Excel for financial and economic data."
},
{
"code": null,
"e": 983,
"s": 624,
"text": "I had to transform the data to make it work in Tableau. One way to do this in Python is with Pandas Melt. Pd.melt allows you to ‘unpivot’ data from a ‘wide format’ into a ‘long format’, perfect for my task taking ‘wide format’ economic data with each column representing a year, and turning it into ‘long format’ data with each row representing a data point."
},
{
"code": null,
"e": 1000,
"s": 983,
"text": "Getting the Data"
},
{
"code": null,
"e": 1350,
"s": 1000,
"text": "Before I jump into the coding, I want to show you how to access the data. If you only want to know about pandas.melt, feel free to skip down to the next section (“Transforming with Pandas Melt”). If you want to do the full tutorial (taking World Bank data and making a Tableau animation), the first step is to go to the World Bank Open Data website."
},
{
"code": null,
"e": 1615,
"s": 1350,
"text": "There are many different ways to access the GDP per capita data. You could click on ‘browse by indicator’ (see the orange box in the image below) on the main page, then scroll down to the ‘Economy & Growth’ section, where you’ll find a few GDP per capita measures."
},
{
"code": null,
"e": 1694,
"s": 1615,
"text": "Alternatively, you can start typing in the measure you want in the search bar."
},
{
"code": null,
"e": 2059,
"s": 1694,
"text": "For my analysis, I did annualized and cumulative per capita GDP growth; both measures require a bit more complexity, so let’s simplify and focus instead on ‘GDP per capita growth (annual %)’. Once you select your category, you’ll get world data. You can click on ‘Map’ to see the data by country and year. We need to go to ‘DataBank’ to explore this data directly."
},
{
"code": null,
"e": 2137,
"s": 2059,
"text": "We’ll end up with a complex screen that looks something like the image below:"
},
{
"code": null,
"e": 2369,
"s": 2137,
"text": "There are some frustrations dealing with World Bank data. If you’re following along, I recommend trying to do something simpler than I did with Sub-Saharan African growth. Instead, focus on South America, which has fewer countries."
},
{
"code": null,
"e": 2734,
"s": 2369,
"text": "First we need to ‘unselect all.’ We’ll then select a handful of South American countries: Argentina, Brazil, Chile, Peru, and Venezuela. Feel free to add the others to your dataset, as well, if you’d like a fuller presentation (Paraguay, Uraguay, Bolivia, Ecuador, Colombia, Guyana, Suriname). Now look at ‘Time’ and make sure all years from 2000–2016 are checked."
},
{
"code": null,
"e": 2893,
"s": 2734,
"text": "Find ‘download options’ in the upper right-hand corner of the screen and download the Excel file. We have a big jumble of data that looks something like this:"
},
{
"code": null,
"e": 2993,
"s": 2893,
"text": "The problem is that Tableau wants a database style format. We need our data to look more like this:"
},
{
"code": null,
"e": 3157,
"s": 2993,
"text": "Note that the difference is that instead of having columns for each individual year, the database-style formatting has an individual row for each country and date."
},
{
"code": null,
"e": 3692,
"s": 3157,
"text": "Before we use pandas.melt, we need to first clean up our data a bit. Let’s delete useless columns such as ‘Series Name’, ‘Series Code’, and ‘Country Code.’ We also need to change the dates to the mm/dd/yyyy format. We can do this in Python, but normally, it’s easier to just type in 12/31/yyyy (type in the year for “yyyy”) for the first two years and then use Excel’s fill command to do the rest. Finally, delete the source data at the bottom (“Data from Database”, “Last Updated”). Now we’re ready to transform the data with Python."
},
{
"code": null,
"e": 3722,
"s": 3692,
"text": "Transforming with Pandas Melt"
},
{
"code": null,
"e": 3862,
"s": 3722,
"text": "First off, we need to import Pandas and the dataset. This will depend on your file location, but your code should look something like this."
},
{
"code": null,
"e": 3973,
"s": 3862,
"text": "import pandas as pddf = pd.read_excel('C:\\PlaceYourDataComesFrom\\data.xlsx', sheetname='data')print(df.head())"
},
{
"code": null,
"e": 4066,
"s": 3973,
"text": "Use df.head() to make sure your data loaded properly. Now, we’ll use pd.melt to reformat it."
},
{
"code": null,
"e": 4161,
"s": 4066,
"text": "d = pd.melt(df, 'Country Name', var_name='Date', value_name='GDPperCapGrowth%')print(d.head())"
},
{
"code": null,
"e": 4237,
"s": 4161,
"text": "The final step is to generate a new Excel file with our transformed output."
},
{
"code": null,
"e": 4331,
"s": 4237,
"text": "d.to_excel(r'C:\\PlaceYouWantYourDataToGo\\output.xlsx', sheet_name='GDPperCapGr', index=False)"
},
{
"code": null,
"e": 4386,
"s": 4331,
"text": "Now, the transformed data should work well in Tableau."
},
{
"code": null,
"e": 4410,
"s": 4386,
"text": "A Little Bit o’ Tableau"
},
{
"code": null,
"e": 4641,
"s": 4410,
"text": "Since this is a Pandas Melt tutorial, I won’t spend too much time on Tableau, but if you want to see how your map will look, you first need Tableau on your computer. You can download the free version at the Tableau Public website."
},
{
"code": null,
"e": 4799,
"s": 4641,
"text": "Open up Tableau Public. Connect to an Excel file. Load your transformed Excel data. Click on ‘Sheet 1’ at the bottom of Tableau and you should see your data."
},
{
"code": null,
"e": 5122,
"s": 4799,
"text": "In the “Dimensions” section, you’ll see “Country Name.” Drag that to the big box in the middle of your screen (‘drop here’). Glance down at the “Measures” section and you’ll see “GDPperCapGr%”. Drag that to the “Color” box. Find “Date” in the “Dimensions” section and drag it into the “Filter” box. Select “All” for years."
},
{
"code": null,
"e": 5486,
"s": 5122,
"text": "Now, go to “Date” again and drag it into the “Pages” box above “Filter.” You’ll see a new box appear on the far right of the screen (I have highlighted it in the image below, enclosed in a black box.) Push the forward button and you’ll get a nifty animation of GDP per Capita growth by year. Add “Country Name” and “GDPperCapGr%” to the “Label” box to add labels."
},
{
"code": null,
"e": 5573,
"s": 5486,
"text": "Now you have a simple (though, not yet elegant) Tableau animation to play around with."
},
{
"code": null,
"e": 5585,
"s": 5573,
"text": "Conclusions"
}
] |
Three ways to use custom validation metrics in tf.keras / TF2 | by Christian Freischlag | Towards Data Science
|
Keras offers a bunch of metrics to validate the test data set like accuracy, MSE or AUC. However, sometimes you need a custom metric to validate your model. In this post, I will show three different approaches to implement your metrics and use it within Keras.
While in the beginning there were only a few metrics included in Keras, today there are a lot of different ones available. For the Keras version bundled with TensorFlow 2 all the metrics can be found in tf.keras.metrics.
The Tensoflow Addons library makes some additional metrics available. Before starting to implement it on your own better check, if your metric is available there. To use tensorflow addons just install it via pip:
pip install tensorflow-addons
If you didn’t find your metrics there we can now look at the three options. Functions, Callbacks and Metrics objects.
The easiest way of defining metrics in Keras is to simply use a function callback. The function takes two arguments. The first parameter is the ground truth (y_true) and the second is the prediction from the model (y_pred). While running the validation, these arguments are Tensors, so we have to use the Keras Backend for calculation.
import tf.keras.backend as Kdef matthews_correlation(y_true, y_pred): y_pred_pos = K.round(K.clip(y_pred, 0, 1)) y_pred_neg = 1 - y_pred_pos y_pos = K.round(K.clip(y_true, 0, 1)) y_neg = 1 - y_pos tp = K.sum(y_pos * y_pred_pos) tn = K.sum(y_neg * y_pred_neg) fp = K.sum(y_neg * y_pred_pos) fn = K.sum(y_pos * y_pred_neg) numerator = (tp * tn - fp * fn) denominator = K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) return numerator / (denominator + K.epsilon())
Using this function with Keras models:
model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=[matthews_correlation])
And calling fit() now outputs:
245063/245063 [==============================] - 63s 256us/step - matthews_correlation: 0.0032 - val_matthews_correlation: 0.0039(Note that the name is the function name, while for validation data there is always the val_ prefix)
If you want to evaluate the model on a separate data set every N epochs you can use a custom callback. In this case, the AUC score from scikit-learn is used.
from sklearn.metrics import roc_auc_scorefrom tf.keras.callbacks import Callbackclass IntervalEvaluation(Callback): def __init__(self, validation_data=(), interval=10): super(Callback, self).__init__() self.interval = interval self.X_val, self.y_val = validation_data def on_epoch_end(self, epoch, logs={}): if epoch % self.interval == 0: y_pred = self.model.predict_proba(self.X_val, verbose=0) score = roc_auc_score(self.y_val, y_pred) print("interval evaluation - epoch: {:d} - score: {:.6f}".format(epoch, score))
To train the model with this evaluation setup, the instance of the object is passed to Keras as a callback.
ival = IntervalEvaluation(validation_data=(x_validate, y_validate), interval=10)model.fit(x_train, y_train, batch_size=8196, epochs=25, validation_data=[x_test, y_test], class_weight=class_weight, callbacks=[ival], verbose=1 )
And the result looks like this:
interval evaluation - epoch: 0 - score: 0.545038interval evaluation - epoch: 10 - score: 0.724098interval evaluation - epoch: 20 - score: 0.731381
And finally, it’s possible to extend the metric object itself. (Credits to Geeocode from Stackoverflow)
class CategoricalTruePositives(tf.keras.metrics.Metric): def __init__(self, num_classes, batch_size, name="categorical_true_positives", **kwargs): super(CategoricalTruePositives, self).__init__(name=name, **kwargs) self.batch_size = batch_size self.num_classes = num_classes self.cat_true_positives = self.add_weight(name="ctp", initializer="zeros") def update_state(self, y_true, y_pred, sample_weight=None): y_true = K.argmax(y_true, axis=-1) y_pred = K.argmax(y_pred, axis=-1) y_true = K.flatten(y_true) true_poss = K.sum(K.cast((K.equal(y_true, y_pred)), dtype=tf.float32)) self.cat_true_positives.assign_add(true_poss) def result(self): return self.cat_true_positives
There is only one notable difference to the first example. The result function returns and the update_state method must be overridden (this is were the calculation happens). It also takes one additional argument (sample_weight). And finally the result tensor is returned by re result method.
model.compile(optimizer='adam', loss='binary_crossentropy', metrics=[CategoricalTruePositives(num_classes, batch_size)])
We have seen three different ways of implementing a custom validation metric. Hopefully, that helped to decide which way works for your use case and don’t forget to check, whether your metric is already available in the large amount of predefined ones in tf.keras.metrics.
This post was initially published on digital-thinking.de (Dec 19 2018)
|
[
{
"code": null,
"e": 308,
"s": 47,
"text": "Keras offers a bunch of metrics to validate the test data set like accuracy, MSE or AUC. However, sometimes you need a custom metric to validate your model. In this post, I will show three different approaches to implement your metrics and use it within Keras."
},
{
"code": null,
"e": 529,
"s": 308,
"text": "While in the beginning there were only a few metrics included in Keras, today there are a lot of different ones available. For the Keras version bundled with TensorFlow 2 all the metrics can be found in tf.keras.metrics."
},
{
"code": null,
"e": 742,
"s": 529,
"text": "The Tensoflow Addons library makes some additional metrics available. Before starting to implement it on your own better check, if your metric is available there. To use tensorflow addons just install it via pip:"
},
{
"code": null,
"e": 772,
"s": 742,
"text": "pip install tensorflow-addons"
},
{
"code": null,
"e": 890,
"s": 772,
"text": "If you didn’t find your metrics there we can now look at the three options. Functions, Callbacks and Metrics objects."
},
{
"code": null,
"e": 1226,
"s": 890,
"text": "The easiest way of defining metrics in Keras is to simply use a function callback. The function takes two arguments. The first parameter is the ground truth (y_true) and the second is the prediction from the model (y_pred). While running the validation, these arguments are Tensors, so we have to use the Keras Backend for calculation."
},
{
"code": null,
"e": 1727,
"s": 1226,
"text": "import tf.keras.backend as Kdef matthews_correlation(y_true, y_pred): y_pred_pos = K.round(K.clip(y_pred, 0, 1)) y_pred_neg = 1 - y_pred_pos y_pos = K.round(K.clip(y_true, 0, 1)) y_neg = 1 - y_pos tp = K.sum(y_pos * y_pred_pos) tn = K.sum(y_neg * y_pred_neg) fp = K.sum(y_neg * y_pred_pos) fn = K.sum(y_pos * y_pred_neg) numerator = (tp * tn - fp * fn) denominator = K.sqrt((tp + fp) * (tp + fn) * (tn + fp) * (tn + fn)) return numerator / (denominator + K.epsilon())"
},
{
"code": null,
"e": 1766,
"s": 1727,
"text": "Using this function with Keras models:"
},
{
"code": null,
"e": 1887,
"s": 1766,
"text": "model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=[matthews_correlation])"
},
{
"code": null,
"e": 1918,
"s": 1887,
"text": "And calling fit() now outputs:"
},
{
"code": null,
"e": 2148,
"s": 1918,
"text": "245063/245063 [==============================] - 63s 256us/step - matthews_correlation: 0.0032 - val_matthews_correlation: 0.0039(Note that the name is the function name, while for validation data there is always the val_ prefix)"
},
{
"code": null,
"e": 2306,
"s": 2148,
"text": "If you want to evaluate the model on a separate data set every N epochs you can use a custom callback. In this case, the AUC score from scikit-learn is used."
},
{
"code": null,
"e": 2891,
"s": 2306,
"text": "from sklearn.metrics import roc_auc_scorefrom tf.keras.callbacks import Callbackclass IntervalEvaluation(Callback): def __init__(self, validation_data=(), interval=10): super(Callback, self).__init__() self.interval = interval self.X_val, self.y_val = validation_data def on_epoch_end(self, epoch, logs={}): if epoch % self.interval == 0: y_pred = self.model.predict_proba(self.X_val, verbose=0) score = roc_auc_score(self.y_val, y_pred) print(\"interval evaluation - epoch: {:d} - score: {:.6f}\".format(epoch, score))"
},
{
"code": null,
"e": 2999,
"s": 2891,
"text": "To train the model with this evaluation setup, the instance of the object is passed to Keras as a callback."
},
{
"code": null,
"e": 3283,
"s": 2999,
"text": "ival = IntervalEvaluation(validation_data=(x_validate, y_validate), interval=10)model.fit(x_train, y_train, batch_size=8196, epochs=25, validation_data=[x_test, y_test], class_weight=class_weight, callbacks=[ival], verbose=1 )"
},
{
"code": null,
"e": 3315,
"s": 3283,
"text": "And the result looks like this:"
},
{
"code": null,
"e": 3462,
"s": 3315,
"text": "interval evaluation - epoch: 0 - score: 0.545038interval evaluation - epoch: 10 - score: 0.724098interval evaluation - epoch: 20 - score: 0.731381"
},
{
"code": null,
"e": 3566,
"s": 3462,
"text": "And finally, it’s possible to extend the metric object itself. (Credits to Geeocode from Stackoverflow)"
},
{
"code": null,
"e": 4343,
"s": 3566,
"text": "class CategoricalTruePositives(tf.keras.metrics.Metric): def __init__(self, num_classes, batch_size, name=\"categorical_true_positives\", **kwargs): super(CategoricalTruePositives, self).__init__(name=name, **kwargs) self.batch_size = batch_size self.num_classes = num_classes self.cat_true_positives = self.add_weight(name=\"ctp\", initializer=\"zeros\") def update_state(self, y_true, y_pred, sample_weight=None): y_true = K.argmax(y_true, axis=-1) y_pred = K.argmax(y_pred, axis=-1) y_true = K.flatten(y_true) true_poss = K.sum(K.cast((K.equal(y_true, y_pred)), dtype=tf.float32)) self.cat_true_positives.assign_add(true_poss) def result(self): return self.cat_true_positives"
},
{
"code": null,
"e": 4635,
"s": 4343,
"text": "There is only one notable difference to the first example. The result function returns and the update_state method must be overridden (this is were the calculation happens). It also takes one additional argument (sample_weight). And finally the result tensor is returned by re result method."
},
{
"code": null,
"e": 4782,
"s": 4635,
"text": "model.compile(optimizer='adam', loss='binary_crossentropy', metrics=[CategoricalTruePositives(num_classes, batch_size)])"
},
{
"code": null,
"e": 5055,
"s": 4782,
"text": "We have seen three different ways of implementing a custom validation metric. Hopefully, that helped to decide which way works for your use case and don’t forget to check, whether your metric is already available in the large amount of predefined ones in tf.keras.metrics."
}
] |
Complex Numbers in Python | Set 1 (Introduction) - GeeksforGeeks
|
04 Feb, 2020
Not only real numbers, Python can also handle complex numbers and its associated functions using the file “cmath”. Complex numbers have their uses in many applications related to mathematics and python provides useful tools to handle and manipulate them.
Converting real numbers to complex number
An complex number is represented by “ x + yi “. Python converts the real numbers x and y into complex using the function complex(x,y). The real part can be accessed using the function real() and imaginary part can be represented by imag().
# Python code to demonstrate the working of# complex(), real() and imag() # importing "cmath" for complex number operationsimport cmath # Initializing real numbersx = 5y = 3 # converting x and y into complex numberz = complex(x,y); # printing real and imaginary part of complex numberprint ("The real part of complex number is : ",end="")print (z.real) print ("The imaginary part of complex number is : ",end="")print (z.imag)
Output:
The real part of complex number is : 5.0
The imaginary part of complex number is : 3.0
Phase of complex number
Geometrically, the phase of a complex number is the angle between the positive real axis and the vector representing complex number. This is also known as argument of complex number. Phase is returned using phase(), which takes complex number as argument. The range of phase lies from -pi to +pi. i.e from -3.14 to +3.14.
# Python code to demonstrate the working of# phase() # importing "cmath" for complex number operationsimport cmath # Initializing real numbersx = -1.0y = 0.0 # converting x and y into complex numberz = complex(x,y); # printing phase of a complex number using phase()print ("The phase of complex number is : ",end="")print (cmath.phase(z))
Output:
The phase of complex number is : 3.141592653589793
Converting from polar to rectangular form and vice versa
Conversion to polar is done using polar(), which returns a pair(r,ph) denoting the modulus r and phase angle ph. modulus can be displayed using abs() and phase using phase().A complex number converts into rectangular coordinates by using rect(r, ph), where r is modulus and ph is phase angle. It returns a value numerically equal to r * (math.cos(ph) + math.sin(ph)*1j)
# Python code to demonstrate the working of# polar() and rect() # importing "cmath" for complex number operationsimport cmathimport math # Initializing real numbersx = 1.0y = 1.0 # converting x and y into complex numberz = complex(x,y); # converting complex number into polar using polar()w = cmath.polar(z) # printing modulus and argument of polar complex numberprint ("The modulus and argument of polar complex number is : ",end="")print (w) # converting complex number into rectangular using rect()w = cmath.rect(1.4142135623730951, 0.7853981633974483) # printing rectangular form of complex numberprint ("The rectangular form of complex number is : ",end="")print (w)
Output:
The modulus and argument of polar complex number is : (1.4142135623730951, 0.7853981633974483)
The rectangular form of complex number is : (1.0000000000000002+1j)
YouTubeGeeksforGeeks502K subscribersPython Programming Tutorial | Complex Numbers (Introduction) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:52•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=3KjD1q6yjhE" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Complex Numbers in Python | Set 2 (Important Functions and Constants)
This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python
|
[
{
"code": null,
"e": 25176,
"s": 25148,
"text": "\n04 Feb, 2020"
},
{
"code": null,
"e": 25431,
"s": 25176,
"text": "Not only real numbers, Python can also handle complex numbers and its associated functions using the file “cmath”. Complex numbers have their uses in many applications related to mathematics and python provides useful tools to handle and manipulate them."
},
{
"code": null,
"e": 25473,
"s": 25431,
"text": "Converting real numbers to complex number"
},
{
"code": null,
"e": 25713,
"s": 25473,
"text": "An complex number is represented by “ x + yi “. Python converts the real numbers x and y into complex using the function complex(x,y). The real part can be accessed using the function real() and imaginary part can be represented by imag()."
},
{
"code": "# Python code to demonstrate the working of# complex(), real() and imag() # importing \"cmath\" for complex number operationsimport cmath # Initializing real numbersx = 5y = 3 # converting x and y into complex numberz = complex(x,y); # printing real and imaginary part of complex numberprint (\"The real part of complex number is : \",end=\"\")print (z.real) print (\"The imaginary part of complex number is : \",end=\"\")print (z.imag)",
"e": 26145,
"s": 25713,
"text": null
},
{
"code": null,
"e": 26153,
"s": 26145,
"text": "Output:"
},
{
"code": null,
"e": 26241,
"s": 26153,
"text": "The real part of complex number is : 5.0\nThe imaginary part of complex number is : 3.0\n"
},
{
"code": null,
"e": 26267,
"s": 26243,
"text": "Phase of complex number"
},
{
"code": null,
"e": 26589,
"s": 26267,
"text": "Geometrically, the phase of a complex number is the angle between the positive real axis and the vector representing complex number. This is also known as argument of complex number. Phase is returned using phase(), which takes complex number as argument. The range of phase lies from -pi to +pi. i.e from -3.14 to +3.14."
},
{
"code": "# Python code to demonstrate the working of# phase() # importing \"cmath\" for complex number operationsimport cmath # Initializing real numbersx = -1.0y = 0.0 # converting x and y into complex numberz = complex(x,y); # printing phase of a complex number using phase()print (\"The phase of complex number is : \",end=\"\")print (cmath.phase(z))",
"e": 26932,
"s": 26589,
"text": null
},
{
"code": null,
"e": 26940,
"s": 26932,
"text": "Output:"
},
{
"code": null,
"e": 26992,
"s": 26940,
"text": "The phase of complex number is : 3.141592653589793\n"
},
{
"code": null,
"e": 27051,
"s": 26994,
"text": "Converting from polar to rectangular form and vice versa"
},
{
"code": null,
"e": 27421,
"s": 27051,
"text": "Conversion to polar is done using polar(), which returns a pair(r,ph) denoting the modulus r and phase angle ph. modulus can be displayed using abs() and phase using phase().A complex number converts into rectangular coordinates by using rect(r, ph), where r is modulus and ph is phase angle. It returns a value numerically equal to r * (math.cos(ph) + math.sin(ph)*1j)"
},
{
"code": "# Python code to demonstrate the working of# polar() and rect() # importing \"cmath\" for complex number operationsimport cmathimport math # Initializing real numbersx = 1.0y = 1.0 # converting x and y into complex numberz = complex(x,y); # converting complex number into polar using polar()w = cmath.polar(z) # printing modulus and argument of polar complex numberprint (\"The modulus and argument of polar complex number is : \",end=\"\")print (w) # converting complex number into rectangular using rect()w = cmath.rect(1.4142135623730951, 0.7853981633974483) # printing rectangular form of complex numberprint (\"The rectangular form of complex number is : \",end=\"\")print (w)",
"e": 28100,
"s": 27421,
"text": null
},
{
"code": null,
"e": 28108,
"s": 28100,
"text": "Output:"
},
{
"code": null,
"e": 28272,
"s": 28108,
"text": "The modulus and argument of polar complex number is : (1.4142135623730951, 0.7853981633974483)\nThe rectangular form of complex number is : (1.0000000000000002+1j)\n"
},
{
"code": null,
"e": 29131,
"s": 28272,
"text": "YouTubeGeeksforGeeks502K subscribersPython Programming Tutorial | Complex Numbers (Introduction) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.More videosMore videosYou're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:52•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=3KjD1q6yjhE\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 29202,
"s": 29131,
"text": "Complex Numbers in Python | Set 2 (Important Functions and Constants) "
},
{
"code": null,
"e": 29503,
"s": 29202,
"text": "This article is contributed by Manjeet Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 29628,
"s": 29503,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29654,
"s": 29628,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 29661,
"s": 29654,
"text": "Python"
},
{
"code": null,
"e": 29759,
"s": 29661,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29777,
"s": 29759,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29812,
"s": 29777,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29834,
"s": 29812,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 29866,
"s": 29834,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29896,
"s": 29866,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 29938,
"s": 29896,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29964,
"s": 29938,
"text": "Python String | replace()"
},
{
"code": null,
"e": 30001,
"s": 29964,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 30044,
"s": 30001,
"text": "Python program to convert a list to string"
}
] |
Projection Operations in LINQ
|
Projection is an operation in which an object is transformed into an altogether new form with only specific properties.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Operators {
class Program {
static void Main(string[] args) {
List<string> words = new List<string>() { "an", "apple", "a", "day" };
var query = from word in words select word.Substring(0, 1);
foreach (string s in query)
Console.WriteLine(s);
Console.ReadLine();
}
}
}
Module Module1
Sub Main()
Dim words = New List(Of String) From {"an", "apple", "a", "day"}
Dim query = From word In words Select word.Substring(0, 1);
Dim sb As New System.Text.StringBuilder()
For Each letter As String In query
sb.AppendLine(letter)
Console.WriteLine(letter)
Next
Console.ReadLine()
End Sub
End Module
When the above code in C# or VB is compiled and executed, it produces the following result −
a
a
a
d
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Operators {
class Program {
static void Main(string[] args) {
List<string> phrases = new List<string>() { "an apple a day", "the quick brown fox" };
var query = from phrase in phrases
from word in phrase.Split(' ')
select word;
foreach (string s in query)
Console.WriteLine(s);
Console.ReadLine();
}
}
}
Module Module1
Sub Main()
Dim phrases = New List(Of String) From {"an apple a day", "the quick brown fox"}
Dim query = From phrase In phrases
From word In phrase.Split(" "c)
Select word;
Dim sb As New System.Text.StringBuilder()
For Each str As String In query
sb.AppendLine(str)
Console.WriteLine(str)
Next
Console.ReadLine()
End Sub
End Module
When the above code in C# or VB is compiled and executed, it produces the following result −
an
apple
a
day
the
quick
brown
fox
23 Lectures
1.5 hours
Anadi Sharma
37 Lectures
13 hours
Trevoir Williams
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1856,
"s": 1736,
"text": "Projection is an operation in which an object is transformed into an altogether new form with only specific properties."
},
{
"code": null,
"e": 2300,
"s": 1856,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Operators {\n class Program {\n static void Main(string[] args) {\n \n List<string> words = new List<string>() { \"an\", \"apple\", \"a\", \"day\" };\n\n var query = from word in words select word.Substring(0, 1);\n\n foreach (string s in query)\n Console.WriteLine(s);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 2701,
"s": 2300,
"text": "Module Module1\n\n Sub Main()\n \n Dim words = New List(Of String) From {\"an\", \"apple\", \"a\", \"day\"}\n\n Dim query = From word In words Select word.Substring(0, 1);\n\n Dim sb As New System.Text.StringBuilder()\n\t \n For Each letter As String In query\n sb.AppendLine(letter)\n Console.WriteLine(letter)\n Next\n Console.ReadLine()\n\t\t \n End Sub\n \nEnd Module"
},
{
"code": null,
"e": 2794,
"s": 2701,
"text": "When the above code in C# or VB is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 2803,
"s": 2794,
"text": "a\na\na\nd\n"
},
{
"code": null,
"e": 3324,
"s": 2803,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Operators {\n class Program {\n static void Main(string[] args) {\n \n List<string> phrases = new List<string>() { \"an apple a day\", \"the quick brown fox\" };\n\n var query = from phrase in phrases\n from word in phrase.Split(' ')\n select word;\n\n foreach (string s in query)\n Console.WriteLine(s);\n Console.ReadLine();\n }\n }\n}"
},
{
"code": null,
"e": 3791,
"s": 3324,
"text": "Module Module1\n\n Sub Main()\n \n Dim phrases = New List(Of String) From {\"an apple a day\", \"the quick brown fox\"}\n\n Dim query = From phrase In phrases \n From word In phrase.Split(\" \"c) \n Select word;\n\n Dim sb As New System.Text.StringBuilder()\n\t \n For Each str As String In query\n sb.AppendLine(str)\n Console.WriteLine(str)\n Next \n Console.ReadLine()\n\t\t \n End Sub\n \nEnd Module"
},
{
"code": null,
"e": 3884,
"s": 3791,
"text": "When the above code in C# or VB is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3920,
"s": 3884,
"text": "an\napple\na\nday\nthe\nquick\nbrown\nfox\n"
},
{
"code": null,
"e": 3955,
"s": 3920,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3969,
"s": 3955,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 4003,
"s": 3969,
"text": "\n 37 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4021,
"s": 4003,
"text": " Trevoir Williams"
},
{
"code": null,
"e": 4028,
"s": 4021,
"text": " Print"
},
{
"code": null,
"e": 4039,
"s": 4028,
"text": " Add Notes"
}
] |
What is PyTorch?. Think about Numpy, but with strong GPU... | by Khuyen Tran | Towards Data Science
|
PyTorch is a library for Python programs that facilitates building deep learning projects. We like Python because is easy to read and understand. PyTorch emphasizes flexibility and allows deep learning models to be expressed in idiomatic Python.
In a simple sentence, think about Numpy, but with strong GPU acceleration. Better yet, PyTorch supports dynamic computation graphs that allow you to change how the network behaves on the fly, unlike static graphs that are used in frameworks such as Tensorflow.
Why PyTorch?
- NumPy-like arrays on GPU’s
- Dynamic computational graphs
- It’s Pythonic!
PyTorch can be installed and used on macOS. It is recommended, but not required to have NVIDIA GPU in order to harness the full power of PyTorch’s CUDA support.
Installation with Anaconda
conda install pytorch torchvision -c pytorch
Installation with pip
pip3 install torch torchvision
If you have any problem with installation, find out more about different ways to install PyTorch here.
If you don’t have NVIDIA GPU in your computer, use Google Colab instead to harness its free GPU power! Click on New notebook in the top left to get started.
Remember to change runtime type to GPU before running the notebook
Are you familiar with Numpy? Great! You just need to shift the syntax using on Numpy to syntax of PyTorch. If you are not familiar with Numpy, PyTorch is written in such an intuitive way that you can learn in second.
Import the two libraries to compare their results and performance
import torchimport numpy
PyTorch tensors are similar to NumPy ndarrays with the option to operate on GPU.
>>> numpy.array([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])array([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])>>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])tensor([[0.1000, 1.2000], [2.2000, 3.1000], [4.9000, 5.2000]])
What do we see here? tensor is shown in place of array. Remember that np.empty(), np.random.randn(), np.zeros(), np.ones() that we love? The same functions and syntax can be applied with PyTorch
w = torch.empty(3, 3)print(w,'\n', w.shape, '\n')x = torch.randn(3, 3, 7)print(x,'\n', x.shape, '\n')y = torch.zeros(3, 3)print(y,'\n', y.shape, '\n')z = torch.ones(3, 3)print(z,'\n', z.shape, '\n')[0., 0., 3., 0., 0.], [4., 0., 5., 0., 0.], [0., 0., 0., 0., 0.]
Change the shape with view() method
>>> x = torch.rand(100,50)>>> print(x.shape)torch.Size([100, 50])>>> y=x.view(20,5,50)>>> print(y.shape)torch.Size([20, 5, 50])>>> z=x.view(-1,5,50)>>> print(z.shape)torch.Size([20, 5, 50])
GPU (graphics processing units) composes of hundreds of simpler cores, which makes training deep learning models much faster. Below is the quick comparison between GPU and CPU.
Whether we decide to use GPU or CPU, PyTorch makes it easy for us to switch between the two
cpu=torch.device("cpu")gpu=torch.device("cuda:0") # GPU 0# Create tensor with CPUx=torch.ones(3,3, device=cpu)print("CPU:",x.device)x=torch.ones(3,3, device=gpu)print("GPU:",x.device)x=torch.ones(3,3).cuda(0)print("CPU to GPU:",x.device)x=torch.ones(3,3, device=gpu).cpu()print("GPU to CPU:",x.device)
Compare time between CPU and GPU
Time in CPU
>>> import time>>> x=torch.rand(10000,10000)>>> y=torch.rand(10000,10000)>>> t = time.time()>>> z=x@y>>> t = time.time()-t>>> print(t)6.999474763870239
Time in GPU
>>> yc=y.cuda(0)>>> t = time.time()>>> z=xc@yc>>> t = time.time()-t>>> print(t)0.4787747859954834
It is nearly 15 times faster than Numpy for simple matrix multiplication!
Since NumPy and PyTorch are really similar, is there a method to change NumPy array to PyTorch array and vice versa? Yes!
a = np.ones(5)#From NumPy to Torchb = torch.from_numpy(a)print('a:',a)print('b:',b)
What is Autograd? Remember in your calculus class when you need to calculate the derivatives of a function? The gradient is like derivative but in vector form. It is important to calculate the loss function in neural networks. But it impractical to calculate gradients of such large composite functions by solving mathematical equations because of the high number of dimensions. Luckily, PyTorch can find this gradient numerically in a matter of seconds!
Let’s say we want to find the gradient of the vector below. We expect the gradient of y to be x. Use tensor to find the gradient and check whether we get the right answer.
Awesome! The gradient is x like what we expected. Break down of the codes above:
requires_grad = True allows for efficient gradient computation. If we know we will compute the gradient based on x, we need to set .requires_grad = True for the input. Learn more about how autograd works here.
y.backward() computes the gradient numerically
x.grad() returns the gradient of y at the point x
Let’s understand how to use PyTorch with a classification example. Our task is to find if a point is in the cluster of yellow or purple
Start with constructing a subclass of nn.Module, a PyTorch module for building a neural network.
Split the data into training and test set
Train the data
Predict and evaluation the prediction
Congratulations! You have just learned what is PyTorch and how to use it. This article is just a gentle introduction to PyTorch. What I hope you gain from this article is that deep learning can be easy and efficient with this tool. To understand more about how to use PyTorch for your deep learning project, I recommend checking this great book: Deep Learning with PyTorch, one of the best resources to learn about PyTorch.
Feel free to fork and play with the code for this article in this Github repo.
I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter.
Star this repo if you want to check out the codes for all of the articles I have written. Follow me on Medium to stay informed with my latest data science articles like these:
|
[
{
"code": null,
"e": 417,
"s": 171,
"text": "PyTorch is a library for Python programs that facilitates building deep learning projects. We like Python because is easy to read and understand. PyTorch emphasizes flexibility and allows deep learning models to be expressed in idiomatic Python."
},
{
"code": null,
"e": 678,
"s": 417,
"text": "In a simple sentence, think about Numpy, but with strong GPU acceleration. Better yet, PyTorch supports dynamic computation graphs that allow you to change how the network behaves on the fly, unlike static graphs that are used in frameworks such as Tensorflow."
},
{
"code": null,
"e": 691,
"s": 678,
"text": "Why PyTorch?"
},
{
"code": null,
"e": 720,
"s": 691,
"text": "- NumPy-like arrays on GPU’s"
},
{
"code": null,
"e": 751,
"s": 720,
"text": "- Dynamic computational graphs"
},
{
"code": null,
"e": 768,
"s": 751,
"text": "- It’s Pythonic!"
},
{
"code": null,
"e": 929,
"s": 768,
"text": "PyTorch can be installed and used on macOS. It is recommended, but not required to have NVIDIA GPU in order to harness the full power of PyTorch’s CUDA support."
},
{
"code": null,
"e": 956,
"s": 929,
"text": "Installation with Anaconda"
},
{
"code": null,
"e": 1001,
"s": 956,
"text": "conda install pytorch torchvision -c pytorch"
},
{
"code": null,
"e": 1023,
"s": 1001,
"text": "Installation with pip"
},
{
"code": null,
"e": 1054,
"s": 1023,
"text": "pip3 install torch torchvision"
},
{
"code": null,
"e": 1157,
"s": 1054,
"text": "If you have any problem with installation, find out more about different ways to install PyTorch here."
},
{
"code": null,
"e": 1314,
"s": 1157,
"text": "If you don’t have NVIDIA GPU in your computer, use Google Colab instead to harness its free GPU power! Click on New notebook in the top left to get started."
},
{
"code": null,
"e": 1381,
"s": 1314,
"text": "Remember to change runtime type to GPU before running the notebook"
},
{
"code": null,
"e": 1598,
"s": 1381,
"text": "Are you familiar with Numpy? Great! You just need to shift the syntax using on Numpy to syntax of PyTorch. If you are not familiar with Numpy, PyTorch is written in such an intuitive way that you can learn in second."
},
{
"code": null,
"e": 1664,
"s": 1598,
"text": "Import the two libraries to compare their results and performance"
},
{
"code": null,
"e": 1689,
"s": 1664,
"text": "import torchimport numpy"
},
{
"code": null,
"e": 1770,
"s": 1689,
"text": "PyTorch tensors are similar to NumPy ndarrays with the option to operate on GPU."
},
{
"code": null,
"e": 2009,
"s": 1770,
"text": ">>> numpy.array([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])array([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])>>> torch.tensor([[0.1, 1.2], [2.2, 3.1], [4.9, 5.2]])tensor([[0.1000, 1.2000], [2.2000, 3.1000], [4.9000, 5.2000]])"
},
{
"code": null,
"e": 2204,
"s": 2009,
"text": "What do we see here? tensor is shown in place of array. Remember that np.empty(), np.random.randn(), np.zeros(), np.ones() that we love? The same functions and syntax can be applied with PyTorch"
},
{
"code": null,
"e": 2499,
"s": 2204,
"text": "w = torch.empty(3, 3)print(w,'\\n', w.shape, '\\n')x = torch.randn(3, 3, 7)print(x,'\\n', x.shape, '\\n')y = torch.zeros(3, 3)print(y,'\\n', y.shape, '\\n')z = torch.ones(3, 3)print(z,'\\n', z.shape, '\\n')[0., 0., 3., 0., 0.], [4., 0., 5., 0., 0.], [0., 0., 0., 0., 0.]"
},
{
"code": null,
"e": 2535,
"s": 2499,
"text": "Change the shape with view() method"
},
{
"code": null,
"e": 2725,
"s": 2535,
"text": ">>> x = torch.rand(100,50)>>> print(x.shape)torch.Size([100, 50])>>> y=x.view(20,5,50)>>> print(y.shape)torch.Size([20, 5, 50])>>> z=x.view(-1,5,50)>>> print(z.shape)torch.Size([20, 5, 50])"
},
{
"code": null,
"e": 2902,
"s": 2725,
"text": "GPU (graphics processing units) composes of hundreds of simpler cores, which makes training deep learning models much faster. Below is the quick comparison between GPU and CPU."
},
{
"code": null,
"e": 2994,
"s": 2902,
"text": "Whether we decide to use GPU or CPU, PyTorch makes it easy for us to switch between the two"
},
{
"code": null,
"e": 3296,
"s": 2994,
"text": "cpu=torch.device(\"cpu\")gpu=torch.device(\"cuda:0\") # GPU 0# Create tensor with CPUx=torch.ones(3,3, device=cpu)print(\"CPU:\",x.device)x=torch.ones(3,3, device=gpu)print(\"GPU:\",x.device)x=torch.ones(3,3).cuda(0)print(\"CPU to GPU:\",x.device)x=torch.ones(3,3, device=gpu).cpu()print(\"GPU to CPU:\",x.device)"
},
{
"code": null,
"e": 3329,
"s": 3296,
"text": "Compare time between CPU and GPU"
},
{
"code": null,
"e": 3341,
"s": 3329,
"text": "Time in CPU"
},
{
"code": null,
"e": 3493,
"s": 3341,
"text": ">>> import time>>> x=torch.rand(10000,10000)>>> y=torch.rand(10000,10000)>>> t = time.time()>>> z=x@y>>> t = time.time()-t>>> print(t)6.999474763870239"
},
{
"code": null,
"e": 3505,
"s": 3493,
"text": "Time in GPU"
},
{
"code": null,
"e": 3603,
"s": 3505,
"text": ">>> yc=y.cuda(0)>>> t = time.time()>>> z=xc@yc>>> t = time.time()-t>>> print(t)0.4787747859954834"
},
{
"code": null,
"e": 3677,
"s": 3603,
"text": "It is nearly 15 times faster than Numpy for simple matrix multiplication!"
},
{
"code": null,
"e": 3799,
"s": 3677,
"text": "Since NumPy and PyTorch are really similar, is there a method to change NumPy array to PyTorch array and vice versa? Yes!"
},
{
"code": null,
"e": 3883,
"s": 3799,
"text": "a = np.ones(5)#From NumPy to Torchb = torch.from_numpy(a)print('a:',a)print('b:',b)"
},
{
"code": null,
"e": 4338,
"s": 3883,
"text": "What is Autograd? Remember in your calculus class when you need to calculate the derivatives of a function? The gradient is like derivative but in vector form. It is important to calculate the loss function in neural networks. But it impractical to calculate gradients of such large composite functions by solving mathematical equations because of the high number of dimensions. Luckily, PyTorch can find this gradient numerically in a matter of seconds!"
},
{
"code": null,
"e": 4510,
"s": 4338,
"text": "Let’s say we want to find the gradient of the vector below. We expect the gradient of y to be x. Use tensor to find the gradient and check whether we get the right answer."
},
{
"code": null,
"e": 4591,
"s": 4510,
"text": "Awesome! The gradient is x like what we expected. Break down of the codes above:"
},
{
"code": null,
"e": 4801,
"s": 4591,
"text": "requires_grad = True allows for efficient gradient computation. If we know we will compute the gradient based on x, we need to set .requires_grad = True for the input. Learn more about how autograd works here."
},
{
"code": null,
"e": 4848,
"s": 4801,
"text": "y.backward() computes the gradient numerically"
},
{
"code": null,
"e": 4898,
"s": 4848,
"text": "x.grad() returns the gradient of y at the point x"
},
{
"code": null,
"e": 5034,
"s": 4898,
"text": "Let’s understand how to use PyTorch with a classification example. Our task is to find if a point is in the cluster of yellow or purple"
},
{
"code": null,
"e": 5131,
"s": 5034,
"text": "Start with constructing a subclass of nn.Module, a PyTorch module for building a neural network."
},
{
"code": null,
"e": 5173,
"s": 5131,
"text": "Split the data into training and test set"
},
{
"code": null,
"e": 5188,
"s": 5173,
"text": "Train the data"
},
{
"code": null,
"e": 5226,
"s": 5188,
"text": "Predict and evaluation the prediction"
},
{
"code": null,
"e": 5650,
"s": 5226,
"text": "Congratulations! You have just learned what is PyTorch and how to use it. This article is just a gentle introduction to PyTorch. What I hope you gain from this article is that deep learning can be easy and efficient with this tool. To understand more about how to use PyTorch for your deep learning project, I recommend checking this great book: Deep Learning with PyTorch, one of the best resources to learn about PyTorch."
},
{
"code": null,
"e": 5729,
"s": 5650,
"text": "Feel free to fork and play with the code for this article in this Github repo."
},
{
"code": null,
"e": 5889,
"s": 5729,
"text": "I like to write about basic data science concepts and play with different algorithms and data science tools. You could connect with me on LinkedIn and Twitter."
}
] |
What is a static constructor in C#?
|
A static constructor is a constructor declared using a static modifier. It is the first block of code executed in a class. With that, a static constructor executes only once in the life cycle of class.
The following is an example of static constructors in C# −
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Difference {
class Demo {
static int val1;
int val2;
static Demo() {
Console.WriteLine("This is Static Constructor");
val1 = 70;
}
public Demo(int val3) {
Console.WriteLine("This is Instance Constructor");
val2 = val3;
}
private void show() {
Console.WriteLine("First Value = " + val1);
Console.WriteLine("Second Value = " + val2);
}
static void Main(string[] args) {
Demo d1 = new Demo(110);
Demo d2 = new Demo(200);
d1.show();
d2.show();
Console.ReadKey();
}
}
}
|
[
{
"code": null,
"e": 1264,
"s": 1062,
"text": "A static constructor is a constructor declared using a static modifier. It is the first block of code executed in a class. With that, a static constructor executes only once in the life cycle of class."
},
{
"code": null,
"e": 1323,
"s": 1264,
"text": "The following is an example of static constructors in C# −"
},
{
"code": null,
"e": 2057,
"s": 1323,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace Difference {\n class Demo {\n static int val1;\n int val2;\n\n static Demo() {\n Console.WriteLine(\"This is Static Constructor\");\n val1 = 70;\n }\n\n public Demo(int val3) {\n Console.WriteLine(\"This is Instance Constructor\");\n val2 = val3;\n }\n \n private void show() {\n Console.WriteLine(\"First Value = \" + val1);\n Console.WriteLine(\"Second Value = \" + val2);\n }\n\n static void Main(string[] args) {\n Demo d1 = new Demo(110);\n Demo d2 = new Demo(200);\n d1.show();\n d2.show();\n Console.ReadKey();\n }\n }\n}"
}
] |
SQLite - Commands
|
This chapter will take you through simple and useful commands used by SQLite programmers. These commands are called SQLite dot commands and exception with these commands is that they should not be terminated by a semi-colon (;).
Let's start with typing a simple sqlite3 command at command prompt which will provide you with SQLite command prompt where you will issue various SQLite commands.
$sqlite3
SQLite version 3.3.6
Enter ".help" for instructions
sqlite>
For a listing of the available dot commands, you can enter ".help" any time. For example −
sqlite>.help
The above command will display a list of various important SQLite dot commands, which are listed in the following table.
.backup ?DB? FILE
Backup DB (default "main") to FILE
.bail ON|OFF
Stop after hitting an error. Default OFF
.databases
List names and files of attached databases
.dump ?TABLE?
Dump the database in an SQL text format. If TABLE specified, only dump tables matching LIKE pattern TABLE
.echo ON|OFF
Turn command echo on or off
.exit
Exit SQLite prompt
.explain ON|OFF
Turn output mode suitable for EXPLAIN on or off. With no args, it turns EXPLAIN on
.header(s) ON|OFF
Turn display of headers on or off
.help
Show this message
.import FILE TABLE
Import data from FILE into TABLE
.indices ?TABLE?
Show names of all indices. If TABLE specified, only show indices for tables matching LIKE pattern TABLE
.load FILE ?ENTRY?
Load an extension library
.log FILE|off
Turn logging on or off. FILE can be stderr/stdout
.mode MODE
Set output mode where MODE is one of −
csv − Comma-separated values
csv − Comma-separated values
column − Left-aligned columns.
column − Left-aligned columns.
html − HTML <table> code
html − HTML <table> code
insert − SQL insert statements for TABLE
insert − SQL insert statements for TABLE
line − One value per line
line − One value per line
list − Values delimited by .separator string
list − Values delimited by .separator string
tabs − Tab-separated values
tabs − Tab-separated values
tcl − TCL list elements
tcl − TCL list elements
.nullvalue STRING
Print STRING in place of NULL values
.output FILENAME
Send output to FILENAME
.output stdout
Send output to the screen
.print STRING...
Print literal STRING
.prompt MAIN CONTINUE
Replace the standard prompts
.quit
Exit SQLite prompt
.read FILENAME
Execute SQL in FILENAME
.schema ?TABLE?
Show the CREATE statements. If TABLE specified, only show tables matching LIKE pattern TABLE
.separator STRING
Change separator used by output mode and .import
.show
Show the current values for various settings
.stats ON|OFF
Turn stats on or off
.tables ?PATTERN?
List names of tables matching a LIKE pattern
.timeout MS
Try opening locked tables for MS milliseconds
.width NUM NUM
Set column widths for "column" mode
.timer ON|OFF
Turn the CPU timer measurement on or off
Let's try .show command to see default setting for your SQLite command prompt.
sqlite>.show
echo: off
explain: off
headers: off
mode: column
nullvalue: ""
output: stdout
separator: "|"
width:
sqlite>
Make sure there is no space in between sqlite> prompt and dot command, otherwise it will not work.
You can use the following sequence of dot commands to format your output.
sqlite>.header on
sqlite>.mode column
sqlite>.timer on
sqlite>
The above setting will produce the output in the following format.
ID NAME AGE ADDRESS SALARY
---------- ---------- ---------- ---------- ----------
1 Paul 32 California 20000.0
2 Allen 25 Texas 15000.0
3 Teddy 23 Norway 20000.0
4 Mark 25 Rich-Mond 65000.0
5 David 27 Texas 85000.0
6 Kim 22 South-Hall 45000.0
7 James 24 Houston 10000.0
CPU Time: user 0.000000 sys 0.000000
The master table holds the key information about your database tables and it is called sqlite_master. You can see its schema as follows −
sqlite>.schema sqlite_master
This will produce the following result.
CREATE TABLE sqlite_master (
type text,
name text,
tbl_name text,
rootpage integer,
sql text
);
25 Lectures
4.5 hours
Sandip Bhattacharya
17 Lectures
1 hours
Laurence Svekis
5 Lectures
51 mins
Vinay Kumar
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2867,
"s": 2638,
"text": "This chapter will take you through simple and useful commands used by SQLite programmers. These commands are called SQLite dot commands and exception with these commands is that they should not be terminated by a semi-colon (;)."
},
{
"code": null,
"e": 3030,
"s": 2867,
"text": "Let's start with typing a simple sqlite3 command at command prompt which will provide you with SQLite command prompt where you will issue various SQLite commands."
},
{
"code": null,
"e": 3100,
"s": 3030,
"text": "$sqlite3\nSQLite version 3.3.6\nEnter \".help\" for instructions\nsqlite>\n"
},
{
"code": null,
"e": 3191,
"s": 3100,
"text": "For a listing of the available dot commands, you can enter \".help\" any time. For example −"
},
{
"code": null,
"e": 3204,
"s": 3191,
"text": "sqlite>.help"
},
{
"code": null,
"e": 3325,
"s": 3204,
"text": "The above command will display a list of various important SQLite dot commands, which are listed in the following table."
},
{
"code": null,
"e": 3343,
"s": 3325,
"text": ".backup ?DB? FILE"
},
{
"code": null,
"e": 3378,
"s": 3343,
"text": "Backup DB (default \"main\") to FILE"
},
{
"code": null,
"e": 3391,
"s": 3378,
"text": ".bail ON|OFF"
},
{
"code": null,
"e": 3432,
"s": 3391,
"text": "Stop after hitting an error. Default OFF"
},
{
"code": null,
"e": 3443,
"s": 3432,
"text": ".databases"
},
{
"code": null,
"e": 3486,
"s": 3443,
"text": "List names and files of attached databases"
},
{
"code": null,
"e": 3500,
"s": 3486,
"text": ".dump ?TABLE?"
},
{
"code": null,
"e": 3606,
"s": 3500,
"text": "Dump the database in an SQL text format. If TABLE specified, only dump tables matching LIKE pattern TABLE"
},
{
"code": null,
"e": 3619,
"s": 3606,
"text": ".echo ON|OFF"
},
{
"code": null,
"e": 3647,
"s": 3619,
"text": "Turn command echo on or off"
},
{
"code": null,
"e": 3653,
"s": 3647,
"text": ".exit"
},
{
"code": null,
"e": 3672,
"s": 3653,
"text": "Exit SQLite prompt"
},
{
"code": null,
"e": 3688,
"s": 3672,
"text": ".explain ON|OFF"
},
{
"code": null,
"e": 3771,
"s": 3688,
"text": "Turn output mode suitable for EXPLAIN on or off. With no args, it turns EXPLAIN on"
},
{
"code": null,
"e": 3789,
"s": 3771,
"text": ".header(s) ON|OFF"
},
{
"code": null,
"e": 3823,
"s": 3789,
"text": "Turn display of headers on or off"
},
{
"code": null,
"e": 3829,
"s": 3823,
"text": ".help"
},
{
"code": null,
"e": 3847,
"s": 3829,
"text": "Show this message"
},
{
"code": null,
"e": 3866,
"s": 3847,
"text": ".import FILE TABLE"
},
{
"code": null,
"e": 3899,
"s": 3866,
"text": "Import data from FILE into TABLE"
},
{
"code": null,
"e": 3916,
"s": 3899,
"text": ".indices ?TABLE?"
},
{
"code": null,
"e": 4020,
"s": 3916,
"text": "Show names of all indices. If TABLE specified, only show indices for tables matching LIKE pattern TABLE"
},
{
"code": null,
"e": 4039,
"s": 4020,
"text": ".load FILE ?ENTRY?"
},
{
"code": null,
"e": 4065,
"s": 4039,
"text": "Load an extension library"
},
{
"code": null,
"e": 4079,
"s": 4065,
"text": ".log FILE|off"
},
{
"code": null,
"e": 4129,
"s": 4079,
"text": "Turn logging on or off. FILE can be stderr/stdout"
},
{
"code": null,
"e": 4140,
"s": 4129,
"text": ".mode MODE"
},
{
"code": null,
"e": 4179,
"s": 4140,
"text": "Set output mode where MODE is one of −"
},
{
"code": null,
"e": 4208,
"s": 4179,
"text": "csv − Comma-separated values"
},
{
"code": null,
"e": 4237,
"s": 4208,
"text": "csv − Comma-separated values"
},
{
"code": null,
"e": 4268,
"s": 4237,
"text": "column − Left-aligned columns."
},
{
"code": null,
"e": 4299,
"s": 4268,
"text": "column − Left-aligned columns."
},
{
"code": null,
"e": 4324,
"s": 4299,
"text": "html − HTML <table> code"
},
{
"code": null,
"e": 4349,
"s": 4324,
"text": "html − HTML <table> code"
},
{
"code": null,
"e": 4390,
"s": 4349,
"text": "insert − SQL insert statements for TABLE"
},
{
"code": null,
"e": 4431,
"s": 4390,
"text": "insert − SQL insert statements for TABLE"
},
{
"code": null,
"e": 4457,
"s": 4431,
"text": "line − One value per line"
},
{
"code": null,
"e": 4483,
"s": 4457,
"text": "line − One value per line"
},
{
"code": null,
"e": 4528,
"s": 4483,
"text": "list − Values delimited by .separator string"
},
{
"code": null,
"e": 4573,
"s": 4528,
"text": "list − Values delimited by .separator string"
},
{
"code": null,
"e": 4601,
"s": 4573,
"text": "tabs − Tab-separated values"
},
{
"code": null,
"e": 4629,
"s": 4601,
"text": "tabs − Tab-separated values"
},
{
"code": null,
"e": 4653,
"s": 4629,
"text": "tcl − TCL list elements"
},
{
"code": null,
"e": 4677,
"s": 4653,
"text": "tcl − TCL list elements"
},
{
"code": null,
"e": 4695,
"s": 4677,
"text": ".nullvalue STRING"
},
{
"code": null,
"e": 4732,
"s": 4695,
"text": "Print STRING in place of NULL values"
},
{
"code": null,
"e": 4749,
"s": 4732,
"text": ".output FILENAME"
},
{
"code": null,
"e": 4773,
"s": 4749,
"text": "Send output to FILENAME"
},
{
"code": null,
"e": 4788,
"s": 4773,
"text": ".output stdout"
},
{
"code": null,
"e": 4815,
"s": 4788,
"text": " Send output to the screen"
},
{
"code": null,
"e": 4832,
"s": 4815,
"text": ".print STRING..."
},
{
"code": null,
"e": 4853,
"s": 4832,
"text": "Print literal STRING"
},
{
"code": null,
"e": 4875,
"s": 4853,
"text": ".prompt MAIN CONTINUE"
},
{
"code": null,
"e": 4904,
"s": 4875,
"text": "Replace the standard prompts"
},
{
"code": null,
"e": 4910,
"s": 4904,
"text": ".quit"
},
{
"code": null,
"e": 4929,
"s": 4910,
"text": "Exit SQLite prompt"
},
{
"code": null,
"e": 4944,
"s": 4929,
"text": ".read FILENAME"
},
{
"code": null,
"e": 4968,
"s": 4944,
"text": "Execute SQL in FILENAME"
},
{
"code": null,
"e": 4984,
"s": 4968,
"text": ".schema ?TABLE?"
},
{
"code": null,
"e": 5077,
"s": 4984,
"text": "Show the CREATE statements. If TABLE specified, only show tables matching LIKE pattern TABLE"
},
{
"code": null,
"e": 5095,
"s": 5077,
"text": ".separator STRING"
},
{
"code": null,
"e": 5144,
"s": 5095,
"text": "Change separator used by output mode and .import"
},
{
"code": null,
"e": 5150,
"s": 5144,
"text": ".show"
},
{
"code": null,
"e": 5195,
"s": 5150,
"text": "Show the current values for various settings"
},
{
"code": null,
"e": 5209,
"s": 5195,
"text": ".stats ON|OFF"
},
{
"code": null,
"e": 5230,
"s": 5209,
"text": "Turn stats on or off"
},
{
"code": null,
"e": 5248,
"s": 5230,
"text": ".tables ?PATTERN?"
},
{
"code": null,
"e": 5293,
"s": 5248,
"text": "List names of tables matching a LIKE pattern"
},
{
"code": null,
"e": 5305,
"s": 5293,
"text": ".timeout MS"
},
{
"code": null,
"e": 5351,
"s": 5305,
"text": "Try opening locked tables for MS milliseconds"
},
{
"code": null,
"e": 5366,
"s": 5351,
"text": ".width NUM NUM"
},
{
"code": null,
"e": 5402,
"s": 5366,
"text": "Set column widths for \"column\" mode"
},
{
"code": null,
"e": 5417,
"s": 5402,
"text": ".timer ON|OFF "
},
{
"code": null,
"e": 5458,
"s": 5417,
"text": "Turn the CPU timer measurement on or off"
},
{
"code": null,
"e": 5537,
"s": 5458,
"text": "Let's try .show command to see default setting for your SQLite command prompt."
},
{
"code": null,
"e": 5679,
"s": 5537,
"text": "sqlite>.show\n echo: off\n explain: off\n headers: off\n mode: column\nnullvalue: \"\"\n output: stdout\nseparator: \"|\"\n width:\nsqlite>"
},
{
"code": null,
"e": 5778,
"s": 5679,
"text": "Make sure there is no space in between sqlite> prompt and dot command, otherwise it will not work."
},
{
"code": null,
"e": 5852,
"s": 5778,
"text": "You can use the following sequence of dot commands to format your output."
},
{
"code": null,
"e": 5915,
"s": 5852,
"text": "sqlite>.header on\nsqlite>.mode column\nsqlite>.timer on\nsqlite>"
},
{
"code": null,
"e": 5982,
"s": 5915,
"text": "The above setting will produce the output in the following format."
},
{
"code": null,
"e": 6526,
"s": 5982,
"text": "ID NAME AGE ADDRESS SALARY\n---------- ---------- ---------- ---------- ----------\n1 Paul 32 California 20000.0\n2 Allen 25 Texas 15000.0\n3 Teddy 23 Norway 20000.0\n4 Mark 25 Rich-Mond 65000.0\n5 David 27 Texas 85000.0\n6 Kim 22 South-Hall 45000.0\n7 James 24 Houston 10000.0\nCPU Time: user 0.000000 sys 0.000000\n"
},
{
"code": null,
"e": 6664,
"s": 6526,
"text": "The master table holds the key information about your database tables and it is called sqlite_master. You can see its schema as follows −"
},
{
"code": null,
"e": 6693,
"s": 6664,
"text": "sqlite>.schema sqlite_master"
},
{
"code": null,
"e": 6733,
"s": 6693,
"text": "This will produce the following result."
},
{
"code": null,
"e": 6845,
"s": 6733,
"text": "CREATE TABLE sqlite_master (\n type text,\n name text,\n tbl_name text,\n rootpage integer,\n sql text\n);\n"
},
{
"code": null,
"e": 6880,
"s": 6845,
"text": "\n 25 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 6901,
"s": 6880,
"text": " Sandip Bhattacharya"
},
{
"code": null,
"e": 6934,
"s": 6901,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6951,
"s": 6934,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 6982,
"s": 6951,
"text": "\n 5 Lectures \n 51 mins\n"
},
{
"code": null,
"e": 6995,
"s": 6982,
"text": " Vinay Kumar"
},
{
"code": null,
"e": 7002,
"s": 6995,
"text": " Print"
},
{
"code": null,
"e": 7013,
"s": 7002,
"text": " Add Notes"
}
] |
Ethereum - Solidity for Contract Writing
|
Solidity is an object-oriented language especially developed for contract writing. It is a high-level language, which inherits traits from C++, Python, and JavaScript. The Solidity compiler compiles your source code into bytecode that runs on Ethereum Virtual Machine (EVM).
For quick understanding of the Solidity syntax, look at the sample code in the IDE.
pragma solidity >=0.4.22 <0.6.0;
contract Ballot {
The first line is a directive to the compiler. The second line starts the definition of the contract. Within the contract, you declare variables such as −
address chairperson;
You can also define structures such as Proposal and create an array of these structure items. Examine this in the code window.
You may then define a constructor which is invoked at the time of instantiating a contract.
constructor(uint8 _numProposals) public {
After the constructor, you will define several methods, which are the contract methods. In the sample contract, giveRightToVote is one such method having the following syntax −
function giveRightToVote(address toVoter) public {
The public keyword makes this method publicly invokable by any client who has access to the contract.
Likewise, the sample contract defines three more methods called delegate, vote, and winningProposal. Examine these for your own understanding of the Solidity syntax. These are the prerequisites to writing your own contract. Explaining the full syntax of Solidity is beyond the scope of this tutorial.
38 Lectures
4.5 hours
Abhilash Nelson
53 Lectures
9.5 hours
Frahaan Hussain
62 Lectures
8.5 hours
Frahaan Hussain
103 Lectures
9.5 hours
Total Seminars
31 Lectures
3.5 hours
Swapnil Kole
64 Lectures
12.5 hours
Blockchain Post
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2438,
"s": 2163,
"text": "Solidity is an object-oriented language especially developed for contract writing. It is a high-level language, which inherits traits from C++, Python, and JavaScript. The Solidity compiler compiles your source code into bytecode that runs on Ethereum Virtual Machine (EVM)."
},
{
"code": null,
"e": 2522,
"s": 2438,
"text": "For quick understanding of the Solidity syntax, look at the sample code in the IDE."
},
{
"code": null,
"e": 2574,
"s": 2522,
"text": "pragma solidity >=0.4.22 <0.6.0;\ncontract Ballot {\n"
},
{
"code": null,
"e": 2729,
"s": 2574,
"text": "The first line is a directive to the compiler. The second line starts the definition of the contract. Within the contract, you declare variables such as −"
},
{
"code": null,
"e": 2751,
"s": 2729,
"text": "address chairperson;\n"
},
{
"code": null,
"e": 2878,
"s": 2751,
"text": "You can also define structures such as Proposal and create an array of these structure items. Examine this in the code window."
},
{
"code": null,
"e": 2970,
"s": 2878,
"text": "You may then define a constructor which is invoked at the time of instantiating a contract."
},
{
"code": null,
"e": 3013,
"s": 2970,
"text": "constructor(uint8 _numProposals) public {\n"
},
{
"code": null,
"e": 3190,
"s": 3013,
"text": "After the constructor, you will define several methods, which are the contract methods. In the sample contract, giveRightToVote is one such method having the following syntax −"
},
{
"code": null,
"e": 3242,
"s": 3190,
"text": "function giveRightToVote(address toVoter) public {\n"
},
{
"code": null,
"e": 3344,
"s": 3242,
"text": "The public keyword makes this method publicly invokable by any client who has access to the contract."
},
{
"code": null,
"e": 3645,
"s": 3344,
"text": "Likewise, the sample contract defines three more methods called delegate, vote, and winningProposal. Examine these for your own understanding of the Solidity syntax. These are the prerequisites to writing your own contract. Explaining the full syntax of Solidity is beyond the scope of this tutorial."
},
{
"code": null,
"e": 3680,
"s": 3645,
"text": "\n 38 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3697,
"s": 3680,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3732,
"s": 3697,
"text": "\n 53 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 3749,
"s": 3732,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3784,
"s": 3749,
"text": "\n 62 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3801,
"s": 3784,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3837,
"s": 3801,
"text": "\n 103 Lectures \n 9.5 hours \n"
},
{
"code": null,
"e": 3853,
"s": 3837,
"text": " Total Seminars"
},
{
"code": null,
"e": 3888,
"s": 3853,
"text": "\n 31 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3902,
"s": 3888,
"text": " Swapnil Kole"
},
{
"code": null,
"e": 3938,
"s": 3902,
"text": "\n 64 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 3955,
"s": 3938,
"text": " Blockchain Post"
},
{
"code": null,
"e": 3962,
"s": 3955,
"text": " Print"
},
{
"code": null,
"e": 3973,
"s": 3962,
"text": " Add Notes"
}
] |
Difference between concat() and + operator in Java - GeeksforGeeks
|
07 Jan, 2022
Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. Concatenation is the process of joining end-to-end.
The Java String concat() method of String class has been itself present inside java.util package concatenates one string to the end of another string. This method returns a string with the value of the string passed into the method, appended to the end of the string.
Illustration:
Input: String 1 : abc
String 2 : def
String n-1 : ...
String n : xyz
Output: abcdef...xyz
Example:
Java
// Java Program to Demonstrate Working of concat() method // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input string 1 String s = "Geeks "; // Custom input string 2 is passed as in arguments // Here we are adding it to end of same string s = s.concat("for Geeks"); // Printing the concatenated string System.out.println(s); }}
Geeks for Geeks
Now let us do dwell on the next concept where we will be discussing
+ operator is used for concatenating strings on either side and is used just likely we are up to adding two numbers, henceforth providing us the flexibility to add on either side.
Example:
Java
// Java Program to Demonstrate Working of + Operator// over Strings // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input strings String s1 = " Geeks "; String s2 = " for Geeks "; // Now using + operator over string where // flexibility is provided to add on either side String s3 = s1 + s2; String s4 = s2 + s1; // Printing strings formed after // using + operator System.out.println(s3); System.out.println(s4); }}
Geeks for Geeks
for Geeks Geeks
Although concat() method of Strings class and + operator are both used for the concatenation of strings, there are some differences between them which are depicted below in the tabular format as follows:
Factor 1: Number of arguments the concat() method and + operator takes
concat() method takes only one argument of string and concatenates it with other string.
+ operator takes any number of arguments and concatenates all the strings.
Example
Java
// Java Program to Illustrate concat() method// vs + operator in Strings // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String s = "Geeks", t = "for", g = "geeks"; // Printing combined string using + operator System.out.println(s + t + g); // Printing combined string using concat() method System.out.println(s.concat(t)); }}
Geeksforgeeks
Geeksfor
Factor 2: Type of arguments
string concat() method takes only string arguments, if there is any other type is given in arguments then it will raise an error.
+ operator takes any type and converts to string type and then concatenates the strings.
Factor 3: concat() method raises java.lang.NullPointer Exception
concat() method throws NullPointer Exception when a string is concatenated with null
+ operator did not raise any Exception when the string is concatenated with null.
Example
Java
// Java Program to Illustrate Raise of NullPointer Exception// in case of concat() Method // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Input string 1 String s = "Geeks"; // Input string 2 String r = null; // Combining above strings using + operator and // printing resultant string System.out.println(s + r); // Combining above strings using concat() method and // printing resultant string // It raises an NullPointer Exception System.out.println(s.concat(r)); }}
Output:
Factor 4: Creates a new String object
concat() method takes concatenates two strings and returns a new string object only string length is greater than 0, otherwise, it returns the same object.
+ operator creates a new String object every time irrespective of the length of the string.
Example
Java
// Java Program to Illustrate Creation of New String object// in concat() method and + Operator // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Input strings String s = "Geeks", g = ""; // Using concat() method over strings String f = s.concat(g); // Checking if both strings are equal // Case 1 if (f == s) // Identical strings System.out.println("Both are same"); else // Non-identical strings System.out.println("not same"); // Case 2 String e = s + g; // Again checking if both strings are equal if (e == s) // Identical strings System.out.println("Both are same"); else // Non-identical strings System.out.println("not same"); }}
Both are same
not same
Factor 5: Performance
concat() method is better than the + operator because it creates a new object only when the string length is greater than zero(0) but the + operator always creates a new string irrespective of the length of the string.
Conclusion: From above two programs we draw see that both are somehow adding up two strings directly or indirectly. In concat method we are bound to while adding strings as we have to pass the string in the parameter while in other case of ‘+’ operator, it is simply adding up strings likely mathematics, so there is no bound we can add either side.
Below is the table to depict major differences between both the methods:
akramyamin97
akshaysingh98088
bhuwanesh
Java-Strings
Picked
Difference Between
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between IPv4 and IPv6
Difference Between Method Overloading and Method Overriding in Java
Difference between Process and Thread
Difference between Clustered and Non-clustered index
For-each loop in Java
Object Oriented Programming (OOPs) Concept in Java
Stream In Java
HashMap in Java with Examples
Reverse a string in Java
|
[
{
"code": null,
"e": 26502,
"s": 26474,
"text": "\n07 Jan, 2022"
},
{
"code": null,
"e": 26860,
"s": 26502,
"text": "Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\\0’. Since arrays are immutable(cannot grow), Strings are immutable as well. Whenever a change to a String is made, an entirely new String is created. Concatenation is the process of joining end-to-end."
},
{
"code": null,
"e": 27128,
"s": 26860,
"text": "The Java String concat() method of String class has been itself present inside java.util package concatenates one string to the end of another string. This method returns a string with the value of the string passed into the method, appended to the end of the string."
},
{
"code": null,
"e": 27142,
"s": 27128,
"text": "Illustration:"
},
{
"code": null,
"e": 27265,
"s": 27142,
"text": "Input: String 1 : abc\n String 2 : def\n String n-1 : ...\n String n : xyz\nOutput: abcdef...xyz "
},
{
"code": null,
"e": 27274,
"s": 27265,
"text": "Example:"
},
{
"code": null,
"e": 27279,
"s": 27274,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Working of concat() method // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input string 1 String s = \"Geeks \"; // Custom input string 2 is passed as in arguments // Here we are adding it to end of same string s = s.concat(\"for Geeks\"); // Printing the concatenated string System.out.println(s); }}",
"e": 27722,
"s": 27279,
"text": null
},
{
"code": null,
"e": 27738,
"s": 27722,
"text": "Geeks for Geeks"
},
{
"code": null,
"e": 27807,
"s": 27738,
"text": "Now let us do dwell on the next concept where we will be discussing "
},
{
"code": null,
"e": 27988,
"s": 27807,
"text": "+ operator is used for concatenating strings on either side and is used just likely we are up to adding two numbers, henceforth providing us the flexibility to add on either side. "
},
{
"code": null,
"e": 27997,
"s": 27988,
"text": "Example:"
},
{
"code": null,
"e": 28002,
"s": 27997,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Working of + Operator// over Strings // Main classclass GFG { // Main driver method public static void main(String args[]) { // Custom input strings String s1 = \" Geeks \"; String s2 = \" for Geeks \"; // Now using + operator over string where // flexibility is provided to add on either side String s3 = s1 + s2; String s4 = s2 + s1; // Printing strings formed after // using + operator System.out.println(s3); System.out.println(s4); }}",
"e": 28561,
"s": 28002,
"text": null
},
{
"code": null,
"e": 28599,
"s": 28561,
"text": " Geeks for Geeks \n for Geeks Geeks "
},
{
"code": null,
"e": 28803,
"s": 28599,
"text": "Although concat() method of Strings class and + operator are both used for the concatenation of strings, there are some differences between them which are depicted below in the tabular format as follows:"
},
{
"code": null,
"e": 28874,
"s": 28803,
"text": "Factor 1: Number of arguments the concat() method and + operator takes"
},
{
"code": null,
"e": 28963,
"s": 28874,
"text": "concat() method takes only one argument of string and concatenates it with other string."
},
{
"code": null,
"e": 29038,
"s": 28963,
"text": "+ operator takes any number of arguments and concatenates all the strings."
},
{
"code": null,
"e": 29046,
"s": 29038,
"text": "Example"
},
{
"code": null,
"e": 29051,
"s": 29046,
"text": "Java"
},
{
"code": "// Java Program to Illustrate concat() method// vs + operator in Strings // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Custom input string String s = \"Geeks\", t = \"for\", g = \"geeks\"; // Printing combined string using + operator System.out.println(s + t + g); // Printing combined string using concat() method System.out.println(s.concat(t)); }}",
"e": 29505,
"s": 29051,
"text": null
},
{
"code": null,
"e": 29528,
"s": 29505,
"text": "Geeksforgeeks\nGeeksfor"
},
{
"code": null,
"e": 29556,
"s": 29528,
"text": "Factor 2: Type of arguments"
},
{
"code": null,
"e": 29686,
"s": 29556,
"text": "string concat() method takes only string arguments, if there is any other type is given in arguments then it will raise an error."
},
{
"code": null,
"e": 29775,
"s": 29686,
"text": "+ operator takes any type and converts to string type and then concatenates the strings."
},
{
"code": null,
"e": 29840,
"s": 29775,
"text": "Factor 3: concat() method raises java.lang.NullPointer Exception"
},
{
"code": null,
"e": 29925,
"s": 29840,
"text": "concat() method throws NullPointer Exception when a string is concatenated with null"
},
{
"code": null,
"e": 30007,
"s": 29925,
"text": "+ operator did not raise any Exception when the string is concatenated with null."
},
{
"code": null,
"e": 30015,
"s": 30007,
"text": "Example"
},
{
"code": null,
"e": 30020,
"s": 30015,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Raise of NullPointer Exception// in case of concat() Method // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Input string 1 String s = \"Geeks\"; // Input string 2 String r = null; // Combining above strings using + operator and // printing resultant string System.out.println(s + r); // Combining above strings using concat() method and // printing resultant string // It raises an NullPointer Exception System.out.println(s.concat(r)); }}",
"e": 30632,
"s": 30020,
"text": null
},
{
"code": null,
"e": 30640,
"s": 30632,
"text": "Output:"
},
{
"code": null,
"e": 30678,
"s": 30640,
"text": "Factor 4: Creates a new String object"
},
{
"code": null,
"e": 30834,
"s": 30678,
"text": "concat() method takes concatenates two strings and returns a new string object only string length is greater than 0, otherwise, it returns the same object."
},
{
"code": null,
"e": 30926,
"s": 30834,
"text": "+ operator creates a new String object every time irrespective of the length of the string."
},
{
"code": null,
"e": 30934,
"s": 30926,
"text": "Example"
},
{
"code": null,
"e": 30939,
"s": 30934,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Creation of New String object// in concat() method and + Operator // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Input strings String s = \"Geeks\", g = \"\"; // Using concat() method over strings String f = s.concat(g); // Checking if both strings are equal // Case 1 if (f == s) // Identical strings System.out.println(\"Both are same\"); else // Non-identical strings System.out.println(\"not same\"); // Case 2 String e = s + g; // Again checking if both strings are equal if (e == s) // Identical strings System.out.println(\"Both are same\"); else // Non-identical strings System.out.println(\"not same\"); }}",
"e": 31827,
"s": 30939,
"text": null
},
{
"code": null,
"e": 31850,
"s": 31827,
"text": "Both are same\nnot same"
},
{
"code": null,
"e": 31872,
"s": 31850,
"text": "Factor 5: Performance"
},
{
"code": null,
"e": 32091,
"s": 31872,
"text": "concat() method is better than the + operator because it creates a new object only when the string length is greater than zero(0) but the + operator always creates a new string irrespective of the length of the string."
},
{
"code": null,
"e": 32441,
"s": 32091,
"text": "Conclusion: From above two programs we draw see that both are somehow adding up two strings directly or indirectly. In concat method we are bound to while adding strings as we have to pass the string in the parameter while in other case of ‘+’ operator, it is simply adding up strings likely mathematics, so there is no bound we can add either side."
},
{
"code": null,
"e": 32514,
"s": 32441,
"text": "Below is the table to depict major differences between both the methods:"
},
{
"code": null,
"e": 32527,
"s": 32514,
"text": "akramyamin97"
},
{
"code": null,
"e": 32544,
"s": 32527,
"text": "akshaysingh98088"
},
{
"code": null,
"e": 32554,
"s": 32544,
"text": "bhuwanesh"
},
{
"code": null,
"e": 32567,
"s": 32554,
"text": "Java-Strings"
},
{
"code": null,
"e": 32574,
"s": 32567,
"text": "Picked"
},
{
"code": null,
"e": 32593,
"s": 32574,
"text": "Difference Between"
},
{
"code": null,
"e": 32598,
"s": 32593,
"text": "Java"
},
{
"code": null,
"e": 32611,
"s": 32598,
"text": "Java-Strings"
},
{
"code": null,
"e": 32616,
"s": 32611,
"text": "Java"
},
{
"code": null,
"e": 32714,
"s": 32616,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32775,
"s": 32714,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32809,
"s": 32775,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 32877,
"s": 32809,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 32915,
"s": 32877,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 32968,
"s": 32915,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 32990,
"s": 32968,
"text": "For-each loop in Java"
},
{
"code": null,
"e": 33041,
"s": 32990,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 33056,
"s": 33041,
"text": "Stream In Java"
},
{
"code": null,
"e": 33086,
"s": 33056,
"text": "HashMap in Java with Examples"
}
] |
Learning Rust by Converting Python to Rust | by Shinichi Okada | Towards Data Science
|
[Updated on 2021–02–18. Codes changed to Gist and added links]
Table of ContentsIntroduction🦀 Leetcode Unique Paths🦀 Python Code🦀 First Step in Rust🦀 Examples of Primitive Data Types:🦀 Functions🦀 Statements and Expressions🦀 Variables🦀 Macros🦀 if-else Statement (Step 2)🦀 Calling a Function🦀 Range🦀 Arrays, Tuples, and Vectors🦀 as Keyword🦀 Final Code🦀 Struct and Impl🦀 Trait🦀 Runtime & Memory UsageConclusion
Rust is a statically and strongly typed systems programming language. Rust is for people who crave speed and stability in a language.
I consider myself a Rust beginner. I started learning Rust after writing this article and I am still learning new things every day. I am at the stage where I can convert simple Python code to Rust and be able to explain what I am coding.
In this article, we are going to use a Python solution of one of the Leetcode problems and convert it to Rust code. You will find not only similarities between the two languages but also learn Rust programming.
You can run the code and also tweak it in the examples in this article.
towardsdatascience.com
LeetCode is a very popular website where you can level up your coding skills. One of the problems is called “Unique Paths” where a robot is located at the top-left corner of a m x n grid. You can only move either down or right and you need to find how many unique paths there are between two points.
For example from point A to B in the image below, there are 3 unique paths and from A to C there are 5 unique paths. The following diagram helps you to find the number of unique paths from A to each area. Since you only move down or right, you add the number above and left to find the number of the unique paths to that point.
There must be many ways to solve this problem using Python, but we are going to use the following solution.
In this Python code:
We create a class called Solution. We define a method called “uniquePaths”. (It is the starting code.)
It takes self, integer m , and an integer n as parameters and returns an integer. It uses type annotations.
If m or n equals 1 then it returns 1.
If n is less than m then it switches the positions and runs the same method.
dp = [1]*n will create a list with n number of 1. e.g [1]*3 will create [1,1,1].
We use a double for-loops and range to add a previous number to the next item. [1,2,3], [1,3,6] etc. You can check this by changing the return value to return dp.
We return the last number in the list using [-1].
We are going to convert this Python code to Rust step by step in this article.
The above result shows that the runtime is 36 ms and the memory usage is 13.6 MB. We will compare this one with the Rust result later.
(When I submitted it again to LeetCode, the result changes and the above one was the best one. You may have a different result.)
We are going to start with a basic Rust code.
Rust always runs the main function first when you run the program. We create a function called unique_pathswith two parameters mand n, which are i32 types.
In function, we must declare the type of each parameter. Every variable, item, and value in a Rust program has a type.
The type of value defines the interpretation of the memory holding it. i32 is one of the primitive data types and a 32-bit fixed-sized signed integer types. i32 can hold a number between -(231), which is -2147483648, and 231-1, which is 2147483647.
More primitive data types are in this link.
By the way, Rust’s default integer type is i32 so if you don't annotate the type of parameters in a closure and if they are integers, Rust will use i32. Rust's compiler is able to infer the types of the parameters and most variables.
Functions use the fn keyword to start. Rust code uses a snake case as the conventional style for functions. Functions can return values and we declare their type for the return value using an arrow ->. The unique_paths returns data type of i32. Rust uses {} for the function body.
We return the sum, m + n. Functions' bodies are made of a series of statements and ending in an expression.
Statements are instructions that perform some action and do not return a value. Expressions evaluate to a resulting value. — Function Bodies Contain Statements and Expressions
The expression m + n doesn't include ending semicolons because we want to return it. If you add a semicolon to the end of an expression, you turn it into a statement and it will not return a value.
In the main() function, we use a keyword let to indicate a variable. Local variables are immutable as default, but you can use mut to make them mutable. For our case, we don’t need to make it mutable.
println!() is one of the standard macros. It parses the format string and converts it into the print format.
pritln! fills up the placeholders in order. You can use the index and name="vale".
In the next step, we add a if-else statement. expr == expr (where expr means expression) is the equality comparison. expr || expr is the logical OR.
If either of m or n equals 1 then we return 1. Please note no semicolon after 1 since we want to return 1.
Rust doesn’t use a bracket for the condition in if statement.
if-else if-else has the following form.
This may not be necessary to pass the LeetCode, but this shows you how to call the own function from within.
If n is smaller than m, we swap the variable positions and call the own function.
In Python, we used range as:
for i in range(1,m): for j in range(1,n):
In Rust, we use .. or ..=.
The above code will output 1 to 9.
The above code will output 1 to 10.
In Python we used dp = [1]*n. This will create n numbers of [1]. For example when n=3, [1, 1, 1].
Let’s check which one from arrays, tuples, or vectors in Rust we can use for this purpose.
Arrays
Arrays must have the same type and fixed-length. Arrays are immutable by default and we can’t use mut to change its element.
Output:
one: 1, b: [4, 5, 6], c: [1, 1, 1, 1, 1], d: [1, 1, 1, 1, 1]
We also can’t set an array length dynamically. Because arrays have a length defined at compile time. A variable is not known at compile-time because it can vary. The compiler would not know how much space to allocate on the stack to provide storage for the array.
If you try to print out without the {:?}, you will fail. We can’t format an array with the default formatter. All the Rust data types implement Debug trait, and you can use {:?} to format it and print an array.
So we can’t use an array here.
Tuples
Tuples can have different types and have a fixed length.
let tup: (i32, f64, u8) = (100, 2.32, 4);
To get the individual values out of a tuple, we can use pattern matching to destructure a tuple value.
Output:
x = 500, y = 6.2, z = 41
Again we can’t use tuples since they must have a fixed length.
Vectors
Rust vectors store more than one value next to each other in memory. Vectors store values of the same type.
A contiguous growable array type with heap-allocated contents. — doc.rust-lang.org
The vec! macro creates a new vector that holds the values you give it.
let v = vec![1, 1, 1];// this is the same as abovelet u = vec![1; 3];
A vector is like a re-sizable array but all elements must be in the same type.
So we will need to use a vector.
dpm = vec![1; m as usize];dpn = vec![1; n as usize];
The second number, the length, in vec![1; 3] needs to be usize type. We annotated m and n as i32 but we can cast types using theas keyword. We can use the as expression only converting between primitive types.
as is most commonly used to turn primitive types into other primitive types. — doc.rust-lang
vectors has a method len that returns the number of elements in the vector.
We use all the above codes to get the number of unique paths.
You may notice that #[allow(unused_variables)]. It will work without it but the compiler gives you a warning:
warning: unused variable: `i` --> main.rs" data-line="11" data-column="13">main.rs:11:13 |11 | for i in 1..dpm.len() { | ^ help: if this is intentional, prefix it with an underscore: `_i` | = note: `#[warn(unused_variables)]` on by defaultwarning: 1 warning emitted
To remove this warning we add #[allow(unused_variables)].
We will see the final code for LeetCode later. Before that, we are going a step further with this code.
We are going to apply struct, impl, and trait to the above solution. Please note that this won’t work on LeetCode.
Structs are used to encapsulate related properties into one unified data type. Structs are different from classes in other languages. For example, Rust’s struct doesn’t support inheritance.
Tuples are convenient but using the index like t.0 and keeping track of the meaning of each part isn't straightforward.
Rust structs contain named fields. We use a keyword struct and set fields with its type within the curly bracket. A structure defines data as a key-value pair.
struct Name_of_struct { field1:data_type, field2:data_type, ...}
&str and String
You may be wondering why we need to_string(). Rust has two main types of strings: &str and String. &str is called ‘string slices’. A string slice has a fixed size, and cannot be mutated. A String is stored as a vector. String is heap-allocated, growable, and not null-terminated. (More on this in this link.)
"John" is a &str and since we defined the type of first_name as String in the struct, we need to convert to a String using to_string.
We put associated functions into a impl block.
Method parameter self, &self, and &mut self
We added a method full_name in impl Person. The function takes &self as the first parameter. It can take one of self, &self, or &mut self.
We use &self when we want to read the data in the struct, not write to it.
We use self when we want the method to take ownership.
We use &mut self when we want the method to write to it.
We use the dot operator for instance methods as in p.full_name() to access the field.
Let’s use struct and impl to our code:
Traits are similar to interfaces in OOP languages. They are used to define the functionality a type must provide.
We added a trait called UiquePaths with a function unique_paths. We need to update the impl using impl trait-name for struct-name.
We instantiate it in the main function using :: notation.
Now we implemented struct, impl, and trait.
The following solution is adjusted for the LeetCode environment.
impl Solution { pub fn unique_paths(m: i32, n: i32) -> i32 { if m == 1 || n == 1 { 1 } else { let mut dpm = vec![1; m as usize]; let mut dpn = vec![1; n as usize]; for i in 1..dpm.len() { for j in 1..dpn.len() { dpn[j] += dpn[j-1]; } } *dpn.last().unwrap() } }}
Please note Runtime 0 ms. Rust does not have a runtime. Rust applies Zero-cost abstraction. There’s no extra runtime overhead that you pay for certain powerful abstractions or safety features that you do have to pay a runtime cost for in other languages.
... iterators, although a high-level abstraction, get compiled down to roughly the same code as if you’d written the lower-level code yourself. Iterators are one of Rust’s zero-cost abstractions, by which we mean using the abstraction imposes no additional runtime overhead. — Rust Programming Language
Rust’s memory usage was 2.1 MB comparing to 13.8 MB in Python.
Rust has unique ways of managing heap memory and it uses a concept called ownership to manage it. I recommend that you dive into the Rust documentation to learn more about it.
We touched the surfaces of primitive data types, type annotations, functions, statements, expressions, variables, macro, if statement, range, arrays, tuples, vectors, struct, impl, and trait. You can find more information in the official book.
As I stated before I am still learning Rust. I appreciate expert feedback on how to improve the solution.
I hope you learned something and are ready for the next step. There are many key concepts we couldn’t cover in this article. Please stay tuned for the next post.
Get full access to every story on Medium by becoming a member.
|
[
{
"code": null,
"e": 110,
"s": 47,
"text": "[Updated on 2021–02–18. Codes changed to Gist and added links]"
},
{
"code": null,
"e": 455,
"s": 110,
"text": "Table of ContentsIntroduction🦀 Leetcode Unique Paths🦀 Python Code🦀 First Step in Rust🦀 Examples of Primitive Data Types:🦀 Functions🦀 Statements and Expressions🦀 Variables🦀 Macros🦀 if-else Statement (Step 2)🦀 Calling a Function🦀 Range🦀 Arrays, Tuples, and Vectors🦀 as Keyword🦀 Final Code🦀 Struct and Impl🦀 Trait🦀 Runtime & Memory UsageConclusion"
},
{
"code": null,
"e": 589,
"s": 455,
"text": "Rust is a statically and strongly typed systems programming language. Rust is for people who crave speed and stability in a language."
},
{
"code": null,
"e": 827,
"s": 589,
"text": "I consider myself a Rust beginner. I started learning Rust after writing this article and I am still learning new things every day. I am at the stage where I can convert simple Python code to Rust and be able to explain what I am coding."
},
{
"code": null,
"e": 1038,
"s": 827,
"text": "In this article, we are going to use a Python solution of one of the Leetcode problems and convert it to Rust code. You will find not only similarities between the two languages but also learn Rust programming."
},
{
"code": null,
"e": 1110,
"s": 1038,
"text": "You can run the code and also tweak it in the examples in this article."
},
{
"code": null,
"e": 1133,
"s": 1110,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1433,
"s": 1133,
"text": "LeetCode is a very popular website where you can level up your coding skills. One of the problems is called “Unique Paths” where a robot is located at the top-left corner of a m x n grid. You can only move either down or right and you need to find how many unique paths there are between two points."
},
{
"code": null,
"e": 1761,
"s": 1433,
"text": "For example from point A to B in the image below, there are 3 unique paths and from A to C there are 5 unique paths. The following diagram helps you to find the number of unique paths from A to each area. Since you only move down or right, you add the number above and left to find the number of the unique paths to that point."
},
{
"code": null,
"e": 1869,
"s": 1761,
"text": "There must be many ways to solve this problem using Python, but we are going to use the following solution."
},
{
"code": null,
"e": 1890,
"s": 1869,
"text": "In this Python code:"
},
{
"code": null,
"e": 1993,
"s": 1890,
"text": "We create a class called Solution. We define a method called “uniquePaths”. (It is the starting code.)"
},
{
"code": null,
"e": 2101,
"s": 1993,
"text": "It takes self, integer m , and an integer n as parameters and returns an integer. It uses type annotations."
},
{
"code": null,
"e": 2139,
"s": 2101,
"text": "If m or n equals 1 then it returns 1."
},
{
"code": null,
"e": 2216,
"s": 2139,
"text": "If n is less than m then it switches the positions and runs the same method."
},
{
"code": null,
"e": 2297,
"s": 2216,
"text": "dp = [1]*n will create a list with n number of 1. e.g [1]*3 will create [1,1,1]."
},
{
"code": null,
"e": 2460,
"s": 2297,
"text": "We use a double for-loops and range to add a previous number to the next item. [1,2,3], [1,3,6] etc. You can check this by changing the return value to return dp."
},
{
"code": null,
"e": 2510,
"s": 2460,
"text": "We return the last number in the list using [-1]."
},
{
"code": null,
"e": 2589,
"s": 2510,
"text": "We are going to convert this Python code to Rust step by step in this article."
},
{
"code": null,
"e": 2724,
"s": 2589,
"text": "The above result shows that the runtime is 36 ms and the memory usage is 13.6 MB. We will compare this one with the Rust result later."
},
{
"code": null,
"e": 2853,
"s": 2724,
"text": "(When I submitted it again to LeetCode, the result changes and the above one was the best one. You may have a different result.)"
},
{
"code": null,
"e": 2899,
"s": 2853,
"text": "We are going to start with a basic Rust code."
},
{
"code": null,
"e": 3055,
"s": 2899,
"text": "Rust always runs the main function first when you run the program. We create a function called unique_pathswith two parameters mand n, which are i32 types."
},
{
"code": null,
"e": 3174,
"s": 3055,
"text": "In function, we must declare the type of each parameter. Every variable, item, and value in a Rust program has a type."
},
{
"code": null,
"e": 3423,
"s": 3174,
"text": "The type of value defines the interpretation of the memory holding it. i32 is one of the primitive data types and a 32-bit fixed-sized signed integer types. i32 can hold a number between -(231), which is -2147483648, and 231-1, which is 2147483647."
},
{
"code": null,
"e": 3467,
"s": 3423,
"text": "More primitive data types are in this link."
},
{
"code": null,
"e": 3701,
"s": 3467,
"text": "By the way, Rust’s default integer type is i32 so if you don't annotate the type of parameters in a closure and if they are integers, Rust will use i32. Rust's compiler is able to infer the types of the parameters and most variables."
},
{
"code": null,
"e": 3982,
"s": 3701,
"text": "Functions use the fn keyword to start. Rust code uses a snake case as the conventional style for functions. Functions can return values and we declare their type for the return value using an arrow ->. The unique_paths returns data type of i32. Rust uses {} for the function body."
},
{
"code": null,
"e": 4090,
"s": 3982,
"text": "We return the sum, m + n. Functions' bodies are made of a series of statements and ending in an expression."
},
{
"code": null,
"e": 4266,
"s": 4090,
"text": "Statements are instructions that perform some action and do not return a value. Expressions evaluate to a resulting value. — Function Bodies Contain Statements and Expressions"
},
{
"code": null,
"e": 4464,
"s": 4266,
"text": "The expression m + n doesn't include ending semicolons because we want to return it. If you add a semicolon to the end of an expression, you turn it into a statement and it will not return a value."
},
{
"code": null,
"e": 4665,
"s": 4464,
"text": "In the main() function, we use a keyword let to indicate a variable. Local variables are immutable as default, but you can use mut to make them mutable. For our case, we don’t need to make it mutable."
},
{
"code": null,
"e": 4774,
"s": 4665,
"text": "println!() is one of the standard macros. It parses the format string and converts it into the print format."
},
{
"code": null,
"e": 4857,
"s": 4774,
"text": "pritln! fills up the placeholders in order. You can use the index and name=\"vale\"."
},
{
"code": null,
"e": 5006,
"s": 4857,
"text": "In the next step, we add a if-else statement. expr == expr (where expr means expression) is the equality comparison. expr || expr is the logical OR."
},
{
"code": null,
"e": 5113,
"s": 5006,
"text": "If either of m or n equals 1 then we return 1. Please note no semicolon after 1 since we want to return 1."
},
{
"code": null,
"e": 5175,
"s": 5113,
"text": "Rust doesn’t use a bracket for the condition in if statement."
},
{
"code": null,
"e": 5215,
"s": 5175,
"text": "if-else if-else has the following form."
},
{
"code": null,
"e": 5324,
"s": 5215,
"text": "This may not be necessary to pass the LeetCode, but this shows you how to call the own function from within."
},
{
"code": null,
"e": 5406,
"s": 5324,
"text": "If n is smaller than m, we swap the variable positions and call the own function."
},
{
"code": null,
"e": 5435,
"s": 5406,
"text": "In Python, we used range as:"
},
{
"code": null,
"e": 5480,
"s": 5435,
"text": "for i in range(1,m): for j in range(1,n):"
},
{
"code": null,
"e": 5507,
"s": 5480,
"text": "In Rust, we use .. or ..=."
},
{
"code": null,
"e": 5542,
"s": 5507,
"text": "The above code will output 1 to 9."
},
{
"code": null,
"e": 5578,
"s": 5542,
"text": "The above code will output 1 to 10."
},
{
"code": null,
"e": 5676,
"s": 5578,
"text": "In Python we used dp = [1]*n. This will create n numbers of [1]. For example when n=3, [1, 1, 1]."
},
{
"code": null,
"e": 5767,
"s": 5676,
"text": "Let’s check which one from arrays, tuples, or vectors in Rust we can use for this purpose."
},
{
"code": null,
"e": 5774,
"s": 5767,
"text": "Arrays"
},
{
"code": null,
"e": 5899,
"s": 5774,
"text": "Arrays must have the same type and fixed-length. Arrays are immutable by default and we can’t use mut to change its element."
},
{
"code": null,
"e": 5907,
"s": 5899,
"text": "Output:"
},
{
"code": null,
"e": 5968,
"s": 5907,
"text": "one: 1, b: [4, 5, 6], c: [1, 1, 1, 1, 1], d: [1, 1, 1, 1, 1]"
},
{
"code": null,
"e": 6232,
"s": 5968,
"text": "We also can’t set an array length dynamically. Because arrays have a length defined at compile time. A variable is not known at compile-time because it can vary. The compiler would not know how much space to allocate on the stack to provide storage for the array."
},
{
"code": null,
"e": 6443,
"s": 6232,
"text": "If you try to print out without the {:?}, you will fail. We can’t format an array with the default formatter. All the Rust data types implement Debug trait, and you can use {:?} to format it and print an array."
},
{
"code": null,
"e": 6474,
"s": 6443,
"text": "So we can’t use an array here."
},
{
"code": null,
"e": 6481,
"s": 6474,
"text": "Tuples"
},
{
"code": null,
"e": 6538,
"s": 6481,
"text": "Tuples can have different types and have a fixed length."
},
{
"code": null,
"e": 6580,
"s": 6538,
"text": "let tup: (i32, f64, u8) = (100, 2.32, 4);"
},
{
"code": null,
"e": 6683,
"s": 6580,
"text": "To get the individual values out of a tuple, we can use pattern matching to destructure a tuple value."
},
{
"code": null,
"e": 6691,
"s": 6683,
"text": "Output:"
},
{
"code": null,
"e": 6716,
"s": 6691,
"text": "x = 500, y = 6.2, z = 41"
},
{
"code": null,
"e": 6779,
"s": 6716,
"text": "Again we can’t use tuples since they must have a fixed length."
},
{
"code": null,
"e": 6787,
"s": 6779,
"text": "Vectors"
},
{
"code": null,
"e": 6895,
"s": 6787,
"text": "Rust vectors store more than one value next to each other in memory. Vectors store values of the same type."
},
{
"code": null,
"e": 6978,
"s": 6895,
"text": "A contiguous growable array type with heap-allocated contents. — doc.rust-lang.org"
},
{
"code": null,
"e": 7049,
"s": 6978,
"text": "The vec! macro creates a new vector that holds the values you give it."
},
{
"code": null,
"e": 7119,
"s": 7049,
"text": "let v = vec![1, 1, 1];// this is the same as abovelet u = vec![1; 3];"
},
{
"code": null,
"e": 7198,
"s": 7119,
"text": "A vector is like a re-sizable array but all elements must be in the same type."
},
{
"code": null,
"e": 7231,
"s": 7198,
"text": "So we will need to use a vector."
},
{
"code": null,
"e": 7284,
"s": 7231,
"text": "dpm = vec![1; m as usize];dpn = vec![1; n as usize];"
},
{
"code": null,
"e": 7494,
"s": 7284,
"text": "The second number, the length, in vec![1; 3] needs to be usize type. We annotated m and n as i32 but we can cast types using theas keyword. We can use the as expression only converting between primitive types."
},
{
"code": null,
"e": 7587,
"s": 7494,
"text": "as is most commonly used to turn primitive types into other primitive types. — doc.rust-lang"
},
{
"code": null,
"e": 7663,
"s": 7587,
"text": "vectors has a method len that returns the number of elements in the vector."
},
{
"code": null,
"e": 7725,
"s": 7663,
"text": "We use all the above codes to get the number of unique paths."
},
{
"code": null,
"e": 7835,
"s": 7725,
"text": "You may notice that #[allow(unused_variables)]. It will work without it but the compiler gives you a warning:"
},
{
"code": null,
"e": 8130,
"s": 7835,
"text": "warning: unused variable: `i` --> main.rs\" data-line=\"11\" data-column=\"13\">main.rs:11:13 |11 | for i in 1..dpm.len() { | ^ help: if this is intentional, prefix it with an underscore: `_i` | = note: `#[warn(unused_variables)]` on by defaultwarning: 1 warning emitted"
},
{
"code": null,
"e": 8188,
"s": 8130,
"text": "To remove this warning we add #[allow(unused_variables)]."
},
{
"code": null,
"e": 8292,
"s": 8188,
"text": "We will see the final code for LeetCode later. Before that, we are going a step further with this code."
},
{
"code": null,
"e": 8407,
"s": 8292,
"text": "We are going to apply struct, impl, and trait to the above solution. Please note that this won’t work on LeetCode."
},
{
"code": null,
"e": 8597,
"s": 8407,
"text": "Structs are used to encapsulate related properties into one unified data type. Structs are different from classes in other languages. For example, Rust’s struct doesn’t support inheritance."
},
{
"code": null,
"e": 8717,
"s": 8597,
"text": "Tuples are convenient but using the index like t.0 and keeping track of the meaning of each part isn't straightforward."
},
{
"code": null,
"e": 8877,
"s": 8717,
"text": "Rust structs contain named fields. We use a keyword struct and set fields with its type within the curly bracket. A structure defines data as a key-value pair."
},
{
"code": null,
"e": 8948,
"s": 8877,
"text": "struct Name_of_struct { field1:data_type, field2:data_type, ...}"
},
{
"code": null,
"e": 8964,
"s": 8948,
"text": "&str and String"
},
{
"code": null,
"e": 9273,
"s": 8964,
"text": "You may be wondering why we need to_string(). Rust has two main types of strings: &str and String. &str is called ‘string slices’. A string slice has a fixed size, and cannot be mutated. A String is stored as a vector. String is heap-allocated, growable, and not null-terminated. (More on this in this link.)"
},
{
"code": null,
"e": 9407,
"s": 9273,
"text": "\"John\" is a &str and since we defined the type of first_name as String in the struct, we need to convert to a String using to_string."
},
{
"code": null,
"e": 9454,
"s": 9407,
"text": "We put associated functions into a impl block."
},
{
"code": null,
"e": 9498,
"s": 9454,
"text": "Method parameter self, &self, and &mut self"
},
{
"code": null,
"e": 9637,
"s": 9498,
"text": "We added a method full_name in impl Person. The function takes &self as the first parameter. It can take one of self, &self, or &mut self."
},
{
"code": null,
"e": 9712,
"s": 9637,
"text": "We use &self when we want to read the data in the struct, not write to it."
},
{
"code": null,
"e": 9767,
"s": 9712,
"text": "We use self when we want the method to take ownership."
},
{
"code": null,
"e": 9824,
"s": 9767,
"text": "We use &mut self when we want the method to write to it."
},
{
"code": null,
"e": 9910,
"s": 9824,
"text": "We use the dot operator for instance methods as in p.full_name() to access the field."
},
{
"code": null,
"e": 9949,
"s": 9910,
"text": "Let’s use struct and impl to our code:"
},
{
"code": null,
"e": 10063,
"s": 9949,
"text": "Traits are similar to interfaces in OOP languages. They are used to define the functionality a type must provide."
},
{
"code": null,
"e": 10194,
"s": 10063,
"text": "We added a trait called UiquePaths with a function unique_paths. We need to update the impl using impl trait-name for struct-name."
},
{
"code": null,
"e": 10252,
"s": 10194,
"text": "We instantiate it in the main function using :: notation."
},
{
"code": null,
"e": 10296,
"s": 10252,
"text": "Now we implemented struct, impl, and trait."
},
{
"code": null,
"e": 10361,
"s": 10296,
"text": "The following solution is adjusted for the LeetCode environment."
},
{
"code": null,
"e": 10768,
"s": 10361,
"text": "impl Solution { pub fn unique_paths(m: i32, n: i32) -> i32 { if m == 1 || n == 1 { 1 } else { let mut dpm = vec![1; m as usize]; let mut dpn = vec![1; n as usize]; for i in 1..dpm.len() { for j in 1..dpn.len() { dpn[j] += dpn[j-1]; } } *dpn.last().unwrap() } }}"
},
{
"code": null,
"e": 11023,
"s": 10768,
"text": "Please note Runtime 0 ms. Rust does not have a runtime. Rust applies Zero-cost abstraction. There’s no extra runtime overhead that you pay for certain powerful abstractions or safety features that you do have to pay a runtime cost for in other languages."
},
{
"code": null,
"e": 11326,
"s": 11023,
"text": "... iterators, although a high-level abstraction, get compiled down to roughly the same code as if you’d written the lower-level code yourself. Iterators are one of Rust’s zero-cost abstractions, by which we mean using the abstraction imposes no additional runtime overhead. — Rust Programming Language"
},
{
"code": null,
"e": 11389,
"s": 11326,
"text": "Rust’s memory usage was 2.1 MB comparing to 13.8 MB in Python."
},
{
"code": null,
"e": 11565,
"s": 11389,
"text": "Rust has unique ways of managing heap memory and it uses a concept called ownership to manage it. I recommend that you dive into the Rust documentation to learn more about it."
},
{
"code": null,
"e": 11809,
"s": 11565,
"text": "We touched the surfaces of primitive data types, type annotations, functions, statements, expressions, variables, macro, if statement, range, arrays, tuples, vectors, struct, impl, and trait. You can find more information in the official book."
},
{
"code": null,
"e": 11915,
"s": 11809,
"text": "As I stated before I am still learning Rust. I appreciate expert feedback on how to improve the solution."
},
{
"code": null,
"e": 12077,
"s": 11915,
"text": "I hope you learned something and are ready for the next step. There are many key concepts we couldn’t cover in this article. Please stay tuned for the next post."
}
] |
Java Exceptions (Try...Catch)
|
When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input,
or other unforeseeable things.
When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error).
The try statement allows you to define a block of code to be
tested for errors while it is being executed.
The catch statement allows you to define a block of code to
be executed, if an error occurs in the try block.
The try and catch keywords
come in pairs:
try {
// Block of code to try
}
catch(Exception e) {
// Block of code to handle errors
}
Consider the following example:
This will generate an error, because myNumbers[10] does not exist.
public class Main {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
}
}
The output will be something like this:
If an error occurs, we can use try...catch to catch the error and execute some code to handle it:
public class Main {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
}
}
The output will be:
The finally statement lets you execute code, after try...catch, regardless of the result:
public class Main {
public static void main(String[] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
} finally {
System.out.println("The 'try catch' is finished.");
}
}
}
The output will be:
The throw statement allows you to create a custom error.
The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException,
FileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:
Throw an exception if age is below 18 (print "Access
denied"). If age is 18 or older, print "Access granted":
public class Main {
static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
}
else {
System.out.println("Access granted - You are old enough!");
}
}
public static void main(String[] args) {
checkAge(15); // Set age to 15 (which is below 18...)
}
}
The output will be:
If age was 20, you would not get an exception:
checkAge(20);
The output will be:
Insert the missing parts to handle the error in the code below.
{
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} (Exception e) {
System.out.println("Something went wrong.");
}
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
help@w3schools.com
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 151,
"s": 0,
"text": "When executing Java code, different errors can occur: coding errors made by the programmer, errors due to wrong input, \nor other unforeseeable things."
},
{
"code": null,
"e": 307,
"s": 151,
"text": "When an error occurs, Java will normally stop and generate an error message. The technical term for this is: Java will throw an exception (throw an error)."
},
{
"code": null,
"e": 415,
"s": 307,
"text": "The try statement allows you to define a block of code to be \ntested for errors while it is being executed."
},
{
"code": null,
"e": 526,
"s": 415,
"text": "The catch statement allows you to define a block of code to \nbe executed, if an error occurs in the try block."
},
{
"code": null,
"e": 569,
"s": 526,
"text": "The try and catch keywords \ncome in pairs:"
},
{
"code": null,
"e": 665,
"s": 569,
"text": "try {\n // Block of code to try\n}\ncatch(Exception e) {\n // Block of code to handle errors\n}\n"
},
{
"code": null,
"e": 697,
"s": 665,
"text": "Consider the following example:"
},
{
"code": null,
"e": 764,
"s": 697,
"text": "This will generate an error, because myNumbers[10] does not exist."
},
{
"code": null,
"e": 917,
"s": 764,
"text": "public class Main {\n public static void main(String[ ] args) {\n int[] myNumbers = {1, 2, 3};\n System.out.println(myNumbers[10]); // error!\n }\n}\n"
},
{
"code": null,
"e": 957,
"s": 917,
"text": "The output will be something like this:"
},
{
"code": null,
"e": 1055,
"s": 957,
"text": "If an error occurs, we can use try...catch to catch the error and execute some code to handle it:"
},
{
"code": null,
"e": 1301,
"s": 1055,
"text": "public class Main {\n public static void main(String[ ] args) {\n try {\n int[] myNumbers = {1, 2, 3};\n System.out.println(myNumbers[10]);\n } catch (Exception e) {\n System.out.println(\"Something went wrong.\");\n }\n }\n}\n \n \n"
},
{
"code": null,
"e": 1321,
"s": 1301,
"text": "The output will be:"
},
{
"code": null,
"e": 1411,
"s": 1321,
"text": "The finally statement lets you execute code, after try...catch, regardless of the result:"
},
{
"code": null,
"e": 1728,
"s": 1411,
"text": "public class Main {\n public static void main(String[] args) {\n try {\n int[] myNumbers = {1, 2, 3};\n System.out.println(myNumbers[10]);\n } catch (Exception e) {\n System.out.println(\"Something went wrong.\");\n } finally {\n System.out.println(\"The 'try catch' is finished.\");\n }\n }\n}\n \n"
},
{
"code": null,
"e": 1748,
"s": 1728,
"text": "The output will be:"
},
{
"code": null,
"e": 1805,
"s": 1748,
"text": "The throw statement allows you to create a custom error."
},
{
"code": null,
"e": 2017,
"s": 1805,
"text": "The throw statement is used together with an exception type. There are many exception types available in Java: ArithmeticException, \nFileNotFoundException, ArrayIndexOutOfBoundsException, SecurityException, etc:"
},
{
"code": null,
"e": 2128,
"s": 2017,
"text": "Throw an exception if age is below 18 (print \"Access \ndenied\"). If age is 18 or older, print \"Access granted\":"
},
{
"code": null,
"e": 2497,
"s": 2128,
"text": "public class Main {\n static void checkAge(int age) {\n if (age < 18) {\n throw new ArithmeticException(\"Access denied - You must be at least 18 years old.\");\n }\n else {\n System.out.println(\"Access granted - You are old enough!\");\n }\n }\n\n public static void main(String[] args) {\n checkAge(15); // Set age to 15 (which is below 18...)\n }\n}\n \n"
},
{
"code": null,
"e": 2517,
"s": 2497,
"text": "The output will be:"
},
{
"code": null,
"e": 2564,
"s": 2517,
"text": "If age was 20, you would not get an exception:"
},
{
"code": null,
"e": 2579,
"s": 2564,
"text": "checkAge(20);\n"
},
{
"code": null,
"e": 2599,
"s": 2579,
"text": "The output will be:"
},
{
"code": null,
"e": 2663,
"s": 2599,
"text": "Insert the missing parts to handle the error in the code below."
},
{
"code": null,
"e": 2803,
"s": 2663,
"text": " {\n int[] myNumbers = {1, 2, 3};\n System.out.println(myNumbers[10]);\n} (Exception e) {\n System.out.println(\"Something went wrong.\");\n}\n"
},
{
"code": null,
"e": 2822,
"s": 2803,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2855,
"s": 2822,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2897,
"s": 2855,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3004,
"s": 2897,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 3023,
"s": 3004,
"text": "help@w3schools.com"
}
] |
Build, Test and Deploy a Flask REST API Application from GitHub using Jenkins Pipeline Running on Docker
|
22 Sep, 2021
Nowadays even for small web applications or microservices, we need an easier and faster way to deploy applications that is reliable and safe. These applications may be simple but they undergo rapid changes from the business requirement, to handle these changes we definitely need a CI/CD pipeline for deployment.
Jenkins is one such tool that can make your life easier when you want to build, test and deploy on the fly. This article will give you the complete or at least most of the things that you need for creating a CI/CD pipeline to deploy Flask Application using Jenkins.
Docker
Python3.6+
Git
Flask
There is the list of contents that I will be covering to get this up and working.
We will be performing the below-listed operation in this article:
Building the Flask App (local build)Creating the JenkinsFileSpinning up Jenkins on DockerIntegrating GitHub repo to JenkinsTesting out Jenkins Pipeline Trigger
Building the Flask App (local build)
Creating the JenkinsFile
Spinning up Jenkins on Docker
Integrating GitHub repo to Jenkins
Testing out Jenkins Pipeline Trigger
First, we will try to build our Flask application locally before we push it to GitHub.
git clone https://github.com/Santhoshkumard11/Flask-Calculator-Beginner-Docker.git
Run the Flask app as below (after getting into the Flask-Calculator-Beginner-Docker)
flask run
or
python app.py
the output of the above code
We will be creating a three-stage pipeline, but you can have as many as your application requires.
Build Stage – This is where we download the code from your code repository, but since we have already configured GitHub as the branch source Jenkins will do the work of downloading the code or at least in our case. It’s different if you have a React or Angular application.
Test Stage – You run the unit tests for the Flask App and output the results using xmlrunner which will be picked up by Jenkins
Deploy Stage – run the Flask Application on nohup and append the output to log.txt but you will use Gunicorn or WSGI in actual deployment.
We also have a post-stage which will do the clean-up or email notification of the pipeline’s success or failure.
Javascript
pipeline { agent any stages { stage('Build') { parallel { stage('Build') { steps { sh 'echo "building the repo"' } } } } stage('Test') { steps { sh 'python3 test_app.py' input(id: "Deploy Gate", message: "Deploy ${params.project_name}?", ok: 'Deploy') } } stage('Deploy') { steps { echo "deploying the application" sh "sudo nohup python3 app.py > log.txt 2>&1 &" } } } post { always { echo 'The pipeline completed' junit allowEmptyResults: true, testResults:'**/test_reports/*.xml' } success { echo "Flask Application Up and running!!" } failure { echo 'Build stage failed' error('Stopping early...') } }}
Pull the Docker Image from Docker Hub
docker pull santhoshkdhana/jenkins-python3.9
Now it’s time to spin up the container with the below command,
docker run --name myjenkins -p 8080:8080 -p 50000:50000 -p 5000:5000 -v /your/home:/var/jenkins_home -v /your/home/sock:/var/run/docker.sock jenkins-python3.9
Verify if the container is running using
docker container list -a
checking on the container
Once you have successfully seen the container is up and running, install the required packages
docker exec myjenkins pip3 install flask flask_restful xmlrunner
Type localhost:8080 in your favorite browser. You should see Jenkins asking for the password or use the below command to get the password. Use the initial password from the command line to create an admin user.
docker exec myjenkins cat /var/jenkins_home/secrets/initialAdminPassword
Note: make sure your docker daemon is running else use service docker start to start the daemon (Ubuntu/Debian)
Jenkins password
Start by creating a new item, give it the name Flask Jenkins Build (it’s your choice)
Select the multibranch pipeline style and click ok
Select GitHub from Branch Sources
Paste https://github.com/Santhoshkumard11/Flask-Calculator-Beginner-Docker and click on validate (you need to add credentials if it’s not a publicly accessible repo)
Once it says connected, scroll down to the bottom and click apply and save
Now you have integrated your GitHub repo to Jenkins, from now on whenever you commit to the qa branch the pipeline would start running.Go to Jenkins home and click on the Pipeline name you created and then the branch name.
To run this manually, click on Build Now from the sidebar on your left.
After the test stage, you will have to manually click deploy to get the deployment stage running.
Click on Open Blue Ocean to see a new UI with the build stages.
Blogathon-2021
DevOps
docker
GitHub
Advanced Computer Subject
Blogathon
TechTips
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
ML | Monte Carlo Tree Search (MCTS)
Copying Files to and from Docker Containers
Basics of API Testing Using Postman
Markov Decision Process
Getting Started with System Design
How to Call or Consume External API in Spring Boot?
Re-rendering Components in ReactJS
SQL Query to Insert Multiple Rows
How to Connect Python with SQL Database?
How to Import JSON Data into SQL Server?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Sep, 2021"
},
{
"code": null,
"e": 341,
"s": 28,
"text": "Nowadays even for small web applications or microservices, we need an easier and faster way to deploy applications that is reliable and safe. These applications may be simple but they undergo rapid changes from the business requirement, to handle these changes we definitely need a CI/CD pipeline for deployment."
},
{
"code": null,
"e": 607,
"s": 341,
"text": "Jenkins is one such tool that can make your life easier when you want to build, test and deploy on the fly. This article will give you the complete or at least most of the things that you need for creating a CI/CD pipeline to deploy Flask Application using Jenkins."
},
{
"code": null,
"e": 614,
"s": 607,
"text": "Docker"
},
{
"code": null,
"e": 625,
"s": 614,
"text": "Python3.6+"
},
{
"code": null,
"e": 629,
"s": 625,
"text": "Git"
},
{
"code": null,
"e": 635,
"s": 629,
"text": "Flask"
},
{
"code": null,
"e": 717,
"s": 635,
"text": "There is the list of contents that I will be covering to get this up and working."
},
{
"code": null,
"e": 783,
"s": 717,
"text": "We will be performing the below-listed operation in this article:"
},
{
"code": null,
"e": 943,
"s": 783,
"text": "Building the Flask App (local build)Creating the JenkinsFileSpinning up Jenkins on DockerIntegrating GitHub repo to JenkinsTesting out Jenkins Pipeline Trigger"
},
{
"code": null,
"e": 980,
"s": 943,
"text": "Building the Flask App (local build)"
},
{
"code": null,
"e": 1005,
"s": 980,
"text": "Creating the JenkinsFile"
},
{
"code": null,
"e": 1035,
"s": 1005,
"text": "Spinning up Jenkins on Docker"
},
{
"code": null,
"e": 1070,
"s": 1035,
"text": "Integrating GitHub repo to Jenkins"
},
{
"code": null,
"e": 1107,
"s": 1070,
"text": "Testing out Jenkins Pipeline Trigger"
},
{
"code": null,
"e": 1194,
"s": 1107,
"text": "First, we will try to build our Flask application locally before we push it to GitHub."
},
{
"code": null,
"e": 1277,
"s": 1194,
"text": "git clone https://github.com/Santhoshkumard11/Flask-Calculator-Beginner-Docker.git"
},
{
"code": null,
"e": 1362,
"s": 1277,
"text": "Run the Flask app as below (after getting into the Flask-Calculator-Beginner-Docker)"
},
{
"code": null,
"e": 1389,
"s": 1362,
"text": "flask run\nor\npython app.py"
},
{
"code": null,
"e": 1418,
"s": 1389,
"text": "the output of the above code"
},
{
"code": null,
"e": 1517,
"s": 1418,
"text": "We will be creating a three-stage pipeline, but you can have as many as your application requires."
},
{
"code": null,
"e": 1791,
"s": 1517,
"text": "Build Stage – This is where we download the code from your code repository, but since we have already configured GitHub as the branch source Jenkins will do the work of downloading the code or at least in our case. It’s different if you have a React or Angular application."
},
{
"code": null,
"e": 1919,
"s": 1791,
"text": "Test Stage – You run the unit tests for the Flask App and output the results using xmlrunner which will be picked up by Jenkins"
},
{
"code": null,
"e": 2058,
"s": 1919,
"text": "Deploy Stage – run the Flask Application on nohup and append the output to log.txt but you will use Gunicorn or WSGI in actual deployment."
},
{
"code": null,
"e": 2171,
"s": 2058,
"text": "We also have a post-stage which will do the clean-up or email notification of the pipeline’s success or failure."
},
{
"code": null,
"e": 2182,
"s": 2171,
"text": "Javascript"
},
{
"code": "pipeline { agent any stages { stage('Build') { parallel { stage('Build') { steps { sh 'echo \"building the repo\"' } } } } stage('Test') { steps { sh 'python3 test_app.py' input(id: \"Deploy Gate\", message: \"Deploy ${params.project_name}?\", ok: 'Deploy') } } stage('Deploy') { steps { echo \"deploying the application\" sh \"sudo nohup python3 app.py > log.txt 2>&1 &\" } } } post { always { echo 'The pipeline completed' junit allowEmptyResults: true, testResults:'**/test_reports/*.xml' } success { echo \"Flask Application Up and running!!\" } failure { echo 'Build stage failed' error('Stopping early...') } }}",
"e": 3041,
"s": 2182,
"text": null
},
{
"code": null,
"e": 3079,
"s": 3041,
"text": "Pull the Docker Image from Docker Hub"
},
{
"code": null,
"e": 3124,
"s": 3079,
"text": "docker pull santhoshkdhana/jenkins-python3.9"
},
{
"code": null,
"e": 3187,
"s": 3124,
"text": "Now it’s time to spin up the container with the below command,"
},
{
"code": null,
"e": 3346,
"s": 3187,
"text": "docker run --name myjenkins -p 8080:8080 -p 50000:50000 -p 5000:5000 -v /your/home:/var/jenkins_home -v /your/home/sock:/var/run/docker.sock jenkins-python3.9"
},
{
"code": null,
"e": 3387,
"s": 3346,
"text": "Verify if the container is running using"
},
{
"code": null,
"e": 3412,
"s": 3387,
"text": "docker container list -a"
},
{
"code": null,
"e": 3438,
"s": 3412,
"text": "checking on the container"
},
{
"code": null,
"e": 3533,
"s": 3438,
"text": "Once you have successfully seen the container is up and running, install the required packages"
},
{
"code": null,
"e": 3598,
"s": 3533,
"text": "docker exec myjenkins pip3 install flask flask_restful xmlrunner"
},
{
"code": null,
"e": 3810,
"s": 3598,
"text": "Type localhost:8080 in your favorite browser. You should see Jenkins asking for the password or use the below command to get the password. Use the initial password from the command line to create an admin user. "
},
{
"code": null,
"e": 3884,
"s": 3810,
"text": "docker exec myjenkins cat /var/jenkins_home/secrets/initialAdminPassword"
},
{
"code": null,
"e": 3996,
"s": 3884,
"text": "Note: make sure your docker daemon is running else use service docker start to start the daemon (Ubuntu/Debian)"
},
{
"code": null,
"e": 4013,
"s": 3996,
"text": "Jenkins password"
},
{
"code": null,
"e": 4099,
"s": 4013,
"text": "Start by creating a new item, give it the name Flask Jenkins Build (it’s your choice)"
},
{
"code": null,
"e": 4150,
"s": 4099,
"text": "Select the multibranch pipeline style and click ok"
},
{
"code": null,
"e": 4184,
"s": 4150,
"text": "Select GitHub from Branch Sources"
},
{
"code": null,
"e": 4350,
"s": 4184,
"text": "Paste https://github.com/Santhoshkumard11/Flask-Calculator-Beginner-Docker and click on validate (you need to add credentials if it’s not a publicly accessible repo)"
},
{
"code": null,
"e": 4425,
"s": 4350,
"text": "Once it says connected, scroll down to the bottom and click apply and save"
},
{
"code": null,
"e": 4648,
"s": 4425,
"text": "Now you have integrated your GitHub repo to Jenkins, from now on whenever you commit to the qa branch the pipeline would start running.Go to Jenkins home and click on the Pipeline name you created and then the branch name."
},
{
"code": null,
"e": 4720,
"s": 4648,
"text": "To run this manually, click on Build Now from the sidebar on your left."
},
{
"code": null,
"e": 4818,
"s": 4720,
"text": "After the test stage, you will have to manually click deploy to get the deployment stage running."
},
{
"code": null,
"e": 4882,
"s": 4818,
"text": "Click on Open Blue Ocean to see a new UI with the build stages."
},
{
"code": null,
"e": 4899,
"s": 4884,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 4906,
"s": 4899,
"text": "DevOps"
},
{
"code": null,
"e": 4913,
"s": 4906,
"text": "docker"
},
{
"code": null,
"e": 4920,
"s": 4913,
"text": "GitHub"
},
{
"code": null,
"e": 4946,
"s": 4920,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 4956,
"s": 4946,
"text": "Blogathon"
},
{
"code": null,
"e": 4965,
"s": 4956,
"text": "TechTips"
},
{
"code": null,
"e": 5063,
"s": 4965,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5099,
"s": 5063,
"text": "ML | Monte Carlo Tree Search (MCTS)"
},
{
"code": null,
"e": 5143,
"s": 5099,
"text": "Copying Files to and from Docker Containers"
},
{
"code": null,
"e": 5179,
"s": 5143,
"text": "Basics of API Testing Using Postman"
},
{
"code": null,
"e": 5203,
"s": 5179,
"text": "Markov Decision Process"
},
{
"code": null,
"e": 5238,
"s": 5203,
"text": "Getting Started with System Design"
},
{
"code": null,
"e": 5290,
"s": 5238,
"text": "How to Call or Consume External API in Spring Boot?"
},
{
"code": null,
"e": 5325,
"s": 5290,
"text": "Re-rendering Components in ReactJS"
},
{
"code": null,
"e": 5359,
"s": 5325,
"text": "SQL Query to Insert Multiple Rows"
},
{
"code": null,
"e": 5400,
"s": 5359,
"text": "How to Connect Python with SQL Database?"
}
] |
SQL Query to Find the Number of Columns in a Table
|
09 Aug, 2021
SQL stands for a structure query language, which is used in the database to retrieve data, update and modify data in relational databases like MySql, Oracle, etc. And a query is a question or request for data from the database, that is if we ask someone any question then the question is the query. Similarly when we want any data from the database then we write the query in SQL to get that data. In this article, we are talking about how we can find the number of columns present in a table.
Creating database :
To create a database there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The query is,
create database database_name;
For example,
create database GeeksforGeeks;
Output :
Commands completed successfully
Using the database :
To use the database there is a query we need to use in the SQL portal, like MySql, Oracle, etc. The query is,
use database_name;
Here the query will be,
use GeeksforGeeks;
Output :
Commands completed successfully
Add tables in the database :
To create tables in a database there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The query is,
create table table_name(
column1 type(size),
column2 type(size),
.
.
.
columnN type(size)
);
For example,
create table GeeksforGeeks(
course_ID INT,
course_name VARCHAR(50),
course_mentor VARCHAR(30),
course_fee INT,
course_start_date DATE
course_enrolled_student INT
);
Here, the table has 6 columns in it.
See the table :
To see the table use the ‘DESC table_name‘ query.
here the query is,
desc geeksforgeeks;
If we use a Microsoft SQL server then we need to use ‘EXEC sp_help’ in place of DESC. In the Microsoft SQL server, the DESC command is not an SQL command, it is used in Oracle.
EXEC sp_help GFG_salary;
Output :
SL No | Column_name | Type | Computed | Length
----------------------------------------------------------------------------------
1. | course_ID | int | no | 4
2. | course_name | varchar | no | 50
3. | course_mentor | varchar | no | 30
4. | course_fee | int | no | 4
5. | course_start_date | date | no | 3
6. | course_enrolled_student | int | no | 4
----------------------------------------------------------------------------------
Add value into the table :
To add value to the table there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The query is,
insert into table_name(
value1,
value2,
value3
.
.
.
valueN);
For example, here the query will be,
INSERT INTO `geeksforgeeks` (`course_ID`, `course_name`, `course_mentor`, `course_fee`, `course_start_date`, `course_enrolled_student`) VALUES
(1, 'SQL', 'mentor1', '3000', '2021-03-02', '10'),
(2, 'JAVA', 'mentor2a', '5000', '2021-03-02', '12'),
(3, 'DSA', 'mentor3', '4500', '2021-03-02', '25'),
(4, 'Python', 'mentor4', '3500', '2021-03-02', '20');
Output :
4 rows affected
Data present in the table after insertion :
select * from geeksforgeeks;
Output :
| course_ID | course_name | course_mentor | course_fee | course_start_date | course_enrolled_student
----------------------------------------------------------------------------------------------------------
1. | 1 | SQL | mentor1 | 3000 | 2021-03-02 | 10
2. | 2 | JAVA | mentor2a | 5000 | 2021-03-02 | 12
3. | 3 | DSA | mentor3 | 4500 | 2021-03-02 | 25
4. | 4 | Python | mentor4 | 3500 | 2021-03-02 | 20
----------------------------------------------------------------------------------------------------------
Now we have to find the number of columns present in the table,
To find that we can use a simple function COUNT() with INFORMATION_SCHEMA view in a relational database. This INFORMATION_SCHEMA is an ANSI standard set of views that provides read-only access to the details of databases and their objects like tables, constraints, procedures, etc. See the below query
SELECT count(*) as No_of_Column FROM information_schema.columns WHERE table_name ='geeksforgeeks';
Here, COUNT(*) counts the number of columns returned by the INFORMATION_SCHEMA .columns one by one and provides the final count of the columns. Here table_name selects the table in which we wish to work.
Output :
| No_of_Column
-------------------
1. | 6
-------------------
So here, the final output will be 6, because in the table “geeksforgeeks” there are 6 columns present.
DBMS-SQL
Picked
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 | DROP, TRUNCATE
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Aug, 2021"
},
{
"code": null,
"e": 522,
"s": 28,
"text": "SQL stands for a structure query language, which is used in the database to retrieve data, update and modify data in relational databases like MySql, Oracle, etc. And a query is a question or request for data from the database, that is if we ask someone any question then the question is the query. Similarly when we want any data from the database then we write the query in SQL to get that data. In this article, we are talking about how we can find the number of columns present in a table."
},
{
"code": null,
"e": 542,
"s": 522,
"text": "Creating database :"
},
{
"code": null,
"e": 655,
"s": 542,
"text": "To create a database there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The query is,"
},
{
"code": null,
"e": 686,
"s": 655,
"text": "create database database_name;"
},
{
"code": null,
"e": 700,
"s": 686,
"text": "For example, "
},
{
"code": null,
"e": 731,
"s": 700,
"text": "create database GeeksforGeeks;"
},
{
"code": null,
"e": 740,
"s": 731,
"text": "Output :"
},
{
"code": null,
"e": 772,
"s": 740,
"text": "Commands completed successfully"
},
{
"code": null,
"e": 793,
"s": 772,
"text": "Using the database :"
},
{
"code": null,
"e": 904,
"s": 793,
"text": "To use the database there is a query we need to use in the SQL portal, like MySql, Oracle, etc. The query is,"
},
{
"code": null,
"e": 923,
"s": 904,
"text": "use database_name;"
},
{
"code": null,
"e": 948,
"s": 923,
"text": "Here the query will be, "
},
{
"code": null,
"e": 967,
"s": 948,
"text": "use GeeksforGeeks;"
},
{
"code": null,
"e": 976,
"s": 967,
"text": "Output :"
},
{
"code": null,
"e": 1008,
"s": 976,
"text": "Commands completed successfully"
},
{
"code": null,
"e": 1037,
"s": 1008,
"text": "Add tables in the database :"
},
{
"code": null,
"e": 1161,
"s": 1037,
"text": "To create tables in a database there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The query is,"
},
{
"code": null,
"e": 1254,
"s": 1161,
"text": "create table table_name(\ncolumn1 type(size),\ncolumn2 type(size),\n.\n.\n.\ncolumnN type(size)\n);"
},
{
"code": null,
"e": 1267,
"s": 1254,
"text": "For example,"
},
{
"code": null,
"e": 1432,
"s": 1267,
"text": "create table GeeksforGeeks(\ncourse_ID INT,\ncourse_name VARCHAR(50),\ncourse_mentor VARCHAR(30),\ncourse_fee INT,\ncourse_start_date DATE\ncourse_enrolled_student INT\n);"
},
{
"code": null,
"e": 1469,
"s": 1432,
"text": "Here, the table has 6 columns in it."
},
{
"code": null,
"e": 1485,
"s": 1469,
"text": "See the table :"
},
{
"code": null,
"e": 1535,
"s": 1485,
"text": "To see the table use the ‘DESC table_name‘ query."
},
{
"code": null,
"e": 1555,
"s": 1535,
"text": "here the query is, "
},
{
"code": null,
"e": 1575,
"s": 1555,
"text": "desc geeksforgeeks;"
},
{
"code": null,
"e": 1752,
"s": 1575,
"text": "If we use a Microsoft SQL server then we need to use ‘EXEC sp_help’ in place of DESC. In the Microsoft SQL server, the DESC command is not an SQL command, it is used in Oracle."
},
{
"code": null,
"e": 1777,
"s": 1752,
"text": "EXEC sp_help GFG_salary;"
},
{
"code": null,
"e": 1786,
"s": 1777,
"text": "Output :"
},
{
"code": null,
"e": 2528,
"s": 1786,
"text": "SL No | Column_name | Type | Computed | Length\n----------------------------------------------------------------------------------\n1. | course_ID | int | no | 4\n2. | course_name | varchar | no | 50 \n3. | course_mentor | varchar | no | 30\n4. | course_fee | int | no | 4\n5. | course_start_date | date | no | 3\n6. | course_enrolled_student | int | no | 4\n----------------------------------------------------------------------------------"
},
{
"code": null,
"e": 2555,
"s": 2528,
"text": "Add value into the table :"
},
{
"code": null,
"e": 2673,
"s": 2555,
"text": "To add value to the table there is a query we need to use in the SQL platform, like MySql, Oracle, etc. The query is,"
},
{
"code": null,
"e": 2736,
"s": 2673,
"text": "insert into table_name(\nvalue1,\nvalue2,\nvalue3\n.\n.\n.\n\nvalueN);"
},
{
"code": null,
"e": 2773,
"s": 2736,
"text": "For example, here the query will be,"
},
{
"code": null,
"e": 3125,
"s": 2773,
"text": "INSERT INTO `geeksforgeeks` (`course_ID`, `course_name`, `course_mentor`, `course_fee`, `course_start_date`, `course_enrolled_student`) VALUES\n(1, 'SQL', 'mentor1', '3000', '2021-03-02', '10'),\n(2, 'JAVA', 'mentor2a', '5000', '2021-03-02', '12'),\n(3, 'DSA', 'mentor3', '4500', '2021-03-02', '25'),\n(4, 'Python', 'mentor4', '3500', '2021-03-02', '20');"
},
{
"code": null,
"e": 3134,
"s": 3125,
"text": "Output :"
},
{
"code": null,
"e": 3150,
"s": 3134,
"text": "4 rows affected"
},
{
"code": null,
"e": 3194,
"s": 3150,
"text": "Data present in the table after insertion :"
},
{
"code": null,
"e": 3223,
"s": 3194,
"text": "select * from geeksforgeeks;"
},
{
"code": null,
"e": 3232,
"s": 3223,
"text": "Output :"
},
{
"code": null,
"e": 3899,
"s": 3232,
"text": " | course_ID | course_name | course_mentor | course_fee | course_start_date | course_enrolled_student \n----------------------------------------------------------------------------------------------------------\n1. | 1 | SQL | mentor1 | 3000 | 2021-03-02 | 10\n2. | 2 | JAVA | mentor2a | 5000 | 2021-03-02 | 12 \n3. | 3 | DSA | mentor3 | 4500 | 2021-03-02 | 25\n4. | 4 | Python | mentor4 | 3500 | 2021-03-02 | 20\n----------------------------------------------------------------------------------------------------------"
},
{
"code": null,
"e": 3963,
"s": 3899,
"text": "Now we have to find the number of columns present in the table,"
},
{
"code": null,
"e": 4265,
"s": 3963,
"text": "To find that we can use a simple function COUNT() with INFORMATION_SCHEMA view in a relational database. This INFORMATION_SCHEMA is an ANSI standard set of views that provides read-only access to the details of databases and their objects like tables, constraints, procedures, etc. See the below query"
},
{
"code": null,
"e": 4364,
"s": 4265,
"text": "SELECT count(*) as No_of_Column FROM information_schema.columns WHERE table_name ='geeksforgeeks';"
},
{
"code": null,
"e": 4568,
"s": 4364,
"text": "Here, COUNT(*) counts the number of columns returned by the INFORMATION_SCHEMA .columns one by one and provides the final count of the columns. Here table_name selects the table in which we wish to work."
},
{
"code": null,
"e": 4577,
"s": 4568,
"text": "Output :"
},
{
"code": null,
"e": 4646,
"s": 4577,
"text": " | No_of_Column \n-------------------\n1. | 6\n-------------------"
},
{
"code": null,
"e": 4749,
"s": 4646,
"text": "So here, the final output will be 6, because in the table “geeksforgeeks” there are 6 columns present."
},
{
"code": null,
"e": 4758,
"s": 4749,
"text": "DBMS-SQL"
},
{
"code": null,
"e": 4765,
"s": 4758,
"text": "Picked"
},
{
"code": null,
"e": 4769,
"s": 4765,
"text": "SQL"
},
{
"code": null,
"e": 4773,
"s": 4769,
"text": "SQL"
},
{
"code": null,
"e": 4871,
"s": 4773,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4937,
"s": 4871,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 4961,
"s": 4937,
"text": "Window functions in SQL"
},
{
"code": null,
"e": 4993,
"s": 4961,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 5010,
"s": 4993,
"text": "SQL using Python"
},
{
"code": null,
"e": 5043,
"s": 5010,
"text": "SQL | Sub queries in From Clause"
},
{
"code": null,
"e": 5121,
"s": 5043,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 5151,
"s": 5121,
"text": "RANK() Function in SQL Server"
},
{
"code": null,
"e": 5187,
"s": 5151,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 5218,
"s": 5187,
"text": "SQL Query to Compare Two Dates"
}
] |
HTML <select> Tag
|
13 Dec, 2021
The <select> tag in HTML is used to create a drop-down list. The <select> tag contains <option> tag to display the available option of drop-down list.
Note: The <select> tag is used in a form to receive user responses.
Syntax:
<select>
<option>
</option>
...
</select>
Attributes: The attributes of the <select> tag are listed below:
autofocus: The HTML <select> autofocus Attribute is used to specify that the dropdown should automatically get focus when the page loads. It is a type of boolean attribute.
disabled: The <select> disabled attribute is used to specify the select element is disabled. A disabled drop-down list is un-clickable and unusable. It is a boolean attribute.
form: The HTML <select> form attribute is used to specify one or more forms that the <select> element belongs to.
multiple: The HTML <select> multiple attribute is a Boolean Attribute. It specifies that the user is allowed to select more than one value that presents in <select> element.
name: The HTML <select> name attribute is used to specify a name for the drop-down list. It is used to reference the form data after submitting the form or to reference the element in JavaScript.
required: The HTML <select> required attribute is a Boolean attribute that is used to specify that the user should be selected value before submitting the Form.
size: The HTML size attribute is used to specify the number of visible options in a drop-down list.
Example 1: In this example, we simply create a drop-down list in HTML.
HTML
<!DOCTYPE html><html> <body> <h2>Welcome To GeeksforGeeks</h2> <select> <option value="By the way">BTW</option> <option value="Talk to you later">TTYL</option> <option value="To be honest">TBH</option> <option value=" I don’t know">IDK</option> </select></body> </html>
Output:
HTML <select> Tag
Example 2: This example describes the HTML <select> tag with one pre-selected option.
HTML
<!DOCTYPE html><html> <head> <title>HTML select Tag</title></head> <body style="text-align:center;"> <h1>GeeksforGeeks</h1> <h2>HTML select Tag</h2> <p>Select one option from drop-down list:</p> <select> <option value="GFG">GFG</option> <option value="OS">OS</option> <option value="DBMS">DBMS</option> <option value="Data Structure">Data Structure</option> </select></body> </html>
Output:
HTML <select> Tag with pre-selected option
Example 3: In this example, we are using an optgroup tag with <select> tag. optgroup tag is used for displaying related options in the drop-down list.
HTML
<!DOCTYPE html><html> <body> <h2>Welcome To GeeksforGeeks</h2> <label for="Brands">Choose a Brand:</label> <select name="Brands" id="Brands"> <optgroup label="Tech Brands"> <option value="Google">Google</option> <option value="Apple">Apple</option> </optgroup> <optgroup label="Automative Brands"> <option value="Tesla">Tesla</option> <option value="audi">Audi</option> </optgroup> <optgroup label="Entertainment Brand"> <option value="Disney">Disney</option> </optgroup> </select></body> </html>
Output:
HTML <select> Tag with <optgroup> tag
Supported Browsers:
Google Chrome
Internet Explorer
Microsoft Edge
Firefox
Safari
Opera
nidhi_biet
simmytarika5
clintra
shubhamyadav4
bhaskargeeksforgeeks
HTML-Tags
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Design a Tribute Page using HTML & CSS
Types of CSS (Cascading Style Sheet)
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 179,
"s": 28,
"text": "The <select> tag in HTML is used to create a drop-down list. The <select> tag contains <option> tag to display the available option of drop-down list."
},
{
"code": null,
"e": 247,
"s": 179,
"text": "Note: The <select> tag is used in a form to receive user responses."
},
{
"code": null,
"e": 255,
"s": 247,
"text": "Syntax:"
},
{
"code": null,
"e": 309,
"s": 255,
"text": "<select>\n <option>\n </option>\n ...\n</select>"
},
{
"code": null,
"e": 375,
"s": 309,
"text": "Attributes: The attributes of the <select> tag are listed below: "
},
{
"code": null,
"e": 548,
"s": 375,
"text": "autofocus: The HTML <select> autofocus Attribute is used to specify that the dropdown should automatically get focus when the page loads. It is a type of boolean attribute."
},
{
"code": null,
"e": 724,
"s": 548,
"text": "disabled: The <select> disabled attribute is used to specify the select element is disabled. A disabled drop-down list is un-clickable and unusable. It is a boolean attribute."
},
{
"code": null,
"e": 838,
"s": 724,
"text": "form: The HTML <select> form attribute is used to specify one or more forms that the <select> element belongs to."
},
{
"code": null,
"e": 1012,
"s": 838,
"text": "multiple: The HTML <select> multiple attribute is a Boolean Attribute. It specifies that the user is allowed to select more than one value that presents in <select> element."
},
{
"code": null,
"e": 1208,
"s": 1012,
"text": "name: The HTML <select> name attribute is used to specify a name for the drop-down list. It is used to reference the form data after submitting the form or to reference the element in JavaScript."
},
{
"code": null,
"e": 1369,
"s": 1208,
"text": "required: The HTML <select> required attribute is a Boolean attribute that is used to specify that the user should be selected value before submitting the Form."
},
{
"code": null,
"e": 1469,
"s": 1369,
"text": "size: The HTML size attribute is used to specify the number of visible options in a drop-down list."
},
{
"code": null,
"e": 1540,
"s": 1469,
"text": "Example 1: In this example, we simply create a drop-down list in HTML."
},
{
"code": null,
"e": 1545,
"s": 1540,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h2>Welcome To GeeksforGeeks</h2> <select> <option value=\"By the way\">BTW</option> <option value=\"Talk to you later\">TTYL</option> <option value=\"To be honest\">TBH</option> <option value=\" I don’t know\">IDK</option> </select></body> </html>",
"e": 1852,
"s": 1545,
"text": null
},
{
"code": null,
"e": 1860,
"s": 1852,
"text": "Output:"
},
{
"code": null,
"e": 1878,
"s": 1860,
"text": "HTML <select> Tag"
},
{
"code": null,
"e": 1964,
"s": 1878,
"text": "Example 2: This example describes the HTML <select> tag with one pre-selected option."
},
{
"code": null,
"e": 1969,
"s": 1964,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML select Tag</title></head> <body style=\"text-align:center;\"> <h1>GeeksforGeeks</h1> <h2>HTML select Tag</h2> <p>Select one option from drop-down list:</p> <select> <option value=\"GFG\">GFG</option> <option value=\"OS\">OS</option> <option value=\"DBMS\">DBMS</option> <option value=\"Data Structure\">Data Structure</option> </select></body> </html>",
"e": 2400,
"s": 1969,
"text": null
},
{
"code": null,
"e": 2408,
"s": 2400,
"text": "Output:"
},
{
"code": null,
"e": 2451,
"s": 2408,
"text": "HTML <select> Tag with pre-selected option"
},
{
"code": null,
"e": 2602,
"s": 2451,
"text": "Example 3: In this example, we are using an optgroup tag with <select> tag. optgroup tag is used for displaying related options in the drop-down list."
},
{
"code": null,
"e": 2607,
"s": 2602,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <h2>Welcome To GeeksforGeeks</h2> <label for=\"Brands\">Choose a Brand:</label> <select name=\"Brands\" id=\"Brands\"> <optgroup label=\"Tech Brands\"> <option value=\"Google\">Google</option> <option value=\"Apple\">Apple</option> </optgroup> <optgroup label=\"Automative Brands\"> <option value=\"Tesla\">Tesla</option> <option value=\"audi\">Audi</option> </optgroup> <optgroup label=\"Entertainment Brand\"> <option value=\"Disney\">Disney</option> </optgroup> </select></body> </html>",
"e": 3213,
"s": 2607,
"text": null
},
{
"code": null,
"e": 3221,
"s": 3213,
"text": "Output:"
},
{
"code": null,
"e": 3259,
"s": 3221,
"text": "HTML <select> Tag with <optgroup> tag"
},
{
"code": null,
"e": 3280,
"s": 3259,
"text": "Supported Browsers: "
},
{
"code": null,
"e": 3294,
"s": 3280,
"text": "Google Chrome"
},
{
"code": null,
"e": 3312,
"s": 3294,
"text": "Internet Explorer"
},
{
"code": null,
"e": 3327,
"s": 3312,
"text": "Microsoft Edge"
},
{
"code": null,
"e": 3335,
"s": 3327,
"text": "Firefox"
},
{
"code": null,
"e": 3342,
"s": 3335,
"text": "Safari"
},
{
"code": null,
"e": 3348,
"s": 3342,
"text": "Opera"
},
{
"code": null,
"e": 3359,
"s": 3348,
"text": "nidhi_biet"
},
{
"code": null,
"e": 3372,
"s": 3359,
"text": "simmytarika5"
},
{
"code": null,
"e": 3380,
"s": 3372,
"text": "clintra"
},
{
"code": null,
"e": 3394,
"s": 3380,
"text": "shubhamyadav4"
},
{
"code": null,
"e": 3415,
"s": 3394,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 3425,
"s": 3415,
"text": "HTML-Tags"
},
{
"code": null,
"e": 3430,
"s": 3425,
"text": "HTML"
},
{
"code": null,
"e": 3447,
"s": 3430,
"text": "Web Technologies"
},
{
"code": null,
"e": 3452,
"s": 3447,
"text": "HTML"
},
{
"code": null,
"e": 3550,
"s": 3452,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3598,
"s": 3550,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3622,
"s": 3598,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 3672,
"s": 3622,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 3711,
"s": 3672,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 3748,
"s": 3711,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 3781,
"s": 3748,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3842,
"s": 3781,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3885,
"s": 3842,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3957,
"s": 3885,
"text": "Differences between Functional Components and Class Components in React"
}
] |
How to use SnackBar Component in ReactJS ?
|
11 Jan, 2022
Snackbars provide brief messages about app processes. Material UI for React has this component available for us, and it is very easy to integrate. We can use SnackBar Component in ReactJS using the following approach.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command.
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command.
cd foldername
Step 3: After creating the ReactJS application, Install the material-ui modules using the following command.
npm install @material-ui/core
npm install @material-ui/icons
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from "react";import IconButton from "@material-ui/core/IconButton";import Snackbar from "@material-ui/core/Snackbar";import CloseIcon from "@material-ui/icons/Close";import Button from "@material-ui/core/Button"; export default function App() { const [open, setOpen] = React.useState(false); const handleToClose = (event, reason) => { if ("clickaway" == reason) return; setOpen(false); }; const handleClickEvent = () => { setOpen(true); }; return ( <div style={{}}> <h4> How to use SnackBar Component in ReactJS? </h4> <Button onClick={handleClickEvent}> Open Snackbar </Button> <Snackbar anchorOrigin={{ horizontal: "left", vertical: "bottom", }} open={open} autoHideDuration={5000} message="Sample Warning" onClose={handleToClose} action={ <React.Fragment> <IconButton size="small" aria-label="close" color="inherit" onClick={handleToClose} > <CloseIcon fontSize="small" /> </IconButton> </React.Fragment> } /> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project.
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output.
Reference: https://material-ui.com/components/snackbars/
gulshankumarar231
Material-UI
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to create a multi-page website using React.js ?
ReactJS useNavigate() Hook
Axios in React: A Guide for Beginners
How to do crud operations in ReactJS ?
React-Router Hooks
Installation of Node.js on Linux
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to set the default value for an HTML <select> element ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 246,
"s": 28,
"text": "Snackbars provide brief messages about app processes. Material UI for React has this component available for us, and it is very easy to integrate. We can use SnackBar Component in ReactJS using the following approach."
},
{
"code": null,
"e": 296,
"s": 246,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 360,
"s": 296,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 392,
"s": 360,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 492,
"s": 392,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 506,
"s": 492,
"text": "cd foldername"
},
{
"code": null,
"e": 615,
"s": 506,
"text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command."
},
{
"code": null,
"e": 676,
"s": 615,
"text": "npm install @material-ui/core\nnpm install @material-ui/icons"
},
{
"code": null,
"e": 728,
"s": 676,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 746,
"s": 728,
"text": "Project Structure"
},
{
"code": null,
"e": 876,
"s": 746,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 883,
"s": 876,
"text": "App.js"
},
{
"code": "import React from \"react\";import IconButton from \"@material-ui/core/IconButton\";import Snackbar from \"@material-ui/core/Snackbar\";import CloseIcon from \"@material-ui/icons/Close\";import Button from \"@material-ui/core/Button\"; export default function App() { const [open, setOpen] = React.useState(false); const handleToClose = (event, reason) => { if (\"clickaway\" == reason) return; setOpen(false); }; const handleClickEvent = () => { setOpen(true); }; return ( <div style={{}}> <h4> How to use SnackBar Component in ReactJS? </h4> <Button onClick={handleClickEvent}> Open Snackbar </Button> <Snackbar anchorOrigin={{ horizontal: \"left\", vertical: \"bottom\", }} open={open} autoHideDuration={5000} message=\"Sample Warning\" onClose={handleToClose} action={ <React.Fragment> <IconButton size=\"small\" aria-label=\"close\" color=\"inherit\" onClick={handleToClose} > <CloseIcon fontSize=\"small\" /> </IconButton> </React.Fragment> } /> </div> );}",
"e": 2083,
"s": 883,
"text": null
},
{
"code": null,
"e": 2196,
"s": 2083,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project."
},
{
"code": null,
"e": 2206,
"s": 2196,
"text": "npm start"
},
{
"code": null,
"e": 2305,
"s": 2206,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output."
},
{
"code": null,
"e": 2362,
"s": 2305,
"text": "Reference: https://material-ui.com/components/snackbars/"
},
{
"code": null,
"e": 2380,
"s": 2362,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 2392,
"s": 2380,
"text": "Material-UI"
},
{
"code": null,
"e": 2408,
"s": 2392,
"text": "React-Questions"
},
{
"code": null,
"e": 2416,
"s": 2408,
"text": "ReactJS"
},
{
"code": null,
"e": 2433,
"s": 2416,
"text": "Web Technologies"
},
{
"code": null,
"e": 2531,
"s": 2433,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2583,
"s": 2531,
"text": "How to create a multi-page website using React.js ?"
},
{
"code": null,
"e": 2610,
"s": 2583,
"text": "ReactJS useNavigate() Hook"
},
{
"code": null,
"e": 2648,
"s": 2610,
"text": "Axios in React: A Guide for Beginners"
},
{
"code": null,
"e": 2687,
"s": 2648,
"text": "How to do crud operations in ReactJS ?"
},
{
"code": null,
"e": 2706,
"s": 2687,
"text": "React-Router Hooks"
},
{
"code": null,
"e": 2739,
"s": 2706,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2789,
"s": 2739,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 2851,
"s": 2789,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2909,
"s": 2851,
"text": "How to create footer to stay at the bottom of a Web page?"
}
] |
HTML | <video> poster Attribute
|
16 Jun, 2022
The HTML <video> poster Attribute is used to display the image while video downloading or when user click the play button. If this image not set then it will take the first frame of video as a poster image.
Syntax:
<video poster="URL">
Attribute Values: It contains a single value URL which specifies the link of source image. There are two types of URL link which are listed below:
Absolute URL: It points to another webpage.
Relative URL: It points to other files of the same web page.
Example:
html
<!DOCTYPE html><html> <head> <title>HTML video poster Attribute</title></head> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <h3>HTML video poster Attribute</h3> <video width="400" height="200" controls poster="https://media.geeksforgeeks.org/wp-content/uploads/20190627130930/a218.png"> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4" type="video/mp4"> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg" type="video/ogg"> </video> </center></body> </html>
Output:
Note: Always specify the width and the height of the video else web page will be confused that how much space that video will be required due to that reason web page become slow down.
Supported Browsers: The browser supported by HTML <video> poster Attribute are listed below:
Google Chrome 3.0 and above
Edge 12.0 and above
Firefox 3.5 and above
Internet Explorer 9.0 and above
Opera 10.5 and above
Safari 3.1 and above
Akanksha_Rai
satyamm09
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to update Node.js and NPM to next version ?
REST API (Introduction)
CSS to put icon inside an input element in a form
Types of CSS (Cascading Style Sheet)
HTTP headers | Content-Type
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n16 Jun, 2022"
},
{
"code": null,
"e": 236,
"s": 28,
"text": "The HTML <video> poster Attribute is used to display the image while video downloading or when user click the play button. If this image not set then it will take the first frame of video as a poster image. "
},
{
"code": null,
"e": 244,
"s": 236,
"text": "Syntax:"
},
{
"code": null,
"e": 265,
"s": 244,
"text": "<video poster=\"URL\">"
},
{
"code": null,
"e": 412,
"s": 265,
"text": "Attribute Values: It contains a single value URL which specifies the link of source image. There are two types of URL link which are listed below:"
},
{
"code": null,
"e": 456,
"s": 412,
"text": "Absolute URL: It points to another webpage."
},
{
"code": null,
"e": 517,
"s": 456,
"text": "Relative URL: It points to other files of the same web page."
},
{
"code": null,
"e": 527,
"s": 517,
"text": "Example: "
},
{
"code": null,
"e": 532,
"s": 527,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML video poster Attribute</title></head> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>HTML video poster Attribute</h3> <video width=\"400\" height=\"200\" controls poster=\"https://media.geeksforgeeks.org/wp-content/uploads/20190627130930/a218.png\"> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4\" type=\"video/mp4\"> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg\" type=\"video/ogg\"> </video> </center></body> </html>",
"e": 1277,
"s": 532,
"text": null
},
{
"code": null,
"e": 1285,
"s": 1277,
"text": "Output:"
},
{
"code": null,
"e": 1471,
"s": 1287,
"text": "Note: Always specify the width and the height of the video else web page will be confused that how much space that video will be required due to that reason web page become slow down."
},
{
"code": null,
"e": 1564,
"s": 1471,
"text": "Supported Browsers: The browser supported by HTML <video> poster Attribute are listed below:"
},
{
"code": null,
"e": 1592,
"s": 1564,
"text": "Google Chrome 3.0 and above"
},
{
"code": null,
"e": 1612,
"s": 1592,
"text": "Edge 12.0 and above"
},
{
"code": null,
"e": 1634,
"s": 1612,
"text": "Firefox 3.5 and above"
},
{
"code": null,
"e": 1666,
"s": 1634,
"text": "Internet Explorer 9.0 and above"
},
{
"code": null,
"e": 1687,
"s": 1666,
"text": "Opera 10.5 and above"
},
{
"code": null,
"e": 1708,
"s": 1687,
"text": "Safari 3.1 and above"
},
{
"code": null,
"e": 1721,
"s": 1708,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 1731,
"s": 1721,
"text": "satyamm09"
},
{
"code": null,
"e": 1747,
"s": 1731,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1752,
"s": 1747,
"text": "HTML"
},
{
"code": null,
"e": 1769,
"s": 1752,
"text": "Web Technologies"
},
{
"code": null,
"e": 1774,
"s": 1769,
"text": "HTML"
},
{
"code": null,
"e": 1872,
"s": 1774,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1920,
"s": 1872,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 1944,
"s": 1920,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1994,
"s": 1944,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 2031,
"s": 1994,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 2059,
"s": 2031,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 2092,
"s": 2059,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2153,
"s": 2092,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2196,
"s": 2153,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2268,
"s": 2196,
"text": "Differences between Functional Components and Class Components in React"
}
] |
turtle.hideturtle() function in Python
|
17 Jul, 2020
The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support.
This method is used to make the turtle invisible. It’s a good idea to do this while you’re in the middle of a complicated drawing because hiding the turtle speeds up the drawing observably. This method does not require any argument.
Syntax:
turtle.hideturtle() or turtle.ht()
Below is the implementation of the above method with some examples :
Example 1 :
Python3
# importing packageimport turtle # forward turtle by 100turtle.forward(100) # hide the turtleturtle.hideturtle()
Output :
Example 2 :
Python3
# importing packageimport turtle # draw a circleturtle.circle(80) # hide the turtleturtle.hideturtle()
Output :
Without hiding the turtle
Hiding the turtle
Python-turtle
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": 28,
"s": 0,
"text": "\n17 Jul, 2020"
},
{
"code": null,
"e": 245,
"s": 28,
"text": "The turtle module provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses Tkinter for the underlying graphics, it needs a version of Python installed with Tk support."
},
{
"code": null,
"e": 478,
"s": 245,
"text": "This method is used to make the turtle invisible. It’s a good idea to do this while you’re in the middle of a complicated drawing because hiding the turtle speeds up the drawing observably. This method does not require any argument."
},
{
"code": null,
"e": 486,
"s": 478,
"text": "Syntax:"
},
{
"code": null,
"e": 523,
"s": 486,
"text": "turtle.hideturtle() or turtle.ht()\n\n"
},
{
"code": null,
"e": 592,
"s": 523,
"text": "Below is the implementation of the above method with some examples :"
},
{
"code": null,
"e": 604,
"s": 592,
"text": "Example 1 :"
},
{
"code": null,
"e": 612,
"s": 604,
"text": "Python3"
},
{
"code": "# importing packageimport turtle # forward turtle by 100turtle.forward(100) # hide the turtleturtle.hideturtle()",
"e": 727,
"s": 612,
"text": null
},
{
"code": null,
"e": 736,
"s": 727,
"text": "Output :"
},
{
"code": null,
"e": 748,
"s": 736,
"text": "Example 2 :"
},
{
"code": null,
"e": 756,
"s": 748,
"text": "Python3"
},
{
"code": "# importing packageimport turtle # draw a circleturtle.circle(80) # hide the turtleturtle.hideturtle()",
"e": 861,
"s": 756,
"text": null
},
{
"code": null,
"e": 870,
"s": 861,
"text": "Output :"
},
{
"code": null,
"e": 896,
"s": 870,
"text": "Without hiding the turtle"
},
{
"code": null,
"e": 914,
"s": 896,
"text": "Hiding the turtle"
},
{
"code": null,
"e": 928,
"s": 914,
"text": "Python-turtle"
},
{
"code": null,
"e": 935,
"s": 928,
"text": "Python"
},
{
"code": null,
"e": 1033,
"s": 935,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1065,
"s": 1033,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1092,
"s": 1065,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 1113,
"s": 1092,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 1136,
"s": 1113,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 1192,
"s": 1136,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 1223,
"s": 1192,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 1265,
"s": 1223,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1307,
"s": 1265,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 1346,
"s": 1307,
"text": "Python | Get unique values from a list"
}
] |
Python – tensorflow.concat()
|
26 Jun, 2020
TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks.
concat() is used to concatenate tensors along one dimension.
Syntax: tensorflow.concat( values, axis, name )
Parameter:
values: It is a tensor or list of tensor.
axis: It is 0-D tensor which represents dimension to concatenate.
name(optional): It defines the name for the operation.
Returns: It returns the concatenated Tensor.
Example 1:
Python3
# Importing the libraryimport tensorflow as tf # Initializing the input tensort1 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]t2 = [[[7, 4], [8, 4]], [[2, 10], [15, 11]]] # Printing the input tensorprint('t1: ', t1)print('t2: ', t2) # Calculating resultres = tf.concat([t1, t2], 2) # Printing the resultprint('Result: ', res)
Output:
t1: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
t2: [[[7, 4], [8, 4]], [[2, 10], [15, 11]]]
Result: tf.Tensor(
[[[ 1 2 7 4]
[ 3 4 8 4]]
[[ 5 6 2 10]
[ 7 8 15 11]]], shape=(2, 2, 4), dtype=int32)
Example 2:
Python3
# Importing the libraryimport tensorflow as tf # Initializing the input tensort1 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]t2 = [[[7, 4], [8, 4]], [[2, 10], [15, 11]]] # Printing the input tensorprint('t1: ', t1)print('t2: ', t2) # Calculating resultres = tf.concat([t1, t2], 1) # Printing the resultprint('Result: ', res)
Output:
t1: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
t2: [[[7, 4], [8, 4]], [[2, 10], [15, 11]]]
Result: tf.Tensor(
[[[ 1 2]
[ 3 4]
[ 7 4]
[ 8 4]]
[[ 5 6]
[ 7 8]
[ 2 10]
[15 11]]], shape=(2, 4, 2), dtype=int32)
Python-Tensorflow
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
How to Install PIP on Windows ?
Python String | replace()
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Iterate over a list in Python
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jun, 2020"
},
{
"code": null,
"e": 159,
"s": 28,
"text": "TensorFlow is open-source Python library designed by Google to develop Machine Learning models and deep learning neural networks."
},
{
"code": null,
"e": 220,
"s": 159,
"text": "concat() is used to concatenate tensors along one dimension."
},
{
"code": null,
"e": 268,
"s": 220,
"text": "Syntax: tensorflow.concat( values, axis, name )"
},
{
"code": null,
"e": 279,
"s": 268,
"text": "Parameter:"
},
{
"code": null,
"e": 321,
"s": 279,
"text": "values: It is a tensor or list of tensor."
},
{
"code": null,
"e": 387,
"s": 321,
"text": "axis: It is 0-D tensor which represents dimension to concatenate."
},
{
"code": null,
"e": 442,
"s": 387,
"text": "name(optional): It defines the name for the operation."
},
{
"code": null,
"e": 487,
"s": 442,
"text": "Returns: It returns the concatenated Tensor."
},
{
"code": null,
"e": 498,
"s": 487,
"text": "Example 1:"
},
{
"code": null,
"e": 506,
"s": 498,
"text": "Python3"
},
{
"code": "# Importing the libraryimport tensorflow as tf # Initializing the input tensort1 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]t2 = [[[7, 4], [8, 4]], [[2, 10], [15, 11]]] # Printing the input tensorprint('t1: ', t1)print('t2: ', t2) # Calculating resultres = tf.concat([t1, t2], 2) # Printing the resultprint('Result: ', res)",
"e": 831,
"s": 506,
"text": null
},
{
"code": null,
"e": 839,
"s": 831,
"text": "Output:"
},
{
"code": null,
"e": 1053,
"s": 839,
"text": "t1: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\nt2: [[[7, 4], [8, 4]], [[2, 10], [15, 11]]]\nResult: tf.Tensor(\n[[[ 1 2 7 4]\n [ 3 4 8 4]]\n\n [[ 5 6 2 10]\n [ 7 8 15 11]]], shape=(2, 2, 4), dtype=int32)\n \n \n\n"
},
{
"code": null,
"e": 1064,
"s": 1053,
"text": "Example 2:"
},
{
"code": null,
"e": 1072,
"s": 1064,
"text": "Python3"
},
{
"code": "# Importing the libraryimport tensorflow as tf # Initializing the input tensort1 = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]t2 = [[[7, 4], [8, 4]], [[2, 10], [15, 11]]] # Printing the input tensorprint('t1: ', t1)print('t2: ', t2) # Calculating resultres = tf.concat([t1, t2], 1) # Printing the resultprint('Result: ', res)",
"e": 1397,
"s": 1072,
"text": null
},
{
"code": null,
"e": 1405,
"s": 1397,
"text": "Output:"
},
{
"code": null,
"e": 1630,
"s": 1405,
"text": "t1: [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]\nt2: [[[7, 4], [8, 4]], [[2, 10], [15, 11]]]\nResult: tf.Tensor(\n[[[ 1 2]\n [ 3 4]\n [ 7 4]\n [ 8 4]]\n\n [[ 5 6]\n [ 7 8]\n [ 2 10]\n [15 11]]], shape=(2, 4, 2), dtype=int32)\n\n\n"
},
{
"code": null,
"e": 1648,
"s": 1630,
"text": "Python-Tensorflow"
},
{
"code": null,
"e": 1655,
"s": 1648,
"text": "Python"
},
{
"code": null,
"e": 1753,
"s": 1655,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1771,
"s": 1753,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1813,
"s": 1771,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1835,
"s": 1813,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1870,
"s": 1835,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1902,
"s": 1870,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1928,
"s": 1902,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1957,
"s": 1928,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1984,
"s": 1957,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2005,
"s": 1984,
"text": "Python OOPs Concepts"
}
] |
TypeScript | String concat() Method
|
18 Jun, 2020
The concat() is an inbuilt function in TypeScript which is used to add two or more strings and returns a new single string.
Syntax:
string.concat(string2, string3[, ..., stringN]);
Parameter: This method accept a single parameter as mentioned above and described below.
string2...stringN: This parameter holds the strings which will be concatenate.
Return Value: This method returns the concatenated string.
Below example illustrate the String concat() method in TypeScriptJS:
Example 1:
JavaScript
<script> // Original strings var str1 = new String('GeeksforGeeks'); var str2 = new String(' - Best Platform'); // Combines the text of two strings and // returns a new string. console.log("Concatenated String : " + str1.concat(str2.toString()));</script>
Output:
Concatenated String : GeeksforGeeks - Best Platform
Example 2:
JavaScript
<script> // Original strings var str1 = new String('Geeks'); var str2 = new String('for'); var str3 = new String('Geeks'); // Combines the text of two strings and // returns a new string. var str = str2.concat(str3.toString()) str = str1.concat(str.toString()) console.log("Concatenated String : " + str);</script>
Output:
Concatenated String : GeeksforGeeks
TypeScript
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
How to append HTML code to a div using JavaScript ?
Difference Between PUT and PATCH Request
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Jun, 2020"
},
{
"code": null,
"e": 153,
"s": 28,
"text": "The concat() is an inbuilt function in TypeScript which is used to add two or more strings and returns a new single string. "
},
{
"code": null,
"e": 161,
"s": 153,
"text": "Syntax:"
},
{
"code": null,
"e": 211,
"s": 161,
"text": "string.concat(string2, string3[, ..., stringN]); "
},
{
"code": null,
"e": 300,
"s": 211,
"text": "Parameter: This method accept a single parameter as mentioned above and described below."
},
{
"code": null,
"e": 379,
"s": 300,
"text": "string2...stringN: This parameter holds the strings which will be concatenate."
},
{
"code": null,
"e": 438,
"s": 379,
"text": "Return Value: This method returns the concatenated string."
},
{
"code": null,
"e": 508,
"s": 438,
"text": "Below example illustrate the String concat() method in TypeScriptJS:"
},
{
"code": null,
"e": 520,
"s": 508,
"text": "Example 1: "
},
{
"code": null,
"e": 531,
"s": 520,
"text": "JavaScript"
},
{
"code": "<script> // Original strings var str1 = new String('GeeksforGeeks'); var str2 = new String(' - Best Platform'); // Combines the text of two strings and // returns a new string. console.log(\"Concatenated String : \" + str1.concat(str2.toString()));</script>",
"e": 822,
"s": 531,
"text": null
},
{
"code": null,
"e": 831,
"s": 822,
"text": "Output: "
},
{
"code": null,
"e": 884,
"s": 831,
"text": "Concatenated String : GeeksforGeeks - Best Platform\n"
},
{
"code": null,
"e": 896,
"s": 884,
"text": "Example 2: "
},
{
"code": null,
"e": 907,
"s": 896,
"text": "JavaScript"
},
{
"code": "<script> // Original strings var str1 = new String('Geeks'); var str2 = new String('for'); var str3 = new String('Geeks'); // Combines the text of two strings and // returns a new string. var str = str2.concat(str3.toString()) str = str1.concat(str.toString()) console.log(\"Concatenated String : \" + str);</script>",
"e": 1255,
"s": 907,
"text": null
},
{
"code": null,
"e": 1264,
"s": 1255,
"text": "Output: "
},
{
"code": null,
"e": 1300,
"s": 1264,
"text": "Concatenated String : GeeksforGeeks"
},
{
"code": null,
"e": 1311,
"s": 1300,
"text": "TypeScript"
},
{
"code": null,
"e": 1322,
"s": 1311,
"text": "JavaScript"
},
{
"code": null,
"e": 1339,
"s": 1322,
"text": "Web Technologies"
},
{
"code": null,
"e": 1437,
"s": 1339,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1498,
"s": 1437,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1570,
"s": 1498,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 1610,
"s": 1570,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 1662,
"s": 1610,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 1703,
"s": 1662,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 1765,
"s": 1703,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 1798,
"s": 1765,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1859,
"s": 1798,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1909,
"s": 1859,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to Rotate X-Axis Tick Label Text in Matplotlib?
|
24 Jan, 2021
Matplotlib is an amazing and one of the most widely used data visualization library in Python for plots of arrays. It is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It is much popular because of its customization options as we can tweak about any element from its hierarchy of objects.
To rotate X-axis labels, there are various methods provided by matplotlib i.e. change it on the Figure-level or by changing it on an Axes-level or individually by using built-in functions. Some methods are listed below :
Let’s create a simple line plot which we will modify in the further examples:
Python3
# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetx = np.arange(0, np.pi*2, 0.05)y = np.sin(x**2) # Creating plotplt.plot(x, y) # Setting titleplt.title('Simple Example') # Show plotplt.show()
Output :
Example 1: In this example, we will rotate X-axis labels on Figure-level using plt.xticks().
Syntax: matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs)
Parameters: This method accept the following parameters that are described below:
ticks: This parameter is the list of xtick locations. and an optional parameter. If an empty list is passed as an argument then it will removes all xticks
labels: This parameter contains labels to place at the given ticks locations. And it is an optional parameter.
**kwargs: This parameter is Text properties that is used to control the appearance of the labels.
Python3
# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetx = np.arange(0, np.pi*2, 0.05)y = np.sin(x**2) # Creating plotplt.plot(x, y) # Rotating X-axis labelsplt.xticks(rotation = 25) # Setting titleplt.title('Rotating using plt.xticks()') # Show plotplt.show()
Output :
Example 2: In this example, we will rotate X-axis labels on Axes-level using tick.set_rotation().
Syntax: Axes.get_xticks(self, minor=False)
Parameters: This method accepts the following parameters.
minor : This parameter is used whether set major ticks or to set minor ticks
Return value: This method returns a list of Text values.
Python3
# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetx = np.arange(0, np.pi*2, 0.05)y = np.sin(x**2) # Creating Figurefig, ax = plt.subplots() # Creating plotax.plot(x, y) # Rotating X-axis labelsax.set_xticklabels(ax.get_xticks(), rotation = 50) # Setting titleplt.title('Rotating using tick.set_rotation()') # Show plotplt.show()
Output :
Example 3: In this example, we will rotate X-axis labels individually by using built-in ax.set_xticklabels() function.
Python3
# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetx = np.arange(0, np.pi*2, 0.05)y = np.sin(x**2) # Creating Figurefig, ax = plt.subplots() # Creating plotax.plot(x, y) # Rotating X-axis labelsfor tick in ax.get_xticklabels(): tick.set_rotation(75) # Setting titleplt.title('Rotating using ax.set_xticklabels()') # Show plotplt.show()
Output :
Example 4: In this example, we will rotate X-axis labels individually by using built-in ax.xtick_params() function.
Syntax: matplotlib.pyplot.tick_params(axis=’both’, **kwargs)
Python3
# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetx = np.arange(0, np.pi*2, 0.05)y = np.sin(x**2) # Creating Figurefig, ax = plt.subplots() # Creating plotax.plot(x, y) # Rotating X-axis labelsax.tick_params(axis='x', labelrotation = 100) # Setting titleplt.title('Rotating using ax.xtick_params()') # Show plotplt.show()
Output :
Picked
Python-matplotlib
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to iterate through Excel rows in Python?
Deque in Python
Defaultdict in Python
Queue in Python
Rotate axis tick labels in Seaborn and Matplotlib
Check if element exists in list in Python
Python Classes and Objects
Bar Plot in Matplotlib
Python OOPs Concepts
How To Convert Python Dictionary To JSON?
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 387,
"s": 28,
"text": "Matplotlib is an amazing and one of the most widely used data visualization library in Python for plots of arrays. It is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. It is much popular because of its customization options as we can tweak about any element from its hierarchy of objects."
},
{
"code": null,
"e": 608,
"s": 387,
"text": "To rotate X-axis labels, there are various methods provided by matplotlib i.e. change it on the Figure-level or by changing it on an Axes-level or individually by using built-in functions. Some methods are listed below :"
},
{
"code": null,
"e": 686,
"s": 608,
"text": "Let’s create a simple line plot which we will modify in the further examples:"
},
{
"code": null,
"e": 694,
"s": 686,
"text": "Python3"
},
{
"code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetx = np.arange(0, np.pi*2, 0.05)y = np.sin(x**2) # Creating plotplt.plot(x, y) # Setting titleplt.title('Simple Example') # Show plotplt.show()",
"e": 927,
"s": 694,
"text": null
},
{
"code": null,
"e": 936,
"s": 927,
"text": "Output :"
},
{
"code": null,
"e": 1029,
"s": 936,
"text": "Example 1: In this example, we will rotate X-axis labels on Figure-level using plt.xticks()."
},
{
"code": null,
"e": 1097,
"s": 1029,
"text": "Syntax: matplotlib.pyplot.xticks(ticks=None, labels=None, **kwargs)"
},
{
"code": null,
"e": 1179,
"s": 1097,
"text": "Parameters: This method accept the following parameters that are described below:"
},
{
"code": null,
"e": 1334,
"s": 1179,
"text": "ticks: This parameter is the list of xtick locations. and an optional parameter. If an empty list is passed as an argument then it will removes all xticks"
},
{
"code": null,
"e": 1445,
"s": 1334,
"text": "labels: This parameter contains labels to place at the given ticks locations. And it is an optional parameter."
},
{
"code": null,
"e": 1543,
"s": 1445,
"text": "**kwargs: This parameter is Text properties that is used to control the appearance of the labels."
},
{
"code": null,
"e": 1551,
"s": 1543,
"text": "Python3"
},
{
"code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetx = np.arange(0, np.pi*2, 0.05)y = np.sin(x**2) # Creating plotplt.plot(x, y) # Rotating X-axis labelsplt.xticks(rotation = 25) # Setting titleplt.title('Rotating using plt.xticks()') # Show plotplt.show()",
"e": 1848,
"s": 1551,
"text": null
},
{
"code": null,
"e": 1857,
"s": 1848,
"text": "Output :"
},
{
"code": null,
"e": 1955,
"s": 1857,
"text": "Example 2: In this example, we will rotate X-axis labels on Axes-level using tick.set_rotation()."
},
{
"code": null,
"e": 1998,
"s": 1955,
"text": "Syntax: Axes.get_xticks(self, minor=False)"
},
{
"code": null,
"e": 2056,
"s": 1998,
"text": "Parameters: This method accepts the following parameters."
},
{
"code": null,
"e": 2133,
"s": 2056,
"text": "minor : This parameter is used whether set major ticks or to set minor ticks"
},
{
"code": null,
"e": 2190,
"s": 2133,
"text": "Return value: This method returns a list of Text values."
},
{
"code": null,
"e": 2198,
"s": 2190,
"text": "Python3"
},
{
"code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetx = np.arange(0, np.pi*2, 0.05)y = np.sin(x**2) # Creating Figurefig, ax = plt.subplots() # Creating plotax.plot(x, y) # Rotating X-axis labelsax.set_xticklabels(ax.get_xticks(), rotation = 50) # Setting titleplt.title('Rotating using tick.set_rotation()') # Show plotplt.show()",
"e": 2570,
"s": 2198,
"text": null
},
{
"code": null,
"e": 2579,
"s": 2570,
"text": "Output :"
},
{
"code": null,
"e": 2698,
"s": 2579,
"text": "Example 3: In this example, we will rotate X-axis labels individually by using built-in ax.set_xticklabels() function."
},
{
"code": null,
"e": 2706,
"s": 2698,
"text": "Python3"
},
{
"code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetx = np.arange(0, np.pi*2, 0.05)y = np.sin(x**2) # Creating Figurefig, ax = plt.subplots() # Creating plotax.plot(x, y) # Rotating X-axis labelsfor tick in ax.get_xticklabels(): tick.set_rotation(75) # Setting titleplt.title('Rotating using ax.set_xticklabels()') # Show plotplt.show()",
"e": 3087,
"s": 2706,
"text": null
},
{
"code": null,
"e": 3096,
"s": 3087,
"text": "Output :"
},
{
"code": null,
"e": 3212,
"s": 3096,
"text": "Example 4: In this example, we will rotate X-axis labels individually by using built-in ax.xtick_params() function."
},
{
"code": null,
"e": 3273,
"s": 3212,
"text": "Syntax: matplotlib.pyplot.tick_params(axis=’both’, **kwargs)"
},
{
"code": null,
"e": 3281,
"s": 3273,
"text": "Python3"
},
{
"code": "# Import librariesimport matplotlib.pyplot as pltimport numpy as np # Creating datasetx = np.arange(0, np.pi*2, 0.05)y = np.sin(x**2) # Creating Figurefig, ax = plt.subplots() # Creating plotax.plot(x, y) # Rotating X-axis labelsax.tick_params(axis='x', labelrotation = 100) # Setting titleplt.title('Rotating using ax.xtick_params()') # Show plotplt.show()",
"e": 3646,
"s": 3281,
"text": null
},
{
"code": null,
"e": 3655,
"s": 3646,
"text": "Output :"
},
{
"code": null,
"e": 3662,
"s": 3655,
"text": "Picked"
},
{
"code": null,
"e": 3680,
"s": 3662,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 3704,
"s": 3680,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3711,
"s": 3704,
"text": "Python"
},
{
"code": null,
"e": 3730,
"s": 3711,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3828,
"s": 3730,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3873,
"s": 3828,
"text": "How to iterate through Excel rows in Python?"
},
{
"code": null,
"e": 3889,
"s": 3873,
"text": "Deque in Python"
},
{
"code": null,
"e": 3911,
"s": 3889,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 3927,
"s": 3911,
"text": "Queue in Python"
},
{
"code": null,
"e": 3977,
"s": 3927,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 4019,
"s": 3977,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4046,
"s": 4019,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4069,
"s": 4046,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 4090,
"s": 4069,
"text": "Python OOPs Concepts"
}
] |
Sorting Strings using Bubble Sort
|
21 Jan, 2022
Given an array of strings arr[]. Sort given strings using Bubble Sort and display the sorted array.
In Bubble Sort, the two successive strings arr[i] and arr[i+1] are exchanged whenever arr[i]> arr[i+1]. The larger values sink to the bottom and hence called sinking sort. At the end of each pass, smaller values gradually “bubble” their way upward to the top and hence called bubble sort.
After all the passes, we get all the strings in sorted order. Complexity of the above algorithm will be O(N2).
Let us look at the code snippet:
C++
Java
C#
// C++ implementation #include<bits/stdc++.h>using namespace std;#define MAX 100 void sortStrings(char arr[][MAX], int n){ char temp[MAX]; // Sorting strings using bubble sort for (int i=0; i<n-1; i++) { for (int j=0; j<n-1-i; j++) { if (strcmp(arr[j], arr[j+1]) > 0) { strcpy(temp, arr[j]); strcpy(arr[j], arr[j+1]); strcpy(arr[j+1], temp); } } }} int main(){ char arr[][MAX] = {"GeeksforGeeks","Quiz","Practice","Gblogs","Coding"}; int n = sizeof(arr)/sizeof(arr[0]); sortStrings(arr, n); printf("Strings in sorted order are : "); for (int i=0; i<n; i++) printf("\n String %d is %s", i+1, arr[i]); return 0;}
// Java implementationclass GFG{ static int MAX = 100; public static void sortStrings(String[] arr, int n) { String temp; // Sorting strings using bubble sort for (int j = 0; j < n - 1; j++) { for (int i = j + 1; i < n; i++) { if (arr[j].compareTo(arr[i]) > 0) { temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } } } // Driver code public static void main(String[] args) { String[] arr = { "GeeksforGeeks", "Quiz", "Practice", "Gblogs", "Coding" }; int n = arr.length; sortStrings(arr, n); System.out.println("Strings in sorted order are : "); for (int i = 0; i < n; i++) System.out.println("String " + (i + 1) + " is " + arr[i]); }} // This code is contributed by// sanjeev2552
// C# implementationusing System; class GFG{ static int MAX = 100; public static void sortStrings(String[] arr, int n) { String temp; // Sorting strings using bubble sort for (int j = 0; j < n - 1; j++) { for (int i = j + 1; i < n; i++) { if (arr[j].CompareTo(arr[i]) > 0) { temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } } } // Driver code public static void Main(String[] args) { String[] arr = {"GeeksforGeeks", "Quiz", "Practice", "Gblogs", "Coding"}; int n = arr.Length; sortStrings(arr, n); Console.WriteLine("Strings in sorted order are : "); for (int i = 0; i < n; i++) Console.WriteLine("String " + (i + 1) + " is " + arr[i]); }} // This code is contributed by Princi Singh
Output:
Strings in sorted order are :
String 1 is Coding
String 2 is Gblogs
String 3 is GeeksforGeeks
String 4 is Practice
String 5 is Quiz
This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. 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
sanjeev2552
princi singh
defaultacc
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Sort a nearly sorted (or K sorted) array
Longest Common Prefix using Sorting
Segregate 0s and 1s in an array
Find whether an array is subset of another array
Sorting in Java
Find all triplets with zero sum
Quickselect Algorithm
Find a pair with the given difference
Quick Sort vs Merge Sort
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Jan, 2022"
},
{
"code": null,
"e": 154,
"s": 54,
"text": "Given an array of strings arr[]. Sort given strings using Bubble Sort and display the sorted array."
},
{
"code": null,
"e": 443,
"s": 154,
"text": "In Bubble Sort, the two successive strings arr[i] and arr[i+1] are exchanged whenever arr[i]> arr[i+1]. The larger values sink to the bottom and hence called sinking sort. At the end of each pass, smaller values gradually “bubble” their way upward to the top and hence called bubble sort."
},
{
"code": null,
"e": 557,
"s": 446,
"text": "After all the passes, we get all the strings in sorted order. Complexity of the above algorithm will be O(N2)."
},
{
"code": null,
"e": 592,
"s": 559,
"text": "Let us look at the code snippet:"
},
{
"code": null,
"e": 598,
"s": 594,
"text": "C++"
},
{
"code": null,
"e": 603,
"s": 598,
"text": "Java"
},
{
"code": null,
"e": 606,
"s": 603,
"text": "C#"
},
{
"code": "// C++ implementation #include<bits/stdc++.h>using namespace std;#define MAX 100 void sortStrings(char arr[][MAX], int n){ char temp[MAX]; // Sorting strings using bubble sort for (int i=0; i<n-1; i++) { for (int j=0; j<n-1-i; j++) { if (strcmp(arr[j], arr[j+1]) > 0) { strcpy(temp, arr[j]); strcpy(arr[j], arr[j+1]); strcpy(arr[j+1], temp); } } }} int main(){ char arr[][MAX] = {\"GeeksforGeeks\",\"Quiz\",\"Practice\",\"Gblogs\",\"Coding\"}; int n = sizeof(arr)/sizeof(arr[0]); sortStrings(arr, n); printf(\"Strings in sorted order are : \"); for (int i=0; i<n; i++) printf(\"\\n String %d is %s\", i+1, arr[i]); return 0;}",
"e": 1359,
"s": 606,
"text": null
},
{
"code": "// Java implementationclass GFG{ static int MAX = 100; public static void sortStrings(String[] arr, int n) { String temp; // Sorting strings using bubble sort for (int j = 0; j < n - 1; j++) { for (int i = j + 1; i < n; i++) { if (arr[j].compareTo(arr[i]) > 0) { temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } } } // Driver code public static void main(String[] args) { String[] arr = { \"GeeksforGeeks\", \"Quiz\", \"Practice\", \"Gblogs\", \"Coding\" }; int n = arr.length; sortStrings(arr, n); System.out.println(\"Strings in sorted order are : \"); for (int i = 0; i < n; i++) System.out.println(\"String \" + (i + 1) + \" is \" + arr[i]); }} // This code is contributed by// sanjeev2552",
"e": 2306,
"s": 1359,
"text": null
},
{
"code": "// C# implementationusing System; class GFG{ static int MAX = 100; public static void sortStrings(String[] arr, int n) { String temp; // Sorting strings using bubble sort for (int j = 0; j < n - 1; j++) { for (int i = j + 1; i < n; i++) { if (arr[j].CompareTo(arr[i]) > 0) { temp = arr[j]; arr[j] = arr[i]; arr[i] = temp; } } } } // Driver code public static void Main(String[] args) { String[] arr = {\"GeeksforGeeks\", \"Quiz\", \"Practice\", \"Gblogs\", \"Coding\"}; int n = arr.Length; sortStrings(arr, n); Console.WriteLine(\"Strings in sorted order are : \"); for (int i = 0; i < n; i++) Console.WriteLine(\"String \" + (i + 1) + \" is \" + arr[i]); }} // This code is contributed by Princi Singh",
"e": 3326,
"s": 2306,
"text": null
},
{
"code": null,
"e": 3336,
"s": 3326,
"text": "Output: "
},
{
"code": null,
"e": 3479,
"s": 3336,
"text": "Strings in sorted order are : \n\n String 1 is Coding\n\n String 2 is Gblogs\n\n String 3 is GeeksforGeeks\n\n String 4 is Practice\n\n String 5 is Quiz"
},
{
"code": null,
"e": 3871,
"s": 3479,
"text": "This article is contributed by Rahul Agrawal. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to review-team@geeksforgeeks.org. 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": 3883,
"s": 3871,
"text": "sanjeev2552"
},
{
"code": null,
"e": 3896,
"s": 3883,
"text": "princi singh"
},
{
"code": null,
"e": 3907,
"s": 3896,
"text": "defaultacc"
},
{
"code": null,
"e": 3915,
"s": 3907,
"text": "Sorting"
},
{
"code": null,
"e": 3923,
"s": 3915,
"text": "Sorting"
},
{
"code": null,
"e": 4021,
"s": 3923,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4052,
"s": 4021,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 4093,
"s": 4052,
"text": "Sort a nearly sorted (or K sorted) array"
},
{
"code": null,
"e": 4129,
"s": 4093,
"text": "Longest Common Prefix using Sorting"
},
{
"code": null,
"e": 4161,
"s": 4129,
"text": "Segregate 0s and 1s in an array"
},
{
"code": null,
"e": 4210,
"s": 4161,
"text": "Find whether an array is subset of another array"
},
{
"code": null,
"e": 4226,
"s": 4210,
"text": "Sorting in Java"
},
{
"code": null,
"e": 4258,
"s": 4226,
"text": "Find all triplets with zero sum"
},
{
"code": null,
"e": 4280,
"s": 4258,
"text": "Quickselect Algorithm"
},
{
"code": null,
"e": 4318,
"s": 4280,
"text": "Find a pair with the given difference"
}
] |
Swap all odd and even bits
|
14 Feb, 2022
Given an unsigned integer, swap all odd bits with even bits. For example, if the given number is 23 (00010111), it should be converted to 43 (00101011). Every even position bit is swapped with adjacent bit on right side (even position bits are highlighted in binary representation of 23), and every odd position bit is swapped with adjacent on left side.
It is very hard to remember 0xAAAAAAAA as a number of 32 bit which is set at all even bits and 0x55555555 as a number of 32 bit which is set at all odd bits. So there is another solution for this. Here we need to perform operation in a brute force manner.
Find bit of i and i+1.To swap the bits subtract and add corresponding values.To remove bit at ith bit to i+1. we need to subtract i_bit<<i and add it at i+1 location for that we need to add i_bit<<(i+1).Similarly do for (i+1)th bit. Remove it from i+1 to i.
Find bit of i and i+1.
To swap the bits subtract and add corresponding values.
To remove bit at ith bit to i+1. we need to subtract i_bit<<i and add it at i+1 location for that we need to add i_bit<<(i+1).
Similarly do for (i+1)th bit. Remove it from i+1 to i.
C++
Java
Python3
C#
Javascript
// C++ program to swap even and// odd bits of a given number#include <bits/stdc++.h>using namespace std; // Function to swap even// and odd bitsunsigned int swapBits(unsigned int x){ for(int i=0; i<32; i+=2){ int i_bit = ( x >> i ) & 1; // find i th bit int i_1_bit = (x >> ( i+1 )) & 1; // find i+1 th bit x = x - ( i_bit << i) // remove i_bit - ( i_1_bit << ( i+1 ) ) // remove i+1 th bit + ( i_bit << ( i+1 ) ) // put i_bit at i+1 location + ( i_1_bit << i ); // put i+1 bit at i location } return x;} // Driver codeint main(){ unsigned int x =23; // 00010111 // Output is 43 (00101011) cout<<swapBits(x); return 0;} // This code is contributed by Amandeep Gupta
// Java program to swap even and// odd bits of a given numberimport java.io.*; class GFG { // Function to swap even // and odd bits static int swapBits(int x) { for (int i = 0; i < 32; i += 2) { int i_bit = (x >> i) & 1; // find i th bit int i_1_bit = (x >> (i + 1)) & 1; // find i+1 th bit x = x - (i_bit << i) // remove i_bit - (i_1_bit << (i + 1)) // remove i+1 th bit + (i_bit << (i + 1)) // put i_bit at i+1 location + (i_1_bit << i); // put i+1 bit at i location } return x; } // Driver code public static void main(String[] args) { int x = 23; // 00010111 // Output is 43 (00101011) System.out.print(swapBits(x)); }} // This code is contributed by subham348.
# Python program to swap even and# odd bits of a given number # Function to swap even# and odd bitsdef swapBits(x): # Get all even bits of x even_bits = x & 0xAAAAAAAA # Get all odd bits of x odd_bits = x & 0x55555555 # Right shift even bits even_bits >>= 1 # Left shift odd bits odd_bits <<= 1 for i in range(0,32,2): i_bit = (x >> 1) & 1; # find i th bit i_1_bit = (x >> (i + 1)) & 1; # find i+1 th bit x = x - (i_bit << i) # remove i_bit - (i_1_bit << (i + 2)) # remove i+1 th bit + (i_bit << (i + 1)) # put i_bit at i+1 location + (i_1_bit << i); # put i+1 bit at i location # Combine even and odd bits return (even_bits | odd_bits) # Driver codeif __name__ == '__main__': x = 23; # 00010111 # Output is 43 (00101011) print(swapBits(x)); # This code is contributed by Rajput-Ji
// C# program to swap even and// odd bits of a given numberusing System; class GFG { // Function to swap even // and odd bits static int swapBits(int x) { for (int i = 0; i < 32; i += 2) { int i_bit = (x >> i) & 1; // find i th bit int i_1_bit = (x >> (i + 1)) & 1; // find i+1 th bit x = x - (i_bit << i) // remove i_bit - (i_1_bit << (i + 1)) // remove i+1 th bit + (i_bit << (i + 1)) // put i_bit at i+1 location + (i_1_bit << i); // put i+1 bit at i location } return x; } // Driver code public static void Main() { int x = 23; // 00010111 // Output is 43 (00101011) Console.Write(swapBits(x)); }} // This code is contributed by subham348.
<script>// JavaScript Program to implement// the above approach // Function to swap even// and odd bitsfunction swapBits( x){ for(let i = 0; i < 32; i += 2){ let i_bit = ( x >> i ) & 1; // find i th bit let i_1_bit = (x >> ( i+1 )) & 1; // find i+1 th bit x = x - ( i_bit << i) // remove i_bit - ( i_1_bit << ( i+1 ) ) // remove i+1 th bit + ( i_bit << ( i+1 ) ) // put i_bit at i+1 location + ( i_1_bit << i ); // put i+1 bit at i location } return x;} // Driver code let x =23; // 00010111 // Output is 43 (00101011) document.write(swapBits(x)); // This code is contributed by Potta Lokesh </script>
Output:
43
Time Complexity: O(constant)
Auxiliary Space: O(1)
If we take a closer look at the example, we can observe that we basically need to right shift (>>) all even bits (In the above example, even bits of 23 are highlighted) by 1 so that they become odd bits (highlighted in 43), and left shift (<<) all odd bits by 1 so that they become even bits. The following solution is based on this observation. The solution assumes that input number is stored using 32 bits.Let the input number be x 1) Get all even bits of x by doing bitwise and of x with 0xAAAAAAAA. The number 0xAAAAAAAA is a 32 bit number with all even bits set as 1 and all odd bits as 0. 2) Get all odd bits of x by doing bitwise and of x with 0x55555555. The number 0x55555555 is a 32 bit number with all odd bits set as 1 and all even bits as 0. 3) Right shift all even bits. 4) Left shift all odd bits. 5) Combine new even and odd bits and return.
C++
C
Java
Python 3
C#
PHP
Javascript
// C++ program to swap even and// odd bits of a given number#include <bits/stdc++.h>using namespace std; // Function to swap even// and odd bitsunsigned int swapBits(unsigned int x){ // Get all even bits of x unsigned int even_bits = x & 0xAAAAAAAA; // Get all odd bits of x unsigned int odd_bits = x & 0x55555555; even_bits >>= 1; // Right shift even bits odd_bits <<= 1; // Left shift odd bits return (even_bits | odd_bits); // Combine even and odd bits} // Driver codeint main(){ unsigned int x = 23; // 00010111 // Output is 43 (00101011) cout<<swapBits(x); return 0;} // This code is contributed by rathbhupendra
// C program to swap even and// odd bits of a given number#include <stdio.h> // Function to swap even// and odd bitsunsigned int swapBits(unsigned int x){ // Get all even bits of x unsigned int even_bits = x & 0xAAAAAAAA; // Get all odd bits of x unsigned int odd_bits = x & 0x55555555; even_bits >>= 1; // Right shift even bits odd_bits <<= 1; // Left shift odd bits return (even_bits | odd_bits); // Combine even and odd bits} // Driver program to test above functionint main(){ unsigned int x = 23; // 00010111 // Output is 43 (00101011) printf("%u ", swapBits(x)); return 0;}
// Java program to swap even// and odd bits of a given number class GFG{ // Function to swap even // and odd bits static int swapBits(int x) { // Get all even bits of x int even_bits = x & 0xAAAAAAAA; // Get all odd bits of x int odd_bits = x & 0x55555555; // Right shift even bits even_bits >>= 1; // Left shift even bits odd_bits <<= 1; // Combine even and odd bits return (even_bits | odd_bits); } // Driver program to test above function public static void main(String[] args) { int x = 23; // 00010111 // Output is 43 (00101011) System.out.println(swapBits(x)); }} // This code is contributed by Smitha Dinesh Semwal
# Python 3 program to swap even# and odd bits of a given number # Function for swapping even# and odd bitsdef swapBits(x) : # Get all even bits of x even_bits = x & 0xAAAAAAAA # Get all odd bits of x odd_bits = x & 0x55555555 # Right shift even bits even_bits >>= 1 # Left shift odd bits odd_bits <<= 1 # Combine even and odd bits return (even_bits | odd_bits) # Driver program# 00010111x = 23 # Output is 43 (00101011)print(swapBits(x)) # This code is contributed# by Nikita Tiwari.
// C# program to swap even and odd bits// of a given numberusing System; class GFG { // Function to swap even // and odd bits static long swapBits(int x) { // Get all even bits of x long even_bits = x & 0xAAAAAAAA; // Get all odd bits of x long odd_bits = x & 0x55555555; // Right shift even bits even_bits >>= 1; // Left shift even bits odd_bits <<= 1; // Combine even and odd bits return (even_bits | odd_bits); } // Driver program to test above function public static void Main() { int x = 23; // 00010111 // Output is 43 (00101011) Console.Write(swapBits(x)); }} // This code is contributed by Sam007.
<?php// PHP program to swap even and// odd bits of a given number // Function to swap even// and odd bitsfunction swapBits( $x){ // Get all even bits of x $even_bits = $x & 0xAAAAAAAA; // Get all odd bits of x $odd_bits = $x & 0x55555555; // Right shift even bits $even_bits >>= 1; // Left shift odd bits $odd_bits <<= 1; // Combine even and odd bits return ($even_bits | $odd_bits);} // Driver Code // 00010111$x = 23; // Output is 43 (00101011)echo swapBits($x); // This code is contributed by Ajit?>
<script>// java script program to swap even and// odd bits of a given number // Function to swap even// and odd bitsfunction swapBits( x){ // Get all even bits of x even_bits = x & 0xAAAAAAAA; // Get all odd bits of x odd_bits = x & 0x55555555; // Right shift even bits even_bits >>= 1; // Left shift odd bits odd_bits <<= 1; // Combine even and odd bits return (even_bits | odd_bits);} // Driver Code // 00010111let x = 23; // Output is 43 (00101011)document.write(swapBits(x)); // This code is contributed by sravan kumar </script>
Output:
43
Time Complexity: O(1)
Auxiliary Space: O(1)
Swap all odd and even bits | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersSwap all odd and even bits | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:32•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=GWLCF808oVI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
jit_t
rathbhupendra
sravankumar8128
indianamandeep2001
subham348
lokeshpotta20
Rajput-Ji
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 410,
"s": 54,
"text": "Given an unsigned integer, swap all odd bits with even bits. For example, if the given number is 23 (00010111), it should be converted to 43 (00101011). Every even position bit is swapped with adjacent bit on right side (even position bits are highlighted in binary representation of 23), and every odd position bit is swapped with adjacent on left side. "
},
{
"code": null,
"e": 669,
"s": 410,
"text": "It is very hard to remember 0xAAAAAAAA as a number of 32 bit which is set at all even bits and 0x55555555 as a number of 32 bit which is set at all odd bits. So there is another solution for this. Here we need to perform operation in a brute force manner. "
},
{
"code": null,
"e": 928,
"s": 669,
"text": "Find bit of i and i+1.To swap the bits subtract and add corresponding values.To remove bit at ith bit to i+1. we need to subtract i_bit<<i and add it at i+1 location for that we need to add i_bit<<(i+1).Similarly do for (i+1)th bit. Remove it from i+1 to i."
},
{
"code": null,
"e": 952,
"s": 928,
"text": "Find bit of i and i+1."
},
{
"code": null,
"e": 1008,
"s": 952,
"text": "To swap the bits subtract and add corresponding values."
},
{
"code": null,
"e": 1135,
"s": 1008,
"text": "To remove bit at ith bit to i+1. we need to subtract i_bit<<i and add it at i+1 location for that we need to add i_bit<<(i+1)."
},
{
"code": null,
"e": 1190,
"s": 1135,
"text": "Similarly do for (i+1)th bit. Remove it from i+1 to i."
},
{
"code": null,
"e": 1194,
"s": 1190,
"text": "C++"
},
{
"code": null,
"e": 1199,
"s": 1194,
"text": "Java"
},
{
"code": null,
"e": 1207,
"s": 1199,
"text": "Python3"
},
{
"code": null,
"e": 1210,
"s": 1207,
"text": "C#"
},
{
"code": null,
"e": 1221,
"s": 1210,
"text": "Javascript"
},
{
"code": "// C++ program to swap even and// odd bits of a given number#include <bits/stdc++.h>using namespace std; // Function to swap even// and odd bitsunsigned int swapBits(unsigned int x){ for(int i=0; i<32; i+=2){ int i_bit = ( x >> i ) & 1; // find i th bit int i_1_bit = (x >> ( i+1 )) & 1; // find i+1 th bit x = x - ( i_bit << i) // remove i_bit - ( i_1_bit << ( i+1 ) ) // remove i+1 th bit + ( i_bit << ( i+1 ) ) // put i_bit at i+1 location + ( i_1_bit << i ); // put i+1 bit at i location } return x;} // Driver codeint main(){ unsigned int x =23; // 00010111 // Output is 43 (00101011) cout<<swapBits(x); return 0;} // This code is contributed by Amandeep Gupta",
"e": 1981,
"s": 1221,
"text": null
},
{
"code": "// Java program to swap even and// odd bits of a given numberimport java.io.*; class GFG { // Function to swap even // and odd bits static int swapBits(int x) { for (int i = 0; i < 32; i += 2) { int i_bit = (x >> i) & 1; // find i th bit int i_1_bit = (x >> (i + 1)) & 1; // find i+1 th bit x = x - (i_bit << i) // remove i_bit - (i_1_bit << (i + 1)) // remove i+1 th bit + (i_bit << (i + 1)) // put i_bit at i+1 location + (i_1_bit << i); // put i+1 bit at i location } return x; } // Driver code public static void main(String[] args) { int x = 23; // 00010111 // Output is 43 (00101011) System.out.print(swapBits(x)); }} // This code is contributed by subham348.",
"e": 2849,
"s": 1981,
"text": null
},
{
"code": "# Python program to swap even and# odd bits of a given number # Function to swap even# and odd bitsdef swapBits(x): # Get all even bits of x even_bits = x & 0xAAAAAAAA # Get all odd bits of x odd_bits = x & 0x55555555 # Right shift even bits even_bits >>= 1 # Left shift odd bits odd_bits <<= 1 for i in range(0,32,2): i_bit = (x >> 1) & 1; # find i th bit i_1_bit = (x >> (i + 1)) & 1; # find i+1 th bit x = x - (i_bit << i) # remove i_bit - (i_1_bit << (i + 2)) # remove i+1 th bit + (i_bit << (i + 1)) # put i_bit at i+1 location + (i_1_bit << i); # put i+1 bit at i location # Combine even and odd bits return (even_bits | odd_bits) # Driver codeif __name__ == '__main__': x = 23; # 00010111 # Output is 43 (00101011) print(swapBits(x)); # This code is contributed by Rajput-Ji",
"e": 3745,
"s": 2849,
"text": null
},
{
"code": "// C# program to swap even and// odd bits of a given numberusing System; class GFG { // Function to swap even // and odd bits static int swapBits(int x) { for (int i = 0; i < 32; i += 2) { int i_bit = (x >> i) & 1; // find i th bit int i_1_bit = (x >> (i + 1)) & 1; // find i+1 th bit x = x - (i_bit << i) // remove i_bit - (i_1_bit << (i + 1)) // remove i+1 th bit + (i_bit << (i + 1)) // put i_bit at i+1 location + (i_1_bit << i); // put i+1 bit at i location } return x; } // Driver code public static void Main() { int x = 23; // 00010111 // Output is 43 (00101011) Console.Write(swapBits(x)); }} // This code is contributed by subham348.",
"e": 4591,
"s": 3745,
"text": null
},
{
"code": "<script>// JavaScript Program to implement// the above approach // Function to swap even// and odd bitsfunction swapBits( x){ for(let i = 0; i < 32; i += 2){ let i_bit = ( x >> i ) & 1; // find i th bit let i_1_bit = (x >> ( i+1 )) & 1; // find i+1 th bit x = x - ( i_bit << i) // remove i_bit - ( i_1_bit << ( i+1 ) ) // remove i+1 th bit + ( i_bit << ( i+1 ) ) // put i_bit at i+1 location + ( i_1_bit << i ); // put i+1 bit at i location } return x;} // Driver code let x =23; // 00010111 // Output is 43 (00101011) document.write(swapBits(x)); // This code is contributed by Potta Lokesh </script>",
"e": 5290,
"s": 4591,
"text": null
},
{
"code": null,
"e": 5299,
"s": 5290,
"text": "Output: "
},
{
"code": null,
"e": 5304,
"s": 5299,
"text": " 43 "
},
{
"code": null,
"e": 5333,
"s": 5304,
"text": "Time Complexity: O(constant)"
},
{
"code": null,
"e": 5355,
"s": 5333,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 6216,
"s": 5355,
"text": "If we take a closer look at the example, we can observe that we basically need to right shift (>>) all even bits (In the above example, even bits of 23 are highlighted) by 1 so that they become odd bits (highlighted in 43), and left shift (<<) all odd bits by 1 so that they become even bits. The following solution is based on this observation. The solution assumes that input number is stored using 32 bits.Let the input number be x 1) Get all even bits of x by doing bitwise and of x with 0xAAAAAAAA. The number 0xAAAAAAAA is a 32 bit number with all even bits set as 1 and all odd bits as 0. 2) Get all odd bits of x by doing bitwise and of x with 0x55555555. The number 0x55555555 is a 32 bit number with all odd bits set as 1 and all even bits as 0. 3) Right shift all even bits. 4) Left shift all odd bits. 5) Combine new even and odd bits and return. "
},
{
"code": null,
"e": 6220,
"s": 6216,
"text": "C++"
},
{
"code": null,
"e": 6222,
"s": 6220,
"text": "C"
},
{
"code": null,
"e": 6227,
"s": 6222,
"text": "Java"
},
{
"code": null,
"e": 6236,
"s": 6227,
"text": "Python 3"
},
{
"code": null,
"e": 6239,
"s": 6236,
"text": "C#"
},
{
"code": null,
"e": 6243,
"s": 6239,
"text": "PHP"
},
{
"code": null,
"e": 6254,
"s": 6243,
"text": "Javascript"
},
{
"code": "// C++ program to swap even and// odd bits of a given number#include <bits/stdc++.h>using namespace std; // Function to swap even// and odd bitsunsigned int swapBits(unsigned int x){ // Get all even bits of x unsigned int even_bits = x & 0xAAAAAAAA; // Get all odd bits of x unsigned int odd_bits = x & 0x55555555; even_bits >>= 1; // Right shift even bits odd_bits <<= 1; // Left shift odd bits return (even_bits | odd_bits); // Combine even and odd bits} // Driver codeint main(){ unsigned int x = 23; // 00010111 // Output is 43 (00101011) cout<<swapBits(x); return 0;} // This code is contributed by rathbhupendra",
"e": 6910,
"s": 6254,
"text": null
},
{
"code": "// C program to swap even and// odd bits of a given number#include <stdio.h> // Function to swap even// and odd bitsunsigned int swapBits(unsigned int x){ // Get all even bits of x unsigned int even_bits = x & 0xAAAAAAAA; // Get all odd bits of x unsigned int odd_bits = x & 0x55555555; even_bits >>= 1; // Right shift even bits odd_bits <<= 1; // Left shift odd bits return (even_bits | odd_bits); // Combine even and odd bits} // Driver program to test above functionint main(){ unsigned int x = 23; // 00010111 // Output is 43 (00101011) printf(\"%u \", swapBits(x)); return 0;}",
"e": 7532,
"s": 6910,
"text": null
},
{
"code": "// Java program to swap even// and odd bits of a given number class GFG{ // Function to swap even // and odd bits static int swapBits(int x) { // Get all even bits of x int even_bits = x & 0xAAAAAAAA; // Get all odd bits of x int odd_bits = x & 0x55555555; // Right shift even bits even_bits >>= 1; // Left shift even bits odd_bits <<= 1; // Combine even and odd bits return (even_bits | odd_bits); } // Driver program to test above function public static void main(String[] args) { int x = 23; // 00010111 // Output is 43 (00101011) System.out.println(swapBits(x)); }} // This code is contributed by Smitha Dinesh Semwal",
"e": 8315,
"s": 7532,
"text": null
},
{
"code": "# Python 3 program to swap even# and odd bits of a given number # Function for swapping even# and odd bitsdef swapBits(x) : # Get all even bits of x even_bits = x & 0xAAAAAAAA # Get all odd bits of x odd_bits = x & 0x55555555 # Right shift even bits even_bits >>= 1 # Left shift odd bits odd_bits <<= 1 # Combine even and odd bits return (even_bits | odd_bits) # Driver program# 00010111x = 23 # Output is 43 (00101011)print(swapBits(x)) # This code is contributed# by Nikita Tiwari.",
"e": 8848,
"s": 8315,
"text": null
},
{
"code": "// C# program to swap even and odd bits// of a given numberusing System; class GFG { // Function to swap even // and odd bits static long swapBits(int x) { // Get all even bits of x long even_bits = x & 0xAAAAAAAA; // Get all odd bits of x long odd_bits = x & 0x55555555; // Right shift even bits even_bits >>= 1; // Left shift even bits odd_bits <<= 1; // Combine even and odd bits return (even_bits | odd_bits); } // Driver program to test above function public static void Main() { int x = 23; // 00010111 // Output is 43 (00101011) Console.Write(swapBits(x)); }} // This code is contributed by Sam007.",
"e": 9624,
"s": 8848,
"text": null
},
{
"code": "<?php// PHP program to swap even and// odd bits of a given number // Function to swap even// and odd bitsfunction swapBits( $x){ // Get all even bits of x $even_bits = $x & 0xAAAAAAAA; // Get all odd bits of x $odd_bits = $x & 0x55555555; // Right shift even bits $even_bits >>= 1; // Left shift odd bits $odd_bits <<= 1; // Combine even and odd bits return ($even_bits | $odd_bits);} // Driver Code // 00010111$x = 23; // Output is 43 (00101011)echo swapBits($x); // This code is contributed by Ajit?>",
"e": 10174,
"s": 9624,
"text": null
},
{
"code": "<script>// java script program to swap even and// odd bits of a given number // Function to swap even// and odd bitsfunction swapBits( x){ // Get all even bits of x even_bits = x & 0xAAAAAAAA; // Get all odd bits of x odd_bits = x & 0x55555555; // Right shift even bits even_bits >>= 1; // Left shift odd bits odd_bits <<= 1; // Combine even and odd bits return (even_bits | odd_bits);} // Driver Code // 00010111let x = 23; // Output is 43 (00101011)document.write(swapBits(x)); // This code is contributed by sravan kumar </script>",
"e": 10755,
"s": 10174,
"text": null
},
{
"code": null,
"e": 10764,
"s": 10755,
"text": "Output: "
},
{
"code": null,
"e": 10769,
"s": 10764,
"text": " 43 "
},
{
"code": null,
"e": 10791,
"s": 10769,
"text": "Time Complexity: O(1)"
},
{
"code": null,
"e": 10814,
"s": 10791,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 11684,
"s": 10814,
"text": "Swap all odd and even bits | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersSwap all odd and even bits | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 6:32•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=GWLCF808oVI\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>"
},
{
"code": null,
"e": 11810,
"s": 11684,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 11816,
"s": 11810,
"text": "jit_t"
},
{
"code": null,
"e": 11830,
"s": 11816,
"text": "rathbhupendra"
},
{
"code": null,
"e": 11846,
"s": 11830,
"text": "sravankumar8128"
},
{
"code": null,
"e": 11865,
"s": 11846,
"text": "indianamandeep2001"
},
{
"code": null,
"e": 11875,
"s": 11865,
"text": "subham348"
},
{
"code": null,
"e": 11889,
"s": 11875,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 11899,
"s": 11889,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 11909,
"s": 11899,
"text": "Bit Magic"
},
{
"code": null,
"e": 11919,
"s": 11909,
"text": "Bit Magic"
}
] |
How to select all records that are 10 minutes within current timestamp in MySQL?
|
You can select all records that are 10 minutes within current timestamp using the following syntax−
SELECT *FROM yourTableName
WHERE yourColumnName > = DATE_SUB(NOW(),INTERVAL 10 MINUTE);
To understand the above syntax, let us create a table. The query to create a table is as follows−
mysql> create table users
-> (
-> Id int NOT NULL AUTO_INCREMENT,
-> UserName varchar(20),
-> UserLastseen datetime,
-> PRIMARY KEY(Id)
-> );
Query OK, 0 rows affected (0.91 sec)
Insert some records in the table using insert command. The query is as follows−
mysql> insert into users(UserName,UserLastseen) values('Larry','2019-01-15 02−45−00');
Query OK, 1 row affected (0.15 sec)
mysql> insert into users(UserName,UserLastseen) values('Sam',now());
Query OK, 1 row affected (0.25 sec)
mysql> insert into users(UserName,UserLastseen) values('Mike','2019-01-15 02−30−00');
Query OK, 1 row affected (0.15 sec)
mysql> insert into users(UserName,UserLastseen) values('Bob','2019-01-15 15−02−00');
Query OK, 1 row affected (0.23 sec)
mysql> insert into users(UserName,UserLastseen) values('David','2019-01-15 14−55−00');
Query OK, 1 row affected (0.15 sec)
Display all records from the table using select statement. The query is as follows−
mysql> select *from users;
The following is the output−
+----+----------+---------------------+
| Id | UserName | UserLastseen |
+----+----------+---------------------+
| 1 | Larry | 2019-01-15 02−45−00 |
| 2 | Sam | 2019-01-15 15−01−52 |
| 3 | Mike | 2019-01-15 02−30−00 |
| 4 | Bob | 2019-01-15 15−02−00 |
| 5 | David | 2019-01-15 14−55−00 |
+----+----------+---------------------+
5 rows in set (0.00 sec)
Here is the query to select all records that are 10 minutes within the current timestamp−
mysql> select *from users
-> where UserLastseen> = date_sub(now(),interval 10 minute);
The following is the output−
+----+----------+---------------------+
| Id | UserName | UserLastseen |
+----+----------+---------------------+
| 2 | Sam | 2019-01-15 15−01−52 |
| 4 | Bob | 2019-01-15 15−02−00 |
| 5 | David | 2019-01-15 14−55−00 |
+----+----------+---------------------+
3 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "You can select all records that are 10 minutes within current timestamp using the following syntax−"
},
{
"code": null,
"e": 1250,
"s": 1162,
"text": "SELECT *FROM yourTableName\nWHERE yourColumnName > = DATE_SUB(NOW(),INTERVAL 10 MINUTE);"
},
{
"code": null,
"e": 1348,
"s": 1250,
"text": "To understand the above syntax, let us create a table. The query to create a table is as follows−"
},
{
"code": null,
"e": 1545,
"s": 1348,
"text": "mysql> create table users\n -> (\n -> Id int NOT NULL AUTO_INCREMENT,\n -> UserName varchar(20),\n -> UserLastseen datetime,\n -> PRIMARY KEY(Id)\n -> );\nQuery OK, 0 rows affected (0.91 sec)"
},
{
"code": null,
"e": 1625,
"s": 1545,
"text": "Insert some records in the table using insert command. The query is as follows−"
},
{
"code": null,
"e": 2223,
"s": 1625,
"text": "mysql> insert into users(UserName,UserLastseen) values('Larry','2019-01-15 02−45−00');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into users(UserName,UserLastseen) values('Sam',now());\nQuery OK, 1 row affected (0.25 sec)\n\nmysql> insert into users(UserName,UserLastseen) values('Mike','2019-01-15 02−30−00');\nQuery OK, 1 row affected (0.15 sec)\n\nmysql> insert into users(UserName,UserLastseen) values('Bob','2019-01-15 15−02−00');\nQuery OK, 1 row affected (0.23 sec)\n\nmysql> insert into users(UserName,UserLastseen) values('David','2019-01-15 14−55−00');\nQuery OK, 1 row affected (0.15 sec)"
},
{
"code": null,
"e": 2307,
"s": 2223,
"text": "Display all records from the table using select statement. The query is as follows−"
},
{
"code": null,
"e": 2334,
"s": 2307,
"text": "mysql> select *from users;"
},
{
"code": null,
"e": 2363,
"s": 2334,
"text": "The following is the output−"
},
{
"code": null,
"e": 2731,
"s": 2363,
"text": "+----+----------+---------------------+\n| Id | UserName | UserLastseen |\n+----+----------+---------------------+\n| 1 | Larry | 2019-01-15 02−45−00 |\n| 2 | Sam | 2019-01-15 15−01−52 |\n| 3 | Mike | 2019-01-15 02−30−00 |\n| 4 | Bob | 2019-01-15 15−02−00 |\n| 5 | David | 2019-01-15 14−55−00 |\n+----+----------+---------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2821,
"s": 2731,
"text": "Here is the query to select all records that are 10 minutes within the current timestamp−"
},
{
"code": null,
"e": 2911,
"s": 2821,
"text": "mysql> select *from users\n -> where UserLastseen> = date_sub(now(),interval 10 minute);"
},
{
"code": null,
"e": 2940,
"s": 2911,
"text": "The following is the output−"
},
{
"code": null,
"e": 3245,
"s": 2940,
"text": "+----+----------+---------------------+\n| Id | UserName | UserLastseen |\n+----+----------+---------------------+\n| 2 | Sam | 2019-01-15 15−01−52 |\n| 4 | Bob | 2019-01-15 15−02−00 |\n| 5 | David | 2019-01-15 14−55−00 |\n+----+----------+---------------------+\n3 rows in set (0.00 sec)"
}
] |
String matches() Method in Java with Examples - GeeksforGeeks
|
12 Nov, 2021
Variants of matches() method is used to tell more precisely not test whether the given string matches to a regular expression or not as whenever this method is called in itself as matches() or be it matches() where here we do pass two arguments that are our string and regular expression, the working and output remains same.
There exist multiple variants three variants of the matches() method as listed and described below as follows:
This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str).
Syntax:
public boolean matches(String regex)
Parameters: The regular expression to which this string is to be matched.
Return Type: Boolean value, returning true if and only if strings match the given regular expression else false.
Example:
Java
// Java Program to Demonstrate Working of matches() Method// of String class // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Declaring and initializing a string // Input string String Str = new String("Welcome to geeksforgeeks"); // Display message for better readability System.out.print( "Does String contains regex (.*)geeks(.*) ? : "); // Testing if regex is present or not System.out.println(Str.matches("(.*)geeks(.*)")); // Display message for better readability System.out.print( "Does String contains regex geeks ? : "); // Testing if regex is present or not System.out.println(Str.matches("geeks")); }}
Does String contains regex (.*)geeks(.*) ? : true
Does String contains regex geeks ? : false
This method has two variants that can be used to test if two string regions are equal.
Syntax:
public boolean regionMatches(int str_strt, String other, int other_strt,int len)
Parameters:
The starting offset of the subregion in this string
The string argument
The starting offset of the subregion in the string argument
The number of characters to compare
Return Type: Boolean value, true if the specified subregion of this string matches the specified subregion of the string argument; false otherwise.
Example:
Java
// Java Program to Demonstrate Working of regionmatches()// method of String class // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Declaring and initializing a string String Str1 = new String("Welcome to geeksforgeeks"); // Initializing test string String Str2 = new String("GEEKS"); // Tests whether GEEKS starts in geeksforgeeks // starting from pos 11 and // compares 5 characters of GEEKS System.out.print( "Checking if GEEKS is in geeksforgeeks( case sensitive ) : "); System.out.println( Str1.regionMatches(11, Str2, 0, 5)); }}
Checking if GEEKS is in geeksforgeeks( case sensitive ) : false
This method has two variants that can be used to test if two string regions are equal.
Syntax:
public boolean
regionMatches(boolean ignoreCase, int str_strt, String other, int other_strt,int len)
Parameters:
The starting offset of the subregion in this string
The string argument
The starting offset of the subregion in the string argument
The number of characters to compare
ignoreCase: if true, ignore the case when comparing characters
Return Type: It returns true if the specified subregion of this string matches the specified subregion of the string argument; false otherwise. Whether the matching is exact or case insensitive depends on the ignoreCase argument.
Example:
Java
// Java Program to Demonstrate Working of regionmatches() // Main class public class GFG { // Main driver method public static void main(String args[]) { // Declaring and initializing a string String Str1 = new String("Welcome to geeksforgeeks"); // Initializing a test string String Str2 = new String("GEEKS"); // Tests whether GEEKS starts in geeksforgeeks starting from pos 11 // and from 0 ( i.e starting in GEEKS) and ignores case // and compares 5 characters of GEEKS System.out.print("Checking if GEEKS is in geeksforgeeks( case insensitive ) : " ); System.out.println(Str1.regionMatches(true, 11, Str2, 0, 5)); }}
Output:
Checking if GEEKS is in geeksforgeeks( case insensitive ) : true
This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
solankimayank
Java-Functions
Java-lang package
java-regular-expression
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Interfaces in Java
ArrayList in Java
Singleton Class in Java
Overriding in Java
Collections in Java
Set in Java
LinkedList in Java
Stream In Java
Multidimensional Arrays in Java
Constructors in Java
|
[
{
"code": null,
"e": 24255,
"s": 24227,
"text": "\n12 Nov, 2021"
},
{
"code": null,
"e": 24581,
"s": 24255,
"text": "Variants of matches() method is used to tell more precisely not test whether the given string matches to a regular expression or not as whenever this method is called in itself as matches() or be it matches() where here we do pass two arguments that are our string and regular expression, the working and output remains same."
},
{
"code": null,
"e": 24694,
"s": 24581,
"text": "There exist multiple variants three variants of the matches() method as listed and described below as follows: "
},
{
"code": null,
"e": 24915,
"s": 24694,
"text": "This method tells whether or not this string matches the given regular expression. An invocation of this method of the form str.matches(regex) yields exactly the same result as the expression Pattern.matches(regex, str)."
},
{
"code": null,
"e": 24924,
"s": 24915,
"text": "Syntax: "
},
{
"code": null,
"e": 24962,
"s": 24924,
"text": "public boolean matches(String regex) "
},
{
"code": null,
"e": 25037,
"s": 24962,
"text": "Parameters: The regular expression to which this string is to be matched. "
},
{
"code": null,
"e": 25150,
"s": 25037,
"text": "Return Type: Boolean value, returning true if and only if strings match the given regular expression else false."
},
{
"code": null,
"e": 25159,
"s": 25150,
"text": "Example:"
},
{
"code": null,
"e": 25164,
"s": 25159,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Working of matches() Method// of String class // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Declaring and initializing a string // Input string String Str = new String(\"Welcome to geeksforgeeks\"); // Display message for better readability System.out.print( \"Does String contains regex (.*)geeks(.*) ? : \"); // Testing if regex is present or not System.out.println(Str.matches(\"(.*)geeks(.*)\")); // Display message for better readability System.out.print( \"Does String contains regex geeks ? : \"); // Testing if regex is present or not System.out.println(Str.matches(\"geeks\")); }}",
"e": 25949,
"s": 25164,
"text": null
},
{
"code": null,
"e": 26042,
"s": 25949,
"text": "Does String contains regex (.*)geeks(.*) ? : true\nDoes String contains regex geeks ? : false"
},
{
"code": null,
"e": 26130,
"s": 26042,
"text": "This method has two variants that can be used to test if two string regions are equal. "
},
{
"code": null,
"e": 26138,
"s": 26130,
"text": "Syntax:"
},
{
"code": null,
"e": 26219,
"s": 26138,
"text": "public boolean regionMatches(int str_strt, String other, int other_strt,int len)"
},
{
"code": null,
"e": 26231,
"s": 26219,
"text": "Parameters:"
},
{
"code": null,
"e": 26283,
"s": 26231,
"text": "The starting offset of the subregion in this string"
},
{
"code": null,
"e": 26303,
"s": 26283,
"text": "The string argument"
},
{
"code": null,
"e": 26363,
"s": 26303,
"text": "The starting offset of the subregion in the string argument"
},
{
"code": null,
"e": 26399,
"s": 26363,
"text": "The number of characters to compare"
},
{
"code": null,
"e": 26547,
"s": 26399,
"text": "Return Type: Boolean value, true if the specified subregion of this string matches the specified subregion of the string argument; false otherwise."
},
{
"code": null,
"e": 26556,
"s": 26547,
"text": "Example:"
},
{
"code": null,
"e": 26561,
"s": 26556,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Working of regionmatches()// method of String class // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Declaring and initializing a string String Str1 = new String(\"Welcome to geeksforgeeks\"); // Initializing test string String Str2 = new String(\"GEEKS\"); // Tests whether GEEKS starts in geeksforgeeks // starting from pos 11 and // compares 5 characters of GEEKS System.out.print( \"Checking if GEEKS is in geeksforgeeks( case sensitive ) : \"); System.out.println( Str1.regionMatches(11, Str2, 0, 5)); }}",
"e": 27260,
"s": 26561,
"text": null
},
{
"code": null,
"e": 27324,
"s": 27260,
"text": "Checking if GEEKS is in geeksforgeeks( case sensitive ) : false"
},
{
"code": null,
"e": 27412,
"s": 27324,
"text": "This method has two variants that can be used to test if two string regions are equal. "
},
{
"code": null,
"e": 27420,
"s": 27412,
"text": "Syntax:"
},
{
"code": null,
"e": 27522,
"s": 27420,
"text": "public boolean \nregionMatches(boolean ignoreCase, int str_strt, String other, int other_strt,int len)"
},
{
"code": null,
"e": 27534,
"s": 27522,
"text": "Parameters:"
},
{
"code": null,
"e": 27586,
"s": 27534,
"text": "The starting offset of the subregion in this string"
},
{
"code": null,
"e": 27606,
"s": 27586,
"text": "The string argument"
},
{
"code": null,
"e": 27666,
"s": 27606,
"text": "The starting offset of the subregion in the string argument"
},
{
"code": null,
"e": 27702,
"s": 27666,
"text": "The number of characters to compare"
},
{
"code": null,
"e": 27766,
"s": 27702,
"text": "ignoreCase: if true, ignore the case when comparing characters"
},
{
"code": null,
"e": 27996,
"s": 27766,
"text": "Return Type: It returns true if the specified subregion of this string matches the specified subregion of the string argument; false otherwise. Whether the matching is exact or case insensitive depends on the ignoreCase argument."
},
{
"code": null,
"e": 28005,
"s": 27996,
"text": "Example:"
},
{
"code": null,
"e": 28010,
"s": 28005,
"text": "Java"
},
{
"code": "// Java Program to Demonstrate Working of regionmatches() // Main class public class GFG { // Main driver method public static void main(String args[]) { // Declaring and initializing a string String Str1 = new String(\"Welcome to geeksforgeeks\"); // Initializing a test string String Str2 = new String(\"GEEKS\"); // Tests whether GEEKS starts in geeksforgeeks starting from pos 11 // and from 0 ( i.e starting in GEEKS) and ignores case // and compares 5 characters of GEEKS System.out.print(\"Checking if GEEKS is in geeksforgeeks( case insensitive ) : \" ); System.out.println(Str1.regionMatches(true, 11, Str2, 0, 5)); }}",
"e": 28723,
"s": 28010,
"text": null
},
{
"code": null,
"e": 28732,
"s": 28723,
"text": "Output: "
},
{
"code": null,
"e": 28797,
"s": 28732,
"text": "Checking if GEEKS is in geeksforgeeks( case insensitive ) : true"
},
{
"code": null,
"e": 29217,
"s": 28797,
"text": "This article is contributed by Astha Tyagi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 29231,
"s": 29217,
"text": "solankimayank"
},
{
"code": null,
"e": 29246,
"s": 29231,
"text": "Java-Functions"
},
{
"code": null,
"e": 29264,
"s": 29246,
"text": "Java-lang package"
},
{
"code": null,
"e": 29288,
"s": 29264,
"text": "java-regular-expression"
},
{
"code": null,
"e": 29301,
"s": 29288,
"text": "Java-Strings"
},
{
"code": null,
"e": 29306,
"s": 29301,
"text": "Java"
},
{
"code": null,
"e": 29319,
"s": 29306,
"text": "Java-Strings"
},
{
"code": null,
"e": 29324,
"s": 29319,
"text": "Java"
},
{
"code": null,
"e": 29422,
"s": 29324,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29431,
"s": 29422,
"text": "Comments"
},
{
"code": null,
"e": 29444,
"s": 29431,
"text": "Old Comments"
},
{
"code": null,
"e": 29463,
"s": 29444,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29481,
"s": 29463,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29505,
"s": 29481,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 29524,
"s": 29505,
"text": "Overriding in Java"
},
{
"code": null,
"e": 29544,
"s": 29524,
"text": "Collections in Java"
},
{
"code": null,
"e": 29556,
"s": 29544,
"text": "Set in Java"
},
{
"code": null,
"e": 29575,
"s": 29556,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 29590,
"s": 29575,
"text": "Stream In Java"
},
{
"code": null,
"e": 29622,
"s": 29590,
"text": "Multidimensional Arrays in Java"
}
] |
How to build a KNN classification model from scratch and visualize it using Streamlit | by Rahul Banerjee | Towards Data Science
|
KNN or K Nearest Neighbour is used for classification and regression. In this tutorial, we will be using it for classification. Since the target label is known, it is a Supervised algorithm. It essentially takes an input and finds the K nearest points to it. It then checks the labels of the nearest points and classifies the input as the label which occurred the most. Say we want to build a model to classify an animal as a dog or a cat based on the weight, height as input. If K = 3, we find the 3 nearest points to our input and check their label. If 2 of the 3 nearest points have a label ‘dog’, our model classifies the input as ‘dog’. If 2 of the 3 nearest points have a label ‘cat’, our model will classify the input as ‘cat’
Normalize the dataset and store it, i.e make sure all values are between 0 and 1.
Take an input data point and find the distance from all the records in our dataset. Store the distances in a list.
Sort the list containing the distances and check the labels for the first K records in the sorted list
Classify the input as the label which occurred the most in the first K records
First, we will create all the helper functions we will need. Then we will combine them and add some streamlit functions to build a web app.
For ease of understanding and visualization, we will be working with a dataset that has 2 features and has binary labels, i.e ‘0’ and ‘1’.
To normalize a list of values, we iterate over each value and find the difference between the value and minimum value in the list. We then divide it by the difference of maximum and minimum values in the list.
def min_max_normalize(lst): minimum = min(lst) maximum = max(lst) normalized = [(val - minimum)/(maximum - minimum) for val in lst] return normalized
The function takes in a list of values and returns the normalized values
This function will be used to calculate the distance between two given points. We will use Euclid's Formula to calculate the distance.
def distance(element1 , element2): x_distance = (element1[0] - element2[0])**2 y_distance = (element1[1] - element2[1])**2 return (x_distance + y_distance)**0.5
The function takes in two 2D points and returns the Euclidean Distance between them. Since we are considering a dataset with only 2 features, we are only considering the x and y coordinates. As the number of features increases, this function will need to change to find the squared difference between all indices.
We iterate over each value in the dataset and use our distance function above to calculate the distance between the two points. We then store the distances and sort it.
def find_nearest(x , y , input , k): distances = [] for id,element in enumerate(x): distances.append([distance(input , element),id]) distances = sorted(distances) predicted_label = get_label(distances[0:k] , y) return predicted_label, distances[0:k] , distances[k:]
The function takes the following parameters as input:
x: This is our dataset containing the two features
y: This contains the labels for each row in x. They are mapped respectively, i.e the label for x[i] is y[i]
input: This is a 2D array which contains the features of the points we want to classify
k: The number of nearest neighbour we want our model to consider
First, we create an empty array to store the distances. We need to store the distance and the index of the record in the dataset. The index can be used in the y array to find the label for that record.
Then we sort the distances. Next, we use the get_label function (It will be discussed below) to get the most occurring label.
Since the distances array is sorted, the first k elements,i.e distances[0:k] are the k nearest neighbours to our input. We return the predicted label of our input, the k nearest neighbours and the rest of the neighbours.
We essentially get the k nearest neighbours, check the label for each. In our case, we have only two labels ‘0’ and ‘1’. If the label of a neighbour is ‘0’ we increment count for occurrences of ‘0’ and do the same for ‘1’. We compare the counts for occurrences of both labels and return the label with the higher count.
def get_label(neighbours, y): zero_count , one_count = 0,0 for element in neighbours: if y[element[1]] == 0: zero_count +=1 elif y[element[1]] == 1: one_count +=1 if zero_count == one_count: return y[neighbours[0][1]] return 1 if one_count > zero_count else 0
The function takes the k nearest neighbours as the input. Each record in neighbours contains the distance from the input point and its original id. We use the id and the y array to get the label of the record. We then check the label and return the predicted label.
We have created the required Helper functions. Now we will combine them along with some streamlit functions. Exciting Stuff! 😎
We will use Plotly to plot our graphs since Plotly plots interactive graphs. For our dataset, we will import a dataset from sklearn.datasets. We will also use the pandas library to create Datframes.
import streamlit as stimport pandas as pdfrom sklearn.datasets import make_blobsimport plotly.express as pximport plotly.graph_objects as go
I will break the rest of the tutorial into three parts
Input from UserImporting Dataset and Visualizing itVisualizing the Prediction
Input from User
Importing Dataset and Visualizing it
Visualizing the Prediction
We will use streamlit’s title method to display a title and slider method to create a numerical slider to get input from the user. Since our data is normalized, we expect the input to be normalized as well. Therefore we restrict the user to enter values between 0 and 1. We can also take input from the user and use minimum, maximum values in our dataset to normalize the input.
st.title("KNN Visualize")x_input = st.slider("Choose X input", min_value=0.0, max_value=1.0,key='x')y_input = st.slider("Choose Y input", min_value=0.0, max_value=1.0,key='y')k = st.slider("Choose value of K", min_value=1, max_value=10,key='k')input = (x_input,y_input)
Every time the slider value is changed the entire python script is re-run and the variables will contain the new values according to the slider.
x , y = make_blobs(n_samples = 100 , n_features = 2 , centers = 2, random_state= 2)
The make_blobs functions create a dataset for us which looks similar to the distribution in the graph above. In the real world, the dataset won’t be so co-operative but this dataset will suffice for now. I suggest you plot a scatter plot using matplotlib to see the distribution of the data.
x contains the features and y contains the respective labels
# Normalizing Datax[:,0] = min_max_normalize(x[:,0])x[:,1] = min_max_normalize(x[:,1])# Dataframedf = pd.DataFrame(x , columns = ['Feature1' , 'Feature2'] )df['Label'] = yst.dataframe(df)
First, we use the normalizing helper function we created before to normalize our data. Then we combine the x and y array to create a Dataframe. We use streamlit’s dataframe method to view the dataframe.
# Initial Data Plotfig = px.scatter(df, x = 'Feature1' , y='Feature2', symbol='Label',symbol_map={'0':'square-dot' , '1':'circle'})fig.add_trace( go.Scatter(x= [input[0]], y=[input[1]], name = "Point to Classify", ))st.plotly_chart(fig)
You can read Plotly’s documentation for a better understanding of the above code. We create a figure with the scatter plot of the dataframe we just created. We also add our input point to better understand where it is located with respect to other points in the dataset. Streamlit’s plotly_chart method takes a Plotly figure as a parameter and plots an interactive graph on our app.
#Finding Nearest Neighbourspredicted_label , nearest_neighbours, far_neighbours = find_nearest(x ,y , input ,k)st.title('Prediction')st.subheader('Predicted Label : {}'.format(predicted_label))
We use the find_nearest function we created earlier to get the predicted label and ids, distances of the k nearest neighbours and the far neighbours.
We display the predicted label us streamlit’s subheader method
nearest_neighbours = [[neighbour[1],x[neighbour[1],0],x[neighbour[1],1],neighbour[0],y[neighbour[1]]] for neighbour in nearest_neighbours]nearest_neighbours = pd.DataFrame(nearest_neighbours , columns = ['id','Feature1','Feature2','Distance','Label'])st.dataframe(nearest_neighbours)
The above code basically uses the id of the nearest neighbours and combines the id, distance with the feature1, feature2 values of the record and its label. We use the combined list to create a dataframe containing the information of the nearest neighbours. We then use streamlit’s dataframe method to display it. This dataframe will help us understand the graph below it.
far_neighbours = [[neighbour[1],x[neighbour[1],0],x[neighbour[1],1],neighbour[0],y[neighbour[1]]] for neighbour in far_neighbours]far_neighbours = pd.DataFrame(far_neighbours , columns = ['id','Feature1','Feature2','Distance','Label'])fig2 = px.scatter(far_neighbours,x='Feature1',y='Feature2',symbol='Label',symbol_map={'0':'square-dot' , '1':'circle'})
We create a similar dataframe for the far neighbours. We use Plotly to plot a scatter plot. We will now add the input and lines connecting the input to its k nearest neighbours.
for index,neighbour in nearest_neighbours.iterrows(): fig2.add_trace( go.Scatter( x=[input[0], neighbour['Feature1']], y=[input[1], neighbour['Feature2']],mode='lines+markers' , name = 'id {}'.format(int(neighbour['id'])) ) )st.plotly_chart(fig2)
We iterate over each of the neighbours and add a line between the neighbour and our input point to the figure we created. Finally, we use the plotly_chart method to plot the figure.
And That’s It 👏 We have a created a KNN classifier from scratch and created a Streamlit App to visualize it
If you are interested in deploying your streamlit app, check out my tutorial.
You can find the GitHub repo here.
I am still fairly new to the world of Machine Learning, if you find any errors/mistakes or any piece of code which can be optimized, please let me know! I am always open to feedback 😃
I recently created a blog using WordPress, I would love it if you check it out 😃
realpythonproject.com
Connect with me on LinkedIn
www.linkedin.com
Connect with me on Twitter
|
[
{
"code": null,
"e": 906,
"s": 172,
"text": "KNN or K Nearest Neighbour is used for classification and regression. In this tutorial, we will be using it for classification. Since the target label is known, it is a Supervised algorithm. It essentially takes an input and finds the K nearest points to it. It then checks the labels of the nearest points and classifies the input as the label which occurred the most. Say we want to build a model to classify an animal as a dog or a cat based on the weight, height as input. If K = 3, we find the 3 nearest points to our input and check their label. If 2 of the 3 nearest points have a label ‘dog’, our model classifies the input as ‘dog’. If 2 of the 3 nearest points have a label ‘cat’, our model will classify the input as ‘cat’"
},
{
"code": null,
"e": 988,
"s": 906,
"text": "Normalize the dataset and store it, i.e make sure all values are between 0 and 1."
},
{
"code": null,
"e": 1103,
"s": 988,
"text": "Take an input data point and find the distance from all the records in our dataset. Store the distances in a list."
},
{
"code": null,
"e": 1206,
"s": 1103,
"text": "Sort the list containing the distances and check the labels for the first K records in the sorted list"
},
{
"code": null,
"e": 1285,
"s": 1206,
"text": "Classify the input as the label which occurred the most in the first K records"
},
{
"code": null,
"e": 1425,
"s": 1285,
"text": "First, we will create all the helper functions we will need. Then we will combine them and add some streamlit functions to build a web app."
},
{
"code": null,
"e": 1564,
"s": 1425,
"text": "For ease of understanding and visualization, we will be working with a dataset that has 2 features and has binary labels, i.e ‘0’ and ‘1’."
},
{
"code": null,
"e": 1774,
"s": 1564,
"text": "To normalize a list of values, we iterate over each value and find the difference between the value and minimum value in the list. We then divide it by the difference of maximum and minimum values in the list."
},
{
"code": null,
"e": 1971,
"s": 1774,
"text": "def min_max_normalize(lst): minimum = min(lst) maximum = max(lst) normalized = [(val - minimum)/(maximum - minimum) for val in lst] return normalized"
},
{
"code": null,
"e": 2044,
"s": 1971,
"text": "The function takes in a list of values and returns the normalized values"
},
{
"code": null,
"e": 2179,
"s": 2044,
"text": "This function will be used to calculate the distance between two given points. We will use Euclid's Formula to calculate the distance."
},
{
"code": null,
"e": 2349,
"s": 2179,
"text": "def distance(element1 , element2): x_distance = (element1[0] - element2[0])**2 y_distance = (element1[1] - element2[1])**2 return (x_distance + y_distance)**0.5"
},
{
"code": null,
"e": 2663,
"s": 2349,
"text": "The function takes in two 2D points and returns the Euclidean Distance between them. Since we are considering a dataset with only 2 features, we are only considering the x and y coordinates. As the number of features increases, this function will need to change to find the squared difference between all indices."
},
{
"code": null,
"e": 2832,
"s": 2663,
"text": "We iterate over each value in the dataset and use our distance function above to calculate the distance between the two points. We then store the distances and sort it."
},
{
"code": null,
"e": 3120,
"s": 2832,
"text": "def find_nearest(x , y , input , k): distances = [] for id,element in enumerate(x): distances.append([distance(input , element),id]) distances = sorted(distances) predicted_label = get_label(distances[0:k] , y) return predicted_label, distances[0:k] , distances[k:]"
},
{
"code": null,
"e": 3174,
"s": 3120,
"text": "The function takes the following parameters as input:"
},
{
"code": null,
"e": 3225,
"s": 3174,
"text": "x: This is our dataset containing the two features"
},
{
"code": null,
"e": 3333,
"s": 3225,
"text": "y: This contains the labels for each row in x. They are mapped respectively, i.e the label for x[i] is y[i]"
},
{
"code": null,
"e": 3421,
"s": 3333,
"text": "input: This is a 2D array which contains the features of the points we want to classify"
},
{
"code": null,
"e": 3486,
"s": 3421,
"text": "k: The number of nearest neighbour we want our model to consider"
},
{
"code": null,
"e": 3688,
"s": 3486,
"text": "First, we create an empty array to store the distances. We need to store the distance and the index of the record in the dataset. The index can be used in the y array to find the label for that record."
},
{
"code": null,
"e": 3814,
"s": 3688,
"text": "Then we sort the distances. Next, we use the get_label function (It will be discussed below) to get the most occurring label."
},
{
"code": null,
"e": 4035,
"s": 3814,
"text": "Since the distances array is sorted, the first k elements,i.e distances[0:k] are the k nearest neighbours to our input. We return the predicted label of our input, the k nearest neighbours and the rest of the neighbours."
},
{
"code": null,
"e": 4355,
"s": 4035,
"text": "We essentially get the k nearest neighbours, check the label for each. In our case, we have only two labels ‘0’ and ‘1’. If the label of a neighbour is ‘0’ we increment count for occurrences of ‘0’ and do the same for ‘1’. We compare the counts for occurrences of both labels and return the label with the higher count."
},
{
"code": null,
"e": 4661,
"s": 4355,
"text": "def get_label(neighbours, y): zero_count , one_count = 0,0 for element in neighbours: if y[element[1]] == 0: zero_count +=1 elif y[element[1]] == 1: one_count +=1 if zero_count == one_count: return y[neighbours[0][1]] return 1 if one_count > zero_count else 0"
},
{
"code": null,
"e": 4927,
"s": 4661,
"text": "The function takes the k nearest neighbours as the input. Each record in neighbours contains the distance from the input point and its original id. We use the id and the y array to get the label of the record. We then check the label and return the predicted label."
},
{
"code": null,
"e": 5054,
"s": 4927,
"text": "We have created the required Helper functions. Now we will combine them along with some streamlit functions. Exciting Stuff! 😎"
},
{
"code": null,
"e": 5253,
"s": 5054,
"text": "We will use Plotly to plot our graphs since Plotly plots interactive graphs. For our dataset, we will import a dataset from sklearn.datasets. We will also use the pandas library to create Datframes."
},
{
"code": null,
"e": 5394,
"s": 5253,
"text": "import streamlit as stimport pandas as pdfrom sklearn.datasets import make_blobsimport plotly.express as pximport plotly.graph_objects as go"
},
{
"code": null,
"e": 5449,
"s": 5394,
"text": "I will break the rest of the tutorial into three parts"
},
{
"code": null,
"e": 5527,
"s": 5449,
"text": "Input from UserImporting Dataset and Visualizing itVisualizing the Prediction"
},
{
"code": null,
"e": 5543,
"s": 5527,
"text": "Input from User"
},
{
"code": null,
"e": 5580,
"s": 5543,
"text": "Importing Dataset and Visualizing it"
},
{
"code": null,
"e": 5607,
"s": 5580,
"text": "Visualizing the Prediction"
},
{
"code": null,
"e": 5986,
"s": 5607,
"text": "We will use streamlit’s title method to display a title and slider method to create a numerical slider to get input from the user. Since our data is normalized, we expect the input to be normalized as well. Therefore we restrict the user to enter values between 0 and 1. We can also take input from the user and use minimum, maximum values in our dataset to normalize the input."
},
{
"code": null,
"e": 6256,
"s": 5986,
"text": "st.title(\"KNN Visualize\")x_input = st.slider(\"Choose X input\", min_value=0.0, max_value=1.0,key='x')y_input = st.slider(\"Choose Y input\", min_value=0.0, max_value=1.0,key='y')k = st.slider(\"Choose value of K\", min_value=1, max_value=10,key='k')input = (x_input,y_input)"
},
{
"code": null,
"e": 6401,
"s": 6256,
"text": "Every time the slider value is changed the entire python script is re-run and the variables will contain the new values according to the slider."
},
{
"code": null,
"e": 6485,
"s": 6401,
"text": "x , y = make_blobs(n_samples = 100 , n_features = 2 , centers = 2, random_state= 2)"
},
{
"code": null,
"e": 6777,
"s": 6485,
"text": "The make_blobs functions create a dataset for us which looks similar to the distribution in the graph above. In the real world, the dataset won’t be so co-operative but this dataset will suffice for now. I suggest you plot a scatter plot using matplotlib to see the distribution of the data."
},
{
"code": null,
"e": 6838,
"s": 6777,
"text": "x contains the features and y contains the respective labels"
},
{
"code": null,
"e": 7026,
"s": 6838,
"text": "# Normalizing Datax[:,0] = min_max_normalize(x[:,0])x[:,1] = min_max_normalize(x[:,1])# Dataframedf = pd.DataFrame(x , columns = ['Feature1' , 'Feature2'] )df['Label'] = yst.dataframe(df)"
},
{
"code": null,
"e": 7229,
"s": 7026,
"text": "First, we use the normalizing helper function we created before to normalize our data. Then we combine the x and y array to create a Dataframe. We use streamlit’s dataframe method to view the dataframe."
},
{
"code": null,
"e": 7470,
"s": 7229,
"text": "# Initial Data Plotfig = px.scatter(df, x = 'Feature1' , y='Feature2', symbol='Label',symbol_map={'0':'square-dot' , '1':'circle'})fig.add_trace( go.Scatter(x= [input[0]], y=[input[1]], name = \"Point to Classify\", ))st.plotly_chart(fig)"
},
{
"code": null,
"e": 7853,
"s": 7470,
"text": "You can read Plotly’s documentation for a better understanding of the above code. We create a figure with the scatter plot of the dataframe we just created. We also add our input point to better understand where it is located with respect to other points in the dataset. Streamlit’s plotly_chart method takes a Plotly figure as a parameter and plots an interactive graph on our app."
},
{
"code": null,
"e": 8047,
"s": 7853,
"text": "#Finding Nearest Neighbourspredicted_label , nearest_neighbours, far_neighbours = find_nearest(x ,y , input ,k)st.title('Prediction')st.subheader('Predicted Label : {}'.format(predicted_label))"
},
{
"code": null,
"e": 8197,
"s": 8047,
"text": "We use the find_nearest function we created earlier to get the predicted label and ids, distances of the k nearest neighbours and the far neighbours."
},
{
"code": null,
"e": 8260,
"s": 8197,
"text": "We display the predicted label us streamlit’s subheader method"
},
{
"code": null,
"e": 8544,
"s": 8260,
"text": "nearest_neighbours = [[neighbour[1],x[neighbour[1],0],x[neighbour[1],1],neighbour[0],y[neighbour[1]]] for neighbour in nearest_neighbours]nearest_neighbours = pd.DataFrame(nearest_neighbours , columns = ['id','Feature1','Feature2','Distance','Label'])st.dataframe(nearest_neighbours)"
},
{
"code": null,
"e": 8917,
"s": 8544,
"text": "The above code basically uses the id of the nearest neighbours and combines the id, distance with the feature1, feature2 values of the record and its label. We use the combined list to create a dataframe containing the information of the nearest neighbours. We then use streamlit’s dataframe method to display it. This dataframe will help us understand the graph below it."
},
{
"code": null,
"e": 9272,
"s": 8917,
"text": "far_neighbours = [[neighbour[1],x[neighbour[1],0],x[neighbour[1],1],neighbour[0],y[neighbour[1]]] for neighbour in far_neighbours]far_neighbours = pd.DataFrame(far_neighbours , columns = ['id','Feature1','Feature2','Distance','Label'])fig2 = px.scatter(far_neighbours,x='Feature1',y='Feature2',symbol='Label',symbol_map={'0':'square-dot' , '1':'circle'})"
},
{
"code": null,
"e": 9450,
"s": 9272,
"text": "We create a similar dataframe for the far neighbours. We use Plotly to plot a scatter plot. We will now add the input and lines connecting the input to its k nearest neighbours."
},
{
"code": null,
"e": 9721,
"s": 9450,
"text": "for index,neighbour in nearest_neighbours.iterrows(): fig2.add_trace( go.Scatter( x=[input[0], neighbour['Feature1']], y=[input[1], neighbour['Feature2']],mode='lines+markers' , name = 'id {}'.format(int(neighbour['id'])) ) )st.plotly_chart(fig2)"
},
{
"code": null,
"e": 9903,
"s": 9721,
"text": "We iterate over each of the neighbours and add a line between the neighbour and our input point to the figure we created. Finally, we use the plotly_chart method to plot the figure."
},
{
"code": null,
"e": 10011,
"s": 9903,
"text": "And That’s It 👏 We have a created a KNN classifier from scratch and created a Streamlit App to visualize it"
},
{
"code": null,
"e": 10089,
"s": 10011,
"text": "If you are interested in deploying your streamlit app, check out my tutorial."
},
{
"code": null,
"e": 10124,
"s": 10089,
"text": "You can find the GitHub repo here."
},
{
"code": null,
"e": 10308,
"s": 10124,
"text": "I am still fairly new to the world of Machine Learning, if you find any errors/mistakes or any piece of code which can be optimized, please let me know! I am always open to feedback 😃"
},
{
"code": null,
"e": 10389,
"s": 10308,
"text": "I recently created a blog using WordPress, I would love it if you check it out 😃"
},
{
"code": null,
"e": 10411,
"s": 10389,
"text": "realpythonproject.com"
},
{
"code": null,
"e": 10439,
"s": 10411,
"text": "Connect with me on LinkedIn"
},
{
"code": null,
"e": 10456,
"s": 10439,
"text": "www.linkedin.com"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.