title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to print calendar for a month in Python? | You can use the calender module to get the calender for a given month of a given year in Python. You need to provide the year and month as arguments.
import calendar
y = 2017
m = 11
print(calendar.month(y, m))
This will give the output −
November 2017
Mo Tu We Th Fr Sa Su
1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 | [
{
"code": null,
"e": 1213,
"s": 1062,
"text": "You can use the calender module to get the calender for a given month of a given year in Python. You need to provide the year and month as arguments. "
},
{
"code": null,
"e": 1273,
"s": 1213,
"text": "import calendar\ny = 2017\nm = 11\nprint(calendar.month(y, m))"
},
{
"code": null,
"e": 1301,
"s": 1273,
"text": "This will give the output −"
},
{
"code": null,
"e": 1435,
"s": 1301,
"text": " November 2017\nMo Tu We Th Fr Sa Su\n 1 2 3 4 5\n 6 7 8 9 10 11 12\n13 14 15 16 17 18 19\n20 21 22 23 24 25 26\n27 28 29 30"
}
] |
Rexx - do-until Loop | The do-until loop is a slight variation of the do while loop. This loop varies in the fact that is exits when the condition being evaluated is false.
The syntax of the do-until statement is as follows −
do until (condition)
statement #1
statement #2
...
end
The do-until statement is different from the do-while statement in the fact, that it will only execute the statements until the condition evaluated is true. If the condition is true, then the loop is exited.
The following diagram shows the diagrammatic explanation of this loop.
The key thing to note is that the code block runs till the condition in the do-until evaluates to false. As soon as the condition evaluates to true, the do loop exits.
The following program is an example of a do-until loop statement.
/* Main program */
j = 1
do until (j <= 10)
say j
j = j + 1
end
The output of the above code will be −
1
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2489,
"s": 2339,
"text": "The do-until loop is a slight variation of the do while loop. This loop varies in the fact that is exits when the condition being evaluated is false."
},
{
"code": null,
"e": 2542,
"s": 2489,
"text": "The syntax of the do-until statement is as follows −"
},
{
"code": null,
"e": 2611,
"s": 2542,
"text": "do until (condition) \n statement #1 \n statement #2 \n ... \nend\n"
},
{
"code": null,
"e": 2819,
"s": 2611,
"text": "The do-until statement is different from the do-while statement in the fact, that it will only execute the statements until the condition evaluated is true. If the condition is true, then the loop is exited."
},
{
"code": null,
"e": 2890,
"s": 2819,
"text": "The following diagram shows the diagrammatic explanation of this loop."
},
{
"code": null,
"e": 3058,
"s": 2890,
"text": "The key thing to note is that the code block runs till the condition in the do-until evaluates to false. As soon as the condition evaluates to true, the do loop exits."
},
{
"code": null,
"e": 3124,
"s": 3058,
"text": "The following program is an example of a do-until loop statement."
},
{
"code": null,
"e": 3200,
"s": 3124,
"text": "/* Main program */ \nj = 1 \n\ndo until (j <= 10) \n say j \n j = j + 1 \nend"
},
{
"code": null,
"e": 3239,
"s": 3200,
"text": "The output of the above code will be −"
},
{
"code": null,
"e": 3243,
"s": 3239,
"text": "1 \n"
},
{
"code": null,
"e": 3250,
"s": 3243,
"text": " Print"
},
{
"code": null,
"e": 3261,
"s": 3250,
"text": " Add Notes"
}
] |
Maximum Path Sum between 2 Leaf Nodes | Practice | GeeksforGeeks | Given a binary tree in which each node element contains a number. Find the maximum possible path sum from one leaf node to another leaf node.
Note: Here Leaf node is a node which is connected to exactly one different node.
Example 1:
Input:
3
/ \
4 5
/ \
-10 4
Output: 16
Explanation:
Maximum Sum lies between leaf node 4 and 5.
4 + 4 + 3 + 5 = 16.
Example 2:
Input:
-15
/ \
5 6
/ \ / \
-8 1 3 9
/ \ \
2 -3 0
/ \
4 -1
/
10
Output: 27
Explanation:
The maximum possible sum from one leaf node
to another is (3 + 6 + 9 + 0 + -1 + 10 = 27)
Your Task:
You dont need to read input or print anything. Complete the function maxPathSum() which takes root node as input parameter and returns the maximum sum between 2 leaf nodes.
Expected Time Complexity: O(N)
Expected Auxiliary Space: O(Height of Tree)
Constraints:
2 ≤ Number of nodes ≤ 104
-103 ≤ Value of each node ≤ 103
0
akashkhurana2820 hours ago
JAVA EASY SOLUTION
int sum=Integer.MIN_VALUE; int findMaxPathSum(Node root){ if(root==null)return 0; int lsum=findMaxPathSum(root.left); int rsum=findMaxPathSum(root.right); if(root.left== null && root.right==null)return root.data; if(root.left==null) return root.data+ rsum; if(root.right==null) return root.data+lsum; sum=Math.max(sum, root.data+lsum+rsum); return Math.max(root.data+lsum, root.data+rsum); } int maxPathSum(Node root) { int ans=findMaxPathSum(root); if(root.left==null || root.right==null) sum=Math.max(sum,ans); return sum; } }
0
saicharanthammi1 week ago
int help(Node * root,int &m) { if(!root) return 0; if(!root->left && !root->right) return root->data; int l=help(root->left,m); int r=help(root->right,m); if(root->left && root->right) { m=max(m, root->data + l +r); return root->data +max(l,r); } if(!root->left) return root->data +r; return root->data +l; } int maxPathSum(Node* root) { int maxi=INT_MIN;help(root,maxi); if(!root ||root->left==NULL || root->right==NULL) { int k=0; if(!root) return 0; if(!root->left) return max(maxi,root->data+help(root->right,k)); return max(maxi,root->data+help(root->left,k)); } return maxi; }
-1
goelyash4 weeks ago
Easy c++ solution
class Solution {public: int maxsum =INT_MIN;
int maxPathSumUtil(Node* root) { if(!root)return 0; int l = maxPathSumUtil(root->left); int r= maxPathSumUtil(root->right); if(root->left && root->right){ maxsum =max(maxsum,l+r+root->data); return root->data+max(l,r);} else if(root->left)return root->data+l; else return root->data+r; } int maxPathSum(Node* root){ int x= maxPathSumUtil(root); if(root->left && root->right)return maxsum; return max(maxsum,x); }};
0
aggarwaldeepali4541 month ago
int solve(Node *root, Node *par, int &ans){ if(root == NULL) return 0; if(root->left == NULL && root->right == NULL) return root->data; if(root->left == NULL){ int temp = solve(root->right, root, ans) + root->data; if(par == root) ans = max(temp, ans); return temp; } if(root->right == NULL){ int temp = solve(root->left, root, ans) + root->data; if(par == root) ans = max(ans, temp); return temp; } int l = solve(root->left,root, ans); int r = solve(root->right,root, ans); int temp = max(l, r) + root->data; ans = max(ans, root->data + l + r); return temp; }
int maxPathSum(Node* root) { int ans = INT_MIN; solve(root,root, ans); return ans; }
+1
harrypotter01 month ago
def maxPathSumUtil(root, res):
if root is None:
return 0
ls = maxPathSumUtil(root.left, res)
rs = maxPathSumUtil(root.right, res)
if root.left is not None and root.right is not None:
res[0] = max(res[0], ls + rs + root.data)
return max(ls, rs) + root.data
if root.left is None:
return rs + root.data
else:
return ls + root.data
return root.data+max(ls,rs)
class Solution:
def maxPathSum(self, root):
res = [-float('inf')]
ans = maxPathSumUtil(root, res)
if not root.left or not root.right:
res[0] = max(res[0], ans)
return res[0]
0
amishasahu3281 month ago
class Solution {
public:
int maxSum(Node *node, int &sum)
{
if(node == NULL) return 0;
int leftSum = maxSum(node->left, sum);
int rightSum = maxSum(node->right, sum);
if(!node->left && !node->right)
return node->data;
if(!node->left)
return node->data + rightSum;
if(!node->right)
return node->data + leftSum;
sum = max(sum, leftSum + rightSum + node->data);
return (node->data + max(leftSum, rightSum));
}
int maxPathSum(Node* root)
{
// code here
int sum = INT_MIN;
int ans = maxSum(root, sum);
// Here Leaf node is a node which is connected to exactly one different node.
// If root has only one child the it is also a leaf node
// hence, will be counted
if(!root->left || !root->right)
sum = max(sum, ans);
return sum;
}
};
+8
bishtayush20011 month ago
why the solution for this test case is 16 ?
5 N 6 -5 5
I think it would be 6 instead.
Infact the code given in editorial section failed at this point ...
-2
piyushsagar7251 month ago
class Solution{ int mx = -9999999; int maxPathSum(Node root) { maxPathSumUtil(root); return mx; } int maxPathSumUtil(Node root) { if (root == null) return 0; int l = maxPathSumUtil(root.left); int r = maxPathSumUtil(root.right); mx = Math.max(mx, l + root.data + r); if (l > r) return l + root.data; return r + root.data; }}
0
bishtkunal092 months ago
int solve(Node* root,int& res){ if(root==NULL){ return 0; } if(root->left==NULL&&root->right==NULL){ return root->data; } if(root->left==NULL){ return solve(root->right,res)+root->data; } if(root->right==NULL){ return solve(root->left,res)+root->data; } int l=solve(root->left,res); int r=solve(root->right,res); int temp=max(l,r)+root->data; int ans=l+r+root->data; res=max(res,ans); return temp; } int maxPathSum(Node* root) { int res=-1e9; int val=solve(root,res); ; if(res==-1e9){ return val; } return res; }
0
binnukaniki1232 months ago
class Solution{ int max=Integer.MIN_VALUE; int maxPathSum(Node root) { int p=m(root); if(max ==Integer.MIN_VALUE ) { return p; } return max; } int m(Node root){ if(root==null) return 0; int l=m(root.left); int r=m(root.right); if(root.left==null && root.right==null) return root.data; if(root.left==null )return r+root.data; if(root.right==null )return l+root.data; int p= l+r+root.data; if(max<p) max=p; if(l>r) return l+root.data; else return r+root.data; }}
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": 380,
"s": 238,
"text": "Given a binary tree in which each node element contains a number. Find the maximum possible path sum from one leaf node to another leaf node."
},
{
"code": null,
"e": 461,
"s": 380,
"text": "Note: Here Leaf node is a node which is connected to exactly one different node."
},
{
"code": null,
"e": 473,
"s": 461,
"text": "\nExample 1:"
},
{
"code": null,
"e": 754,
"s": 473,
"text": "Input: \n 3 \n / \\ \n 4 5 \n / \\ \n -10 4 \nOutput: 16\nExplanation:\nMaximum Sum lies between leaf node 4 and 5.\n4 + 4 + 3 + 5 = 16.\n"
},
{
"code": null,
"e": 765,
"s": 754,
"text": "Example 2:"
},
{
"code": null,
"e": 1216,
"s": 765,
"text": "Input: \n -15 \n / \\ \n 5 6 \n / \\ / \\\n -8 1 3 9\n / \\ \\\n 2 -3 0\n / \\\n 4 -1\n /\n 10 \nOutput: 27\nExplanation:\nThe maximum possible sum from one leaf node \nto another is (3 + 6 + 9 + 0 + -1 + 10 = 27)"
},
{
"code": null,
"e": 1403,
"s": 1216,
"text": "\nYour Task: \nYou dont need to read input or print anything. Complete the function maxPathSum() which takes root node as input parameter and returns the maximum sum between 2 leaf nodes."
},
{
"code": null,
"e": 1479,
"s": 1403,
"text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(Height of Tree)"
},
{
"code": null,
"e": 1556,
"s": 1479,
"text": "\nConstraints:\n2 ≤ Number of nodes ≤ 104\n-103 ≤ Value of each node ≤ 103"
},
{
"code": null,
"e": 1558,
"s": 1556,
"text": "0"
},
{
"code": null,
"e": 1585,
"s": 1558,
"text": "akashkhurana2820 hours ago"
},
{
"code": null,
"e": 1604,
"s": 1585,
"text": "JAVA EASY SOLUTION"
},
{
"code": null,
"e": 2319,
"s": 1604,
"text": "int sum=Integer.MIN_VALUE; int findMaxPathSum(Node root){ if(root==null)return 0; int lsum=findMaxPathSum(root.left); int rsum=findMaxPathSum(root.right); if(root.left== null && root.right==null)return root.data; if(root.left==null) return root.data+ rsum; if(root.right==null) return root.data+lsum; sum=Math.max(sum, root.data+lsum+rsum); return Math.max(root.data+lsum, root.data+rsum); } int maxPathSum(Node root) { int ans=findMaxPathSum(root); if(root.left==null || root.right==null) sum=Math.max(sum,ans); return sum; } }"
},
{
"code": null,
"e": 2321,
"s": 2319,
"text": "0"
},
{
"code": null,
"e": 2347,
"s": 2321,
"text": "saicharanthammi1 week ago"
},
{
"code": null,
"e": 3189,
"s": 2347,
"text": " int help(Node * root,int &m) { if(!root) return 0; if(!root->left && !root->right) return root->data; int l=help(root->left,m); int r=help(root->right,m); if(root->left && root->right) { m=max(m, root->data + l +r); return root->data +max(l,r); } if(!root->left) return root->data +r; return root->data +l; } int maxPathSum(Node* root) { int maxi=INT_MIN;help(root,maxi); if(!root ||root->left==NULL || root->right==NULL) { int k=0; if(!root) return 0; if(!root->left) return max(maxi,root->data+help(root->right,k)); return max(maxi,root->data+help(root->left,k)); } return maxi; }"
},
{
"code": null,
"e": 3192,
"s": 3189,
"text": "-1"
},
{
"code": null,
"e": 3212,
"s": 3192,
"text": "goelyash4 weeks ago"
},
{
"code": null,
"e": 3230,
"s": 3212,
"text": "Easy c++ solution"
},
{
"code": null,
"e": 3277,
"s": 3230,
"text": "class Solution {public: int maxsum =INT_MIN;"
},
{
"code": null,
"e": 3769,
"s": 3277,
"text": " int maxPathSumUtil(Node* root) { if(!root)return 0; int l = maxPathSumUtil(root->left); int r= maxPathSumUtil(root->right); if(root->left && root->right){ maxsum =max(maxsum,l+r+root->data); return root->data+max(l,r);} else if(root->left)return root->data+l; else return root->data+r; } int maxPathSum(Node* root){ int x= maxPathSumUtil(root); if(root->left && root->right)return maxsum; return max(maxsum,x); }};"
},
{
"code": null,
"e": 3771,
"s": 3769,
"text": "0"
},
{
"code": null,
"e": 3801,
"s": 3771,
"text": "aggarwaldeepali4541 month ago"
},
{
"code": null,
"e": 4605,
"s": 3801,
"text": "int solve(Node *root, Node *par, int &ans){ if(root == NULL) return 0; if(root->left == NULL && root->right == NULL) return root->data; if(root->left == NULL){ int temp = solve(root->right, root, ans) + root->data; if(par == root) ans = max(temp, ans); return temp; } if(root->right == NULL){ int temp = solve(root->left, root, ans) + root->data; if(par == root) ans = max(ans, temp); return temp; } int l = solve(root->left,root, ans); int r = solve(root->right,root, ans); int temp = max(l, r) + root->data; ans = max(ans, root->data + l + r); return temp; } "
},
{
"code": null,
"e": 4715,
"s": 4605,
"text": " int maxPathSum(Node* root) { int ans = INT_MIN; solve(root,root, ans); return ans; }"
},
{
"code": null,
"e": 4718,
"s": 4715,
"text": "+1"
},
{
"code": null,
"e": 4742,
"s": 4718,
"text": "harrypotter01 month ago"
},
{
"code": null,
"e": 5383,
"s": 4742,
"text": "def maxPathSumUtil(root, res):\n\n if root is None:\n return 0\n ls = maxPathSumUtil(root.left, res)\n rs = maxPathSumUtil(root.right, res)\n if root.left is not None and root.right is not None:\n\n res[0] = max(res[0], ls + rs + root.data)\n\n return max(ls, rs) + root.data\n\n if root.left is None:\n return rs + root.data\n else:\n return ls + root.data\n return root.data+max(ls,rs)\nclass Solution: \n def maxPathSum(self, root):\n res = [-float('inf')]\n ans = maxPathSumUtil(root, res)\n if not root.left or not root.right:\n res[0] = max(res[0], ans)\n return res[0]\n"
},
{
"code": null,
"e": 5385,
"s": 5383,
"text": "0"
},
{
"code": null,
"e": 5410,
"s": 5385,
"text": "amishasahu3281 month ago"
},
{
"code": null,
"e": 6338,
"s": 5410,
"text": "class Solution {\npublic:\n int maxSum(Node *node, int &sum)\n {\n if(node == NULL) return 0;\n int leftSum = maxSum(node->left, sum);\n int rightSum = maxSum(node->right, sum);\n if(!node->left && !node->right)\n return node->data;\n if(!node->left)\n return node->data + rightSum;\n if(!node->right)\n return node->data + leftSum;\n sum = max(sum, leftSum + rightSum + node->data);\n return (node->data + max(leftSum, rightSum));\n }\n int maxPathSum(Node* root)\n {\n // code here\n int sum = INT_MIN;\n int ans = maxSum(root, sum);\n // Here Leaf node is a node which is connected to exactly one different node.\n // If root has only one child the it is also a leaf node\n // hence, will be counted\n if(!root->left || !root->right)\n sum = max(sum, ans);\n return sum;\n }\n};"
},
{
"code": null,
"e": 6341,
"s": 6338,
"text": "+8"
},
{
"code": null,
"e": 6367,
"s": 6341,
"text": "bishtayush20011 month ago"
},
{
"code": null,
"e": 6412,
"s": 6367,
"text": "why the solution for this test case is 16 ? "
},
{
"code": null,
"e": 6423,
"s": 6412,
"text": "5 N 6 -5 5"
},
{
"code": null,
"e": 6456,
"s": 6425,
"text": "I think it would be 6 instead."
},
{
"code": null,
"e": 6525,
"s": 6456,
"text": "Infact the code given in editorial section failed at this point ... "
},
{
"code": null,
"e": 6528,
"s": 6525,
"text": "-2"
},
{
"code": null,
"e": 6554,
"s": 6528,
"text": "piyushsagar7251 month ago"
},
{
"code": null,
"e": 6989,
"s": 6554,
"text": "class Solution{ int mx = -9999999; int maxPathSum(Node root) { maxPathSumUtil(root); return mx; } int maxPathSumUtil(Node root) { if (root == null) return 0; int l = maxPathSumUtil(root.left); int r = maxPathSumUtil(root.right); mx = Math.max(mx, l + root.data + r); if (l > r) return l + root.data; return r + root.data; }}"
},
{
"code": null,
"e": 6991,
"s": 6989,
"text": "0"
},
{
"code": null,
"e": 7016,
"s": 6991,
"text": "bishtkunal092 months ago"
},
{
"code": null,
"e": 7718,
"s": 7016,
"text": "int solve(Node* root,int& res){ if(root==NULL){ return 0; } if(root->left==NULL&&root->right==NULL){ return root->data; } if(root->left==NULL){ return solve(root->right,res)+root->data; } if(root->right==NULL){ return solve(root->left,res)+root->data; } int l=solve(root->left,res); int r=solve(root->right,res); int temp=max(l,r)+root->data; int ans=l+r+root->data; res=max(res,ans); return temp; } int maxPathSum(Node* root) { int res=-1e9; int val=solve(root,res); ; if(res==-1e9){ return val; } return res; }"
},
{
"code": null,
"e": 7720,
"s": 7718,
"text": "0"
},
{
"code": null,
"e": 7747,
"s": 7720,
"text": "binnukaniki1232 months ago"
},
{
"code": null,
"e": 8352,
"s": 7747,
"text": "class Solution{ int max=Integer.MIN_VALUE; int maxPathSum(Node root) { int p=m(root); if(max ==Integer.MIN_VALUE ) { return p; } return max; } int m(Node root){ if(root==null) return 0; int l=m(root.left); int r=m(root.right); if(root.left==null && root.right==null) return root.data; if(root.left==null )return r+root.data; if(root.right==null )return l+root.data; int p= l+r+root.data; if(max<p) max=p; if(l>r) return l+root.data; else return r+root.data; }}"
},
{
"code": null,
"e": 8498,
"s": 8352,
"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": 8534,
"s": 8498,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 8544,
"s": 8534,
"text": "\nProblem\n"
},
{
"code": null,
"e": 8554,
"s": 8544,
"text": "\nContest\n"
},
{
"code": null,
"e": 8617,
"s": 8554,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8765,
"s": 8617,
"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": 8973,
"s": 8765,
"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": 9079,
"s": 8973,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Creating functional components in React.js | Components are building blocks of React library. There are two types of components.
Stateful component
Stateless component
Stateful component has a local state object which can be manipulated internally.
Stateless component does not have a local state object but we can add some state using React hooks in it.
const player = () => {
}
Here we used a const keyword to function name so that it does not get modified accidentally. Let's add a return statement with some jsx code.
const player = () => {
return (
<p>I'm a Player</p>
);
}
To work with jsx in JavaScript file we will have to import React like below
import React from 'react';
const player = () => {
return (
<p>I'm a Player</p>
);
}
Finally we have to export this function
export default player;
Now, we can use this functional component using below import statement.
Path to actual file may need to change depending upon relative location.
import Player from './Player'
If you have noticed there is no mention of file extension in above import statement. This is because build workflow automatically consider it as a js or jsx file type by default. If file is of different type then we will need to mention the extension of the file as well.
This Player functional component can be used in jsx element like −
<Player/>
This functional component can be used anywhere and multiple times as well. Its reusable component.
We have a below Player component
import React from 'react';
const player = () => {
return (
<p>I'm a Player</p>
);
}
export default player;
Player component is imported in app.js file
import React from 'react';
import logo from './logo.svg';
import './App.css';
import Player from './Player'
function App() {
return (
<div className="App">
<Player/>
<Player/>
<Player/>
</div>
);
}
export default App;
Now, suppose we want to display some random score for each player then we can do like below −
import React from 'react';
const player = () => {
return (
<p>I'm a Player: My score {Math.floor(Math.random() * 50)}</p>
);
}
export default player;
Once we save file, and run npm start on terminal from project directory.
To add dynamic content in jsx we can do it inside {} braces.
import React from 'react';
import './App.css';
import Player from './Player'
function App() {
return (
<div className="App">
<Player name="Smith" score="100"/>
<Player name="David" score="99">Plays for Australia </Player>
<Player name="Phil" score="80"/>
</div>
);
}
export default App;
We can add attributes to the Player element like above. To access the attributes in the functional component defined for Player, we have to pass an argument like below.
import React from 'react';
const player = (props) => {
return (
<p>I'm a Player: My name {props.name} and my score is {props.score}</p>
);
}
export default player;
Name of the argument to function can be different but it's a standard that we use props as a name for it. we access the attributes using props.name and props.score in {} braces
We have a children property on the player David, We can access it like below −
import React from 'react';
const player = (props) => {
return (
<div>
<p>I'm a Player: My name {props.name} and my score is {props.score}</p>
{props.children}
</div>
);
}
export default player;
The {props.children} property makes us access that text. | [
{
"code": null,
"e": 1146,
"s": 1062,
"text": "Components are building blocks of React library. There are two types of components."
},
{
"code": null,
"e": 1165,
"s": 1146,
"text": "Stateful component"
},
{
"code": null,
"e": 1185,
"s": 1165,
"text": "Stateless component"
},
{
"code": null,
"e": 1266,
"s": 1185,
"text": "Stateful component has a local state object which can be manipulated internally."
},
{
"code": null,
"e": 1372,
"s": 1266,
"text": "Stateless component does not have a local state object but we can add some state using React hooks in it."
},
{
"code": null,
"e": 1397,
"s": 1372,
"text": "const player = () => {\n}"
},
{
"code": null,
"e": 1539,
"s": 1397,
"text": "Here we used a const keyword to function name so that it does not get modified accidentally. Let's add a return statement with some jsx code."
},
{
"code": null,
"e": 1608,
"s": 1539,
"text": "const player = () => {\n return (\n <p>I'm a Player</p>\n );\n}"
},
{
"code": null,
"e": 1684,
"s": 1608,
"text": "To work with jsx in JavaScript file we will have to import React like below"
},
{
"code": null,
"e": 1780,
"s": 1684,
"text": "import React from 'react';\nconst player = () => {\n return (\n <p>I'm a Player</p>\n );\n}"
},
{
"code": null,
"e": 1820,
"s": 1780,
"text": "Finally we have to export this function"
},
{
"code": null,
"e": 1843,
"s": 1820,
"text": "export default player;"
},
{
"code": null,
"e": 1915,
"s": 1843,
"text": "Now, we can use this functional component using below import statement."
},
{
"code": null,
"e": 1988,
"s": 1915,
"text": "Path to actual file may need to change depending upon relative location."
},
{
"code": null,
"e": 2018,
"s": 1988,
"text": "import Player from './Player'"
},
{
"code": null,
"e": 2290,
"s": 2018,
"text": "If you have noticed there is no mention of file extension in above import statement. This is because build workflow automatically consider it as a js or jsx file type by default. If file is of different type then we will need to mention the extension of the file as well."
},
{
"code": null,
"e": 2357,
"s": 2290,
"text": "This Player functional component can be used in jsx element like −"
},
{
"code": null,
"e": 2367,
"s": 2357,
"text": "<Player/>"
},
{
"code": null,
"e": 2466,
"s": 2367,
"text": "This functional component can be used anywhere and multiple times as well. Its reusable component."
},
{
"code": null,
"e": 2499,
"s": 2466,
"text": "We have a below Player component"
},
{
"code": null,
"e": 2618,
"s": 2499,
"text": "import React from 'react';\nconst player = () => {\n return (\n <p>I'm a Player</p>\n );\n}\nexport default player;"
},
{
"code": null,
"e": 2662,
"s": 2618,
"text": "Player component is imported in app.js file"
},
{
"code": null,
"e": 2925,
"s": 2662,
"text": "import React from 'react';\nimport logo from './logo.svg';\nimport './App.css';\nimport Player from './Player'\nfunction App() {\n return (\n <div className=\"App\">\n <Player/>\n <Player/>\n <Player/>\n </div>\n );\n}\nexport default App;"
},
{
"code": null,
"e": 3019,
"s": 2925,
"text": "Now, suppose we want to display some random score for each player then we can do like below −"
},
{
"code": null,
"e": 3181,
"s": 3019,
"text": "import React from 'react';\nconst player = () => {\n return (\n <p>I'm a Player: My score {Math.floor(Math.random() * 50)}</p>\n );\n}\nexport default player;"
},
{
"code": null,
"e": 3254,
"s": 3181,
"text": "Once we save file, and run npm start on terminal from project directory."
},
{
"code": null,
"e": 3315,
"s": 3254,
"text": "To add dynamic content in jsx we can do it inside {} braces."
},
{
"code": null,
"e": 3647,
"s": 3315,
"text": "import React from 'react';\nimport './App.css';\nimport Player from './Player'\nfunction App() {\n return (\n <div className=\"App\">\n <Player name=\"Smith\" score=\"100\"/>\n <Player name=\"David\" score=\"99\">Plays for Australia </Player>\n <Player name=\"Phil\" score=\"80\"/>\n </div>\n );\n}\nexport default App;"
},
{
"code": null,
"e": 3816,
"s": 3647,
"text": "We can add attributes to the Player element like above. To access the attributes in the functional component defined for Player, we have to pass an argument like below."
},
{
"code": null,
"e": 3992,
"s": 3816,
"text": "import React from 'react';\nconst player = (props) => {\n return (\n <p>I'm a Player: My name {props.name} and my score is {props.score}</p>\n );\n}\nexport default player;"
},
{
"code": null,
"e": 4169,
"s": 3992,
"text": "Name of the argument to function can be different but it's a standard that we use props as a name for it. we access the attributes using props.name and props.score in {} braces"
},
{
"code": null,
"e": 4248,
"s": 4169,
"text": "We have a children property on the player David, We can access it like below −"
},
{
"code": null,
"e": 4478,
"s": 4248,
"text": "import React from 'react';\nconst player = (props) => {\n return (\n <div>\n <p>I'm a Player: My name {props.name} and my score is {props.score}</p>\n {props.children}\n </div>\n );\n}\nexport default player;"
},
{
"code": null,
"e": 4535,
"s": 4478,
"text": "The {props.children} property makes us access that text."
}
] |
Program to check if matrix is upper triangular - GeeksforGeeks | 26 Apr, 2021
Given a square matrix and the task is to check the matrix is in upper triangular form or not. A square matrix is called upper triangular if all the entries below the main diagonal are zero.
Examples:
Input : mat[4][4] = {{1, 3, 5, 3},
{0, 4, 6, 2},
{0, 0, 2, 5},
{0, 0, 0, 6}};
Output : Matrix is in Upper Triangular form.
Input : mat[4][4] = {{5, 6, 3, 6},
{0, 4, 6, 6},
{1, 0, 8, 5},
{0, 1, 0, 6}};
Output : Matrix is not in Upper Triangular form.
C++
Java
Python3
C#
PHP
Javascript
// Program to check upper triangular matrix.#include <bits/stdc++.h>#define N 4using namespace std; // Function to check matrix is in upper triangular// form or not.bool isUpperTriangularMatrix(int mat[N][N]){ for (int i = 1; i < N; i++) for (int j = 0; j < i; j++) if (mat[i][j] != 0) return false; return true;} // Driver function.int main(){ int mat[N][N] = { { 1, 3, 5, 3 }, { 0, 4, 6, 2 }, { 0, 0, 2, 5 }, { 0, 0, 0, 6 } }; if (isUpperTriangularMatrix(mat)) cout << "Yes"; else cout << "No"; return 0;}
// Java Program to check upper// triangular matrix.import java.util.*;import java.lang.*; public class GfG{ private static final int N = 4; // Function to check matrix is in // upper triangular form or not. public static Boolean isUpperTriangularMatrix(int mat[][]) { for (int i = 1; i < N ; i++) for (int j = 0; j < i; j++) if (mat[i][j] != 0) return false; return true; } // driver function public static void main(String argc[]){ int[][] mat= { { 1, 3, 5, 3 }, { 0, 4, 6, 2 }, { 0, 0, 2, 5 }, { 0, 0, 0, 6 } }; if (isUpperTriangularMatrix(mat)) System.out.println("Yes"); else System.out.println("No"); }} /* This code is contributed by Sagar Shukla */
# Python3 Program to check upper# triangular matrix. # Function to check matrix# is in upper triangulardef isuppertriangular(M): for i in range(1, len(M)): for j in range(0, i): if(M[i][j] != 0): return False return True # Driver function.M = [[1,3,5,3], [0,4,6,2], [0,0,2,5], [0,0,0,6]] if isuppertriangular(M): print ("Yes")else: print ("No") # This code is contributed by Anurag Rawat
// C# Program to check upper// triangular matrix.using System; public class GfG{ private static int N = 4; // Function to check matrix is in // upper triangular form or not. public static bool isUpperTriangularMatrix(int [,]mat) { for (int i = 1; i < N ; i++) for (int j = 0; j < i; j++) if (mat[i, j] != 0) return false; return true; } // Driver function public static void Main(){ int [,]mat= { { 1, 3, 5, 3 }, { 0, 4, 6, 2 }, { 0, 0, 2, 5 }, { 0, 0, 0, 6 } }; if (isUpperTriangularMatrix(mat)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} /* This code is contributed by vt_m */
<?php// PHP Program to check upper// triangular matrix.$N = 4; // Function to check matrix is// in upper triangular form or// not.function isUpperTriangularMatrix($mat){ global $N; for ($i = 1; $i < $N; $i++) for ($j = 0; $j < $i; $j++) if ($mat[$i][$j] != 0) return false; return true;} // Driver Code $mat = array(array(1, 3, 5, 3), array(0, 4, 6, 2) , array(0, 0, 2, 5), array(0, 0, 0, 6)); if (isUpperTriangularMatrix($mat)) echo "Yes"; else echo"No"; // This code is contributed by anuj_67.?>
<script>// Java script Program to check upper// triangular matrix.let N = 4; // Function to check matrix is in // upper triangular form or not. function isUpperTriangularMatrix(mat) { for (let i = 1; i < N ; i++) for (let j = 0; j < i; j++) if (mat[i][j] != 0) return false; return true; } // driver function let mat= [[1, 3, 5, 3 ], [ 0, 4, 6, 2 ], [ 0, 0, 2, 5 ], [ 0, 0, 0, 6 ]]; if (isUpperTriangularMatrix(mat)) document.write("Yes"); else document.write("No"); // contributed by sravan kumar</script>
Output:
Yes
vt_m
sravankumar8128
Matrix
School Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Sudoku | Backtracking-7
Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)
Program to multiply two matrices
Min Cost Path | DP-6
The Celebrity Problem
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 25083,
"s": 25055,
"text": "\n26 Apr, 2021"
},
{
"code": null,
"e": 25274,
"s": 25083,
"text": "Given a square matrix and the task is to check the matrix is in upper triangular form or not. A square matrix is called upper triangular if all the entries below the main diagonal are zero. "
},
{
"code": null,
"e": 25286,
"s": 25274,
"text": "Examples: "
},
{
"code": null,
"e": 25663,
"s": 25286,
"text": "Input : mat[4][4] = {{1, 3, 5, 3},\n {0, 4, 6, 2},\n {0, 0, 2, 5},\n {0, 0, 0, 6}};\nOutput : Matrix is in Upper Triangular form.\n\nInput : mat[4][4] = {{5, 6, 3, 6},\n {0, 4, 6, 6},\n {1, 0, 8, 5},\n {0, 1, 0, 6}};\nOutput : Matrix is not in Upper Triangular form."
},
{
"code": null,
"e": 25671,
"s": 25667,
"text": "C++"
},
{
"code": null,
"e": 25676,
"s": 25671,
"text": "Java"
},
{
"code": null,
"e": 25684,
"s": 25676,
"text": "Python3"
},
{
"code": null,
"e": 25687,
"s": 25684,
"text": "C#"
},
{
"code": null,
"e": 25691,
"s": 25687,
"text": "PHP"
},
{
"code": null,
"e": 25702,
"s": 25691,
"text": "Javascript"
},
{
"code": "// Program to check upper triangular matrix.#include <bits/stdc++.h>#define N 4using namespace std; // Function to check matrix is in upper triangular// form or not.bool isUpperTriangularMatrix(int mat[N][N]){ for (int i = 1; i < N; i++) for (int j = 0; j < i; j++) if (mat[i][j] != 0) return false; return true;} // Driver function.int main(){ int mat[N][N] = { { 1, 3, 5, 3 }, { 0, 4, 6, 2 }, { 0, 0, 2, 5 }, { 0, 0, 0, 6 } }; if (isUpperTriangularMatrix(mat)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 26338,
"s": 25702,
"text": null
},
{
"code": "// Java Program to check upper// triangular matrix.import java.util.*;import java.lang.*; public class GfG{ private static final int N = 4; // Function to check matrix is in // upper triangular form or not. public static Boolean isUpperTriangularMatrix(int mat[][]) { for (int i = 1; i < N ; i++) for (int j = 0; j < i; j++) if (mat[i][j] != 0) return false; return true; } // driver function public static void main(String argc[]){ int[][] mat= { { 1, 3, 5, 3 }, { 0, 4, 6, 2 }, { 0, 0, 2, 5 }, { 0, 0, 0, 6 } }; if (isUpperTriangularMatrix(mat)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} /* This code is contributed by Sagar Shukla */",
"e": 27216,
"s": 26338,
"text": null
},
{
"code": "# Python3 Program to check upper# triangular matrix. # Function to check matrix# is in upper triangulardef isuppertriangular(M): for i in range(1, len(M)): for j in range(0, i): if(M[i][j] != 0): return False return True # Driver function.M = [[1,3,5,3], [0,4,6,2], [0,0,2,5], [0,0,0,6]] if isuppertriangular(M): print (\"Yes\")else: print (\"No\") # This code is contributed by Anurag Rawat",
"e": 27666,
"s": 27216,
"text": null
},
{
"code": "// C# Program to check upper// triangular matrix.using System; public class GfG{ private static int N = 4; // Function to check matrix is in // upper triangular form or not. public static bool isUpperTriangularMatrix(int [,]mat) { for (int i = 1; i < N ; i++) for (int j = 0; j < i; j++) if (mat[i, j] != 0) return false; return true; } // Driver function public static void Main(){ int [,]mat= { { 1, 3, 5, 3 }, { 0, 4, 6, 2 }, { 0, 0, 2, 5 }, { 0, 0, 0, 6 } }; if (isUpperTriangularMatrix(mat)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} /* This code is contributed by vt_m */",
"e": 28474,
"s": 27666,
"text": null
},
{
"code": "<?php// PHP Program to check upper// triangular matrix.$N = 4; // Function to check matrix is// in upper triangular form or// not.function isUpperTriangularMatrix($mat){ global $N; for ($i = 1; $i < $N; $i++) for ($j = 0; $j < $i; $j++) if ($mat[$i][$j] != 0) return false; return true;} // Driver Code $mat = array(array(1, 3, 5, 3), array(0, 4, 6, 2) , array(0, 0, 2, 5), array(0, 0, 0, 6)); if (isUpperTriangularMatrix($mat)) echo \"Yes\"; else echo\"No\"; // This code is contributed by anuj_67.?>",
"e": 29106,
"s": 28474,
"text": null
},
{
"code": "<script>// Java script Program to check upper// triangular matrix.let N = 4; // Function to check matrix is in // upper triangular form or not. function isUpperTriangularMatrix(mat) { for (let i = 1; i < N ; i++) for (let j = 0; j < i; j++) if (mat[i][j] != 0) return false; return true; } // driver function let mat= [[1, 3, 5, 3 ], [ 0, 4, 6, 2 ], [ 0, 0, 2, 5 ], [ 0, 0, 0, 6 ]]; if (isUpperTriangularMatrix(mat)) document.write(\"Yes\"); else document.write(\"No\"); // contributed by sravan kumar</script>",
"e": 29837,
"s": 29106,
"text": null
},
{
"code": null,
"e": 29847,
"s": 29837,
"text": "Output: "
},
{
"code": null,
"e": 29851,
"s": 29847,
"text": "Yes"
},
{
"code": null,
"e": 29858,
"s": 29853,
"text": "vt_m"
},
{
"code": null,
"e": 29874,
"s": 29858,
"text": "sravankumar8128"
},
{
"code": null,
"e": 29881,
"s": 29874,
"text": "Matrix"
},
{
"code": null,
"e": 29900,
"s": 29881,
"text": "School Programming"
},
{
"code": null,
"e": 29907,
"s": 29900,
"text": "Matrix"
},
{
"code": null,
"e": 30005,
"s": 29907,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30014,
"s": 30005,
"text": "Comments"
},
{
"code": null,
"e": 30027,
"s": 30014,
"text": "Old Comments"
},
{
"code": null,
"e": 30051,
"s": 30027,
"text": "Sudoku | Backtracking-7"
},
{
"code": null,
"e": 30113,
"s": 30051,
"text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)"
},
{
"code": null,
"e": 30146,
"s": 30113,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 30167,
"s": 30146,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 30189,
"s": 30167,
"text": "The Celebrity Problem"
},
{
"code": null,
"e": 30207,
"s": 30189,
"text": "Python Dictionary"
},
{
"code": null,
"e": 30223,
"s": 30207,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 30242,
"s": 30223,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 30267,
"s": 30242,
"text": "Reverse a string in Java"
}
] |
ASP GetSpecialFolder Method - GeeksforGeeks | 03 Mar, 2021
The ASP GetSpecialFolder Method is used to return a reference to a specified special Folder.
Syntax:
FileSystemObject.GetSpecialFolder(foldername)
Parameter Values
FolderName: Required attribute. It specifies the name of the special folder to be returned. It contains a numeric value between 0 and 2 which represents three different types of folders as shown below.
0=WindowsFolder- Contains files installed by the Windows operating system
1=SystemFolder- Contains libraries, fonts, and device drivers.
2=TemporaryFolder- Used to store temporary files.
Example: Below code demonstrates the ASP GetSpecialFolder Method.
ASP
<%dim fs,pset fs=Server.CreateObject("Scripting.FileSystemObject")set p=fs.GetSpecialFolder(1)Response.Write(p)set p=nothingset fs=nothing%>
Output:
C:\WINNT\system32
ASP-Basics
ASP-Methods
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
How to fetch data from an API in ReactJS ?
Difference between var, let and const keywords in JavaScript
Convert a string to an integer in JavaScript
Differences between Functional Components and Class Components in React
How to redirect to another page in ReactJS ?
How to Insert Form Data into Database using PHP ?
How to pass data from child component to its parent in ReactJS ?
How to execute PHP code using command line ?
REST API (Introduction) | [
{
"code": null,
"e": 24525,
"s": 24497,
"text": "\n03 Mar, 2021"
},
{
"code": null,
"e": 24620,
"s": 24525,
"text": " The ASP GetSpecialFolder Method is used to return a reference to a specified special Folder. "
},
{
"code": null,
"e": 24628,
"s": 24620,
"text": "Syntax:"
},
{
"code": null,
"e": 24675,
"s": 24628,
"text": "FileSystemObject.GetSpecialFolder(foldername) "
},
{
"code": null,
"e": 24693,
"s": 24675,
"text": "Parameter Values "
},
{
"code": null,
"e": 24896,
"s": 24693,
"text": "FolderName: Required attribute. It specifies the name of the special folder to be returned. It contains a numeric value between 0 and 2 which represents three different types of folders as shown below. "
},
{
"code": null,
"e": 24970,
"s": 24896,
"text": "0=WindowsFolder- Contains files installed by the Windows operating system"
},
{
"code": null,
"e": 25033,
"s": 24970,
"text": "1=SystemFolder- Contains libraries, fonts, and device drivers."
},
{
"code": null,
"e": 25083,
"s": 25033,
"text": "2=TemporaryFolder- Used to store temporary files."
},
{
"code": null,
"e": 25151,
"s": 25083,
"text": "Example: Below code demonstrates the ASP GetSpecialFolder Method. "
},
{
"code": null,
"e": 25155,
"s": 25151,
"text": "ASP"
},
{
"code": "<%dim fs,pset fs=Server.CreateObject(\"Scripting.FileSystemObject\")set p=fs.GetSpecialFolder(1)Response.Write(p)set p=nothingset fs=nothing%>",
"e": 25296,
"s": 25155,
"text": null
},
{
"code": null,
"e": 25304,
"s": 25296,
"text": "Output:"
},
{
"code": null,
"e": 25322,
"s": 25304,
"text": "C:\\WINNT\\system32"
},
{
"code": null,
"e": 25333,
"s": 25322,
"text": "ASP-Basics"
},
{
"code": null,
"e": 25345,
"s": 25333,
"text": "ASP-Methods"
},
{
"code": null,
"e": 25362,
"s": 25345,
"text": "Web Technologies"
},
{
"code": null,
"e": 25460,
"s": 25362,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25469,
"s": 25460,
"text": "Comments"
},
{
"code": null,
"e": 25482,
"s": 25469,
"text": "Old Comments"
},
{
"code": null,
"e": 25538,
"s": 25482,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 25581,
"s": 25538,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 25642,
"s": 25581,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 25687,
"s": 25642,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 25759,
"s": 25687,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 25804,
"s": 25759,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 25854,
"s": 25804,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 25919,
"s": 25854,
"text": "How to pass data from child component to its parent in ReactJS ?"
},
{
"code": null,
"e": 25964,
"s": 25919,
"text": "How to execute PHP code using command line ?"
}
] |
What is a JAR file? | A java archive file is a file format/ archiving tool which contains all the components of an executable Java application. All the predefined libraries are available in this format.
To include any of these (other than rt.jar) in to your project you need to set the class path for this particular JAR file. You can create a JAR file using the command line options or using any IDE’s.
You can create a Jar file using the jar command as shown below.
jar cf jar-file input-file(s)
Let us consider an example, create a Sample Java program with name Sample.java
public class Sample {
public static void main(String args[]){
System.out.println("Hi welcome to Tutorialspoint");
}
}
If you compile this program using Javac command as shown below −
C:\Examples >javac Sample.java
This command compiles the given java file and generates a .class file (byte code)
Now, create a jar file for the generated class as −
C:\Sample>jar cvf sample.jar *.class
added manifest
adding: Sample.class(in = 434) (out= 302)(deflated 30%)
This will generate a jar file for all the classes in the current directory (since we used * instead of name) with specified name. | [
{
"code": null,
"e": 1243,
"s": 1062,
"text": "A java archive file is a file format/ archiving tool which contains all the components of an executable Java application. All the predefined libraries are available in this format."
},
{
"code": null,
"e": 1444,
"s": 1243,
"text": "To include any of these (other than rt.jar) in to your project you need to set the class path for this particular JAR file. You can create a JAR file using the command line options or using any IDE’s."
},
{
"code": null,
"e": 1508,
"s": 1444,
"text": "You can create a Jar file using the jar command as shown below."
},
{
"code": null,
"e": 1539,
"s": 1508,
"text": "jar cf jar-file input-file(s)\n"
},
{
"code": null,
"e": 1618,
"s": 1539,
"text": "Let us consider an example, create a Sample Java program with name Sample.java"
},
{
"code": null,
"e": 1748,
"s": 1618,
"text": "public class Sample {\n public static void main(String args[]){\n System.out.println(\"Hi welcome to Tutorialspoint\");\n }\n}"
},
{
"code": null,
"e": 1813,
"s": 1748,
"text": "If you compile this program using Javac command as shown below −"
},
{
"code": null,
"e": 1845,
"s": 1813,
"text": "C:\\Examples >javac Sample.java\n"
},
{
"code": null,
"e": 1927,
"s": 1845,
"text": "This command compiles the given java file and generates a .class file (byte code)"
},
{
"code": null,
"e": 1979,
"s": 1927,
"text": "Now, create a jar file for the generated class as −"
},
{
"code": null,
"e": 2088,
"s": 1979,
"text": "C:\\Sample>jar cvf sample.jar *.class\nadded manifest\nadding: Sample.class(in = 434) (out= 302)(deflated 30%)\n"
},
{
"code": null,
"e": 2218,
"s": 2088,
"text": "This will generate a jar file for all the classes in the current directory (since we used * instead of name) with specified name."
}
] |
Training a Snake Game AI: A Literature Review | by Thomas Hikaru Clark | Towards Data Science | You’ve probably played, or at least seen, the game of Snake before. The player controls a snake by pressing the arrow keys, and the snake has to maneuver around the screen, eating apples. With each apple eaten, the tail’s snake grows one unit. The goal is to eat as many apples as possible without running into a wall or the snake’s ever-increasing tail.
Building an AI agent to play Snake is a classic programming challenge, with many videos on YouTube showing various attempts using a wide range of techniques. In this article, I review the pros and cons of various approaches, and include links to the original sources. Broadly speaking, the approaches to an AI Snake agent belong to one of three categories: non-ML approaches, genetic algorithms, and reinforcement learning. There’s a lot to be learned from these topics, so let’s dive right in!
The game of Snake actually has a trivial, unbeatable solution. Create a cyclic path that goes through every square on the board without crossing itself (this is known as a Hamiltonian Cycle), and then just keep following this cyclical path until the snake’s head is as long as the entire path. This will work every time, but it is very boring and also wastes a lot of moves. In an NxN grid, it will take ~N2 apples to grow a tail long enough to fill the board. If the apples appear randomly, we would expect that the snake will need to pass through half the currently open squares to reach the apple from its current position, or around N2/2 moves at the start of the game. Since this number decreases as the snake gets longer, we expect that on average, the snake will need ~N4/4 moves to beat the game using this strategy. This is about 40,000 moves for a 20x20 board.
Several approaches I found on the Internet are essentially just optimizations on this naive first approach, finding clever ways to cut off bits of the cycle without trapping the snake, so that the apple can be reached in fewer moves. This involves dynamically cutting and restitching the Hamiltonian cycle to reach the apple quickly. One approach even implemented this on an old Nokia phone! There are other non-ML techniques for playing snake, such as using the A* algorithm to find the shortest path to the food, but unlike the Hamiltonian Cycle approach, this is not guaranteed to beat the game.
Pros: Guaranteed to beat the game, eventually.
Cons: No machine learning involved — the algorithm must be encoded by hand. Requires some familiarity with graph theory. Could be slow for large game boards.
The example below comes from AlphaPhoenix on YouTube.
Genetic algorithms are another popular approach to this type of problem. This approach is modeled off of biological evolution and natural selection. A machine learning model (could be a neural network, for example, but does not need to be) maps perceptual inputs to action outputs. An input might be the snake’s distance to obstacles in the four main directions (up, down, left, right). The output would be an action like turn left or turn right. Each instance of a model corresponds to an organism in the natural selection analogy, while the model’s parameters correspond to the organism’s genes.
To start, a bunch of random models (e.g. neural networks with random weights) are initialized in an environment and set loose. Once all the snakes (i.e. models) die, a fitness function selects the best individuals from a given generation. In the case of Snake, the fitness function would just pick snakes with the highest scores. A new generation is then bred from the best individuals, with the addition of random mutations (e.g. randomly tweaked network weights). Some of these mutations will hurt, some will not have any effect, and some will be beneficial. Over time, the evolutionary pressure will select for better and better models. To play around with and visualize learning via genetic algorithm, see this tool by Keiwan.
Pros: Easy concept to understand. Once the model is trained, predicting the next move is fast.
Cons: Can be slow to converge because mutations are random. The performance is dependent on the inputs available to the model. If the inputs only describe whether there are obstacles are in the immediate vicinity of the snake, then the snake isn’t aware of the “big picture” and is prone to getting trapped inside of its own tail.
The example below comes from Code Bullet, while another example by Greer Viau can also be found on YouTube.
Reinforcement learning is a fast-growing and exciting field of AI. At a very basic level, reinforcement learning involves an agent, an environment, a set of actions that the agent can take, and a reward function that rewards the agent for good actions or punishes the agent for bad actions. As the agent explores the environment, it updates its parameters to maximize its own expected reward. In the case of Snake, the agent is obviously the snake. The environment is the NxN board (with many possible states of this environment depending on where the food and the snake are located). The possible actions are turn left, turn right, and keep going straight.
Deep Reinforcement Learning (DRL) combines the above ideas of RL with deep neural networks. DRL has recently been used to build superhuman chess and Go systems, learn to play Atari games with only the pixels on the screen as input, and control robots.
Deep Q-Learning is a specific type of DRL. While it’s a bit tricky to grasp at first, the reasoning behind it is extremely elegant. The neural network learns the “Q function”, which takes as input the current environment state and outputs a vector containing expected rewards for each possible action. The agent can then pick the action that maximizes the Q function. Based on this action, the game then updates the environment to a new state and assigns a reward (e.g. +10 for eating an apple, -10 for hitting a wall). At the beginning of training, the Q function is just approximated by a randomly initialized neural network. Now, you might ask: what do we compare the output to in order to generate a loss and update the weights?
This is where the Bellman Equation comes in. This equation is used to provide an approximation for Q to guide the neural network in the right direction. As the network improves, the output of the Bellman Equation also improves. Crucially, there is recursion in the definition of the Q function (this is the Bellman variant I used for my program):
Q(state, action) = reward(state, action) + discount * max(Q(next_state, actions))
So the Q function is recursively defined as the reward for this move plus the Q function for the best possible next move. That term will then expand into the next reward plus the Q function for the following best move, and so on. As training progresses, this Q function (hopefully) approaches the true expected future reward of a given move. (Note the presence of a discount factor to give more weight to immediate rewards than expected but uncertain future rewards).
The cool thing about watching Snake AI train itself using Deep Q-Learning is that you can see its process of exploration and exploitation, happening live. In some games, the snake dies after 5 moves. This might be disappointing at first, but remember that this incurs a penalty, and the network will update itself to avoid similar moves in the future. In some games, the snake stays alive for a long time and amasses a long tail, earning lots of reward. Either way, the actions are either positively or negatively reinforced to teach the snake how to play better in the future.
To learn more about Q-learning, I highly recommend the introductory video by TheComputerScientist on YouTube. I also recommend the MIT lecture on Reinforcement Learning by Lex Fridman, also available on YouTube.
Pros: It’s a really cool and elegant concept. RL can be applied to many other tasks as well, and doesn’t require supervision beyond setting up the environment and reward system. In my experience, it converges faster than genetic algorithms because it can take advantage of gradient descent rather than mutating randomly.
Cons: A little mind-bending to understand at first. Like with the genetic algorithm, the model’s performance is dependent on what inputs are available to the network, and more inputs means more model parameters, which means longer to train.
The following video is Part 1 of an amazing 4-part tutorial by The Python Engineer on YouTube, which I highly recommend. The corresponding code can be found on GitHub.
The best way to learn is by doing. Following the tutorials/explanations linked above and implementing my own Snake AI taught me more about the topics at hand than any amount of reading or watching alone could have done. I encourage you to try it out for yourself, and consider adapting these methods to a different game, such as Pong, Asteroids, or Breakout. Thanks for reading!
[1] Hamiltonian path, https://en.wikipedia.org/wiki/Hamiltonian_path
[2] Greer Viau, Neural Network Learns to Play Snake, https://www.youtube.com/watch?v=zIkBYwdkuTk
[3] Bellman equation, https://en.wikipedia.org/wiki/Bellman_equation
[4] Evolution by Keiwan, https://keiwan.itch.io/evolution
[5] Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model, https://arxiv.org/pdf/1911.08265.pdf
[6] The Python Engineer, Teach AI to Play Snake, https://www.youtube.com/watch?v=PJl4iabBEz0&t=3s
[7] Code Bullet, AI Learns to Play Snake Using Genetic Algorithms and Deep Learning, https://www.youtube.com/watch?v=3bhP7zulFfY&t=18s
[8] Robot Control in Human Environment Using Deep Reinforcement Learning, https://ieeexplore.ieee.org/document/8961517
[9] Lex Fridman, MIT 6.S091: Introduction to Deep Reinforcement Learning (Deep RL), https://www.youtube.com/watch?v=zR11FLZ-O9M&t=3036s | [
{
"code": null,
"e": 526,
"s": 171,
"text": "You’ve probably played, or at least seen, the game of Snake before. The player controls a snake by pressing the arrow keys, and the snake has to maneuver around the screen, eating apples. With each apple eaten, the tail’s snake grows one unit. The goal is to eat as many apples as possible without running into a wall or the snake’s ever-increasing tail."
},
{
"code": null,
"e": 1021,
"s": 526,
"text": "Building an AI agent to play Snake is a classic programming challenge, with many videos on YouTube showing various attempts using a wide range of techniques. In this article, I review the pros and cons of various approaches, and include links to the original sources. Broadly speaking, the approaches to an AI Snake agent belong to one of three categories: non-ML approaches, genetic algorithms, and reinforcement learning. There’s a lot to be learned from these topics, so let’s dive right in!"
},
{
"code": null,
"e": 1892,
"s": 1021,
"text": "The game of Snake actually has a trivial, unbeatable solution. Create a cyclic path that goes through every square on the board without crossing itself (this is known as a Hamiltonian Cycle), and then just keep following this cyclical path until the snake’s head is as long as the entire path. This will work every time, but it is very boring and also wastes a lot of moves. In an NxN grid, it will take ~N2 apples to grow a tail long enough to fill the board. If the apples appear randomly, we would expect that the snake will need to pass through half the currently open squares to reach the apple from its current position, or around N2/2 moves at the start of the game. Since this number decreases as the snake gets longer, we expect that on average, the snake will need ~N4/4 moves to beat the game using this strategy. This is about 40,000 moves for a 20x20 board."
},
{
"code": null,
"e": 2491,
"s": 1892,
"text": "Several approaches I found on the Internet are essentially just optimizations on this naive first approach, finding clever ways to cut off bits of the cycle without trapping the snake, so that the apple can be reached in fewer moves. This involves dynamically cutting and restitching the Hamiltonian cycle to reach the apple quickly. One approach even implemented this on an old Nokia phone! There are other non-ML techniques for playing snake, such as using the A* algorithm to find the shortest path to the food, but unlike the Hamiltonian Cycle approach, this is not guaranteed to beat the game."
},
{
"code": null,
"e": 2538,
"s": 2491,
"text": "Pros: Guaranteed to beat the game, eventually."
},
{
"code": null,
"e": 2696,
"s": 2538,
"text": "Cons: No machine learning involved — the algorithm must be encoded by hand. Requires some familiarity with graph theory. Could be slow for large game boards."
},
{
"code": null,
"e": 2750,
"s": 2696,
"text": "The example below comes from AlphaPhoenix on YouTube."
},
{
"code": null,
"e": 3348,
"s": 2750,
"text": "Genetic algorithms are another popular approach to this type of problem. This approach is modeled off of biological evolution and natural selection. A machine learning model (could be a neural network, for example, but does not need to be) maps perceptual inputs to action outputs. An input might be the snake’s distance to obstacles in the four main directions (up, down, left, right). The output would be an action like turn left or turn right. Each instance of a model corresponds to an organism in the natural selection analogy, while the model’s parameters correspond to the organism’s genes."
},
{
"code": null,
"e": 4079,
"s": 3348,
"text": "To start, a bunch of random models (e.g. neural networks with random weights) are initialized in an environment and set loose. Once all the snakes (i.e. models) die, a fitness function selects the best individuals from a given generation. In the case of Snake, the fitness function would just pick snakes with the highest scores. A new generation is then bred from the best individuals, with the addition of random mutations (e.g. randomly tweaked network weights). Some of these mutations will hurt, some will not have any effect, and some will be beneficial. Over time, the evolutionary pressure will select for better and better models. To play around with and visualize learning via genetic algorithm, see this tool by Keiwan."
},
{
"code": null,
"e": 4174,
"s": 4079,
"text": "Pros: Easy concept to understand. Once the model is trained, predicting the next move is fast."
},
{
"code": null,
"e": 4505,
"s": 4174,
"text": "Cons: Can be slow to converge because mutations are random. The performance is dependent on the inputs available to the model. If the inputs only describe whether there are obstacles are in the immediate vicinity of the snake, then the snake isn’t aware of the “big picture” and is prone to getting trapped inside of its own tail."
},
{
"code": null,
"e": 4613,
"s": 4505,
"text": "The example below comes from Code Bullet, while another example by Greer Viau can also be found on YouTube."
},
{
"code": null,
"e": 5271,
"s": 4613,
"text": "Reinforcement learning is a fast-growing and exciting field of AI. At a very basic level, reinforcement learning involves an agent, an environment, a set of actions that the agent can take, and a reward function that rewards the agent for good actions or punishes the agent for bad actions. As the agent explores the environment, it updates its parameters to maximize its own expected reward. In the case of Snake, the agent is obviously the snake. The environment is the NxN board (with many possible states of this environment depending on where the food and the snake are located). The possible actions are turn left, turn right, and keep going straight."
},
{
"code": null,
"e": 5523,
"s": 5271,
"text": "Deep Reinforcement Learning (DRL) combines the above ideas of RL with deep neural networks. DRL has recently been used to build superhuman chess and Go systems, learn to play Atari games with only the pixels on the screen as input, and control robots."
},
{
"code": null,
"e": 6256,
"s": 5523,
"text": "Deep Q-Learning is a specific type of DRL. While it’s a bit tricky to grasp at first, the reasoning behind it is extremely elegant. The neural network learns the “Q function”, which takes as input the current environment state and outputs a vector containing expected rewards for each possible action. The agent can then pick the action that maximizes the Q function. Based on this action, the game then updates the environment to a new state and assigns a reward (e.g. +10 for eating an apple, -10 for hitting a wall). At the beginning of training, the Q function is just approximated by a randomly initialized neural network. Now, you might ask: what do we compare the output to in order to generate a loss and update the weights?"
},
{
"code": null,
"e": 6603,
"s": 6256,
"text": "This is where the Bellman Equation comes in. This equation is used to provide an approximation for Q to guide the neural network in the right direction. As the network improves, the output of the Bellman Equation also improves. Crucially, there is recursion in the definition of the Q function (this is the Bellman variant I used for my program):"
},
{
"code": null,
"e": 6689,
"s": 6603,
"text": "Q(state, action) = reward(state, action) + discount * max(Q(next_state, actions))"
},
{
"code": null,
"e": 7157,
"s": 6689,
"text": "So the Q function is recursively defined as the reward for this move plus the Q function for the best possible next move. That term will then expand into the next reward plus the Q function for the following best move, and so on. As training progresses, this Q function (hopefully) approaches the true expected future reward of a given move. (Note the presence of a discount factor to give more weight to immediate rewards than expected but uncertain future rewards)."
},
{
"code": null,
"e": 7735,
"s": 7157,
"text": "The cool thing about watching Snake AI train itself using Deep Q-Learning is that you can see its process of exploration and exploitation, happening live. In some games, the snake dies after 5 moves. This might be disappointing at first, but remember that this incurs a penalty, and the network will update itself to avoid similar moves in the future. In some games, the snake stays alive for a long time and amasses a long tail, earning lots of reward. Either way, the actions are either positively or negatively reinforced to teach the snake how to play better in the future."
},
{
"code": null,
"e": 7947,
"s": 7735,
"text": "To learn more about Q-learning, I highly recommend the introductory video by TheComputerScientist on YouTube. I also recommend the MIT lecture on Reinforcement Learning by Lex Fridman, also available on YouTube."
},
{
"code": null,
"e": 8268,
"s": 7947,
"text": "Pros: It’s a really cool and elegant concept. RL can be applied to many other tasks as well, and doesn’t require supervision beyond setting up the environment and reward system. In my experience, it converges faster than genetic algorithms because it can take advantage of gradient descent rather than mutating randomly."
},
{
"code": null,
"e": 8509,
"s": 8268,
"text": "Cons: A little mind-bending to understand at first. Like with the genetic algorithm, the model’s performance is dependent on what inputs are available to the network, and more inputs means more model parameters, which means longer to train."
},
{
"code": null,
"e": 8677,
"s": 8509,
"text": "The following video is Part 1 of an amazing 4-part tutorial by The Python Engineer on YouTube, which I highly recommend. The corresponding code can be found on GitHub."
},
{
"code": null,
"e": 9056,
"s": 8677,
"text": "The best way to learn is by doing. Following the tutorials/explanations linked above and implementing my own Snake AI taught me more about the topics at hand than any amount of reading or watching alone could have done. I encourage you to try it out for yourself, and consider adapting these methods to a different game, such as Pong, Asteroids, or Breakout. Thanks for reading!"
},
{
"code": null,
"e": 9125,
"s": 9056,
"text": "[1] Hamiltonian path, https://en.wikipedia.org/wiki/Hamiltonian_path"
},
{
"code": null,
"e": 9222,
"s": 9125,
"text": "[2] Greer Viau, Neural Network Learns to Play Snake, https://www.youtube.com/watch?v=zIkBYwdkuTk"
},
{
"code": null,
"e": 9291,
"s": 9222,
"text": "[3] Bellman equation, https://en.wikipedia.org/wiki/Bellman_equation"
},
{
"code": null,
"e": 9349,
"s": 9291,
"text": "[4] Evolution by Keiwan, https://keiwan.itch.io/evolution"
},
{
"code": null,
"e": 9461,
"s": 9349,
"text": "[5] Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model, https://arxiv.org/pdf/1911.08265.pdf"
},
{
"code": null,
"e": 9559,
"s": 9461,
"text": "[6] The Python Engineer, Teach AI to Play Snake, https://www.youtube.com/watch?v=PJl4iabBEz0&t=3s"
},
{
"code": null,
"e": 9694,
"s": 9559,
"text": "[7] Code Bullet, AI Learns to Play Snake Using Genetic Algorithms and Deep Learning, https://www.youtube.com/watch?v=3bhP7zulFfY&t=18s"
},
{
"code": null,
"e": 9813,
"s": 9694,
"text": "[8] Robot Control in Human Environment Using Deep Reinforcement Learning, https://ieeexplore.ieee.org/document/8961517"
}
] |
Angular forms FormGroupName Directive - GeeksforGeeks | 04 Jul, 2021
In this article, we are going to see what is FormGroupName in Angular 10 and how to use it. The FormGroupName is used to sync a nested FormGroup to a DOM element.
Syntax:
<form [FormGroupName] ="details">
Exported from:
ReactiveFormsModule
Selectors:
[FormGroupName]
Approach:
Create the Angular app to be used
In app.component.ts make an object that contain value for the input.
In app.component.html use FormGroupName to get values.
Serve the angular app using ng serve to see the output.
Example:
app.component.ts
import { Component, Inject } from '@angular/core'; import { FormGroup, FormControl, FormArray } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { form = new FormGroup({ details: new FormGroup({ name: new FormControl(), email: new FormControl() }) }); get name(): any { return this.form.get('details.name'); } get email(): any { return this.form.get('details.email'); } onSubmit(): void { console.log(this.form.value); } }
app.module.ts
import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule ]})export class AppModule { }
app.component.html
<br><form [formGroup]="form" (ngSubmit)="onSubmit()"> <div formGroupName="details"> <input formControlName="name" placeholder="Name"> <input formControlName="email" placeholder="Email"> </div> <br> <button type='submit'>Submit</button> <br><br></form>
Output:
Reference: https://angular.io/api/forms/FormGroupName
Angular10
AngularJS-Directives
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Properties of Fourier Transform
Univariate, Bivariate and Multivariate data and its analysis
Spatial Filtering and its Types
Advantages and Disadvantages of OOP
Lex Program to count number of words
Introduction to Internet of Things (IoT) | Set 1
Consensus Algorithms in Blockchain
Characteristics of Internet of Things
Transmission Impairment in Data Communication
Advantages and Disadvantages of E-mail | [
{
"code": null,
"e": 24568,
"s": 24540,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 24731,
"s": 24568,
"text": "In this article, we are going to see what is FormGroupName in Angular 10 and how to use it. The FormGroupName is used to sync a nested FormGroup to a DOM element."
},
{
"code": null,
"e": 24739,
"s": 24731,
"text": "Syntax:"
},
{
"code": null,
"e": 24773,
"s": 24739,
"text": "<form [FormGroupName] =\"details\">"
},
{
"code": null,
"e": 24788,
"s": 24773,
"text": "Exported from:"
},
{
"code": null,
"e": 24808,
"s": 24788,
"text": "ReactiveFormsModule"
},
{
"code": null,
"e": 24819,
"s": 24808,
"text": "Selectors:"
},
{
"code": null,
"e": 24835,
"s": 24819,
"text": "[FormGroupName]"
},
{
"code": null,
"e": 24848,
"s": 24837,
"text": "Approach: "
},
{
"code": null,
"e": 24882,
"s": 24848,
"text": "Create the Angular app to be used"
},
{
"code": null,
"e": 24951,
"s": 24882,
"text": "In app.component.ts make an object that contain value for the input."
},
{
"code": null,
"e": 25006,
"s": 24951,
"text": "In app.component.html use FormGroupName to get values."
},
{
"code": null,
"e": 25062,
"s": 25006,
"text": "Serve the angular app using ng serve to see the output."
},
{
"code": null,
"e": 25071,
"s": 25062,
"text": "Example:"
},
{
"code": null,
"e": 25088,
"s": 25071,
"text": "app.component.ts"
},
{
"code": "import { Component, Inject } from '@angular/core'; import { FormGroup, FormControl, FormArray } from '@angular/forms' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent { form = new FormGroup({ details: new FormGroup({ name: new FormControl(), email: new FormControl() }) }); get name(): any { return this.form.get('details.name'); } get email(): any { return this.form.get('details.email'); } onSubmit(): void { console.log(this.form.value); } }",
"e": 25711,
"s": 25088,
"text": null
},
{
"code": null,
"e": 25725,
"s": 25711,
"text": "app.module.ts"
},
{
"code": "import { NgModule } from '@angular/core'; // Importing forms moduleimport { FormsModule, ReactiveFormsModule } from '@angular/forms';import { BrowserModule } from '@angular/platform-browser';import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { AppComponent } from './app.component'; @NgModule({ bootstrap: [ AppComponent ], declarations: [ AppComponent ], imports: [ FormsModule, BrowserModule, BrowserAnimationsModule, ReactiveFormsModule ]})export class AppModule { }",
"e": 26272,
"s": 25725,
"text": null
},
{
"code": null,
"e": 26291,
"s": 26272,
"text": "app.component.html"
},
{
"code": "<br><form [formGroup]=\"form\" (ngSubmit)=\"onSubmit()\"> <div formGroupName=\"details\"> <input formControlName=\"name\" placeholder=\"Name\"> <input formControlName=\"email\" placeholder=\"Email\"> </div> <br> <button type='submit'>Submit</button> <br><br></form>",
"e": 26558,
"s": 26291,
"text": null
},
{
"code": null,
"e": 26566,
"s": 26558,
"text": "Output:"
},
{
"code": null,
"e": 26620,
"s": 26566,
"text": "Reference: https://angular.io/api/forms/FormGroupName"
},
{
"code": null,
"e": 26630,
"s": 26620,
"text": "Angular10"
},
{
"code": null,
"e": 26651,
"s": 26630,
"text": "AngularJS-Directives"
},
{
"code": null,
"e": 26656,
"s": 26651,
"text": "Misc"
},
{
"code": null,
"e": 26661,
"s": 26656,
"text": "Misc"
},
{
"code": null,
"e": 26666,
"s": 26661,
"text": "Misc"
},
{
"code": null,
"e": 26764,
"s": 26666,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26773,
"s": 26764,
"text": "Comments"
},
{
"code": null,
"e": 26786,
"s": 26773,
"text": "Old Comments"
},
{
"code": null,
"e": 26818,
"s": 26786,
"text": "Properties of Fourier Transform"
},
{
"code": null,
"e": 26879,
"s": 26818,
"text": "Univariate, Bivariate and Multivariate data and its analysis"
},
{
"code": null,
"e": 26911,
"s": 26879,
"text": "Spatial Filtering and its Types"
},
{
"code": null,
"e": 26947,
"s": 26911,
"text": "Advantages and Disadvantages of OOP"
},
{
"code": null,
"e": 26984,
"s": 26947,
"text": "Lex Program to count number of words"
},
{
"code": null,
"e": 27033,
"s": 26984,
"text": "Introduction to Internet of Things (IoT) | Set 1"
},
{
"code": null,
"e": 27068,
"s": 27033,
"text": "Consensus Algorithms in Blockchain"
},
{
"code": null,
"e": 27106,
"s": 27068,
"text": "Characteristics of Internet of Things"
},
{
"code": null,
"e": 27152,
"s": 27106,
"text": "Transmission Impairment in Data Communication"
}
] |
Age - GeeksforGeeks | 23 Apr, 2019
Let the ages of children be x, (x+4),
(x+8) and (x+12) years.
Then x + x + 4 + x + 8 + x +12 = 36
4x + 24 = 36
4x = 12
x = 3
Age of the youngest child = x = 3 years
Let C’s age be x years then B’s age be 3x
years and A’s age be (3x+5) years
Therefore x + 3x + (3x + 5) = 40
7x + 5 = 40
7x = 35
x = 5
Then (3x+5) / (4x+5) = 7 / 9
∴ 9(3x + 5) = 7(4x + 5)
∴ 27x + 45 = 28x + 35
∴ x = 10
∴ Ashok’s present age = 4x = 40 years
Let the present age of son and father be x years and 3x years respectively.
Then (3x + 15) = 2(x + 15)
∴ 3x + 15 = 2x + 30
∴ x = 15
∴ Son’s present age = x = 15 years.
Let the present age of son and father be x years and 3x years respectively.
Then (3x + 15) = 2(x + 15)
∴ 3x + 15 = 2x + 30
∴ x = 15
∴ Son’s present age = x = 15 years.
Let the present age of Ram and Shyam be 6x years and 5x years respectively.
Then 5x + 7 = 32
∴ 5x = 25
∴ x = 5
∴ Present age of Ram = 6x = 30 years
Then (4x-9) + (5x-9) + (9x-9) =45
∴ 18x – 27 = 45
∴ 18x = 72
∴ x = 4
Then (3x + 12) = 2( x + 12)
∴ 3x + 12 = 2x + 24
∴ x = 12
∴ Present age of mother = 3x = 36 years
A – B = C – A
∴ 2A = B + C
And also given that B + C = 68
∴ 2A = 68
∴ A = 34
Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
Must Do Coding Questions for Product Based Companies
Difference between var, let and const keywords in JavaScript
Array of Objects in C++ with Examples
How to Replace Values in Column Based on Condition in Pandas?
C Program to read contents of Whole File
How to Replace Values in a List in Python?
How to Read Text Files with Pandas?
How to Read Text File Into List in Python?
Python Data Structures and Algorithms
How to Change Axis Scales in R Plots? | [
{
"code": null,
"e": 27610,
"s": 27582,
"text": "\n23 Apr, 2019"
},
{
"code": null,
"e": 27859,
"s": 27610,
"text": "Let the ages of children be x, (x+4), \n(x+8) and (x+12) years.\n\nThen x + x + 4 + x + 8 + x +12 = 36\n 4x + 24 = 36\n 4x = 12\n x = 3\nAge of the youngest child = x = 3 years"
},
{
"code": null,
"e": 28072,
"s": 27859,
"text": "Let C’s age be x years then B’s age be 3x\nyears and A’s age be (3x+5) years\n\nTherefore x + 3x + (3x + 5) = 40\n 7x + 5 = 40\n 7x = 35\n x = 5"
},
{
"code": null,
"e": 28198,
"s": 28072,
"text": "Then (3x+5) / (4x+5) = 7 / 9 \n\n∴ 9(3x + 5) = 7(4x + 5)\n∴ 27x + 45 = 28x + 35\n∴ x = 10\n∴ Ashok’s present age = 4x = 40 years "
},
{
"code": null,
"e": 28369,
"s": 28198,
"text": "Let the present age of son and father be x years and 3x years respectively.\n\nThen (3x + 15) = 2(x + 15)\n\n∴ 3x + 15 = 2x + 30\n∴ x = 15\n∴ Son’s present age = x = 15 years. "
},
{
"code": null,
"e": 28540,
"s": 28369,
"text": "Let the present age of son and father be x years and 3x years respectively.\n\nThen (3x + 15) = 2(x + 15)\n\n∴ 3x + 15 = 2x + 30\n∴ x = 15\n∴ Son’s present age = x = 15 years. "
},
{
"code": null,
"e": 28701,
"s": 28540,
"text": "Let the present age of Ram and Shyam be 6x years and 5x years respectively.\n\nThen 5x + 7 = 32\n∴ 5x = 25\n∴ x = 5\n∴ Present age of Ram = 6x = 30 years"
},
{
"code": null,
"e": 28770,
"s": 28701,
"text": "Then (4x-9) + (5x-9) + (9x-9) =45\n∴ 18x – 27 = 45\n∴ 18x = 72\n∴ x = 4"
},
{
"code": null,
"e": 28868,
"s": 28770,
"text": "Then (3x + 12) = 2( x + 12)\n∴ 3x + 12 = 2x + 24\n∴ x = 12\n∴ Present age of mother = 3x = 36 years "
},
{
"code": null,
"e": 28949,
"s": 28868,
"text": "A – B = C – A\n∴ 2A = B + C\nAnd also given that B + C = 68\n∴ 2A = 68\n∴ A = 34 \n"
},
{
"code": null,
"e": 29047,
"s": 28949,
"text": "Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here."
},
{
"code": null,
"e": 29100,
"s": 29047,
"text": "Must Do Coding Questions for Product Based Companies"
},
{
"code": null,
"e": 29161,
"s": 29100,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 29199,
"s": 29161,
"text": "Array of Objects in C++ with Examples"
},
{
"code": null,
"e": 29261,
"s": 29199,
"text": "How to Replace Values in Column Based on Condition in Pandas?"
},
{
"code": null,
"e": 29302,
"s": 29261,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 29345,
"s": 29302,
"text": "How to Replace Values in a List in Python?"
},
{
"code": null,
"e": 29381,
"s": 29345,
"text": "How to Read Text Files with Pandas?"
},
{
"code": null,
"e": 29424,
"s": 29381,
"text": "How to Read Text File Into List in Python?"
},
{
"code": null,
"e": 29462,
"s": 29424,
"text": "Python Data Structures and Algorithms"
}
] |
Find the largest number smaller than integer N with maximum number of set bits - GeeksforGeeks | 17 Nov, 2021
Given an integer N, the task is to find the largest number smaller than N having the maximum number of set bits.Examples:
Input : N = 345 Output : 255 Explanation: 345 in binary representation is 101011001 with 5 set bits, and 255 is 11111111 with maximum number of set bits less than the integer N.Input : N = 2 Output : 1 Explanation: 2 in binary representation is 10 with 1 set bit, and 1 has maximum number of set bits less than the integer N.
Naive Approach:The naive way to solve the above problem is to iterate till the integer N and find the number of set bits of each number and store the number having the largest set bits at each step.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to Find the// largest number smaller than integer// N with maximum number of set bits#include <bits/stdc++.h>using namespace std; // Function to return the largest// number less than Nint largestNum(int n){ int num = 0; int max_setBits = 0; // Iterate through all the numbers for (int i = 0; i <= n; i++) { // Find the number of set bits // for the current number int setBits = __builtin_popcount(i); // Check if this number has the // highest set bits if (setBits >= max_setBits) { num = i; max_setBits = setBits; } } // Return the result return num;} // Driver codeint main(){ int N = 345; cout << largestNum(N); return 0;}
// Java implementation to Find the// largest number smaller than integer// N with maximum number of set bitsclass GFG{ /* Function to get no of set bits in binary representation of positive integer n */ static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } // Function to return the largest // number less than N static int largestNum(int n) { int num = 0; int max_setBits = 0; // Iterate through all the numbers for (int i = 0; i <= n; i++) { // Find the number of set bits // for the current number int setBits = countSetBits(i); // Check if this number has the // highest set bits if (setBits >= max_setBits) { num = i; max_setBits = setBits; } } // Return the result return num; } // Driver code public static void main (String[] args) { int N = 345; System.out.println(largestNum(N)); }} // This code is contributed by AnkitRai01
# Python3 implementation to find the# largest number smaller than integer# N with maximum number of set bits # Function to return the largest# number less than Ndef largestNum(n): num = 0; max_setBits = 0; # Iterate through all the numbers for i in range(n + 1): # Find the number of set bits # for the current number setBits = bin(i).count('1'); # Check if this number has the # highest set bits if (setBits >= max_setBits): num = i; max_setBits = setBits; # Return the result return num; # Driver codeif __name__ == "__main__" : N = 345; print(largestNum(N)); # This code is contributed by AnkitRai01
// C# implementation to Find the// largest number smaller than integer// N with a maximum number of set bitsusing System; class GFG{ // Function to get no of set// bits in binary representation// of positive integer nstatic int countSetBits(int n){ int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count;} // Function to return the largest// number less than Nstatic int largestNum(int n){ int num = 0; int max_setBits = 0; // Iterate through all the numbers for(int i = 0; i <= n; i++) { // Find the number of set bits // for the current number int setBits = countSetBits(i); // Check if this number has // the highest set bits if (setBits >= max_setBits) { num = i; max_setBits = setBits; } } // Return the result return num;} // Driver codepublic static void Main(String[] args){ int N = 345; Console.Write(largestNum(N));}} // This code is contributed by shivanisinghss2110
<script> // Javascript implementation to Find the // largest number smaller than integer // N with a maximum number of set bits // Function to get no of set // bits in binary representation // of positive integer n function countSetBits(n) { let count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } // Function to return the largest // number less than N function largestNum(n) { let num = 0; let max_setBits = 0; // Iterate through all the numbers for(let i = 0; i <= n; i++) { // Find the number of set bits // for the current number let setBits = countSetBits(i); // Check if this number has // the highest set bits if (setBits >= max_setBits) { num = i; max_setBits = setBits; } } // Return the result return num; } let N = 345; document.write(largestNum(N)); </script>
255
Time Complexity: O(n)
Auxiliary Space: O(1)
Efficient Approach: To optimize the above solution we have to observe that the number with the highest set bits will surely be of form 2k – 1. So we only need to iterate over the possible values of k and find the highest value just less than the integer N. Since we are iterating over the exponent variable therefore at most log(N) steps will be required.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation to Find the// largest number smaller than integer// N with maximum number of set bits#include <bits/stdc++.h>using namespace std; // Function to return the largest// number less than Nint largestNum(int n){ int num = 0; // Iterate through all possible values for (int i = 0; i <= 32; i++) { // Multiply the number by 2 i times int x = (1 << i); if ((x - 1) <= n) num = (1 << i) - 1; else break; } // Return the final result return num;} // Driver codeint main(){ int N = 345; cout << largestNum(N); return 0;}
// Java implementation to Find the// largest number smaller than integer// N with maximum number of set bitsimport java.util.*;class GFG{ // Function to return the largest// number less than Nstatic int largestNum(int n){ int num = 0; // Iterate through all possible values for (int i = 0; i <= 32; i++) { // Multiply the number by 2 i times int x = (1 << i); if ((x - 1) <= n) num = (1 << i) - 1; else break; } // Return the final result return num;} // Driver codepublic static void main(String args[]){ int N = 345; System.out.print(largestNum(N));}} // This code is contributed by Akanksha_Rai
# Python3 implementation to find the# largest number smaller than integer# N with the maximum number of set bits # Function to return the largest# number less than Ndef largestNum(n): num = 0; # Iterate through all possible # values for i in range(32): # Multiply the number by # 2 i times x = (1 << i); if ((x - 1) <= n): num = (1 << i) - 1; else: break; # Return the final result return num; # Driver codeif __name__ == "__main__": N = 345; print(largestNum(N)); # This code is contributed by AnkitRai01
// C# implementation to Find the// largest number smaller than integer// N with maximum number of set bitsusing System;class GFG{ // Function to return the largest// number less than Nstatic int largestNum(int n){ int num = 0; // Iterate through all possible values for (int i = 0; i <= 32; i++) { // Multiply the number by 2 i times int x = (1 << i); if ((x - 1) <= n) num = (1 << i) - 1; else break; } // Return the final result return num;} // Driver codepublic static void Main(){ int N = 345; Console.Write(largestNum(N));}} // This code is contributed by Nidhi_Biet
<script> // Javascript implementation to Find the // largest number smaller than integer // N with maximum number of set bits // Function to return the largest // number less than N function largestNum(n) { let num = 0; // Iterate through all possible values for (let i = 0; i <= 32; i++) { // Multiply the number by 2 i times let x = (1 << i); if ((x - 1) <= n) num = (1 << i) - 1; else break; } // Return the final result return num; } let N = 345; document.write(largestNum(N)); // This code is contributed by suresh07.</script>
255
Time Complexity: O(log N)
Auxiliary Space: O(1)
ankthon
nidhi_biet
Akanksha_Rai
shivanisinghss2110
divyesh072019
suresh07
souravmahato348
Bit Magic
Greedy
Mathematical
Greedy
Mathematical
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Cyclic Redundancy Check and Modulo-2 Division
Program to find parity
Bit Fields in C
Little and Big Endian Mystery
Bits manipulation (Important tactics)
Dijkstra's shortest path algorithm | Greedy Algo-7
Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5
Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2
Write a program to print all permutations of a given string
Program for array rotation | [
{
"code": null,
"e": 25559,
"s": 25531,
"text": "\n17 Nov, 2021"
},
{
"code": null,
"e": 25682,
"s": 25559,
"text": "Given an integer N, the task is to find the largest number smaller than N having the maximum number of set bits.Examples: "
},
{
"code": null,
"e": 26010,
"s": 25682,
"text": "Input : N = 345 Output : 255 Explanation: 345 in binary representation is 101011001 with 5 set bits, and 255 is 11111111 with maximum number of set bits less than the integer N.Input : N = 2 Output : 1 Explanation: 2 in binary representation is 10 with 1 set bit, and 1 has maximum number of set bits less than the integer N. "
},
{
"code": null,
"e": 26262,
"s": 26012,
"text": "Naive Approach:The naive way to solve the above problem is to iterate till the integer N and find the number of set bits of each number and store the number having the largest set bits at each step.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26266,
"s": 26262,
"text": "C++"
},
{
"code": null,
"e": 26271,
"s": 26266,
"text": "Java"
},
{
"code": null,
"e": 26279,
"s": 26271,
"text": "Python3"
},
{
"code": null,
"e": 26282,
"s": 26279,
"text": "C#"
},
{
"code": null,
"e": 26293,
"s": 26282,
"text": "Javascript"
},
{
"code": "// C++ implementation to Find the// largest number smaller than integer// N with maximum number of set bits#include <bits/stdc++.h>using namespace std; // Function to return the largest// number less than Nint largestNum(int n){ int num = 0; int max_setBits = 0; // Iterate through all the numbers for (int i = 0; i <= n; i++) { // Find the number of set bits // for the current number int setBits = __builtin_popcount(i); // Check if this number has the // highest set bits if (setBits >= max_setBits) { num = i; max_setBits = setBits; } } // Return the result return num;} // Driver codeint main(){ int N = 345; cout << largestNum(N); return 0;}",
"e": 27049,
"s": 26293,
"text": null
},
{
"code": "// Java implementation to Find the// largest number smaller than integer// N with maximum number of set bitsclass GFG{ /* Function to get no of set bits in binary representation of positive integer n */ static int countSetBits(int n) { int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } // Function to return the largest // number less than N static int largestNum(int n) { int num = 0; int max_setBits = 0; // Iterate through all the numbers for (int i = 0; i <= n; i++) { // Find the number of set bits // for the current number int setBits = countSetBits(i); // Check if this number has the // highest set bits if (setBits >= max_setBits) { num = i; max_setBits = setBits; } } // Return the result return num; } // Driver code public static void main (String[] args) { int N = 345; System.out.println(largestNum(N)); }} // This code is contributed by AnkitRai01",
"e": 28276,
"s": 27049,
"text": null
},
{
"code": "# Python3 implementation to find the# largest number smaller than integer# N with maximum number of set bits # Function to return the largest# number less than Ndef largestNum(n): num = 0; max_setBits = 0; # Iterate through all the numbers for i in range(n + 1): # Find the number of set bits # for the current number setBits = bin(i).count('1'); # Check if this number has the # highest set bits if (setBits >= max_setBits): num = i; max_setBits = setBits; # Return the result return num; # Driver codeif __name__ == \"__main__\" : N = 345; print(largestNum(N)); # This code is contributed by AnkitRai01",
"e": 28974,
"s": 28276,
"text": null
},
{
"code": "// C# implementation to Find the// largest number smaller than integer// N with a maximum number of set bitsusing System; class GFG{ // Function to get no of set// bits in binary representation// of positive integer nstatic int countSetBits(int n){ int count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count;} // Function to return the largest// number less than Nstatic int largestNum(int n){ int num = 0; int max_setBits = 0; // Iterate through all the numbers for(int i = 0; i <= n; i++) { // Find the number of set bits // for the current number int setBits = countSetBits(i); // Check if this number has // the highest set bits if (setBits >= max_setBits) { num = i; max_setBits = setBits; } } // Return the result return num;} // Driver codepublic static void Main(String[] args){ int N = 345; Console.Write(largestNum(N));}} // This code is contributed by shivanisinghss2110",
"e": 30046,
"s": 28974,
"text": null
},
{
"code": "<script> // Javascript implementation to Find the // largest number smaller than integer // N with a maximum number of set bits // Function to get no of set // bits in binary representation // of positive integer n function countSetBits(n) { let count = 0; while (n > 0) { count += n & 1; n >>= 1; } return count; } // Function to return the largest // number less than N function largestNum(n) { let num = 0; let max_setBits = 0; // Iterate through all the numbers for(let i = 0; i <= n; i++) { // Find the number of set bits // for the current number let setBits = countSetBits(i); // Check if this number has // the highest set bits if (setBits >= max_setBits) { num = i; max_setBits = setBits; } } // Return the result return num; } let N = 345; document.write(largestNum(N)); </script>",
"e": 31130,
"s": 30046,
"text": null
},
{
"code": null,
"e": 31134,
"s": 31130,
"text": "255"
},
{
"code": null,
"e": 31158,
"s": 31136,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 31180,
"s": 31158,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 31588,
"s": 31180,
"text": "Efficient Approach: To optimize the above solution we have to observe that the number with the highest set bits will surely be of form 2k – 1. So we only need to iterate over the possible values of k and find the highest value just less than the integer N. Since we are iterating over the exponent variable therefore at most log(N) steps will be required.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 31592,
"s": 31588,
"text": "C++"
},
{
"code": null,
"e": 31597,
"s": 31592,
"text": "Java"
},
{
"code": null,
"e": 31605,
"s": 31597,
"text": "Python3"
},
{
"code": null,
"e": 31608,
"s": 31605,
"text": "C#"
},
{
"code": null,
"e": 31619,
"s": 31608,
"text": "Javascript"
},
{
"code": "// C++ implementation to Find the// largest number smaller than integer// N with maximum number of set bits#include <bits/stdc++.h>using namespace std; // Function to return the largest// number less than Nint largestNum(int n){ int num = 0; // Iterate through all possible values for (int i = 0; i <= 32; i++) { // Multiply the number by 2 i times int x = (1 << i); if ((x - 1) <= n) num = (1 << i) - 1; else break; } // Return the final result return num;} // Driver codeint main(){ int N = 345; cout << largestNum(N); return 0;}",
"e": 32238,
"s": 31619,
"text": null
},
{
"code": "// Java implementation to Find the// largest number smaller than integer// N with maximum number of set bitsimport java.util.*;class GFG{ // Function to return the largest// number less than Nstatic int largestNum(int n){ int num = 0; // Iterate through all possible values for (int i = 0; i <= 32; i++) { // Multiply the number by 2 i times int x = (1 << i); if ((x - 1) <= n) num = (1 << i) - 1; else break; } // Return the final result return num;} // Driver codepublic static void main(String args[]){ int N = 345; System.out.print(largestNum(N));}} // This code is contributed by Akanksha_Rai",
"e": 32918,
"s": 32238,
"text": null
},
{
"code": "# Python3 implementation to find the# largest number smaller than integer# N with the maximum number of set bits # Function to return the largest# number less than Ndef largestNum(n): num = 0; # Iterate through all possible # values for i in range(32): # Multiply the number by # 2 i times x = (1 << i); if ((x - 1) <= n): num = (1 << i) - 1; else: break; # Return the final result return num; # Driver codeif __name__ == \"__main__\": N = 345; print(largestNum(N)); # This code is contributed by AnkitRai01",
"e": 33512,
"s": 32918,
"text": null
},
{
"code": "// C# implementation to Find the// largest number smaller than integer// N with maximum number of set bitsusing System;class GFG{ // Function to return the largest// number less than Nstatic int largestNum(int n){ int num = 0; // Iterate through all possible values for (int i = 0; i <= 32; i++) { // Multiply the number by 2 i times int x = (1 << i); if ((x - 1) <= n) num = (1 << i) - 1; else break; } // Return the final result return num;} // Driver codepublic static void Main(){ int N = 345; Console.Write(largestNum(N));}} // This code is contributed by Nidhi_Biet",
"e": 34166,
"s": 33512,
"text": null
},
{
"code": "<script> // Javascript implementation to Find the // largest number smaller than integer // N with maximum number of set bits // Function to return the largest // number less than N function largestNum(n) { let num = 0; // Iterate through all possible values for (let i = 0; i <= 32; i++) { // Multiply the number by 2 i times let x = (1 << i); if ((x - 1) <= n) num = (1 << i) - 1; else break; } // Return the final result return num; } let N = 345; document.write(largestNum(N)); // This code is contributed by suresh07.</script>",
"e": 34872,
"s": 34166,
"text": null
},
{
"code": null,
"e": 34876,
"s": 34872,
"text": "255"
},
{
"code": null,
"e": 34904,
"s": 34878,
"text": "Time Complexity: O(log N)"
},
{
"code": null,
"e": 34927,
"s": 34904,
"text": "Auxiliary Space: O(1) "
},
{
"code": null,
"e": 34935,
"s": 34927,
"text": "ankthon"
},
{
"code": null,
"e": 34946,
"s": 34935,
"text": "nidhi_biet"
},
{
"code": null,
"e": 34959,
"s": 34946,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 34978,
"s": 34959,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 34992,
"s": 34978,
"text": "divyesh072019"
},
{
"code": null,
"e": 35001,
"s": 34992,
"text": "suresh07"
},
{
"code": null,
"e": 35017,
"s": 35001,
"text": "souravmahato348"
},
{
"code": null,
"e": 35027,
"s": 35017,
"text": "Bit Magic"
},
{
"code": null,
"e": 35034,
"s": 35027,
"text": "Greedy"
},
{
"code": null,
"e": 35047,
"s": 35034,
"text": "Mathematical"
},
{
"code": null,
"e": 35054,
"s": 35047,
"text": "Greedy"
},
{
"code": null,
"e": 35067,
"s": 35054,
"text": "Mathematical"
},
{
"code": null,
"e": 35077,
"s": 35067,
"text": "Bit Magic"
},
{
"code": null,
"e": 35175,
"s": 35077,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35184,
"s": 35175,
"text": "Comments"
},
{
"code": null,
"e": 35197,
"s": 35184,
"text": "Old Comments"
},
{
"code": null,
"e": 35243,
"s": 35197,
"text": "Cyclic Redundancy Check and Modulo-2 Division"
},
{
"code": null,
"e": 35266,
"s": 35243,
"text": "Program to find parity"
},
{
"code": null,
"e": 35282,
"s": 35266,
"text": "Bit Fields in C"
},
{
"code": null,
"e": 35312,
"s": 35282,
"text": "Little and Big Endian Mystery"
},
{
"code": null,
"e": 35350,
"s": 35312,
"text": "Bits manipulation (Important tactics)"
},
{
"code": null,
"e": 35401,
"s": 35350,
"text": "Dijkstra's shortest path algorithm | Greedy Algo-7"
},
{
"code": null,
"e": 35452,
"s": 35401,
"text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5"
},
{
"code": null,
"e": 35510,
"s": 35452,
"text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2"
},
{
"code": null,
"e": 35570,
"s": 35510,
"text": "Write a program to print all permutations of a given string"
}
] |
Mathematical Analysis of Reinforcement Learning — Bellman Optimality Equation | by Vaibhav Kumar | Towards Data Science | Reinforcement learning has achieved remarkable results in playing games like StarCraft (AlphaStar) and Go (AlphaGO). At the core of all these successful projects lies — The Bellman optimality equation for Markov decision processes (MDPs).
The Bellman optimality equation is a recursive equation that can be solved using dynamic programming (DP) algorithms to find the optimal value function and the optimal policy. In this article, I will try to explain why the Bellman optimality equation can solve every MDP by providing an optimal policy and perform an easy (hopefully) mathematical analysis of the same.
S is state space.
V is the value function.
V* is the optimal value function.
V(s) is the value of state s.
π is a policy.
π* is the optimal policy.
π(s) returns the action for state s under the policy π.
P is the transition probability matrix.
A is the action space.
Despite my best efforts, the analysis is going to be fairly rigorous and I assume the readers to be familiar with the following perquisites:
Markov decision process (MDP)Bellman Equation and how it’s solved using iterative methods.Basics of RL — Value functions, rewards, policies, discount factor etc.Linear algebraVector calculus
Markov decision process (MDP)
Bellman Equation and how it’s solved using iterative methods.
Basics of RL — Value functions, rewards, policies, discount factor etc.
Linear algebra
Vector calculus
If you have studied RL and MDPs, you must’ve encountered the claim: “For each MDP, there is always at least one policy that is better than or equal to all other policies.” This occurs both in Sutton and Barto’s book as well as in the lecture series by David Silver. Reading/Hearing this makes the claim pretty intuitive, however, I had to dig in deeper and understand this in a more concrete manner. Therefore, in this article, I will mathematically prove the following theorem:
Theorem: For any finite MDP, there exists an optimal policy π* such that it is better than or equal to every other possible policy π.
Before finding the best policy, we need to understand the ordering of policies. When is one policy (π1) considered better than the other (π2)?
If the value of a state derived using π1 is better than or equal the value of a state derived using π2 for every state in the environment, then the policy π1 is said to be better than policy π2. Mathematically, this can be written as follows:
Now that we know how to compare policies, we need to prove that there always exists a policy that is better than all other policies.
We are going to prove this using the Banach fixed point theorem by showing that the Bellman optimality operator is a contraction over a complete metric space of real numbers with metric L-infinity norm. For this, we will first discuss the fixed point problem and complete metric spaces with respect to the Cauchy sequence.
The above paragraph sounds very intimidating but its actually going to be pretty easy and intuitive once we get past the basic terminologies. We will be discussing everything that is in bold in the above paragraph. Let’s follow a bottom-up approach and learn each concept and conquer our fears:
I am sure most of us are familiar with the problem of finding the roots of an equation. We solve for x such that a function f(x) = 0. However, in a fixed point problem, we solve for x such that f(x) = x. As the name suggests, x is a fixed point, it does not change even on the application of the function. A fixed point problem can be converted into a problem of finding roots by forming another function g(x) = f(x)-x = 0. In fact, even root finding problems can also be converted back to fixed point problems. However, it’s really easy to solve fixed point problems (for special cases) and that is what makes them incredibly interesting and useful (sans the computational overhead).
To solve a fixed point problem, choose a random starting value of x and repeatedly apply f(x) infinite times. If the function is convergent and you’re lucky, you will find the solution.
Mathematically, it’s pretty simple, lets first describe a notation:
Now, if the function is convergent then it must converge to some value, say, x*. This value, x* is indeed the solution to the fixed point problem as shown below:
Let's choose some arbitrary value x0 and apply the function f(.) on x0 for infinite times to get x*, and then use that to solve the fixed point problem:
The intuition behind this is pretty simple, if a function has converged at some point then the value of this function at that convergent point will be the convergent point itself. Therefore, the convergent point is the fixed point itself.
This can also be observed empirically through the notebook below:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import warnings
warnings.simplefilter("ignore")
def f(x):
return np.sin(x)/x
def plot(lower=-1, upper=200):
ys, xs = [], []
plt.figure(figsize=(6, 4))
for x in range(lower, upper):
try:
ys.append(f(x))
xs.append(x)
except:
continue
plt.xlabel("x")
plt.ylabel("f(x)")
plt.plot(xs, ys)
plt.show()
plot()
The function above is clearly converging
Note: Instead of infinity, we just apply it 10000 times
def fixed_point(INF = 10000):
x0 = np.random.randn()
for _ in range(INF):
x0 = f(x0)
return x0
solution = fixed_point()
print(solution)
0.8767262153950625
def verify(solution):
print(f"Values of function: f{f(solution)} | Value of x: {solution}")
if f(solution) == solution:
return True
verify(solution)
Values of function: f0.8767262153950625 | Value of x: 0.8767262153950625
True
A metric space is simply a set with a metric defined to measure the distance between any two elements of the set. For example, the Euclidean space is a metric space with distance defined as the Euclidean distance in the set of real numbers. Therefore, a metric space M is represented as (X, d) where X is the set and d is some sort of metric. The metric d must satisfy the following properties:
Identify d(x,x) = 0Non-Negativity d(x, y) >0Symmetry: d(x,y) = d(y,x)Triangular inequality: d(x,z) ≤ d(x,y)+d(y,z)
Identify d(x,x) = 0
Non-Negativity d(x, y) >0
Symmetry: d(x,y) = d(y,x)
Triangular inequality: d(x,z) ≤ d(x,y)+d(y,z)
For a metric space (X, d) the sequence of elements of the set X, (x1, x2, x3.... xn) is a Cauchy sequence if, for every positive real number ε, there exists an integer N such that the following equation holds:
The mathematical explanation here isn’t very intuitive and needlessly complex. In simple words, a sequence of elements of a metric space is Cauchy if this sequence converges at some point (the distance between them becomes constant). Another great explanation for this is given by this website and goes as follows: “for any small distance, there is a certain index past which any two terms are within that distance of each other, which captures the intuitive idea of the terms becoming close.” The idea of “terms become close” is the basic intuition behind convergence or the limit of the series.
A metric space (X, d) is complete if every possible Cauchy sequence of the elements in the set X converges to an element that also belongs to the set X. That is to say, the convergent limit of every Cauchy sequence of the elements of set lies in the set itself. Which is why it’s called “complete”.
A function (or operator or mapping) defined on the elements of the metric space (X, d) is a contraction (or contractor) if there exists some constant γ∈[0,1) such that for any two elements of the metric space x1 and x2, the following condition holds:
This means that after applying the mapping f(.) on the elements x1 and x2, they got closer to each other by at least a factor γ. Also, the smallest value of such a constant γ is called the Lipschitz constant (this is an important constant for generative adversarial networks). Also, if γ=1, the mapping is no more a contraction but rather a short mapping. Intuitively, it can be observed that the sequential values of the elements are getting closer after applying the contraction mapping.
This is the heart and soul of our proof. Informally, this theorem says that for a complete metric space, the application of a contractor on the elements of the set, again and again, would eventually get us to an optimal, unique value. We know:
Contractors bring the elements of the set together.Applying this contractor, again and again, would get us a sequence. (Cauchy?)The Cauchy sequences in a complete metric space always converge to a value that is part of the metric space.
Contractors bring the elements of the set together.
Applying this contractor, again and again, would get us a sequence. (Cauchy?)
The Cauchy sequences in a complete metric space always converge to a value that is part of the metric space.
Formally, this theorem can be formulated as:
Theorem: Let (X, d) be a complete metric space and a function f: X->X be a contractor then, f has a unique fixed point x*∈ X (i.e. f(x*)=x*) such that the sequence f(f(f(...f(x)))) converges to x*.
Now, to prove this mathematically, we need to prove both the uniqueness and existence of x*.
Uniqueness: We will prove this by contradiction. Let us assume that the convergence value is not unique and x1* and x2* are two values at which the sequence of contractor converges then, we will have:
Uniqueness: We will prove this by contradiction. Let us assume that the convergence value is not unique and x1* and x2* are two values at which the sequence of contractor converges then, we will have:
Also, note that f is a contractor so it must hold the following property:
Now since γ∈[0,1), it’s impossible to satisfy both equation 1 and 2 simultaneously. Therefore our assumption must be wrong. Hence, by contradiction, x* must be unique.
2. Existence: Now that we’ve proved that x* is unique, we need to prove that x* exists. Let (x1, x2, x3, .... xn) be the sequence formed by repeatedly applying the contractor.
If we assume that the sequence (x1, x2, x3, .... xn) is Cauchy, we know for certain that this sequence will converge to some point, say, x*. Also, since the metric space is complete, this convergent point,x* will belong to the metric space (X,d). Now, we just need to prove that this sequence is Cauchy. We will do this by taking two elements of the set xn and xm such that m>>n and, m is very large, then by repeatedly applying the triangular inequality property of the metric d, we have:
Now, since f is a contractor, we know that:
We can further reduce d(xm, xn) as follows:
Now, by choosing n to be sufficiently large, we can make the RHS of the above equation less than any positive real number ε. Hence, the sequence (x1, x2, x3, .... xn) is Cauchy and an optimal x*∈X exists. This concludes the proof of the Banach fixed point theorem.
For the value function, V(s) we define a new operator, the optimal Bellman operator,B which takes in a value function and returns another value function. We define this operator as follows:
It can easily be observed, B is a recursive operator. Therefore, this will generate a sequence of value functions. If we can show that B is indeed a contractor for some metric space (X,d) then by the Banach fixed point theorem, we can conclude that the repeated application of the optimal Bellman operator will eventually give a unique optimal value function using which an optimal (best) policy can be derived. Therefore, all our work now reduces to proving that B is a contractor. First, let's define the metric space as follows:
Metric space (X,d): The set X is the set of real numbers defined as follows:
For the metric, we use the L-infinity norm defined as follows:
According to this metric, the distance between the two value functions will be equal to the highest element-wise absolute difference between the two. Also, for finite MDPs with finite rewards, the value functions will always stay in the real space. It is impossible for the value function to not be in the real space, therefore, this finite space will always be complete.
Theorem: Bellman operator B is a contraction mapping in the finite space (R, L-infinity)
Proof: Let V1 and V2 be two value functions. Then:
In the second step above, we introduce inequality by replacing a’ by a for the second value function. This is because by replacing its optimal action a’ by some other action a, we have reduced its overall value thereby introducing an inequality.
In the fourth step, we remove the L-infinity norm by taking the max over s’ (recall the definition of L-infinity with respect to value functions in our setting)
In the final step, we remove the sigma because the sum of probabilities is always 1.
Finally, for the Bellman optimality equation, since γ∈[0,1) (let's ignore the possibility of γ=1 for now), the Bellman operator is, therefore, a contractor.
Now we know:
(R, L-infinity) is a complete metric spaceBellman operator B is a contractor
(R, L-infinity) is a complete metric space
Bellman operator B is a contractor
Hence, by the Banach fixed point theorem, we conclude that there exists a unique optimal value function V* for every MDP. Using this V*, we can derive the optimal policy π*.
Hence proved, for any finite MDP, there exists an optimal policy π* such that it is better than or equal to every other possible policy π.
Now, how to find this optimal policy and value function? One way is to just repeatedly apply the Bellman operator to a random initial value function to get the optimal function. But, this is computationally very expensive and often downright infeasible. Therefore, we use iterative methods like value and policy iteration or temporal difference methods like Q-Learning or SARSA. For more on this, please refer to my blog Reinforcement learning: Temporal-Difference, SARSA, Q-Learning & Expected SARSA in python or just view these algorithms on my Github: RL_from_scratch.
We learned some basic mathematical tools like metric spaces, complete metric spaces, Cauchy sequences, contraction mapping and the Banach fixed point theorem. Building upon all of this, we mathematically proved the unique optimality of the Bellman optimality equation for every MDP.
I used https://latex.codecogs.com/eqneditor/editor.php to generate images for LaTeX. (I wish medium allowed LaTeX)
Wikipedia for providing all the formal definitions and theorems.
The CMU 15–781 course
The notes and video by Dr Daniel Murfet
The free NPTEL course by Dr Balaraman Ravindran and IIT-Madras
I have tried to explain everything in as simple words as possible. If I was unclear or if I made some mistakes, please let me know in the responses. Also, there might be some mistakes in the latex equations. Please let me know if you find them. Last but not least, thanks for reading! | [
{
"code": null,
"e": 410,
"s": 171,
"text": "Reinforcement learning has achieved remarkable results in playing games like StarCraft (AlphaStar) and Go (AlphaGO). At the core of all these successful projects lies — The Bellman optimality equation for Markov decision processes (MDPs)."
},
{
"code": null,
"e": 779,
"s": 410,
"text": "The Bellman optimality equation is a recursive equation that can be solved using dynamic programming (DP) algorithms to find the optimal value function and the optimal policy. In this article, I will try to explain why the Bellman optimality equation can solve every MDP by providing an optimal policy and perform an easy (hopefully) mathematical analysis of the same."
},
{
"code": null,
"e": 797,
"s": 779,
"text": "S is state space."
},
{
"code": null,
"e": 822,
"s": 797,
"text": "V is the value function."
},
{
"code": null,
"e": 856,
"s": 822,
"text": "V* is the optimal value function."
},
{
"code": null,
"e": 886,
"s": 856,
"text": "V(s) is the value of state s."
},
{
"code": null,
"e": 901,
"s": 886,
"text": "π is a policy."
},
{
"code": null,
"e": 927,
"s": 901,
"text": "π* is the optimal policy."
},
{
"code": null,
"e": 983,
"s": 927,
"text": "π(s) returns the action for state s under the policy π."
},
{
"code": null,
"e": 1023,
"s": 983,
"text": "P is the transition probability matrix."
},
{
"code": null,
"e": 1046,
"s": 1023,
"text": "A is the action space."
},
{
"code": null,
"e": 1187,
"s": 1046,
"text": "Despite my best efforts, the analysis is going to be fairly rigorous and I assume the readers to be familiar with the following perquisites:"
},
{
"code": null,
"e": 1378,
"s": 1187,
"text": "Markov decision process (MDP)Bellman Equation and how it’s solved using iterative methods.Basics of RL — Value functions, rewards, policies, discount factor etc.Linear algebraVector calculus"
},
{
"code": null,
"e": 1408,
"s": 1378,
"text": "Markov decision process (MDP)"
},
{
"code": null,
"e": 1470,
"s": 1408,
"text": "Bellman Equation and how it’s solved using iterative methods."
},
{
"code": null,
"e": 1542,
"s": 1470,
"text": "Basics of RL — Value functions, rewards, policies, discount factor etc."
},
{
"code": null,
"e": 1557,
"s": 1542,
"text": "Linear algebra"
},
{
"code": null,
"e": 1573,
"s": 1557,
"text": "Vector calculus"
},
{
"code": null,
"e": 2052,
"s": 1573,
"text": "If you have studied RL and MDPs, you must’ve encountered the claim: “For each MDP, there is always at least one policy that is better than or equal to all other policies.” This occurs both in Sutton and Barto’s book as well as in the lecture series by David Silver. Reading/Hearing this makes the claim pretty intuitive, however, I had to dig in deeper and understand this in a more concrete manner. Therefore, in this article, I will mathematically prove the following theorem:"
},
{
"code": null,
"e": 2186,
"s": 2052,
"text": "Theorem: For any finite MDP, there exists an optimal policy π* such that it is better than or equal to every other possible policy π."
},
{
"code": null,
"e": 2329,
"s": 2186,
"text": "Before finding the best policy, we need to understand the ordering of policies. When is one policy (π1) considered better than the other (π2)?"
},
{
"code": null,
"e": 2572,
"s": 2329,
"text": "If the value of a state derived using π1 is better than or equal the value of a state derived using π2 for every state in the environment, then the policy π1 is said to be better than policy π2. Mathematically, this can be written as follows:"
},
{
"code": null,
"e": 2705,
"s": 2572,
"text": "Now that we know how to compare policies, we need to prove that there always exists a policy that is better than all other policies."
},
{
"code": null,
"e": 3028,
"s": 2705,
"text": "We are going to prove this using the Banach fixed point theorem by showing that the Bellman optimality operator is a contraction over a complete metric space of real numbers with metric L-infinity norm. For this, we will first discuss the fixed point problem and complete metric spaces with respect to the Cauchy sequence."
},
{
"code": null,
"e": 3323,
"s": 3028,
"text": "The above paragraph sounds very intimidating but its actually going to be pretty easy and intuitive once we get past the basic terminologies. We will be discussing everything that is in bold in the above paragraph. Let’s follow a bottom-up approach and learn each concept and conquer our fears:"
},
{
"code": null,
"e": 4008,
"s": 3323,
"text": "I am sure most of us are familiar with the problem of finding the roots of an equation. We solve for x such that a function f(x) = 0. However, in a fixed point problem, we solve for x such that f(x) = x. As the name suggests, x is a fixed point, it does not change even on the application of the function. A fixed point problem can be converted into a problem of finding roots by forming another function g(x) = f(x)-x = 0. In fact, even root finding problems can also be converted back to fixed point problems. However, it’s really easy to solve fixed point problems (for special cases) and that is what makes them incredibly interesting and useful (sans the computational overhead)."
},
{
"code": null,
"e": 4194,
"s": 4008,
"text": "To solve a fixed point problem, choose a random starting value of x and repeatedly apply f(x) infinite times. If the function is convergent and you’re lucky, you will find the solution."
},
{
"code": null,
"e": 4262,
"s": 4194,
"text": "Mathematically, it’s pretty simple, lets first describe a notation:"
},
{
"code": null,
"e": 4424,
"s": 4262,
"text": "Now, if the function is convergent then it must converge to some value, say, x*. This value, x* is indeed the solution to the fixed point problem as shown below:"
},
{
"code": null,
"e": 4577,
"s": 4424,
"text": "Let's choose some arbitrary value x0 and apply the function f(.) on x0 for infinite times to get x*, and then use that to solve the fixed point problem:"
},
{
"code": null,
"e": 4816,
"s": 4577,
"text": "The intuition behind this is pretty simple, if a function has converged at some point then the value of this function at that convergent point will be the convergent point itself. Therefore, the convergent point is the fixed point itself."
},
{
"code": null,
"e": 4882,
"s": 4816,
"text": "This can also be observed empirically through the notebook below:"
},
{
"code": null,
"e": 5024,
"s": 4882,
"text": "import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport warnings\nwarnings.simplefilter(\"ignore\")\n"
},
{
"code": null,
"e": 5373,
"s": 5024,
"text": "def f(x):\n return np.sin(x)/x\n\ndef plot(lower=-1, upper=200):\n ys, xs = [], []\n plt.figure(figsize=(6, 4))\n for x in range(lower, upper):\n try:\n ys.append(f(x))\n xs.append(x)\n except:\n continue\n plt.xlabel(\"x\") \n plt.ylabel(\"f(x)\") \n plt.plot(xs, ys)\n plt.show()\n"
},
{
"code": null,
"e": 5381,
"s": 5373,
"text": "plot()\n"
},
{
"code": null,
"e": 5422,
"s": 5381,
"text": "The function above is clearly converging"
},
{
"code": null,
"e": 5478,
"s": 5422,
"text": "Note: Instead of infinity, we just apply it 10000 times"
},
{
"code": null,
"e": 5598,
"s": 5478,
"text": "def fixed_point(INF = 10000):\n x0 = np.random.randn()\n for _ in range(INF):\n x0 = f(x0)\n return x0 \n"
},
{
"code": null,
"e": 5640,
"s": 5598,
"text": "solution = fixed_point()\nprint(solution)\n"
},
{
"code": null,
"e": 5660,
"s": 5640,
"text": "0.8767262153950625\n"
},
{
"code": null,
"e": 5809,
"s": 5660,
"text": "def verify(solution):\n print(f\"Values of function: f{f(solution)} | Value of x: {solution}\")\n if f(solution) == solution:\n return True\n"
},
{
"code": null,
"e": 5827,
"s": 5809,
"text": "verify(solution)\n"
},
{
"code": null,
"e": 5901,
"s": 5827,
"text": "Values of function: f0.8767262153950625 | Value of x: 0.8767262153950625\n"
},
{
"code": null,
"e": 5906,
"s": 5901,
"text": "True"
},
{
"code": null,
"e": 6301,
"s": 5906,
"text": "A metric space is simply a set with a metric defined to measure the distance between any two elements of the set. For example, the Euclidean space is a metric space with distance defined as the Euclidean distance in the set of real numbers. Therefore, a metric space M is represented as (X, d) where X is the set and d is some sort of metric. The metric d must satisfy the following properties:"
},
{
"code": null,
"e": 6416,
"s": 6301,
"text": "Identify d(x,x) = 0Non-Negativity d(x, y) >0Symmetry: d(x,y) = d(y,x)Triangular inequality: d(x,z) ≤ d(x,y)+d(y,z)"
},
{
"code": null,
"e": 6436,
"s": 6416,
"text": "Identify d(x,x) = 0"
},
{
"code": null,
"e": 6462,
"s": 6436,
"text": "Non-Negativity d(x, y) >0"
},
{
"code": null,
"e": 6488,
"s": 6462,
"text": "Symmetry: d(x,y) = d(y,x)"
},
{
"code": null,
"e": 6534,
"s": 6488,
"text": "Triangular inequality: d(x,z) ≤ d(x,y)+d(y,z)"
},
{
"code": null,
"e": 6744,
"s": 6534,
"text": "For a metric space (X, d) the sequence of elements of the set X, (x1, x2, x3.... xn) is a Cauchy sequence if, for every positive real number ε, there exists an integer N such that the following equation holds:"
},
{
"code": null,
"e": 7341,
"s": 6744,
"text": "The mathematical explanation here isn’t very intuitive and needlessly complex. In simple words, a sequence of elements of a metric space is Cauchy if this sequence converges at some point (the distance between them becomes constant). Another great explanation for this is given by this website and goes as follows: “for any small distance, there is a certain index past which any two terms are within that distance of each other, which captures the intuitive idea of the terms becoming close.” The idea of “terms become close” is the basic intuition behind convergence or the limit of the series."
},
{
"code": null,
"e": 7640,
"s": 7341,
"text": "A metric space (X, d) is complete if every possible Cauchy sequence of the elements in the set X converges to an element that also belongs to the set X. That is to say, the convergent limit of every Cauchy sequence of the elements of set lies in the set itself. Which is why it’s called “complete”."
},
{
"code": null,
"e": 7891,
"s": 7640,
"text": "A function (or operator or mapping) defined on the elements of the metric space (X, d) is a contraction (or contractor) if there exists some constant γ∈[0,1) such that for any two elements of the metric space x1 and x2, the following condition holds:"
},
{
"code": null,
"e": 8381,
"s": 7891,
"text": "This means that after applying the mapping f(.) on the elements x1 and x2, they got closer to each other by at least a factor γ. Also, the smallest value of such a constant γ is called the Lipschitz constant (this is an important constant for generative adversarial networks). Also, if γ=1, the mapping is no more a contraction but rather a short mapping. Intuitively, it can be observed that the sequential values of the elements are getting closer after applying the contraction mapping."
},
{
"code": null,
"e": 8625,
"s": 8381,
"text": "This is the heart and soul of our proof. Informally, this theorem says that for a complete metric space, the application of a contractor on the elements of the set, again and again, would eventually get us to an optimal, unique value. We know:"
},
{
"code": null,
"e": 8862,
"s": 8625,
"text": "Contractors bring the elements of the set together.Applying this contractor, again and again, would get us a sequence. (Cauchy?)The Cauchy sequences in a complete metric space always converge to a value that is part of the metric space."
},
{
"code": null,
"e": 8914,
"s": 8862,
"text": "Contractors bring the elements of the set together."
},
{
"code": null,
"e": 8992,
"s": 8914,
"text": "Applying this contractor, again and again, would get us a sequence. (Cauchy?)"
},
{
"code": null,
"e": 9101,
"s": 8992,
"text": "The Cauchy sequences in a complete metric space always converge to a value that is part of the metric space."
},
{
"code": null,
"e": 9146,
"s": 9101,
"text": "Formally, this theorem can be formulated as:"
},
{
"code": null,
"e": 9344,
"s": 9146,
"text": "Theorem: Let (X, d) be a complete metric space and a function f: X->X be a contractor then, f has a unique fixed point x*∈ X (i.e. f(x*)=x*) such that the sequence f(f(f(...f(x)))) converges to x*."
},
{
"code": null,
"e": 9437,
"s": 9344,
"text": "Now, to prove this mathematically, we need to prove both the uniqueness and existence of x*."
},
{
"code": null,
"e": 9638,
"s": 9437,
"text": "Uniqueness: We will prove this by contradiction. Let us assume that the convergence value is not unique and x1* and x2* are two values at which the sequence of contractor converges then, we will have:"
},
{
"code": null,
"e": 9839,
"s": 9638,
"text": "Uniqueness: We will prove this by contradiction. Let us assume that the convergence value is not unique and x1* and x2* are two values at which the sequence of contractor converges then, we will have:"
},
{
"code": null,
"e": 9913,
"s": 9839,
"text": "Also, note that f is a contractor so it must hold the following property:"
},
{
"code": null,
"e": 10081,
"s": 9913,
"text": "Now since γ∈[0,1), it’s impossible to satisfy both equation 1 and 2 simultaneously. Therefore our assumption must be wrong. Hence, by contradiction, x* must be unique."
},
{
"code": null,
"e": 10257,
"s": 10081,
"text": "2. Existence: Now that we’ve proved that x* is unique, we need to prove that x* exists. Let (x1, x2, x3, .... xn) be the sequence formed by repeatedly applying the contractor."
},
{
"code": null,
"e": 10747,
"s": 10257,
"text": "If we assume that the sequence (x1, x2, x3, .... xn) is Cauchy, we know for certain that this sequence will converge to some point, say, x*. Also, since the metric space is complete, this convergent point,x* will belong to the metric space (X,d). Now, we just need to prove that this sequence is Cauchy. We will do this by taking two elements of the set xn and xm such that m>>n and, m is very large, then by repeatedly applying the triangular inequality property of the metric d, we have:"
},
{
"code": null,
"e": 10791,
"s": 10747,
"text": "Now, since f is a contractor, we know that:"
},
{
"code": null,
"e": 10835,
"s": 10791,
"text": "We can further reduce d(xm, xn) as follows:"
},
{
"code": null,
"e": 11100,
"s": 10835,
"text": "Now, by choosing n to be sufficiently large, we can make the RHS of the above equation less than any positive real number ε. Hence, the sequence (x1, x2, x3, .... xn) is Cauchy and an optimal x*∈X exists. This concludes the proof of the Banach fixed point theorem."
},
{
"code": null,
"e": 11290,
"s": 11100,
"text": "For the value function, V(s) we define a new operator, the optimal Bellman operator,B which takes in a value function and returns another value function. We define this operator as follows:"
},
{
"code": null,
"e": 11822,
"s": 11290,
"text": "It can easily be observed, B is a recursive operator. Therefore, this will generate a sequence of value functions. If we can show that B is indeed a contractor for some metric space (X,d) then by the Banach fixed point theorem, we can conclude that the repeated application of the optimal Bellman operator will eventually give a unique optimal value function using which an optimal (best) policy can be derived. Therefore, all our work now reduces to proving that B is a contractor. First, let's define the metric space as follows:"
},
{
"code": null,
"e": 11899,
"s": 11822,
"text": "Metric space (X,d): The set X is the set of real numbers defined as follows:"
},
{
"code": null,
"e": 11962,
"s": 11899,
"text": "For the metric, we use the L-infinity norm defined as follows:"
},
{
"code": null,
"e": 12334,
"s": 11962,
"text": "According to this metric, the distance between the two value functions will be equal to the highest element-wise absolute difference between the two. Also, for finite MDPs with finite rewards, the value functions will always stay in the real space. It is impossible for the value function to not be in the real space, therefore, this finite space will always be complete."
},
{
"code": null,
"e": 12423,
"s": 12334,
"text": "Theorem: Bellman operator B is a contraction mapping in the finite space (R, L-infinity)"
},
{
"code": null,
"e": 12474,
"s": 12423,
"text": "Proof: Let V1 and V2 be two value functions. Then:"
},
{
"code": null,
"e": 12720,
"s": 12474,
"text": "In the second step above, we introduce inequality by replacing a’ by a for the second value function. This is because by replacing its optimal action a’ by some other action a, we have reduced its overall value thereby introducing an inequality."
},
{
"code": null,
"e": 12881,
"s": 12720,
"text": "In the fourth step, we remove the L-infinity norm by taking the max over s’ (recall the definition of L-infinity with respect to value functions in our setting)"
},
{
"code": null,
"e": 12966,
"s": 12881,
"text": "In the final step, we remove the sigma because the sum of probabilities is always 1."
},
{
"code": null,
"e": 13123,
"s": 12966,
"text": "Finally, for the Bellman optimality equation, since γ∈[0,1) (let's ignore the possibility of γ=1 for now), the Bellman operator is, therefore, a contractor."
},
{
"code": null,
"e": 13136,
"s": 13123,
"text": "Now we know:"
},
{
"code": null,
"e": 13213,
"s": 13136,
"text": "(R, L-infinity) is a complete metric spaceBellman operator B is a contractor"
},
{
"code": null,
"e": 13256,
"s": 13213,
"text": "(R, L-infinity) is a complete metric space"
},
{
"code": null,
"e": 13291,
"s": 13256,
"text": "Bellman operator B is a contractor"
},
{
"code": null,
"e": 13465,
"s": 13291,
"text": "Hence, by the Banach fixed point theorem, we conclude that there exists a unique optimal value function V* for every MDP. Using this V*, we can derive the optimal policy π*."
},
{
"code": null,
"e": 13604,
"s": 13465,
"text": "Hence proved, for any finite MDP, there exists an optimal policy π* such that it is better than or equal to every other possible policy π."
},
{
"code": null,
"e": 14176,
"s": 13604,
"text": "Now, how to find this optimal policy and value function? One way is to just repeatedly apply the Bellman operator to a random initial value function to get the optimal function. But, this is computationally very expensive and often downright infeasible. Therefore, we use iterative methods like value and policy iteration or temporal difference methods like Q-Learning or SARSA. For more on this, please refer to my blog Reinforcement learning: Temporal-Difference, SARSA, Q-Learning & Expected SARSA in python or just view these algorithms on my Github: RL_from_scratch."
},
{
"code": null,
"e": 14459,
"s": 14176,
"text": "We learned some basic mathematical tools like metric spaces, complete metric spaces, Cauchy sequences, contraction mapping and the Banach fixed point theorem. Building upon all of this, we mathematically proved the unique optimality of the Bellman optimality equation for every MDP."
},
{
"code": null,
"e": 14574,
"s": 14459,
"text": "I used https://latex.codecogs.com/eqneditor/editor.php to generate images for LaTeX. (I wish medium allowed LaTeX)"
},
{
"code": null,
"e": 14639,
"s": 14574,
"text": "Wikipedia for providing all the formal definitions and theorems."
},
{
"code": null,
"e": 14661,
"s": 14639,
"text": "The CMU 15–781 course"
},
{
"code": null,
"e": 14701,
"s": 14661,
"text": "The notes and video by Dr Daniel Murfet"
},
{
"code": null,
"e": 14764,
"s": 14701,
"text": "The free NPTEL course by Dr Balaraman Ravindran and IIT-Madras"
}
] |
Bitonic Point | Practice | GeeksforGeeks | Given an array arr of n elements which is first increasing and then may be decreasing, find the maximum element in the array.
Note: If the array is increasing then just print then last element will be the maximum value.
Example 1:
Input:
n = 9
arr[] = {1,15,25,45,42,21,17,12,11}
Output: 45
Explanation: Maximum element is 45.
Example 2:
Input:
n = 5
arr[] = {1, 45, 47, 50, 5}
Output: 50
Explanation: Maximum element is 50.
Your Task:
You don't need to read input or print anything. Your task is to complete the function findMaximum() which takes the array arr[], and n as parameters and returns an integer denoting the answer.
Expected Time Complexity: O(logn)
Expected Auxiliary Space: O(1)
Constraints:
3 ≤ n ≤ 106
1 ≤ arri ≤ 106
+1
mrpalashbharati3 days ago
int findMaximum(int arr[], int n) { // code here int l=0,h=n-1; while(l<=h){ int mid=l+(h-l)/2; if( (mid==0 || arr[mid]>arr[mid-1]) && (mid==n-1 || arr[mid]>arr[mid+1] )){ return arr[mid]; } else if(mid-1>0 && arr[mid-1]>arr[mid]){ h=mid-1; } else{ l=mid+1; } } return arr[h];}
0
vaishnavigabda996 days ago
// JAVA CODE
class Solution { int findMaximum(int[] arr, int n) { Arrays.sort(arr); int i=arr[n-1]; return i; }}
0
harshilrpanchal19981 week ago
java solution
class Solution { int findMaximum(int[] arr, int n) { // code here int count=0; for (int i=0 ; i < n ; i++){ if (arr[i] >= count){ count = arr[i]; } } return count; }}
0
priyansh708901 week ago
int findMaximum(int arr[], int n) { // code here int start = 0; int end = n-1; int mid = start + (end - start)/2; while(start<end) { if(arr[mid]<arr[mid+1]) { start = mid+1; } else { end = mid; } mid = start + (end-start)/2; } return arr[start];}
0
atif836141 week ago
JAVA SOLUTION:
if(arr.length==0){
return 0;
}
int var=arr[0];
for(int i=1;i<n;i++){
if(arr[i]>var){
var=arr[i];
}
}
return var;
0
mehtay0371 week ago
Python Solution:
class Solution:
def findMaximum(self,arr, n): # code here for i in range(n-1): if(arr[i]<arr[i+1]): continue else: return arr[i] return arr[-1]
-1
vishutyagi72 weeks ago
2 line code 😂
sort(arr,arr+n); return arr[n-1];
0
prachimahajan6312 weeks ago
int findMaximum(int arr[], int n) { // code here int l=0,r=n-1,mid; while(l<=r) { mid=l+(r-l)/2; if(arr[mid]>arr[mid-1]&&arr[mid]>arr[mid+1]) return arr[mid]; else if(arr[mid]>arr[mid-1]&&arr[mid]<arr[mid+1]) l=mid+1; else if(arr[mid]<arr[mid-1]) r=mid-1; }
0
shrustis1763 weeks ago
C++ solution using Binary Search in O(logn) complexity
int findMaximum(int arr[], int n) { // code here int l=0, h=n-1, mid; while(l<=h) { mid = l+(h-l)/2; if(arr[mid] < arr[mid-1]) h=mid-1; else if ( arr[mid] > arr[mid-1]) l=mid+1; } return arr[h];}
+1
rajat2306161 month ago
Python solution:--
def findMaximum(self,arr, n):
# code here
l = 0
h = n-1
while l < h:
mid = (l+h)//2
if arr[mid] > arr[mid-1] and arr[mid] > arr[mid+1]:
return arr[mid]
elif arr[mid] > arr[l] and arr[mid] < arr[mid + 1]:
l = mid
else:
h = mid
return arr[n-1]
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": 458,
"s": 238,
"text": "Given an array arr of n elements which is first increasing and then may be decreasing, find the maximum element in the array.\nNote: If the array is increasing then just print then last element will be the maximum value."
},
{
"code": null,
"e": 469,
"s": 458,
"text": "Example 1:"
},
{
"code": null,
"e": 566,
"s": 469,
"text": "Input: \nn = 9\narr[] = {1,15,25,45,42,21,17,12,11}\nOutput: 45\nExplanation: Maximum element is 45."
},
{
"code": null,
"e": 577,
"s": 566,
"text": "Example 2:"
},
{
"code": null,
"e": 665,
"s": 577,
"text": "Input: \nn = 5\narr[] = {1, 45, 47, 50, 5}\nOutput: 50\nExplanation: Maximum element is 50."
},
{
"code": null,
"e": 937,
"s": 665,
"text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function findMaximum() which takes the array arr[], and n as parameters and returns an integer denoting the answer.\n\nExpected Time Complexity: O(logn)\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 977,
"s": 937,
"text": "Constraints:\n3 ≤ n ≤ 106\n1 ≤ arri ≤ 106"
},
{
"code": null,
"e": 982,
"s": 979,
"text": "+1"
},
{
"code": null,
"e": 1008,
"s": 982,
"text": "mrpalashbharati3 days ago"
},
{
"code": null,
"e": 1411,
"s": 1008,
"text": "int findMaximum(int arr[], int n) { // code here int l=0,h=n-1; while(l<=h){ int mid=l+(h-l)/2; if( (mid==0 || arr[mid]>arr[mid-1]) && (mid==n-1 || arr[mid]>arr[mid+1] )){ return arr[mid]; } else if(mid-1>0 && arr[mid-1]>arr[mid]){ h=mid-1; } else{ l=mid+1; } } return arr[h];}"
},
{
"code": null,
"e": 1413,
"s": 1411,
"text": "0"
},
{
"code": null,
"e": 1440,
"s": 1413,
"text": "vaishnavigabda996 days ago"
},
{
"code": null,
"e": 1453,
"s": 1440,
"text": "// JAVA CODE"
},
{
"code": null,
"e": 1591,
"s": 1455,
"text": "class Solution { int findMaximum(int[] arr, int n) { Arrays.sort(arr); int i=arr[n-1]; return i; }}"
},
{
"code": null,
"e": 1593,
"s": 1591,
"text": "0"
},
{
"code": null,
"e": 1623,
"s": 1593,
"text": "harshilrpanchal19981 week ago"
},
{
"code": null,
"e": 1637,
"s": 1623,
"text": "java solution"
},
{
"code": null,
"e": 1881,
"s": 1639,
"text": "class Solution { int findMaximum(int[] arr, int n) { // code here int count=0; for (int i=0 ; i < n ; i++){ if (arr[i] >= count){ count = arr[i]; } } return count; }}"
},
{
"code": null,
"e": 1883,
"s": 1881,
"text": "0"
},
{
"code": null,
"e": 1907,
"s": 1883,
"text": "priyansh708901 week ago"
},
{
"code": null,
"e": 2250,
"s": 1907,
"text": " int findMaximum(int arr[], int n) { // code here int start = 0; int end = n-1; int mid = start + (end - start)/2; while(start<end) { if(arr[mid]<arr[mid+1]) { start = mid+1; } else { end = mid; } mid = start + (end-start)/2; } return arr[start];}"
},
{
"code": null,
"e": 2252,
"s": 2250,
"text": "0"
},
{
"code": null,
"e": 2272,
"s": 2252,
"text": "atif836141 week ago"
},
{
"code": null,
"e": 2287,
"s": 2272,
"text": "JAVA SOLUTION:"
},
{
"code": null,
"e": 2492,
"s": 2287,
"text": "if(arr.length==0){\n return 0;\n }\n int var=arr[0];\n for(int i=1;i<n;i++){\n if(arr[i]>var){\n var=arr[i];\n }\n }\n return var;"
},
{
"code": null,
"e": 2494,
"s": 2492,
"text": "0"
},
{
"code": null,
"e": 2514,
"s": 2494,
"text": "mehtay0371 week ago"
},
{
"code": null,
"e": 2531,
"s": 2514,
"text": "Python Solution:"
},
{
"code": null,
"e": 2547,
"s": 2531,
"text": "class Solution:"
},
{
"code": null,
"e": 2708,
"s": 2547,
"text": "def findMaximum(self,arr, n): # code here for i in range(n-1): if(arr[i]<arr[i+1]): continue else: return arr[i] return arr[-1] "
},
{
"code": null,
"e": 2713,
"s": 2710,
"text": "-1"
},
{
"code": null,
"e": 2736,
"s": 2713,
"text": "vishutyagi72 weeks ago"
},
{
"code": null,
"e": 2750,
"s": 2736,
"text": "2 line code 😂"
},
{
"code": null,
"e": 2787,
"s": 2750,
"text": "sort(arr,arr+n); return arr[n-1];"
},
{
"code": null,
"e": 2789,
"s": 2787,
"text": "0"
},
{
"code": null,
"e": 2817,
"s": 2789,
"text": "prachimahajan6312 weeks ago"
},
{
"code": null,
"e": 3147,
"s": 2817,
"text": "int findMaximum(int arr[], int n) { // code here int l=0,r=n-1,mid; while(l<=r) { mid=l+(r-l)/2; if(arr[mid]>arr[mid-1]&&arr[mid]>arr[mid+1]) return arr[mid]; else if(arr[mid]>arr[mid-1]&&arr[mid]<arr[mid+1]) l=mid+1; else if(arr[mid]<arr[mid-1]) r=mid-1; }"
},
{
"code": null,
"e": 3149,
"s": 3147,
"text": "0"
},
{
"code": null,
"e": 3172,
"s": 3149,
"text": "shrustis1763 weeks ago"
},
{
"code": null,
"e": 3227,
"s": 3172,
"text": "C++ solution using Binary Search in O(logn) complexity"
},
{
"code": null,
"e": 3498,
"s": 3229,
"text": "int findMaximum(int arr[], int n) { // code here int l=0, h=n-1, mid; while(l<=h) { mid = l+(h-l)/2; if(arr[mid] < arr[mid-1]) h=mid-1; else if ( arr[mid] > arr[mid-1]) l=mid+1; } return arr[h];}"
},
{
"code": null,
"e": 3501,
"s": 3498,
"text": "+1"
},
{
"code": null,
"e": 3524,
"s": 3501,
"text": "rajat2306161 month ago"
},
{
"code": null,
"e": 3543,
"s": 3524,
"text": "Python solution:--"
},
{
"code": null,
"e": 3856,
"s": 3543,
"text": "\tdef findMaximum(self,arr, n):\n\t\t# code here\n\t\tl = 0\n\t\th = n-1\n\t\t\n\t\twhile l < h:\n\t\t mid = (l+h)//2\n\t\t if arr[mid] > arr[mid-1] and arr[mid] > arr[mid+1]:\n\t\t return arr[mid]\n\t\t elif arr[mid] > arr[l] and arr[mid] < arr[mid + 1]:\n\t\t l = mid\n\t\t else:\n\t\t h = mid\n\t\t\n\t\treturn arr[n-1]"
},
{
"code": null,
"e": 4002,
"s": 3856,
"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": 4038,
"s": 4002,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4048,
"s": 4038,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4058,
"s": 4048,
"text": "\nContest\n"
},
{
"code": null,
"e": 4121,
"s": 4058,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4269,
"s": 4121,
"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": 4477,
"s": 4269,
"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": 4583,
"s": 4477,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Disarium Number - GeeksforGeeks | 07 Mar, 2022
Given a number “n”, find if it is Disarium or not. A number is called Disarium if sum of its digits powered with their respective positions is equal to the number itself.
Examples:
Input : n = 135
Output : Yes
1^1 + 3^2 + 5^3 = 135
Therefore, 135 is a Disarium number
Input : n = 89
Output : Yes
8^1+9^2 = 89
Therefore, 89 is a Disarium number
Input : n = 80
Output : No
8^1 + 0^2 = 8
The idea is to first count digits in given numbers. Once we have count, we traverse all digits from right most (using % operator), raise its power to digit count and decrement the digit count.
Below is the implementation of above idea.
C++
Java
Python3
C#
Javascript
// C++ program to check whether a number is Disarium// or not#include<bits/stdc++.h>using namespace std; // Finds count of digits in nint countDigits(int n){ int count_digits = 0; // Count number of digits in n int x = n; while (x) { x = x/10; // Count the no. of digits count_digits++; } return count_digits;} // Function to check whether a number is disarium or notbool check(int n){ // Count digits in n. int count_digits = countDigits(n); // Compute sum of terms like digit multiplied by // power of position int sum = 0; // Initialize sum of terms int x = n; while (x) { // Get the rightmost digit int r = x%10; // Sum the digits by powering according to // the positions sum = sum + pow(r, count_digits--); x = x/10; } // If sum is same as number, then number is return (sum == n);} //Driver code to check if number is disarium or notint main(){ int n = 135; if( check(n)) cout << "Disarium Number"; else cout << "Not a Disarium Number"; return 0;}
// Java program to check whether a number is disarium// or not class Test{ // Method to check whether a number is disarium or not static boolean check(int n) { // Count digits in n. int count_digits = Integer.toString(n).length(); // Compute sum of terms like digit multiplied by // power of position int sum = 0; // Initialize sum of terms int x = n; while (x!=0) { // Get the rightmost digit int r = x%10; // Sum the digits by powering according to // the positions sum = (int) (sum + Math.pow(r, count_digits--)); x = x/10; } // If sum is same as number, then number is return (sum == n); } // Driver method public static void main(String[] args) { int n = 135; System.out.println(check(n) ? "Disarium Number" : "Not a Disarium Number"); }}
# Python program to check whether a number is Disarium# or notimport math # Method to check whether a number is disarium or notdef check(n) : # Count digits in n. count_digits = len(str(n)) # Compute sum of terms like digit multiplied by # power of position sum = 0 # Initialize sum of terms x = n while (x!=0) : # Get the rightmost digit r = x % 10 # Sum the digits by powering according to # the positions sum = (int) (sum + math.pow(r, count_digits)) count_digits = count_digits - 1 x = x//10 # If sum is same as number, then number is if sum == n : return 1 else : return 0 # Driver methodn = 135if (check(n) == 1) : print ("Disarium Number")else : print ("Not a Disarium Number") # This code is contributed by Nikita Tiwari.
// C# program to check whether a number// is Disarium or notusing System; class GFG{ // Method to check whether a number// is disarium or notstatic bool check(int n){ // Count digits in n. int count_digits = n.ToString().Length; // Compute sum of terms like digit // multiplied by power of position // Initialize sum of terms int sum = 0; int x = n; while (x != 0) { // Get the rightmost digit int r = x % 10; // Sum the digits by powering according // to the positions sum = (int)(sum + Math.Pow( r, count_digits--)); x = x / 10; } // If sum is same as number, // then number is return (sum == n);} // Driver codepublic static void Main(string[] args){ int n = 135; Console.Write(check(n) ? "Disarium Number" : "Not a Disarium Number");}} // This code is contributed by rutvik_56
<script> // JavaScript program to check whether a number is Disarium// or not// Method to check whether a number is disarium or notfunction check(n) { // Count digits in n. var count_digits = Number.toString(); // Compute sum of terms like digit multiplied by // power of position var sum = 0; // Initialize sum of terms var x = n; while (x!=0) { // Get the rightmost digit var r = x%10; // Sum the digits by powering according to // the positions sum = (sum + Math.pow(r, count_digits--)); x = x/10; } // If sum is same as number, then number is return (sum = n); } // Driver method var n = 135; document.write(check(n) ? "Disarium Number" : "Not a Disarium Number"); // This code is contributed by shivanisinghss2110</script>
Output:
Disarium Number
YouTubeGeeksforGeeks502K subscribersDisarium Numbers | 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 / 4:56•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=t4xdYNvjJyk" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Sahil Chhabra(KILLER). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
rutvik_56
arorakashish0911
shivanisinghss2110
amartyaghoshgfg
surinderdawra388
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to find GCD or HCF of two numbers
Merge two sorted arrays
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Program for factorial of a number
Program for Decimal to Binary Conversion
Sieve of Eratosthenes
Operators in C / C++
Euclidean algorithms (Basic and Extended) | [
{
"code": null,
"e": 24422,
"s": 24394,
"text": "\n07 Mar, 2022"
},
{
"code": null,
"e": 24593,
"s": 24422,
"text": "Given a number “n”, find if it is Disarium or not. A number is called Disarium if sum of its digits powered with their respective positions is equal to the number itself."
},
{
"code": null,
"e": 24604,
"s": 24593,
"text": "Examples: "
},
{
"code": null,
"e": 24821,
"s": 24604,
"text": "Input : n = 135\nOutput : Yes \n1^1 + 3^2 + 5^3 = 135\nTherefore, 135 is a Disarium number\n\nInput : n = 89\nOutput : Yes \n8^1+9^2 = 89\nTherefore, 89 is a Disarium number\n\nInput : n = 80\nOutput : No\n8^1 + 0^2 = 8"
},
{
"code": null,
"e": 25014,
"s": 24821,
"text": "The idea is to first count digits in given numbers. Once we have count, we traverse all digits from right most (using % operator), raise its power to digit count and decrement the digit count."
},
{
"code": null,
"e": 25058,
"s": 25014,
"text": "Below is the implementation of above idea. "
},
{
"code": null,
"e": 25062,
"s": 25058,
"text": "C++"
},
{
"code": null,
"e": 25067,
"s": 25062,
"text": "Java"
},
{
"code": null,
"e": 25075,
"s": 25067,
"text": "Python3"
},
{
"code": null,
"e": 25078,
"s": 25075,
"text": "C#"
},
{
"code": null,
"e": 25089,
"s": 25078,
"text": "Javascript"
},
{
"code": "// C++ program to check whether a number is Disarium// or not#include<bits/stdc++.h>using namespace std; // Finds count of digits in nint countDigits(int n){ int count_digits = 0; // Count number of digits in n int x = n; while (x) { x = x/10; // Count the no. of digits count_digits++; } return count_digits;} // Function to check whether a number is disarium or notbool check(int n){ // Count digits in n. int count_digits = countDigits(n); // Compute sum of terms like digit multiplied by // power of position int sum = 0; // Initialize sum of terms int x = n; while (x) { // Get the rightmost digit int r = x%10; // Sum the digits by powering according to // the positions sum = sum + pow(r, count_digits--); x = x/10; } // If sum is same as number, then number is return (sum == n);} //Driver code to check if number is disarium or notint main(){ int n = 135; if( check(n)) cout << \"Disarium Number\"; else cout << \"Not a Disarium Number\"; return 0;}",
"e": 26192,
"s": 25089,
"text": null
},
{
"code": "// Java program to check whether a number is disarium// or not class Test{ // Method to check whether a number is disarium or not static boolean check(int n) { // Count digits in n. int count_digits = Integer.toString(n).length(); // Compute sum of terms like digit multiplied by // power of position int sum = 0; // Initialize sum of terms int x = n; while (x!=0) { // Get the rightmost digit int r = x%10; // Sum the digits by powering according to // the positions sum = (int) (sum + Math.pow(r, count_digits--)); x = x/10; } // If sum is same as number, then number is return (sum == n); } // Driver method public static void main(String[] args) { int n = 135; System.out.println(check(n) ? \"Disarium Number\" : \"Not a Disarium Number\"); }}",
"e": 27149,
"s": 26192,
"text": null
},
{
"code": "# Python program to check whether a number is Disarium# or notimport math # Method to check whether a number is disarium or notdef check(n) : # Count digits in n. count_digits = len(str(n)) # Compute sum of terms like digit multiplied by # power of position sum = 0 # Initialize sum of terms x = n while (x!=0) : # Get the rightmost digit r = x % 10 # Sum the digits by powering according to # the positions sum = (int) (sum + math.pow(r, count_digits)) count_digits = count_digits - 1 x = x//10 # If sum is same as number, then number is if sum == n : return 1 else : return 0 # Driver methodn = 135if (check(n) == 1) : print (\"Disarium Number\")else : print (\"Not a Disarium Number\") # This code is contributed by Nikita Tiwari.",
"e": 28012,
"s": 27149,
"text": null
},
{
"code": "// C# program to check whether a number// is Disarium or notusing System; class GFG{ // Method to check whether a number// is disarium or notstatic bool check(int n){ // Count digits in n. int count_digits = n.ToString().Length; // Compute sum of terms like digit // multiplied by power of position // Initialize sum of terms int sum = 0; int x = n; while (x != 0) { // Get the rightmost digit int r = x % 10; // Sum the digits by powering according // to the positions sum = (int)(sum + Math.Pow( r, count_digits--)); x = x / 10; } // If sum is same as number, // then number is return (sum == n);} // Driver codepublic static void Main(string[] args){ int n = 135; Console.Write(check(n) ? \"Disarium Number\" : \"Not a Disarium Number\");}} // This code is contributed by rutvik_56",
"e": 28949,
"s": 28012,
"text": null
},
{
"code": "<script> // JavaScript program to check whether a number is Disarium// or not// Method to check whether a number is disarium or notfunction check(n) { // Count digits in n. var count_digits = Number.toString(); // Compute sum of terms like digit multiplied by // power of position var sum = 0; // Initialize sum of terms var x = n; while (x!=0) { // Get the rightmost digit var r = x%10; // Sum the digits by powering according to // the positions sum = (sum + Math.pow(r, count_digits--)); x = x/10; } // If sum is same as number, then number is return (sum = n); } // Driver method var n = 135; document.write(check(n) ? \"Disarium Number\" : \"Not a Disarium Number\"); // This code is contributed by shivanisinghss2110</script>",
"e": 29888,
"s": 28949,
"text": null
},
{
"code": null,
"e": 29897,
"s": 29888,
"text": "Output: "
},
{
"code": null,
"e": 29913,
"s": 29897,
"text": "Disarium Number"
},
{
"code": null,
"e": 30728,
"s": 29913,
"text": "YouTubeGeeksforGeeks502K subscribersDisarium Numbers | 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 / 4:56•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=t4xdYNvjJyk\" 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": 31158,
"s": 30728,
"text": "This article is contributed by Sahil Chhabra(KILLER). If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 31168,
"s": 31158,
"text": "rutvik_56"
},
{
"code": null,
"e": 31185,
"s": 31168,
"text": "arorakashish0911"
},
{
"code": null,
"e": 31204,
"s": 31185,
"text": "shivanisinghss2110"
},
{
"code": null,
"e": 31220,
"s": 31204,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 31237,
"s": 31220,
"text": "surinderdawra388"
},
{
"code": null,
"e": 31244,
"s": 31237,
"text": "series"
},
{
"code": null,
"e": 31257,
"s": 31244,
"text": "Mathematical"
},
{
"code": null,
"e": 31270,
"s": 31257,
"text": "Mathematical"
},
{
"code": null,
"e": 31277,
"s": 31270,
"text": "series"
},
{
"code": null,
"e": 31375,
"s": 31277,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31417,
"s": 31375,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 31441,
"s": 31417,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 31484,
"s": 31441,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 31498,
"s": 31484,
"text": "Prime Numbers"
},
{
"code": null,
"e": 31547,
"s": 31498,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 31581,
"s": 31547,
"text": "Program for factorial of a number"
},
{
"code": null,
"e": 31622,
"s": 31581,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 31644,
"s": 31622,
"text": "Sieve of Eratosthenes"
},
{
"code": null,
"e": 31665,
"s": 31644,
"text": "Operators in C / C++"
}
] |
Exploratory Data Analysis, Categorical Data — Part II | by Priyanka Banerjee | Towards Data Science | “Coming up with features is difficult, time-consuming, requires expert knowledge. ‘Applied machine learning’ is basically feature engineering.”
— Prof. Andrew Ng.
Data scientists spend close to 75% of their time in analyzing data and engineering features which are indeed a difficult and time-consuming processes. They require domain knowledge along with mathematical computations.
Exploratory Data Analysis and Feature Engineering are the processes of selecting, profiling and transforming data into features which can be fetched as inputs for machine learning models to make predictions. We should remember that good quality features always help in improving the overall model performance. Many times even though the machine learning task can be same in different scenarios but the features extracted after analyzing the data in each scenario will be different from the other.
The above data set has a feature “predicted_category” which detects the emotion of the person based on his statement which is present in the feature “cleaned_hm”. “Raw features” are obtained directly from the data set with no extra data manipulation or engineering whereas “Derived features” are obtained from feature engineering, where we extract features from existing data attributes.
nycdata = pd.read_csv(“train.csv”)nycdata.head(5)
nycdata.shape(50000, 8)
Now, after certain feature engineering, let's check :
nycdata.head(5)
nycdata.shape(50000, 12)
Hence, we have extracted 4 more features from our original raw data set through feature engineering.
In this article, I will deal with data analysis and a bit of feature engineering of Categorical Data.
Let us consider a simple example where the statements of people determine their emotion. Now, if I consider all to be happy in this data set, happiness is categorized into several groups — Affection, Achievement, Leisure, Bonding. Eg- Someone has got a promotion in his workplace hence, he is happy which denotes “Achievement” whereas someone else is happy because he had a warm conversation with his friends after a long long time which clearly shows “Bonding”, a mother is happy because of her child’s birthday which shows again “Affection”. We can clearly see here is no way of ordering these values of the attribute of “Happiness”.
But there are certain ordinal categorical data like shoe sizes or sizes of tee shirts or education level, etc. which follow a particular order.
I prefer to start always by loading all the required necessary dependencies.
import numpy as np #linear algebraimport pandas as pd #data processingimport os #operating system dependent modules of pythonimport matplotlib.pyplot as plt #visualizationimport seaborn as sns #visualization%matplotlib inlinefrom nltk.corpus import stopwordsfrom nltk.stem import PorterStemmerfrom sklearn.preprocessing import LabelEncoderimport refrom wordcloud import WordCloud, ImageColorGeneratorfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
Loading the .csv file
at.head(5)
Let us get the information of our data set.
at.info()Output--<class 'pandas.core.frame.DataFrame'>RangeIndex: 60321 entries, 0 to 60320Data columns (total 5 columns):hmid 60321 non-null int64reflection_period 60321 non-null objectcleaned_hm 60321 non-null objectnum_sentence 60321 non-null int64predicted_category 60321 non-null objectdtypes: int64(2), object(3)memory usage: 2.3+ MB
In case of a big data set having several features, I can get the name of all the features by the command :
dataset.columns
Details information of the data set is obtained by :
at.describe()
I can get a description of those features which have numeric data. In case I want a description of all the features, I will use :
at.describe(include='all')
This is a descriptive statistics to summarize the central tendency, dispersion and shape of a data set’s distribution.
Encoding Categorical Variable:
I need to predict the “happiness” based on the sentences. Initially I have mapped an index to the different labels of “happiness” :
from sklearn.preprocessing import LabelEncodercols = [‘predicted_category’]lbl = LabelEncoder()pred_lbl = lbl.fit_transform(at[cols])mappings = {index: label for index, label in enumerate(lbl.classes_)}mappings{0: 'achievement', 1: 'affection', 2: 'bonding', 3: 'enjoy_the_moment', 4: 'exercise', 5: 'leisure', 6: 'nature'}
Through the function “Label Encoder”, an object “lbl” has mapped a number to each value of the “predicted_category” feature.
Now, I need to apply a specific encoding scheme to our categorical variables. The reason is simple. If I directly feed the pred_lbl attribute as a feature in a machine learning model, it would consider it to be a continuous numeric feature thinking value 6(‘Nature’) is greater than 2(‘Bonding’) but that is meaningless because ‘Nature’ is certainly not bigger or smaller than ‘Bonding’, These are actually categories which cannot be compared directly. Hence I need an additional layer of encoding schemes where dummy features are needed to be created for each unique value.
dummy_features = pd.get_dummies(at['predicted_category'])at=pd.concat([at[['hmid','cleaned_hm']],dummy_features],axis=1)at.head(9)
Since our predicted_category is only dependent on the statements of the people, hence we have considered “cleaned_hm” along with “hmid”
Clean and pre-process raw text :
The feature “cleaned_hm” contains messy raw data which we need to clean.
stops = set(stopwords.words("english"))def cleanData(text, lowercase = False, remove_stops = False, stemming = False): txt = str(text)#print(txt) txt = re.sub(r'[^A-Za-z0-9\s]',r'',txt)#print(txt) txt = re.sub(r'\n',r' ',txt)#print(txt) #convert whole text to lower case & remove stopwords and stemmers if lowercase: txt = " ".join([w.lower() for w in txt.split()]) if remove_stops: txt = " ".join([w for w in txt.split() if w not in stops]) if stemming: st = PorterStemmer() txt = " ".join([st.stem(w) for w in txt.split()])#print(txt) return txt# clean descriptionat['cleaned_hm'] = at['cleaned_hm'].map(lambda x: cleanData(x, lowercase=True, remove_stops=True, stemming=True))
Unlike the raw data set, I have a much compact information now for my data to be fed for machine learning. The function “cleanData” has removed punctuation and words that are not required and has converted it into complete lower case.
Now, all my features are in numeric format except “cleaned_hm”. I have to get the words that have the most frequencies. The same can be achieved by using WordCloud.
#use word cloud to understand the word that has the most frequencytext = ' '.join(at['cleaned_hm'].tolist())text = text.lower()wordcloud = WordCloud(background_color="white", height=2700, width=3600).generate(text)plt.figure( figsize=(14,8) )plt.imshow(wordcloud.recolor(colormap=plt.get_cmap('Set2')), interpolation='bilinear')plt.axis("off")
Vectorization :
To make sense from the feature “cleaned_hm” which can be used in our machine learning models, we’ll need to convert each statement to a numeric representation, which we call vectorization.
Next time we will get into the details of various types of vectorization and how to work with them. | [
{
"code": null,
"e": 315,
"s": 171,
"text": "“Coming up with features is difficult, time-consuming, requires expert knowledge. ‘Applied machine learning’ is basically feature engineering.”"
},
{
"code": null,
"e": 334,
"s": 315,
"text": "— Prof. Andrew Ng."
},
{
"code": null,
"e": 553,
"s": 334,
"text": "Data scientists spend close to 75% of their time in analyzing data and engineering features which are indeed a difficult and time-consuming processes. They require domain knowledge along with mathematical computations."
},
{
"code": null,
"e": 1050,
"s": 553,
"text": "Exploratory Data Analysis and Feature Engineering are the processes of selecting, profiling and transforming data into features which can be fetched as inputs for machine learning models to make predictions. We should remember that good quality features always help in improving the overall model performance. Many times even though the machine learning task can be same in different scenarios but the features extracted after analyzing the data in each scenario will be different from the other."
},
{
"code": null,
"e": 1438,
"s": 1050,
"text": "The above data set has a feature “predicted_category” which detects the emotion of the person based on his statement which is present in the feature “cleaned_hm”. “Raw features” are obtained directly from the data set with no extra data manipulation or engineering whereas “Derived features” are obtained from feature engineering, where we extract features from existing data attributes."
},
{
"code": null,
"e": 1488,
"s": 1438,
"text": "nycdata = pd.read_csv(“train.csv”)nycdata.head(5)"
},
{
"code": null,
"e": 1512,
"s": 1488,
"text": "nycdata.shape(50000, 8)"
},
{
"code": null,
"e": 1566,
"s": 1512,
"text": "Now, after certain feature engineering, let's check :"
},
{
"code": null,
"e": 1582,
"s": 1566,
"text": "nycdata.head(5)"
},
{
"code": null,
"e": 1607,
"s": 1582,
"text": "nycdata.shape(50000, 12)"
},
{
"code": null,
"e": 1708,
"s": 1607,
"text": "Hence, we have extracted 4 more features from our original raw data set through feature engineering."
},
{
"code": null,
"e": 1810,
"s": 1708,
"text": "In this article, I will deal with data analysis and a bit of feature engineering of Categorical Data."
},
{
"code": null,
"e": 2446,
"s": 1810,
"text": "Let us consider a simple example where the statements of people determine their emotion. Now, if I consider all to be happy in this data set, happiness is categorized into several groups — Affection, Achievement, Leisure, Bonding. Eg- Someone has got a promotion in his workplace hence, he is happy which denotes “Achievement” whereas someone else is happy because he had a warm conversation with his friends after a long long time which clearly shows “Bonding”, a mother is happy because of her child’s birthday which shows again “Affection”. We can clearly see here is no way of ordering these values of the attribute of “Happiness”."
},
{
"code": null,
"e": 2590,
"s": 2446,
"text": "But there are certain ordinal categorical data like shoe sizes or sizes of tee shirts or education level, etc. which follow a particular order."
},
{
"code": null,
"e": 2667,
"s": 2590,
"text": "I prefer to start always by loading all the required necessary dependencies."
},
{
"code": null,
"e": 3144,
"s": 2667,
"text": "import numpy as np #linear algebraimport pandas as pd #data processingimport os #operating system dependent modules of pythonimport matplotlib.pyplot as plt #visualizationimport seaborn as sns #visualization%matplotlib inlinefrom nltk.corpus import stopwordsfrom nltk.stem import PorterStemmerfrom sklearn.preprocessing import LabelEncoderimport refrom wordcloud import WordCloud, ImageColorGeneratorfrom sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer"
},
{
"code": null,
"e": 3166,
"s": 3144,
"text": "Loading the .csv file"
},
{
"code": null,
"e": 3177,
"s": 3166,
"text": "at.head(5)"
},
{
"code": null,
"e": 3221,
"s": 3177,
"text": "Let us get the information of our data set."
},
{
"code": null,
"e": 3605,
"s": 3221,
"text": "at.info()Output--<class 'pandas.core.frame.DataFrame'>RangeIndex: 60321 entries, 0 to 60320Data columns (total 5 columns):hmid 60321 non-null int64reflection_period 60321 non-null objectcleaned_hm 60321 non-null objectnum_sentence 60321 non-null int64predicted_category 60321 non-null objectdtypes: int64(2), object(3)memory usage: 2.3+ MB"
},
{
"code": null,
"e": 3712,
"s": 3605,
"text": "In case of a big data set having several features, I can get the name of all the features by the command :"
},
{
"code": null,
"e": 3728,
"s": 3712,
"text": "dataset.columns"
},
{
"code": null,
"e": 3781,
"s": 3728,
"text": "Details information of the data set is obtained by :"
},
{
"code": null,
"e": 3795,
"s": 3781,
"text": "at.describe()"
},
{
"code": null,
"e": 3925,
"s": 3795,
"text": "I can get a description of those features which have numeric data. In case I want a description of all the features, I will use :"
},
{
"code": null,
"e": 3952,
"s": 3925,
"text": "at.describe(include='all')"
},
{
"code": null,
"e": 4071,
"s": 3952,
"text": "This is a descriptive statistics to summarize the central tendency, dispersion and shape of a data set’s distribution."
},
{
"code": null,
"e": 4102,
"s": 4071,
"text": "Encoding Categorical Variable:"
},
{
"code": null,
"e": 4234,
"s": 4102,
"text": "I need to predict the “happiness” based on the sentences. Initially I have mapped an index to the different labels of “happiness” :"
},
{
"code": null,
"e": 4558,
"s": 4234,
"text": "from sklearn.preprocessing import LabelEncodercols = [‘predicted_category’]lbl = LabelEncoder()pred_lbl = lbl.fit_transform(at[cols])mappings = {index: label for index, label in enumerate(lbl.classes_)}mappings{0: 'achievement', 1: 'affection', 2: 'bonding', 3: 'enjoy_the_moment', 4: 'exercise', 5: 'leisure', 6: 'nature'}"
},
{
"code": null,
"e": 4683,
"s": 4558,
"text": "Through the function “Label Encoder”, an object “lbl” has mapped a number to each value of the “predicted_category” feature."
},
{
"code": null,
"e": 5258,
"s": 4683,
"text": "Now, I need to apply a specific encoding scheme to our categorical variables. The reason is simple. If I directly feed the pred_lbl attribute as a feature in a machine learning model, it would consider it to be a continuous numeric feature thinking value 6(‘Nature’) is greater than 2(‘Bonding’) but that is meaningless because ‘Nature’ is certainly not bigger or smaller than ‘Bonding’, These are actually categories which cannot be compared directly. Hence I need an additional layer of encoding schemes where dummy features are needed to be created for each unique value."
},
{
"code": null,
"e": 5389,
"s": 5258,
"text": "dummy_features = pd.get_dummies(at['predicted_category'])at=pd.concat([at[['hmid','cleaned_hm']],dummy_features],axis=1)at.head(9)"
},
{
"code": null,
"e": 5525,
"s": 5389,
"text": "Since our predicted_category is only dependent on the statements of the people, hence we have considered “cleaned_hm” along with “hmid”"
},
{
"code": null,
"e": 5558,
"s": 5525,
"text": "Clean and pre-process raw text :"
},
{
"code": null,
"e": 5631,
"s": 5558,
"text": "The feature “cleaned_hm” contains messy raw data which we need to clean."
},
{
"code": null,
"e": 6371,
"s": 5631,
"text": "stops = set(stopwords.words(\"english\"))def cleanData(text, lowercase = False, remove_stops = False, stemming = False): txt = str(text)#print(txt) txt = re.sub(r'[^A-Za-z0-9\\s]',r'',txt)#print(txt) txt = re.sub(r'\\n',r' ',txt)#print(txt) #convert whole text to lower case & remove stopwords and stemmers if lowercase: txt = \" \".join([w.lower() for w in txt.split()]) if remove_stops: txt = \" \".join([w for w in txt.split() if w not in stops]) if stemming: st = PorterStemmer() txt = \" \".join([st.stem(w) for w in txt.split()])#print(txt) return txt# clean descriptionat['cleaned_hm'] = at['cleaned_hm'].map(lambda x: cleanData(x, lowercase=True, remove_stops=True, stemming=True))"
},
{
"code": null,
"e": 6606,
"s": 6371,
"text": "Unlike the raw data set, I have a much compact information now for my data to be fed for machine learning. The function “cleanData” has removed punctuation and words that are not required and has converted it into complete lower case."
},
{
"code": null,
"e": 6771,
"s": 6606,
"text": "Now, all my features are in numeric format except “cleaned_hm”. I have to get the words that have the most frequencies. The same can be achieved by using WordCloud."
},
{
"code": null,
"e": 7115,
"s": 6771,
"text": "#use word cloud to understand the word that has the most frequencytext = ' '.join(at['cleaned_hm'].tolist())text = text.lower()wordcloud = WordCloud(background_color=\"white\", height=2700, width=3600).generate(text)plt.figure( figsize=(14,8) )plt.imshow(wordcloud.recolor(colormap=plt.get_cmap('Set2')), interpolation='bilinear')plt.axis(\"off\")"
},
{
"code": null,
"e": 7131,
"s": 7115,
"text": "Vectorization :"
},
{
"code": null,
"e": 7320,
"s": 7131,
"text": "To make sense from the feature “cleaned_hm” which can be used in our machine learning models, we’ll need to convert each statement to a numeric representation, which we call vectorization."
}
] |
setkey - Unix, Linux Command | setkey
takes a series of operations from standard input
(
if invoked with
-c
)
or the file named
filename
(
if invoked with
-f filename
).
Meta-arguments are as follows:
key
must be a double-quoted character string, or a series of hexadecimal
digits preceded by
"0x".
Possible values for
ealgo,
aalgo,
and
calgo
are specified in the
Algorithms
sections.
address
address/prefixlen
address[port]
address/prefixlen[port]
prefixlen
and
port
must be decimal numbers.
The square brackets around
port
are really necessary,
they are not man page meta-characters.
For FQDN resolution, the rules applicable to
src
and
dst
apply here as well.
spdadd ::/0 ::/0 icmp6 135,0 -P in none;
Note:
upperspec
does not work against forwarding case at this moment,
as it requires extra reassembly at the forwarding node
(not implemented at this moment).
There are many protocols in
/etc/protocols,
but all protocols except of TCP, UDP, and ICMP may not be suitable
to use with IPsec.
You have to consider carefully what to use.
You must specify the direction of its policy as
direction.
Either
out,
in,
or
fwd
can be used.
priority specification
is used to control the placement of the policy within the SPD.
Policy position is determined by
a signed integer where higher priorities indicate the policy is placed
closer to the beginning of the list and lower priorities indicate the
policy is placed closer to the end of the list.
Policies with equal priorities are added at the end of groups
of such policies.
Priority can only
be specified when setkey has been compiled against kernel headers that
support policy priorities (Linux Gt]= 2.6.6).
If the kernel does not support priorities, a warning message will
be printed the first time a priority specification is used.
Policy priority takes one of the following formats:
offset
is an unsigned integer.
It can be up to 1073741824 for
positive offsets, and up to 1073741823 for negative offsets.
discard
means the packet matching indexes will be discarded.
none
means that IPsec operation will not take place onto the packet.
ipsec
means that IPsec operation will take place onto the packet.
The
protocol/mode/src-dst/level
part specifies the rule how to process the packet.
Either
ah,
esp,
or
ipcomp
must be used as
protocol.
mode
is either
transport
or
tunnel.
If
mode
is
tunnel,
you must specify the end-point addresses of the SA as
src
and
dst
with
'-'
between these addresses, which is used to specify the SA to use.
If
mode
is
transport,
both
src
and
dst
can be omitted.
level
is to be one of the following:
default, use, require,
or
unique.
If the SA is not available in every level, the kernel will
ask the key exchange daemon to establish a suitable SA.
default
means the kernel consults the system wide default for the protocol
you specified, e.g. the
esp_trans_deflev
sysctl variable, when the kernel processes the packet.
use
means that the kernel uses an SA if it’s available,
otherwise the kernel keeps normal operation.
require
means SA is required whenever the kernel sends a packet matched
with the policy.
unique
is the same as
require;
in addition, it allows the policy to match the unique out-bound SA.
You just specify the policy level
unique,
racoon(8)
will configure the SA for the policy.
If you configure the SA by manual keying for that policy,
you can put a decimal number as the policy identifier after
unique
separated by a colon
':'
like:
unique:number
in order to bind this policy to the SA.
number
must be between 1 and 32767.
It corresponds to
extensions-u
of the manual SA configuration.
When you want to use SA bundle, you can define multiple rules.
For example, if an IP header was followed by an AH header followed
by an ESP header followed by an upper layer protocol header, the
rule would be:
esp/transport//require ah/transport//require;
The rule order is very important.
When NAT-T is enabled in the kernel, policy matching for ESP over
UDP packets may be done on endpoint addresses and port
(this depends on the system.
System that do not perform the port check cannot support
multiple endpoints behind the same NAT).
When using ESP over UDP, you can specify port numbers in the endpoint
addresses to get the correct matching.
Here is an example:
spdadd 10.0.11.0/24[any] 10.0.11.33/32[any] any -P out ipsec
esp/tunnel/192.168.0.1[4500]-192.168.1.2[30000]/require ;
Note that
"discard"
and
"none"
are not in the syntax described in
ipsec_set_policy(3).
There are a few differences in the syntax.
See
ipsec_set_policy(3)
for detail.
algorithm keylen (bits)
hmac-md5 128 ah: rfc2403
128 ah-old: rfc2085
hmac-sha1 160 ah: rfc2404
160 ah-old: 128bit ICV (no document)
keyed-md5 128 ah: 96bit ICV (no document)
128 ah-old: rfc1828
keyed-sha1 160 ah: 96bit ICV (no document)
160 ah-old: 128bit ICV (no document)
null 0 to 2048 for debugging
hmac-sha256 256 ah: 96bit ICV
(draft-ietf-ipsec-ciph-sha-256-00)
256 ah-old: 128bit ICV (no document)
hmac-sha384 384 ah: 96bit ICV (no document)
384 ah-old: 128bit ICV (no document)
hmac-sha512 512 ah: 96bit ICV (no document)
512 ah-old: 128bit ICV (no document)
hmac-ripemd160 160 ah: 96bit ICV (RFC2857)
ah-old: 128bit ICV (no document)
aes-xcbc-mac 128 ah: 96bit ICV (RFC3566)
128 ah-old: 128bit ICV (no document)
tcp-md5 8 to 640 tcp: rfc2385
These encryption algorithms can be used as
ealgo
in
-E ealgo
of the
protocol
parameter:
algorithm keylen (bits)
des-cbc 64 esp-old: rfc1829, esp: rfc2405
3des-cbc 192 rfc2451
null 0 to 2048 rfc2410
blowfish-cbc 40 to 448 rfc2451
cast128-cbc 40 to 128 rfc2451
des-deriv 64 ipsec-ciph-des-derived-01
3des-deriv 192 no document
rijndael-cbc 128/192/256 rfc3602
twofish-cbc 0 to 256 draft-ietf-ipsec-ciph-aes-cbc-01
aes-ctr 160/224/288 draft-ietf-ipsec-ciph-aes-ctr-03
Note that the first 128 bits of a key for
aes-ctr
will be used as AES key, and the remaining 32 bits will be used as nonce.
These compression algorithms can be used as
calgo
in
-C calgo
of the
protocol
parameter:
algorithm
deflate rfc2394
In
kernel
mode,
setkey
manages and shows policies and SAs exactly as they are stored in the kernel.
In
RFC
mode,
setkey
add 3ffe:501:4819::1 3ffe:501:481d::1 esp 123457
-E des-cbc 0x3ffe05014819ffff ;
add -6 myhost.example.com yourhost.example.com ah 123456
-A hmac-sha1 "AH SA configuration!" ;
add 10.0.11.41 10.0.11.33 esp 0x10001
-E des-cbc 0x3ffe05014819ffff
-A hmac-md5 "authentication!!" ;
get 3ffe:501:4819::1 3ffe:501:481d::1 ah 123456 ;
flush ;
dump esp ;
spdadd 10.0.11.41/32[21] 10.0.11.33/32[any] any
-P out ipsec esp/tunnel/192.168.0.1-192.168.1.2/require ;
add 10.1.10.34 10.1.10.36 tcp 0x1000 -A tcp-md5 "TCP-MD5 BGP secret" ;
add 10.0.11.41 10.0.11.33 esp 0x10001
-ctx 1 1 "system_u:system_r:unconfined_t:SystemLow-SystemHigh"
-E des-cbc 0x3ffe05014819ffff;
spdadd 10.0.11.41 10.0.11.33 any
-ctx 1 1 "system_u:system_r:unconfined_t:SystemLow-SystemHigh"
-P out ipsec esp/transport//require ;
add -6 myhost.example.com yourhost.example.com ah 123456
-A hmac-sha1 "AH SA configuration!" ;
add 10.0.11.41 10.0.11.33 esp 0x10001
-E des-cbc 0x3ffe05014819ffff
-A hmac-md5 "authentication!!" ;
get 3ffe:501:4819::1 3ffe:501:481d::1 ah 123456 ;
flush ;
dump esp ;
spdadd 10.0.11.41/32[21] 10.0.11.33/32[any] any
-P out ipsec esp/tunnel/192.168.0.1-192.168.1.2/require ;
add 10.1.10.34 10.1.10.36 tcp 0x1000 -A tcp-md5 "TCP-MD5 BGP secret" ;
add 10.0.11.41 10.0.11.33 esp 0x10001
-ctx 1 1 "system_u:system_r:unconfined_t:SystemLow-SystemHigh"
-E des-cbc 0x3ffe05014819ffff;
spdadd 10.0.11.41 10.0.11.33 any
-ctx 1 1 "system_u:system_r:unconfined_t:SystemLow-SystemHigh"
-P out ipsec esp/transport//require ;
For IPsec gateway configuration,
src_range
and
dst_range
with TCP/UDP port numbers does not work, as the gateway does not
reassemble packets
(it cannot inspect upper-layer headers).
Advertisements
129 Lectures
23 hours
Eduonix Learning Solutions
5 Lectures
4.5 hours
Frahaan Hussain
35 Lectures
2 hours
Pradeep D
41 Lectures
2.5 hours
Musab Zayadneh
46 Lectures
4 hours
GUHARAJANM
6 Lectures
4 hours
Uplatz
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 10721,
"s": 10577,
"text": "\nsetkey\ntakes a series of operations from standard input\n(\nif invoked with\n-c \n)\nor the file named\n filename\n(\nif invoked with\n-f filename\n).\n"
},
{
"code": null,
"e": 10754,
"s": 10721,
"text": "\nMeta-arguments are as follows:\n"
},
{
"code": null,
"e": 10865,
"s": 10764,
"text": "\n key\nmust be a double-quoted character string, or a series of hexadecimal\ndigits preceded by\n\"0x\".\n"
},
{
"code": null,
"e": 10957,
"s": 10865,
"text": "\nPossible values for\n ealgo,\n aalgo,\nand\n calgo\nare specified in the\n Algorithms\nsections.\n"
},
{
"code": null,
"e": 11028,
"s": 10959,
"text": " address\n address/prefixlen\n address[port]\n address/prefixlen[port]\n"
},
{
"code": null,
"e": 11249,
"s": 11028,
"text": "\n prefixlen\nand\n port\nmust be decimal numbers.\nThe square brackets around\n port\nare really necessary,\nthey are not man page meta-characters.\nFor FQDN resolution, the rules applicable to\n src\nand\n dst\napply here as well.\n"
},
{
"code": null,
"e": 11297,
"s": 11251,
"text": " spdadd ::/0 ::/0 icmp6 135,0 -P in none;"
},
{
"code": null,
"e": 11637,
"s": 11299,
"text": "\n Note:\n upperspec\ndoes not work against forwarding case at this moment,\nas it requires extra reassembly at the forwarding node\n(not implemented at this moment).\nThere are many protocols in\n /etc/protocols,\nbut all protocols except of TCP, UDP, and ICMP may not be suitable\nto use with IPsec.\nYou have to consider carefully what to use.\n"
},
{
"code": null,
"e": 11742,
"s": 11641,
"text": "\nYou must specify the direction of its policy as\n direction.\nEither\n out,\n in,\nor\n fwd\ncan be used.\n"
},
{
"code": null,
"e": 12133,
"s": 11742,
"text": "\n priority specification\nis used to control the placement of the policy within the SPD.\nPolicy position is determined by\na signed integer where higher priorities indicate the policy is placed\ncloser to the beginning of the list and lower priorities indicate the\npolicy is placed closer to the end of the list.\nPolicies with equal priorities are added at the end of groups\nof such policies.\n"
},
{
"code": null,
"e": 12448,
"s": 12133,
"text": "\nPriority can only\nbe specified when setkey has been compiled against kernel headers that\nsupport policy priorities (Linux Gt]= 2.6.6).\nIf the kernel does not support priorities, a warning message will\nbe printed the first time a priority specification is used.\nPolicy priority takes one of the following formats:\n"
},
{
"code": null,
"e": 12574,
"s": 12448,
"text": "\n offset\nis an unsigned integer.\nIt can be up to 1073741824 for\npositive offsets, and up to 1073741823 for negative offsets.\n"
},
{
"code": null,
"e": 12772,
"s": 12574,
"text": "\ndiscard\nmeans the packet matching indexes will be discarded.\nnone\nmeans that IPsec operation will not take place onto the packet.\nipsec\nmeans that IPsec operation will take place onto the packet.\n"
},
{
"code": null,
"e": 14426,
"s": 12772,
"text": "\nThe\n protocol/mode/src-dst/level\npart specifies the rule how to process the packet.\nEither\nah,\nesp,\nor\nipcomp\nmust be used as\n protocol.\n mode\nis either\ntransport\nor\ntunnel.\nIf\n mode\nis\ntunnel,\nyou must specify the end-point addresses of the SA as\n src\nand\n dst\nwith\n'-'\nbetween these addresses, which is used to specify the SA to use.\nIf\n mode\nis\ntransport,\nboth\n src\nand\n dst\ncan be omitted.\n level\nis to be one of the following:\ndefault, use, require,\nor\nunique.\nIf the SA is not available in every level, the kernel will\nask the key exchange daemon to establish a suitable SA.\ndefault\nmeans the kernel consults the system wide default for the protocol\nyou specified, e.g. the\nesp_trans_deflev\nsysctl variable, when the kernel processes the packet.\nuse\nmeans that the kernel uses an SA if it’s available,\notherwise the kernel keeps normal operation.\nrequire\nmeans SA is required whenever the kernel sends a packet matched\nwith the policy.\nunique\nis the same as\nrequire;\nin addition, it allows the policy to match the unique out-bound SA.\nYou just specify the policy level\nunique,\nracoon(8)\nwill configure the SA for the policy.\nIf you configure the SA by manual keying for that policy,\nyou can put a decimal number as the policy identifier after\nunique\nseparated by a colon\n':'\nlike:\nunique:number\nin order to bind this policy to the SA.\nnumber\nmust be between 1 and 32767.\nIt corresponds to\n extensions-u \nof the manual SA configuration.\nWhen you want to use SA bundle, you can define multiple rules.\nFor example, if an IP header was followed by an AH header followed\nby an ESP header followed by an upper layer protocol header, the\nrule would be:\n"
},
{
"code": null,
"e": 14477,
"s": 14426,
"text": " esp/transport//require ah/transport//require;"
},
{
"code": null,
"e": 14514,
"s": 14477,
"text": "\n\nThe rule order is very important.\n"
},
{
"code": null,
"e": 14893,
"s": 14514,
"text": "\nWhen NAT-T is enabled in the kernel, policy matching for ESP over\nUDP packets may be done on endpoint addresses and port\n(this depends on the system.\nSystem that do not perform the port check cannot support\nmultiple endpoints behind the same NAT).\nWhen using ESP over UDP, you can specify port numbers in the endpoint\naddresses to get the correct matching.\nHere is an example:\n"
},
{
"code": null,
"e": 15018,
"s": 14893,
"text": "spdadd 10.0.11.0/24[any] 10.0.11.33/32[any] any -P out ipsec\n esp/tunnel/192.168.0.1[4500]-192.168.1.2[30000]/require ;\n\n"
},
{
"code": null,
"e": 15188,
"s": 15020,
"text": "\nNote that\n\"discard\"\nand\n\"none\"\nare not in the syntax described in\nipsec_set_policy(3).\nThere are a few differences in the syntax.\nSee\nipsec_set_policy(3)\nfor detail.\n"
},
{
"code": null,
"e": 16416,
"s": 15190,
"text": "algorithm keylen (bits)\nhmac-md5 128 ah: rfc2403\n 128 ah-old: rfc2085\nhmac-sha1 160 ah: rfc2404\n 160 ah-old: 128bit ICV (no document)\nkeyed-md5 128 ah: 96bit ICV (no document)\n 128 ah-old: rfc1828\nkeyed-sha1 160 ah: 96bit ICV (no document)\n 160 ah-old: 128bit ICV (no document)\nnull 0 to 2048 for debugging\nhmac-sha256 256 ah: 96bit ICV\n (draft-ietf-ipsec-ciph-sha-256-00)\n 256 ah-old: 128bit ICV (no document)\nhmac-sha384 384 ah: 96bit ICV (no document)\n 384 ah-old: 128bit ICV (no document)\nhmac-sha512 512 ah: 96bit ICV (no document)\n 512 ah-old: 128bit ICV (no document)\nhmac-ripemd160 160 ah: 96bit ICV (RFC2857)\n ah-old: 128bit ICV (no document)\naes-xcbc-mac 128 ah: 96bit ICV (RFC3566)\n 128 ah-old: 128bit ICV (no document)\ntcp-md5 8 to 640 tcp: rfc2385\n"
},
{
"code": null,
"e": 16509,
"s": 16416,
"text": "\nThese encryption algorithms can be used as\n ealgo\nin\n-E ealgo\nof the\n protocol\nparameter:\n"
},
{
"code": null,
"e": 17037,
"s": 16511,
"text": "algorithm keylen (bits)\ndes-cbc 64 esp-old: rfc1829, esp: rfc2405\n3des-cbc 192 rfc2451\nnull 0 to 2048 rfc2410\nblowfish-cbc 40 to 448 rfc2451\ncast128-cbc 40 to 128 rfc2451\ndes-deriv 64 ipsec-ciph-des-derived-01\n3des-deriv 192 no document\nrijndael-cbc 128/192/256 rfc3602\ntwofish-cbc 0 to 256 draft-ietf-ipsec-ciph-aes-cbc-01\naes-ctr 160/224/288 draft-ietf-ipsec-ciph-aes-ctr-03\n"
},
{
"code": null,
"e": 17163,
"s": 17037,
"text": "\nNote that the first 128 bits of a key for\naes-ctr\nwill be used as AES key, and the remaining 32 bits will be used as nonce.\n"
},
{
"code": null,
"e": 17257,
"s": 17163,
"text": "\nThese compression algorithms can be used as\n calgo\nin\n-C calgo\nof the\n protocol\nparameter:\n"
},
{
"code": null,
"e": 17294,
"s": 17259,
"text": "algorithm\ndeflate rfc2394\n"
},
{
"code": null,
"e": 17397,
"s": 17294,
"text": "\nIn\n kernel\nmode,\nsetkey\nmanages and shows policies and SAs exactly as they are stored in the kernel.\n"
},
{
"code": null,
"e": 17420,
"s": 17397,
"text": "\nIn\n RFC\nmode,\nsetkey\n"
},
{
"code": null,
"e": 18291,
"s": 17420,
"text": "add 3ffe:501:4819::1 3ffe:501:481d::1 esp 123457\n -E des-cbc 0x3ffe05014819ffff ;\n\nadd -6 myhost.example.com yourhost.example.com ah 123456\n -A hmac-sha1 \"AH SA configuration!\" ;\n\nadd 10.0.11.41 10.0.11.33 esp 0x10001\n -E des-cbc 0x3ffe05014819ffff\n -A hmac-md5 \"authentication!!\" ;\n\nget 3ffe:501:4819::1 3ffe:501:481d::1 ah 123456 ;\n\nflush ;\n\ndump esp ;\n\nspdadd 10.0.11.41/32[21] 10.0.11.33/32[any] any\n -P out ipsec esp/tunnel/192.168.0.1-192.168.1.2/require ;\n\nadd 10.1.10.34 10.1.10.36 tcp 0x1000 -A tcp-md5 \"TCP-MD5 BGP secret\" ;\n\nadd 10.0.11.41 10.0.11.33 esp 0x10001\n -ctx 1 1 \"system_u:system_r:unconfined_t:SystemLow-SystemHigh\"\n -E des-cbc 0x3ffe05014819ffff;\n\nspdadd 10.0.11.41 10.0.11.33 any\n -ctx 1 1 \"system_u:system_r:unconfined_t:SystemLow-SystemHigh\"\n -P out ipsec esp/transport//require ;\n"
},
{
"code": null,
"e": 18396,
"s": 18291,
"text": "\nadd -6 myhost.example.com yourhost.example.com ah 123456\n -A hmac-sha1 \"AH SA configuration!\" ;\n"
},
{
"code": null,
"e": 18515,
"s": 18396,
"text": "\nadd 10.0.11.41 10.0.11.33 esp 0x10001\n -E des-cbc 0x3ffe05014819ffff\n -A hmac-md5 \"authentication!!\" ;\n"
},
{
"code": null,
"e": 18567,
"s": 18515,
"text": "\nget 3ffe:501:4819::1 3ffe:501:481d::1 ah 123456 ;\n"
},
{
"code": null,
"e": 18577,
"s": 18567,
"text": "\nflush ;\n"
},
{
"code": null,
"e": 18590,
"s": 18577,
"text": "\ndump esp ;\n"
},
{
"code": null,
"e": 18706,
"s": 18590,
"text": "\nspdadd 10.0.11.41/32[21] 10.0.11.33/32[any] any\n -P out ipsec esp/tunnel/192.168.0.1-192.168.1.2/require ;\n"
},
{
"code": null,
"e": 18779,
"s": 18706,
"text": "\nadd 10.1.10.34 10.1.10.36 tcp 0x1000 -A tcp-md5 \"TCP-MD5 BGP secret\" ;\n"
},
{
"code": null,
"e": 18929,
"s": 18779,
"text": "\nadd 10.0.11.41 10.0.11.33 esp 0x10001\n -ctx 1 1 \"system_u:system_r:unconfined_t:SystemLow-SystemHigh\"\n -E des-cbc 0x3ffe05014819ffff;\n"
},
{
"code": null,
"e": 19081,
"s": 18929,
"text": "\nspdadd 10.0.11.41 10.0.11.33 any\n -ctx 1 1 \"system_u:system_r:unconfined_t:SystemLow-SystemHigh\"\n -P out ipsec esp/transport//require ;\n"
},
{
"code": null,
"e": 19276,
"s": 19081,
"text": "\nFor IPsec gateway configuration,\n src_range\nand\n dst_range\nwith TCP/UDP port numbers does not work, as the gateway does not\nreassemble packets\n(it cannot inspect upper-layer headers).\n\n\n\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 19293,
"s": 19276,
"text": "\nAdvertisements\n"
},
{
"code": null,
"e": 19328,
"s": 19293,
"text": "\n 129 Lectures \n 23 hours \n"
},
{
"code": null,
"e": 19356,
"s": 19328,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 19390,
"s": 19356,
"text": "\n 5 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 19407,
"s": 19390,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 19440,
"s": 19407,
"text": "\n 35 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 19451,
"s": 19440,
"text": " Pradeep D"
},
{
"code": null,
"e": 19486,
"s": 19451,
"text": "\n 41 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 19502,
"s": 19486,
"text": " Musab Zayadneh"
},
{
"code": null,
"e": 19535,
"s": 19502,
"text": "\n 46 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 19547,
"s": 19535,
"text": " GUHARAJANM"
},
{
"code": null,
"e": 19579,
"s": 19547,
"text": "\n 6 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 19587,
"s": 19579,
"text": " Uplatz"
},
{
"code": null,
"e": 19594,
"s": 19587,
"text": " Print"
},
{
"code": null,
"e": 19605,
"s": 19594,
"text": " Add Notes"
}
] |
Gerrit - Add SSH Key to use with Git | You can add SSH key to Git using the following commands −
Step 1 − Open Git Bash and get the ssh-agent using the following command.
Step 1 − Open Git Bash and get the ssh-agent using the following command.
$ eval 'ssh-agent'
Step 2 − Next, add the SSH key to the ssh-agent using the following command
Step 2 − Next, add the SSH key to the ssh-agent using the following command
$ ssh-add ~/.ssh/id_rsa
Step 3 − Now, run the ssh using the following command, which matches the SSH fingerprint used when logging for the first time.
Step 3 − Now, run the ssh using the following command, which matches the SSH fingerprint used when logging for the first time.
$ ssh -p 29418 <user_name>@gerrit.wikimedia.org
In the above screenshot, you can see that xyz123 is a instance shell account name, which is used while creating Gerrit account and Abc123 is a user name of your Gerrit account.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2296,
"s": 2238,
"text": "You can add SSH key to Git using the following commands −"
},
{
"code": null,
"e": 2370,
"s": 2296,
"text": "Step 1 − Open Git Bash and get the ssh-agent using the following command."
},
{
"code": null,
"e": 2444,
"s": 2370,
"text": "Step 1 − Open Git Bash and get the ssh-agent using the following command."
},
{
"code": null,
"e": 2464,
"s": 2444,
"text": "$ eval 'ssh-agent'\n"
},
{
"code": null,
"e": 2540,
"s": 2464,
"text": "Step 2 − Next, add the SSH key to the ssh-agent using the following command"
},
{
"code": null,
"e": 2616,
"s": 2540,
"text": "Step 2 − Next, add the SSH key to the ssh-agent using the following command"
},
{
"code": null,
"e": 2641,
"s": 2616,
"text": "$ ssh-add ~/.ssh/id_rsa\n"
},
{
"code": null,
"e": 2768,
"s": 2641,
"text": "Step 3 − Now, run the ssh using the following command, which matches the SSH fingerprint used when logging for the first time."
},
{
"code": null,
"e": 2895,
"s": 2768,
"text": "Step 3 − Now, run the ssh using the following command, which matches the SSH fingerprint used when logging for the first time."
},
{
"code": null,
"e": 2944,
"s": 2895,
"text": "$ ssh -p 29418 <user_name>@gerrit.wikimedia.org\n"
},
{
"code": null,
"e": 3121,
"s": 2944,
"text": "In the above screenshot, you can see that xyz123 is a instance shell account name, which is used while creating Gerrit account and Abc123 is a user name of your Gerrit account."
},
{
"code": null,
"e": 3128,
"s": 3121,
"text": " Print"
},
{
"code": null,
"e": 3139,
"s": 3128,
"text": " Add Notes"
}
] |
How can I set the default value for an HTML <select> element? | With HTML, you can easily create a simple drop down list of items to get user input in HTML forms. Use the <select> element for this, which is a select box, also called drop down box, with option to list down items.
Also, you can set the default value from the dropdown list of items in HTML forms. For that, add selected in the <option> tag for the value you want to preselect.
You can try to run the following code to learn how to set the default value for HTML <select> element −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>HTML Select Element</title>
</head>
<body>
<p> Select any one:</p>
<form>
<select name = "dropdown">
<option value = "Java">Java</option>
<option value = "Discrete Mathematics" selected >Discrete Mathematics</option>
<option value = "Chemistry">Chemistry</option>
</select>
</form>
</body>
</html> | [
{
"code": null,
"e": 1278,
"s": 1062,
"text": "With HTML, you can easily create a simple drop down list of items to get user input in HTML forms. Use the <select> element for this, which is a select box, also called drop down box, with option to list down items."
},
{
"code": null,
"e": 1441,
"s": 1278,
"text": "Also, you can set the default value from the dropdown list of items in HTML forms. For that, add selected in the <option> tag for the value you want to preselect."
},
{
"code": null,
"e": 1545,
"s": 1441,
"text": "You can try to run the following code to learn how to set the default value for HTML <select> element −"
},
{
"code": null,
"e": 1555,
"s": 1545,
"text": "Live Demo"
},
{
"code": null,
"e": 1980,
"s": 1555,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML Select Element</title>\n </head>\n <body>\n <p> Select any one:</p>\n <form>\n <select name = \"dropdown\">\n <option value = \"Java\">Java</option>\n <option value = \"Discrete Mathematics\" selected >Discrete Mathematics</option>\n <option value = \"Chemistry\">Chemistry</option>\n </select>\n </form>\n </body>\n</html>"
}
] |
Let's Create a COVID-19 Tracker using React.js | by Sabesan Sathananthan | Towards Data Science | Most people in the world stay at home these days because of the lockdown. Most of you are frustrated about staying at home for a long time. Therefore, we will make a COVID-19 tracking application and get pleasure about that we create a tracking application. we will fetch the data from this link.
When I scrolled Youtube videos I found a tutorial about how to make the Corona Virus tracking application. I watched that video and started to create a COVID-19 tracker and Finally, I created a Tracker using React.js. I added some features more than shown in the video. Here I will describe how to create a tracking application using React application from scratch. Here is the demo of that React application. This is my 30th article in Medium.
As usual, we need to create a React application using create-react-app. To create a React application run the following command in your shell/terminal in a specific folder (e.g. desktop )
npx create-react-app covid-tracker
A new folder will be created, and it will be named as google-map. From this step, our application is bootstrapped with Create React App. For more information, click the link. Then open that project in your IDE. I am using VS Code IDE.
Delete all the files inside the src folder and create an app.js file and index.js file inside the src folder.
Now, in our src folder directory we create an index.js file with the following code:
Then create the api folder, Components folder, and images folder inside the src folder. Thereafter create the Cards folder, Chart folder, CountryPicker folder, and index.js file inside the component folder. Now our project’s folder structure should like below:
With this project structure, each folder (Cards, Chart, CountryPicker) is going to have its own styles and its own component.
Now we need to install all the necessary dependencies for that run the following command in your shell/terminal which was integrated with VSCode or your IDE.
npm install --save axios react-chartjs-2 react-countup classnames @material-ui/core
In case you’re having issues installing dependencies, Try
npm cache clean — force
With the help of Axios, we will make a get request to the API. ‘react-chartjs-2’ is one of the better libraries for making charts. ‘react-countup’ is going to help us make that animation while counting numbers. ‘classnames’ is a library that provides us conditional class selection in React. ‘Material-UI’ is the world’s most popular React UI framework like bootstrap.
We need to fetch the data from the API. Now, in our api folder directory we create an index.js file with the following code:
It loads Axios, which is responsible for REST calls. As you can see, we are making 3 different calls for Chart, Cards & CountryPicker.
fetchData function is to fetch the confirmed, recovered, and death details with last updated time according to the worldwide or according to the country wise. fetchData function helps to fetch the data to display the results in the Cards component.
fetchDailyData function is to fetch the daily total deaths and total confirmed details with the respective dates. Unfortunately, we couldn’t fetch the total recovered details now (today: 18-Jun-2020). fetchDailyData function helps to fetch the data to display the results in the Chart component.
fetchCountries function is to map the country’s shortened name with the Country’s name. fetchCountries function helps to fetch the country name to display the results in the CountryPicker component.
This component loads 4 cards: Infected, Recovered, deaths, and active on the top of the website. Now we are going to create Cards.jsx file inside the Cards folder with the following code:
Cards component is a purely functional component that returns JSX. I calculated the active cases by subtracting the recovered cases and death cases from confirmed cases. There is no point of creating the Cards component without styling, therefore, we are going to create Cards.module.css file inside the Cards folder with the following code:
@media tag is responsible for the responsive view.
Yeah, we finished the Cards component !!
This loads both bar and line charts: Line chart to show global data and bar chart to represent a single country. Now we are going to create Chart.jsx file inside the Chart folder with the following code:
Chart component is a purely functional component that returns JSX. There is no point of creating the Chart component without styling, therefore, we are going to create Chart.module.css file inside the Chart folder with the following code:
Drop down to select a country based on the selected country showing a bar chart and showing cards with death, confirmed, active, and recovered details for that particular country. Now we are going to create CountryPicker.jsx file inside the CountryPicker folder with the following code:
CountryPicker component is a purely functional component that returns JSX. There is no point of creating the CountryPicker component without styling, therefore, we are going to create CountryPicker.module.css file inside the CountryPicker folder with the following code:
If we are going to import Cards, Chart and CountryPicker Components in App.js like below would just clutter up your App.js.
import Cards from "./Components/Cards/Cards";import Chart from "./Components/Chart/Chart";import CountryPicker from "./Components/CountryPicker/CountryPicker";
Therefore, we need to use a neat little trick. We don’t need to have imports like above. As you can see there is a lot of repetitive code. We spend lot of time specifying where we want to import from what we want to import from. Therefore we can have one import file like below.
import { Cards, Chart, CountryPicker } from “./Components”;
Now we are going to create an index.js file inside the Components folder with the following code:
After adding all the functionalities we need to update App.js. App Component is responsible for sending country & data together into a single view so the website can dynamically change based on the country’s selection whether to show a bar chart or line chart. Now we are going to add the following Code into the App.js which is in the src folder.
Here you can download the coronaImage and add it into the images folder which we created inside the src folder. App Component is a class component that has asynchronous React lifecycle method componentDidMount. we need to add some styling to the App.js component. Therefore we need to add the App.module.css file inside the src folder with the following code:
Boom!!! Our Covid-19 Tracking Application is ready. Start the application by running the following command
npm start
The features of the above website are easy to use, attractive UI, charts speaks more than text, real-time data, and last but not least, it is a responsive website for both desktop & mobile view. Covid-19 API is Serving data from John Hopkins University CSSE as a JSON API. You can clone the repo from this link. Finally I would like to thank JavaScript Mastery for the YouTube Video.
Try something new today. Feel good about yourself. | [
{
"code": null,
"e": 469,
"s": 172,
"text": "Most people in the world stay at home these days because of the lockdown. Most of you are frustrated about staying at home for a long time. Therefore, we will make a COVID-19 tracking application and get pleasure about that we create a tracking application. we will fetch the data from this link."
},
{
"code": null,
"e": 914,
"s": 469,
"text": "When I scrolled Youtube videos I found a tutorial about how to make the Corona Virus tracking application. I watched that video and started to create a COVID-19 tracker and Finally, I created a Tracker using React.js. I added some features more than shown in the video. Here I will describe how to create a tracking application using React application from scratch. Here is the demo of that React application. This is my 30th article in Medium."
},
{
"code": null,
"e": 1102,
"s": 914,
"text": "As usual, we need to create a React application using create-react-app. To create a React application run the following command in your shell/terminal in a specific folder (e.g. desktop )"
},
{
"code": null,
"e": 1137,
"s": 1102,
"text": "npx create-react-app covid-tracker"
},
{
"code": null,
"e": 1372,
"s": 1137,
"text": "A new folder will be created, and it will be named as google-map. From this step, our application is bootstrapped with Create React App. For more information, click the link. Then open that project in your IDE. I am using VS Code IDE."
},
{
"code": null,
"e": 1482,
"s": 1372,
"text": "Delete all the files inside the src folder and create an app.js file and index.js file inside the src folder."
},
{
"code": null,
"e": 1567,
"s": 1482,
"text": "Now, in our src folder directory we create an index.js file with the following code:"
},
{
"code": null,
"e": 1828,
"s": 1567,
"text": "Then create the api folder, Components folder, and images folder inside the src folder. Thereafter create the Cards folder, Chart folder, CountryPicker folder, and index.js file inside the component folder. Now our project’s folder structure should like below:"
},
{
"code": null,
"e": 1954,
"s": 1828,
"text": "With this project structure, each folder (Cards, Chart, CountryPicker) is going to have its own styles and its own component."
},
{
"code": null,
"e": 2112,
"s": 1954,
"text": "Now we need to install all the necessary dependencies for that run the following command in your shell/terminal which was integrated with VSCode or your IDE."
},
{
"code": null,
"e": 2196,
"s": 2112,
"text": "npm install --save axios react-chartjs-2 react-countup classnames @material-ui/core"
},
{
"code": null,
"e": 2254,
"s": 2196,
"text": "In case you’re having issues installing dependencies, Try"
},
{
"code": null,
"e": 2278,
"s": 2254,
"text": "npm cache clean — force"
},
{
"code": null,
"e": 2647,
"s": 2278,
"text": "With the help of Axios, we will make a get request to the API. ‘react-chartjs-2’ is one of the better libraries for making charts. ‘react-countup’ is going to help us make that animation while counting numbers. ‘classnames’ is a library that provides us conditional class selection in React. ‘Material-UI’ is the world’s most popular React UI framework like bootstrap."
},
{
"code": null,
"e": 2772,
"s": 2647,
"text": "We need to fetch the data from the API. Now, in our api folder directory we create an index.js file with the following code:"
},
{
"code": null,
"e": 2907,
"s": 2772,
"text": "It loads Axios, which is responsible for REST calls. As you can see, we are making 3 different calls for Chart, Cards & CountryPicker."
},
{
"code": null,
"e": 3156,
"s": 2907,
"text": "fetchData function is to fetch the confirmed, recovered, and death details with last updated time according to the worldwide or according to the country wise. fetchData function helps to fetch the data to display the results in the Cards component."
},
{
"code": null,
"e": 3452,
"s": 3156,
"text": "fetchDailyData function is to fetch the daily total deaths and total confirmed details with the respective dates. Unfortunately, we couldn’t fetch the total recovered details now (today: 18-Jun-2020). fetchDailyData function helps to fetch the data to display the results in the Chart component."
},
{
"code": null,
"e": 3651,
"s": 3452,
"text": "fetchCountries function is to map the country’s shortened name with the Country’s name. fetchCountries function helps to fetch the country name to display the results in the CountryPicker component."
},
{
"code": null,
"e": 3839,
"s": 3651,
"text": "This component loads 4 cards: Infected, Recovered, deaths, and active on the top of the website. Now we are going to create Cards.jsx file inside the Cards folder with the following code:"
},
{
"code": null,
"e": 4181,
"s": 3839,
"text": "Cards component is a purely functional component that returns JSX. I calculated the active cases by subtracting the recovered cases and death cases from confirmed cases. There is no point of creating the Cards component without styling, therefore, we are going to create Cards.module.css file inside the Cards folder with the following code:"
},
{
"code": null,
"e": 4232,
"s": 4181,
"text": "@media tag is responsible for the responsive view."
},
{
"code": null,
"e": 4273,
"s": 4232,
"text": "Yeah, we finished the Cards component !!"
},
{
"code": null,
"e": 4477,
"s": 4273,
"text": "This loads both bar and line charts: Line chart to show global data and bar chart to represent a single country. Now we are going to create Chart.jsx file inside the Chart folder with the following code:"
},
{
"code": null,
"e": 4716,
"s": 4477,
"text": "Chart component is a purely functional component that returns JSX. There is no point of creating the Chart component without styling, therefore, we are going to create Chart.module.css file inside the Chart folder with the following code:"
},
{
"code": null,
"e": 5003,
"s": 4716,
"text": "Drop down to select a country based on the selected country showing a bar chart and showing cards with death, confirmed, active, and recovered details for that particular country. Now we are going to create CountryPicker.jsx file inside the CountryPicker folder with the following code:"
},
{
"code": null,
"e": 5274,
"s": 5003,
"text": "CountryPicker component is a purely functional component that returns JSX. There is no point of creating the CountryPicker component without styling, therefore, we are going to create CountryPicker.module.css file inside the CountryPicker folder with the following code:"
},
{
"code": null,
"e": 5398,
"s": 5274,
"text": "If we are going to import Cards, Chart and CountryPicker Components in App.js like below would just clutter up your App.js."
},
{
"code": null,
"e": 5558,
"s": 5398,
"text": "import Cards from \"./Components/Cards/Cards\";import Chart from \"./Components/Chart/Chart\";import CountryPicker from \"./Components/CountryPicker/CountryPicker\";"
},
{
"code": null,
"e": 5837,
"s": 5558,
"text": "Therefore, we need to use a neat little trick. We don’t need to have imports like above. As you can see there is a lot of repetitive code. We spend lot of time specifying where we want to import from what we want to import from. Therefore we can have one import file like below."
},
{
"code": null,
"e": 5897,
"s": 5837,
"text": "import { Cards, Chart, CountryPicker } from “./Components”;"
},
{
"code": null,
"e": 5995,
"s": 5897,
"text": "Now we are going to create an index.js file inside the Components folder with the following code:"
},
{
"code": null,
"e": 6343,
"s": 5995,
"text": "After adding all the functionalities we need to update App.js. App Component is responsible for sending country & data together into a single view so the website can dynamically change based on the country’s selection whether to show a bar chart or line chart. Now we are going to add the following Code into the App.js which is in the src folder."
},
{
"code": null,
"e": 6703,
"s": 6343,
"text": "Here you can download the coronaImage and add it into the images folder which we created inside the src folder. App Component is a class component that has asynchronous React lifecycle method componentDidMount. we need to add some styling to the App.js component. Therefore we need to add the App.module.css file inside the src folder with the following code:"
},
{
"code": null,
"e": 6810,
"s": 6703,
"text": "Boom!!! Our Covid-19 Tracking Application is ready. Start the application by running the following command"
},
{
"code": null,
"e": 6820,
"s": 6810,
"text": "npm start"
},
{
"code": null,
"e": 7204,
"s": 6820,
"text": "The features of the above website are easy to use, attractive UI, charts speaks more than text, real-time data, and last but not least, it is a responsive website for both desktop & mobile view. Covid-19 API is Serving data from John Hopkins University CSSE as a JSON API. You can clone the repo from this link. Finally I would like to thank JavaScript Mastery for the YouTube Video."
}
] |
How To Analyse NDVI Trend. Analyzing the annual maximum NDVI trend... | by Ravindu Kavishwara | Towards Data Science | The normalized difference vegetation index (NDVI) is a simple graphical indication that may be used to analyse remote sensing data, often from a space platform, to determine whether or not the objective under observation has living green vegetation.
Satellite data of the Normalized Difference Vegetation Index can be used to quantify changing patterns in ecosystem productivity (NDVI). The estimate of trends using NDVI time series, on the other hand, varies significantly depending on the studied satellite dataset, the related spatiotemporal resolution, and the statistical approach used. We analyze the efficacy of a variety of trend estimate approaches and show that performance diminishes as inter-annual variability in the NDVI time series increases.
The Environmental Systems Research Institute maintains ArcGIS, a geographic information system for dealing with maps and geographic information. It is used to create and utilize maps, collect geographic data, analyze mapped information, distribute and find geographic information, use maps and geographic information in a variety of applications, and manage geographic data in a database.
I utilize Arcpy.ia and the ArcGis API for Python in this scenario. arcpy.ia is a Python module for managing and processing images and raster data. The module also provides all of the geoprocessing methods given by the ArcGIS Image Analyst extension, as well as enhanced functions and classes that allow you to automate your raster processing workflows.
Without any further ado, let’s get started. I’ll describe the procedure as I explain the code. First, I import the required modules into my workflow.
import osimport matplotlib.pyplot as pltimport arcpyarcpy.CheckOutExtension("ImageAnalyst")
I set up my data folder. I collected this data from U.S. Geological Survey, and you can get similar data by registering with U.S. Geological Survey. I also created four arrays for future use.
folder = r"\\landsat\\LE70820552011359EDC00"raster_lists = []acquisition_time = []names = []quality_bands = []
In the code below, I retrieve all tif files from the source folder and add them to the raster dataset. I also include the acquisition time and filename for each array. However, before adding the filename, I change it with .xml.
for directory in sorted(os.listdir(folder)):for file in os.listdir(folder+"\\"+directory):if file.endswith("xml") and len(file.split(".")) == 2:raster_lists.append(folder+"\\"+directory+"\\"+file)time = file.split("_")[3]acquisition_time.append(time[:4]+"-"+time[4:6]+"-"+time[6:])names.append(file.replace(".xml", ""))quality_bands.append(folder+"\\"+directory+"\\"+file.replace(".xml", "") + "_pixel_qa.tif")
To generate a raster collection, I utilize the RasterCollection method. The RasterCollection object easily sorts and filters a bunch of rasters and prepares a collection for subsequent processing and analysis. The RasterCollection object has six methods for generating statistics for each pixel across matching bands inside the collection’s rasters (max, min, median, mean, majority, and sum).
rc = arcpy.ia.RasterCollection(raster_lists, {"Varieble": "Landsat7", names, "STDTime": acquisition_time, "Quantity": quality_bands})
The dataset we’re utilizing has data covering 18 years. So I’m just going to use only 10 years of data. We may accomplish this by using the filterByCalanderRange function.
filtered_rc = rc.filterByCalenderRange(calender_field = "YEAR", start = 1997, end = 2007)
No, we can view the Raster Collection.
filtered_rc
The result is as follows. As we can see, it’s displaying variables, names, and so on.
The code below retrieves the raster from the collection’s final entry. I use the arcpy.ia.Render function to render the result and the exportImage method to display it as an image.
To improve symbology, use the Render function to adjust the appearance of a raster object. When working in a Jupyter notebook, where data presentation is a crucial advantage, this function comes in useful. The function generates a raster object using the specified rendering rule or color map. At least one rendering rule or color map must be given.
first_item = filtered_rc[0]['Raster']rendered_raster = arcpy.ia.Render(first_item_raster, rendering_rule = {"bands": [3, 2, 1], "min": 500, "max": 1000, colormap='NDVI'})rendered_raster.exportImage(width = 500)
This is the resulting picture. As we can see, this image has a lot of clouds. As a result, we must clean up this image.
In the Pre-processing phase, I’m going to process the previously obtained image and remove clouds, shadows, water, and snow.
In the code below, I first retrieve the raster and the quality of each raster. Then I save the pixel values that I need to remove from the raster. Following that, I use arcpy.ia.Apply with bandRaster to apply to each and every raster. bandRaster will mask the pixels in the specified RGB bands. Then I assign a cleaned rater and assign it to return.
def clean(item):raster - item["Raster"]qa_raster = arcpy.Raster(item["Quantity"])values_tb = (qa_raster != 68) & (qa_raster != 72) & (qa_raster != 80) & (qa_raster != 96) & (qa_raster != 132) & (qa_raster != 136) & (qa_raster != 112) & (qa_raster != 144) & (qa_raster != 160) & (qa_raster != 176)masked_clean_band_list = []for bandRaster in raster.getRasterBands([1, 2, 3, 4, 5, 6]):masked_clean_band = arcpy.ia.Apply((values_tb, bandRaster, 0), "Local", args = {"Operation": "StdTime"})masked_clean_band_list.append(masked_clean_band)masked_clean_raster = arcpy.ia.CompositeBand(masked_clean_band_list)return {"raster": masked_clean_raster, "Name" : item["Name"], "StdTime" : item["StdTime"]}cleaned_rc = filtered_rc.map(clean)
Using this code, I retrieve the raster within the collection’s second item.
first_item_raster = cleaned_rc[0]['Raster']rendered_raster = arcpy.ia.Render(first_item_raster, rendering_rule = {"bands": [3, 2, 1], "min": 500, "max": 1000, colormap='NDVI'})renderes_raster.exportImage(width = 500)
As shown in the image below, the whole water area has been masked out.
I define a method called clacNDVI to calculate NDVI, and I use arcpy.ia.NDVI to create an NDVI raster from an item raster and two band values. Finally, I return parameters like item, name, and standard time.
def clacNDVI(item):ndvi = arcpy.ia.NDVI(item['Raster'], nir_band_id = 4, red_band = 3)return {"raster": ndvi, "Name": item["Name"], "StdTime": item["StdTime"]}ndvi_rc = cleaned_rc.map(calcNDVI)
When we call the function, we get the NDVI raster.
Let’s visualize the raster in the same way that I did earlier.
first_item_raster = ndvi_rc[0]['Raster']rendered_raster = arcpy.ia.Render(first_item_raster, rendering_rule = {"bands": [3, 2, 1], "min": 0, "max": 1.0, colormap='NDVI'})rendred_raster.exportImage(width = 500)
It’s the same raster as the one in previous. However, it is now displaying NDVI.
I converted the multidimensional raster collection using the code below. This method returns a multidimensional raster dataset, with each item in the raster collection representing a slice in the multidimensional raster.
anual_max_ndvi_mdraster = arcpy.ia.Aggregate(ndvi_mdraster, demension_name = "StdTime", raster_function = "MaxIgnoreNoData", aggregate_definition = {"interval": "yearly"})
I use the arcpy.ia.Aggregate function to determine the maximum NDVI each year. This method generates a raster object based on the provided multidimensional raster. Aggregation is computed by default for all variables linked with the chosen dimension. In this case, I’m using STDTime as the dimension time and MaxIgnoreNoData as the raster function with an annual interval time.
Now I apply linear trend for the annual maximum multidimensional raster. The linear trend line is a best-fit straight line for estimating basic linear relationships. A linear trend denotes a pace of change that increases or decreases at a consistent rate.
max_ndvi_linear_trend = arcpy.ia.Apply(Annual_max_ndvi_mdraster, "TrendAnalysis", raster_function_arguments = {"DimensionName": "StdTime", "RegressionType": 0})
We can retrieve the slope of the trend raster using the code below. getRasterBands returns a Raster object for each band supplied in a multiband raster dataset. In this situation, I use 1 as the raster band.
slope - max_ndvi_linear_trend.getRaterBands(1)
To modify negative pixel values, I utilize the remap function. The remap function allows you to alter or reclassify raster data pixel values. This may be accomplished by either supplying a range of pixel values to map to an output pixel value or by mapping the pixel values to output pixel values using a table. As a result, the output will be a boolean map.
increase_decrease_trend_map = arcpy.ia.Remap(slope, input_ranges=[-10000, 0, 0, 10000], output_values=[-1, 1])
I use the render function with different colors to render (green and gray).
rendered_raster = arcpy.ia.Render(increase_decrease_trend_map, colormap = {"values":[0, 1], "colors": ["#B0C4DE", "green", "gray"]})rendered_raster.exportImage(width = 500)
When we look at this image, we can see that the NDVI is increasing in the green area. The grey spots on the image represent NDVI-decreasing areas.
NDVI is a pixel-by-pixel mathematical computation performed on an image with GIS tools. It is a plant health indicator determined by measuring the absorption and reflection of red and near-infrared light. NDVI may be used to study land all over the world, making it suitable for both focused field studies and continental or global-scale vegetation monitoring. ArcGIS, a geographic information system for dealing with maps and geographic information, is maintained by the Environmental Systems Research Institute. ArcGIS can be used to calculate NDVI.
Reference
What is NDVI (Normalized Difference Vegetation Index)? | [
{
"code": null,
"e": 422,
"s": 172,
"text": "The normalized difference vegetation index (NDVI) is a simple graphical indication that may be used to analyse remote sensing data, often from a space platform, to determine whether or not the objective under observation has living green vegetation."
},
{
"code": null,
"e": 930,
"s": 422,
"text": "Satellite data of the Normalized Difference Vegetation Index can be used to quantify changing patterns in ecosystem productivity (NDVI). The estimate of trends using NDVI time series, on the other hand, varies significantly depending on the studied satellite dataset, the related spatiotemporal resolution, and the statistical approach used. We analyze the efficacy of a variety of trend estimate approaches and show that performance diminishes as inter-annual variability in the NDVI time series increases."
},
{
"code": null,
"e": 1319,
"s": 930,
"text": "The Environmental Systems Research Institute maintains ArcGIS, a geographic information system for dealing with maps and geographic information. It is used to create and utilize maps, collect geographic data, analyze mapped information, distribute and find geographic information, use maps and geographic information in a variety of applications, and manage geographic data in a database."
},
{
"code": null,
"e": 1672,
"s": 1319,
"text": "I utilize Arcpy.ia and the ArcGis API for Python in this scenario. arcpy.ia is a Python module for managing and processing images and raster data. The module also provides all of the geoprocessing methods given by the ArcGIS Image Analyst extension, as well as enhanced functions and classes that allow you to automate your raster processing workflows."
},
{
"code": null,
"e": 1822,
"s": 1672,
"text": "Without any further ado, let’s get started. I’ll describe the procedure as I explain the code. First, I import the required modules into my workflow."
},
{
"code": null,
"e": 1914,
"s": 1822,
"text": "import osimport matplotlib.pyplot as pltimport arcpyarcpy.CheckOutExtension(\"ImageAnalyst\")"
},
{
"code": null,
"e": 2106,
"s": 1914,
"text": "I set up my data folder. I collected this data from U.S. Geological Survey, and you can get similar data by registering with U.S. Geological Survey. I also created four arrays for future use."
},
{
"code": null,
"e": 2217,
"s": 2106,
"text": "folder = r\"\\\\landsat\\\\LE70820552011359EDC00\"raster_lists = []acquisition_time = []names = []quality_bands = []"
},
{
"code": null,
"e": 2445,
"s": 2217,
"text": "In the code below, I retrieve all tif files from the source folder and add them to the raster dataset. I also include the acquisition time and filename for each array. However, before adding the filename, I change it with .xml."
},
{
"code": null,
"e": 2856,
"s": 2445,
"text": "for directory in sorted(os.listdir(folder)):for file in os.listdir(folder+\"\\\\\"+directory):if file.endswith(\"xml\") and len(file.split(\".\")) == 2:raster_lists.append(folder+\"\\\\\"+directory+\"\\\\\"+file)time = file.split(\"_\")[3]acquisition_time.append(time[:4]+\"-\"+time[4:6]+\"-\"+time[6:])names.append(file.replace(\".xml\", \"\"))quality_bands.append(folder+\"\\\\\"+directory+\"\\\\\"+file.replace(\".xml\", \"\") + \"_pixel_qa.tif\")"
},
{
"code": null,
"e": 3250,
"s": 2856,
"text": "To generate a raster collection, I utilize the RasterCollection method. The RasterCollection object easily sorts and filters a bunch of rasters and prepares a collection for subsequent processing and analysis. The RasterCollection object has six methods for generating statistics for each pixel across matching bands inside the collection’s rasters (max, min, median, mean, majority, and sum)."
},
{
"code": null,
"e": 3384,
"s": 3250,
"text": "rc = arcpy.ia.RasterCollection(raster_lists, {\"Varieble\": \"Landsat7\", names, \"STDTime\": acquisition_time, \"Quantity\": quality_bands})"
},
{
"code": null,
"e": 3556,
"s": 3384,
"text": "The dataset we’re utilizing has data covering 18 years. So I’m just going to use only 10 years of data. We may accomplish this by using the filterByCalanderRange function."
},
{
"code": null,
"e": 3646,
"s": 3556,
"text": "filtered_rc = rc.filterByCalenderRange(calender_field = \"YEAR\", start = 1997, end = 2007)"
},
{
"code": null,
"e": 3685,
"s": 3646,
"text": "No, we can view the Raster Collection."
},
{
"code": null,
"e": 3697,
"s": 3685,
"text": "filtered_rc"
},
{
"code": null,
"e": 3783,
"s": 3697,
"text": "The result is as follows. As we can see, it’s displaying variables, names, and so on."
},
{
"code": null,
"e": 3964,
"s": 3783,
"text": "The code below retrieves the raster from the collection’s final entry. I use the arcpy.ia.Render function to render the result and the exportImage method to display it as an image."
},
{
"code": null,
"e": 4314,
"s": 3964,
"text": "To improve symbology, use the Render function to adjust the appearance of a raster object. When working in a Jupyter notebook, where data presentation is a crucial advantage, this function comes in useful. The function generates a raster object using the specified rendering rule or color map. At least one rendering rule or color map must be given."
},
{
"code": null,
"e": 4525,
"s": 4314,
"text": "first_item = filtered_rc[0]['Raster']rendered_raster = arcpy.ia.Render(first_item_raster, rendering_rule = {\"bands\": [3, 2, 1], \"min\": 500, \"max\": 1000, colormap='NDVI'})rendered_raster.exportImage(width = 500)"
},
{
"code": null,
"e": 4645,
"s": 4525,
"text": "This is the resulting picture. As we can see, this image has a lot of clouds. As a result, we must clean up this image."
},
{
"code": null,
"e": 4770,
"s": 4645,
"text": "In the Pre-processing phase, I’m going to process the previously obtained image and remove clouds, shadows, water, and snow."
},
{
"code": null,
"e": 5120,
"s": 4770,
"text": "In the code below, I first retrieve the raster and the quality of each raster. Then I save the pixel values that I need to remove from the raster. Following that, I use arcpy.ia.Apply with bandRaster to apply to each and every raster. bandRaster will mask the pixels in the specified RGB bands. Then I assign a cleaned rater and assign it to return."
},
{
"code": null,
"e": 5849,
"s": 5120,
"text": "def clean(item):raster - item[\"Raster\"]qa_raster = arcpy.Raster(item[\"Quantity\"])values_tb = (qa_raster != 68) & (qa_raster != 72) & (qa_raster != 80) & (qa_raster != 96) & (qa_raster != 132) & (qa_raster != 136) & (qa_raster != 112) & (qa_raster != 144) & (qa_raster != 160) & (qa_raster != 176)masked_clean_band_list = []for bandRaster in raster.getRasterBands([1, 2, 3, 4, 5, 6]):masked_clean_band = arcpy.ia.Apply((values_tb, bandRaster, 0), \"Local\", args = {\"Operation\": \"StdTime\"})masked_clean_band_list.append(masked_clean_band)masked_clean_raster = arcpy.ia.CompositeBand(masked_clean_band_list)return {\"raster\": masked_clean_raster, \"Name\" : item[\"Name\"], \"StdTime\" : item[\"StdTime\"]}cleaned_rc = filtered_rc.map(clean)"
},
{
"code": null,
"e": 5925,
"s": 5849,
"text": "Using this code, I retrieve the raster within the collection’s second item."
},
{
"code": null,
"e": 6142,
"s": 5925,
"text": "first_item_raster = cleaned_rc[0]['Raster']rendered_raster = arcpy.ia.Render(first_item_raster, rendering_rule = {\"bands\": [3, 2, 1], \"min\": 500, \"max\": 1000, colormap='NDVI'})renderes_raster.exportImage(width = 500)"
},
{
"code": null,
"e": 6213,
"s": 6142,
"text": "As shown in the image below, the whole water area has been masked out."
},
{
"code": null,
"e": 6421,
"s": 6213,
"text": "I define a method called clacNDVI to calculate NDVI, and I use arcpy.ia.NDVI to create an NDVI raster from an item raster and two band values. Finally, I return parameters like item, name, and standard time."
},
{
"code": null,
"e": 6615,
"s": 6421,
"text": "def clacNDVI(item):ndvi = arcpy.ia.NDVI(item['Raster'], nir_band_id = 4, red_band = 3)return {\"raster\": ndvi, \"Name\": item[\"Name\"], \"StdTime\": item[\"StdTime\"]}ndvi_rc = cleaned_rc.map(calcNDVI)"
},
{
"code": null,
"e": 6666,
"s": 6615,
"text": "When we call the function, we get the NDVI raster."
},
{
"code": null,
"e": 6729,
"s": 6666,
"text": "Let’s visualize the raster in the same way that I did earlier."
},
{
"code": null,
"e": 6939,
"s": 6729,
"text": "first_item_raster = ndvi_rc[0]['Raster']rendered_raster = arcpy.ia.Render(first_item_raster, rendering_rule = {\"bands\": [3, 2, 1], \"min\": 0, \"max\": 1.0, colormap='NDVI'})rendred_raster.exportImage(width = 500)"
},
{
"code": null,
"e": 7020,
"s": 6939,
"text": "It’s the same raster as the one in previous. However, it is now displaying NDVI."
},
{
"code": null,
"e": 7241,
"s": 7020,
"text": "I converted the multidimensional raster collection using the code below. This method returns a multidimensional raster dataset, with each item in the raster collection representing a slice in the multidimensional raster."
},
{
"code": null,
"e": 7413,
"s": 7241,
"text": "anual_max_ndvi_mdraster = arcpy.ia.Aggregate(ndvi_mdraster, demension_name = \"StdTime\", raster_function = \"MaxIgnoreNoData\", aggregate_definition = {\"interval\": \"yearly\"})"
},
{
"code": null,
"e": 7791,
"s": 7413,
"text": "I use the arcpy.ia.Aggregate function to determine the maximum NDVI each year. This method generates a raster object based on the provided multidimensional raster. Aggregation is computed by default for all variables linked with the chosen dimension. In this case, I’m using STDTime as the dimension time and MaxIgnoreNoData as the raster function with an annual interval time."
},
{
"code": null,
"e": 8047,
"s": 7791,
"text": "Now I apply linear trend for the annual maximum multidimensional raster. The linear trend line is a best-fit straight line for estimating basic linear relationships. A linear trend denotes a pace of change that increases or decreases at a consistent rate."
},
{
"code": null,
"e": 8208,
"s": 8047,
"text": "max_ndvi_linear_trend = arcpy.ia.Apply(Annual_max_ndvi_mdraster, \"TrendAnalysis\", raster_function_arguments = {\"DimensionName\": \"StdTime\", \"RegressionType\": 0})"
},
{
"code": null,
"e": 8416,
"s": 8208,
"text": "We can retrieve the slope of the trend raster using the code below. getRasterBands returns a Raster object for each band supplied in a multiband raster dataset. In this situation, I use 1 as the raster band."
},
{
"code": null,
"e": 8463,
"s": 8416,
"text": "slope - max_ndvi_linear_trend.getRaterBands(1)"
},
{
"code": null,
"e": 8822,
"s": 8463,
"text": "To modify negative pixel values, I utilize the remap function. The remap function allows you to alter or reclassify raster data pixel values. This may be accomplished by either supplying a range of pixel values to map to an output pixel value or by mapping the pixel values to output pixel values using a table. As a result, the output will be a boolean map."
},
{
"code": null,
"e": 8933,
"s": 8822,
"text": "increase_decrease_trend_map = arcpy.ia.Remap(slope, input_ranges=[-10000, 0, 0, 10000], output_values=[-1, 1])"
},
{
"code": null,
"e": 9009,
"s": 8933,
"text": "I use the render function with different colors to render (green and gray)."
},
{
"code": null,
"e": 9182,
"s": 9009,
"text": "rendered_raster = arcpy.ia.Render(increase_decrease_trend_map, colormap = {\"values\":[0, 1], \"colors\": [\"#B0C4DE\", \"green\", \"gray\"]})rendered_raster.exportImage(width = 500)"
},
{
"code": null,
"e": 9329,
"s": 9182,
"text": "When we look at this image, we can see that the NDVI is increasing in the green area. The grey spots on the image represent NDVI-decreasing areas."
},
{
"code": null,
"e": 9881,
"s": 9329,
"text": "NDVI is a pixel-by-pixel mathematical computation performed on an image with GIS tools. It is a plant health indicator determined by measuring the absorption and reflection of red and near-infrared light. NDVI may be used to study land all over the world, making it suitable for both focused field studies and continental or global-scale vegetation monitoring. ArcGIS, a geographic information system for dealing with maps and geographic information, is maintained by the Environmental Systems Research Institute. ArcGIS can be used to calculate NDVI."
},
{
"code": null,
"e": 9891,
"s": 9881,
"text": "Reference"
}
] |
Deque in Python | The Deque is basically a generalization of stack and queue structure, where it is initialized from left to right. It uses the list object to create a deque.It provides O(1) time complexity for popping and appending.
The Dequeis a standard library class, which is located in the collections module.
To use it at first we need to import it the collections standard library module.
import collections
In this section we will see some functions of the Deque class
There are two different types of append. The append() method is used to add elements at the right end of the queue, and appendleft() method is used to append the element at the left of the queue.
import collections as col
#Insert some elements into the queue at first
my_deque = col.deque('124dfre')
print('Dequeue: ' + str(my_deque))
#insert x at right and B at left
my_deque.append('x')
my_deque.appendleft('B')
print('Dequeue after appending: ' + str(my_deque))
Dequeue: deque(['1', '2', '4', 'd', 'f', 'r', 'e'])
Dequeue after appending: deque(['B', '1', '2', '4', 'd', 'f', 'r', 'e', 'x'])
Like appending, there are two different types of pop functions. The pop() method is used to remove and return the right most element from the queue, and popleft() method is used to remove and return left most element from the queue.
import collections as col
#Insert some elements into the queue at first
my_deque = col.deque('124dfre')
print('Dequeue: ' + str(my_deque))
#delete item from right and left
item = my_deque.pop()
print('Popped Item: ' + str(item))
item = my_deque.popleft()
print('Popped Item: ' + str(item))
print('Dequeue after pop operations: ' + str(my_deque))
Dequeue: deque(['1', '2', '4', 'd', 'f', 'r', 'e'])
Popped Item: e
Popped Item: 1
Dequeue after pop operations: deque(['2', '4', 'd', 'f', 'r'])
Some functions in Deque are used to get information related to items. There are some functions like index(), count() etc. The index method is used to get the index of the first occurrence an element. When no argument is passed with the element, it will choose the entire list, when a certain limit is specified, it checks the index in that limit. On the other hand the count() method counts the frequency of an item in the Deque.
import collections as col
#Insert some elements into the queue at first
my_deque = col.deque('AABCDDEFD')
print('Dequeue: ' + str(my_deque))
#find the index of D
print('Index of D:' + str(my_deque.index('D')))
print('Index of D in range 5 to 8 is: ' + str(my_deque.index('D', 5, 8)))
#Count the number of occurrences
print('Occurrences of A: ' + str(my_deque.count('A')))
print('Occurrences of D: ' + str(my_deque.count('D')))
Dequeue: deque(['A', 'A', 'B', 'C', 'D', 'D', 'E', 'F', 'D'])
Index of D:4
Index of D in range 5 to 8 is: 5
Occurrences of A: 2
Occurrences of D: 3
We have already seen the append and pop functions in the Deque for inserting and deleting the elements respectively. There are another two methods related to insertion and deletion. The insert() method is used to insert a number. In this case we can provide the index for inserting. So on a specified location, the item can be inserted. And the remove() method is used to remove the first occurrence of an element.
import collections as col
#Insert some elements into the queue at first
my_deque = col.deque('AABCDDEFD')
print('Dequeue: ' + str(my_deque))
#Insert letter G and H into the position 5, 7 respectively
my_deque.insert(5, 'G')
my_deque.insert(7, 'H')
print('Dequeue after inserting: ' + str(my_deque))
#Delete first occurrence of letter D
my_deque.remove('D')
print('Dequeue after removing: ' + str(my_deque))
Dequeue: deque(['A', 'A', 'B', 'C', 'D', 'D', 'E', 'F', 'D'])
Dequeue after inserting: deque(['A', 'A', 'B', 'C', 'D', 'G', 'D', 'H', 'E', 'F', 'D'])
Dequeue after removing: deque(['A', 'A', 'B', 'C', 'G', 'D', 'H', 'E', 'F', 'D'])
The extending functions are used to add multiple elements into Deque. We can use collections like lists, tuples to provide multiple values. There are two types of extending functions. The extend() method is used to add elements to the right, it is similar to the repetitive append() function. And the extendleft() method is used to add elements to the left, it is similar to the repetitive appendleft() function.
import collections as col
#Insert some elements into the queue at first
my_deque = col.deque('AABCDDEFD')
print('Dequeue: ' + str(my_deque))
#Extend by adding 1, 3, 5, 7 to the right and x, y, z to the left
my_deque.extend([1, 3, 5, 7])
my_deque.extendleft(['x', 'y', 'z'])
print('Dequeue after Extending: ' + str(my_deque))
Dequeue: deque(['A', 'A', 'B', 'C', 'D', 'D', 'E', 'F', 'D'])
Dequeue after Extending: deque(['z', 'y', 'x', 'A', 'A', 'B', 'C', 'D', 'D', 'E', 'F', 'D', 1, 3, 5, 7])
We can reverse the sequence of the dequeuer using the reverse() method. There is another method called rotate(). Using the rotate method, the deque can be rotated with the number specified as argument. If the argument is positive, it rotates right, and for negative number it will be left rotate.
import collections as col
#Insert some elements into the queue at first
my_deque = col.deque('AABCDDEFD')
print('Dequeue: ' + str(my_deque))
my_deque.reverse()
print('Deque after Reversing:' + str(my_deque))
#rotate to the right, 3 elements
my_deque.rotate(3)
print('Deque after rotating:' + str(my_deque))
Dequeue: deque(['A', 'A', 'B', 'C', 'D', 'D', 'E', 'F', 'D'])
Deque after Reversing:deque(['D', 'F', 'E', 'D', 'D', 'C', 'B', 'A', 'A'])
Deque after rotating:deque(['B', 'A', 'A', 'D', 'F', 'E', 'D', 'D', 'C']) | [
{
"code": null,
"e": 1278,
"s": 1062,
"text": "The Deque is basically a generalization of stack and queue structure, where it is initialized from left to right. It uses the list object to create a deque.It provides O(1) time complexity for popping and appending."
},
{
"code": null,
"e": 1360,
"s": 1278,
"text": "The Dequeis a standard library class, which is located in the collections module."
},
{
"code": null,
"e": 1441,
"s": 1360,
"text": "To use it at first we need to import it the collections standard library module."
},
{
"code": null,
"e": 1460,
"s": 1441,
"text": "import collections"
},
{
"code": null,
"e": 1522,
"s": 1460,
"text": "In this section we will see some functions of the Deque class"
},
{
"code": null,
"e": 1718,
"s": 1522,
"text": "There are two different types of append. The append() method is used to add elements at the right end of the queue, and appendleft() method is used to append the element at the left of the queue."
},
{
"code": null,
"e": 2011,
"s": 1718,
"text": "import collections as col\n#Insert some elements into the queue at first\nmy_deque = col.deque('124dfre')\n print('Dequeue: ' + str(my_deque))\n #insert x at right and B at left\n my_deque.append('x')\n my_deque.appendleft('B')\n print('Dequeue after appending: ' + str(my_deque))"
},
{
"code": null,
"e": 2141,
"s": 2011,
"text": "Dequeue: deque(['1', '2', '4', 'd', 'f', 'r', 'e'])\nDequeue after appending: deque(['B', '1', '2', '4', 'd', 'f', 'r', 'e', 'x'])"
},
{
"code": null,
"e": 2374,
"s": 2141,
"text": "Like appending, there are two different types of pop functions. The pop() method is used to remove and return the right most element from the queue, and popleft() method is used to remove and return left most element from the queue."
},
{
"code": null,
"e": 2747,
"s": 2374,
"text": "import collections as col\n#Insert some elements into the queue at first\nmy_deque = col.deque('124dfre')\n print('Dequeue: ' + str(my_deque))\n #delete item from right and left\n item = my_deque.pop()\n print('Popped Item: ' + str(item))\n item = my_deque.popleft()\n print('Popped Item: ' + str(item))\nprint('Dequeue after pop operations: ' + str(my_deque))"
},
{
"code": null,
"e": 2892,
"s": 2747,
"text": "Dequeue: deque(['1', '2', '4', 'd', 'f', 'r', 'e'])\nPopped Item: e\nPopped Item: 1\nDequeue after pop operations: deque(['2', '4', 'd', 'f', 'r'])"
},
{
"code": null,
"e": 3322,
"s": 2892,
"text": "Some functions in Deque are used to get information related to items. There are some functions like index(), count() etc. The index method is used to get the index of the first occurrence an element. When no argument is passed with the element, it will choose the entire list, when a certain limit is specified, it checks the index in that limit. On the other hand the count() method counts the frequency of an item in the Deque."
},
{
"code": null,
"e": 3764,
"s": 3322,
"text": "import collections as col\n#Insert some elements into the queue at first\nmy_deque = col.deque('AABCDDEFD')\n print('Dequeue: ' + str(my_deque))\n #find the index of D\n print('Index of D:' + str(my_deque.index('D')))\nprint('Index of D in range 5 to 8 is: ' + str(my_deque.index('D', 5, 8)))\n#Count the number of occurrences\n print('Occurrences of A: ' + str(my_deque.count('A')))\nprint('Occurrences of D: ' + str(my_deque.count('D')))"
},
{
"code": null,
"e": 3912,
"s": 3764,
"text": "Dequeue: deque(['A', 'A', 'B', 'C', 'D', 'D', 'E', 'F', 'D'])\nIndex of D:4\nIndex of D in range 5 to 8 is: 5\nOccurrences of A: 2\nOccurrences of D: 3"
},
{
"code": null,
"e": 4327,
"s": 3912,
"text": "We have already seen the append and pop functions in the Deque for inserting and deleting the elements respectively. There are another two methods related to insertion and deletion. The insert() method is used to insert a number. In this case we can provide the index for inserting. So on a specified location, the item can be inserted. And the remove() method is used to remove the first occurrence of an element."
},
{
"code": null,
"e": 4734,
"s": 4327,
"text": "import collections as col\n#Insert some elements into the queue at first\nmy_deque = col.deque('AABCDDEFD')\nprint('Dequeue: ' + str(my_deque))\n#Insert letter G and H into the position 5, 7 respectively\nmy_deque.insert(5, 'G')\nmy_deque.insert(7, 'H')\nprint('Dequeue after inserting: ' + str(my_deque))\n#Delete first occurrence of letter D\nmy_deque.remove('D')\nprint('Dequeue after removing: ' + str(my_deque))"
},
{
"code": null,
"e": 4966,
"s": 4734,
"text": "Dequeue: deque(['A', 'A', 'B', 'C', 'D', 'D', 'E', 'F', 'D'])\nDequeue after inserting: deque(['A', 'A', 'B', 'C', 'D', 'G', 'D', 'H', 'E', 'F', 'D'])\nDequeue after removing: deque(['A', 'A', 'B', 'C', 'G', 'D', 'H', 'E', 'F', 'D'])"
},
{
"code": null,
"e": 5379,
"s": 4966,
"text": "The extending functions are used to add multiple elements into Deque. We can use collections like lists, tuples to provide multiple values. There are two types of extending functions. The extend() method is used to add elements to the right, it is similar to the repetitive append() function. And the extendleft() method is used to add elements to the left, it is similar to the repetitive appendleft() function."
},
{
"code": null,
"e": 5704,
"s": 5379,
"text": "import collections as col\n#Insert some elements into the queue at first\nmy_deque = col.deque('AABCDDEFD')\nprint('Dequeue: ' + str(my_deque))\n#Extend by adding 1, 3, 5, 7 to the right and x, y, z to the left\nmy_deque.extend([1, 3, 5, 7])\nmy_deque.extendleft(['x', 'y', 'z'])\nprint('Dequeue after Extending: ' + str(my_deque))"
},
{
"code": null,
"e": 5871,
"s": 5704,
"text": "Dequeue: deque(['A', 'A', 'B', 'C', 'D', 'D', 'E', 'F', 'D'])\nDequeue after Extending: deque(['z', 'y', 'x', 'A', 'A', 'B', 'C', 'D', 'D', 'E', 'F', 'D', 1, 3, 5, 7])"
},
{
"code": null,
"e": 6168,
"s": 5871,
"text": "We can reverse the sequence of the dequeuer using the reverse() method. There is another method called rotate(). Using the rotate method, the deque can be rotated with the number specified as argument. If the argument is positive, it rotates right, and for negative number it will be left rotate."
},
{
"code": null,
"e": 6475,
"s": 6168,
"text": "import collections as col\n#Insert some elements into the queue at first\nmy_deque = col.deque('AABCDDEFD')\nprint('Dequeue: ' + str(my_deque))\nmy_deque.reverse()\nprint('Deque after Reversing:' + str(my_deque))\n#rotate to the right, 3 elements\nmy_deque.rotate(3)\nprint('Deque after rotating:' + str(my_deque))"
},
{
"code": null,
"e": 6686,
"s": 6475,
"text": "Dequeue: deque(['A', 'A', 'B', 'C', 'D', 'D', 'E', 'F', 'D'])\nDeque after Reversing:deque(['D', 'F', 'E', 'D', 'D', 'C', 'B', 'A', 'A'])\nDeque after rotating:deque(['B', 'A', 'A', 'D', 'F', 'E', 'D', 'D', 'C'])"
}
] |
JavaScript - Form Validation | Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which used to put a lot of burden on the server.
JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions.
Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data.
Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.
Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data.
We will take an example to understand the process of validation. Here is a simple form in html format.
<html>
<head>
<title>Form Validation</title>
<script type = "text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action = "/cgi-bin/test.cgi" name = "myForm" onsubmit = "return(validate());">
<table cellspacing = "2" cellpadding = "2" border = "1">
<tr>
<td align = "right">Name</td>
<td><input type = "text" name = "Name" /></td>
</tr>
<tr>
<td align = "right">EMail</td>
<td><input type = "text" name = "EMail" /></td>
</tr>
<tr>
<td align = "right">Zip Code</td>
<td><input type = "text" name = "Zip" /></td>
</tr>
<tr>
<td align = "right">Country</td>
<td>
<select name = "Country">
<option value = "-1" selected>[choose yours]</option>
<option value = "1">USA</option>
<option value = "2">UK</option>
<option value = "3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align = "right"></td>
<td><input type = "submit" value = "Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
First let us see how to do a basic form validation. In the above form, we are calling validate() to validate data when onsubmit event is occurring. The following code shows the implementation of this validate() function.
<script type = "text/javascript">
<!--
// Form validation code will come here.
function validate() {
if( document.myForm.Name.value == "" ) {
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" ) {
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" || isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 ) {
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" ) {
alert( "Please provide your country!" );
return false;
}
return( true );
}
//-->
</script>
Now we will see how we can validate our entered form data before submitting it to the web server.
The following example shows how to validate an entered email address. An email address must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first character of the email address, and the last dot must at least be one character after the ‘@’ sign.
Try the following code for email validation.
<script type = "text/javascript">
<!--
function validateEmail() {
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 )) {
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
//-->
</script>
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": 2889,
"s": 2466,
"text": "Form validation normally used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which used to put a lot of burden on the server."
},
{
"code": null,
"e": 3051,
"s": 2889,
"text": "JavaScript provides a way to validate form's data on the client's computer before sending it to the web server. Form validation generally performs two functions."
},
{
"code": null,
"e": 3242,
"s": 3051,
"text": "Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data."
},
{
"code": null,
"e": 3433,
"s": 3242,
"text": "Basic Validation − First of all, the form must be checked to make sure all the mandatory fields are filled in. It would require just a loop through each field in the form and check for data."
},
{
"code": null,
"e": 3607,
"s": 3433,
"text": "Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data."
},
{
"code": null,
"e": 3781,
"s": 3607,
"text": "Data Format Validation − Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test correctness of data."
},
{
"code": null,
"e": 3884,
"s": 3781,
"text": "We will take an example to understand the process of validation. Here is a simple form in html format."
},
{
"code": null,
"e": 5415,
"s": 3884,
"text": "<html> \n <head>\n <title>Form Validation</title> \n <script type = \"text/javascript\">\n <!--\n // Form validation code will come here.\n //-->\n </script> \n </head>\n \n <body>\n <form action = \"/cgi-bin/test.cgi\" name = \"myForm\" onsubmit = \"return(validate());\">\n <table cellspacing = \"2\" cellpadding = \"2\" border = \"1\">\n \n <tr>\n <td align = \"right\">Name</td>\n <td><input type = \"text\" name = \"Name\" /></td>\n </tr>\n \n <tr>\n <td align = \"right\">EMail</td>\n <td><input type = \"text\" name = \"EMail\" /></td>\n </tr>\n \n <tr>\n <td align = \"right\">Zip Code</td>\n <td><input type = \"text\" name = \"Zip\" /></td>\n </tr>\n \n <tr>\n <td align = \"right\">Country</td>\n <td>\n <select name = \"Country\">\n <option value = \"-1\" selected>[choose yours]</option>\n <option value = \"1\">USA</option>\n <option value = \"2\">UK</option>\n <option value = \"3\">INDIA</option>\n </select>\n </td>\n </tr>\n \n <tr>\n <td align = \"right\"></td>\n <td><input type = \"submit\" value = \"Submit\" /></td>\n </tr>\n \n </table>\n </form> \n </body>\n</html>"
},
{
"code": null,
"e": 5636,
"s": 5415,
"text": "First let us see how to do a basic form validation. In the above form, we are calling validate() to validate data when onsubmit event is occurring. The following code shows the implementation of this validate() function."
},
{
"code": null,
"e": 6617,
"s": 5636,
"text": "<script type = \"text/javascript\">\n <!--\n // Form validation code will come here.\n function validate() {\n \n if( document.myForm.Name.value == \"\" ) {\n alert( \"Please provide your name!\" );\n document.myForm.Name.focus() ;\n return false;\n }\n if( document.myForm.EMail.value == \"\" ) {\n alert( \"Please provide your Email!\" );\n document.myForm.EMail.focus() ;\n return false;\n }\n if( document.myForm.Zip.value == \"\" || isNaN( document.myForm.Zip.value ) ||\n document.myForm.Zip.value.length != 5 ) {\n \n alert( \"Please provide a zip in the format #####.\" );\n document.myForm.Zip.focus() ;\n return false;\n }\n if( document.myForm.Country.value == \"-1\" ) {\n alert( \"Please provide your country!\" );\n return false;\n }\n return( true );\n }\n //-->\n</script>"
},
{
"code": null,
"e": 6715,
"s": 6617,
"text": "Now we will see how we can validate our entered form data before submitting it to the web server."
},
{
"code": null,
"e": 6986,
"s": 6715,
"text": "The following example shows how to validate an entered email address. An email address must contain at least a ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first character of the email address, and the last dot must at least be one character after the ‘@’ sign."
},
{
"code": null,
"e": 7031,
"s": 6986,
"text": "Try the following code for email validation."
},
{
"code": null,
"e": 7487,
"s": 7031,
"text": "<script type = \"text/javascript\">\n <!--\n function validateEmail() {\n var emailID = document.myForm.EMail.value;\n atpos = emailID.indexOf(\"@\");\n dotpos = emailID.lastIndexOf(\".\");\n \n if (atpos < 1 || ( dotpos - atpos < 2 )) {\n alert(\"Please enter correct email ID\")\n document.myForm.EMail.focus() ;\n return false;\n }\n return( true );\n }\n //-->\n</script>"
},
{
"code": null,
"e": 7522,
"s": 7487,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 7536,
"s": 7522,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7570,
"s": 7536,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 7584,
"s": 7570,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7619,
"s": 7584,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7636,
"s": 7619,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7671,
"s": 7636,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 7688,
"s": 7671,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7721,
"s": 7688,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7749,
"s": 7721,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7783,
"s": 7749,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 7811,
"s": 7783,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7818,
"s": 7811,
"text": " Print"
},
{
"code": null,
"e": 7829,
"s": 7818,
"text": " Add Notes"
}
] |
How to find a value is present in binary tree or not in JavaScript ? | We are required to write a JavaScript function on the prototype object of a BinarySearchTree data type that takes in a value and finds whether or not that value is contained in the BST.
The code for this will be -
// class for a single Node for BST
class Node {
constructor(value) {
this.value = value;
}
}
// class for BST
// contains function to insert node and search for existing nodes
class BinarySearchTree {
constructor() {
this._root = null;
};
insert(value) {
let node = this, side = '_root';
while (node[side]) {
node = node[side];
if (value === node.value) {
return;
};
side = value < node.value ? 'left' : 'right';
};
node[side] = new Node(value);
};
contains(value) {
let current = this._root;
while (current) {
if (value === current.value) {
return true;
};
current = value < current.value ? current.left : current.right;
}
return false;
};
}
const tree = new BinarySearchTree();
for (let i = 0; i < 10; i++) {
tree.insert(Math.floor(Math.random() * 1000));
};
tree.insert(34);
console.log(tree.contains(34));
console.log(tree.contains(334));
And the output in the console will be −
true
false | [
{
"code": null,
"e": 1248,
"s": 1062,
"text": "We are required to write a JavaScript function on the prototype object of a BinarySearchTree data type that takes in a value and finds whether or not that value is contained in the BST."
},
{
"code": null,
"e": 1276,
"s": 1248,
"text": "The code for this will be -"
},
{
"code": null,
"e": 2293,
"s": 1276,
"text": "// class for a single Node for BST\nclass Node {\n constructor(value) {\n this.value = value;\n }\n}\n// class for BST\n// contains function to insert node and search for existing nodes\nclass BinarySearchTree {\n constructor() {\n this._root = null;\n };\n insert(value) {\n let node = this, side = '_root';\n while (node[side]) {\n node = node[side];\n if (value === node.value) {\n return;\n };\n side = value < node.value ? 'left' : 'right';\n };\n node[side] = new Node(value);\n };\n contains(value) {\n let current = this._root;\n while (current) {\n if (value === current.value) {\n return true;\n };\n current = value < current.value ? current.left : current.right;\n }\n return false;\n };\n}\nconst tree = new BinarySearchTree();\nfor (let i = 0; i < 10; i++) {\n tree.insert(Math.floor(Math.random() * 1000));\n};\ntree.insert(34);\nconsole.log(tree.contains(34));\nconsole.log(tree.contains(334));"
},
{
"code": null,
"e": 2333,
"s": 2293,
"text": "And the output in the console will be −"
},
{
"code": null,
"e": 2344,
"s": 2333,
"text": "true\nfalse"
}
] |
Arduino - DC Motor | In this chapter, we will interface different types of motors with the Arduino board (UNO) and show you how to connect the motor and drive it from your board.
There are three different type of motors −
DC motor
Servo motor
Stepper motor
A DC motor (Direct Current motor) is the most common type of motor. DC motors normally have just two leads, one positive and one negative. If you connect these two leads directly to a battery, the motor will rotate. If you switch the leads, the motor will rotate in the opposite direction.
Warning − Do not drive the motor directly from Arduino board pins. This may damage the board. Use a driver Circuit or an IC.
We will divide this chapter into three parts −
Just make your motor spin
Control motor speed
Control the direction of the spin of DC motor
You will need the following components −
1x Arduino UNO board
1x PN2222 Transistor
1x Small 6V DC Motor
1x 1N4001 diode
1x 270 Ω Resistor
Follow the circuit diagram and make the connections as shown in the image given below.
Take the following precautions while making the connections.
First, make sure that the transistor is connected in the right way. The flat side of the transistor should face the Arduino board as shown in the arrangement.
First, make sure that the transistor is connected in the right way. The flat side of the transistor should face the Arduino board as shown in the arrangement.
Second, the striped end of the diode should be towards the +5V power line according to the arrangement shown in the image.
Second, the striped end of the diode should be towards the +5V power line according to the arrangement shown in the image.
int motorPin = 3;
void setup() {
}
void loop() {
digitalWrite(motorPin, HIGH);
}
The transistor acts like a switch, controlling the power to the motor. Arduino pin 3 is used to turn the transistor on and off and is given the name 'motorPin' in the sketch.
Motor will spin in full speed when the Arduino pin number 3 goes high.
Following is the schematic diagram of a DC motor, connected to the Arduino board.
int motorPin = 9;
void setup() {
pinMode(motorPin, OUTPUT);
Serial.begin(9600);
while (! Serial);
Serial.println("Speed 0 to 255");
}
void loop() {
if (Serial.available()) {
int speed = Serial.parseInt();
if (speed >= 0 && speed <= 255) {
analogWrite(motorPin, speed);
}
}
}
The transistor acts like a switch, controlling the power of the motor. Arduino pin 3 is used to turn the transistor on and off and is given the name 'motorPin' in the sketch.
When the program starts, it prompts you to give the values to control the speed of the motor. You need to enter a value between 0 and 255 in the Serial Monitor.
In the 'loop' function, the command 'Serial.parseInt' is used to read the number entered as text in the Serial Monitor and convert it into an 'int'. You can type any number here. The 'if' statement in the next line simply does an analog write with this number, if the number is between 0 and 255.
The DC motor will spin with different speeds according to the value (0 to 250) received via the serial port.
To control the direction of the spin of DC motor, without interchanging the leads, you can use a circuit called an H-Bridge. An H-bridge is an electronic circuit that can drive the motor in both directions. H-bridges are used in many different applications. One of the most common application is to control motors in robots. It is called an H-bridge because it uses four transistors connected in such a way that the schematic diagram looks like an "H."
We will be using the L298 H-Bridge IC here. The L298 can control the speed and direction of DC motors and stepper motors, and can control two motors simultaneously. Its current rating is 2A for each motor. At these currents, however, you will need to use heat sinks.
You will need the following components −
1 × L298 bridge IC
1 × DC motor
1 × Arduino UNO
1 × breadboard
10 × jumper wires
Following is the schematic diagram of the DC motor interface to Arduino Uno board.
The above diagram shows how to connect the L298 IC to control two motors. There are three input pins for each motor, Input1 (IN1), Input2 (IN2), and Enable1 (EN1) for Motor1 and Input3, Input4, and Enable2 for Motor2.
Since we will be controlling only one motor in this example, we will connect the Arduino to IN1 (pin 5), IN2 (pin 7), and Enable1 (pin 6) of the L298 IC. Pins 5 and 7 are digital, i.e. ON or OFF inputs, while pin 6 needs a pulse-width modulated (PWM) signal to control the motor speed.
The following table shows which direction the motor will turn based on the digital values of IN1 and IN2.
Pin IN1 of the IC L298 is connected to pin 8 of Arduino while IN2 is connected to pin 9. These two digital pins of Arduino control the direction of the motor. The EN A pin of IC is connected to the PWM pin 2 of Arduino. This will control the speed of the motor.
To set the values of Arduino pins 8 and 9, we have used the digitalWrite() function, and to set the value of pin 2, we have to use the analogWrite() function.
Connect 5V and the ground of the IC to 5V and the ground of Arduino, respectively.
Connect the motor to pins 2 and 3 of the IC.
Connect IN1 of the IC to pin 8 of Arduino.
Connect IN2 of the IC to pin 9 of Arduino.
Connect EN1 of IC to pin 2 of Arduino.
Connect SENS A pin of IC to the ground.
Connect Arduino using Arduino USB cable and upload the program to Arduino using Arduino IDE software.
Provide power to Arduino board using power supply, battery, or USB cable.
const int pwm = 2 ; //initializing pin 2 as pwm
const int in_1 = 8 ;
const int in_2 = 9 ;
//For providing logic to L298 IC to choose the direction of the DC motor
void setup() {
pinMode(pwm,OUTPUT) ; //we have to set PWM pin as output
pinMode(in_1,OUTPUT) ; //Logic pins are also set as output
pinMode(in_2,OUTPUT) ;
}
void loop() {
//For Clock wise motion , in_1 = High , in_2 = Low
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,LOW) ;
analogWrite(pwm,255) ;
/* setting pwm of the motor to 255 we can change the speed of rotation
by changing pwm input but we are only using arduino so we are using highest
value to driver the motor */
//Clockwise for 3 secs
delay(3000) ;
//For brake
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,HIGH) ;
delay(1000) ;
//For Anti Clock-wise motion - IN_1 = LOW , IN_2 = HIGH
digitalWrite(in_1,LOW) ;
digitalWrite(in_2,HIGH) ;
delay(3000) ;
//For brake
digitalWrite(in_1,HIGH) ;
digitalWrite(in_2,HIGH) ;
delay(1000) ;
}
The motor will run first in the clockwise (CW) direction for 3 seconds and then counter-clockwise (CCW) for 3 seconds.
65 Lectures
6.5 hours
Amit Rana
43 Lectures
3 hours
Amit Rana
20 Lectures
2 hours
Ashraf Said
19 Lectures
1.5 hours
Ashraf Said
11 Lectures
47 mins
Ashraf Said
9 Lectures
41 mins
Ashraf Said
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3028,
"s": 2870,
"text": "In this chapter, we will interface different types of motors with the Arduino board (UNO) and show you how to connect the motor and drive it from your board."
},
{
"code": null,
"e": 3071,
"s": 3028,
"text": "There are three different type of motors −"
},
{
"code": null,
"e": 3080,
"s": 3071,
"text": "DC motor"
},
{
"code": null,
"e": 3092,
"s": 3080,
"text": "Servo motor"
},
{
"code": null,
"e": 3106,
"s": 3092,
"text": "Stepper motor"
},
{
"code": null,
"e": 3396,
"s": 3106,
"text": "A DC motor (Direct Current motor) is the most common type of motor. DC motors normally have just two leads, one positive and one negative. If you connect these two leads directly to a battery, the motor will rotate. If you switch the leads, the motor will rotate in the opposite direction."
},
{
"code": null,
"e": 3521,
"s": 3396,
"text": "Warning − Do not drive the motor directly from Arduino board pins. This may damage the board. Use a driver Circuit or an IC."
},
{
"code": null,
"e": 3568,
"s": 3521,
"text": "We will divide this chapter into three parts −"
},
{
"code": null,
"e": 3594,
"s": 3568,
"text": "Just make your motor spin"
},
{
"code": null,
"e": 3614,
"s": 3594,
"text": "Control motor speed"
},
{
"code": null,
"e": 3660,
"s": 3614,
"text": "Control the direction of the spin of DC motor"
},
{
"code": null,
"e": 3701,
"s": 3660,
"text": "You will need the following components −"
},
{
"code": null,
"e": 3722,
"s": 3701,
"text": "1x Arduino UNO board"
},
{
"code": null,
"e": 3743,
"s": 3722,
"text": "1x PN2222 Transistor"
},
{
"code": null,
"e": 3764,
"s": 3743,
"text": "1x Small 6V DC Motor"
},
{
"code": null,
"e": 3780,
"s": 3764,
"text": "1x 1N4001 diode"
},
{
"code": null,
"e": 3798,
"s": 3780,
"text": "1x 270 Ω Resistor"
},
{
"code": null,
"e": 3885,
"s": 3798,
"text": "Follow the circuit diagram and make the connections as shown in the image given below."
},
{
"code": null,
"e": 3946,
"s": 3885,
"text": "Take the following precautions while making the connections."
},
{
"code": null,
"e": 4105,
"s": 3946,
"text": "First, make sure that the transistor is connected in the right way. The flat side of the transistor should face the Arduino board as shown in the arrangement."
},
{
"code": null,
"e": 4264,
"s": 4105,
"text": "First, make sure that the transistor is connected in the right way. The flat side of the transistor should face the Arduino board as shown in the arrangement."
},
{
"code": null,
"e": 4387,
"s": 4264,
"text": "Second, the striped end of the diode should be towards the +5V power line according to the arrangement shown in the image."
},
{
"code": null,
"e": 4510,
"s": 4387,
"text": "Second, the striped end of the diode should be towards the +5V power line according to the arrangement shown in the image."
},
{
"code": null,
"e": 4597,
"s": 4510,
"text": "int motorPin = 3;\n\nvoid setup() {\n\n}\n\nvoid loop() {\n digitalWrite(motorPin, HIGH);\n}"
},
{
"code": null,
"e": 4772,
"s": 4597,
"text": "The transistor acts like a switch, controlling the power to the motor. Arduino pin 3 is used to turn the transistor on and off and is given the name 'motorPin' in the sketch."
},
{
"code": null,
"e": 4843,
"s": 4772,
"text": "Motor will spin in full speed when the Arduino pin number 3 goes high."
},
{
"code": null,
"e": 4925,
"s": 4843,
"text": "Following is the schematic diagram of a DC motor, connected to the Arduino board."
},
{
"code": null,
"e": 5247,
"s": 4925,
"text": "int motorPin = 9;\n\nvoid setup() {\n pinMode(motorPin, OUTPUT);\n Serial.begin(9600);\n while (! Serial);\n Serial.println(\"Speed 0 to 255\");\n}\n\nvoid loop() {\n if (Serial.available()) {\n int speed = Serial.parseInt();\n if (speed >= 0 && speed <= 255) {\n analogWrite(motorPin, speed);\n }\n }\n}"
},
{
"code": null,
"e": 5422,
"s": 5247,
"text": "The transistor acts like a switch, controlling the power of the motor. Arduino pin 3 is used to turn the transistor on and off and is given the name 'motorPin' in the sketch."
},
{
"code": null,
"e": 5583,
"s": 5422,
"text": "When the program starts, it prompts you to give the values to control the speed of the motor. You need to enter a value between 0 and 255 in the Serial Monitor."
},
{
"code": null,
"e": 5880,
"s": 5583,
"text": "In the 'loop' function, the command 'Serial.parseInt' is used to read the number entered as text in the Serial Monitor and convert it into an 'int'. You can type any number here. The 'if' statement in the next line simply does an analog write with this number, if the number is between 0 and 255."
},
{
"code": null,
"e": 5989,
"s": 5880,
"text": "The DC motor will spin with different speeds according to the value (0 to 250) received via the serial port."
},
{
"code": null,
"e": 6442,
"s": 5989,
"text": "To control the direction of the spin of DC motor, without interchanging the leads, you can use a circuit called an H-Bridge. An H-bridge is an electronic circuit that can drive the motor in both directions. H-bridges are used in many different applications. One of the most common application is to control motors in robots. It is called an H-bridge because it uses four transistors connected in such a way that the schematic diagram looks like an \"H.\""
},
{
"code": null,
"e": 6709,
"s": 6442,
"text": "We will be using the L298 H-Bridge IC here. The L298 can control the speed and direction of DC motors and stepper motors, and can control two motors simultaneously. Its current rating is 2A for each motor. At these currents, however, you will need to use heat sinks."
},
{
"code": null,
"e": 6750,
"s": 6709,
"text": "You will need the following components −"
},
{
"code": null,
"e": 6769,
"s": 6750,
"text": "1 × L298 bridge IC"
},
{
"code": null,
"e": 6782,
"s": 6769,
"text": "1 × DC motor"
},
{
"code": null,
"e": 6798,
"s": 6782,
"text": "1 × Arduino UNO"
},
{
"code": null,
"e": 6813,
"s": 6798,
"text": "1 × breadboard"
},
{
"code": null,
"e": 6831,
"s": 6813,
"text": "10 × jumper wires"
},
{
"code": null,
"e": 6914,
"s": 6831,
"text": "Following is the schematic diagram of the DC motor interface to Arduino Uno board."
},
{
"code": null,
"e": 7132,
"s": 6914,
"text": "The above diagram shows how to connect the L298 IC to control two motors. There are three input pins for each motor, Input1 (IN1), Input2 (IN2), and Enable1 (EN1) for Motor1 and Input3, Input4, and Enable2 for Motor2."
},
{
"code": null,
"e": 7418,
"s": 7132,
"text": "Since we will be controlling only one motor in this example, we will connect the Arduino to IN1 (pin 5), IN2 (pin 7), and Enable1 (pin 6) of the L298 IC. Pins 5 and 7 are digital, i.e. ON or OFF inputs, while pin 6 needs a pulse-width modulated (PWM) signal to control the motor speed."
},
{
"code": null,
"e": 7524,
"s": 7418,
"text": "The following table shows which direction the motor will turn based on the digital values of IN1 and IN2."
},
{
"code": null,
"e": 7786,
"s": 7524,
"text": "Pin IN1 of the IC L298 is connected to pin 8 of Arduino while IN2 is connected to pin 9. These two digital pins of Arduino control the direction of the motor. The EN A pin of IC is connected to the PWM pin 2 of Arduino. This will control the speed of the motor."
},
{
"code": null,
"e": 7945,
"s": 7786,
"text": "To set the values of Arduino pins 8 and 9, we have used the digitalWrite() function, and to set the value of pin 2, we have to use the analogWrite() function."
},
{
"code": null,
"e": 8028,
"s": 7945,
"text": "Connect 5V and the ground of the IC to 5V and the ground of Arduino, respectively."
},
{
"code": null,
"e": 8073,
"s": 8028,
"text": "Connect the motor to pins 2 and 3 of the IC."
},
{
"code": null,
"e": 8116,
"s": 8073,
"text": "Connect IN1 of the IC to pin 8 of Arduino."
},
{
"code": null,
"e": 8159,
"s": 8116,
"text": "Connect IN2 of the IC to pin 9 of Arduino."
},
{
"code": null,
"e": 8198,
"s": 8159,
"text": "Connect EN1 of IC to pin 2 of Arduino."
},
{
"code": null,
"e": 8238,
"s": 8198,
"text": "Connect SENS A pin of IC to the ground."
},
{
"code": null,
"e": 8340,
"s": 8238,
"text": "Connect Arduino using Arduino USB cable and upload the program to Arduino using Arduino IDE software."
},
{
"code": null,
"e": 8414,
"s": 8340,
"text": "Provide power to Arduino board using power supply, battery, or USB cable."
},
{
"code": null,
"e": 9438,
"s": 8414,
"text": "const int pwm = 2 ; //initializing pin 2 as pwm\nconst int in_1 = 8 ;\nconst int in_2 = 9 ;\n//For providing logic to L298 IC to choose the direction of the DC motor\n\nvoid setup() {\n pinMode(pwm,OUTPUT) ; //we have to set PWM pin as output\n pinMode(in_1,OUTPUT) ; //Logic pins are also set as output\n pinMode(in_2,OUTPUT) ;\n}\n\nvoid loop() {\n //For Clock wise motion , in_1 = High , in_2 = Low\n digitalWrite(in_1,HIGH) ;\n digitalWrite(in_2,LOW) ;\n analogWrite(pwm,255) ;\n /* setting pwm of the motor to 255 we can change the speed of rotation\n by changing pwm input but we are only using arduino so we are using highest\n value to driver the motor */\n //Clockwise for 3 secs\n delay(3000) ;\n //For brake\n digitalWrite(in_1,HIGH) ;\n digitalWrite(in_2,HIGH) ;\n delay(1000) ;\n //For Anti Clock-wise motion - IN_1 = LOW , IN_2 = HIGH\n digitalWrite(in_1,LOW) ;\n digitalWrite(in_2,HIGH) ;\n delay(3000) ;\n //For brake\n digitalWrite(in_1,HIGH) ;\n digitalWrite(in_2,HIGH) ;\n delay(1000) ;\n}"
},
{
"code": null,
"e": 9557,
"s": 9438,
"text": "The motor will run first in the clockwise (CW) direction for 3 seconds and then counter-clockwise (CCW) for 3 seconds."
},
{
"code": null,
"e": 9592,
"s": 9557,
"text": "\n 65 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 9603,
"s": 9592,
"text": " Amit Rana"
},
{
"code": null,
"e": 9636,
"s": 9603,
"text": "\n 43 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 9647,
"s": 9636,
"text": " Amit Rana"
},
{
"code": null,
"e": 9680,
"s": 9647,
"text": "\n 20 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 9693,
"s": 9680,
"text": " Ashraf Said"
},
{
"code": null,
"e": 9728,
"s": 9693,
"text": "\n 19 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 9741,
"s": 9728,
"text": " Ashraf Said"
},
{
"code": null,
"e": 9773,
"s": 9741,
"text": "\n 11 Lectures \n 47 mins\n"
},
{
"code": null,
"e": 9786,
"s": 9773,
"text": " Ashraf Said"
},
{
"code": null,
"e": 9817,
"s": 9786,
"text": "\n 9 Lectures \n 41 mins\n"
},
{
"code": null,
"e": 9830,
"s": 9817,
"text": " Ashraf Said"
},
{
"code": null,
"e": 9837,
"s": 9830,
"text": " Print"
},
{
"code": null,
"e": 9848,
"s": 9837,
"text": " Add Notes"
}
] |
How can a MySQL stored procedure call another MySQL stored procedure inside it? | It is quite possible that a MySQL stored procedure can call another MySQL stored procedure inside it. To demonstrate it, we are taking an example in which a stored procedure will call another stored procedure to find out the last_insert_id.
mysql> Create table employee.tbl(Id INT NOT NULL AUTO_INCREMENT, Name Varchar(30) NOT NULL, PRIMARY KEY(id))//
Query OK, 0 rows affected (3.87 sec)
mysql> Create Procedure insert1()
-> BEGIN insert into employee.tbl(name) values ('Ram');
-> END//
Query OK, 0 rows affected (0.10 sec)
Now, in the next procedure insert2() we will call the 1st stored procedure i.e. insert1().
mysql> Create Procedure insert2()
-> BEGIN
-> CALL insert1();
-> Select last_insert_id();
-> END //
Query OK, 0 rows affected (0.11 sec)
mysql> Delimiter ;
mysql> Call insert2();
+------------------+
| last_insert_id() |
+------------------+
| 1 |
+------------------+
1 row in set (0.36 sec)
Query OK, 0 rows affected (0.37 sec)
The above result set shows that when we call insert1() then it inserted the first value in the table called employee.tbl and when we select last_insert_id() in 2nd stored procedure i.e. insert2() then it gives the output 1. | [
{
"code": null,
"e": 1303,
"s": 1062,
"text": "It is quite possible that a MySQL stored procedure can call another MySQL stored procedure inside it. To demonstrate it, we are taking an example in which a stored procedure will call another stored procedure to find out the last_insert_id."
},
{
"code": null,
"e": 1594,
"s": 1303,
"text": "mysql> Create table employee.tbl(Id INT NOT NULL AUTO_INCREMENT, Name Varchar(30) NOT NULL, PRIMARY KEY(id))//\nQuery OK, 0 rows affected (3.87 sec)\n\nmysql> Create Procedure insert1()\n -> BEGIN insert into employee.tbl(name) values ('Ram');\n -> END//\nQuery OK, 0 rows affected (0.10 sec)"
},
{
"code": null,
"e": 1685,
"s": 1594,
"text": "Now, in the next procedure insert2() we will call the 1st stored procedure i.e. insert1()."
},
{
"code": null,
"e": 2043,
"s": 1685,
"text": "mysql> Create Procedure insert2()\n -> BEGIN\n -> CALL insert1();\n -> Select last_insert_id();\n -> END //\nQuery OK, 0 rows affected (0.11 sec)\nmysql> Delimiter ;\n\nmysql> Call insert2();\n+------------------+\n| last_insert_id() |\n+------------------+\n| 1 |\n+------------------+\n1 row in set (0.36 sec)\nQuery OK, 0 rows affected (0.37 sec)"
},
{
"code": null,
"e": 2267,
"s": 2043,
"text": "The above result set shows that when we call insert1() then it inserted the first value in the table called employee.tbl and when we select last_insert_id() in 2nd stored procedure i.e. insert2() then it gives the output 1."
}
] |
Speeding up Neural Net Training with LR-Finder | by Faizan Ahemad | Towards Data Science | While training a Deep Neural Network selecting a good learning rate is essential for both fast convergence and a lower error. We also have to select a optimiser which decides how weight updates are done in a DNN.
There are various optimisers available like Adam, SGD+momentum, Adagrad, RMSprop, AdaDelta, AdaBound. Of these Adam and SGD+momentum are most popular. While training a Fully Connected DNN or a Convolutional network most State of the Art networks use SGD+momentum. This is due to the fact that it generalises better to unseen data and gives better validation/test scores.
There are two tiny problems with SGD though, SGD is slow to converge compared to Adam and SGD requires learning rate tuning. Surprisingly the solution to both problems is using a good starting learning rate. In case your LR is too high, your errors will never reduce and training will not converge. Too low LR and you have to wait too long for training to converge. So we start with a good LR given by LR-Finder, then decay it a little as we reach the end.
Basic objective of a LR Finder is to find the highest LR which still minimises the loss and does not make the loss explode/diverge. We do this by training a model while increasing the LR after each batch, we record the loss and finally we use the LR just before loss exploded. We do this for 1 epoch.
start_lr = 0.0001end_lr = 1.0num_batches = len(Data)/batch_sizecur_lr = start_lrlr_multiplier = (end_lr / start_lr) ** (1.0 / num_batches)losses = []lrs = []for i in 1 to num_batches: loss = train_model_get_loss(batch=i) losses.append(loss) lrs.append(cur_lr) cur_lr = cur_lr*lr_multiplier # increase LRplot(lrs,losses)
You will get a plot which looks like below
We plot the points with a arrow to indicate location in our implementation
From this plot we find the point after which loss starts increasing too much.
I have written a small library which contains the LR Finder. This is for Keras. For pytorch fast.ai implementation works.To install:
pip install --upgrade --upgrade-strategy only-if-needed https://github.com/faizanahemad/data-science-utils/tarball/master > /dev/null
Next in your notebook (For Cifar 10)
First Define Imports and Data generators for our Data set.
from data_science_utils.vision.keras import *X_train, Y_train, X_test, Y_test = get_cifar10_data()cutout_fn = get_cutout_eraser(p=0.75, s_l=0.1, s_h=0.3, r_1=0.3, r_2=1 / 0.3, max_erasures_per_image=2, pixel_level=True)datagen = ImageDataGenerator(featurewise_center=True,featurewise_std_normalization=True, preprocessing_function=cutout_fn)datagen_validation = ImageDataGenerator(featurewise_center=True,featurewise_std_normalization=True,)datagen_validation.fit(X_train)model = build_model()
Next We build our model and use LR Finder on it.
model = build_model() # returns an instance of Keras Modellrf = LRFinder(model)generator = datagen.flow(X_train, Y_train, batch_size=256,shuffle=True)test_generator = datagen_validation.flow(X_test, Y_test, batch_size=256, shuffle=True)lrf.find_generator(generator, 0.0001, 10.0,test_generator, epochs=1, steps_per_epoch=None,)lrf.plot_loss()
The above 2 plots you saw were generated using this. You can see the example in this Google Colab Notebook.
We use the minimas as our candidate LRs. You can notice that some of these are local minimas, where the overall loss is quite high, for the candidate LRs the overall loss should be near to the minimum loss. So we filter these local minimas
We need to use validation set to find loss, using training set to find loss will not yield correct results since the weights will overfit to training set.
When we generate candidate LRs, we need to ensure that those are distinct enough. For example generating candidates like 0.552 and 0.563 doesn’t make sense since these LRs are too close. As such we apply a rule that each LR should be atleast 20% different from its previous lower LR.
Note that LR Finder gives you an approx value, So it doesn’t matter if you take the exact value or not. Like if LRF gives you 0.012, then you can use 0.01 as well. If it gives 0.056 then both 0.05 and 0.06 are fine.
We can use LR scheduling or LR decay to reduce LR in later epochs since we started with high LR initially.
We used SGD directly with a learning_rate of 0.01 and nesterov’s momentum. We trained the network on CIFAR-10 for 100 epochs. Our network has 450K params.
As you can notice it took about 60 epochs for validation error to converge and it is 86.7% accuracy.
We use the LR provided by LR finder. Everything else is same.
You can see that here we get 86.4% accuracy but training converges in 40 epochs instead of 60. Using LR given by LR finder along with EarlyStopping can reduce compute time massively.
We use LR scheduling from keras to decrease LR in each epoch. Basically after each epoch we decrease LR by multiplying with 0.97. You can see the section LR Scheduling in the example notebook
Notice that we get 88.4% with same network and LR. Also notice that towards the end the loss and accuracy graphs are no longer fluctuating as before.
So we have gotten over 1% accuracy increase just by using LR finder with LR scheduling using the same 100 epochs we started with.
Using LR Finder is shown to be beneficial for both faster training and increasing accuracy. We also show how to use LR finder using an example notebook. The code of LR Finder is here.
In case you found this useful, do visit my Notebook/Github for full code. | [
{
"code": null,
"e": 385,
"s": 172,
"text": "While training a Deep Neural Network selecting a good learning rate is essential for both fast convergence and a lower error. We also have to select a optimiser which decides how weight updates are done in a DNN."
},
{
"code": null,
"e": 756,
"s": 385,
"text": "There are various optimisers available like Adam, SGD+momentum, Adagrad, RMSprop, AdaDelta, AdaBound. Of these Adam and SGD+momentum are most popular. While training a Fully Connected DNN or a Convolutional network most State of the Art networks use SGD+momentum. This is due to the fact that it generalises better to unseen data and gives better validation/test scores."
},
{
"code": null,
"e": 1213,
"s": 756,
"text": "There are two tiny problems with SGD though, SGD is slow to converge compared to Adam and SGD requires learning rate tuning. Surprisingly the solution to both problems is using a good starting learning rate. In case your LR is too high, your errors will never reduce and training will not converge. Too low LR and you have to wait too long for training to converge. So we start with a good LR given by LR-Finder, then decay it a little as we reach the end."
},
{
"code": null,
"e": 1514,
"s": 1213,
"text": "Basic objective of a LR Finder is to find the highest LR which still minimises the loss and does not make the loss explode/diverge. We do this by training a model while increasing the LR after each batch, we record the loss and finally we use the LR just before loss exploded. We do this for 1 epoch."
},
{
"code": null,
"e": 1846,
"s": 1514,
"text": "start_lr = 0.0001end_lr = 1.0num_batches = len(Data)/batch_sizecur_lr = start_lrlr_multiplier = (end_lr / start_lr) ** (1.0 / num_batches)losses = []lrs = []for i in 1 to num_batches: loss = train_model_get_loss(batch=i) losses.append(loss) lrs.append(cur_lr) cur_lr = cur_lr*lr_multiplier # increase LRplot(lrs,losses)"
},
{
"code": null,
"e": 1889,
"s": 1846,
"text": "You will get a plot which looks like below"
},
{
"code": null,
"e": 1964,
"s": 1889,
"text": "We plot the points with a arrow to indicate location in our implementation"
},
{
"code": null,
"e": 2042,
"s": 1964,
"text": "From this plot we find the point after which loss starts increasing too much."
},
{
"code": null,
"e": 2175,
"s": 2042,
"text": "I have written a small library which contains the LR Finder. This is for Keras. For pytorch fast.ai implementation works.To install:"
},
{
"code": null,
"e": 2309,
"s": 2175,
"text": "pip install --upgrade --upgrade-strategy only-if-needed https://github.com/faizanahemad/data-science-utils/tarball/master > /dev/null"
},
{
"code": null,
"e": 2346,
"s": 2309,
"text": "Next in your notebook (For Cifar 10)"
},
{
"code": null,
"e": 2405,
"s": 2346,
"text": "First Define Imports and Data generators for our Data set."
},
{
"code": null,
"e": 2925,
"s": 2405,
"text": "from data_science_utils.vision.keras import *X_train, Y_train, X_test, Y_test = get_cifar10_data()cutout_fn = get_cutout_eraser(p=0.75, s_l=0.1, s_h=0.3, r_1=0.3, r_2=1 / 0.3, max_erasures_per_image=2, pixel_level=True)datagen = ImageDataGenerator(featurewise_center=True,featurewise_std_normalization=True, preprocessing_function=cutout_fn)datagen_validation = ImageDataGenerator(featurewise_center=True,featurewise_std_normalization=True,)datagen_validation.fit(X_train)model = build_model()"
},
{
"code": null,
"e": 2974,
"s": 2925,
"text": "Next We build our model and use LR Finder on it."
},
{
"code": null,
"e": 3317,
"s": 2974,
"text": "model = build_model() # returns an instance of Keras Modellrf = LRFinder(model)generator = datagen.flow(X_train, Y_train, batch_size=256,shuffle=True)test_generator = datagen_validation.flow(X_test, Y_test, batch_size=256, shuffle=True)lrf.find_generator(generator, 0.0001, 10.0,test_generator, epochs=1, steps_per_epoch=None,)lrf.plot_loss()"
},
{
"code": null,
"e": 3425,
"s": 3317,
"text": "The above 2 plots you saw were generated using this. You can see the example in this Google Colab Notebook."
},
{
"code": null,
"e": 3665,
"s": 3425,
"text": "We use the minimas as our candidate LRs. You can notice that some of these are local minimas, where the overall loss is quite high, for the candidate LRs the overall loss should be near to the minimum loss. So we filter these local minimas"
},
{
"code": null,
"e": 3820,
"s": 3665,
"text": "We need to use validation set to find loss, using training set to find loss will not yield correct results since the weights will overfit to training set."
},
{
"code": null,
"e": 4104,
"s": 3820,
"text": "When we generate candidate LRs, we need to ensure that those are distinct enough. For example generating candidates like 0.552 and 0.563 doesn’t make sense since these LRs are too close. As such we apply a rule that each LR should be atleast 20% different from its previous lower LR."
},
{
"code": null,
"e": 4320,
"s": 4104,
"text": "Note that LR Finder gives you an approx value, So it doesn’t matter if you take the exact value or not. Like if LRF gives you 0.012, then you can use 0.01 as well. If it gives 0.056 then both 0.05 and 0.06 are fine."
},
{
"code": null,
"e": 4427,
"s": 4320,
"text": "We can use LR scheduling or LR decay to reduce LR in later epochs since we started with high LR initially."
},
{
"code": null,
"e": 4582,
"s": 4427,
"text": "We used SGD directly with a learning_rate of 0.01 and nesterov’s momentum. We trained the network on CIFAR-10 for 100 epochs. Our network has 450K params."
},
{
"code": null,
"e": 4683,
"s": 4582,
"text": "As you can notice it took about 60 epochs for validation error to converge and it is 86.7% accuracy."
},
{
"code": null,
"e": 4745,
"s": 4683,
"text": "We use the LR provided by LR finder. Everything else is same."
},
{
"code": null,
"e": 4928,
"s": 4745,
"text": "You can see that here we get 86.4% accuracy but training converges in 40 epochs instead of 60. Using LR given by LR finder along with EarlyStopping can reduce compute time massively."
},
{
"code": null,
"e": 5120,
"s": 4928,
"text": "We use LR scheduling from keras to decrease LR in each epoch. Basically after each epoch we decrease LR by multiplying with 0.97. You can see the section LR Scheduling in the example notebook"
},
{
"code": null,
"e": 5270,
"s": 5120,
"text": "Notice that we get 88.4% with same network and LR. Also notice that towards the end the loss and accuracy graphs are no longer fluctuating as before."
},
{
"code": null,
"e": 5400,
"s": 5270,
"text": "So we have gotten over 1% accuracy increase just by using LR finder with LR scheduling using the same 100 epochs we started with."
},
{
"code": null,
"e": 5584,
"s": 5400,
"text": "Using LR Finder is shown to be beneficial for both faster training and increasing accuracy. We also show how to use LR finder using an example notebook. The code of LR Finder is here."
}
] |
How to add placeholder to an Entry in tkinter? | Tkinter provides features to add widgets such as button, text, entry, dialogue and
other attributes that help to develop an application. However, tkinter doesn't
include a placeholder in the entry widget. Placeholders are the dummy text that
appears in the entry widget to inform the user about it.
In this article, we will add a placeholder in the entry widget using the insert(default value, text) function that takes a default value such as 0 along with the placeholder text.
#Import tkinter library
from tkinter import*
#Create an instance of frame
win= Tk()
#Set geometry
win.geometry("700x400")
#Create a text Label
Label(win, text="Notepad", font=('Poppins bold', 25)).pack(pady=20)
text= StringVar()
#Create an entry widget
test= Entry(win, textvariable=text)
test.pack(fill='x', expand=True, padx= 45, pady=45)
test.focus()
#Add a placeholder in the entry Widget
test.insert(0, "Enter any Text")
win.mainloop()
Running the above code will create an Entry Widget with some placeholder in it. | [
{
"code": null,
"e": 1361,
"s": 1062,
"text": "Tkinter provides features to add widgets such as button, text, entry, dialogue and\nother attributes that help to develop an application. However, tkinter doesn't\ninclude a placeholder in the entry widget. Placeholders are the dummy text that\nappears in the entry widget to inform the user about it."
},
{
"code": null,
"e": 1541,
"s": 1361,
"text": "In this article, we will add a placeholder in the entry widget using the insert(default value, text) function that takes a default value such as 0 along with the placeholder text."
},
{
"code": null,
"e": 1987,
"s": 1541,
"text": "#Import tkinter library\nfrom tkinter import*\n\n#Create an instance of frame\nwin= Tk()\n\n#Set geometry\nwin.geometry(\"700x400\")\n\n#Create a text Label\nLabel(win, text=\"Notepad\", font=('Poppins bold', 25)).pack(pady=20)\ntext= StringVar()\n\n#Create an entry widget\ntest= Entry(win, textvariable=text)\ntest.pack(fill='x', expand=True, padx= 45, pady=45)\ntest.focus()\n\n#Add a placeholder in the entry Widget\ntest.insert(0, \"Enter any Text\")\nwin.mainloop()"
},
{
"code": null,
"e": 2067,
"s": 1987,
"text": "Running the above code will create an Entry Widget with some placeholder in it."
}
] |
GATE | GATE-CS-2015 (Set 2) | Question 65 - GeeksforGeeks | 28 Jun, 2021
A system has 6 identical resources and N processes competing for them. Each process can request atmost 2 resources. Which one of the following values of N could lead to a deadlock?
(A) 1(B) 2(C) 3(D) 4Answer: (D)Explanation: It seems to be wrong question in GATE exam. Below seems to be the worst case situation. In below situation P1 and P2 can continue as they have 2 resources each
P1 --> 2
P2 --> 2
P3 --> 1
P4 --> 1
Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-IT-2004 | Question 71
GATE | GATE CS 2011 | Question 7
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE CS 2018 | Question 37
GATE | GATE-IT-2004 | Question 83
GATE | GATE-CS-2016 (Set 1) | Question 63
GATE | GATE-CS-2014-(Set-2) | Question 65
GATE | GATE-CS-2007 | Question 64 | [
{
"code": null,
"e": 24466,
"s": 24438,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24647,
"s": 24466,
"text": "A system has 6 identical resources and N processes competing for them. Each process can request atmost 2 resources. Which one of the following values of N could lead to a deadlock?"
},
{
"code": null,
"e": 24851,
"s": 24647,
"text": "(A) 1(B) 2(C) 3(D) 4Answer: (D)Explanation: It seems to be wrong question in GATE exam. Below seems to be the worst case situation. In below situation P1 and P2 can continue as they have 2 resources each"
},
{
"code": null,
"e": 24888,
"s": 24851,
"text": "P1 --> 2\nP2 --> 2\nP3 --> 1\nP4 --> 1 "
},
{
"code": null,
"e": 24910,
"s": 24888,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 24931,
"s": 24910,
"text": "GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 24957,
"s": 24931,
"text": "GATE-GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 24962,
"s": 24957,
"text": "GATE"
},
{
"code": null,
"e": 25060,
"s": 24962,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25069,
"s": 25060,
"text": "Comments"
},
{
"code": null,
"e": 25082,
"s": 25069,
"text": "Old Comments"
},
{
"code": null,
"e": 25116,
"s": 25082,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25149,
"s": 25116,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25191,
"s": 25149,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25233,
"s": 25191,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 25275,
"s": 25233,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
},
{
"code": null,
"e": 25309,
"s": 25275,
"text": "GATE | GATE CS 2018 | Question 37"
},
{
"code": null,
"e": 25343,
"s": 25309,
"text": "GATE | GATE-IT-2004 | Question 83"
},
{
"code": null,
"e": 25385,
"s": 25343,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 63"
},
{
"code": null,
"e": 25427,
"s": 25385,
"text": "GATE | GATE-CS-2014-(Set-2) | Question 65"
}
] |
PHP | Number of week days between two dates - GeeksforGeeks | 20 Oct, 2018
You are given two string (dd-mm-yyyy) representing two date, you have to find number of all weekdays present in between given dates.(both inclusive)
Examples:
Input : startDate = "01-01-2018" endDate = "01-03-2018"
Output : Array
(
[Monday] => 9
[Tuesday] => 9
[Wednesday] => 9
[Thursday] => 9
[Friday] => 8
[Saturday] => 8
[Sunday] => 8
)
Input : startDate = "01-01-2018" endDate = "01-01-2018"
Output : Array
(
[Monday] => 1
[Tuesday] => 0
[Wednesday] => 0
[Thursday] => 0
[Friday] => 0
[Saturday] => 0
[Sunday] => 0
)
The basic idea to find out number of all weekdays is very simple, you have to iterate from start date to end date and increase the count of each day. Hence you can calculate the desired result.
In php we can find day for a particular date by using date() function as date(‘l’, $timestamp) where $timestamp is the value of strtotime($date). Also you can increase the date value by 1 with the help of $date->modify(‘+1 day’).
Algorithm :
convert startDate & endDate string into Datetime() object. Iterate from startDate to endDate in a loop: Find out then timestamp of startDate.Find out the weekday for current timestamp of startDate.Increase the value of particular weekday by 1.Increase the value of startDate by 1.Print the array containing value of all weekdays.
convert startDate & endDate string into Datetime() object.
Iterate from startDate to endDate in a loop: Find out then timestamp of startDate.Find out the weekday for current timestamp of startDate.Increase the value of particular weekday by 1.Increase the value of startDate by 1.
Find out then timestamp of startDate.
Find out the weekday for current timestamp of startDate.
Increase the value of particular weekday by 1.
Increase the value of startDate by 1.
Print the array containing value of all weekdays.
<?php // input start and end date $startDate = "01-01-2018"; $endDate = "01-01-2019"; $resultDays = array('Monday' => 0, 'Tuesday' => 0, 'Wednesday' => 0, 'Thursday' => 0, 'Friday' => 0, 'Saturday' => 0, 'Sunday' => 0); // change string to date time object $startDate = new DateTime($startDate); $endDate = new DateTime($endDate); // iterate over start to end date while($startDate <= $endDate ){ // find the timestamp value of start date $timestamp = strtotime($startDate->format('d-m-Y')); // find out the day for timestamp and increase particular day $weekDay = date('l', $timestamp); $resultDays[$weekDay] = $resultDays[$weekDay] + 1; // increase startDate by 1 $startDate->modify('+1 day'); } // print the result print_r($resultDays);?>
Output :
Array
(
[Monday] => 53
[Tuesday] => 53
[Wednesday] => 52
[Thursday] => 52
[Friday] => 52
[Saturday] => 52
[Sunday] => 52
)
date-time-program
PHP-date-time
PHP
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to pop an alert message box using PHP ?
How to delete an array element based on key in PHP?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | strval() Function
Comparing two dates in PHP | [
{
"code": null,
"e": 31406,
"s": 31378,
"text": "\n20 Oct, 2018"
},
{
"code": null,
"e": 31555,
"s": 31406,
"text": "You are given two string (dd-mm-yyyy) representing two date, you have to find number of all weekdays present in between given dates.(both inclusive)"
},
{
"code": null,
"e": 31565,
"s": 31555,
"text": "Examples:"
},
{
"code": null,
"e": 31990,
"s": 31565,
"text": "Input : startDate = \"01-01-2018\" endDate = \"01-03-2018\"\nOutput : Array\n(\n [Monday] => 9\n [Tuesday] => 9\n [Wednesday] => 9\n [Thursday] => 9\n [Friday] => 8\n [Saturday] => 8\n [Sunday] => 8\n)\n\nInput : startDate = \"01-01-2018\" endDate = \"01-01-2018\"\nOutput : Array\n(\n [Monday] => 1\n [Tuesday] => 0\n [Wednesday] => 0\n [Thursday] => 0\n [Friday] => 0\n [Saturday] => 0\n [Sunday] => 0\n)\n\n"
},
{
"code": null,
"e": 32184,
"s": 31990,
"text": "The basic idea to find out number of all weekdays is very simple, you have to iterate from start date to end date and increase the count of each day. Hence you can calculate the desired result."
},
{
"code": null,
"e": 32414,
"s": 32184,
"text": "In php we can find day for a particular date by using date() function as date(‘l’, $timestamp) where $timestamp is the value of strtotime($date). Also you can increase the date value by 1 with the help of $date->modify(‘+1 day’)."
},
{
"code": null,
"e": 32426,
"s": 32414,
"text": "Algorithm :"
},
{
"code": null,
"e": 32757,
"s": 32426,
"text": "convert startDate & endDate string into Datetime() object. Iterate from startDate to endDate in a loop: Find out then timestamp of startDate.Find out the weekday for current timestamp of startDate.Increase the value of particular weekday by 1.Increase the value of startDate by 1.Print the array containing value of all weekdays."
},
{
"code": null,
"e": 32816,
"s": 32757,
"text": "convert startDate & endDate string into Datetime() object."
},
{
"code": null,
"e": 33040,
"s": 32816,
"text": " Iterate from startDate to endDate in a loop: Find out then timestamp of startDate.Find out the weekday for current timestamp of startDate.Increase the value of particular weekday by 1.Increase the value of startDate by 1."
},
{
"code": null,
"e": 33080,
"s": 33040,
"text": " Find out then timestamp of startDate."
},
{
"code": null,
"e": 33137,
"s": 33080,
"text": "Find out the weekday for current timestamp of startDate."
},
{
"code": null,
"e": 33184,
"s": 33137,
"text": "Increase the value of particular weekday by 1."
},
{
"code": null,
"e": 33222,
"s": 33184,
"text": "Increase the value of startDate by 1."
},
{
"code": null,
"e": 33272,
"s": 33222,
"text": "Print the array containing value of all weekdays."
},
{
"code": "<?php // input start and end date $startDate = \"01-01-2018\"; $endDate = \"01-01-2019\"; $resultDays = array('Monday' => 0, 'Tuesday' => 0, 'Wednesday' => 0, 'Thursday' => 0, 'Friday' => 0, 'Saturday' => 0, 'Sunday' => 0); // change string to date time object $startDate = new DateTime($startDate); $endDate = new DateTime($endDate); // iterate over start to end date while($startDate <= $endDate ){ // find the timestamp value of start date $timestamp = strtotime($startDate->format('d-m-Y')); // find out the day for timestamp and increase particular day $weekDay = date('l', $timestamp); $resultDays[$weekDay] = $resultDays[$weekDay] + 1; // increase startDate by 1 $startDate->modify('+1 day'); } // print the result print_r($resultDays);?>",
"e": 34133,
"s": 33272,
"text": null
},
{
"code": null,
"e": 34142,
"s": 34133,
"text": "Output :"
},
{
"code": null,
"e": 34294,
"s": 34142,
"text": "Array\n(\n [Monday] => 53\n [Tuesday] => 53\n [Wednesday] => 52\n [Thursday] => 52\n [Friday] => 52\n [Saturday] => 52\n [Sunday] => 52\n)\n"
},
{
"code": null,
"e": 34312,
"s": 34294,
"text": "date-time-program"
},
{
"code": null,
"e": 34326,
"s": 34312,
"text": "PHP-date-time"
},
{
"code": null,
"e": 34330,
"s": 34326,
"text": "PHP"
},
{
"code": null,
"e": 34334,
"s": 34330,
"text": "PHP"
},
{
"code": null,
"e": 34432,
"s": 34334,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34477,
"s": 34432,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 34527,
"s": 34477,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 34551,
"s": 34527,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 34591,
"s": 34551,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 34635,
"s": 34591,
"text": "How to pop an alert message box using PHP ?"
},
{
"code": null,
"e": 34687,
"s": 34635,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 34748,
"s": 34687,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 34798,
"s": 34748,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 34822,
"s": 34798,
"text": "PHP | strval() Function"
}
] |
Take it to Twitter: Social Media Analysis of Members of Congress | by Blake Robert Mills | Towards Data Science | Twitter and American Politics
Since the Trump administration took office, Twitter usage has been discussed ad nauseam in American politics. While Former President Trump has since left office, the importance of the social media app has remained constant. Twitter has now become a primary way for congressional members to engage with their constituents and express their opinions on policy issues.
With the new Biden Administration taking office, congressional bipartisanship has been at the forefront of every major issue in politics. With tight margins in both the House and the Senate, the need for members of both parties to support legislation is crucial for effective government. While both sides talk about the need for bipartisan support, in a time of hyper-polarization, do they reflect this need in their social media?
To examine this question, I collected tweets from sitting members of congress. Any and all accounts owned and (appeared to be) operated by a congress member were scraped for tweets. While many politicians have teams running their social media, the specific goal of this analysis was to look at tweets from accounts where the source appeared to the congress member themselves.
To examine this question, I collected tweets from sitting members of congress. Any and all accounts owned and operated by a congress member were scrapped for tweets. While many politicians have teams running their social media, the specific goal of this analysis was to look at tweets from accounts where the source appeared to be the congress members themselves.
For this specific project, the main areas of interest were:
How are members of congress tweeting about each other (both members of their own party and the opposing party)?Are they tweeting about social and policy issues in a positive or negative way?What keywords are most often used for social and policy issues? And how do these keywords differ by party?
How are members of congress tweeting about each other (both members of their own party and the opposing party)?
Are they tweeting about social and policy issues in a positive or negative way?
What keywords are most often used for social and policy issues? And how do these keywords differ by party?
Tweet Collection and Pre-Processing
In order to conduct this analysis, Twitter accounts of members of Congress had to be determined. The Triage Cancer organization has a spreadsheet located on their website with the main handles of all congressional members (link to sheet here). While this served as a solid base, I noticed that there were members on the list that were no longer serving. One limitation of the list only contained was that it only named the governmental accounts of congressional members; however, many have other accounts, which are often more frequently used. Thus, I manually looked each member up on Twitter to confirm the congressional account was accurate and discover any other profiles owned by current congressional members. I sorted these additional accounts into three categories: personal, campaign, and press office accounts. Personal accounts were usually stated as such in their bio and were often more active than a congress member’s congressional account. Campaign accounts were also collected if and only if the tweets presented as though they were originating from the congress member. Any account with a disclosure that it was run by a congress member’s team was excluded.. Finally, press office accounts were collected under a similar condition as a campaign account. If the bio of the account stated that tweets did not originate from the congress member themself, the account was not included. The purpose of collecting accounts this way was to analyze only the tweets that originate from the congress member.
Of all 535 members of congress, 532 were found to have at least one Twitter account. Former Rep. Alcee Hastings (D-FL), who passed away in April of 2021, did not have a Twitter account. His seat is currently vacant as well; thus, no tweets from Florida’s 23rd District could be analyzed. Rep. Chris Smith (R-NJ) was also found to have no Twitter accounts. The last member not analyzed was Rep. Jeff Van Drew (R-NJ). Rep. Van Drew possessed a Twitter account; however, it was deleted in February of 2021. It did not feel appropriate to include whatever tweets could be collected, as the timespan of his tweets would not be the same as all other accounts.
There were also two other accounts in which tweets could not be collected. Rep. Doug LaMalfa (R-CA) and Rep. Zoe Lofgren (D-CA) had private personal accounts not included in this analysis. Given that these are not accessible to a general audience, it did not make sense to include them, as the purpose of this analysis was to see how congressional members present themselves publicly.
In the end, 1,016 accounts linked to congressional members were identified. This included 517 governmental accounts, 320 personal accounts, 166 campaign accounts, and 17 press office accounts.
Tweets were collected between the period of November 3rd, 2020, to July 25th, 2021. The first collection of tweets were pulled on April 25th, and additional tweets were added on June 15th and July 25th. Because additional tweets were appended to an existing data frame, it is possible that deleted tweets could be included in the data frame. Tweets were collected using a Twitter API and the get_timeline function from the rtweet package in R. Due to restriction of the Twitter API, only the most recent 3,200 tweets from any account could be pulled. There were no congress members that had tweeted more than 3,200 times since November 3rd, 2020, when the initial collection was executed. When additional tweets were appended to the previous collection, duplicates were checked based on the tweet’s content, the screen name of the tweeter, and the time at which it was created. This allowed for new tweets to be kept and any duplicated to be removed. Example code for collecting tweets and checking for duplicates is provided below in the embedded code where “TwitterAccounts” is a data frame with congressional accounts and “Handle” is the column with each Twitter screen name.
library(rtweet)Tweets <- vector()for (i in TwitterAccounts$Handle){ df <- get_timeline(i, n=3200) #Collects the most recent 3,200 Tweets from each handle Tweets <- rbind(Tweets, df) #Binds into one large df }#Used when appending additional tweets to existing dfNewTwitterDf <- rbind(OldTwitterDf, Tweets)NewTwitterDf <- NewTwitterDf %>% mutate(screen_name= tolower(screen_name)) %>% #Standardizes handles to all be lowercase distinct(text, screen_name, created_at, .keep_all = TRUE) #Checks for dups based on tweet, user, and time tweeted
While 1,016 accounts relating to sitting members of congress were identified, only 976 accounts were found to have had tweets between November 3rd, 2020, and July 25th, 2021. Most of the accounts dropped were campaign accounts that were not active after November 3rd. From these accounts, 541,689 tweets in the specified time frame were collected. These served as the tweets used in the analyses.
Twitter Profiles and Behavior of Congressional Members
Before any text was processed, simple measures of the following and engagement of congressional members were examined. In the figure below, the follower count (as of July 25th, 2021) of the 976 accounts was analyzed and broken up by state. Of all accounts, only 35 have garnered more than a million followers, with the most popular accounts people identified by their handle on Figure 1 below.
It is seen that a majority of the highly followed accounts (more than 1,000,000 followers) are owned by Democrats (20 of 35). This is reflective of overall trends as well. The mean number of followers for a Republican congressional member’s account is 106,521 with a median of 15,024, while the mean number of followers for Democrats or Independents (grouped together as the two Independent senators caucus with the Democrats) is 253,327 followers with a median of 31,570. However, if the follower counts of Independents (mostly driven by Sen. Bernie Sanders) are dropped from the Democrat’s counts, the mean followers fall to 199,693 followers with a median of 31,496. Regardless, the overall trend appears that Democrats are more followed than Republicans.
It is also important to gather engagement of congressional members’ tweets. This was calculated using the mean number of favorites and retweets each account gets per tweet. Only original tweets were used for these calculations, meaning that retweets were not utilized to measure the congressional members’ engagement accurately. Once again, it appears Democrats have a slight edge over Republicans, with Democrats receiving a mean number of 1,171 favorites per tweetand Republicans receiving 627 favorites per tweet. These figures are likely inflated due to certain members receiving lots of engagement, as the mean number of favorites for Democrats at 94 favorites per tweet and 58 favorites per tweets for Republicans.
That all said, it appears the most accounts seem to receive retweets proportional to their number of favorites, with the vast majority of accounts receiving less than 500 favorites per tweet. Notably, of all tweets from congressional members since November 3, 2020, only three have received more than one million likes, with all tweets originating from Congresswoman Alexandria Ocasio-Cortez’s personal account (@AOC).
Text Processing
Next, the content of the tweets from these accounts was analyzed. Pre-processing was conducted on all tweets to make them able to be analyzed. First, all emojis were converted to text. This was done by using the “Emoji’s” data frame from Unicode.org in the rtweet package. The data frame contains two columns, one with each emoji and one with the text equivalent of the emoji. To make things interpretable when the tweets were tokenized, spaces in the emoji description were replaced with a hyphen, so they were read as a single token, and the word “emoji” was appended to each description. For example, “😀” was converted to “grinning-face-emoji.” After this, a simple loop checked tweets for each emoji and replaced it with its text equivalent. Example code is provided below.
library(rtweet)Emojis <- emojis Emojis$description <- str_replace_all(Emojis$description, " ", "-") %>% paste(" ", .,"emoji ", sep="-")for(i in 2284:2623){Election$text <- str_replace_all(Election$text, as.character(Emojis[i,1]), #Identify Emoji as.character(Emojis[i, 2]))} #Replace with word
Next, hashtags were cleaned. To do this, the “#” character was replaced with the word “hashtag” to help identity which strings were part of hashtags. Following this, all punctuation and capitalization were removed from the document. All numeric values were also removed from every tweet; however, before this occured, the numbers “45” and “46” were converted to “fortyfive” and “fortysix” so they would not be removed. These were chosen, as they usually carry an important semantic value in American politics: 45th President Trump and 46th President Biden.
Before any other processing was done, a frame was created. This frame was used to run sentiment analysis (described later). For this to occur, however, a frame was needed that did not have any further text processing, as the words in the tweets needed to remain unchanged for the sentiment library to work.
The document was also stemmed using the tm library in R. This allowed for tense deviations (vote, votes, voted, voting) and plurals (ballot, ballots) to be read as the same. One issue that arose from this is that the words “policy,” “policies,” and “police” were all read as the same character (“polici” after stemming). Given that these words have different meanings, especially in contemporary politics, a distinction must be made. Thus, prior to stemming, all instances of the words “policy” or “policies” were changed to “policygov” and “police” and other forms of the word were left unchanged to be stemmed. This allowed for the difference between the two words to be kept.
After this was complete, stop words, words frequently used that carry little to no semantic meaning individually, were removed. While the tm library in R contains a stop word library, it includes words like “states.” When used in terms of the verb, this word has little significance; however, in the realm of United States politics, this word needs to be kept. To prevent the exclusion of politically important words, a modified list of stop words was removed.
Finally, all extra whitespace in tweets were removed using the stripWhitespace function in the tm package. The final result was two data frames, one capable of running sentiment analysis after having tweets cleaned, and one used for tokenization for a bag of words model after stemming and the removal of stop words was complete. Code for how all of this cleaning was done is provided below.
Twitter$text <- tolower(Twitter$text) #Removes capitalization Twitter$text <- removePunctuation(Twitter$text) #Removes punctuation Twitter$text <- str_replace_all(Twitter$text, "policy|policies", "policygov") #Chnages policy (Document) to "policygov"Twitter$text <- str_replace_all(Twitter$text, "45", "fortyfive") #Changes number 45 to wordsTwitter$text <- str_replace_all(Twitter$text, "46", "fortysix") #Changes number 46 to wordsTwitter$text <- gsub("[[:digit:]]+", "", Twitter$text) #Removes all numbersTwitterSentiment <- Twitter #Creates a data frame for sentiment analysisTwitter$text <- stemDocument(Twitter$text) #Stems documentTwitter$text <- removeWords(Twitter$text, StopWords) #Removes all stopwords from a custom vectorTwitter$text <- stripWhitespace(Twitter$text) #Collapses all white space in a tweet
Sentiment Analysis
One area of interest is the sentiment of congressional members’ tweets. This is the process of taking a piece of text and analyzing the words used to determine emotion or assign a numeric value in order to rate it on its positivity or negativity.
Using the sentiment frame described above, tweets were assigned a unique ID number so that tokenization could occur and each tweet could still be identified later. Tweets were then split into individual tokens using the unnest_token function in the tidytext package. This resulted in a data frame where each row contained the original tweet ID number given and each word.
Next, the afinn sentiment library was loaded from the tidytext package as well. This creates a data frame with columns: one with sentimentally charged words and a corresponding sentiment. The scale of sentiments ranges from -5 (very negative) to +5 (very positive). This library was then joined to each token. If a word is included in a tweet but not included in the afinn library, the sentiment was labeled as NA. Following this, each tweet was aggregated so that the average sentiment of all words in the tweet was calculated. If all words in a tweet were NA, the sentiment of the tweet was coded as 0 (neutral sentiment). An example of this process using a tweet by Rep. Val Demings (D-FL), as well as the code for this process, is presented below.
library(tidytext)TwitterSentiment <- TwitterSentiment %>% mutate(TweetID=1:nrow(TwitterSentiment)) #unique ID for each tweetafinn <- TwitterSentiment %>% unnest_tokens(word, tweet) %>% #extracts each word in a tweet to its own row left_join(., get_sentiments("afinn")) %>% #Attaches sentiment from afinn library to each word select(-word) #removes word columnafinnTweets <- aggregate(value ~ TweetID, data=afinn, FUN=mean) %>% #Averages sentiment for all words in a tweet left_join(TwitterSentiment, ., by="TweetID") %>% #Adds sentiment to original df with complete tweet and data mutate(afinn = ifelse(is.na(value)==TRUE, 0, value)) #Changes tweets with NA sentiment to 0
As seen in the code, the NAs were filled with 0 when all words in a tweet were NA. Words that were not sentimentally charged in the afinn library were not replaced with a sentiment of 0, as this would have neutralized long tweets. For instance, in the tweet from Rep. Val Demings above, if NAs were filled with zeros prior to aggregating the mean, the tweet would have a sentiment of +0.45. However, suppose she tweeted, “Congratulations Tampa Bay Buccaneers and thank you to our amazing health care workers!” This tweet would have a sentiment of +0.77, as it has fewer neutral words. Despite the fact that the two phrases are semantically almost identical, they have quite different sentiments. Thus, NAs were not filled with 0s unless all words were NA after joining the afinn library.
Congressional Sentiment
Once the sentiment of all tweets were determined, the average sentiment for every member of congress across all their accounts was determined. This showed how positive (or negative) congressional members were presenting themselves publicly. From this analysis, it was found that the average sentiment for all members of congress with Twitter accounts was +0.56, meaning that, as a whole, the average congress member is tweeting slightly more positive statements. In fact, of the 532 members with Twitter accounts, only 25 had an average negative sentiment. The average sentiment of all congressional members is presented in the map below, with members with the highest and lowest sentiment and other frequently mentioned congressional members broken out. Further, the sentiment rank (starting at 1 for most negative and ending with 532 for most negative) is labeled. Additionally, the three members with no Twitter accounts are presented as gray hexagons in their respective states. Each hexagon is marked with the state and either the congressional district they represent or “Sen” for senators. The acronym “MAL” stands for “Member-At-Large” and is used when applicable.
One interesting thing to note is that some of the most talked about politicians have the lowest sentiments. Almost all of the frequently talked about congress members fall into the bottom 100 when ranked on sentiment. This could be due to them using their platform to criticize or speak negatively about policy proposals, current events, or other members to promote their agendas to their large audience; however, no formal analysis was done to test this.
Interactions through Mentions
Another area of interest is how politicians interact with each other. To measure this, the sentiment of each politician was gathered and aggregated by each party. First, using the mentions_screen_name variable provided in the Twitter dataset, any tweets mentioning the 976 accounts of congress members were pulled. Using the tweet sentiment method discussed above, the average sentiment of each politician mentioning any of their accounts was determined and broken apart by party. This means that the average sentiment of Democrats and Republicans could be determined for every member of congress. The results, along with the number of times each member of congress is mentioned by a party, is presented in Figures 5 and 6 below. Once again, for analysis purposes, both Independent senators were treated as Democrats but are presented as Independents in the graphs.
Interestingly, the graphs are strikingly similar, with almost all politicians, regardless of party, clustered above 0, meaning that, for the most part, all members are being mentioned in a positive light. Those below 0, for both parties, are almost exclusively members of the other party. However, what is perhaps the most interesting is that members of the opposite party are heavily clustered around 0 on the x-axis. This means that both parties are hardly mentioning the other in their tweet. This has two large implications. First, average sentiment for many members is determined by one or two tweets. Thus, extremities are heightened and should be taken with a grain of salt. Second, in an era where bipartisanship has been at the center of almost every piece of legislation, politicians tend to stick to their own members when it comes to talking about them, at least on Twitter. While it is positive to see that, for the most part, politicians are not tweeting about opposing party members negatively, in order to foster cooperation and give the appearance of bipartisanship to their constituents and followers, more interactions between parties need to occur.
One important caveat that should be noted for this and further sentiment analysis conducted is that some tweets may appear to be negative according to the afinn library, but contextually are not. This is exemplified in the case of Rep. Grace Meng (D-NY). She is one of the most mentioned politicians from tweets by Democrats (mentioned 440 times) and has a slight negative sentiment by Democrats as well (sentiment of -0.15). This is not because she is viewed as unfavorable, but rather because she is the sponsor of H.R. 1843, the COVID-19 Hate Crimes Act. When mentioning her, many congressional members have also mentioned her bill, and the afinn library is attaching a negative sentiment to the word “hate.” While this is an important caveat to note for particular examples, the analysis of tweets as a whole are more reflective of the afinn library’s determined sentiment rather than exceptions such as these.
Sentiments about Issues
While congressional members may not talk about each other that often, one area they overlap is the discussion of social and policy issues. With sentiments of all tweets determined, how members discuss contemporary issues could be examined.
Four contentious contemporary issues were randomly selected to examine: Black Lives Matter, immigration, infrastructure, and the minimum wage. Throughout the 2020 campaigns and continuing into legislation of the 117th congress, these issues have been discussed frequently, thus producing many tweets to allow for a thorough analysis.
Using only tweets that mentioned these issues, the average sentiment of all congressional members (if they had any tweets about said issue) was calculated. Their sentiments, as well as their frequency of tweeting about each issue are presented in Figures 7, 8, 9, and 10 below.
From the graphs, it is evident that for almost every issue, there is a clear divide between the two parties in terms of sentiment. Even in the case of infrastructure, nearly all tweets are slightly positive in sentiment, and it appears Democrats are still more positive as a whole than Republicans. In terms of frequency of tweets, it appears that both parties have similar trends for the issues of immigration and infrastructure, with the majority of their party mentioning the issue a few times and a few members tweeting about it frequently. For the issue of minimum wage, it is seen that almost all of the top tweeters are Democrats.
As for Black Lives Matter, it can be seen that the graph is overwhelmingly filled with blue dots compared to the reds. This signifies, as a whole, more Democrats have mentioned Black Lives Matter in at least one tweet compared to Republicans. Interestingly, the most frequent tweeter for the issue is Rep. Majorie Taylor Greene (R-GA). In fact, she makes up over 25% of all Republican tweets about Black Lives Matter. Given her outspokenness on this matter, this comes as little surprise; however, it can be noted that this is the only issue of the four selected where the top tweeter has a negative sentiment. It should be noted that tweets about Black Lives Matter naturally skew negative, as events surrounding it (such as murder) will negatively affect the afinn library. Thus, negative sentiment may not reflect a politician’s view of the issue but rather what events they are choosing to focus on.
While there appears to be a difference between the parties for the issues, tests should be conducted to test for this difference. Thus, a two-tailed Student’s t-test was performed on the difference between each party’s mean sentiment for both issues. Additionally, to check the effect size of these differences, the Cohen’s d was calculated. The results from all these tests are presented in the table below.
There was a highly statically significant difference between the mean sentiment of tweets for Democrats for all four issues compared to the mean sentiment of tweets for Republicans. For all the issues, but infrastructure, the average sentiment for Democrats was positive and the average sentiment for Republicans was negative. The issues of infrastructure and Black Lives Matter are seen to have a small effect size based on the Cohen’s d estimate. Thus, while there is a difference between the average sentiment of the respective issues for each party, the size of this effect is relatively small; however, the issues of minimum wage and infrastructure produced medium and large effect sizes, respectively, according to the estimated Cohen’s d. Thus, based on tweets about them, these policy issues see the largest partisan divide. What is striking is the especially high Cohen’s d estimate of immigration. At 0.93, this large effect size signals that this is the policy area of all the issues chosen when Democrats and Republicans have the biggest discrepancy of viewpoints based on the sentiment of their tweets.
Talking about Issues
Given that there is a clear difference between the way Democrats and Republicans tweet about policy issues, it will be interesting to see what keywords are most frequently used in relation to each issue. To do this, the Twitter data frame with removed stop words and stemmed was used. Once again, any tweet mentioning one of the four social or policy issues decided was separated. From there, using the unnest_token function part of the tidytext package, the frequency of all unigram (one-word tokens) and bigrams (two-word tokens) in a tweet were calculated. The frequency of these was then summed for each party to gather the total number of times a unigram or bigram is used for a party in a tweet about a specific policy or social issue. Once again, Independent tweets were categorized under Democrats.
After this, the top 25 unigram or bigrams for an issue by party was found. The following four figures display these most common tokens in tweets by Democrats and Republicans.
Not only do these word clouds reveal what each party associates with an issue, but it also helps explain the trends in their sentiments. One of the most exciting areas is the difference in parties in the issue of Black Lives Matter. As seen in the Cohen’s d test, the effect size of the difference of sentiment was seen as small. However, this may be because both parties are tweeting about the issue negatively, but in different ways. From the word clouds, it can be seen that “protest” is one of the frequent words used for Democrats, which carries a sentiment of -2 according to the afinn library. Meanwhile, Republicans often use the words “Riot” and “Violence” in association with Black Lives Matter, which carry a sentiment of -2 and -3, respectively. Here, we can see that while both parties are using negative words, the connotation of protest and riot are quite different. It should also be reiterated that Rep. Marjorie Taylor Greene accounted for approximately 27% of all Republican tweets about Black Lives Matter, meaning that this word cloud may be more reflective of her view rather than the Republican Party as a whole. Nonetheless, her prominence here signifies her focus of the issue, but also the notable lack of Republican tweets, especially compared to that of number of tweets by Democrats
One interesting thing to note is that “Biden” is one of the most frequently used words for all issues in Republican tweets; however, “Biden” does not appear on any of the word clouds for Democratic tweets. An interesting area for further analysis would be to determine in what context Biden’s name is being used: whether this is merely because he is the current president (thus an important taking point), or rather because they are criticizing his approach to these issues.
Key Take-aways
From the sentiment analyses conducted and the tokenization of tweets regarding issues, a few key takeaways can be seen.
There is a clear difference between the ways Democrats and Republicans tweet about issues. From our select social and policy problems, the t-test and Cohen’s d test revealed that there is a clear difference between the sentiment of the two parties. Looking at the word clouds as well, it can be seen that Democrats and Republicans seldom use similar words to describe the selected issues. This signals that instead of using Twitter as a platform to promote a bipartisanship agenda, congress members are doubling down on party divides and making this public to their constituents as well.Republicans tend to tweet more negatively about issues than Democrats, even on issues where there is bipartisan support, such as infrastructure. This phenomenon could occur for several reasons, including the topics selected, the current administration being Democratic, or Twitter behavior in general. Another possibility is that this displays the partisan divide of congress, where even in terms of policy agreement, sentiment and enthusiasm is not equal.Frequent or passionate tweeters have the power to dominate a party’s sentiment and views on Twitter. As seen with Rep. Marjorie Taylor Greene, one politician can dominate an issue if they tweet about it enough. To a lesser extent, this could also be applied to Rep. Pramilia Jayapal (D-WA), who was found to be the most frequent tweeter for 3 of the 4 issues select.While Democrats lead in terms of most followed accounts, top Republicans are getting close to the same engagement. Democratic members own 20 of the 35 accounts with over 1,000,000 followers, and Rep. Alexandria Ocasio-Cortez stands out with the average likes and retweets she receives; however, accounts that received the most engagement are closer to a 50–50 split between Republicans and Democrats.To make waves, you might have to be negative. As seen in the sentiment map of all members, some of the most talked are seen to have some of the most negative sentiments of all congress members. From this analysis, it is unclear whether negativity receives more attention, or if the most well known members of congress naturally tweet more negatively.
There is a clear difference between the ways Democrats and Republicans tweet about issues. From our select social and policy problems, the t-test and Cohen’s d test revealed that there is a clear difference between the sentiment of the two parties. Looking at the word clouds as well, it can be seen that Democrats and Republicans seldom use similar words to describe the selected issues. This signals that instead of using Twitter as a platform to promote a bipartisanship agenda, congress members are doubling down on party divides and making this public to their constituents as well.
Republicans tend to tweet more negatively about issues than Democrats, even on issues where there is bipartisan support, such as infrastructure. This phenomenon could occur for several reasons, including the topics selected, the current administration being Democratic, or Twitter behavior in general. Another possibility is that this displays the partisan divide of congress, where even in terms of policy agreement, sentiment and enthusiasm is not equal.
Frequent or passionate tweeters have the power to dominate a party’s sentiment and views on Twitter. As seen with Rep. Marjorie Taylor Greene, one politician can dominate an issue if they tweet about it enough. To a lesser extent, this could also be applied to Rep. Pramilia Jayapal (D-WA), who was found to be the most frequent tweeter for 3 of the 4 issues select.
While Democrats lead in terms of most followed accounts, top Republicans are getting close to the same engagement. Democratic members own 20 of the 35 accounts with over 1,000,000 followers, and Rep. Alexandria Ocasio-Cortez stands out with the average likes and retweets she receives; however, accounts that received the most engagement are closer to a 50–50 split between Republicans and Democrats.
To make waves, you might have to be negative. As seen in the sentiment map of all members, some of the most talked are seen to have some of the most negative sentiments of all congress members. From this analysis, it is unclear whether negativity receives more attention, or if the most well known members of congress naturally tweet more negatively.
Areas for Further Examination
There are several areas where a further examination is warranted. First, a wider range of issues should be examined. While the four issues were chosen due to their prevalence, with the exception of infrastructure, they are pro-Democrat issues (issues Democrats are pushing for). Issues that Republicans are pushing for should be examined to see how Democrats tweet about those issues.
Additionally, different ways in which the parties discuss issues could present a fascinating insight. For instance, when it comes to gun legislation, seeing how the words “regulation,” “control,” or “2nd Amendment” affect engagements (likes and retweets) and sentiment could reveal insights on how the parties present these issues to their followers.
Finally, using a different sentiment library may be more useful for some policy issues. As seen with Black Lives Matter, words with a negative sentiment are naturally used by both parties; however, discussing “riots” and “protests” shows a different viewpoint on the issue that cannot easily be captured in a semantic value. Using a different library or a different process may be able to capture this difference between parties better.
Thank you for reading. Feel free to email me with any questions at [email protected] or reach out to me on LinkedIn here.
Note: All photos of congressional members are their official portraits and are therefore part of the public domain. Photos were taken from the Government Printing Office’s Member Guide Photos | [
{
"code": null,
"e": 201,
"s": 171,
"text": "Twitter and American Politics"
},
{
"code": null,
"e": 567,
"s": 201,
"text": "Since the Trump administration took office, Twitter usage has been discussed ad nauseam in American politics. While Former President Trump has since left office, the importance of the social media app has remained constant. Twitter has now become a primary way for congressional members to engage with their constituents and express their opinions on policy issues."
},
{
"code": null,
"e": 998,
"s": 567,
"text": "With the new Biden Administration taking office, congressional bipartisanship has been at the forefront of every major issue in politics. With tight margins in both the House and the Senate, the need for members of both parties to support legislation is crucial for effective government. While both sides talk about the need for bipartisan support, in a time of hyper-polarization, do they reflect this need in their social media?"
},
{
"code": null,
"e": 1374,
"s": 998,
"text": "To examine this question, I collected tweets from sitting members of congress. Any and all accounts owned and (appeared to be) operated by a congress member were scraped for tweets. While many politicians have teams running their social media, the specific goal of this analysis was to look at tweets from accounts where the source appeared to the congress member themselves."
},
{
"code": null,
"e": 1738,
"s": 1374,
"text": "To examine this question, I collected tweets from sitting members of congress. Any and all accounts owned and operated by a congress member were scrapped for tweets. While many politicians have teams running their social media, the specific goal of this analysis was to look at tweets from accounts where the source appeared to be the congress members themselves."
},
{
"code": null,
"e": 1798,
"s": 1738,
"text": "For this specific project, the main areas of interest were:"
},
{
"code": null,
"e": 2095,
"s": 1798,
"text": "How are members of congress tweeting about each other (both members of their own party and the opposing party)?Are they tweeting about social and policy issues in a positive or negative way?What keywords are most often used for social and policy issues? And how do these keywords differ by party?"
},
{
"code": null,
"e": 2207,
"s": 2095,
"text": "How are members of congress tweeting about each other (both members of their own party and the opposing party)?"
},
{
"code": null,
"e": 2287,
"s": 2207,
"text": "Are they tweeting about social and policy issues in a positive or negative way?"
},
{
"code": null,
"e": 2394,
"s": 2287,
"text": "What keywords are most often used for social and policy issues? And how do these keywords differ by party?"
},
{
"code": null,
"e": 2430,
"s": 2394,
"text": "Tweet Collection and Pre-Processing"
},
{
"code": null,
"e": 3945,
"s": 2430,
"text": "In order to conduct this analysis, Twitter accounts of members of Congress had to be determined. The Triage Cancer organization has a spreadsheet located on their website with the main handles of all congressional members (link to sheet here). While this served as a solid base, I noticed that there were members on the list that were no longer serving. One limitation of the list only contained was that it only named the governmental accounts of congressional members; however, many have other accounts, which are often more frequently used. Thus, I manually looked each member up on Twitter to confirm the congressional account was accurate and discover any other profiles owned by current congressional members. I sorted these additional accounts into three categories: personal, campaign, and press office accounts. Personal accounts were usually stated as such in their bio and were often more active than a congress member’s congressional account. Campaign accounts were also collected if and only if the tweets presented as though they were originating from the congress member. Any account with a disclosure that it was run by a congress member’s team was excluded.. Finally, press office accounts were collected under a similar condition as a campaign account. If the bio of the account stated that tweets did not originate from the congress member themself, the account was not included. The purpose of collecting accounts this way was to analyze only the tweets that originate from the congress member."
},
{
"code": null,
"e": 4599,
"s": 3945,
"text": "Of all 535 members of congress, 532 were found to have at least one Twitter account. Former Rep. Alcee Hastings (D-FL), who passed away in April of 2021, did not have a Twitter account. His seat is currently vacant as well; thus, no tweets from Florida’s 23rd District could be analyzed. Rep. Chris Smith (R-NJ) was also found to have no Twitter accounts. The last member not analyzed was Rep. Jeff Van Drew (R-NJ). Rep. Van Drew possessed a Twitter account; however, it was deleted in February of 2021. It did not feel appropriate to include whatever tweets could be collected, as the timespan of his tweets would not be the same as all other accounts."
},
{
"code": null,
"e": 4984,
"s": 4599,
"text": "There were also two other accounts in which tweets could not be collected. Rep. Doug LaMalfa (R-CA) and Rep. Zoe Lofgren (D-CA) had private personal accounts not included in this analysis. Given that these are not accessible to a general audience, it did not make sense to include them, as the purpose of this analysis was to see how congressional members present themselves publicly."
},
{
"code": null,
"e": 5177,
"s": 4984,
"text": "In the end, 1,016 accounts linked to congressional members were identified. This included 517 governmental accounts, 320 personal accounts, 166 campaign accounts, and 17 press office accounts."
},
{
"code": null,
"e": 6356,
"s": 5177,
"text": "Tweets were collected between the period of November 3rd, 2020, to July 25th, 2021. The first collection of tweets were pulled on April 25th, and additional tweets were added on June 15th and July 25th. Because additional tweets were appended to an existing data frame, it is possible that deleted tweets could be included in the data frame. Tweets were collected using a Twitter API and the get_timeline function from the rtweet package in R. Due to restriction of the Twitter API, only the most recent 3,200 tweets from any account could be pulled. There were no congress members that had tweeted more than 3,200 times since November 3rd, 2020, when the initial collection was executed. When additional tweets were appended to the previous collection, duplicates were checked based on the tweet’s content, the screen name of the tweeter, and the time at which it was created. This allowed for new tweets to be kept and any duplicated to be removed. Example code for collecting tweets and checking for duplicates is provided below in the embedded code where “TwitterAccounts” is a data frame with congressional accounts and “Handle” is the column with each Twitter screen name."
},
{
"code": null,
"e": 6898,
"s": 6356,
"text": "library(rtweet)Tweets <- vector()for (i in TwitterAccounts$Handle){ df <- get_timeline(i, n=3200) #Collects the most recent 3,200 Tweets from each handle Tweets <- rbind(Tweets, df) #Binds into one large df }#Used when appending additional tweets to existing dfNewTwitterDf <- rbind(OldTwitterDf, Tweets)NewTwitterDf <- NewTwitterDf %>% mutate(screen_name= tolower(screen_name)) %>% #Standardizes handles to all be lowercase distinct(text, screen_name, created_at, .keep_all = TRUE) #Checks for dups based on tweet, user, and time tweeted"
},
{
"code": null,
"e": 7295,
"s": 6898,
"text": "While 1,016 accounts relating to sitting members of congress were identified, only 976 accounts were found to have had tweets between November 3rd, 2020, and July 25th, 2021. Most of the accounts dropped were campaign accounts that were not active after November 3rd. From these accounts, 541,689 tweets in the specified time frame were collected. These served as the tweets used in the analyses."
},
{
"code": null,
"e": 7350,
"s": 7295,
"text": "Twitter Profiles and Behavior of Congressional Members"
},
{
"code": null,
"e": 7744,
"s": 7350,
"text": "Before any text was processed, simple measures of the following and engagement of congressional members were examined. In the figure below, the follower count (as of July 25th, 2021) of the 976 accounts was analyzed and broken up by state. Of all accounts, only 35 have garnered more than a million followers, with the most popular accounts people identified by their handle on Figure 1 below."
},
{
"code": null,
"e": 8503,
"s": 7744,
"text": "It is seen that a majority of the highly followed accounts (more than 1,000,000 followers) are owned by Democrats (20 of 35). This is reflective of overall trends as well. The mean number of followers for a Republican congressional member’s account is 106,521 with a median of 15,024, while the mean number of followers for Democrats or Independents (grouped together as the two Independent senators caucus with the Democrats) is 253,327 followers with a median of 31,570. However, if the follower counts of Independents (mostly driven by Sen. Bernie Sanders) are dropped from the Democrat’s counts, the mean followers fall to 199,693 followers with a median of 31,496. Regardless, the overall trend appears that Democrats are more followed than Republicans."
},
{
"code": null,
"e": 9224,
"s": 8503,
"text": "It is also important to gather engagement of congressional members’ tweets. This was calculated using the mean number of favorites and retweets each account gets per tweet. Only original tweets were used for these calculations, meaning that retweets were not utilized to measure the congressional members’ engagement accurately. Once again, it appears Democrats have a slight edge over Republicans, with Democrats receiving a mean number of 1,171 favorites per tweetand Republicans receiving 627 favorites per tweet. These figures are likely inflated due to certain members receiving lots of engagement, as the mean number of favorites for Democrats at 94 favorites per tweet and 58 favorites per tweets for Republicans."
},
{
"code": null,
"e": 9643,
"s": 9224,
"text": "That all said, it appears the most accounts seem to receive retweets proportional to their number of favorites, with the vast majority of accounts receiving less than 500 favorites per tweet. Notably, of all tweets from congressional members since November 3, 2020, only three have received more than one million likes, with all tweets originating from Congresswoman Alexandria Ocasio-Cortez’s personal account (@AOC)."
},
{
"code": null,
"e": 9659,
"s": 9643,
"text": "Text Processing"
},
{
"code": null,
"e": 10437,
"s": 9659,
"text": "Next, the content of the tweets from these accounts was analyzed. Pre-processing was conducted on all tweets to make them able to be analyzed. First, all emojis were converted to text. This was done by using the “Emoji’s” data frame from Unicode.org in the rtweet package. The data frame contains two columns, one with each emoji and one with the text equivalent of the emoji. To make things interpretable when the tweets were tokenized, spaces in the emoji description were replaced with a hyphen, so they were read as a single token, and the word “emoji” was appended to each description. For example, “😀” was converted to “grinning-face-emoji.” After this, a simple loop checked tweets for each emoji and replaced it with its text equivalent. Example code is provided below."
},
{
"code": null,
"e": 10761,
"s": 10437,
"text": "library(rtweet)Emojis <- emojis Emojis$description <- str_replace_all(Emojis$description, \" \", \"-\") %>% paste(\" \", .,\"emoji \", sep=\"-\")for(i in 2284:2623){Election$text <- str_replace_all(Election$text, as.character(Emojis[i,1]), #Identify Emoji as.character(Emojis[i, 2]))} #Replace with word"
},
{
"code": null,
"e": 11318,
"s": 10761,
"text": "Next, hashtags were cleaned. To do this, the “#” character was replaced with the word “hashtag” to help identity which strings were part of hashtags. Following this, all punctuation and capitalization were removed from the document. All numeric values were also removed from every tweet; however, before this occured, the numbers “45” and “46” were converted to “fortyfive” and “fortysix” so they would not be removed. These were chosen, as they usually carry an important semantic value in American politics: 45th President Trump and 46th President Biden."
},
{
"code": null,
"e": 11625,
"s": 11318,
"text": "Before any other processing was done, a frame was created. This frame was used to run sentiment analysis (described later). For this to occur, however, a frame was needed that did not have any further text processing, as the words in the tweets needed to remain unchanged for the sentiment library to work."
},
{
"code": null,
"e": 12304,
"s": 11625,
"text": "The document was also stemmed using the tm library in R. This allowed for tense deviations (vote, votes, voted, voting) and plurals (ballot, ballots) to be read as the same. One issue that arose from this is that the words “policy,” “policies,” and “police” were all read as the same character (“polici” after stemming). Given that these words have different meanings, especially in contemporary politics, a distinction must be made. Thus, prior to stemming, all instances of the words “policy” or “policies” were changed to “policygov” and “police” and other forms of the word were left unchanged to be stemmed. This allowed for the difference between the two words to be kept."
},
{
"code": null,
"e": 12765,
"s": 12304,
"text": "After this was complete, stop words, words frequently used that carry little to no semantic meaning individually, were removed. While the tm library in R contains a stop word library, it includes words like “states.” When used in terms of the verb, this word has little significance; however, in the realm of United States politics, this word needs to be kept. To prevent the exclusion of politically important words, a modified list of stop words was removed."
},
{
"code": null,
"e": 13157,
"s": 12765,
"text": "Finally, all extra whitespace in tweets were removed using the stripWhitespace function in the tm package. The final result was two data frames, one capable of running sentiment analysis after having tweets cleaned, and one used for tokenization for a bag of words model after stemming and the removal of stop words was complete. Code for how all of this cleaning was done is provided below."
},
{
"code": null,
"e": 13975,
"s": 13157,
"text": "Twitter$text <- tolower(Twitter$text) #Removes capitalization Twitter$text <- removePunctuation(Twitter$text) #Removes punctuation Twitter$text <- str_replace_all(Twitter$text, \"policy|policies\", \"policygov\") #Chnages policy (Document) to \"policygov\"Twitter$text <- str_replace_all(Twitter$text, \"45\", \"fortyfive\") #Changes number 45 to wordsTwitter$text <- str_replace_all(Twitter$text, \"46\", \"fortysix\") #Changes number 46 to wordsTwitter$text <- gsub(\"[[:digit:]]+\", \"\", Twitter$text) #Removes all numbersTwitterSentiment <- Twitter #Creates a data frame for sentiment analysisTwitter$text <- stemDocument(Twitter$text) #Stems documentTwitter$text <- removeWords(Twitter$text, StopWords) #Removes all stopwords from a custom vectorTwitter$text <- stripWhitespace(Twitter$text) #Collapses all white space in a tweet"
},
{
"code": null,
"e": 13994,
"s": 13975,
"text": "Sentiment Analysis"
},
{
"code": null,
"e": 14241,
"s": 13994,
"text": "One area of interest is the sentiment of congressional members’ tweets. This is the process of taking a piece of text and analyzing the words used to determine emotion or assign a numeric value in order to rate it on its positivity or negativity."
},
{
"code": null,
"e": 14613,
"s": 14241,
"text": "Using the sentiment frame described above, tweets were assigned a unique ID number so that tokenization could occur and each tweet could still be identified later. Tweets were then split into individual tokens using the unnest_token function in the tidytext package. This resulted in a data frame where each row contained the original tweet ID number given and each word."
},
{
"code": null,
"e": 15365,
"s": 14613,
"text": "Next, the afinn sentiment library was loaded from the tidytext package as well. This creates a data frame with columns: one with sentimentally charged words and a corresponding sentiment. The scale of sentiments ranges from -5 (very negative) to +5 (very positive). This library was then joined to each token. If a word is included in a tweet but not included in the afinn library, the sentiment was labeled as NA. Following this, each tweet was aggregated so that the average sentiment of all words in the tweet was calculated. If all words in a tweet were NA, the sentiment of the tweet was coded as 0 (neutral sentiment). An example of this process using a tweet by Rep. Val Demings (D-FL), as well as the code for this process, is presented below."
},
{
"code": null,
"e": 16042,
"s": 15365,
"text": "library(tidytext)TwitterSentiment <- TwitterSentiment %>% mutate(TweetID=1:nrow(TwitterSentiment)) #unique ID for each tweetafinn <- TwitterSentiment %>% unnest_tokens(word, tweet) %>% #extracts each word in a tweet to its own row left_join(., get_sentiments(\"afinn\")) %>% #Attaches sentiment from afinn library to each word select(-word) #removes word columnafinnTweets <- aggregate(value ~ TweetID, data=afinn, FUN=mean) %>% #Averages sentiment for all words in a tweet left_join(TwitterSentiment, ., by=\"TweetID\") %>% #Adds sentiment to original df with complete tweet and data mutate(afinn = ifelse(is.na(value)==TRUE, 0, value)) #Changes tweets with NA sentiment to 0"
},
{
"code": null,
"e": 16830,
"s": 16042,
"text": "As seen in the code, the NAs were filled with 0 when all words in a tweet were NA. Words that were not sentimentally charged in the afinn library were not replaced with a sentiment of 0, as this would have neutralized long tweets. For instance, in the tweet from Rep. Val Demings above, if NAs were filled with zeros prior to aggregating the mean, the tweet would have a sentiment of +0.45. However, suppose she tweeted, “Congratulations Tampa Bay Buccaneers and thank you to our amazing health care workers!” This tweet would have a sentiment of +0.77, as it has fewer neutral words. Despite the fact that the two phrases are semantically almost identical, they have quite different sentiments. Thus, NAs were not filled with 0s unless all words were NA after joining the afinn library."
},
{
"code": null,
"e": 16854,
"s": 16830,
"text": "Congressional Sentiment"
},
{
"code": null,
"e": 18027,
"s": 16854,
"text": "Once the sentiment of all tweets were determined, the average sentiment for every member of congress across all their accounts was determined. This showed how positive (or negative) congressional members were presenting themselves publicly. From this analysis, it was found that the average sentiment for all members of congress with Twitter accounts was +0.56, meaning that, as a whole, the average congress member is tweeting slightly more positive statements. In fact, of the 532 members with Twitter accounts, only 25 had an average negative sentiment. The average sentiment of all congressional members is presented in the map below, with members with the highest and lowest sentiment and other frequently mentioned congressional members broken out. Further, the sentiment rank (starting at 1 for most negative and ending with 532 for most negative) is labeled. Additionally, the three members with no Twitter accounts are presented as gray hexagons in their respective states. Each hexagon is marked with the state and either the congressional district they represent or “Sen” for senators. The acronym “MAL” stands for “Member-At-Large” and is used when applicable."
},
{
"code": null,
"e": 18483,
"s": 18027,
"text": "One interesting thing to note is that some of the most talked about politicians have the lowest sentiments. Almost all of the frequently talked about congress members fall into the bottom 100 when ranked on sentiment. This could be due to them using their platform to criticize or speak negatively about policy proposals, current events, or other members to promote their agendas to their large audience; however, no formal analysis was done to test this."
},
{
"code": null,
"e": 18513,
"s": 18483,
"text": "Interactions through Mentions"
},
{
"code": null,
"e": 19379,
"s": 18513,
"text": "Another area of interest is how politicians interact with each other. To measure this, the sentiment of each politician was gathered and aggregated by each party. First, using the mentions_screen_name variable provided in the Twitter dataset, any tweets mentioning the 976 accounts of congress members were pulled. Using the tweet sentiment method discussed above, the average sentiment of each politician mentioning any of their accounts was determined and broken apart by party. This means that the average sentiment of Democrats and Republicans could be determined for every member of congress. The results, along with the number of times each member of congress is mentioned by a party, is presented in Figures 5 and 6 below. Once again, for analysis purposes, both Independent senators were treated as Democrats but are presented as Independents in the graphs."
},
{
"code": null,
"e": 20548,
"s": 19379,
"text": "Interestingly, the graphs are strikingly similar, with almost all politicians, regardless of party, clustered above 0, meaning that, for the most part, all members are being mentioned in a positive light. Those below 0, for both parties, are almost exclusively members of the other party. However, what is perhaps the most interesting is that members of the opposite party are heavily clustered around 0 on the x-axis. This means that both parties are hardly mentioning the other in their tweet. This has two large implications. First, average sentiment for many members is determined by one or two tweets. Thus, extremities are heightened and should be taken with a grain of salt. Second, in an era where bipartisanship has been at the center of almost every piece of legislation, politicians tend to stick to their own members when it comes to talking about them, at least on Twitter. While it is positive to see that, for the most part, politicians are not tweeting about opposing party members negatively, in order to foster cooperation and give the appearance of bipartisanship to their constituents and followers, more interactions between parties need to occur."
},
{
"code": null,
"e": 21463,
"s": 20548,
"text": "One important caveat that should be noted for this and further sentiment analysis conducted is that some tweets may appear to be negative according to the afinn library, but contextually are not. This is exemplified in the case of Rep. Grace Meng (D-NY). She is one of the most mentioned politicians from tweets by Democrats (mentioned 440 times) and has a slight negative sentiment by Democrats as well (sentiment of -0.15). This is not because she is viewed as unfavorable, but rather because she is the sponsor of H.R. 1843, the COVID-19 Hate Crimes Act. When mentioning her, many congressional members have also mentioned her bill, and the afinn library is attaching a negative sentiment to the word “hate.” While this is an important caveat to note for particular examples, the analysis of tweets as a whole are more reflective of the afinn library’s determined sentiment rather than exceptions such as these."
},
{
"code": null,
"e": 21487,
"s": 21463,
"text": "Sentiments about Issues"
},
{
"code": null,
"e": 21727,
"s": 21487,
"text": "While congressional members may not talk about each other that often, one area they overlap is the discussion of social and policy issues. With sentiments of all tweets determined, how members discuss contemporary issues could be examined."
},
{
"code": null,
"e": 22061,
"s": 21727,
"text": "Four contentious contemporary issues were randomly selected to examine: Black Lives Matter, immigration, infrastructure, and the minimum wage. Throughout the 2020 campaigns and continuing into legislation of the 117th congress, these issues have been discussed frequently, thus producing many tweets to allow for a thorough analysis."
},
{
"code": null,
"e": 22339,
"s": 22061,
"text": "Using only tweets that mentioned these issues, the average sentiment of all congressional members (if they had any tweets about said issue) was calculated. Their sentiments, as well as their frequency of tweeting about each issue are presented in Figures 7, 8, 9, and 10 below."
},
{
"code": null,
"e": 22977,
"s": 22339,
"text": "From the graphs, it is evident that for almost every issue, there is a clear divide between the two parties in terms of sentiment. Even in the case of infrastructure, nearly all tweets are slightly positive in sentiment, and it appears Democrats are still more positive as a whole than Republicans. In terms of frequency of tweets, it appears that both parties have similar trends for the issues of immigration and infrastructure, with the majority of their party mentioning the issue a few times and a few members tweeting about it frequently. For the issue of minimum wage, it is seen that almost all of the top tweeters are Democrats."
},
{
"code": null,
"e": 23881,
"s": 22977,
"text": "As for Black Lives Matter, it can be seen that the graph is overwhelmingly filled with blue dots compared to the reds. This signifies, as a whole, more Democrats have mentioned Black Lives Matter in at least one tweet compared to Republicans. Interestingly, the most frequent tweeter for the issue is Rep. Majorie Taylor Greene (R-GA). In fact, she makes up over 25% of all Republican tweets about Black Lives Matter. Given her outspokenness on this matter, this comes as little surprise; however, it can be noted that this is the only issue of the four selected where the top tweeter has a negative sentiment. It should be noted that tweets about Black Lives Matter naturally skew negative, as events surrounding it (such as murder) will negatively affect the afinn library. Thus, negative sentiment may not reflect a politician’s view of the issue but rather what events they are choosing to focus on."
},
{
"code": null,
"e": 24290,
"s": 23881,
"text": "While there appears to be a difference between the parties for the issues, tests should be conducted to test for this difference. Thus, a two-tailed Student’s t-test was performed on the difference between each party’s mean sentiment for both issues. Additionally, to check the effect size of these differences, the Cohen’s d was calculated. The results from all these tests are presented in the table below."
},
{
"code": null,
"e": 25406,
"s": 24290,
"text": "There was a highly statically significant difference between the mean sentiment of tweets for Democrats for all four issues compared to the mean sentiment of tweets for Republicans. For all the issues, but infrastructure, the average sentiment for Democrats was positive and the average sentiment for Republicans was negative. The issues of infrastructure and Black Lives Matter are seen to have a small effect size based on the Cohen’s d estimate. Thus, while there is a difference between the average sentiment of the respective issues for each party, the size of this effect is relatively small; however, the issues of minimum wage and infrastructure produced medium and large effect sizes, respectively, according to the estimated Cohen’s d. Thus, based on tweets about them, these policy issues see the largest partisan divide. What is striking is the especially high Cohen’s d estimate of immigration. At 0.93, this large effect size signals that this is the policy area of all the issues chosen when Democrats and Republicans have the biggest discrepancy of viewpoints based on the sentiment of their tweets."
},
{
"code": null,
"e": 25427,
"s": 25406,
"text": "Talking about Issues"
},
{
"code": null,
"e": 26234,
"s": 25427,
"text": "Given that there is a clear difference between the way Democrats and Republicans tweet about policy issues, it will be interesting to see what keywords are most frequently used in relation to each issue. To do this, the Twitter data frame with removed stop words and stemmed was used. Once again, any tweet mentioning one of the four social or policy issues decided was separated. From there, using the unnest_token function part of the tidytext package, the frequency of all unigram (one-word tokens) and bigrams (two-word tokens) in a tweet were calculated. The frequency of these was then summed for each party to gather the total number of times a unigram or bigram is used for a party in a tweet about a specific policy or social issue. Once again, Independent tweets were categorized under Democrats."
},
{
"code": null,
"e": 26409,
"s": 26234,
"text": "After this, the top 25 unigram or bigrams for an issue by party was found. The following four figures display these most common tokens in tweets by Democrats and Republicans."
},
{
"code": null,
"e": 27721,
"s": 26409,
"text": "Not only do these word clouds reveal what each party associates with an issue, but it also helps explain the trends in their sentiments. One of the most exciting areas is the difference in parties in the issue of Black Lives Matter. As seen in the Cohen’s d test, the effect size of the difference of sentiment was seen as small. However, this may be because both parties are tweeting about the issue negatively, but in different ways. From the word clouds, it can be seen that “protest” is one of the frequent words used for Democrats, which carries a sentiment of -2 according to the afinn library. Meanwhile, Republicans often use the words “Riot” and “Violence” in association with Black Lives Matter, which carry a sentiment of -2 and -3, respectively. Here, we can see that while both parties are using negative words, the connotation of protest and riot are quite different. It should also be reiterated that Rep. Marjorie Taylor Greene accounted for approximately 27% of all Republican tweets about Black Lives Matter, meaning that this word cloud may be more reflective of her view rather than the Republican Party as a whole. Nonetheless, her prominence here signifies her focus of the issue, but also the notable lack of Republican tweets, especially compared to that of number of tweets by Democrats"
},
{
"code": null,
"e": 28196,
"s": 27721,
"text": "One interesting thing to note is that “Biden” is one of the most frequently used words for all issues in Republican tweets; however, “Biden” does not appear on any of the word clouds for Democratic tweets. An interesting area for further analysis would be to determine in what context Biden’s name is being used: whether this is merely because he is the current president (thus an important taking point), or rather because they are criticizing his approach to these issues."
},
{
"code": null,
"e": 28211,
"s": 28196,
"text": "Key Take-aways"
},
{
"code": null,
"e": 28331,
"s": 28211,
"text": "From the sentiment analyses conducted and the tokenization of tweets regarding issues, a few key takeaways can be seen."
},
{
"code": null,
"e": 30491,
"s": 28331,
"text": "There is a clear difference between the ways Democrats and Republicans tweet about issues. From our select social and policy problems, the t-test and Cohen’s d test revealed that there is a clear difference between the sentiment of the two parties. Looking at the word clouds as well, it can be seen that Democrats and Republicans seldom use similar words to describe the selected issues. This signals that instead of using Twitter as a platform to promote a bipartisanship agenda, congress members are doubling down on party divides and making this public to their constituents as well.Republicans tend to tweet more negatively about issues than Democrats, even on issues where there is bipartisan support, such as infrastructure. This phenomenon could occur for several reasons, including the topics selected, the current administration being Democratic, or Twitter behavior in general. Another possibility is that this displays the partisan divide of congress, where even in terms of policy agreement, sentiment and enthusiasm is not equal.Frequent or passionate tweeters have the power to dominate a party’s sentiment and views on Twitter. As seen with Rep. Marjorie Taylor Greene, one politician can dominate an issue if they tweet about it enough. To a lesser extent, this could also be applied to Rep. Pramilia Jayapal (D-WA), who was found to be the most frequent tweeter for 3 of the 4 issues select.While Democrats lead in terms of most followed accounts, top Republicans are getting close to the same engagement. Democratic members own 20 of the 35 accounts with over 1,000,000 followers, and Rep. Alexandria Ocasio-Cortez stands out with the average likes and retweets she receives; however, accounts that received the most engagement are closer to a 50–50 split between Republicans and Democrats.To make waves, you might have to be negative. As seen in the sentiment map of all members, some of the most talked are seen to have some of the most negative sentiments of all congress members. From this analysis, it is unclear whether negativity receives more attention, or if the most well known members of congress naturally tweet more negatively."
},
{
"code": null,
"e": 31079,
"s": 30491,
"text": "There is a clear difference between the ways Democrats and Republicans tweet about issues. From our select social and policy problems, the t-test and Cohen’s d test revealed that there is a clear difference between the sentiment of the two parties. Looking at the word clouds as well, it can be seen that Democrats and Republicans seldom use similar words to describe the selected issues. This signals that instead of using Twitter as a platform to promote a bipartisanship agenda, congress members are doubling down on party divides and making this public to their constituents as well."
},
{
"code": null,
"e": 31536,
"s": 31079,
"text": "Republicans tend to tweet more negatively about issues than Democrats, even on issues where there is bipartisan support, such as infrastructure. This phenomenon could occur for several reasons, including the topics selected, the current administration being Democratic, or Twitter behavior in general. Another possibility is that this displays the partisan divide of congress, where even in terms of policy agreement, sentiment and enthusiasm is not equal."
},
{
"code": null,
"e": 31903,
"s": 31536,
"text": "Frequent or passionate tweeters have the power to dominate a party’s sentiment and views on Twitter. As seen with Rep. Marjorie Taylor Greene, one politician can dominate an issue if they tweet about it enough. To a lesser extent, this could also be applied to Rep. Pramilia Jayapal (D-WA), who was found to be the most frequent tweeter for 3 of the 4 issues select."
},
{
"code": null,
"e": 32304,
"s": 31903,
"text": "While Democrats lead in terms of most followed accounts, top Republicans are getting close to the same engagement. Democratic members own 20 of the 35 accounts with over 1,000,000 followers, and Rep. Alexandria Ocasio-Cortez stands out with the average likes and retweets she receives; however, accounts that received the most engagement are closer to a 50–50 split between Republicans and Democrats."
},
{
"code": null,
"e": 32655,
"s": 32304,
"text": "To make waves, you might have to be negative. As seen in the sentiment map of all members, some of the most talked are seen to have some of the most negative sentiments of all congress members. From this analysis, it is unclear whether negativity receives more attention, or if the most well known members of congress naturally tweet more negatively."
},
{
"code": null,
"e": 32685,
"s": 32655,
"text": "Areas for Further Examination"
},
{
"code": null,
"e": 33070,
"s": 32685,
"text": "There are several areas where a further examination is warranted. First, a wider range of issues should be examined. While the four issues were chosen due to their prevalence, with the exception of infrastructure, they are pro-Democrat issues (issues Democrats are pushing for). Issues that Republicans are pushing for should be examined to see how Democrats tweet about those issues."
},
{
"code": null,
"e": 33421,
"s": 33070,
"text": "Additionally, different ways in which the parties discuss issues could present a fascinating insight. For instance, when it comes to gun legislation, seeing how the words “regulation,” “control,” or “2nd Amendment” affect engagements (likes and retweets) and sentiment could reveal insights on how the parties present these issues to their followers."
},
{
"code": null,
"e": 33858,
"s": 33421,
"text": "Finally, using a different sentiment library may be more useful for some policy issues. As seen with Black Lives Matter, words with a negative sentiment are naturally used by both parties; however, discussing “riots” and “protests” shows a different viewpoint on the issue that cannot easily be captured in a semantic value. Using a different library or a different process may be able to capture this difference between parties better."
},
{
"code": null,
"e": 33983,
"s": 33858,
"text": "Thank you for reading. Feel free to email me with any questions at [email protected] or reach out to me on LinkedIn here."
}
] |
How to remove all special characters, punctuation and spaces from a string in Python? | To remove all special characters, punctuation and spaces from string, iterate over the string and filter out all non alpha numeric characters. For example:
>>> string = "Hello $#! People Whitespace 7331"
>>> ''.join(e for e in string if e.isalnum())
'HelloPeopleWhitespace7331'
Regular expressions can also be used to remove any non alphanumeric characters. re.sub(regex, string_to_replace_with, original_string) will substitute all non alphanumeric characters with empty string. For example,
>>> import re
>>> re.sub('[^A-Za-z0-9]+', '', "Hello $#! People Whitespace 7331")
'HelloPeopleWhitespace7331' | [
{
"code": null,
"e": 1218,
"s": 1062,
"text": "To remove all special characters, punctuation and spaces from string, iterate over the string and filter out all non alpha numeric characters. For example:"
},
{
"code": null,
"e": 1342,
"s": 1218,
"text": ">>> string = \"Hello $#! People Whitespace 7331\"\n>>> ''.join(e for e in string if e.isalnum())\n'HelloPeopleWhitespace7331'"
},
{
"code": null,
"e": 1557,
"s": 1342,
"text": "Regular expressions can also be used to remove any non alphanumeric characters. re.sub(regex, string_to_replace_with, original_string) will substitute all non alphanumeric characters with empty string. For example,"
},
{
"code": null,
"e": 1669,
"s": 1557,
"text": ">>> import re\n>>> re.sub('[^A-Za-z0-9]+', '', \"Hello $#! People Whitespace 7331\")\n'HelloPeopleWhitespace7331'"
}
] |
C# Enum ToString() Method | The ToString() method converts the value of this instance to its equivalent string representation.
Firstly, set an enum.
enum Vehicle { Car, Bus, Truck, Motobike };
To convert it to an equivalent string representation, use ToString().
Vehicle.Car.ToString("d")
Live Demo
using System;
public class Demo {
enum Vehicle { Car, Bus, Truck, Motobike };
public static void Main() {
Console.WriteLine("Vehicle.Car = {0}", Vehicle.Car.ToString("d"));
Console.WriteLine("Vehicle.Bus = {0}", Vehicle.Bus.ToString("d"));
}
}
Vehicle.Car = 0
Vehicle.Bus = 1 | [
{
"code": null,
"e": 1161,
"s": 1062,
"text": "The ToString() method converts the value of this instance to its equivalent string representation."
},
{
"code": null,
"e": 1183,
"s": 1161,
"text": "Firstly, set an enum."
},
{
"code": null,
"e": 1227,
"s": 1183,
"text": "enum Vehicle { Car, Bus, Truck, Motobike };"
},
{
"code": null,
"e": 1297,
"s": 1227,
"text": "To convert it to an equivalent string representation, use ToString()."
},
{
"code": null,
"e": 1323,
"s": 1297,
"text": "Vehicle.Car.ToString(\"d\")"
},
{
"code": null,
"e": 1334,
"s": 1323,
"text": " Live Demo"
},
{
"code": null,
"e": 1599,
"s": 1334,
"text": "using System;\npublic class Demo {\n enum Vehicle { Car, Bus, Truck, Motobike };\n public static void Main() {\n Console.WriteLine(\"Vehicle.Car = {0}\", Vehicle.Car.ToString(\"d\"));\n Console.WriteLine(\"Vehicle.Bus = {0}\", Vehicle.Bus.ToString(\"d\"));\n }\n}"
},
{
"code": null,
"e": 1631,
"s": 1599,
"text": "Vehicle.Car = 0\nVehicle.Bus = 1"
}
] |
Check if a binary string has a 0 between 1s or not | Set 2 (Regular Expression Approach) - GeeksforGeeks | 11 Dec, 2017
Given a string of 0 and 1, we need to check that the given string is valid or not. The given string is valid when there is no zero is present in between 1’s. For example, 1111, 0000111110, 1111000 are valid strings but 01010011, 01010, 101 are not.
Examples:
Input : 100
Output : VALID
Input : 1110001
Output : NOT VALID
There is 0 between 1s
Input : 00011
Output : VALID
In Set 1, we have discussed general approach for validity of string.In this post, we will discuss regular expression approach for same and it is simple.
As we know that in a string if there is zero between 1’s, than string is not valid.Hence below is one of the regular expression for invalid string pattern.
10+1
So here is the simple regex algorithm.
Loop over the matcher(string)if above regex match is find in the matcher, then string is not valid, otherwise valid.
Loop over the matcher(string)
if above regex match is find in the matcher, then string is not valid, otherwise valid.
// Java regex program to check for valid string import java.util.regex.Matcher;import java.util.regex.Pattern; class GFG { // Method to check for valid string static boolean checkString(String str) { // regular expression for invalid string String regex = "10+1"; // compiling regex Pattern p = Pattern.compile(regex); // Matcher object Matcher m = p.matcher(str); // loop over matcher while(m.find()) { // if match found, // then string is invalid return false; } // if match doesn't found // then string is valid return true; } // Driver method public static void main (String[] args) { String str = "00011111111100000"; System.out.println(checkString(str) ? "VALID" : "NOT VALID"); }}
Output:
VALID
This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
binary-string
java-regular-expression
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 50 String Coding Problems for Interviews
Naive algorithm for Pattern Searching
Vigenère Cipher
Hill Cipher
Count words in a given string
How to Append a Character to a String in C
Convert character array to string in C++
sprintf() in C
Program to count occurrence of a given character in a string
Converting Roman Numerals to Decimal lying between 1 to 3999 | [
{
"code": null,
"e": 24853,
"s": 24825,
"text": "\n11 Dec, 2017"
},
{
"code": null,
"e": 25102,
"s": 24853,
"text": "Given a string of 0 and 1, we need to check that the given string is valid or not. The given string is valid when there is no zero is present in between 1’s. For example, 1111, 0000111110, 1111000 are valid strings but 01010011, 01010, 101 are not."
},
{
"code": null,
"e": 25112,
"s": 25102,
"text": "Examples:"
},
{
"code": null,
"e": 25228,
"s": 25112,
"text": "Input : 100\nOutput : VALID\n\nInput : 1110001\nOutput : NOT VALID\nThere is 0 between 1s\n\nInput : 00011\nOutput : VALID\n"
},
{
"code": null,
"e": 25381,
"s": 25228,
"text": "In Set 1, we have discussed general approach for validity of string.In this post, we will discuss regular expression approach for same and it is simple."
},
{
"code": null,
"e": 25537,
"s": 25381,
"text": "As we know that in a string if there is zero between 1’s, than string is not valid.Hence below is one of the regular expression for invalid string pattern."
},
{
"code": null,
"e": 25543,
"s": 25537,
"text": "10+1\n"
},
{
"code": null,
"e": 25582,
"s": 25543,
"text": "So here is the simple regex algorithm."
},
{
"code": null,
"e": 25699,
"s": 25582,
"text": "Loop over the matcher(string)if above regex match is find in the matcher, then string is not valid, otherwise valid."
},
{
"code": null,
"e": 25729,
"s": 25699,
"text": "Loop over the matcher(string)"
},
{
"code": null,
"e": 25817,
"s": 25729,
"text": "if above regex match is find in the matcher, then string is not valid, otherwise valid."
},
{
"code": "// Java regex program to check for valid string import java.util.regex.Matcher;import java.util.regex.Pattern; class GFG { // Method to check for valid string static boolean checkString(String str) { // regular expression for invalid string String regex = \"10+1\"; // compiling regex Pattern p = Pattern.compile(regex); // Matcher object Matcher m = p.matcher(str); // loop over matcher while(m.find()) { // if match found, // then string is invalid return false; } // if match doesn't found // then string is valid return true; } // Driver method public static void main (String[] args) { String str = \"00011111111100000\"; System.out.println(checkString(str) ? \"VALID\" : \"NOT VALID\"); }}",
"e": 26726,
"s": 25817,
"text": null
},
{
"code": null,
"e": 26734,
"s": 26726,
"text": "Output:"
},
{
"code": null,
"e": 26741,
"s": 26734,
"text": "VALID\n"
},
{
"code": null,
"e": 27043,
"s": 26741,
"text": "This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 27168,
"s": 27043,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 27182,
"s": 27168,
"text": "binary-string"
},
{
"code": null,
"e": 27206,
"s": 27182,
"text": "java-regular-expression"
},
{
"code": null,
"e": 27214,
"s": 27206,
"text": "Strings"
},
{
"code": null,
"e": 27222,
"s": 27214,
"text": "Strings"
},
{
"code": null,
"e": 27320,
"s": 27222,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27365,
"s": 27320,
"text": "Top 50 String Coding Problems for Interviews"
},
{
"code": null,
"e": 27403,
"s": 27365,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 27420,
"s": 27403,
"text": "Vigenère Cipher"
},
{
"code": null,
"e": 27432,
"s": 27420,
"text": "Hill Cipher"
},
{
"code": null,
"e": 27462,
"s": 27432,
"text": "Count words in a given string"
},
{
"code": null,
"e": 27505,
"s": 27462,
"text": "How to Append a Character to a String in C"
},
{
"code": null,
"e": 27546,
"s": 27505,
"text": "Convert character array to string in C++"
},
{
"code": null,
"e": 27561,
"s": 27546,
"text": "sprintf() in C"
},
{
"code": null,
"e": 27622,
"s": 27561,
"text": "Program to count occurrence of a given character in a string"
}
] |
Building a Handwritten Multi-Digit Calculator | by Neerav Gala | Towards Data Science | The aim of this article is to :
Create a CNN model that can identify digits and simple mathematical operators from an image
Set up the mathematical expression and compute the answer
If incorrect, update the model with the correct answer
In order to easily follow this article, I recommend understanding the basics of the following topics first:
Machine Learning using Python
Convolutional Neural Networks (refer to this youtube video by MIT 6.S191)
Keras API
If you are familiar with these topics, then lets dive right into it!
IntroductionCreating the CNN ModelModel PredictionsCreating the CalculatorModel UpdateConclusion
Introduction
Creating the CNN Model
Model Predictions
Creating the Calculator
Model Update
Conclusion
Convolutional Neural Networks are a subclass of Deep Learning algorithms mainly used for analyzing visual imagery. High amounts of training data, increasing computational powers and advanced deep learning techniques have paved the way for CNNs to perform complex visual tasks [1].
It all started in 1958 when David H. Hubel and Torsten Wiesel performed a series of experiements to understand the structure of the visual cortex (for which the won the Nobel Prize in 1981). The authors found that some neurons had larger receptive fields and would react to complex patterns that were a combination of lower-level patterns detected by other neurons. These observations led to the idea that the higher level neurons are based on the outputs of neighboring lower-level neurons[2].
This powerful visual architecture evolved over the years until, a paper by Yann LeCun et al. in 1998, formulated the famous LeNet-5 architecture. In this paper, the concept of convolutional and pooling layers was introduced[2].
Today, many companies employ CNN for analyzing visual imagery. The following are a few examples:
Tesla for Autopilot [3]
Google Photos for Image Classification [4]
Facebook Artificial Intelligence Research (FAIR) for Language Translation [5]
The objective of this article is to show you how to build a CNN model that can do the following:
The model is build with keras API (Tensorflow backend) using Python.
From the next section onwards, I request you to first copy the section’s code into your IDE before reading the section.
The dataset used for this project can be found in here (file name is dataset.csv). It is an extension of the MNIST dataset and contains 85,709 images of Arabic numerals (0 to 9) and mathematical operators (+, - , * and /). Each image is of size 28 X 28 pixels. In order to be easily encoded, the mathematical operators are numerically labelled as follows:
10 represents “/” (division)
11 represents “+” (addition)
12 represents “-” (subtraction)
13 represents “/” (multiplication)
In the first code snippet, the downloaded datase is loaded as a Pandas dataframe of size (85709 X 785). The labels (y) are separated from the dataset (X).
785 = 1 (label) + 28 (height in pixels) * 28 (width in pixels)
To reduce the effect of illumination, the dataset is gray scale normalized by dividing the dataset by 255. Next the dataset is reshaped to fit the standards of a 4D Tensor ([mini-batch size, height = 28px, width = 28px, channels = 1 due to grayscale]).
Next, the labels are converted from class vectors (14 class vectors) to binary class matrices (necessary for train Keras models).
E.g. 2 -> [0,0,1,0,0,0,0,0,0,0,0,0,0,0]
Lastly, the data is split into training(90%) and validation(10%). The dataset is now ready to be used to train the model.
The CNN model is build using Keras’ Sequential model class. The table below shows the list of layers (and hyperparameters) passed to create the model.
Input and First Hidden layer
First, a set of two Convolutional layers (32 filters and ReLU activation function) to identify the low level image patterns (lines, edges, etc.).Next, the Max Pooling layer (pooling size of 2 X 2) simply downsamples the filters to reduce computational load, memroy usage and number of parameters.Finally, a Dropout is used as regularization method. It randomly ignore 25% of the nodes during every training iteration.
First, a set of two Convolutional layers (32 filters and ReLU activation function) to identify the low level image patterns (lines, edges, etc.).
Next, the Max Pooling layer (pooling size of 2 X 2) simply downsamples the filters to reduce computational load, memroy usage and number of parameters.
Finally, a Dropout is used as regularization method. It randomly ignore 25% of the nodes during every training iteration.
Second Hidden Layer
A set of two Convolutional layers (64 filters and ReLU activation function) to identify complex patterns that are a combination of lower-level patterns detected by the first layer.Max Pooling layer (pooling size of 2 X 2) for downsampling.Dropout for regularization.
A set of two Convolutional layers (64 filters and ReLU activation function) to identify complex patterns that are a combination of lower-level patterns detected by the first layer.
Max Pooling layer (pooling size of 2 X 2) for downsampling.
Dropout for regularization.
Fully Connected Layer and Output
First, a Flatten layer is use to convert the final feature maps into a single 1D vector (necessary for Dense layer input).Next, a fully-connected (Dense) layer that acts as an Artificial Neural Network.Dropout for regularization.Finally, another fully-connected (Dense) layers with Softmax activation as the output layer. The softmax function takes the elements of the output layer and transforms them into a net output distribution of the probability of each class. The class with the highest probability is taken as the model prediction.
First, a Flatten layer is use to convert the final feature maps into a single 1D vector (necessary for Dense layer input).
Next, a fully-connected (Dense) layer that acts as an Artificial Neural Network.
Dropout for regularization.
Finally, another fully-connected (Dense) layers with Softmax activation as the output layer. The softmax function takes the elements of the output layer and transforms them into a net output distribution of the probability of each class. The class with the highest probability is taken as the model prediction.
Once the layers are added, the training parameters (loss function, score function and optimzation function) are defined.
The loss function measures the error rate between the observed and predicted labels. For this model, categorical_crossentropy is used as th loss function.
Next, the famous RMSprop is used as the optimizer algorithm to iteratively improves various model parameters. RMSprop is also one of the fastest optimizers.
The metric function “accuracy” is used as the score function to evaluate the performance our model.
In order to make the optimizer converge faster and closest to the global minimum of the loss function, the ReduceLROnPlateau function from Keras.callbacks is used as an annealing method of the learning rate (LR).
To avoid overfitting, the dataset is expanded by artificially altering the existing dataset (zooming, shifting, etc). This process is called Data Augmentation and is executed using Keras’ ImageDataGenerator.
Finally the model is trained on the dataset with 5 epoches and a batch size of 86.
OUTPUT[]:Epoch 1/5 - 412s - loss: 0.2837 - accuracy: 0.9143 - val_loss: 0.0606 - val_accuracy: 0.9831Epoch 2/5 - 439s - loss: 0.0776 - accuracy: 0.9771 - val_loss: 0.0348 - val_accuracy: 0.9901Epoch 3/5 - 410s - loss: 0.0622 - accuracy: 0.9818 - val_loss: 0.0292 - val_accuracy: 0.9919Epoch 4/5 - 413s - loss: 0.0578 - accuracy: 0.9837 - val_loss: 0.0285 - val_accuracy: 0.9916Epoch 5/5 - 410s - loss: 0.0540 - accuracy: 0.9845 - val_loss: 0.0322 - val_accuracy: 0.9917
The model took about 35 mins to train and reached a validation accuracy of 99.17 % after the 5th epoch.
The trained model is now ready to make some predictions! The model (with its trained structure and weights) can also be saved your computer.
Note: Section 1 & 2 of the article was inspired from this Kaggle Notebook.
Now it is time to use the trained model to analyze the image of a handwritten mathematical expression. The image (file name is testing.png) used in this artciel is available in my GitHub repository.
To analyze the mathematical expression, it first needs to broken down into individual elements which can be then identified by the model.
To do that, the image file (3066 pixels * 208 pixels) is first loaded in grayscale using Pillow (PIL).
Then the image is resized to a height of 28 px (model input requirement). Keeping the same aspect ratio, the width is adjusted as well.
Next, the image is converted from PIL.Image to a Numpy array. The background is changed to black by subtracting 255 and the image is gray scale normalized by dividing by 255. The image looks something like this.
Note: Use matplotlib.pyplot.imshow to display arrays as an image
Now the image array is split into individual element arrays. This is done by searching the image array for successive non zero columns and grouping them to form one element array. These element arrays are all stored in one list. Since there are 14 elements in the mathematical expression, the size of the list is 14.
In []: len(out)Out[]: 14
In order to identify the element using the model, it is important to have the image size of 28px*28px. The height is already 28px. However, due to the splitting process, the width of each element is not exactly 28px.
Therefore, after the splitting, the width of each element is adjusted to 28 px. by adding zero value columns (filler columns) to the element arrays.
This process is repeated for all elements until all are 28px *28px.
Finally, the elements list is converted back into an array of shape (14, 28, 28, 1) to fit the model input requirements of a 4D Tensor [mini_batch_size, height, width, channels].
In []: elements_array.shapeOut[]: (14, 28, 28, 1)
Now these elements array is ready to for the model!
The elements array is passed through the model for prediction. The model returns the probabilities of all the number classes (Softmax function). The class with the highest probability is chosen.
In []: print(elements_pred)Out[]: [ 9 8 10 7 6 13 5 4 11 3 2 12 1 0]
As you can see, the model was able to predict all the elements properly!
The next step is to build the mathematical expression out of these elements and calculate it. Lets get right into it.
Once all the individual elements are identified, it is time to create the mathematical expression and calculate it.
In order to create the mathematical expression, the number classes (0 to 9) are regrouped to form the multi digit numbers. While 10, 11, 12 and 13 classes are converted to “/”, “+”, “-” and “*” operators respectively.
For example:
[1 0] → Elements of class 1 and 0 are regrouped to form the number 10
[10] → Elements of class 10 are converted to the “/” operator
Finally, the numbers and operators are joined together to form a string respresenting the mathematical expression.
In []: m_exp_str = math_expression_generator(elements_pred)In []: print(m_exp_str)Out[]: 98 / 76 * 54 + 32 - 10
The eval() method is then used on the string to calculate the answer.
In []: print(equation)Out[]: 98 / 76 * 54 + 32 - 10 = 91.63
Sometimes, due to wrong predictions like “4++4” the mathematical expressions are incorrect and hence, the eval() method will prompt a Syntax error. Hence, Error Handling method is used.
That’s it. The Multi Digit Handwritten Calculator is ready!
But wait, what to do about wrong prediction? The next section is all about that.
What makes Machine learning algorithms so powerful is its ability to learn from its mistakes. In order to do that the model needs to be retrained with correct information.
When there is a false prediction, the above code asks for the correct mathematical expression from the user. It then compares the predicted with the correct expression and identifies the elements that are wrongly predicted.
The code then trains the model from its second hidden layer till its output layer using the correct data (first hidden layer is not trained).
The updated model is saved and can be used later to make improved predictions.
The article aims to teach you the basics of how CNN models can be used to make simple tools like the calculator. In the future, these basic concepts can help you perform complex visualization analysis and build sophisticated models.
I hope you found this article helpful. If you have any questions or feedback, just leave a comment. Cheers!
Dataset can be found here
Full code can be found here.
[1] ‘Convolutional neural network’, Wikipedia. Dec. 03, 2020, Accessed: Dec. 09, 2020. [Online]. Available: https://en.wikipedia.org/w/index.php?title=Convolutional_neural_network&oldid=992073762.
[2] A. Géron, Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems. O’Reilly Media, Inc., 2019.
[3] ‘Autopilot AI’, Tesla, 2020. https://www.tesla.com/autopilotAI (accessed Dec. 09, 2020).
[4] ‘ML Practicum: Image Classification | Machine Learning Practica’, 2020. https://developers.google.com/machine-learning/practica/image-classification (accessed Dec. 09, 2020).
[5] ‘A novel approach to neural machine translation’, Facebook Engineering, May 09, 2017. https://engineering.fb.com/2017/05/09/ml-applications/a-novel-approach-to-neural-machine-translation/ (accessed Dec. 09, 2020).
[6] ‘Introduction to CNN Keras — 0.997 (top 6%)’. https://kaggle.com/yassineghouzam/introduction-to-cnn-keras-0-997-top-6 (accessed Dec. 09, 2020).
[7] M. D. Learning, ‘MIT Deep Learning 6.S191’, MIT Deep Learning 6.S191. http://introtodeeplearning.com (accessed Dec. 09, 2020). | [
{
"code": null,
"e": 204,
"s": 172,
"text": "The aim of this article is to :"
},
{
"code": null,
"e": 296,
"s": 204,
"text": "Create a CNN model that can identify digits and simple mathematical operators from an image"
},
{
"code": null,
"e": 354,
"s": 296,
"text": "Set up the mathematical expression and compute the answer"
},
{
"code": null,
"e": 409,
"s": 354,
"text": "If incorrect, update the model with the correct answer"
},
{
"code": null,
"e": 517,
"s": 409,
"text": "In order to easily follow this article, I recommend understanding the basics of the following topics first:"
},
{
"code": null,
"e": 547,
"s": 517,
"text": "Machine Learning using Python"
},
{
"code": null,
"e": 621,
"s": 547,
"text": "Convolutional Neural Networks (refer to this youtube video by MIT 6.S191)"
},
{
"code": null,
"e": 631,
"s": 621,
"text": "Keras API"
},
{
"code": null,
"e": 700,
"s": 631,
"text": "If you are familiar with these topics, then lets dive right into it!"
},
{
"code": null,
"e": 797,
"s": 700,
"text": "IntroductionCreating the CNN ModelModel PredictionsCreating the CalculatorModel UpdateConclusion"
},
{
"code": null,
"e": 810,
"s": 797,
"text": "Introduction"
},
{
"code": null,
"e": 833,
"s": 810,
"text": "Creating the CNN Model"
},
{
"code": null,
"e": 851,
"s": 833,
"text": "Model Predictions"
},
{
"code": null,
"e": 875,
"s": 851,
"text": "Creating the Calculator"
},
{
"code": null,
"e": 888,
"s": 875,
"text": "Model Update"
},
{
"code": null,
"e": 899,
"s": 888,
"text": "Conclusion"
},
{
"code": null,
"e": 1180,
"s": 899,
"text": "Convolutional Neural Networks are a subclass of Deep Learning algorithms mainly used for analyzing visual imagery. High amounts of training data, increasing computational powers and advanced deep learning techniques have paved the way for CNNs to perform complex visual tasks [1]."
},
{
"code": null,
"e": 1675,
"s": 1180,
"text": "It all started in 1958 when David H. Hubel and Torsten Wiesel performed a series of experiements to understand the structure of the visual cortex (for which the won the Nobel Prize in 1981). The authors found that some neurons had larger receptive fields and would react to complex patterns that were a combination of lower-level patterns detected by other neurons. These observations led to the idea that the higher level neurons are based on the outputs of neighboring lower-level neurons[2]."
},
{
"code": null,
"e": 1903,
"s": 1675,
"text": "This powerful visual architecture evolved over the years until, a paper by Yann LeCun et al. in 1998, formulated the famous LeNet-5 architecture. In this paper, the concept of convolutional and pooling layers was introduced[2]."
},
{
"code": null,
"e": 2000,
"s": 1903,
"text": "Today, many companies employ CNN for analyzing visual imagery. The following are a few examples:"
},
{
"code": null,
"e": 2024,
"s": 2000,
"text": "Tesla for Autopilot [3]"
},
{
"code": null,
"e": 2067,
"s": 2024,
"text": "Google Photos for Image Classification [4]"
},
{
"code": null,
"e": 2145,
"s": 2067,
"text": "Facebook Artificial Intelligence Research (FAIR) for Language Translation [5]"
},
{
"code": null,
"e": 2242,
"s": 2145,
"text": "The objective of this article is to show you how to build a CNN model that can do the following:"
},
{
"code": null,
"e": 2311,
"s": 2242,
"text": "The model is build with keras API (Tensorflow backend) using Python."
},
{
"code": null,
"e": 2431,
"s": 2311,
"text": "From the next section onwards, I request you to first copy the section’s code into your IDE before reading the section."
},
{
"code": null,
"e": 2787,
"s": 2431,
"text": "The dataset used for this project can be found in here (file name is dataset.csv). It is an extension of the MNIST dataset and contains 85,709 images of Arabic numerals (0 to 9) and mathematical operators (+, - , * and /). Each image is of size 28 X 28 pixels. In order to be easily encoded, the mathematical operators are numerically labelled as follows:"
},
{
"code": null,
"e": 2816,
"s": 2787,
"text": "10 represents “/” (division)"
},
{
"code": null,
"e": 2845,
"s": 2816,
"text": "11 represents “+” (addition)"
},
{
"code": null,
"e": 2877,
"s": 2845,
"text": "12 represents “-” (subtraction)"
},
{
"code": null,
"e": 2912,
"s": 2877,
"text": "13 represents “/” (multiplication)"
},
{
"code": null,
"e": 3067,
"s": 2912,
"text": "In the first code snippet, the downloaded datase is loaded as a Pandas dataframe of size (85709 X 785). The labels (y) are separated from the dataset (X)."
},
{
"code": null,
"e": 3130,
"s": 3067,
"text": "785 = 1 (label) + 28 (height in pixels) * 28 (width in pixels)"
},
{
"code": null,
"e": 3383,
"s": 3130,
"text": "To reduce the effect of illumination, the dataset is gray scale normalized by dividing the dataset by 255. Next the dataset is reshaped to fit the standards of a 4D Tensor ([mini-batch size, height = 28px, width = 28px, channels = 1 due to grayscale])."
},
{
"code": null,
"e": 3513,
"s": 3383,
"text": "Next, the labels are converted from class vectors (14 class vectors) to binary class matrices (necessary for train Keras models)."
},
{
"code": null,
"e": 3553,
"s": 3513,
"text": "E.g. 2 -> [0,0,1,0,0,0,0,0,0,0,0,0,0,0]"
},
{
"code": null,
"e": 3675,
"s": 3553,
"text": "Lastly, the data is split into training(90%) and validation(10%). The dataset is now ready to be used to train the model."
},
{
"code": null,
"e": 3826,
"s": 3675,
"text": "The CNN model is build using Keras’ Sequential model class. The table below shows the list of layers (and hyperparameters) passed to create the model."
},
{
"code": null,
"e": 3855,
"s": 3826,
"text": "Input and First Hidden layer"
},
{
"code": null,
"e": 4273,
"s": 3855,
"text": "First, a set of two Convolutional layers (32 filters and ReLU activation function) to identify the low level image patterns (lines, edges, etc.).Next, the Max Pooling layer (pooling size of 2 X 2) simply downsamples the filters to reduce computational load, memroy usage and number of parameters.Finally, a Dropout is used as regularization method. It randomly ignore 25% of the nodes during every training iteration."
},
{
"code": null,
"e": 4419,
"s": 4273,
"text": "First, a set of two Convolutional layers (32 filters and ReLU activation function) to identify the low level image patterns (lines, edges, etc.)."
},
{
"code": null,
"e": 4571,
"s": 4419,
"text": "Next, the Max Pooling layer (pooling size of 2 X 2) simply downsamples the filters to reduce computational load, memroy usage and number of parameters."
},
{
"code": null,
"e": 4693,
"s": 4571,
"text": "Finally, a Dropout is used as regularization method. It randomly ignore 25% of the nodes during every training iteration."
},
{
"code": null,
"e": 4713,
"s": 4693,
"text": "Second Hidden Layer"
},
{
"code": null,
"e": 4980,
"s": 4713,
"text": "A set of two Convolutional layers (64 filters and ReLU activation function) to identify complex patterns that are a combination of lower-level patterns detected by the first layer.Max Pooling layer (pooling size of 2 X 2) for downsampling.Dropout for regularization."
},
{
"code": null,
"e": 5161,
"s": 4980,
"text": "A set of two Convolutional layers (64 filters and ReLU activation function) to identify complex patterns that are a combination of lower-level patterns detected by the first layer."
},
{
"code": null,
"e": 5221,
"s": 5161,
"text": "Max Pooling layer (pooling size of 2 X 2) for downsampling."
},
{
"code": null,
"e": 5249,
"s": 5221,
"text": "Dropout for regularization."
},
{
"code": null,
"e": 5282,
"s": 5249,
"text": "Fully Connected Layer and Output"
},
{
"code": null,
"e": 5822,
"s": 5282,
"text": "First, a Flatten layer is use to convert the final feature maps into a single 1D vector (necessary for Dense layer input).Next, a fully-connected (Dense) layer that acts as an Artificial Neural Network.Dropout for regularization.Finally, another fully-connected (Dense) layers with Softmax activation as the output layer. The softmax function takes the elements of the output layer and transforms them into a net output distribution of the probability of each class. The class with the highest probability is taken as the model prediction."
},
{
"code": null,
"e": 5945,
"s": 5822,
"text": "First, a Flatten layer is use to convert the final feature maps into a single 1D vector (necessary for Dense layer input)."
},
{
"code": null,
"e": 6026,
"s": 5945,
"text": "Next, a fully-connected (Dense) layer that acts as an Artificial Neural Network."
},
{
"code": null,
"e": 6054,
"s": 6026,
"text": "Dropout for regularization."
},
{
"code": null,
"e": 6365,
"s": 6054,
"text": "Finally, another fully-connected (Dense) layers with Softmax activation as the output layer. The softmax function takes the elements of the output layer and transforms them into a net output distribution of the probability of each class. The class with the highest probability is taken as the model prediction."
},
{
"code": null,
"e": 6486,
"s": 6365,
"text": "Once the layers are added, the training parameters (loss function, score function and optimzation function) are defined."
},
{
"code": null,
"e": 6641,
"s": 6486,
"text": "The loss function measures the error rate between the observed and predicted labels. For this model, categorical_crossentropy is used as th loss function."
},
{
"code": null,
"e": 6798,
"s": 6641,
"text": "Next, the famous RMSprop is used as the optimizer algorithm to iteratively improves various model parameters. RMSprop is also one of the fastest optimizers."
},
{
"code": null,
"e": 6898,
"s": 6798,
"text": "The metric function “accuracy” is used as the score function to evaluate the performance our model."
},
{
"code": null,
"e": 7111,
"s": 6898,
"text": "In order to make the optimizer converge faster and closest to the global minimum of the loss function, the ReduceLROnPlateau function from Keras.callbacks is used as an annealing method of the learning rate (LR)."
},
{
"code": null,
"e": 7319,
"s": 7111,
"text": "To avoid overfitting, the dataset is expanded by artificially altering the existing dataset (zooming, shifting, etc). This process is called Data Augmentation and is executed using Keras’ ImageDataGenerator."
},
{
"code": null,
"e": 7402,
"s": 7319,
"text": "Finally the model is trained on the dataset with 5 epoches and a batch size of 86."
},
{
"code": null,
"e": 7872,
"s": 7402,
"text": "OUTPUT[]:Epoch 1/5 - 412s - loss: 0.2837 - accuracy: 0.9143 - val_loss: 0.0606 - val_accuracy: 0.9831Epoch 2/5 - 439s - loss: 0.0776 - accuracy: 0.9771 - val_loss: 0.0348 - val_accuracy: 0.9901Epoch 3/5 - 410s - loss: 0.0622 - accuracy: 0.9818 - val_loss: 0.0292 - val_accuracy: 0.9919Epoch 4/5 - 413s - loss: 0.0578 - accuracy: 0.9837 - val_loss: 0.0285 - val_accuracy: 0.9916Epoch 5/5 - 410s - loss: 0.0540 - accuracy: 0.9845 - val_loss: 0.0322 - val_accuracy: 0.9917"
},
{
"code": null,
"e": 7976,
"s": 7872,
"text": "The model took about 35 mins to train and reached a validation accuracy of 99.17 % after the 5th epoch."
},
{
"code": null,
"e": 8117,
"s": 7976,
"text": "The trained model is now ready to make some predictions! The model (with its trained structure and weights) can also be saved your computer."
},
{
"code": null,
"e": 8192,
"s": 8117,
"text": "Note: Section 1 & 2 of the article was inspired from this Kaggle Notebook."
},
{
"code": null,
"e": 8391,
"s": 8192,
"text": "Now it is time to use the trained model to analyze the image of a handwritten mathematical expression. The image (file name is testing.png) used in this artciel is available in my GitHub repository."
},
{
"code": null,
"e": 8529,
"s": 8391,
"text": "To analyze the mathematical expression, it first needs to broken down into individual elements which can be then identified by the model."
},
{
"code": null,
"e": 8632,
"s": 8529,
"text": "To do that, the image file (3066 pixels * 208 pixels) is first loaded in grayscale using Pillow (PIL)."
},
{
"code": null,
"e": 8768,
"s": 8632,
"text": "Then the image is resized to a height of 28 px (model input requirement). Keeping the same aspect ratio, the width is adjusted as well."
},
{
"code": null,
"e": 8980,
"s": 8768,
"text": "Next, the image is converted from PIL.Image to a Numpy array. The background is changed to black by subtracting 255 and the image is gray scale normalized by dividing by 255. The image looks something like this."
},
{
"code": null,
"e": 9045,
"s": 8980,
"text": "Note: Use matplotlib.pyplot.imshow to display arrays as an image"
},
{
"code": null,
"e": 9362,
"s": 9045,
"text": "Now the image array is split into individual element arrays. This is done by searching the image array for successive non zero columns and grouping them to form one element array. These element arrays are all stored in one list. Since there are 14 elements in the mathematical expression, the size of the list is 14."
},
{
"code": null,
"e": 9387,
"s": 9362,
"text": "In []: len(out)Out[]: 14"
},
{
"code": null,
"e": 9604,
"s": 9387,
"text": "In order to identify the element using the model, it is important to have the image size of 28px*28px. The height is already 28px. However, due to the splitting process, the width of each element is not exactly 28px."
},
{
"code": null,
"e": 9753,
"s": 9604,
"text": "Therefore, after the splitting, the width of each element is adjusted to 28 px. by adding zero value columns (filler columns) to the element arrays."
},
{
"code": null,
"e": 9821,
"s": 9753,
"text": "This process is repeated for all elements until all are 28px *28px."
},
{
"code": null,
"e": 10000,
"s": 9821,
"text": "Finally, the elements list is converted back into an array of shape (14, 28, 28, 1) to fit the model input requirements of a 4D Tensor [mini_batch_size, height, width, channels]."
},
{
"code": null,
"e": 10050,
"s": 10000,
"text": "In []: elements_array.shapeOut[]: (14, 28, 28, 1)"
},
{
"code": null,
"e": 10102,
"s": 10050,
"text": "Now these elements array is ready to for the model!"
},
{
"code": null,
"e": 10297,
"s": 10102,
"text": "The elements array is passed through the model for prediction. The model returns the probabilities of all the number classes (Softmax function). The class with the highest probability is chosen."
},
{
"code": null,
"e": 10375,
"s": 10297,
"text": "In []: print(elements_pred)Out[]: [ 9 8 10 7 6 13 5 4 11 3 2 12 1 0]"
},
{
"code": null,
"e": 10448,
"s": 10375,
"text": "As you can see, the model was able to predict all the elements properly!"
},
{
"code": null,
"e": 10566,
"s": 10448,
"text": "The next step is to build the mathematical expression out of these elements and calculate it. Lets get right into it."
},
{
"code": null,
"e": 10682,
"s": 10566,
"text": "Once all the individual elements are identified, it is time to create the mathematical expression and calculate it."
},
{
"code": null,
"e": 10900,
"s": 10682,
"text": "In order to create the mathematical expression, the number classes (0 to 9) are regrouped to form the multi digit numbers. While 10, 11, 12 and 13 classes are converted to “/”, “+”, “-” and “*” operators respectively."
},
{
"code": null,
"e": 10913,
"s": 10900,
"text": "For example:"
},
{
"code": null,
"e": 10983,
"s": 10913,
"text": "[1 0] → Elements of class 1 and 0 are regrouped to form the number 10"
},
{
"code": null,
"e": 11045,
"s": 10983,
"text": "[10] → Elements of class 10 are converted to the “/” operator"
},
{
"code": null,
"e": 11160,
"s": 11045,
"text": "Finally, the numbers and operators are joined together to form a string respresenting the mathematical expression."
},
{
"code": null,
"e": 11272,
"s": 11160,
"text": "In []: m_exp_str = math_expression_generator(elements_pred)In []: print(m_exp_str)Out[]: 98 / 76 * 54 + 32 - 10"
},
{
"code": null,
"e": 11342,
"s": 11272,
"text": "The eval() method is then used on the string to calculate the answer."
},
{
"code": null,
"e": 11402,
"s": 11342,
"text": "In []: print(equation)Out[]: 98 / 76 * 54 + 32 - 10 = 91.63"
},
{
"code": null,
"e": 11588,
"s": 11402,
"text": "Sometimes, due to wrong predictions like “4++4” the mathematical expressions are incorrect and hence, the eval() method will prompt a Syntax error. Hence, Error Handling method is used."
},
{
"code": null,
"e": 11648,
"s": 11588,
"text": "That’s it. The Multi Digit Handwritten Calculator is ready!"
},
{
"code": null,
"e": 11729,
"s": 11648,
"text": "But wait, what to do about wrong prediction? The next section is all about that."
},
{
"code": null,
"e": 11901,
"s": 11729,
"text": "What makes Machine learning algorithms so powerful is its ability to learn from its mistakes. In order to do that the model needs to be retrained with correct information."
},
{
"code": null,
"e": 12125,
"s": 11901,
"text": "When there is a false prediction, the above code asks for the correct mathematical expression from the user. It then compares the predicted with the correct expression and identifies the elements that are wrongly predicted."
},
{
"code": null,
"e": 12267,
"s": 12125,
"text": "The code then trains the model from its second hidden layer till its output layer using the correct data (first hidden layer is not trained)."
},
{
"code": null,
"e": 12346,
"s": 12267,
"text": "The updated model is saved and can be used later to make improved predictions."
},
{
"code": null,
"e": 12579,
"s": 12346,
"text": "The article aims to teach you the basics of how CNN models can be used to make simple tools like the calculator. In the future, these basic concepts can help you perform complex visualization analysis and build sophisticated models."
},
{
"code": null,
"e": 12687,
"s": 12579,
"text": "I hope you found this article helpful. If you have any questions or feedback, just leave a comment. Cheers!"
},
{
"code": null,
"e": 12713,
"s": 12687,
"text": "Dataset can be found here"
},
{
"code": null,
"e": 12742,
"s": 12713,
"text": "Full code can be found here."
},
{
"code": null,
"e": 12939,
"s": 12742,
"text": "[1] ‘Convolutional neural network’, Wikipedia. Dec. 03, 2020, Accessed: Dec. 09, 2020. [Online]. Available: https://en.wikipedia.org/w/index.php?title=Convolutional_neural_network&oldid=992073762."
},
{
"code": null,
"e": 13112,
"s": 12939,
"text": "[2] A. Géron, Hands-On Machine Learning with Scikit-Learn, Keras, and TensorFlow: Concepts, Tools, and Techniques to Build Intelligent Systems. O’Reilly Media, Inc., 2019."
},
{
"code": null,
"e": 13205,
"s": 13112,
"text": "[3] ‘Autopilot AI’, Tesla, 2020. https://www.tesla.com/autopilotAI (accessed Dec. 09, 2020)."
},
{
"code": null,
"e": 13384,
"s": 13205,
"text": "[4] ‘ML Practicum: Image Classification | Machine Learning Practica’, 2020. https://developers.google.com/machine-learning/practica/image-classification (accessed Dec. 09, 2020)."
},
{
"code": null,
"e": 13602,
"s": 13384,
"text": "[5] ‘A novel approach to neural machine translation’, Facebook Engineering, May 09, 2017. https://engineering.fb.com/2017/05/09/ml-applications/a-novel-approach-to-neural-machine-translation/ (accessed Dec. 09, 2020)."
},
{
"code": null,
"e": 13750,
"s": 13602,
"text": "[6] ‘Introduction to CNN Keras — 0.997 (top 6%)’. https://kaggle.com/yassineghouzam/introduction-to-cnn-keras-0-997-top-6 (accessed Dec. 09, 2020)."
}
] |
asctime() function in C++ - GeeksforGeeks | 24 Sep, 2021
The asctime() function is defined in the ctime header file. The asctime() function converts the given calendar time of structure tm to a character representation i.e human readable form.
Syntax:
char* asctime(const struct tm * time_ptr);
Parameter: This function accepts single parameter time_ptr i.e pointer to the tm object to be converted.
Return Value: This function returns the calendar time in the form “Www Mmm dd hh:mm:ss yyyy”
Below program illustrate the asctime() function in C++:
Example:-
C++
// c++ program to demonstrate// example of asctime() function. #include <bits/stdc++.h>using namespace std; int main(){ time_t time_ptr; time(&time_ptr); cout << "Current date and time = " << asctime(localtime(&time_ptr)); return 0;}
Current date and time = Mon Oct 1 10:21:26 2018
khushboogoyal499
CPP-Functions
CPP-Library
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Operator Overloading in C++
Socket Programming in C/C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
Copy Constructor in C++
rand() and srand() in C/C++
Polymorphism in C++
unordered_map in C++ STL
Left Shift and Right Shift Operators in C/C++
Friend class and function in C++ | [
{
"code": null,
"e": 24128,
"s": 24100,
"text": "\n24 Sep, 2021"
},
{
"code": null,
"e": 24315,
"s": 24128,
"text": "The asctime() function is defined in the ctime header file. The asctime() function converts the given calendar time of structure tm to a character representation i.e human readable form."
},
{
"code": null,
"e": 24324,
"s": 24315,
"text": "Syntax: "
},
{
"code": null,
"e": 24367,
"s": 24324,
"text": "char* asctime(const struct tm * time_ptr);"
},
{
"code": null,
"e": 24472,
"s": 24367,
"text": "Parameter: This function accepts single parameter time_ptr i.e pointer to the tm object to be converted."
},
{
"code": null,
"e": 24565,
"s": 24472,
"text": "Return Value: This function returns the calendar time in the form “Www Mmm dd hh:mm:ss yyyy”"
},
{
"code": null,
"e": 24621,
"s": 24565,
"text": "Below program illustrate the asctime() function in C++:"
},
{
"code": null,
"e": 24632,
"s": 24621,
"text": "Example:- "
},
{
"code": null,
"e": 24636,
"s": 24632,
"text": "C++"
},
{
"code": "// c++ program to demonstrate// example of asctime() function. #include <bits/stdc++.h>using namespace std; int main(){ time_t time_ptr; time(&time_ptr); cout << \"Current date and time = \" << asctime(localtime(&time_ptr)); return 0;}",
"e": 24893,
"s": 24636,
"text": null
},
{
"code": null,
"e": 24942,
"s": 24893,
"text": "Current date and time = Mon Oct 1 10:21:26 2018"
},
{
"code": null,
"e": 24961,
"s": 24944,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 24975,
"s": 24961,
"text": "CPP-Functions"
},
{
"code": null,
"e": 24987,
"s": 24975,
"text": "CPP-Library"
},
{
"code": null,
"e": 24991,
"s": 24987,
"text": "C++"
},
{
"code": null,
"e": 24995,
"s": 24991,
"text": "CPP"
},
{
"code": null,
"e": 25093,
"s": 24995,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25121,
"s": 25093,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 25149,
"s": 25121,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 25184,
"s": 25149,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 25215,
"s": 25184,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 25239,
"s": 25215,
"text": "Copy Constructor in C++"
},
{
"code": null,
"e": 25267,
"s": 25239,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 25287,
"s": 25267,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 25312,
"s": 25287,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 25358,
"s": 25312,
"text": "Left Shift and Right Shift Operators in C/C++"
}
] |
Base Plotting in R. Using the base plotting system in R can... | by Jesse Libra | Towards Data Science | Base plotting in R can be intimidating. It takes a canvas approach to plot construction, allowing you to paint layer after layer of detail onto your graphics. As a result, there is a seemingly endless number of functions and attributes to learn, but there’s no need to panic or jump straight to ggplot. This article highlights the versatility of the base plot() function while giving you some quick tricks to create beautiful plots.
Throughout this article, I use Edgar Anderson’s Iris dataset, so you can copy the code and see it in action. We will use this dataset to create and compare four graphs:
The most basic plot you can create in R, an XY scatterplotA plot using color to subset a scatterplot of the iris dataset by speciesA plot with customized fonts, colors, and sizes, andA plot with a background-color and grid.
The most basic plot you can create in R, an XY scatterplot
A plot using color to subset a scatterplot of the iris dataset by species
A plot with customized fonts, colors, and sizes, and
A plot with a background-color and grid.
To load the dataset package and learn a little bit about the Iris dataset, enter the following code in your RStudio console:
library(datasets)help(iris)
Above, I used base R plotting to graph petal width vs. petal length. The graph on the left is the most basic graph you can create in R: a scatter plot with an x and y variable.
The graph on the right communicates more information, subsetting the data by species using color. It also looks a little nicer, with axis labels, a title, color, and a legend. Color is applied based on the iris species using ifelse(). It only takes a couple of seconds longer to write code for this level of detail, and adds information and clarity.
You can recreate both of these graphs in R using this code:
##par lets us set global parameters for our graphs.par(mfrow = c(1,2), mar = c(5,5,4,1))##Simple plot (left)plot (iris$Petal.Length,iris$Petal.Width)##Plot showing species subsets (right)plot(iris$Petal.Length, iris$Petal.Width, xlab = "Petal Length", ylab = "Petal Width", main = "Petal Width vs Petal Length", pch = 20, col=ifelse(iris$Species == "setosa","coral1", ifelse(iris$Species == "virginica","cyan4", ifelse(iris$Species == "versicolor", "darkgoldenrod2", "grey"))))##legendlegend("bottomright", c("setosa","virginica", "versicolor"), col = c("coral1","cyan4", "darkgoldenrod2"), pch=20)
The code for the species subsets can be divided into three sections:
ParametersPlot attributesThe legend
Parameters
Plot attributes
The legend
The parameter section fixes the settings for all your plots. Here we haven’t added many arguments. We have mfrow which is specifying that we have one row and two columns of plots — that is, two plots side by side. The mar attribute is a vector of our margin widths, with the first value indicating the margin below the plot (5), the second indicating the margin to the left of the plot(5), the third, the top of the plot(4), and the fourth to the left (1).
par(mfrow = c(1,2), mar = c(5,5,4,1))
The second section is the meat of the plot. You can see that by just adding five arguments to our plot() function we have improved the look and usefulness of our graph. These arguments are:
xlab: specifies the x-axis label of the plot
ylab: specifies the y-axis label
main: titles your graph
pch: specifies the symbology of your graph
col: specifies the colors for your graph.
##Plot with some customizationplot(iris$Petal.Length, iris$Petal.Width, xlab = "Petal Length", ylab = "Petal Width", main = "Petal Width vs. Petal Length", pch = 20, col=ifelse(iris$Species == "setosa","coral1", ifelse(iris$Species == "virginica","cyan4", ifelse(iris$Species == "versicolor", "darkgoldenrod2", "grey"))))
The argument that will make the biggest difference to the look of your graph is col. When you’re starting out, I recommend memorizing the names of three to four colors that look good together from the cheat sheet at the end of this article.
legend("bottomright", c("setosa","virginica", "versicolor"), col = c("coral1","cyan4", "darkgoldenrod2"), pch= c(20))
The legend function allows users to define its location, the strings that appear as labels, and the symbols that appear next to each. Creating legends like this is a double-edged sword: the fact that it is not automatic gives you a huge amount of control over how your legend looks, but it is also easy to mislabel your symbols, so ojo.
This level of customization could be necessary if you are creating graphics for general circulation or for an organization that has strict branding guidelines. The code looks a lot longer because I included a second graph of Sepal Length to show the application of the global parameters, but the code essentially has the same three sections: the parameters, the plot, and the legend. You can see that I didn’t make any major changes with respect to the plots, I just added attributes to customize the colors, fonts, and font sizes of my graph.
One important change between these graphs and the ones in the first section is in the par() function at the beginning. Adding attributes to specify the font, font size, and color here creates ‘global’ settings for your plot, allowing all your following graphs to shed that crunchy 1980’s R look. The attributes I’ve added are:
font: font in the par() expression changes the font for items outside of the plot function. In this case, it is applying to the legend but it will also apply to any margin text you may have.
font.axis: the font of the axis value labels.
fg: the color of the foreground, meaning text and graph outlines.
col.axis: the color of the axis ticks and text.
cex.axis: the size of the axis ticks and text, relative to the default value of 1.
I also added a few similar attributes to the plot section of the code:
font.lab: specifies the font of your labels
col.lab: specifies the color of your labels
font.main: specifies the font of your main title
col.main: specifies the color of your main title
These attributes are specified exactly how their parent attributes (col and font) are specified. Easy, right?
I didn’t make any changes to the legend; the par() function did that for me.
##global settingspar(mfrow = c(1,2), mar = c(5,5,4,1),font = 7,font.axis = 7, fg = "azure4", col.axis = "azure4", cex.axis = .75)## First plot plot(iris$Petal.Length, iris$Petal.Width, xlab = "Petal Length", ylab = "Petal Width", font.lab = 7, col.lab = "azure4", main = "Petal Width vs Petal Length", font.main = 7, col.main = "black", pch = 20, col=ifelse(iris$Species == "setosa","coral1", ifelse(iris$Species == "virginica","cyan4", ifelse(iris$Species == "versicolor", "darkgoldenrod2", "grey")))) ##legend legend("bottomright", c("setosa","virginica", "versicolor"), col = c("coral1","cyan4", "darkgoldenrod2"), pch=20)##Second plot plot(iris$Sepal.Length, iris$Sepal.Width, xlab = "Sepal Length", ylab = "Sepal Width", font.lab = 7, col.lab = "azure4", main = "Sepal Width vs Sepal Length", font.main=7, col.main = "black", pch = 17, col=ifelse(iris$Species == "setosa","coral1", ifelse(iris$Species == "virginica","cyan4", ifelse(iris$Species == "versicolor", "darkgoldenrod2", "grey")))) ##legend legend("bottomright", c("setosa","virginica", "versicolor"), col = c("coral1","cyan4", "darkgoldenrod2"), pch=17)
Backgrounds for your charts are tricky using base plotting in R. The par() function has a background attribute, bg, but it colors the whole area of your chart the background color. For example:
par(mfrow = c(1,1), mar = c(5,5,4,1),bg = "grey") plot(iris$Petal.Length, iris$Petal.Width)
Not what we want.
In base R there is no easy way of just coloring in the background of your plot. You can use the rect function to draw a rectangle that aligns with your axis, or you can use abline. The abline function is very versatile, and using it to create a background for our graph forces us to create our plot a little differently.
We’ll build off of the work in the previous sections, adding a colored background with gridlines to our plot of petal width vs. petal length.
##global parameterspar(mfrow = c(1,1), mar = c(5,5,4,1),font = 7,font.axis = 7, fg = "azure4", col.axis = "azure4", cex.axis = .75) ##Create the empty plotplot(NULL, ylim=c(0,2.5),xlim=c(0,7), xlab = "Petal Length", ylab = "Petal Width", font.lab = 7, main = "Petal Width vs. Petal Length", font.main = 7, col.main = "black",)##Add the background colorabline(v = 0:7, col = "aliceblue", lwd = 200)abline(v = 0:7, col = "white")abline(h=0:2.5, col = "white")##Add the data pointspoints(iris$Petal.Length, iris$Petal.Width, pch = 20, cex = 1.5, col=ifelse(iris$Species == "setosa","coral1", ifelse(iris$Species == "virginica","cyan4", ifelse(iris$Species == "versicolor", "darkgoldenrod2", "grey"))))##legendlegend("bottomright", c("setosa","virginica", "versicolor"), col = c("coral1","cyan4", "darkgoldenrod2"), pch=20)
If you look at the code for this graph, you can see that it approaches plot creation a bit differently. First, it sets up an empty plot and then draws on layers of information, starting with the background color, then the data points, then the legend. The background color is created using thick ab-lines for the solid color and thin white ones for the grid:
##Add the background colorabline(v = 0:7, col = "aliceblue", lwd = 200)abline(v = 0:7, col = "white")abline(h=0:2.5, col = "white")
You can see that we’ve moved our point attributes, (the dataset, pch, and col) to the points() function, but we haven’t changed them. I did add the attribute cex to increase the size of the points.
Graphs are one of the most effective ways of communicating analysis results to any audience. Additions as simple as proper labels, subsetting data by colors or symbols, and font adjustments add both information and clarity, yet consistently we see graphics coming out of R that look like they were created thirty years ago. After putting time into cleaning, summarizing, and analyzing your data, it makes sense to spend a minute on your plots.
Below are some nice cheat sheets to help you with your customizations.
There are many ways to approach fonts in R, but here is a basic cheat sheet for the numerical values associated with different fonts using font = x.
All the code used for this article can be found here. | [
{
"code": null,
"e": 605,
"s": 172,
"text": "Base plotting in R can be intimidating. It takes a canvas approach to plot construction, allowing you to paint layer after layer of detail onto your graphics. As a result, there is a seemingly endless number of functions and attributes to learn, but there’s no need to panic or jump straight to ggplot. This article highlights the versatility of the base plot() function while giving you some quick tricks to create beautiful plots."
},
{
"code": null,
"e": 774,
"s": 605,
"text": "Throughout this article, I use Edgar Anderson’s Iris dataset, so you can copy the code and see it in action. We will use this dataset to create and compare four graphs:"
},
{
"code": null,
"e": 998,
"s": 774,
"text": "The most basic plot you can create in R, an XY scatterplotA plot using color to subset a scatterplot of the iris dataset by speciesA plot with customized fonts, colors, and sizes, andA plot with a background-color and grid."
},
{
"code": null,
"e": 1057,
"s": 998,
"text": "The most basic plot you can create in R, an XY scatterplot"
},
{
"code": null,
"e": 1131,
"s": 1057,
"text": "A plot using color to subset a scatterplot of the iris dataset by species"
},
{
"code": null,
"e": 1184,
"s": 1131,
"text": "A plot with customized fonts, colors, and sizes, and"
},
{
"code": null,
"e": 1225,
"s": 1184,
"text": "A plot with a background-color and grid."
},
{
"code": null,
"e": 1350,
"s": 1225,
"text": "To load the dataset package and learn a little bit about the Iris dataset, enter the following code in your RStudio console:"
},
{
"code": null,
"e": 1378,
"s": 1350,
"text": "library(datasets)help(iris)"
},
{
"code": null,
"e": 1555,
"s": 1378,
"text": "Above, I used base R plotting to graph petal width vs. petal length. The graph on the left is the most basic graph you can create in R: a scatter plot with an x and y variable."
},
{
"code": null,
"e": 1905,
"s": 1555,
"text": "The graph on the right communicates more information, subsetting the data by species using color. It also looks a little nicer, with axis labels, a title, color, and a legend. Color is applied based on the iris species using ifelse(). It only takes a couple of seconds longer to write code for this level of detail, and adds information and clarity."
},
{
"code": null,
"e": 1965,
"s": 1905,
"text": "You can recreate both of these graphs in R using this code:"
},
{
"code": null,
"e": 2660,
"s": 1965,
"text": "##par lets us set global parameters for our graphs.par(mfrow = c(1,2), mar = c(5,5,4,1))##Simple plot (left)plot (iris$Petal.Length,iris$Petal.Width)##Plot showing species subsets (right)plot(iris$Petal.Length, iris$Petal.Width, xlab = \"Petal Length\", ylab = \"Petal Width\", main = \"Petal Width vs Petal Length\", pch = 20, col=ifelse(iris$Species == \"setosa\",\"coral1\", ifelse(iris$Species == \"virginica\",\"cyan4\", ifelse(iris$Species == \"versicolor\", \"darkgoldenrod2\", \"grey\"))))##legendlegend(\"bottomright\", c(\"setosa\",\"virginica\", \"versicolor\"), col = c(\"coral1\",\"cyan4\", \"darkgoldenrod2\"), pch=20)"
},
{
"code": null,
"e": 2729,
"s": 2660,
"text": "The code for the species subsets can be divided into three sections:"
},
{
"code": null,
"e": 2765,
"s": 2729,
"text": "ParametersPlot attributesThe legend"
},
{
"code": null,
"e": 2776,
"s": 2765,
"text": "Parameters"
},
{
"code": null,
"e": 2792,
"s": 2776,
"text": "Plot attributes"
},
{
"code": null,
"e": 2803,
"s": 2792,
"text": "The legend"
},
{
"code": null,
"e": 3260,
"s": 2803,
"text": "The parameter section fixes the settings for all your plots. Here we haven’t added many arguments. We have mfrow which is specifying that we have one row and two columns of plots — that is, two plots side by side. The mar attribute is a vector of our margin widths, with the first value indicating the margin below the plot (5), the second indicating the margin to the left of the plot(5), the third, the top of the plot(4), and the fourth to the left (1)."
},
{
"code": null,
"e": 3298,
"s": 3260,
"text": "par(mfrow = c(1,2), mar = c(5,5,4,1))"
},
{
"code": null,
"e": 3488,
"s": 3298,
"text": "The second section is the meat of the plot. You can see that by just adding five arguments to our plot() function we have improved the look and usefulness of our graph. These arguments are:"
},
{
"code": null,
"e": 3533,
"s": 3488,
"text": "xlab: specifies the x-axis label of the plot"
},
{
"code": null,
"e": 3566,
"s": 3533,
"text": "ylab: specifies the y-axis label"
},
{
"code": null,
"e": 3590,
"s": 3566,
"text": "main: titles your graph"
},
{
"code": null,
"e": 3633,
"s": 3590,
"text": "pch: specifies the symbology of your graph"
},
{
"code": null,
"e": 3675,
"s": 3633,
"text": "col: specifies the colors for your graph."
},
{
"code": null,
"e": 4087,
"s": 3675,
"text": "##Plot with some customizationplot(iris$Petal.Length, iris$Petal.Width, xlab = \"Petal Length\", ylab = \"Petal Width\", main = \"Petal Width vs. Petal Length\", pch = 20, col=ifelse(iris$Species == \"setosa\",\"coral1\", ifelse(iris$Species == \"virginica\",\"cyan4\", ifelse(iris$Species == \"versicolor\", \"darkgoldenrod2\", \"grey\"))))"
},
{
"code": null,
"e": 4328,
"s": 4087,
"text": "The argument that will make the biggest difference to the look of your graph is col. When you’re starting out, I recommend memorizing the names of three to four colors that look good together from the cheat sheet at the end of this article."
},
{
"code": null,
"e": 4452,
"s": 4328,
"text": "legend(\"bottomright\", c(\"setosa\",\"virginica\", \"versicolor\"), col = c(\"coral1\",\"cyan4\", \"darkgoldenrod2\"), pch= c(20))"
},
{
"code": null,
"e": 4789,
"s": 4452,
"text": "The legend function allows users to define its location, the strings that appear as labels, and the symbols that appear next to each. Creating legends like this is a double-edged sword: the fact that it is not automatic gives you a huge amount of control over how your legend looks, but it is also easy to mislabel your symbols, so ojo."
},
{
"code": null,
"e": 5333,
"s": 4789,
"text": "This level of customization could be necessary if you are creating graphics for general circulation or for an organization that has strict branding guidelines. The code looks a lot longer because I included a second graph of Sepal Length to show the application of the global parameters, but the code essentially has the same three sections: the parameters, the plot, and the legend. You can see that I didn’t make any major changes with respect to the plots, I just added attributes to customize the colors, fonts, and font sizes of my graph."
},
{
"code": null,
"e": 5660,
"s": 5333,
"text": "One important change between these graphs and the ones in the first section is in the par() function at the beginning. Adding attributes to specify the font, font size, and color here creates ‘global’ settings for your plot, allowing all your following graphs to shed that crunchy 1980’s R look. The attributes I’ve added are:"
},
{
"code": null,
"e": 5851,
"s": 5660,
"text": "font: font in the par() expression changes the font for items outside of the plot function. In this case, it is applying to the legend but it will also apply to any margin text you may have."
},
{
"code": null,
"e": 5897,
"s": 5851,
"text": "font.axis: the font of the axis value labels."
},
{
"code": null,
"e": 5963,
"s": 5897,
"text": "fg: the color of the foreground, meaning text and graph outlines."
},
{
"code": null,
"e": 6011,
"s": 5963,
"text": "col.axis: the color of the axis ticks and text."
},
{
"code": null,
"e": 6094,
"s": 6011,
"text": "cex.axis: the size of the axis ticks and text, relative to the default value of 1."
},
{
"code": null,
"e": 6165,
"s": 6094,
"text": "I also added a few similar attributes to the plot section of the code:"
},
{
"code": null,
"e": 6209,
"s": 6165,
"text": "font.lab: specifies the font of your labels"
},
{
"code": null,
"e": 6253,
"s": 6209,
"text": "col.lab: specifies the color of your labels"
},
{
"code": null,
"e": 6302,
"s": 6253,
"text": "font.main: specifies the font of your main title"
},
{
"code": null,
"e": 6351,
"s": 6302,
"text": "col.main: specifies the color of your main title"
},
{
"code": null,
"e": 6461,
"s": 6351,
"text": "These attributes are specified exactly how their parent attributes (col and font) are specified. Easy, right?"
},
{
"code": null,
"e": 6538,
"s": 6461,
"text": "I didn’t make any changes to the legend; the par() function did that for me."
},
{
"code": null,
"e": 7915,
"s": 6538,
"text": "##global settingspar(mfrow = c(1,2), mar = c(5,5,4,1),font = 7,font.axis = 7, fg = \"azure4\", col.axis = \"azure4\", cex.axis = .75)## First plot plot(iris$Petal.Length, iris$Petal.Width, xlab = \"Petal Length\", ylab = \"Petal Width\", font.lab = 7, col.lab = \"azure4\", main = \"Petal Width vs Petal Length\", font.main = 7, col.main = \"black\", pch = 20, col=ifelse(iris$Species == \"setosa\",\"coral1\", ifelse(iris$Species == \"virginica\",\"cyan4\", ifelse(iris$Species == \"versicolor\", \"darkgoldenrod2\", \"grey\")))) ##legend legend(\"bottomright\", c(\"setosa\",\"virginica\", \"versicolor\"), col = c(\"coral1\",\"cyan4\", \"darkgoldenrod2\"), pch=20)##Second plot plot(iris$Sepal.Length, iris$Sepal.Width, xlab = \"Sepal Length\", ylab = \"Sepal Width\", font.lab = 7, col.lab = \"azure4\", main = \"Sepal Width vs Sepal Length\", font.main=7, col.main = \"black\", pch = 17, col=ifelse(iris$Species == \"setosa\",\"coral1\", ifelse(iris$Species == \"virginica\",\"cyan4\", ifelse(iris$Species == \"versicolor\", \"darkgoldenrod2\", \"grey\")))) ##legend legend(\"bottomright\", c(\"setosa\",\"virginica\", \"versicolor\"), col = c(\"coral1\",\"cyan4\", \"darkgoldenrod2\"), pch=17)"
},
{
"code": null,
"e": 8109,
"s": 7915,
"text": "Backgrounds for your charts are tricky using base plotting in R. The par() function has a background attribute, bg, but it colors the whole area of your chart the background color. For example:"
},
{
"code": null,
"e": 8201,
"s": 8109,
"text": "par(mfrow = c(1,1), mar = c(5,5,4,1),bg = \"grey\") plot(iris$Petal.Length, iris$Petal.Width)"
},
{
"code": null,
"e": 8219,
"s": 8201,
"text": "Not what we want."
},
{
"code": null,
"e": 8540,
"s": 8219,
"text": "In base R there is no easy way of just coloring in the background of your plot. You can use the rect function to draw a rectangle that aligns with your axis, or you can use abline. The abline function is very versatile, and using it to create a background for our graph forces us to create our plot a little differently."
},
{
"code": null,
"e": 8682,
"s": 8540,
"text": "We’ll build off of the work in the previous sections, adding a colored background with gridlines to our plot of petal width vs. petal length."
},
{
"code": null,
"e": 9633,
"s": 8682,
"text": "##global parameterspar(mfrow = c(1,1), mar = c(5,5,4,1),font = 7,font.axis = 7, fg = \"azure4\", col.axis = \"azure4\", cex.axis = .75) ##Create the empty plotplot(NULL, ylim=c(0,2.5),xlim=c(0,7), xlab = \"Petal Length\", ylab = \"Petal Width\", font.lab = 7, main = \"Petal Width vs. Petal Length\", font.main = 7, col.main = \"black\",)##Add the background colorabline(v = 0:7, col = \"aliceblue\", lwd = 200)abline(v = 0:7, col = \"white\")abline(h=0:2.5, col = \"white\")##Add the data pointspoints(iris$Petal.Length, iris$Petal.Width, pch = 20, cex = 1.5, col=ifelse(iris$Species == \"setosa\",\"coral1\", ifelse(iris$Species == \"virginica\",\"cyan4\", ifelse(iris$Species == \"versicolor\", \"darkgoldenrod2\", \"grey\"))))##legendlegend(\"bottomright\", c(\"setosa\",\"virginica\", \"versicolor\"), col = c(\"coral1\",\"cyan4\", \"darkgoldenrod2\"), pch=20)"
},
{
"code": null,
"e": 9992,
"s": 9633,
"text": "If you look at the code for this graph, you can see that it approaches plot creation a bit differently. First, it sets up an empty plot and then draws on layers of information, starting with the background color, then the data points, then the legend. The background color is created using thick ab-lines for the solid color and thin white ones for the grid:"
},
{
"code": null,
"e": 10124,
"s": 9992,
"text": "##Add the background colorabline(v = 0:7, col = \"aliceblue\", lwd = 200)abline(v = 0:7, col = \"white\")abline(h=0:2.5, col = \"white\")"
},
{
"code": null,
"e": 10322,
"s": 10124,
"text": "You can see that we’ve moved our point attributes, (the dataset, pch, and col) to the points() function, but we haven’t changed them. I did add the attribute cex to increase the size of the points."
},
{
"code": null,
"e": 10766,
"s": 10322,
"text": "Graphs are one of the most effective ways of communicating analysis results to any audience. Additions as simple as proper labels, subsetting data by colors or symbols, and font adjustments add both information and clarity, yet consistently we see graphics coming out of R that look like they were created thirty years ago. After putting time into cleaning, summarizing, and analyzing your data, it makes sense to spend a minute on your plots."
},
{
"code": null,
"e": 10837,
"s": 10766,
"text": "Below are some nice cheat sheets to help you with your customizations."
},
{
"code": null,
"e": 10986,
"s": 10837,
"text": "There are many ways to approach fonts in R, but here is a basic cheat sheet for the numerical values associated with different fonts using font = x."
}
] |
5 Simple Steps to Package and Publish Your Python Code to PyPI | by Sara A. Metwalli | Towards Data Science | Developers and programmers are always learning; their life and their career choice is a never-ending learning journey. In fact, most programmers and data scientists join the field because they have curious minds, and they love to learn and develop their knowledge base.
When you start learning Python, whether to use it to build data science applications or just to build a general programming initiative, you can find many resources and learning paths you can use as a guide throughout your journey. But, these paths and resources often focus more on some aspects of the learning than on others.
One of the aspects of programming in Python that I found lacks the appropriate amount of resources and guidance is what happens after you learn the basics of Python or data science and build a working project. After that, you would want to share, deploy or distribute your code publicly for others to install, use and utilize.
towardsdatascience.com
More precisely, I found the resources to distribute your work via PyPI (Python Project Index) to be very limited and not often complete. The PyPI is an open-source repository for all Python projects that are offered by developers worldwide. The main advantage of using PyPI to distribute your work is how simple it makes it for others to install and use your code on their local devices.
Distributing a package using PyPI makes it installable using pip, which is a command used to install Python packages on local devices in virtual environments. In this article, I will attempt to simplify the process of distributing a package to PyPI by following 5 simple steps using stepuptools.
To package your work, you need work to start with! So, once you’ve completed your code, modulized it, and tested it, you will need to put it in a specific hierarchy before you start packing it and publishing it. Here’s a simple project hierarchy you can start with:
packageName├── LICENSE├── projectName│ ├── __init__.py│ ├── module_1.py│ ├── module_1.py│ └── module_2.py├── README ├── pyproject.toml└── setup file
In some packages, the packageName and the projectName are the same, but that’s not necessary. The packageName is used in the pip install command, so it will be pip install packageName, while the project name is what’s used in the import command after the package is installed. So, once the installation is done, you type import projectName.
If your project requires further depth in the hierarchy, make sure to include a __init__.py file in every hierarchy to make it importable. Basically, if your directory contains an __init__.py file, the content of this file can then be imported. For example, consider the following directory:
mydir├── dir│ ├── __init__.py│ └── module_1.py└── some other files
Assuming that mydir is on your path — the one you choose when you install Python — you will be able to import the code module_1.py in your code files simply as:
import dir.module_1#Orfrom dir import module_1
If the __init__.py file was not in the directory; when you run Python, the interpreter will no longer look for modules within that directory, leading to an import error if you try to import these modules. The __init__.py file in most cases is an empty file. But, sometimes, it can include more convenient or simple names for the submodules.
towardsdatascience.com
Great, now that your files are clean and sorted out, we can move on to the next step, adding the supporting files. To be precise, you will need 4 or 5 supporting files to complete your package files.
No1: The setup fileThis file includes meta-data about the project, for example, its author, its repository, a description of the project, the license it’s published under, and more. There are two types of setup files, static and dynamic.
Static (setup.cfg): is the same every time the package is installed. It has a format that’s easy to read and understand.
Dynamic (setup.py): Some items within it are dynamic or determined at install-time.
The official Python packaging website strongly suggests using static setup files and only use the dynamic when absolutely necessary. So, in this article, I will focus on the static setup file. Here’s a template of a setup.cfg file that you can use.
[metadata]name = NAME_OF_YOUR_PROJECTversion = 0.0.1author = YOUR_NAMEauthor_email = YOUR_EMAILdescription = WHAT IS THE REASON YOU BUILD THIS PROJECT AND WHAT IT DOESlong_description = file: README.mdlong_description_content_type = text/markdownurl = GITHUB REPOSITORY LINKclassifiers = Programming Language :: Python :: 3 License :: OSI Approved :: Apache Software License Operating System :: OS Independent[options]packages = find:python_requires = >=3.7include_package_data = True
The [options] sections deal with dependencies. The line Package = find: works automatically to detect your package dependencies.
No2: The pyproject. tomlThis is a simple, short, and often fixed file that includes Python's tools to create a PyPi package. It basically explains to PyPI that we are planning to use setuptools and wheels to distribute and build our package.
[build-system]requires = [“setuptools>=42”,“wheel”]build-backend = “setuptools.build_meta”
No3: A License fileThere are many different open-source licenses; choosing depends on your goal and the nature of your project; if you need help deciding on a license to use, this website can help you out.
Once you choose your license, you must add it to the setup file in a PyPi accepted format. In the above example, I used the Apache license. You can find all supported license formats here.
No4: A README fileThe README file often includes detailed information about the project, its installation, and maybe a usage example. In PyPI packages, the README files often take one of 4 forms README, README.txt, README.rst, or README.md. They are either plain text, a reStructuredText, or a Markdown file. Whichever you decide to use, it will be used as the project description on the package page on the PyPI website.
No5: MANIFEST.in
This is an optional file, and you only need to include it if you have non-code files in your package. If you do, you need to write them down in this file so the package installer knows where to find them.
You’re almost done. Before you upload your package to PyPI, you need to build it locally and make sure you’re not missing any files or have something wrong with your code or supporting files. So, from the directory of your package, run the command line.
If you don’t have the wheel tool, you will need to install it and have the latest version of the build tool.
pip install wheelpy -m pip install --upgrade build
Now that you have the tool to build the package, you can start your project's build.
py -m build
If all your files are in order, its command should produce many lines of commands and end with no error.
towardsdatascience.com
Just because your package was successfully built locally doesn’t mean you will have no problem when you try to pip install it. So, this step is just a test and debug step; you can skip it if you want. Uploading your package to testPyPI will let you pip install it just to test it out.
So, go ahead and register for both PyPi and testPyPi. I should point out that these two are completely independent and don’t share a database. Once you’re registered, you will have a username and password; make sure you remember them because you will use them to upload your package.
Now, install Twine, which is a tool to help you create the package.
pip install twine
To upload your project to testPyPI, type in the following command:
py -m twine upload --repository testpypi dist/*
Which should result in something similar to:
Uploading distributions to https://test.pypi.org/legacy/Enter your username: [your username]Enter your password:Uploading yourpkg_YOUR_USERNAME_HERE-0.0.1-py3-none-any.whl100%|█████████████████████| 4.65k/4.65k [00:01<00:00, 2.88kB/s]Uploading yourpkg_YOUR_USERNAME_HERE-0.0.1.tar.gz100%|█████████████████████| 4.25k/4.25k [00:01<00:00, 3.05kB/s]
You can then install your package in a virtual environment and test it works properly. If it does, we can move it to the final step.
Once you made sure your package works on testPyPI you can go ahead and upload it to PyPI. If it’s the first time you’re uploading this package, then you can use the following command to upload it.
py -m twine upload --repository PyPI dist/*
But if you already have a package published and you just need to upload a new version of it, you should use this command.
py -m twine upload --skip-existing dist/*
And voila, your package is uploaded and ready to use.
Python is one of the most popular languages within the programming field with its various applications, from building simple desktop apps to complex artificial intelligence and big data applications. Python is even known outside the tech field; many other fields such as chemistry, biology, and medicine use Python and other languages and tools to visualize and analyze their data for everyday use.
Because of the popularity of Python, many learning resources and paths have been developed and published all over the internet. If you have Python-related questions, chances are you will find more than one resource that covers that aspect and provide possible answers to it.
towardsdatascience.com
That being said, some aspects of Python programming are not addressed as much as others. If you want to deal with lists, dictionaries, OOP, modulation in Python, you will find millions of Google results to help you accomplish that easily and efficiently.
But, one of the Python aspects that didn’t get an equal amount of attention is how to package your Python code correctly and distribute it via the Python Project Index (PyPI) for others to use. I hope this article made the process of packaging Python code manageable and understandable for you to distribute your work hassle-free. | [
{
"code": null,
"e": 442,
"s": 172,
"text": "Developers and programmers are always learning; their life and their career choice is a never-ending learning journey. In fact, most programmers and data scientists join the field because they have curious minds, and they love to learn and develop their knowledge base."
},
{
"code": null,
"e": 769,
"s": 442,
"text": "When you start learning Python, whether to use it to build data science applications or just to build a general programming initiative, you can find many resources and learning paths you can use as a guide throughout your journey. But, these paths and resources often focus more on some aspects of the learning than on others."
},
{
"code": null,
"e": 1096,
"s": 769,
"text": "One of the aspects of programming in Python that I found lacks the appropriate amount of resources and guidance is what happens after you learn the basics of Python or data science and build a working project. After that, you would want to share, deploy or distribute your code publicly for others to install, use and utilize."
},
{
"code": null,
"e": 1119,
"s": 1096,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1507,
"s": 1119,
"text": "More precisely, I found the resources to distribute your work via PyPI (Python Project Index) to be very limited and not often complete. The PyPI is an open-source repository for all Python projects that are offered by developers worldwide. The main advantage of using PyPI to distribute your work is how simple it makes it for others to install and use your code on their local devices."
},
{
"code": null,
"e": 1803,
"s": 1507,
"text": "Distributing a package using PyPI makes it installable using pip, which is a command used to install Python packages on local devices in virtual environments. In this article, I will attempt to simplify the process of distributing a package to PyPI by following 5 simple steps using stepuptools."
},
{
"code": null,
"e": 2069,
"s": 1803,
"text": "To package your work, you need work to start with! So, once you’ve completed your code, modulized it, and tested it, you will need to put it in a specific hierarchy before you start packing it and publishing it. Here’s a simple project hierarchy you can start with:"
},
{
"code": null,
"e": 2226,
"s": 2069,
"text": "packageName├── LICENSE├── projectName│ ├── __init__.py│ ├── module_1.py│ ├── module_1.py│ └── module_2.py├── README ├── pyproject.toml└── setup file"
},
{
"code": null,
"e": 2567,
"s": 2226,
"text": "In some packages, the packageName and the projectName are the same, but that’s not necessary. The packageName is used in the pip install command, so it will be pip install packageName, while the project name is what’s used in the import command after the package is installed. So, once the installation is done, you type import projectName."
},
{
"code": null,
"e": 2859,
"s": 2567,
"text": "If your project requires further depth in the hierarchy, make sure to include a __init__.py file in every hierarchy to make it importable. Basically, if your directory contains an __init__.py file, the content of this file can then be imported. For example, consider the following directory:"
},
{
"code": null,
"e": 2930,
"s": 2859,
"text": "mydir├── dir│ ├── __init__.py│ └── module_1.py└── some other files"
},
{
"code": null,
"e": 3091,
"s": 2930,
"text": "Assuming that mydir is on your path — the one you choose when you install Python — you will be able to import the code module_1.py in your code files simply as:"
},
{
"code": null,
"e": 3138,
"s": 3091,
"text": "import dir.module_1#Orfrom dir import module_1"
},
{
"code": null,
"e": 3479,
"s": 3138,
"text": "If the __init__.py file was not in the directory; when you run Python, the interpreter will no longer look for modules within that directory, leading to an import error if you try to import these modules. The __init__.py file in most cases is an empty file. But, sometimes, it can include more convenient or simple names for the submodules."
},
{
"code": null,
"e": 3502,
"s": 3479,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3702,
"s": 3502,
"text": "Great, now that your files are clean and sorted out, we can move on to the next step, adding the supporting files. To be precise, you will need 4 or 5 supporting files to complete your package files."
},
{
"code": null,
"e": 3940,
"s": 3702,
"text": "No1: The setup fileThis file includes meta-data about the project, for example, its author, its repository, a description of the project, the license it’s published under, and more. There are two types of setup files, static and dynamic."
},
{
"code": null,
"e": 4061,
"s": 3940,
"text": "Static (setup.cfg): is the same every time the package is installed. It has a format that’s easy to read and understand."
},
{
"code": null,
"e": 4145,
"s": 4061,
"text": "Dynamic (setup.py): Some items within it are dynamic or determined at install-time."
},
{
"code": null,
"e": 4394,
"s": 4145,
"text": "The official Python packaging website strongly suggests using static setup files and only use the dynamic when absolutely necessary. So, in this article, I will focus on the static setup file. Here’s a template of a setup.cfg file that you can use."
},
{
"code": null,
"e": 4891,
"s": 4394,
"text": "[metadata]name = NAME_OF_YOUR_PROJECTversion = 0.0.1author = YOUR_NAMEauthor_email = YOUR_EMAILdescription = WHAT IS THE REASON YOU BUILD THIS PROJECT AND WHAT IT DOESlong_description = file: README.mdlong_description_content_type = text/markdownurl = GITHUB REPOSITORY LINKclassifiers = Programming Language :: Python :: 3 License :: OSI Approved :: Apache Software License Operating System :: OS Independent[options]packages = find:python_requires = >=3.7include_package_data = True"
},
{
"code": null,
"e": 5020,
"s": 4891,
"text": "The [options] sections deal with dependencies. The line Package = find: works automatically to detect your package dependencies."
},
{
"code": null,
"e": 5262,
"s": 5020,
"text": "No2: The pyproject. tomlThis is a simple, short, and often fixed file that includes Python's tools to create a PyPi package. It basically explains to PyPI that we are planning to use setuptools and wheels to distribute and build our package."
},
{
"code": null,
"e": 5353,
"s": 5262,
"text": "[build-system]requires = [“setuptools>=42”,“wheel”]build-backend = “setuptools.build_meta”"
},
{
"code": null,
"e": 5559,
"s": 5353,
"text": "No3: A License fileThere are many different open-source licenses; choosing depends on your goal and the nature of your project; if you need help deciding on a license to use, this website can help you out."
},
{
"code": null,
"e": 5748,
"s": 5559,
"text": "Once you choose your license, you must add it to the setup file in a PyPi accepted format. In the above example, I used the Apache license. You can find all supported license formats here."
},
{
"code": null,
"e": 6170,
"s": 5748,
"text": "No4: A README fileThe README file often includes detailed information about the project, its installation, and maybe a usage example. In PyPI packages, the README files often take one of 4 forms README, README.txt, README.rst, or README.md. They are either plain text, a reStructuredText, or a Markdown file. Whichever you decide to use, it will be used as the project description on the package page on the PyPI website."
},
{
"code": null,
"e": 6187,
"s": 6170,
"text": "No5: MANIFEST.in"
},
{
"code": null,
"e": 6392,
"s": 6187,
"text": "This is an optional file, and you only need to include it if you have non-code files in your package. If you do, you need to write them down in this file so the package installer knows where to find them."
},
{
"code": null,
"e": 6646,
"s": 6392,
"text": "You’re almost done. Before you upload your package to PyPI, you need to build it locally and make sure you’re not missing any files or have something wrong with your code or supporting files. So, from the directory of your package, run the command line."
},
{
"code": null,
"e": 6755,
"s": 6646,
"text": "If you don’t have the wheel tool, you will need to install it and have the latest version of the build tool."
},
{
"code": null,
"e": 6806,
"s": 6755,
"text": "pip install wheelpy -m pip install --upgrade build"
},
{
"code": null,
"e": 6891,
"s": 6806,
"text": "Now that you have the tool to build the package, you can start your project's build."
},
{
"code": null,
"e": 6903,
"s": 6891,
"text": "py -m build"
},
{
"code": null,
"e": 7008,
"s": 6903,
"text": "If all your files are in order, its command should produce many lines of commands and end with no error."
},
{
"code": null,
"e": 7031,
"s": 7008,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 7316,
"s": 7031,
"text": "Just because your package was successfully built locally doesn’t mean you will have no problem when you try to pip install it. So, this step is just a test and debug step; you can skip it if you want. Uploading your package to testPyPI will let you pip install it just to test it out."
},
{
"code": null,
"e": 7600,
"s": 7316,
"text": "So, go ahead and register for both PyPi and testPyPi. I should point out that these two are completely independent and don’t share a database. Once you’re registered, you will have a username and password; make sure you remember them because you will use them to upload your package."
},
{
"code": null,
"e": 7668,
"s": 7600,
"text": "Now, install Twine, which is a tool to help you create the package."
},
{
"code": null,
"e": 7686,
"s": 7668,
"text": "pip install twine"
},
{
"code": null,
"e": 7753,
"s": 7686,
"text": "To upload your project to testPyPI, type in the following command:"
},
{
"code": null,
"e": 7801,
"s": 7753,
"text": "py -m twine upload --repository testpypi dist/*"
},
{
"code": null,
"e": 7846,
"s": 7801,
"text": "Which should result in something similar to:"
},
{
"code": null,
"e": 8193,
"s": 7846,
"text": "Uploading distributions to https://test.pypi.org/legacy/Enter your username: [your username]Enter your password:Uploading yourpkg_YOUR_USERNAME_HERE-0.0.1-py3-none-any.whl100%|█████████████████████| 4.65k/4.65k [00:01<00:00, 2.88kB/s]Uploading yourpkg_YOUR_USERNAME_HERE-0.0.1.tar.gz100%|█████████████████████| 4.25k/4.25k [00:01<00:00, 3.05kB/s]"
},
{
"code": null,
"e": 8326,
"s": 8193,
"text": "You can then install your package in a virtual environment and test it works properly. If it does, we can move it to the final step."
},
{
"code": null,
"e": 8523,
"s": 8326,
"text": "Once you made sure your package works on testPyPI you can go ahead and upload it to PyPI. If it’s the first time you’re uploading this package, then you can use the following command to upload it."
},
{
"code": null,
"e": 8567,
"s": 8523,
"text": "py -m twine upload --repository PyPI dist/*"
},
{
"code": null,
"e": 8689,
"s": 8567,
"text": "But if you already have a package published and you just need to upload a new version of it, you should use this command."
},
{
"code": null,
"e": 8731,
"s": 8689,
"text": "py -m twine upload --skip-existing dist/*"
},
{
"code": null,
"e": 8785,
"s": 8731,
"text": "And voila, your package is uploaded and ready to use."
},
{
"code": null,
"e": 9184,
"s": 8785,
"text": "Python is one of the most popular languages within the programming field with its various applications, from building simple desktop apps to complex artificial intelligence and big data applications. Python is even known outside the tech field; many other fields such as chemistry, biology, and medicine use Python and other languages and tools to visualize and analyze their data for everyday use."
},
{
"code": null,
"e": 9459,
"s": 9184,
"text": "Because of the popularity of Python, many learning resources and paths have been developed and published all over the internet. If you have Python-related questions, chances are you will find more than one resource that covers that aspect and provide possible answers to it."
},
{
"code": null,
"e": 9482,
"s": 9459,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9737,
"s": 9482,
"text": "That being said, some aspects of Python programming are not addressed as much as others. If you want to deal with lists, dictionaries, OOP, modulation in Python, you will find millions of Google results to help you accomplish that easily and efficiently."
}
] |
Time Series Forecasting with SARIMA in Python | by Marco Peixeiro | Towards Data Science | In previous articles, we introduced moving average processes MA(q), and autoregressive processes AR(p). We combined them and formed ARMA(p,q) and ARIMA(p,d,q) models to model more complex time series.
Now, add one last component to the model: seasonality.
This article will cover:
Seasonal ARIMA models
A complete modelling and forecasting project with real-life data
The notebook and dataset are available on Github.
Let’s get started!
For a complete course on time series analysis in Python, covering both statistical and deep learning models, check my newly released course!
Up until now, we have not considered the effect of seasonality in time series. However, this behaviour is surely present in many cases, such as gift shop sales, or total number of air passengers.
A seasonal ARIMA model or SARIMA is written as follows:
You can see that we add P, D, and Q for the seasonal portion of the time series. They are the same terms as the non-seasonal components, by they involve backshifts of the seasonal period.
In the formula above, m is the number of observations per year or the period. If we are analyzing quarterly data, m would equal 4.
The seasonal part of an AR and MA model can be inferred from the PACF and ACF plots.
In the case of a SARIMA model with only a seasonal moving average process of order 1 and period of 12, denoted as:
A spike is observed at lag 12
Exponential decay in the seasonal lags of the PACF (lag 12, 24, 36, ...)
Similarly, for a model with only a seasonal autoregressive process of order 1 and period of 12:
Exponential decay in the seasonal lags of the ACF (lag 12, 24, 36, ...)
A spike is observed at lag 12 in the PACF
The modelling process is the same as with non-seasonal ARIMA models. In this case, we simply need to consider the additional parameters.
Steps required to make the time series stationary and selecting the model according to the lowest AIC remain in the modelling process.
Let’s cover a complete example with a real-world dataset.
We are going to revisit the dataset of the quarterly earnings per share (EPS) of Johnson&Johnson. This is a very interesting dataset, because there is a moving average process at play, and we have seasonality, which is perfect to get some practice with SARIMA.
As always, we start off by importing all the necessary libraries for our analysis
from statsmodels.graphics.tsaplots import plot_pacffrom statsmodels.graphics.tsaplots import plot_acffrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom statsmodels.tsa.holtwinters import ExponentialSmoothingfrom statsmodels.tsa.stattools import adfullerimport matplotlib.pyplot as pltfrom tqdm import tqdm_notebookimport numpy as npimport pandas as pdfrom itertools import productimport warningswarnings.filterwarnings('ignore')%matplotlib inline
Now, let’s read in the data in a dataframe:
data = pd.read_csv('jj.csv')
Then, we can display a plot of the time series:
plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.plot(data['date'], data['data'])plt.title('Quarterly EPS for Johnson & Johnson')plt.ylabel('EPS per share ($)')plt.xlabel('Date')plt.xticks(rotation=90)plt.grid(True)plt.show()
Clearly, the time series is not stationary, as its mean is not constant through time, and we see an increasing variance in the data, a sign of heteroscedasticity.
To make sure, let’s plot the PACF and ACF:
plot_pacf(data['data']);plot_acf(data['data']);
Again, no information can be deduced from those plots. You can further test for stationarity with the Augmented Dickey-Fuller test:
ad_fuller_result = adfuller(data['data'])print(f'ADF Statistic: {ad_fuller_result[0]}')print(f'p-value: {ad_fuller_result[1]}')
Since the p-value is large, we cannot reject the null hypothesis and must assume that the time series is non-stationary.
Now, let’s take the log difference in an effort to make it stationary:
data['data'] = np.log(data['data'])data['data'] = data['data'].diff()data = data.drop(data.index[0])
Plotting the new data should give:
plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.plot(data['data'])plt.title("Log Difference of Quarterly EPS for Johnson & Johnson")plt.show()
Awesome! Now, we still see the seasonality in the plot above. Since we are dealing with quarterly data, our period is 4. Therefore, we will take the difference over a period of 4:
# Seasonal differencingdata['data'] = data['data'].diff(4)data = data.drop([1, 2, 3, 4], axis=0).reset_index(drop=True)
Plotting the new data:
plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.plot(data['data'])plt.title("Log Difference of Quarterly EPS for Johnson & Johnson")plt.show()
Perfect! Keep in mind that although we took the difference over a period of 4 months, the order of seasonal differencing (D) is 1, because we only took the difference once.
Now, let’s run the Augmented Dickey-Fuller test again to see if we have a stationary time series:
ad_fuller_result = adfuller(data['data'])print(f'ADF Statistic: {ad_fuller_result[0]}')print(f'p-value: {ad_fuller_result[1]}')
Indeed, the p-value is small enough for us to reject the null hypothesis, and we can consider that the time series is stationary.
Taking a look at the ACF and PACF:
plot_pacf(data['data']);plot_acf(data['data']);
We can see from the PACF that we have a significant peak at lag 1, which suggest an AR(1) process. Also, we have another peak at lag 4, suggesting a seasonal autoregressive process of order 1 (P = 1).
Looking at the ACF plot, we only see a significant peak at lag 1, suggesting a non-seasonal MA(1) process.
Although these plots can give us a rough idea of the processes in play, it is better to test multiple scenarios and choose the model that yield the lowest AIC.
Therefore, let’s write a function that will test a series of parameters for the SARIMA model and output a table with the best performing model at the top:
def optimize_SARIMA(parameters_list, d, D, s, exog): """ Return dataframe with parameters, corresponding AIC and SSE parameters_list - list with (p, q, P, Q) tuples d - integration order D - seasonal integration order s - length of season exog - the exogenous variable """ results = [] for param in tqdm_notebook(parameters_list): try: model = SARIMAX(exog, order=(param[0], d, param[1]), seasonal_order=(param[2], D, param[3], s)).fit(disp=-1) except: continue aic = model.aic results.append([param, aic]) result_df = pd.DataFrame(results) result_df.columns = ['(p,q)x(P,Q)', 'AIC'] #Sort in ascending order, lower AIC is better result_df = result_df.sort_values(by='AIC', ascending=True).reset_index(drop=True) return result_df
Note that we will only test different values for the parameters p, P, q and Q. We know that both seasonal and non-seasonal integration parameters should be 1, and that the length of the season is 4.
Therefore, we generate all possible parameters combination:
p = range(0, 4, 1)d = 1q = range(0, 4, 1)P = range(0, 4, 1)D = 1Q = range(0, 4, 1)s = 4parameters = product(p, q, P, Q)parameters_list = list(parameters)print(len(parameters_list))
And you should see that we get 256 unique combinations! Now, our function will fit 256 different SARIMA models on our data to find the one with the lowest AIC:
result_df = optimize_SARIMA(parameters_list, 1, 1, 4, data['data'])result_df
From the table, you can see that the best model is: SARIMA(0, 1, 2)(0, 1, 2, 4).
We can now fit the model and output its summary:
best_model = SARIMAX(data['data'], order=(0, 1, 2), seasonal_order=(0, 1, 2, 4)).fit(dis=-1)print(best_model.summary())
Here, you see that the best performing model has both seasonal and non-seasonal moving average processes.
From the summary above, you can find the value of the coefficients and their p-value. Notice that from the p-value, all coefficients are significant.
Now, we can study the residuals:
best_model.plot_diagnostics(figsize=(15,12));
From the normal Q-Q plot, we can see that we almost have a straight line, which suggest no systematic departure from normality. Also, the correlogram on the bottom right suggests that there is no autocorrelation in the residuals, and so they are effectively white noise.
We are ready to plot the predictions of our model and forecast into the future:
data['arima_model'] = best_model.fittedvaluesdata['arima_model'][:4+1] = np.NaNforecast = best_model.predict(start=data.shape[0], end=data.shape[0] + 8)forecast = data['arima_model'].append(forecast)plt.figure(figsize=(15, 7.5))plt.plot(forecast, color='r', label='model')plt.axvspan(data.index[-1], forecast.index[-1], alpha=0.5, color='lightgrey')plt.plot(data['data'], label='actual')plt.legend()plt.show()
Voilà!
Congratulations! You now understand what a seasonal ARIMA (or SARIMA) model is and how to use it to model and forecast.
Learn more about time series with the following course:
Applied Time Series Analysis in Python | [
{
"code": null,
"e": 373,
"s": 172,
"text": "In previous articles, we introduced moving average processes MA(q), and autoregressive processes AR(p). We combined them and formed ARMA(p,q) and ARIMA(p,d,q) models to model more complex time series."
},
{
"code": null,
"e": 428,
"s": 373,
"text": "Now, add one last component to the model: seasonality."
},
{
"code": null,
"e": 453,
"s": 428,
"text": "This article will cover:"
},
{
"code": null,
"e": 475,
"s": 453,
"text": "Seasonal ARIMA models"
},
{
"code": null,
"e": 540,
"s": 475,
"text": "A complete modelling and forecasting project with real-life data"
},
{
"code": null,
"e": 590,
"s": 540,
"text": "The notebook and dataset are available on Github."
},
{
"code": null,
"e": 609,
"s": 590,
"text": "Let’s get started!"
},
{
"code": null,
"e": 750,
"s": 609,
"text": "For a complete course on time series analysis in Python, covering both statistical and deep learning models, check my newly released course!"
},
{
"code": null,
"e": 946,
"s": 750,
"text": "Up until now, we have not considered the effect of seasonality in time series. However, this behaviour is surely present in many cases, such as gift shop sales, or total number of air passengers."
},
{
"code": null,
"e": 1002,
"s": 946,
"text": "A seasonal ARIMA model or SARIMA is written as follows:"
},
{
"code": null,
"e": 1190,
"s": 1002,
"text": "You can see that we add P, D, and Q for the seasonal portion of the time series. They are the same terms as the non-seasonal components, by they involve backshifts of the seasonal period."
},
{
"code": null,
"e": 1321,
"s": 1190,
"text": "In the formula above, m is the number of observations per year or the period. If we are analyzing quarterly data, m would equal 4."
},
{
"code": null,
"e": 1406,
"s": 1321,
"text": "The seasonal part of an AR and MA model can be inferred from the PACF and ACF plots."
},
{
"code": null,
"e": 1521,
"s": 1406,
"text": "In the case of a SARIMA model with only a seasonal moving average process of order 1 and period of 12, denoted as:"
},
{
"code": null,
"e": 1551,
"s": 1521,
"text": "A spike is observed at lag 12"
},
{
"code": null,
"e": 1624,
"s": 1551,
"text": "Exponential decay in the seasonal lags of the PACF (lag 12, 24, 36, ...)"
},
{
"code": null,
"e": 1720,
"s": 1624,
"text": "Similarly, for a model with only a seasonal autoregressive process of order 1 and period of 12:"
},
{
"code": null,
"e": 1792,
"s": 1720,
"text": "Exponential decay in the seasonal lags of the ACF (lag 12, 24, 36, ...)"
},
{
"code": null,
"e": 1834,
"s": 1792,
"text": "A spike is observed at lag 12 in the PACF"
},
{
"code": null,
"e": 1971,
"s": 1834,
"text": "The modelling process is the same as with non-seasonal ARIMA models. In this case, we simply need to consider the additional parameters."
},
{
"code": null,
"e": 2106,
"s": 1971,
"text": "Steps required to make the time series stationary and selecting the model according to the lowest AIC remain in the modelling process."
},
{
"code": null,
"e": 2164,
"s": 2106,
"text": "Let’s cover a complete example with a real-world dataset."
},
{
"code": null,
"e": 2425,
"s": 2164,
"text": "We are going to revisit the dataset of the quarterly earnings per share (EPS) of Johnson&Johnson. This is a very interesting dataset, because there is a moving average process at play, and we have seasonality, which is perfect to get some practice with SARIMA."
},
{
"code": null,
"e": 2507,
"s": 2425,
"text": "As always, we start off by importing all the necessary libraries for our analysis"
},
{
"code": null,
"e": 2962,
"s": 2507,
"text": "from statsmodels.graphics.tsaplots import plot_pacffrom statsmodels.graphics.tsaplots import plot_acffrom statsmodels.tsa.statespace.sarimax import SARIMAXfrom statsmodels.tsa.holtwinters import ExponentialSmoothingfrom statsmodels.tsa.stattools import adfullerimport matplotlib.pyplot as pltfrom tqdm import tqdm_notebookimport numpy as npimport pandas as pdfrom itertools import productimport warningswarnings.filterwarnings('ignore')%matplotlib inline"
},
{
"code": null,
"e": 3006,
"s": 2962,
"text": "Now, let’s read in the data in a dataframe:"
},
{
"code": null,
"e": 3035,
"s": 3006,
"text": "data = pd.read_csv('jj.csv')"
},
{
"code": null,
"e": 3083,
"s": 3035,
"text": "Then, we can display a plot of the time series:"
},
{
"code": null,
"e": 3322,
"s": 3083,
"text": "plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.plot(data['date'], data['data'])plt.title('Quarterly EPS for Johnson & Johnson')plt.ylabel('EPS per share ($)')plt.xlabel('Date')plt.xticks(rotation=90)plt.grid(True)plt.show()"
},
{
"code": null,
"e": 3485,
"s": 3322,
"text": "Clearly, the time series is not stationary, as its mean is not constant through time, and we see an increasing variance in the data, a sign of heteroscedasticity."
},
{
"code": null,
"e": 3528,
"s": 3485,
"text": "To make sure, let’s plot the PACF and ACF:"
},
{
"code": null,
"e": 3576,
"s": 3528,
"text": "plot_pacf(data['data']);plot_acf(data['data']);"
},
{
"code": null,
"e": 3708,
"s": 3576,
"text": "Again, no information can be deduced from those plots. You can further test for stationarity with the Augmented Dickey-Fuller test:"
},
{
"code": null,
"e": 3836,
"s": 3708,
"text": "ad_fuller_result = adfuller(data['data'])print(f'ADF Statistic: {ad_fuller_result[0]}')print(f'p-value: {ad_fuller_result[1]}')"
},
{
"code": null,
"e": 3957,
"s": 3836,
"text": "Since the p-value is large, we cannot reject the null hypothesis and must assume that the time series is non-stationary."
},
{
"code": null,
"e": 4028,
"s": 3957,
"text": "Now, let’s take the log difference in an effort to make it stationary:"
},
{
"code": null,
"e": 4129,
"s": 4028,
"text": "data['data'] = np.log(data['data'])data['data'] = data['data'].diff()data = data.drop(data.index[0])"
},
{
"code": null,
"e": 4164,
"s": 4129,
"text": "Plotting the new data should give:"
},
{
"code": null,
"e": 4321,
"s": 4164,
"text": "plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.plot(data['data'])plt.title(\"Log Difference of Quarterly EPS for Johnson & Johnson\")plt.show()"
},
{
"code": null,
"e": 4501,
"s": 4321,
"text": "Awesome! Now, we still see the seasonality in the plot above. Since we are dealing with quarterly data, our period is 4. Therefore, we will take the difference over a period of 4:"
},
{
"code": null,
"e": 4621,
"s": 4501,
"text": "# Seasonal differencingdata['data'] = data['data'].diff(4)data = data.drop([1, 2, 3, 4], axis=0).reset_index(drop=True)"
},
{
"code": null,
"e": 4644,
"s": 4621,
"text": "Plotting the new data:"
},
{
"code": null,
"e": 4801,
"s": 4644,
"text": "plt.figure(figsize=[15, 7.5]); # Set dimensions for figureplt.plot(data['data'])plt.title(\"Log Difference of Quarterly EPS for Johnson & Johnson\")plt.show()"
},
{
"code": null,
"e": 4974,
"s": 4801,
"text": "Perfect! Keep in mind that although we took the difference over a period of 4 months, the order of seasonal differencing (D) is 1, because we only took the difference once."
},
{
"code": null,
"e": 5072,
"s": 4974,
"text": "Now, let’s run the Augmented Dickey-Fuller test again to see if we have a stationary time series:"
},
{
"code": null,
"e": 5200,
"s": 5072,
"text": "ad_fuller_result = adfuller(data['data'])print(f'ADF Statistic: {ad_fuller_result[0]}')print(f'p-value: {ad_fuller_result[1]}')"
},
{
"code": null,
"e": 5330,
"s": 5200,
"text": "Indeed, the p-value is small enough for us to reject the null hypothesis, and we can consider that the time series is stationary."
},
{
"code": null,
"e": 5365,
"s": 5330,
"text": "Taking a look at the ACF and PACF:"
},
{
"code": null,
"e": 5413,
"s": 5365,
"text": "plot_pacf(data['data']);plot_acf(data['data']);"
},
{
"code": null,
"e": 5614,
"s": 5413,
"text": "We can see from the PACF that we have a significant peak at lag 1, which suggest an AR(1) process. Also, we have another peak at lag 4, suggesting a seasonal autoregressive process of order 1 (P = 1)."
},
{
"code": null,
"e": 5721,
"s": 5614,
"text": "Looking at the ACF plot, we only see a significant peak at lag 1, suggesting a non-seasonal MA(1) process."
},
{
"code": null,
"e": 5881,
"s": 5721,
"text": "Although these plots can give us a rough idea of the processes in play, it is better to test multiple scenarios and choose the model that yield the lowest AIC."
},
{
"code": null,
"e": 6036,
"s": 5881,
"text": "Therefore, let’s write a function that will test a series of parameters for the SARIMA model and output a table with the best performing model at the top:"
},
{
"code": null,
"e": 6926,
"s": 6036,
"text": "def optimize_SARIMA(parameters_list, d, D, s, exog): \"\"\" Return dataframe with parameters, corresponding AIC and SSE parameters_list - list with (p, q, P, Q) tuples d - integration order D - seasonal integration order s - length of season exog - the exogenous variable \"\"\" results = [] for param in tqdm_notebook(parameters_list): try: model = SARIMAX(exog, order=(param[0], d, param[1]), seasonal_order=(param[2], D, param[3], s)).fit(disp=-1) except: continue aic = model.aic results.append([param, aic]) result_df = pd.DataFrame(results) result_df.columns = ['(p,q)x(P,Q)', 'AIC'] #Sort in ascending order, lower AIC is better result_df = result_df.sort_values(by='AIC', ascending=True).reset_index(drop=True) return result_df"
},
{
"code": null,
"e": 7125,
"s": 6926,
"text": "Note that we will only test different values for the parameters p, P, q and Q. We know that both seasonal and non-seasonal integration parameters should be 1, and that the length of the season is 4."
},
{
"code": null,
"e": 7185,
"s": 7125,
"text": "Therefore, we generate all possible parameters combination:"
},
{
"code": null,
"e": 7366,
"s": 7185,
"text": "p = range(0, 4, 1)d = 1q = range(0, 4, 1)P = range(0, 4, 1)D = 1Q = range(0, 4, 1)s = 4parameters = product(p, q, P, Q)parameters_list = list(parameters)print(len(parameters_list))"
},
{
"code": null,
"e": 7526,
"s": 7366,
"text": "And you should see that we get 256 unique combinations! Now, our function will fit 256 different SARIMA models on our data to find the one with the lowest AIC:"
},
{
"code": null,
"e": 7603,
"s": 7526,
"text": "result_df = optimize_SARIMA(parameters_list, 1, 1, 4, data['data'])result_df"
},
{
"code": null,
"e": 7684,
"s": 7603,
"text": "From the table, you can see that the best model is: SARIMA(0, 1, 2)(0, 1, 2, 4)."
},
{
"code": null,
"e": 7733,
"s": 7684,
"text": "We can now fit the model and output its summary:"
},
{
"code": null,
"e": 7853,
"s": 7733,
"text": "best_model = SARIMAX(data['data'], order=(0, 1, 2), seasonal_order=(0, 1, 2, 4)).fit(dis=-1)print(best_model.summary())"
},
{
"code": null,
"e": 7959,
"s": 7853,
"text": "Here, you see that the best performing model has both seasonal and non-seasonal moving average processes."
},
{
"code": null,
"e": 8109,
"s": 7959,
"text": "From the summary above, you can find the value of the coefficients and their p-value. Notice that from the p-value, all coefficients are significant."
},
{
"code": null,
"e": 8142,
"s": 8109,
"text": "Now, we can study the residuals:"
},
{
"code": null,
"e": 8188,
"s": 8142,
"text": "best_model.plot_diagnostics(figsize=(15,12));"
},
{
"code": null,
"e": 8459,
"s": 8188,
"text": "From the normal Q-Q plot, we can see that we almost have a straight line, which suggest no systematic departure from normality. Also, the correlogram on the bottom right suggests that there is no autocorrelation in the residuals, and so they are effectively white noise."
},
{
"code": null,
"e": 8539,
"s": 8459,
"text": "We are ready to plot the predictions of our model and forecast into the future:"
},
{
"code": null,
"e": 8949,
"s": 8539,
"text": "data['arima_model'] = best_model.fittedvaluesdata['arima_model'][:4+1] = np.NaNforecast = best_model.predict(start=data.shape[0], end=data.shape[0] + 8)forecast = data['arima_model'].append(forecast)plt.figure(figsize=(15, 7.5))plt.plot(forecast, color='r', label='model')plt.axvspan(data.index[-1], forecast.index[-1], alpha=0.5, color='lightgrey')plt.plot(data['data'], label='actual')plt.legend()plt.show()"
},
{
"code": null,
"e": 8957,
"s": 8949,
"text": "Voilà!"
},
{
"code": null,
"e": 9077,
"s": 8957,
"text": "Congratulations! You now understand what a seasonal ARIMA (or SARIMA) model is and how to use it to model and forecast."
},
{
"code": null,
"e": 9133,
"s": 9077,
"text": "Learn more about time series with the following course:"
}
] |
Check if array elements are consecutive | Added Method 4 - GeeksforGeeks | 29 Apr, 2022
Given an unsorted array of numbers, write a function that returns true if the array consists of consecutive numbers. Examples: a) If the array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers from 1 to 5.b) If the array is {83, 78, 80, 81, 79, 82}, then the function should return true because the array has consecutive numbers from 78 to 83.c) If the array is {34, 23, 52, 12, 3}, then the function should return false because the elements are not consecutive.d) If the array is {7, 6, 5, 5, 3, 4}, then the function should return false because 5 and 5 are not consecutive.
Method 1 (Use Sorting) 1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.Time Complexity: O(nLogn)Method 2 (Use visited array) The idea is to check for the following two conditions. If the following two conditions are true, then return true. 1) max – min + 1 = n where max is the maximum element in the array, min is the minimum element in the array and n is the number of elements in the array. 2) All elements are distinct.To check if all elements are distinct, we can create a visited[] array of size n. We can map the ith element of input array arr[] to the visited array by using arr[i] – min as the index in visited[].
C++
Java
Python3
C#
PHP
Javascript
#include<stdio.h>#include<stdlib.h> /* Helper functions to get minimum and maximum in an array */int getMin(int arr[], int n);int getMax(int arr[], int n); /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */bool areConsecutive(int arr[], int n){ if ( n < 1 ) return false; /* 1) Get the minimum element in array */ int min = getMin(arr, n); /* 2) Get the maximum element in array */ int max = getMax(arr, n); /* 3) max - min + 1 is equal to n, then only check all elements */ if (max - min + 1 == n) { /* Create a temp array to hold visited flag of all elements. Note that, calloc is used here so that all values are initialized as false */ bool *visited = (bool *) calloc (n, sizeof(bool)); int i; for (i = 0; i < n; i++) { /* If we see an element again, then return false */ if ( visited[arr[i] - min] != false ) return false; /* If visited first time, then mark the element as visited */ visited[arr[i] - min] = true; } /* If all elements occur once, then return true */ return true; } return false; // if (max - min + 1 != n)} /* UTILITY FUNCTIONS */int getMin(int arr[], int n){ int min = arr[0]; for (int i = 1; i < n; i++) if (arr[i] < min) min = arr[i]; return min;} int getMax(int arr[], int n){ int max = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; return max;} /* Driver program to test above functions */int main(){ int arr[]= {5, 4, 2, 3, 1, 6}; int n = sizeof(arr)/sizeof(arr[0]); if(areConsecutive(arr, n) == true) printf(" Array elements are consecutive "); else printf(" Array elements are not consecutive "); getchar(); return 0;}
class AreConsecutive{ /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */ boolean areConsecutive(int arr[], int n) { if (n < 1) return false; /* 1) Get the minimum element in array */ int min = getMin(arr, n); /* 2) Get the maximum element in array */ int max = getMax(arr, n); /* 3) max - min + 1 is equal to n, then only check all elements */ if (max - min + 1 == n) { /* Create a temp array to hold visited flag of all elements. Note that, calloc is used here so that all values are initialized as false */ boolean visited[] = new boolean[n]; int i; for (i = 0; i < n; i++) { /* If we see an element again, then return false */ if (visited[arr[i] - min] != false) return false; /* If visited first time, then mark the element as visited */ visited[arr[i] - min] = true; } /* If all elements occur once, then return true */ return true; } return false; // if (max - min + 1 != n) } /* UTILITY FUNCTIONS */ int getMin(int arr[], int n) { int min = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; } return min; } int getMax(int arr[], int n) { int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ public static void main(String[] args) { AreConsecutive consecutive = new AreConsecutive(); int arr[] = {5, 4, 2, 3, 1, 6}; int n = arr.length; if (consecutive.areConsecutive(arr, n) == true) System.out.println("Array elements are consecutive"); else System.out.println("Array elements are not consecutive"); }} // This code has been contributed by Mayank Jaiswal
# Helper functions to get Minimum and# Maximum in an array # The function checks if the array elements# are consecutive. If elements are consecutive,# then returns true, else returns falsedef areConsecutive(arr, n): if ( n < 1 ): return False # 1) Get the Minimum element in array */ Min = min(arr) # 2) Get the Maximum element in array */ Max = max(arr) # 3) Max - Min + 1 is equal to n, # then only check all elements */ if (Max - Min + 1 == n): # Create a temp array to hold visited # flag of all elements. Note that, calloc # is used here so that all values are # initialized as false visited = [False for i in range(n)] for i in range(n): # If we see an element again, # then return false */ if (visited[arr[i] - Min] != False): return False # If visited first time, then mark # the element as visited */ visited[arr[i] - Min] = True # If all elements occur once, # then return true */ return True return False # if (Max - Min + 1 != n) # Driver Codearr = [5, 4, 2, 3, 1, 6]n = len(arr)if(areConsecutive(arr, n) == True): print("Array elements are consecutive ")else: print("Array elements are not consecutive ") # This code is contributed by mohit kumar
using System; class GFG { /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */ static bool areConsecutive(int []arr, int n) { if (n < 1) return false; /* 1) Get the minimum element in array */ int min = getMin(arr, n); /* 2) Get the maximum element in array */ int max = getMax(arr, n); /* 3) max - min + 1 is equal to n, then only check all elements */ if (max - min + 1 == n) { /* Create a temp array to hold visited flag of all elements. Note that, calloc is used here so that all values are initialized as false */ bool []visited = new bool[n]; int i; for (i = 0; i < n; i++) { /* If we see an element again, then return false */ if (visited[arr[i] - min] != false) return false; /* If visited first time, then mark the element as visited */ visited[arr[i] - min] = true; } /* If all elements occur once, then return true */ return true; } return false; // if (max - min + 1 != n) } /* UTILITY FUNCTIONS */ static int getMin(int []arr, int n) { int min = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; } return min; } static int getMax(int []arr, int n) { int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ public static void Main() { int []arr = {5, 4, 2, 3, 1, 6}; int n = arr.Length; if (areConsecutive(arr, n) == true) Console.Write("Array elements are" + " consecutive"); else Console.Write("Array elements are" + " not consecutive"); }} // This code is contributed by nitin mittal.
<?php// PHP Program for above approach // The function checks if the array elements// are consecutive. If elements are consecutive,// then returns true, else returns falsefunction areConsecutive($arr, $n){ if ( $n < 1 ) return false; // 1) Get the minimum element in array $min = getMin($arr, $n); // 2) Get the maximum element in array $max = getMax($arr, $n); // 3) $max - $min + 1 is equal to $n, // then only check all elements if ($max - $min + 1 == $n) { // Create a temp array to hold // visited flag of all elements. $visited = array(); for ($i = 0; $i < $n; $i++) { $visited[$i] = false; } for ($i = 0; $i < $n; $i++) { // If we see an element again, // then return false if ( $visited[$arr[$i] - $min] != false ) return false; // If visited first time, then mark // the element as visited $visited[$arr[$i] - $min] = true; } // If all elements occur once, // then return true return true; } return false; // if ($max - $min + 1 != $n)} // UTILITY FUNCTIONSfunction getMin($arr, $n){ $min = $arr[0]; for ($i = 1; $i < $n; $i++) if ($arr[$i] < $min) $min = $arr[$i]; return $min;} function getMax($arr, $n){ $max = $arr[0]; for ($i = 1; $i < $n; $i++) if ($arr[$i] > $max) $max = $arr[$i]; return $max;} // Driver Code$arr = array(5, 4, 2, 3, 1, 6);$n = count($arr);if(areConsecutive($arr, $n) == true) echo "Array elements are consecutive ";else echo "Array elements are not consecutive "; // This code is contributed by rathbhupendra?>
<script> /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */ function areConsecutive(arr,n) { if (n < 1) return false; /* 1) Get the minimum element in array */ let min = getMin(arr, n); /* 2) Get the maximum element in array */ let max = getMax(arr, n); /* 3) max - min + 1 is equal to n, then only check all elements */ if (max - min + 1 == n) { /* Create a temp array to hold visited flag of all elements. Note that, calloc is used here so that all values are initialized as false */ let visited = new Array(n); for(let i=0;i<n;i++) { visited[i]=false; } let i; for (i = 0; i < n; i++) { /* If we see an element again, then return false */ if (visited[arr[i] - min] != false) { return false; } /* If visited first time, then mark the element as visited */ visited[arr[i] - min] = true; } /* If all elements occur once, then return true */ return true; } return false; // if (max - min + 1 != n) } /* UTILITY FUNCTIONS */ function getMin(arr, n) { let min = arr[0]; for (let i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; } return min; } function getMax(arr,n) { let max = arr[0]; for (let i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ let arr=[5, 4, 2, 3, 1, 6] let n = arr.length; if (areConsecutive(arr, n)) { document.write("Array elements are consecutive"); } else { document.write("Array elements are not consecutive"); } // This code is contributed by avanitrachhadiya2155 </script>
Array elements are consecutive
Time Complexity: O(n) Extra Space: O(n)
Output:
Array elements are consecutive
Method 3 (Mark visited array elements as negative) This method is O(n) time complexity and O(1) extra space, but it changes the original array, and it works only if all numbers are positive. We can get the original array by adding an extra step though. It is an extension of method 2, and it has the same two steps. 1) max – min + 1 = n where max is the maximum element in the array, min is the minimum element in the array and n is the number of elements in the array. 2) All elements are distinct.In this method, the implementation of step 2 differs from method 2. Instead of creating a new array, we modify the input array arr[] to keep track of visited elements. The idea is to traverse the array and for each index i (where 0 ≤ i < n), make arr[arr[i] – min]] as a negative value. If we see a negative value again then there is repetition.
C++
Java
Python 3
C#
PHP
Javascript
#include<stdio.h>#include<stdlib.h> /* Helper functions to get minimum and maximum in an array */int getMin(int arr[], int n);int getMax(int arr[], int n); /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */bool areConsecutive(int arr[], int n){ if ( n < 1 ) return false; /* 1) Get the minimum element in array */ int min = getMin(arr, n); /* 2) Get the maximum element in array */ int max = getMax(arr, n); /* 3) max - min + 1 is equal to n then only check all elements */ if (max - min + 1 == n) { int i; for(i = 0; i < n; i++) { int j; if (arr[i] < 0) j = -arr[i] - min; else j = arr[i] - min; // if the value at index j is negative then // there is repetition if (arr[j] > 0) arr[j] = -arr[j]; else return false; } /* If we do not see a negative value then all elements are distinct */ return true; } return false; // if (max - min + 1 != n)} /* UTILITY FUNCTIONS */int getMin(int arr[], int n){ int min = arr[0]; for (int i = 1; i < n; i++) if (arr[i] < min) min = arr[i]; return min;} int getMax(int arr[], int n){ int max = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; return max;} /* Driver program to test above functions */int main(){ int arr[]= {1, 4, 5, 3, 2, 6}; int n = sizeof(arr)/sizeof(arr[0]); if(areConsecutive(arr, n) == true) printf(" Array elements are consecutive "); else printf(" Array elements are not consecutive "); getchar(); return 0;}
class AreConsecutive{ /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */ boolean areConsecutive(int arr[], int n) { if (n < 1) return false; /* 1) Get the minimum element in array */ int min = getMin(arr, n); /* 2) Get the maximum element in array */ int max = getMax(arr, n); /* 3) max-min+1 is equal to n then only check all elements */ if (max - min + 1 == n) { int i; for (i = 0; i < n; i++) { int j; if (arr[i] < 0) j = -arr[i] - min; else j = arr[i] - min; // if the value at index j is negative then // there is repetition if (arr[j] > 0) arr[j] = -arr[j]; else return false; } /* If we do not see a negative value then all elements are distinct */ return true; } return false; // if (max-min+1 != n) } /* UTILITY FUNCTIONS */ int getMin(int arr[], int n) { int min = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; } return min; } int getMax(int arr[], int n) { int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ public static void main(String[] args) { AreConsecutive consecutive = new AreConsecutive(); int arr[] = {5, 4, 2, 3, 1, 6}; int n = arr.length; if (consecutive.areConsecutive(arr, n) == true) System.out.println("Array elements are consecutive"); else System.out.println("Array elements are not consecutive"); }} // This code is contributed by Mayank Jaiswal
# Helper functions to get minimum and# maximum in an array # The function checks if the array# elements are consecutive. If elements# are consecutive, then returns true,# else returns falsedef areConsecutive(arr, n): if ( n < 1 ): return False # 1) Get the minimum element in array min = getMin(arr, n) # 2) Get the maximum element in array max = getMax(arr, n) # 3) max - min + 1 is equal to n # then only check all elements if (max - min + 1 == n): for i in range(n): if (arr[i] < 0): j = -arr[i] - min else: j = arr[i] - min # if the value at index j is negative # then there is repetition if (arr[j] > 0): arr[j] = -arr[j] else: return False # If we do not see a negative value # then all elements are distinct return True return False # if (max - min + 1 != n) # UTILITY FUNCTIONSdef getMin(arr, n): min = arr[0] for i in range(1, n): if (arr[i] < min): min = arr[i] return min def getMax(arr, n): max = arr[0] for i in range(1, n): if (arr[i] > max): max = arr[i] return max # Driver Codeif __name__ == "__main__": arr = [1, 4, 5, 3, 2, 6] n = len(arr) if(areConsecutive(arr, n) == True): print(" Array elements are consecutive ") else: print(" Array elements are not consecutive ") # This code is contributed by ita_c
using System; class GFG { /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */ static bool areConsecutive(int []arr, int n) { if (n < 1) return false; /* 1) Get the minimum element in array */ int min = getMin(arr, n); /* 2) Get the maximum element in array */ int max = getMax(arr, n); /* 3) max-min+1 is equal to n then only check all elements */ if (max - min + 1 == n) { int i; for (i = 0; i < n; i++) { int j; if (arr[i] < 0) j = -arr[i] - min; else j = arr[i] - min; // if the value at index j // is negative then // there is repetition if (arr[j] > 0) arr[j] = -arr[j]; else return false; } /* If we do not see a negative value then all elements are distinct */ return true; } // if (max-min+1 != n) return false; } /* UTILITY FUNCTIONS */ static int getMin(int []arr, int n) { int min = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; } return min; } static int getMax(int []arr, int n) { int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ public static void Main() { int []arr = {5, 4, 2, 3, 1, 6}; int n = arr.Length; if (areConsecutive(arr, n) == true) Console.Write("Array elements " + "are consecutive"); else Console.Write("Array elements " + "are not consecutive"); }} // This code is contributed by nitin mittal.
<?php /* The function checks if the array elementsare consecutive If elements are consecutive,then returns true, else returns false */function areConsecutive( $arr, $n){ if ( $n < 1 ) return false; /* 1) Get the minimum element in array */ $min = getMin($arr, $n); /* 2) Get the maximum element in array */ $max = getMax($arr, $n); /* 3) max - min + 1 is equal to n then only check all elements */ if ($max - $min + 1 == $n) { $i; for($i = 0; $i < $n; $i++) { $j; if ($arr[$i] < 0) $j = -$arr[$i] - $min; else $j = $arr[$i] - $min; // if the value at index j is // negative then there is // repetition if ($arr[$j] > 0) $arr[$j] = -$arr[$j]; else return false; } /* If we do not see a negative value then all elements are distinct */ return true; } return false; // if (max - min + 1 != n)} /* UTILITY FUNCTIONS */function getMin( $arr, $n){ $min = $arr[0]; for ( $i = 1; $i < $n; $i++) if ($arr[$i] < $min) $min = $arr[$i]; return $min;} function getMax( $arr, $n){ $max = $arr[0]; for ( $i = 1; $i < $n; $i++) if ($arr[$i] > $max) $max = $arr[$i]; return $max;} /* Driver program to test above functions */ $arr= array(1, 4, 5, 3, 2, 6); $n = count($arr); if(areConsecutive($arr, $n) == true) echo " Array elements are consecutive "; else echo " Array elements are not consecutive "; // This code is contributed by anuj_67.?>
<script> /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */ function areConsecutive(arr,n) { if (n < 1) return false; /* 1) Get the minimum element in array */ let min = getMin(arr, n); /* 2) Get the maximum element in array */ let max = getMax(arr, n); /* 3) max-min+1 is equal to n then only check all elements */ if (max - min + 1 == n) { let i; for (i = 0; i < n; i++) { let j; if (arr[i] < 0) j = -arr[i] - min; else j = arr[i] - min; // if the value at index j is negative then // there is repetition if (arr[j] > 0) arr[j] = -arr[j]; else return false; } /* If we do not see a negative value then all elements are distinct */ return true; } return false; // if (max-min+1 != n) } /* UTILITY FUNCTIONS */ function getMin(arr,n) { let min = arr[0]; for (let i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; } return min; } function getMax(arr,n) { let max = arr[0]; for (let i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ let arr=[5, 4, 2, 3, 1, 6]; let n = arr.length; if (areConsecutive(arr, n) == true) document.write("Array elements are consecutive"); else document.write("Array elements are not consecutive"); // This code is contributed by unknown2108</script>
Array elements are consecutive
Note that this method might not work for negative numbers. For example, it returns false for {2, 1, 0, -3, -1, -2}.Time Complexity: O(n) Extra Space: O(1)
Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers)
Method 4 (Using XOR property)
This method is O(n) time complexity and O(1) extra space, does not changes the original array, and it works everytime.
As elements should be consecutive, let’s find minimum element or maximum element in array.Now if we take xor of two same elements it will result in zero (a^a = 0).Suppose array is {-2, 0, 1, -3, 4, 3, 2, -1}, now if we xor all array elements with minimum element and keep increasing minimum element, the resulting xor will become 0 only if elements are consecutive
As elements should be consecutive, let’s find minimum element or maximum element in array.
Now if we take xor of two same elements it will result in zero (a^a = 0).
Suppose array is {-2, 0, 1, -3, 4, 3, 2, -1}, now if we xor all array elements with minimum element and keep increasing minimum element, the resulting xor will become 0 only if elements are consecutive
C
C++
//Code is contributed by Dhananjay Dhawale @chessnoobdj #include<stdio.h>#include<stdlib.h> /* UTILITY FUNCTIONS */int getMin(int arr[], int n){ int min = arr[0]; for (int i = 1; i < n; i++) if (arr[i] < min) min = arr[i]; return min;}int areConsecutive(int arr[], int n){ int min_ele = getMin(arr, n), num = 0; for(int i=0; i<n; i++){ num ^= min_ele^arr[i]; min_ele += 1; } if(num == 0) return 1; return 0;} /* Driver program to test above functions */int main(){ int arr[]= {1, 4, 5, 3, 2, 6}; int n = sizeof(arr)/sizeof(arr[0]); if(areConsecutive(arr, n) == 1) printf(" Array elements are consecutive "); else printf(" Array elements are not consecutive "); getchar(); return 0;}
//Code is contributed by Dhananjay Dhawale @chessnoobdj #include <iostream>#include <algorithm>using namespace std; bool areConsecutive(int arr[], int n){ int min_ele = *min_element(arr, arr+n), num = 0; for(int i=0; i<n; i++){ num ^= min_ele^arr[i]; min_ele += 1; } if(num == 0) return 1; return 0;} /* Driver program to test above functions */int main(){ int arr[]= {1, 4, 5, 3, 2, 6}; int n = sizeof(arr)/sizeof(arr[0]); if(areConsecutive(arr, n) == true) printf(" Array elements are consecutive "); else printf(" Array elements are not consecutive "); getchar(); return 0;}
Array elements are consecutive
nitin mittal
vt_m
ukasp
rathbhupendra
mohit kumar 29
avanitrachhadiya2155
unknown2108
chessnoobdj
surinderdawra388
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Arrays in Java
Write a program to reverse an array or string
Arrays in C/C++
Program for array rotation
Stack Data Structure (Introduction and Program)
Top 50 Array Coding Problems for Interviews
Largest Sum Contiguous Subarray
Multidimensional Arrays in Java
Introduction to Arrays | [
{
"code": null,
"e": 41274,
"s": 41246,
"text": "\n29 Apr, 2022"
},
{
"code": null,
"e": 41899,
"s": 41274,
"text": "Given an unsorted array of numbers, write a function that returns true if the array consists of consecutive numbers. Examples: a) If the array is {5, 2, 3, 1, 4}, then the function should return true because the array has consecutive numbers from 1 to 5.b) If the array is {83, 78, 80, 81, 79, 82}, then the function should return true because the array has consecutive numbers from 78 to 83.c) If the array is {34, 23, 52, 12, 3}, then the function should return false because the elements are not consecutive.d) If the array is {7, 6, 5, 5, 3, 4}, then the function should return false because 5 and 5 are not consecutive."
},
{
"code": null,
"e": 42698,
"s": 41899,
"text": "Method 1 (Use Sorting) 1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.Time Complexity: O(nLogn)Method 2 (Use visited array) The idea is to check for the following two conditions. If the following two conditions are true, then return true. 1) max – min + 1 = n where max is the maximum element in the array, min is the minimum element in the array and n is the number of elements in the array. 2) All elements are distinct.To check if all elements are distinct, we can create a visited[] array of size n. We can map the ith element of input array arr[] to the visited array by using arr[i] – min as the index in visited[]. "
},
{
"code": null,
"e": 42702,
"s": 42698,
"text": "C++"
},
{
"code": null,
"e": 42707,
"s": 42702,
"text": "Java"
},
{
"code": null,
"e": 42715,
"s": 42707,
"text": "Python3"
},
{
"code": null,
"e": 42718,
"s": 42715,
"text": "C#"
},
{
"code": null,
"e": 42722,
"s": 42718,
"text": "PHP"
},
{
"code": null,
"e": 42733,
"s": 42722,
"text": "Javascript"
},
{
"code": "#include<stdio.h>#include<stdlib.h> /* Helper functions to get minimum and maximum in an array */int getMin(int arr[], int n);int getMax(int arr[], int n); /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */bool areConsecutive(int arr[], int n){ if ( n < 1 ) return false; /* 1) Get the minimum element in array */ int min = getMin(arr, n); /* 2) Get the maximum element in array */ int max = getMax(arr, n); /* 3) max - min + 1 is equal to n, then only check all elements */ if (max - min + 1 == n) { /* Create a temp array to hold visited flag of all elements. Note that, calloc is used here so that all values are initialized as false */ bool *visited = (bool *) calloc (n, sizeof(bool)); int i; for (i = 0; i < n; i++) { /* If we see an element again, then return false */ if ( visited[arr[i] - min] != false ) return false; /* If visited first time, then mark the element as visited */ visited[arr[i] - min] = true; } /* If all elements occur once, then return true */ return true; } return false; // if (max - min + 1 != n)} /* UTILITY FUNCTIONS */int getMin(int arr[], int n){ int min = arr[0]; for (int i = 1; i < n; i++) if (arr[i] < min) min = arr[i]; return min;} int getMax(int arr[], int n){ int max = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; return max;} /* Driver program to test above functions */int main(){ int arr[]= {5, 4, 2, 3, 1, 6}; int n = sizeof(arr)/sizeof(arr[0]); if(areConsecutive(arr, n) == true) printf(\" Array elements are consecutive \"); else printf(\" Array elements are not consecutive \"); getchar(); return 0;}",
"e": 44558,
"s": 42733,
"text": null
},
{
"code": "class AreConsecutive{ /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */ boolean areConsecutive(int arr[], int n) { if (n < 1) return false; /* 1) Get the minimum element in array */ int min = getMin(arr, n); /* 2) Get the maximum element in array */ int max = getMax(arr, n); /* 3) max - min + 1 is equal to n, then only check all elements */ if (max - min + 1 == n) { /* Create a temp array to hold visited flag of all elements. Note that, calloc is used here so that all values are initialized as false */ boolean visited[] = new boolean[n]; int i; for (i = 0; i < n; i++) { /* If we see an element again, then return false */ if (visited[arr[i] - min] != false) return false; /* If visited first time, then mark the element as visited */ visited[arr[i] - min] = true; } /* If all elements occur once, then return true */ return true; } return false; // if (max - min + 1 != n) } /* UTILITY FUNCTIONS */ int getMin(int arr[], int n) { int min = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; } return min; } int getMax(int arr[], int n) { int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ public static void main(String[] args) { AreConsecutive consecutive = new AreConsecutive(); int arr[] = {5, 4, 2, 3, 1, 6}; int n = arr.length; if (consecutive.areConsecutive(arr, n) == true) System.out.println(\"Array elements are consecutive\"); else System.out.println(\"Array elements are not consecutive\"); }} // This code has been contributed by Mayank Jaiswal",
"e": 46742,
"s": 44558,
"text": null
},
{
"code": "# Helper functions to get Minimum and# Maximum in an array # The function checks if the array elements# are consecutive. If elements are consecutive,# then returns true, else returns falsedef areConsecutive(arr, n): if ( n < 1 ): return False # 1) Get the Minimum element in array */ Min = min(arr) # 2) Get the Maximum element in array */ Max = max(arr) # 3) Max - Min + 1 is equal to n, # then only check all elements */ if (Max - Min + 1 == n): # Create a temp array to hold visited # flag of all elements. Note that, calloc # is used here so that all values are # initialized as false visited = [False for i in range(n)] for i in range(n): # If we see an element again, # then return false */ if (visited[arr[i] - Min] != False): return False # If visited first time, then mark # the element as visited */ visited[arr[i] - Min] = True # If all elements occur once, # then return true */ return True return False # if (Max - Min + 1 != n) # Driver Codearr = [5, 4, 2, 3, 1, 6]n = len(arr)if(areConsecutive(arr, n) == True): print(\"Array elements are consecutive \")else: print(\"Array elements are not consecutive \") # This code is contributed by mohit kumar",
"e": 48144,
"s": 46742,
"text": null
},
{
"code": "using System; class GFG { /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */ static bool areConsecutive(int []arr, int n) { if (n < 1) return false; /* 1) Get the minimum element in array */ int min = getMin(arr, n); /* 2) Get the maximum element in array */ int max = getMax(arr, n); /* 3) max - min + 1 is equal to n, then only check all elements */ if (max - min + 1 == n) { /* Create a temp array to hold visited flag of all elements. Note that, calloc is used here so that all values are initialized as false */ bool []visited = new bool[n]; int i; for (i = 0; i < n; i++) { /* If we see an element again, then return false */ if (visited[arr[i] - min] != false) return false; /* If visited first time, then mark the element as visited */ visited[arr[i] - min] = true; } /* If all elements occur once, then return true */ return true; } return false; // if (max - min + 1 != n) } /* UTILITY FUNCTIONS */ static int getMin(int []arr, int n) { int min = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; } return min; } static int getMax(int []arr, int n) { int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ public static void Main() { int []arr = {5, 4, 2, 3, 1, 6}; int n = arr.Length; if (areConsecutive(arr, n) == true) Console.Write(\"Array elements are\" + \" consecutive\"); else Console.Write(\"Array elements are\" + \" not consecutive\"); }} // This code is contributed by nitin mittal.",
"e": 50448,
"s": 48144,
"text": null
},
{
"code": "<?php// PHP Program for above approach // The function checks if the array elements// are consecutive. If elements are consecutive,// then returns true, else returns falsefunction areConsecutive($arr, $n){ if ( $n < 1 ) return false; // 1) Get the minimum element in array $min = getMin($arr, $n); // 2) Get the maximum element in array $max = getMax($arr, $n); // 3) $max - $min + 1 is equal to $n, // then only check all elements if ($max - $min + 1 == $n) { // Create a temp array to hold // visited flag of all elements. $visited = array(); for ($i = 0; $i < $n; $i++) { $visited[$i] = false; } for ($i = 0; $i < $n; $i++) { // If we see an element again, // then return false if ( $visited[$arr[$i] - $min] != false ) return false; // If visited first time, then mark // the element as visited $visited[$arr[$i] - $min] = true; } // If all elements occur once, // then return true return true; } return false; // if ($max - $min + 1 != $n)} // UTILITY FUNCTIONSfunction getMin($arr, $n){ $min = $arr[0]; for ($i = 1; $i < $n; $i++) if ($arr[$i] < $min) $min = $arr[$i]; return $min;} function getMax($arr, $n){ $max = $arr[0]; for ($i = 1; $i < $n; $i++) if ($arr[$i] > $max) $max = $arr[$i]; return $max;} // Driver Code$arr = array(5, 4, 2, 3, 1, 6);$n = count($arr);if(areConsecutive($arr, $n) == true) echo \"Array elements are consecutive \";else echo \"Array elements are not consecutive \"; // This code is contributed by rathbhupendra?>",
"e": 52209,
"s": 50448,
"text": null
},
{
"code": "<script> /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */ function areConsecutive(arr,n) { if (n < 1) return false; /* 1) Get the minimum element in array */ let min = getMin(arr, n); /* 2) Get the maximum element in array */ let max = getMax(arr, n); /* 3) max - min + 1 is equal to n, then only check all elements */ if (max - min + 1 == n) { /* Create a temp array to hold visited flag of all elements. Note that, calloc is used here so that all values are initialized as false */ let visited = new Array(n); for(let i=0;i<n;i++) { visited[i]=false; } let i; for (i = 0; i < n; i++) { /* If we see an element again, then return false */ if (visited[arr[i] - min] != false) { return false; } /* If visited first time, then mark the element as visited */ visited[arr[i] - min] = true; } /* If all elements occur once, then return true */ return true; } return false; // if (max - min + 1 != n) } /* UTILITY FUNCTIONS */ function getMin(arr, n) { let min = arr[0]; for (let i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; } return min; } function getMax(arr,n) { let max = arr[0]; for (let i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ let arr=[5, 4, 2, 3, 1, 6] let n = arr.length; if (areConsecutive(arr, n)) { document.write(\"Array elements are consecutive\"); } else { document.write(\"Array elements are not consecutive\"); } // This code is contributed by avanitrachhadiya2155 </script>",
"e": 54392,
"s": 52209,
"text": null
},
{
"code": null,
"e": 54425,
"s": 54392,
"text": " Array elements are consecutive "
},
{
"code": null,
"e": 54466,
"s": 54425,
"text": "Time Complexity: O(n) Extra Space: O(n) "
},
{
"code": null,
"e": 54474,
"s": 54466,
"text": "Output:"
},
{
"code": null,
"e": 54505,
"s": 54474,
"text": "Array elements are consecutive"
},
{
"code": null,
"e": 55352,
"s": 54505,
"text": "Method 3 (Mark visited array elements as negative) This method is O(n) time complexity and O(1) extra space, but it changes the original array, and it works only if all numbers are positive. We can get the original array by adding an extra step though. It is an extension of method 2, and it has the same two steps. 1) max – min + 1 = n where max is the maximum element in the array, min is the minimum element in the array and n is the number of elements in the array. 2) All elements are distinct.In this method, the implementation of step 2 differs from method 2. Instead of creating a new array, we modify the input array arr[] to keep track of visited elements. The idea is to traverse the array and for each index i (where 0 ≤ i < n), make arr[arr[i] – min]] as a negative value. If we see a negative value again then there is repetition. "
},
{
"code": null,
"e": 55356,
"s": 55352,
"text": "C++"
},
{
"code": null,
"e": 55361,
"s": 55356,
"text": "Java"
},
{
"code": null,
"e": 55370,
"s": 55361,
"text": "Python 3"
},
{
"code": null,
"e": 55373,
"s": 55370,
"text": "C#"
},
{
"code": null,
"e": 55377,
"s": 55373,
"text": "PHP"
},
{
"code": null,
"e": 55388,
"s": 55377,
"text": "Javascript"
},
{
"code": "#include<stdio.h>#include<stdlib.h> /* Helper functions to get minimum and maximum in an array */int getMin(int arr[], int n);int getMax(int arr[], int n); /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */bool areConsecutive(int arr[], int n){ if ( n < 1 ) return false; /* 1) Get the minimum element in array */ int min = getMin(arr, n); /* 2) Get the maximum element in array */ int max = getMax(arr, n); /* 3) max - min + 1 is equal to n then only check all elements */ if (max - min + 1 == n) { int i; for(i = 0; i < n; i++) { int j; if (arr[i] < 0) j = -arr[i] - min; else j = arr[i] - min; // if the value at index j is negative then // there is repetition if (arr[j] > 0) arr[j] = -arr[j]; else return false; } /* If we do not see a negative value then all elements are distinct */ return true; } return false; // if (max - min + 1 != n)} /* UTILITY FUNCTIONS */int getMin(int arr[], int n){ int min = arr[0]; for (int i = 1; i < n; i++) if (arr[i] < min) min = arr[i]; return min;} int getMax(int arr[], int n){ int max = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > max) max = arr[i]; return max;} /* Driver program to test above functions */int main(){ int arr[]= {1, 4, 5, 3, 2, 6}; int n = sizeof(arr)/sizeof(arr[0]); if(areConsecutive(arr, n) == true) printf(\" Array elements are consecutive \"); else printf(\" Array elements are not consecutive \"); getchar(); return 0;}",
"e": 57182,
"s": 55388,
"text": null
},
{
"code": "class AreConsecutive{ /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */ boolean areConsecutive(int arr[], int n) { if (n < 1) return false; /* 1) Get the minimum element in array */ int min = getMin(arr, n); /* 2) Get the maximum element in array */ int max = getMax(arr, n); /* 3) max-min+1 is equal to n then only check all elements */ if (max - min + 1 == n) { int i; for (i = 0; i < n; i++) { int j; if (arr[i] < 0) j = -arr[i] - min; else j = arr[i] - min; // if the value at index j is negative then // there is repetition if (arr[j] > 0) arr[j] = -arr[j]; else return false; } /* If we do not see a negative value then all elements are distinct */ return true; } return false; // if (max-min+1 != n) } /* UTILITY FUNCTIONS */ int getMin(int arr[], int n) { int min = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; } return min; } int getMax(int arr[], int n) { int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ public static void main(String[] args) { AreConsecutive consecutive = new AreConsecutive(); int arr[] = {5, 4, 2, 3, 1, 6}; int n = arr.length; if (consecutive.areConsecutive(arr, n) == true) System.out.println(\"Array elements are consecutive\"); else System.out.println(\"Array elements are not consecutive\"); }} // This code is contributed by Mayank Jaiswal",
"e": 59241,
"s": 57182,
"text": null
},
{
"code": "# Helper functions to get minimum and# maximum in an array # The function checks if the array# elements are consecutive. If elements# are consecutive, then returns true,# else returns falsedef areConsecutive(arr, n): if ( n < 1 ): return False # 1) Get the minimum element in array min = getMin(arr, n) # 2) Get the maximum element in array max = getMax(arr, n) # 3) max - min + 1 is equal to n # then only check all elements if (max - min + 1 == n): for i in range(n): if (arr[i] < 0): j = -arr[i] - min else: j = arr[i] - min # if the value at index j is negative # then there is repetition if (arr[j] > 0): arr[j] = -arr[j] else: return False # If we do not see a negative value # then all elements are distinct return True return False # if (max - min + 1 != n) # UTILITY FUNCTIONSdef getMin(arr, n): min = arr[0] for i in range(1, n): if (arr[i] < min): min = arr[i] return min def getMax(arr, n): max = arr[0] for i in range(1, n): if (arr[i] > max): max = arr[i] return max # Driver Codeif __name__ == \"__main__\": arr = [1, 4, 5, 3, 2, 6] n = len(arr) if(areConsecutive(arr, n) == True): print(\" Array elements are consecutive \") else: print(\" Array elements are not consecutive \") # This code is contributed by ita_c",
"e": 60757,
"s": 59241,
"text": null
},
{
"code": "using System; class GFG { /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */ static bool areConsecutive(int []arr, int n) { if (n < 1) return false; /* 1) Get the minimum element in array */ int min = getMin(arr, n); /* 2) Get the maximum element in array */ int max = getMax(arr, n); /* 3) max-min+1 is equal to n then only check all elements */ if (max - min + 1 == n) { int i; for (i = 0; i < n; i++) { int j; if (arr[i] < 0) j = -arr[i] - min; else j = arr[i] - min; // if the value at index j // is negative then // there is repetition if (arr[j] > 0) arr[j] = -arr[j]; else return false; } /* If we do not see a negative value then all elements are distinct */ return true; } // if (max-min+1 != n) return false; } /* UTILITY FUNCTIONS */ static int getMin(int []arr, int n) { int min = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; } return min; } static int getMax(int []arr, int n) { int max = arr[0]; for (int i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ public static void Main() { int []arr = {5, 4, 2, 3, 1, 6}; int n = arr.Length; if (areConsecutive(arr, n) == true) Console.Write(\"Array elements \" + \"are consecutive\"); else Console.Write(\"Array elements \" + \"are not consecutive\"); }} // This code is contributed by nitin mittal.",
"e": 62860,
"s": 60757,
"text": null
},
{
"code": "<?php /* The function checks if the array elementsare consecutive If elements are consecutive,then returns true, else returns false */function areConsecutive( $arr, $n){ if ( $n < 1 ) return false; /* 1) Get the minimum element in array */ $min = getMin($arr, $n); /* 2) Get the maximum element in array */ $max = getMax($arr, $n); /* 3) max - min + 1 is equal to n then only check all elements */ if ($max - $min + 1 == $n) { $i; for($i = 0; $i < $n; $i++) { $j; if ($arr[$i] < 0) $j = -$arr[$i] - $min; else $j = $arr[$i] - $min; // if the value at index j is // negative then there is // repetition if ($arr[$j] > 0) $arr[$j] = -$arr[$j]; else return false; } /* If we do not see a negative value then all elements are distinct */ return true; } return false; // if (max - min + 1 != n)} /* UTILITY FUNCTIONS */function getMin( $arr, $n){ $min = $arr[0]; for ( $i = 1; $i < $n; $i++) if ($arr[$i] < $min) $min = $arr[$i]; return $min;} function getMax( $arr, $n){ $max = $arr[0]; for ( $i = 1; $i < $n; $i++) if ($arr[$i] > $max) $max = $arr[$i]; return $max;} /* Driver program to test above functions */ $arr= array(1, 4, 5, 3, 2, 6); $n = count($arr); if(areConsecutive($arr, $n) == true) echo \" Array elements are consecutive \"; else echo \" Array elements are not consecutive \"; // This code is contributed by anuj_67.?>",
"e": 64516,
"s": 62860,
"text": null
},
{
"code": "<script> /* The function checks if the array elements are consecutive If elements are consecutive, then returns true, else returns false */ function areConsecutive(arr,n) { if (n < 1) return false; /* 1) Get the minimum element in array */ let min = getMin(arr, n); /* 2) Get the maximum element in array */ let max = getMax(arr, n); /* 3) max-min+1 is equal to n then only check all elements */ if (max - min + 1 == n) { let i; for (i = 0; i < n; i++) { let j; if (arr[i] < 0) j = -arr[i] - min; else j = arr[i] - min; // if the value at index j is negative then // there is repetition if (arr[j] > 0) arr[j] = -arr[j]; else return false; } /* If we do not see a negative value then all elements are distinct */ return true; } return false; // if (max-min+1 != n) } /* UTILITY FUNCTIONS */ function getMin(arr,n) { let min = arr[0]; for (let i = 1; i < n; i++) { if (arr[i] < min) min = arr[i]; } return min; } function getMax(arr,n) { let max = arr[0]; for (let i = 1; i < n; i++) { if (arr[i] > max) max = arr[i]; } return max; } /* Driver program to test above functions */ let arr=[5, 4, 2, 3, 1, 6]; let n = arr.length; if (areConsecutive(arr, n) == true) document.write(\"Array elements are consecutive\"); else document.write(\"Array elements are not consecutive\"); // This code is contributed by unknown2108</script>",
"e": 66441,
"s": 64516,
"text": null
},
{
"code": null,
"e": 66474,
"s": 66441,
"text": " Array elements are consecutive "
},
{
"code": null,
"e": 66631,
"s": 66474,
"text": "Note that this method might not work for negative numbers. For example, it returns false for {2, 1, 0, -3, -1, -2}.Time Complexity: O(n) Extra Space: O(1) "
},
{
"code": null,
"e": 66744,
"s": 66631,
"text": "Check if array elements are consecutive in O(n) time and O(1) space (Handles Both Positive and negative numbers)"
},
{
"code": null,
"e": 66774,
"s": 66744,
"text": "Method 4 (Using XOR property)"
},
{
"code": null,
"e": 66893,
"s": 66774,
"text": "This method is O(n) time complexity and O(1) extra space, does not changes the original array, and it works everytime."
},
{
"code": null,
"e": 67259,
"s": 66893,
"text": "As elements should be consecutive, let’s find minimum element or maximum element in array.Now if we take xor of two same elements it will result in zero (a^a = 0).Suppose array is {-2, 0, 1, -3, 4, 3, 2, -1}, now if we xor all array elements with minimum element and keep increasing minimum element, the resulting xor will become 0 only if elements are consecutive "
},
{
"code": null,
"e": 67350,
"s": 67259,
"text": "As elements should be consecutive, let’s find minimum element or maximum element in array."
},
{
"code": null,
"e": 67424,
"s": 67350,
"text": "Now if we take xor of two same elements it will result in zero (a^a = 0)."
},
{
"code": null,
"e": 67627,
"s": 67424,
"text": "Suppose array is {-2, 0, 1, -3, 4, 3, 2, -1}, now if we xor all array elements with minimum element and keep increasing minimum element, the resulting xor will become 0 only if elements are consecutive "
},
{
"code": null,
"e": 67629,
"s": 67627,
"text": "C"
},
{
"code": null,
"e": 67633,
"s": 67629,
"text": "C++"
},
{
"code": "//Code is contributed by Dhananjay Dhawale @chessnoobdj #include<stdio.h>#include<stdlib.h> /* UTILITY FUNCTIONS */int getMin(int arr[], int n){ int min = arr[0]; for (int i = 1; i < n; i++) if (arr[i] < min) min = arr[i]; return min;}int areConsecutive(int arr[], int n){ int min_ele = getMin(arr, n), num = 0; for(int i=0; i<n; i++){ num ^= min_ele^arr[i]; min_ele += 1; } if(num == 0) return 1; return 0;} /* Driver program to test above functions */int main(){ int arr[]= {1, 4, 5, 3, 2, 6}; int n = sizeof(arr)/sizeof(arr[0]); if(areConsecutive(arr, n) == 1) printf(\" Array elements are consecutive \"); else printf(\" Array elements are not consecutive \"); getchar(); return 0;}",
"e": 68412,
"s": 67633,
"text": null
},
{
"code": "//Code is contributed by Dhananjay Dhawale @chessnoobdj #include <iostream>#include <algorithm>using namespace std; bool areConsecutive(int arr[], int n){ int min_ele = *min_element(arr, arr+n), num = 0; for(int i=0; i<n; i++){ num ^= min_ele^arr[i]; min_ele += 1; } if(num == 0) return 1; return 0;} /* Driver program to test above functions */int main(){ int arr[]= {1, 4, 5, 3, 2, 6}; int n = sizeof(arr)/sizeof(arr[0]); if(areConsecutive(arr, n) == true) printf(\" Array elements are consecutive \"); else printf(\" Array elements are not consecutive \"); getchar(); return 0;}",
"e": 69059,
"s": 68412,
"text": null
},
{
"code": null,
"e": 69092,
"s": 69059,
"text": " Array elements are consecutive "
},
{
"code": null,
"e": 69105,
"s": 69092,
"text": "nitin mittal"
},
{
"code": null,
"e": 69110,
"s": 69105,
"text": "vt_m"
},
{
"code": null,
"e": 69116,
"s": 69110,
"text": "ukasp"
},
{
"code": null,
"e": 69130,
"s": 69116,
"text": "rathbhupendra"
},
{
"code": null,
"e": 69145,
"s": 69130,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 69166,
"s": 69145,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 69178,
"s": 69166,
"text": "unknown2108"
},
{
"code": null,
"e": 69190,
"s": 69178,
"text": "chessnoobdj"
},
{
"code": null,
"e": 69207,
"s": 69190,
"text": "surinderdawra388"
},
{
"code": null,
"e": 69214,
"s": 69207,
"text": "Arrays"
},
{
"code": null,
"e": 69221,
"s": 69214,
"text": "Arrays"
},
{
"code": null,
"e": 69319,
"s": 69221,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 69334,
"s": 69319,
"text": "Arrays in Java"
},
{
"code": null,
"e": 69380,
"s": 69334,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 69396,
"s": 69380,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 69423,
"s": 69396,
"text": "Program for array rotation"
},
{
"code": null,
"e": 69471,
"s": 69423,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 69515,
"s": 69471,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 69547,
"s": 69515,
"text": "Largest Sum Contiguous Subarray"
},
{
"code": null,
"e": 69579,
"s": 69547,
"text": "Multidimensional Arrays in Java"
}
] |
Date validation using Java Regular Expressions | The date can be validated using the java.util.regex.Pattern.matches() method. This method matches the regular expression for the date and the given input date and returns true if they match and false otherwise.
A program that demonstrates this is given as follows:
Live Demo
public class Demo {
public static void main(String args[]) {
String date = "15-11-2018";
String regex = "\\d{1,2}-\\d{1,2}-\\d{4}";
System.out.println("The date is: " + date);
System.out.println("Is the above date valid? " + date.matches(regex));
}
}
The date is: 15-11-2018
Is the above date valid? True
Now let us understand the above program.
The date is printed. The Pattern.matches() method matches the regular expression for the date and the given input date and the result is printed. A code snippet which demonstrates this is as follows:
String date = "15-11-2018";
String regex = "\\d{1,2}-\\d{1,2}-\\d{4}";
System.out.println("The date is: " + date);
System.out.println("Is the above date valid? " + date.matches(regex)); | [
{
"code": null,
"e": 1273,
"s": 1062,
"text": "The date can be validated using the java.util.regex.Pattern.matches() method. This method matches the regular expression for the date and the given input date and returns true if they match and false otherwise."
},
{
"code": null,
"e": 1327,
"s": 1273,
"text": "A program that demonstrates this is given as follows:"
},
{
"code": null,
"e": 1338,
"s": 1327,
"text": " Live Demo"
},
{
"code": null,
"e": 1619,
"s": 1338,
"text": "public class Demo {\n public static void main(String args[]) {\n String date = \"15-11-2018\";\n String regex = \"\\\\d{1,2}-\\\\d{1,2}-\\\\d{4}\";\n System.out.println(\"The date is: \" + date);\n System.out.println(\"Is the above date valid? \" + date.matches(regex));\n }\n}"
},
{
"code": null,
"e": 1673,
"s": 1619,
"text": "The date is: 15-11-2018\nIs the above date valid? True"
},
{
"code": null,
"e": 1714,
"s": 1673,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 1914,
"s": 1714,
"text": "The date is printed. The Pattern.matches() method matches the regular expression for the date and the given input date and the result is printed. A code snippet which demonstrates this is as follows:"
},
{
"code": null,
"e": 2101,
"s": 1914,
"text": "String date = \"15-11-2018\";\nString regex = \"\\\\d{1,2}-\\\\d{1,2}-\\\\d{4}\";\n\nSystem.out.println(\"The date is: \" + date);\nSystem.out.println(\"Is the above date valid? \" + date.matches(regex));"
}
] |
Python PIL | ImageChops.multiply() method | 25 Jun, 2019
PIL.ImageChops.multiply() method superimposes two images on top of each other.If you multiply an image with a solid black image, the result is black. If you multiply with a solid white image, the image is unaffected. At least one of the images must have mode “1”.
Syntax: PIL.ImageChops.multiply(image1, image2)
Parameters:
image1: first image
image2: second image
Return Type: Image
Image1:
Image2:
# Importing Image and ImageChops module from PIL package from PIL import Image, ImageChops # creating a image1 objectim1 = Image.open(r"C:\Users\sadow984\Desktop\i3.PNG") # creating a image2 objectim2 = Image.open(r"C:\Users\sadow984\Desktop\c1.PNG") # applying multiply methodim3 = ImageChops.multiply(im1, im2) im3.show()
Output:
Image3:
Image4:
# Importing Image and ImageChops module from PIL package from PIL import Image, ImageChops # creating a image3 objectim1 = Image.open(r"C:\Users\sadow984\Desktop\a2.PNG") # creating a image4 objectim2 = Image.open(r"C:\Users\sadow984\Desktop\a3.PNG") # applying multiply methodim3 = ImageChops.multiply(im1, im2) im3.show()
Output:
python-utility
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n25 Jun, 2019"
},
{
"code": null,
"e": 292,
"s": 28,
"text": "PIL.ImageChops.multiply() method superimposes two images on top of each other.If you multiply an image with a solid black image, the result is black. If you multiply with a solid white image, the image is unaffected. At least one of the images must have mode “1”."
},
{
"code": null,
"e": 415,
"s": 292,
"text": "Syntax: PIL.ImageChops.multiply(image1, image2)\n\nParameters:\nimage1: first image\nimage2: second image\n\nReturn Type: Image\n"
},
{
"code": null,
"e": 423,
"s": 415,
"text": "Image1:"
},
{
"code": null,
"e": 431,
"s": 423,
"text": "Image2:"
},
{
"code": "# Importing Image and ImageChops module from PIL package from PIL import Image, ImageChops # creating a image1 objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\i3.PNG\") # creating a image2 objectim2 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\c1.PNG\") # applying multiply methodim3 = ImageChops.multiply(im1, im2) im3.show()",
"e": 765,
"s": 431,
"text": null
},
{
"code": null,
"e": 773,
"s": 765,
"text": "Output:"
},
{
"code": null,
"e": 781,
"s": 773,
"text": "Image3:"
},
{
"code": null,
"e": 789,
"s": 781,
"text": "Image4:"
},
{
"code": "# Importing Image and ImageChops module from PIL package from PIL import Image, ImageChops # creating a image3 objectim1 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\a2.PNG\") # creating a image4 objectim2 = Image.open(r\"C:\\Users\\sadow984\\Desktop\\a3.PNG\") # applying multiply methodim3 = ImageChops.multiply(im1, im2) im3.show()",
"e": 1123,
"s": 789,
"text": null
},
{
"code": null,
"e": 1131,
"s": 1123,
"text": "Output:"
},
{
"code": null,
"e": 1146,
"s": 1131,
"text": "python-utility"
},
{
"code": null,
"e": 1153,
"s": 1146,
"text": "Python"
}
] |
Cube in Scaling Animation with ViewPager in Android | 30 Aug, 2021
The Android ViewPager has become a very interesting concept among Android apps. It enables users to switch smoothly between fragments which have a common UI and it’s the best way to make your app extraordinary from others. ViewPagers provide visual continuity. They basically keep track of which page is visible and then ask PageAdapter to display the next page in the hierarchy. Not just this, it even allows you to create all sorts of awesome slide effects and animations!
In this article, we are going to implement cube-in-scaling animation using ViewPager. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language.
There are 3 basic components for the full implementation of ViewPager:
An Activity that contains ViewPager and chief UI.
A set of Fragments that are viewed as separate pages in ViewPager.
FragmentPageAdapter or FragmentStatePageAdapter returns the correct fragment which needs to be displayed next.
For example, refer to the article – ViewPager Using Fragments in Android with Example.
Here, we will make an image slider using ViewPager and then will apply cube-in-scaling-animation.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Designing the UI
Below is the code for the activity_main.xml file. We have added only a ViewPager to show the images. Below is the complete code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- viewpager to show images --> <androidx.viewpager.widget.ViewPager android:id="@+id/viewPagerMain" android:layout_width="match_parent" android:layout_height="match_parent" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
Now, Create a new Layout Resource File item.xml inside the app > res > layout folder. Below is the code of the item.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <!-- image viewer to view the images --> <ImageView android:id="@+id/imageViewMain" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="10dp" android:contentDescription="image" /> </LinearLayout>
Step 3: Working with the ViewPagerAdapter.kt and MainActivity.kt files
First, create a ViewPagerAdapter class, an Adapter for the ViewPager. Below is the complete code of ViewPagerAdapter.kt class. Comments are added inside the code to understand each line of the code.
Kotlin
import android.content.Contextimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.ImageViewimport android.widget.LinearLayoutimport androidx.viewpager.widget.PagerAdapterimport java.util.* internal class ViewPagerAdapter(private val context: Context, private val images: IntArray) : PagerAdapter() { // Layout Inflater var mLayoutInflater: LayoutInflater override fun getCount(): Int { // return the number of images return images.size } init { mLayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater } override fun isViewFromObject(view: View, `object`: Any): Boolean { return view === `object` as LinearLayout } override fun instantiateItem(container: ViewGroup, position: Int): Any { // inflating the item.xml val itemView: View = mLayoutInflater.inflate(R.layout.item, container, false) // referencing the image view from the item.xml file val imageView: ImageView = itemView.findViewById(R.id.imageViewMain) // setting the image in the imageView imageView.setImageResource(images[position]) // Adding the View Objects.requireNonNull(container).addView(itemView) return itemView } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { container.removeView(`object` as LinearLayout) }}
Below is the complete code for the MainActivity.kt file. Comments are added inside the code to understand each line of the code.
Kotlin
import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.viewpager.widget.ViewPager class MainActivity : AppCompatActivity() { // creating object of ViewPager lateinit var mViewPager: ViewPager // images array private var images = intArrayOf(R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4) // Creating Object of ViewPagerAdapter private lateinit var mViewPagerAdapter: ViewPagerAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initializing the ViewPager Object mViewPager = findViewById(R.id.viewPagerMain) mViewPager.setPageTransformer(true, CubeInScalingAnimation()) // Initializing the ViewPagerAdapter mViewPagerAdapter = ViewPagerAdapter(this@MainActivity, images) // Adding the Adapter to the ViewPager mViewPager.adapter = mViewPagerAdapter }}
Step 4: Create a new class CubeInScalingAnimation.kt to apply the Cube-in-scaling-animation. Below is the complete code for the CubeInScalingAnimation.kt file. Comments are added inside the code to understand each line of the code.
Kotlin
import android.view.Viewimport androidx.viewpager.widget.ViewPagerimport kotlin.math.abs class CubeInScalingAnimation : ViewPager.PageTransformer { override fun transformPage(page: View, position: Float) { page.cameraDistance = 20000F when { position < -1 -> { //{-infinity,-1} // page offset to left side page.alpha = 0F } position <= 0 -> { // transition from left // side of page to current page page.alpha = 1F page.pivotX = page.width.toFloat() page.rotationY = 90F * abs(position) } position <= 1 -> { // transition form current // page to right side page.alpha = 1F page.pivotX = 0F page.rotationY = -90F * abs(position) } //{1,+infinity} else -> { //Page offset to right side page.alpha = 0F } } when { // transition between page1 and page2 abs(position) <= 0.5 -> { page.scaleY = Math.max(0.4f, 1 - abs(position)) } abs(position) <= 1 -> { page.scaleY = Math.max(0.4f, abs(position)) } } }}
Now, run the app
Output:
Source Code: Click Here
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android SDK and it's Components
How to Communicate Between Fragments in Android?
Flutter - Custom Bottom Navigation Bar
Retrofit with Kotlin Coroutine in Android
How to Add Views Dynamically and Store Data in Arraylist in Android?
Android UI Layouts
How to Communicate Between Fragments in Android?
Kotlin Array
Retrofit with Kotlin Coroutine in Android | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Aug, 2021"
},
{
"code": null,
"e": 504,
"s": 28,
"text": "The Android ViewPager has become a very interesting concept among Android apps. It enables users to switch smoothly between fragments which have a common UI and it’s the best way to make your app extraordinary from others. ViewPagers provide visual continuity. They basically keep track of which page is visible and then ask PageAdapter to display the next page in the hierarchy. Not just this, it even allows you to create all sorts of awesome slide effects and animations! "
},
{
"code": null,
"e": 757,
"s": 504,
"text": "In this article, we are going to implement cube-in-scaling animation using ViewPager. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Kotlin language. "
},
{
"code": null,
"e": 828,
"s": 757,
"text": "There are 3 basic components for the full implementation of ViewPager:"
},
{
"code": null,
"e": 878,
"s": 828,
"text": "An Activity that contains ViewPager and chief UI."
},
{
"code": null,
"e": 945,
"s": 878,
"text": "A set of Fragments that are viewed as separate pages in ViewPager."
},
{
"code": null,
"e": 1056,
"s": 945,
"text": "FragmentPageAdapter or FragmentStatePageAdapter returns the correct fragment which needs to be displayed next."
},
{
"code": null,
"e": 1143,
"s": 1056,
"text": "For example, refer to the article – ViewPager Using Fragments in Android with Example."
},
{
"code": null,
"e": 1241,
"s": 1143,
"text": "Here, we will make an image slider using ViewPager and then will apply cube-in-scaling-animation."
},
{
"code": null,
"e": 1270,
"s": 1241,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1434,
"s": 1270,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language."
},
{
"code": null,
"e": 1459,
"s": 1434,
"text": "Step 2: Designing the UI"
},
{
"code": null,
"e": 1619,
"s": 1459,
"text": "Below is the code for the activity_main.xml file. We have added only a ViewPager to show the images. Below is the complete code for the activity_main.xml file."
},
{
"code": null,
"e": 1623,
"s": 1619,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- viewpager to show images --> <androidx.viewpager.widget.ViewPager android:id=\"@+id/viewPagerMain\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 2461,
"s": 1623,
"text": null
},
{
"code": null,
"e": 2587,
"s": 2461,
"text": "Now, Create a new Layout Resource File item.xml inside the app > res > layout folder. Below is the code of the item.xml file."
},
{
"code": null,
"e": 2591,
"s": 2587,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\"> <!-- image viewer to view the images --> <ImageView android:id=\"@+id/imageViewMain\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_margin=\"10dp\" android:contentDescription=\"image\" /> </LinearLayout>",
"e": 3070,
"s": 2591,
"text": null
},
{
"code": null,
"e": 3141,
"s": 3070,
"text": "Step 3: Working with the ViewPagerAdapter.kt and MainActivity.kt files"
},
{
"code": null,
"e": 3340,
"s": 3141,
"text": "First, create a ViewPagerAdapter class, an Adapter for the ViewPager. Below is the complete code of ViewPagerAdapter.kt class. Comments are added inside the code to understand each line of the code."
},
{
"code": null,
"e": 3347,
"s": 3340,
"text": "Kotlin"
},
{
"code": "import android.content.Contextimport android.view.LayoutInflaterimport android.view.Viewimport android.view.ViewGroupimport android.widget.ImageViewimport android.widget.LinearLayoutimport androidx.viewpager.widget.PagerAdapterimport java.util.* internal class ViewPagerAdapter(private val context: Context, private val images: IntArray) : PagerAdapter() { // Layout Inflater var mLayoutInflater: LayoutInflater override fun getCount(): Int { // return the number of images return images.size } init { mLayoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater } override fun isViewFromObject(view: View, `object`: Any): Boolean { return view === `object` as LinearLayout } override fun instantiateItem(container: ViewGroup, position: Int): Any { // inflating the item.xml val itemView: View = mLayoutInflater.inflate(R.layout.item, container, false) // referencing the image view from the item.xml file val imageView: ImageView = itemView.findViewById(R.id.imageViewMain) // setting the image in the imageView imageView.setImageResource(images[position]) // Adding the View Objects.requireNonNull(container).addView(itemView) return itemView } override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) { container.removeView(`object` as LinearLayout) }}",
"e": 4817,
"s": 3347,
"text": null
},
{
"code": null,
"e": 4947,
"s": 4817,
"text": " Below is the complete code for the MainActivity.kt file. Comments are added inside the code to understand each line of the code."
},
{
"code": null,
"e": 4954,
"s": 4947,
"text": "Kotlin"
},
{
"code": "import android.os.Bundleimport androidx.appcompat.app.AppCompatActivityimport androidx.viewpager.widget.ViewPager class MainActivity : AppCompatActivity() { // creating object of ViewPager lateinit var mViewPager: ViewPager // images array private var images = intArrayOf(R.drawable.a1, R.drawable.a2, R.drawable.a3, R.drawable.a4) // Creating Object of ViewPagerAdapter private lateinit var mViewPagerAdapter: ViewPagerAdapter override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Initializing the ViewPager Object mViewPager = findViewById(R.id.viewPagerMain) mViewPager.setPageTransformer(true, CubeInScalingAnimation()) // Initializing the ViewPagerAdapter mViewPagerAdapter = ViewPagerAdapter(this@MainActivity, images) // Adding the Adapter to the ViewPager mViewPager.adapter = mViewPagerAdapter }}",
"e": 5944,
"s": 4954,
"text": null
},
{
"code": null,
"e": 6176,
"s": 5944,
"text": "Step 4: Create a new class CubeInScalingAnimation.kt to apply the Cube-in-scaling-animation. Below is the complete code for the CubeInScalingAnimation.kt file. Comments are added inside the code to understand each line of the code."
},
{
"code": null,
"e": 6183,
"s": 6176,
"text": "Kotlin"
},
{
"code": "import android.view.Viewimport androidx.viewpager.widget.ViewPagerimport kotlin.math.abs class CubeInScalingAnimation : ViewPager.PageTransformer { override fun transformPage(page: View, position: Float) { page.cameraDistance = 20000F when { position < -1 -> { //{-infinity,-1} // page offset to left side page.alpha = 0F } position <= 0 -> { // transition from left // side of page to current page page.alpha = 1F page.pivotX = page.width.toFloat() page.rotationY = 90F * abs(position) } position <= 1 -> { // transition form current // page to right side page.alpha = 1F page.pivotX = 0F page.rotationY = -90F * abs(position) } //{1,+infinity} else -> { //Page offset to right side page.alpha = 0F } } when { // transition between page1 and page2 abs(position) <= 0.5 -> { page.scaleY = Math.max(0.4f, 1 - abs(position)) } abs(position) <= 1 -> { page.scaleY = Math.max(0.4f, abs(position)) } } }}",
"e": 7512,
"s": 6183,
"text": null
},
{
"code": null,
"e": 7529,
"s": 7512,
"text": "Now, run the app"
},
{
"code": null,
"e": 7537,
"s": 7529,
"text": "Output:"
},
{
"code": null,
"e": 7561,
"s": 7537,
"text": "Source Code: Click Here"
},
{
"code": null,
"e": 7569,
"s": 7561,
"text": "Android"
},
{
"code": null,
"e": 7576,
"s": 7569,
"text": "Kotlin"
},
{
"code": null,
"e": 7584,
"s": 7576,
"text": "Android"
},
{
"code": null,
"e": 7682,
"s": 7584,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7751,
"s": 7682,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 7783,
"s": 7751,
"text": "Android SDK and it's Components"
},
{
"code": null,
"e": 7832,
"s": 7783,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 7871,
"s": 7832,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 7913,
"s": 7871,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 7982,
"s": 7913,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 8001,
"s": 7982,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 8050,
"s": 8001,
"text": "How to Communicate Between Fragments in Android?"
},
{
"code": null,
"e": 8063,
"s": 8050,
"text": "Kotlin Array"
}
] |
Python | Program to download complete Youtube playlist | 18 Aug, 2021
Python is a multi-purpose programming language and is widely used for scripting small tasks. Let’s see how to make your own Youtube Playlist Downloader using Python. Though there are many software available in the market but making your own serving that purpose is quite a learning and impressive as well.
Modules needed:
BeautifulSoup bs4
PyQt5
PyQtWebEngine
sys module
urllib module
pytube module
From the given URL of a YouTube playlist, our program will perform web scraping and fetch all the YouTube video links and append it under a links array. Then using the pytube library we will download the corresponding YouTube videos from the link in the links array. The parameters for downloading the YouTube video (quality, mime_type, etc) can be specified in the streams constructor. The videos will be downloaded with the name of the original video.
Let’s see the code:
Python3
# Importing librariesimport bs4 as bsimport sysimport urllib.requestfrom PyQt5.QtWebEngineWidgets import QWebEnginePagefrom PyQt5.QtWidgets import QApplicationfrom PyQt5.QtCore import QUrlimport pytube # library for downloading youtube videos class Page(QWebEnginePage): def __init__(self, url): self.app = QApplication(sys.argv) QWebEnginePage.__init__(self) self.html = '' self.loadFinished.connect(self._on_load_finished) self.load(QUrl(url)) self.app.exec_() def _on_load_finished(self): self.html = self.toHtml(self.Callable) print('Load finished') def Callable(self, html_str): self.html = html_str self.app.quit() links = [] def exact_link(link): vid_id = link.split('=') # print(vid_id) str = "" for i in vid_id[0:2]: str += i + "=" str_new = str[0:len(str) - 1] index = str_new.find("&") new_link = "https://www.youtube.com" + str_new[0:index] return new_link url = "https://www.youtube.com/watch?v=lcJzw0JGfeE&list=PLqM7alHXFySENpNgw27MzGxLzNJuC_Kdj"# Scraping and extracting the video# links from the given playlist urlpage = Page(url)count = 0 soup = bs.BeautifulSoup(page.html, 'html.parser')for link in soup.find_all('a', id='thumbnail'): # not using first link because it is # playlist link not particular video link if count == 0: count += 1 continue else: try: # Prevents error for links with no href. vid_src = link['href'] # print(vid_src) # keeping the format of link to be # given to pytube otherwise in some cases new_link = exact_link(vid_src) # error might occur due to this # print(new_link) # appending the link to the links array links.append(new_link) except Exception as exp: pass # No function necessary for invalid <a> tags. # print(links) # downloading each video from# the link in the links arrayfor link in links: yt = pytube.YouTube(link) # Downloaded video will be the best quality video stream = yt.streams.filter(progressive=True, file_extension='mp4').order_by( 'resolution').desc().first() try: stream.download() # printing the links downloaded print("Downloaded: ", link) except: print('Some error in downloading: ', link)
Output:
ronakjalan98
python-utility
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
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n18 Aug, 2021"
},
{
"code": null,
"e": 360,
"s": 53,
"text": "Python is a multi-purpose programming language and is widely used for scripting small tasks. Let’s see how to make your own Youtube Playlist Downloader using Python. Though there are many software available in the market but making your own serving that purpose is quite a learning and impressive as well. "
},
{
"code": null,
"e": 376,
"s": 360,
"text": "Modules needed:"
},
{
"code": null,
"e": 394,
"s": 376,
"text": "BeautifulSoup bs4"
},
{
"code": null,
"e": 400,
"s": 394,
"text": "PyQt5"
},
{
"code": null,
"e": 414,
"s": 400,
"text": "PyQtWebEngine"
},
{
"code": null,
"e": 425,
"s": 414,
"text": "sys module"
},
{
"code": null,
"e": 439,
"s": 425,
"text": "urllib module"
},
{
"code": null,
"e": 453,
"s": 439,
"text": "pytube module"
},
{
"code": null,
"e": 909,
"s": 453,
"text": "From the given URL of a YouTube playlist, our program will perform web scraping and fetch all the YouTube video links and append it under a links array. Then using the pytube library we will download the corresponding YouTube videos from the link in the links array. The parameters for downloading the YouTube video (quality, mime_type, etc) can be specified in the streams constructor. The videos will be downloaded with the name of the original video. "
},
{
"code": null,
"e": 930,
"s": 909,
"text": "Let’s see the code: "
},
{
"code": null,
"e": 938,
"s": 930,
"text": "Python3"
},
{
"code": "# Importing librariesimport bs4 as bsimport sysimport urllib.requestfrom PyQt5.QtWebEngineWidgets import QWebEnginePagefrom PyQt5.QtWidgets import QApplicationfrom PyQt5.QtCore import QUrlimport pytube # library for downloading youtube videos class Page(QWebEnginePage): def __init__(self, url): self.app = QApplication(sys.argv) QWebEnginePage.__init__(self) self.html = '' self.loadFinished.connect(self._on_load_finished) self.load(QUrl(url)) self.app.exec_() def _on_load_finished(self): self.html = self.toHtml(self.Callable) print('Load finished') def Callable(self, html_str): self.html = html_str self.app.quit() links = [] def exact_link(link): vid_id = link.split('=') # print(vid_id) str = \"\" for i in vid_id[0:2]: str += i + \"=\" str_new = str[0:len(str) - 1] index = str_new.find(\"&\") new_link = \"https://www.youtube.com\" + str_new[0:index] return new_link url = \"https://www.youtube.com/watch?v=lcJzw0JGfeE&list=PLqM7alHXFySENpNgw27MzGxLzNJuC_Kdj\"# Scraping and extracting the video# links from the given playlist urlpage = Page(url)count = 0 soup = bs.BeautifulSoup(page.html, 'html.parser')for link in soup.find_all('a', id='thumbnail'): # not using first link because it is # playlist link not particular video link if count == 0: count += 1 continue else: try: # Prevents error for links with no href. vid_src = link['href'] # print(vid_src) # keeping the format of link to be # given to pytube otherwise in some cases new_link = exact_link(vid_src) # error might occur due to this # print(new_link) # appending the link to the links array links.append(new_link) except Exception as exp: pass # No function necessary for invalid <a> tags. # print(links) # downloading each video from# the link in the links arrayfor link in links: yt = pytube.YouTube(link) # Downloaded video will be the best quality video stream = yt.streams.filter(progressive=True, file_extension='mp4').order_by( 'resolution').desc().first() try: stream.download() # printing the links downloaded print(\"Downloaded: \", link) except: print('Some error in downloading: ', link)",
"e": 3368,
"s": 938,
"text": null
},
{
"code": null,
"e": 3378,
"s": 3368,
"text": "Output: "
},
{
"code": null,
"e": 3393,
"s": 3380,
"text": "ronakjalan98"
},
{
"code": null,
"e": 3408,
"s": 3393,
"text": "python-utility"
},
{
"code": null,
"e": 3415,
"s": 3408,
"text": "Python"
},
{
"code": null,
"e": 3513,
"s": 3415,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3531,
"s": 3513,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3573,
"s": 3531,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3595,
"s": 3573,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3630,
"s": 3595,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3656,
"s": 3630,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3688,
"s": 3656,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3717,
"s": 3688,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3744,
"s": 3717,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3774,
"s": 3744,
"text": "Iterate over a list in Python"
}
] |
How to create a Face Detection Android App using Machine Learning KIT on Firebase | 24 Jun, 2021
Pre-requisites:
Firebase Machine Learning kit
Adding Firebase to Android App
Firebase ML KIT aims to make machine learning more accessible, by providing a range of pre-trained models that can use in the iOS and Android apps. Let’s use ML Kit’s Face Detection API which will identify faces in photos. By the end of this article, we’ll have an app that can identify faces in an image, and then display information about these faces, such as whether the person is smiling, or has their eyes closed with wonderful GUI.
Step 1: Create a New Project
Open a new project in android studio with whatever name you want.We are gonna work with empty activity for the particular project.The minimum SDK required for this particular project is 23, so choose any API of 23 or above.The language used for this project would be JAVA.Leave all the options other than those mentioned above, untouched.Click on FINISH.
Open a new project in android studio with whatever name you want.
We are gonna work with empty activity for the particular project.
The minimum SDK required for this particular project is 23, so choose any API of 23 or above.
The language used for this project would be JAVA.
Leave all the options other than those mentioned above, untouched.
Click on FINISH.
Step 2: Connect with ML KIT on Firebase.
Login or signup on Firebase.In Firebase console, create a new project or if you wanna work with an existing project then open that.Name the project as per your choice.Go to Docs.Click on Firebase ML, and in the left space, choose ‘recognize text‘ under Vision.Go through the steps mentioned for better understanding.Come back to Android Studio.Go to Tools -> Firebase -> Analytics -> Connect with Firebase -> Choose your project from the dialog box appeared -> Click Connect. (This step connects your android app to the Firebase)
Login or signup on Firebase.
In Firebase console, create a new project or if you wanna work with an existing project then open that.
Name the project as per your choice.
Go to Docs.
Click on Firebase ML, and in the left space, choose ‘recognize text‘ under Vision.
Go through the steps mentioned for better understanding.
Come back to Android Studio.
Go to Tools -> Firebase -> Analytics -> Connect with Firebase -> Choose your project from the dialog box appeared -> Click Connect. (This step connects your android app to the Firebase)
Step 3: Custom Assets and Gradle
For enhancing the GUI either choose an image of .png format and add it in the res folder and set it as the background of main .xml file, or set a background color by going to the design view of the layout and customizing background under Declared Attributes as shown below:
To, include the ML KIT dependencies, in the app, go to Gradle Script -> build.gradle(Module:app) and add an implementation mentioned below:
implementation ‘com.google.firebase:firebase-ml-vision:17.0.0’
Now copy the below-mentioned text, and paste it at the very end of the app level Gradle, outside all the brackets as shown in the image below.
apply plugin: ‘com.google.gms.google-services’
Next, go to build.gradle (project) and copy the below-mentioned text, and paste it in ‘dependencies’ classpath as shown in the image below.
classpath ‘com.google.gms:google-services:4.2.0’
Click on sync now.
Step 4: Designing the UI
Below is the code for the basic XML file. Add a Button to open the camera option.
XML
<?xml version="1.0" encoding="UTF-8"?><androidx.constraintlayout.widget.ConstraintLayout tools:context=".MainActivity" android:layout_height="match_parent" android:layout_width="match_parent" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android"> <Button android:background="#000000" android:layout_height="wrap_content" android:layout_width="wrap_content" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:text=CAMERA android:layout_marginBottom="100dp" android:padding="16dp" android:id="@+id/camera_button"/></androidx.constraintlayout.widget.ConstraintLayout>
Now the UI will look like this.
Now go to layout -> new -> layout resource file -> Name: fragment_resultdialog.xml. This file has been created to customize the output screen, which will display a dialog box called Result Dialog box with a text view called Result Text with all the attributes of the detected image. Below is the XML file for the XML file created.
XML
<?xml version="1.0" encoding="UTF-8"?><androidx.constraintlayout.widget.ConstraintLayout android:layout_height="match_parent" android:layout_width="match_parent" xmlns:tools="http://schemas.android.com/tools" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:android="http://schemas.android.com/apk/res/android"> <ScrollView android:layout_width="wrap_content" android:layout_height="wrap_content" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <RelativeLayout android:id="@+id/relativeLayout" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginStart="20dp" android:layout_marginEnd="20dp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"> <!--text view to display the result text after reading an image--> <TextView android:id="@+id/result_text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:gravity="center" android:text="LCOFaceDetection" android:textColor="#000000" android:textSize="18sp" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toTopOf="parent"/> <!--a button with text 'ok' written on it--> <Button android:id="@+id/result_ok_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@id/result_text_view" android:layout_centerInParent="true" android:layout_marginTop="20dp" android:layout_marginBottom="5dp" android:background="#75DA8B" android:padding="16dp" android:text="ok" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintStart_toStartOf="parent" app:layout_constraintTop_toBottomOf="@+id/result_text_view"/> </RelativeLayout> </ScrollView> </androidx.constraintlayout.widget.ConstraintLayout>
Step 5: Firebase App Initializer
Create a new java class by java -> new -> class -> Name: LCOFaceDetection.java -> superclass: Application(android.app.Application). Below is the example source code for the java class.
Java
import android.app.Application;import com.google.firebase.FirebaseApp; public class LCOFaceDetection extends Application { public final static String RESULT_TEXT = "RESULT_TEXT"; public final static String RESULT_DIALOG = "RESULT_DIALOG"; // initializing our firebase @Override public void onCreate() { super.onCreate(); FirebaseApp.initializeApp(this); }}
Step 6: Inflating the Result Dialog Box
Create a new java class namely, ResultDialog.java and superclass, DialogFragment, which is the java file for the fragment_resultdialog.xml. Below is the example code for java file.
Java
import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.DialogFragment; public class ResultDialog extends DialogFragment { Button okBtn; TextView resultTextView; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // importing View so as to inflate // the layout of our result dialog // using layout inflater. View view = inflater.inflate( R.layout.fragment_resultdialog, container, false); String resultText = ""; // finding the elements by their id's. okBtn = view.findViewById(R.id.result_ok_button); resultTextView = view.findViewById(R.id.result_text_view); // To get the result text // after final face detection // and append it to the text view. Bundle bundle = getArguments(); resultText = bundle.getString( LCOFaceDetection.RESULT_TEXT); resultTextView.setText(resultText); // Onclick listener so as // to make a dismissable button okBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); return view; }}
Step 7: Open Camera on a Real Device and Enabling Face Detection
Below is the example code for the main java file.
There is a need of FirebaseVision and FirebaseVisionFaceDetector classes for this.
Here’s a list of all the settings you can configure in your face detection model.
FAST (default) | ACCURATE
Favor speed or accuracy when detecting faces.
NO_LANDMARKS (default) | ALL_LANDMARKS
Whether to attempt to identify facial “landmarks”:
eyes, ears, nose, cheeks, mouth, and so on.
NO_CONTOURS (default) | ALL_CONTOURS
Whether to detect the contours of facial features.
Contours are detected for only the most prominent face in an image.
NO_CLASSIFICATIONS (default) | ALL_CLASSIFICATIONS
Whether or not to classify faces into categories
such as “smiling”, and “eyes open”.
float (default: 0.1f )
The minimum size, relative to the image, of faces to detect.
false (default) | true
Whether or not to assign faces an ID, which
can be used to track faces across images.
Note that when contour detection is enabled,
only one face is detected, so face tracking doesn’t
produce useful results. For this reason, and to improve
detection speed, don’t enable both contour detection and face tracking.
It is suggested to read a detailed analysis of these classes and work on the code at the Firebase ML docs for text recognition.
Java
/*package whatever do not write package name here*/ import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.fragment.app.DialogFragment;import android.content.Intent;import android.graphics.Bitmap;import android.os.Bundle;import android.provider.MediaStore;import android.view.View;import android.widget.Button;import android.widget.Toast;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.FirebaseApp;import com.google.firebase.ml.vision.FirebaseVision;import com.google.firebase.ml.vision.common.FirebaseVisionImage;import com.google.firebase.ml.vision.common.FirebaseVisionPoint;import com.google.firebase.ml.vision.face.FirebaseVisionFace;import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetector;import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions;import com.google.firebase.ml.vision.face.FirebaseVisionFaceLandmark;import java.util.List; public class MainActivity extends AppCompatActivity { Button cameraButton; // whenever we request for our customized permission, we // need to declare an integer and initialize it to some // value . private final static int REQUEST_IMAGE_CAPTURE = 124; FirebaseVisionImage image; FirebaseVisionFaceDetector detector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our firebase in main activity FirebaseApp.initializeApp(this); // finding the elements by their id's alloted. cameraButton = findViewById(R.id.camera_button); // setting an onclick listener to the button so as // to request image capture using camera cameraButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // makin a new intent for opening camera Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); if (intent.resolveActivity( getPackageManager()) != null) { startActivityForResult( intent, REQUEST_IMAGE_CAPTURE); } else { // if the image is not captured, set // a toast to display an error image. Toast .makeText( MainActivity.this, "Something went wrong", Toast.LENGTH_SHORT) .show(); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { // after the image is captured, ML Kit provides an // easy way to detect faces from variety of image // types like Bitmap super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extra = data.getExtras(); Bitmap bitmap = (Bitmap)extra.get("data"); detectFace(bitmap); } } // If you want to configure your face detection model // according to your needs, you can do that with a // FirebaseVisionFaceDetectorOptions object. private void detectFace(Bitmap bitmap) { FirebaseVisionFaceDetectorOptions options = new FirebaseVisionFaceDetectorOptions .Builder() .setModeType( FirebaseVisionFaceDetectorOptions .ACCURATE_MODE) .setLandmarkType( FirebaseVisionFaceDetectorOptions .ALL_LANDMARKS) .setClassificationType( FirebaseVisionFaceDetectorOptions .ALL_CLASSIFICATIONS) .build(); // we need to create a FirebaseVisionImage object // from the above mentioned image types(bitmap in // this case) and pass it to the model. try { image = FirebaseVisionImage.fromBitmap(bitmap); detector = FirebaseVision.getInstance() .getVisionFaceDetector(options); } catch (Exception e) { e.printStackTrace(); } // It’s time to prepare our Face Detection model. detector.detectInImage(image) .addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionFace> >() { @Override // adding an onSuccess Listener, i.e, in case // our image is successfully detected, it will // append it's attribute to the result // textview in result dialog box. public void onSuccess( List<FirebaseVisionFace> firebaseVisionFaces) { String resultText = ""; int i = 1; for (FirebaseVisionFace face : firebaseVisionFaces) { resultText = resultText .concat("\nFACE NUMBER. " + i + ": ") .concat( "\nSmile: " + face.getSmilingProbability() * 100 + "%") .concat( "\nleft eye open: " + face.getLeftEyeOpenProbability() * 100 + "%") .concat( "\nright eye open " + face.getRightEyeOpenProbability() * 100 + "%"); i++; } // if no face is detected, give a toast // message. if (firebaseVisionFaces.size() == 0) { Toast .makeText(MainActivity.this, "NO FACE DETECT", Toast.LENGTH_SHORT) .show(); } else { Bundle bundle = new Bundle(); bundle.putString( LCOFaceDetection.RESULT_TEXT, resultText); DialogFragment resultDialog = new ResultDialog(); resultDialog.setArguments(bundle); resultDialog.setCancelable(true); resultDialog.show( getSupportFragmentManager(), LCOFaceDetection.RESULT_DIALOG); } } }) // adding an onfailure listener as well if // something goes wrong. .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast .makeText( MainActivity.this, "Oops, Something went wrong", Toast.LENGTH_SHORT) .show(); } }); }}
as5853535
arorakashish0911
android
Java
Machine Learning
Java
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
ArrayList in Java
Collections in Java
Multidimensional Arrays in Java
Stream In Java
Naive Bayes Classifiers
ML | Linear Regression
Linear Regression (Python Implementation)
Reinforcement learning
Agents in Artificial Intelligence | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Jun, 2021"
},
{
"code": null,
"e": 70,
"s": 54,
"text": "Pre-requisites:"
},
{
"code": null,
"e": 100,
"s": 70,
"text": "Firebase Machine Learning kit"
},
{
"code": null,
"e": 131,
"s": 100,
"text": "Adding Firebase to Android App"
},
{
"code": null,
"e": 569,
"s": 131,
"text": "Firebase ML KIT aims to make machine learning more accessible, by providing a range of pre-trained models that can use in the iOS and Android apps. Let’s use ML Kit’s Face Detection API which will identify faces in photos. By the end of this article, we’ll have an app that can identify faces in an image, and then display information about these faces, such as whether the person is smiling, or has their eyes closed with wonderful GUI."
},
{
"code": null,
"e": 598,
"s": 569,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 953,
"s": 598,
"text": "Open a new project in android studio with whatever name you want.We are gonna work with empty activity for the particular project.The minimum SDK required for this particular project is 23, so choose any API of 23 or above.The language used for this project would be JAVA.Leave all the options other than those mentioned above, untouched.Click on FINISH."
},
{
"code": null,
"e": 1019,
"s": 953,
"text": "Open a new project in android studio with whatever name you want."
},
{
"code": null,
"e": 1085,
"s": 1019,
"text": "We are gonna work with empty activity for the particular project."
},
{
"code": null,
"e": 1179,
"s": 1085,
"text": "The minimum SDK required for this particular project is 23, so choose any API of 23 or above."
},
{
"code": null,
"e": 1229,
"s": 1179,
"text": "The language used for this project would be JAVA."
},
{
"code": null,
"e": 1296,
"s": 1229,
"text": "Leave all the options other than those mentioned above, untouched."
},
{
"code": null,
"e": 1313,
"s": 1296,
"text": "Click on FINISH."
},
{
"code": null,
"e": 1354,
"s": 1313,
"text": "Step 2: Connect with ML KIT on Firebase."
},
{
"code": null,
"e": 1884,
"s": 1354,
"text": "Login or signup on Firebase.In Firebase console, create a new project or if you wanna work with an existing project then open that.Name the project as per your choice.Go to Docs.Click on Firebase ML, and in the left space, choose ‘recognize text‘ under Vision.Go through the steps mentioned for better understanding.Come back to Android Studio.Go to Tools -> Firebase -> Analytics -> Connect with Firebase -> Choose your project from the dialog box appeared -> Click Connect. (This step connects your android app to the Firebase)"
},
{
"code": null,
"e": 1913,
"s": 1884,
"text": "Login or signup on Firebase."
},
{
"code": null,
"e": 2017,
"s": 1913,
"text": "In Firebase console, create a new project or if you wanna work with an existing project then open that."
},
{
"code": null,
"e": 2054,
"s": 2017,
"text": "Name the project as per your choice."
},
{
"code": null,
"e": 2066,
"s": 2054,
"text": "Go to Docs."
},
{
"code": null,
"e": 2149,
"s": 2066,
"text": "Click on Firebase ML, and in the left space, choose ‘recognize text‘ under Vision."
},
{
"code": null,
"e": 2206,
"s": 2149,
"text": "Go through the steps mentioned for better understanding."
},
{
"code": null,
"e": 2235,
"s": 2206,
"text": "Come back to Android Studio."
},
{
"code": null,
"e": 2421,
"s": 2235,
"text": "Go to Tools -> Firebase -> Analytics -> Connect with Firebase -> Choose your project from the dialog box appeared -> Click Connect. (This step connects your android app to the Firebase)"
},
{
"code": null,
"e": 2454,
"s": 2421,
"text": "Step 3: Custom Assets and Gradle"
},
{
"code": null,
"e": 2729,
"s": 2454,
"text": "For enhancing the GUI either choose an image of .png format and add it in the res folder and set it as the background of main .xml file, or set a background color by going to the design view of the layout and customizing background under Declared Attributes as shown below:"
},
{
"code": null,
"e": 2869,
"s": 2729,
"text": "To, include the ML KIT dependencies, in the app, go to Gradle Script -> build.gradle(Module:app) and add an implementation mentioned below:"
},
{
"code": null,
"e": 2932,
"s": 2869,
"text": "implementation ‘com.google.firebase:firebase-ml-vision:17.0.0’"
},
{
"code": null,
"e": 3077,
"s": 2934,
"text": "Now copy the below-mentioned text, and paste it at the very end of the app level Gradle, outside all the brackets as shown in the image below."
},
{
"code": null,
"e": 3125,
"s": 3077,
"text": "apply plugin: ‘com.google.gms.google-services’ "
},
{
"code": null,
"e": 3265,
"s": 3125,
"text": "Next, go to build.gradle (project) and copy the below-mentioned text, and paste it in ‘dependencies’ classpath as shown in the image below."
},
{
"code": null,
"e": 3315,
"s": 3265,
"text": "classpath ‘com.google.gms:google-services:4.2.0’ "
},
{
"code": null,
"e": 3334,
"s": 3315,
"text": "Click on sync now."
},
{
"code": null,
"e": 3359,
"s": 3334,
"text": "Step 4: Designing the UI"
},
{
"code": null,
"e": 3441,
"s": 3359,
"text": "Below is the code for the basic XML file. Add a Button to open the camera option."
},
{
"code": null,
"e": 3445,
"s": 3441,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><androidx.constraintlayout.widget.ConstraintLayout tools:context=\".MainActivity\" android:layout_height=\"match_parent\" android:layout_width=\"match_parent\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:android=\"http://schemas.android.com/apk/res/android\"> <Button android:background=\"#000000\" android:layout_height=\"wrap_content\" android:layout_width=\"wrap_content\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintBottom_toBottomOf=\"parent\" android:text=CAMERA android:layout_marginBottom=\"100dp\" android:padding=\"16dp\" android:id=\"@+id/camera_button\"/></androidx.constraintlayout.widget.ConstraintLayout>",
"e": 4299,
"s": 3445,
"text": null
},
{
"code": null,
"e": 4334,
"s": 4302,
"text": "Now the UI will look like this."
},
{
"code": null,
"e": 4665,
"s": 4334,
"text": "Now go to layout -> new -> layout resource file -> Name: fragment_resultdialog.xml. This file has been created to customize the output screen, which will display a dialog box called Result Dialog box with a text view called Result Text with all the attributes of the detected image. Below is the XML file for the XML file created."
},
{
"code": null,
"e": 4671,
"s": 4667,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"UTF-8\"?><androidx.constraintlayout.widget.ConstraintLayout android:layout_height=\"match_parent\" android:layout_width=\"match_parent\" xmlns:tools=\"http://schemas.android.com/tools\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:android=\"http://schemas.android.com/apk/res/android\"> <ScrollView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <RelativeLayout android:id=\"@+id/relativeLayout\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginStart=\"20dp\" android:layout_marginEnd=\"20dp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"> <!--text view to display the result text after reading an image--> <TextView android:id=\"@+id/result_text_view\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:gravity=\"center\" android:text=\"LCOFaceDetection\" android:textColor=\"#000000\" android:textSize=\"18sp\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\"/> <!--a button with text 'ok' written on it--> <Button android:id=\"@+id/result_ok_button\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:layout_below=\"@id/result_text_view\" android:layout_centerInParent=\"true\" android:layout_marginTop=\"20dp\" android:layout_marginBottom=\"5dp\" android:background=\"#75DA8B\" android:padding=\"16dp\" android:text=\"ok\" app:layout_constraintEnd_toEndOf=\"parent\" app:layout_constraintStart_toStartOf=\"parent\" app:layout_constraintTop_toBottomOf=\"@+id/result_text_view\"/> </RelativeLayout> </ScrollView> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 7171,
"s": 4671,
"text": null
},
{
"code": null,
"e": 7207,
"s": 7174,
"text": "Step 5: Firebase App Initializer"
},
{
"code": null,
"e": 7394,
"s": 7209,
"text": "Create a new java class by java -> new -> class -> Name: LCOFaceDetection.java -> superclass: Application(android.app.Application). Below is the example source code for the java class."
},
{
"code": null,
"e": 7401,
"s": 7396,
"text": "Java"
},
{
"code": "import android.app.Application;import com.google.firebase.FirebaseApp; public class LCOFaceDetection extends Application { public final static String RESULT_TEXT = \"RESULT_TEXT\"; public final static String RESULT_DIALOG = \"RESULT_DIALOG\"; // initializing our firebase @Override public void onCreate() { super.onCreate(); FirebaseApp.initializeApp(this); }}",
"e": 7794,
"s": 7401,
"text": null
},
{
"code": null,
"e": 7837,
"s": 7797,
"text": "Step 6: Inflating the Result Dialog Box"
},
{
"code": null,
"e": 8020,
"s": 7839,
"text": "Create a new java class namely, ResultDialog.java and superclass, DialogFragment, which is the java file for the fragment_resultdialog.xml. Below is the example code for java file."
},
{
"code": null,
"e": 8027,
"s": 8022,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.Button;import android.widget.TextView;import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.fragment.app.DialogFragment; public class ResultDialog extends DialogFragment { Button okBtn; TextView resultTextView; @Nullable @Override public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // importing View so as to inflate // the layout of our result dialog // using layout inflater. View view = inflater.inflate( R.layout.fragment_resultdialog, container, false); String resultText = \"\"; // finding the elements by their id's. okBtn = view.findViewById(R.id.result_ok_button); resultTextView = view.findViewById(R.id.result_text_view); // To get the result text // after final face detection // and append it to the text view. Bundle bundle = getArguments(); resultText = bundle.getString( LCOFaceDetection.RESULT_TEXT); resultTextView.setText(resultText); // Onclick listener so as // to make a dismissable button okBtn.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); return view; }}",
"e": 9645,
"s": 8027,
"text": null
},
{
"code": null,
"e": 9713,
"s": 9648,
"text": "Step 7: Open Camera on a Real Device and Enabling Face Detection"
},
{
"code": null,
"e": 9765,
"s": 9715,
"text": "Below is the example code for the main java file."
},
{
"code": null,
"e": 9848,
"s": 9765,
"text": "There is a need of FirebaseVision and FirebaseVisionFaceDetector classes for this."
},
{
"code": null,
"e": 9930,
"s": 9848,
"text": "Here’s a list of all the settings you can configure in your face detection model."
},
{
"code": null,
"e": 9956,
"s": 9930,
"text": "FAST (default) | ACCURATE"
},
{
"code": null,
"e": 10002,
"s": 9956,
"text": "Favor speed or accuracy when detecting faces."
},
{
"code": null,
"e": 10041,
"s": 10002,
"text": "NO_LANDMARKS (default) | ALL_LANDMARKS"
},
{
"code": null,
"e": 10093,
"s": 10041,
"text": "Whether to attempt to identify facial “landmarks”: "
},
{
"code": null,
"e": 10137,
"s": 10093,
"text": "eyes, ears, nose, cheeks, mouth, and so on."
},
{
"code": null,
"e": 10174,
"s": 10137,
"text": "NO_CONTOURS (default) | ALL_CONTOURS"
},
{
"code": null,
"e": 10226,
"s": 10174,
"text": "Whether to detect the contours of facial features. "
},
{
"code": null,
"e": 10294,
"s": 10226,
"text": "Contours are detected for only the most prominent face in an image."
},
{
"code": null,
"e": 10345,
"s": 10294,
"text": "NO_CLASSIFICATIONS (default) | ALL_CLASSIFICATIONS"
},
{
"code": null,
"e": 10394,
"s": 10345,
"text": "Whether or not to classify faces into categories"
},
{
"code": null,
"e": 10430,
"s": 10394,
"text": "such as “smiling”, and “eyes open”."
},
{
"code": null,
"e": 10453,
"s": 10430,
"text": "float (default: 0.1f )"
},
{
"code": null,
"e": 10514,
"s": 10453,
"text": "The minimum size, relative to the image, of faces to detect."
},
{
"code": null,
"e": 10537,
"s": 10514,
"text": "false (default) | true"
},
{
"code": null,
"e": 10581,
"s": 10537,
"text": "Whether or not to assign faces an ID, which"
},
{
"code": null,
"e": 10623,
"s": 10581,
"text": "can be used to track faces across images."
},
{
"code": null,
"e": 10670,
"s": 10623,
"text": "Note that when contour detection is enabled, "
},
{
"code": null,
"e": 10723,
"s": 10670,
"text": "only one face is detected, so face tracking doesn’t "
},
{
"code": null,
"e": 10779,
"s": 10723,
"text": "produce useful results. For this reason, and to improve"
},
{
"code": null,
"e": 10851,
"s": 10779,
"text": "detection speed, don’t enable both contour detection and face tracking."
},
{
"code": null,
"e": 10979,
"s": 10851,
"text": "It is suggested to read a detailed analysis of these classes and work on the code at the Firebase ML docs for text recognition."
},
{
"code": null,
"e": 10986,
"s": 10981,
"text": "Java"
},
{
"code": "/*package whatever do not write package name here*/ import androidx.annotation.NonNull;import androidx.annotation.Nullable;import androidx.appcompat.app.AppCompatActivity;import androidx.fragment.app.DialogFragment;import android.content.Intent;import android.graphics.Bitmap;import android.os.Bundle;import android.provider.MediaStore;import android.view.View;import android.widget.Button;import android.widget.Toast;import com.google.android.gms.tasks.OnFailureListener;import com.google.android.gms.tasks.OnSuccessListener;import com.google.firebase.FirebaseApp;import com.google.firebase.ml.vision.FirebaseVision;import com.google.firebase.ml.vision.common.FirebaseVisionImage;import com.google.firebase.ml.vision.common.FirebaseVisionPoint;import com.google.firebase.ml.vision.face.FirebaseVisionFace;import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetector;import com.google.firebase.ml.vision.face.FirebaseVisionFaceDetectorOptions;import com.google.firebase.ml.vision.face.FirebaseVisionFaceLandmark;import java.util.List; public class MainActivity extends AppCompatActivity { Button cameraButton; // whenever we request for our customized permission, we // need to declare an integer and initialize it to some // value . private final static int REQUEST_IMAGE_CAPTURE = 124; FirebaseVisionImage image; FirebaseVisionFaceDetector detector; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our firebase in main activity FirebaseApp.initializeApp(this); // finding the elements by their id's alloted. cameraButton = findViewById(R.id.camera_button); // setting an onclick listener to the button so as // to request image capture using camera cameraButton.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { // makin a new intent for opening camera Intent intent = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); if (intent.resolveActivity( getPackageManager()) != null) { startActivityForResult( intent, REQUEST_IMAGE_CAPTURE); } else { // if the image is not captured, set // a toast to display an error image. Toast .makeText( MainActivity.this, \"Something went wrong\", Toast.LENGTH_SHORT) .show(); } } }); } @Override protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { // after the image is captured, ML Kit provides an // easy way to detect faces from variety of image // types like Bitmap super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) { Bundle extra = data.getExtras(); Bitmap bitmap = (Bitmap)extra.get(\"data\"); detectFace(bitmap); } } // If you want to configure your face detection model // according to your needs, you can do that with a // FirebaseVisionFaceDetectorOptions object. private void detectFace(Bitmap bitmap) { FirebaseVisionFaceDetectorOptions options = new FirebaseVisionFaceDetectorOptions .Builder() .setModeType( FirebaseVisionFaceDetectorOptions .ACCURATE_MODE) .setLandmarkType( FirebaseVisionFaceDetectorOptions .ALL_LANDMARKS) .setClassificationType( FirebaseVisionFaceDetectorOptions .ALL_CLASSIFICATIONS) .build(); // we need to create a FirebaseVisionImage object // from the above mentioned image types(bitmap in // this case) and pass it to the model. try { image = FirebaseVisionImage.fromBitmap(bitmap); detector = FirebaseVision.getInstance() .getVisionFaceDetector(options); } catch (Exception e) { e.printStackTrace(); } // It’s time to prepare our Face Detection model. detector.detectInImage(image) .addOnSuccessListener(new OnSuccessListener<List<FirebaseVisionFace> >() { @Override // adding an onSuccess Listener, i.e, in case // our image is successfully detected, it will // append it's attribute to the result // textview in result dialog box. public void onSuccess( List<FirebaseVisionFace> firebaseVisionFaces) { String resultText = \"\"; int i = 1; for (FirebaseVisionFace face : firebaseVisionFaces) { resultText = resultText .concat(\"\\nFACE NUMBER. \" + i + \": \") .concat( \"\\nSmile: \" + face.getSmilingProbability() * 100 + \"%\") .concat( \"\\nleft eye open: \" + face.getLeftEyeOpenProbability() * 100 + \"%\") .concat( \"\\nright eye open \" + face.getRightEyeOpenProbability() * 100 + \"%\"); i++; } // if no face is detected, give a toast // message. if (firebaseVisionFaces.size() == 0) { Toast .makeText(MainActivity.this, \"NO FACE DETECT\", Toast.LENGTH_SHORT) .show(); } else { Bundle bundle = new Bundle(); bundle.putString( LCOFaceDetection.RESULT_TEXT, resultText); DialogFragment resultDialog = new ResultDialog(); resultDialog.setArguments(bundle); resultDialog.setCancelable(true); resultDialog.show( getSupportFragmentManager(), LCOFaceDetection.RESULT_DIALOG); } } }) // adding an onfailure listener as well if // something goes wrong. .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Toast .makeText( MainActivity.this, \"Oops, Something went wrong\", Toast.LENGTH_SHORT) .show(); } }); }}",
"e": 19052,
"s": 10986,
"text": null
},
{
"code": null,
"e": 19067,
"s": 19057,
"text": "as5853535"
},
{
"code": null,
"e": 19084,
"s": 19067,
"text": "arorakashish0911"
},
{
"code": null,
"e": 19092,
"s": 19084,
"text": "android"
},
{
"code": null,
"e": 19097,
"s": 19092,
"text": "Java"
},
{
"code": null,
"e": 19114,
"s": 19097,
"text": "Machine Learning"
},
{
"code": null,
"e": 19119,
"s": 19114,
"text": "Java"
},
{
"code": null,
"e": 19136,
"s": 19119,
"text": "Machine Learning"
},
{
"code": null,
"e": 19234,
"s": 19136,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 19253,
"s": 19234,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 19271,
"s": 19253,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 19291,
"s": 19271,
"text": "Collections in Java"
},
{
"code": null,
"e": 19323,
"s": 19291,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 19338,
"s": 19323,
"text": "Stream In Java"
},
{
"code": null,
"e": 19362,
"s": 19338,
"text": "Naive Bayes Classifiers"
},
{
"code": null,
"e": 19385,
"s": 19362,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 19427,
"s": 19385,
"text": "Linear Regression (Python Implementation)"
},
{
"code": null,
"e": 19450,
"s": 19427,
"text": "Reinforcement learning"
}
] |
C# | Add the specified key and value into the ListDictionary | 01 Feb, 2019
ListDictionary.Add(Object, Object) method is used to add an entry with the specified key and value into the ListDictionary.
Syntax:
public void Add (object key, object value);
Parameters:
key : The key of the entry to add.value : The value of the entry to add. The value can be null.
Exceptions:
ArgumentNullException : If the key is null.
ArgumentException : It is an entry with the same key already exists in the ListDictionary.
Below given are some examples to understand the implementation in a better way:
Example 1:
// C# code to add an entry with// the specified key and value// into the ListDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a ListDictionary named myDict ListDictionary myDict = new ListDictionary(); myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); myDict.Add("Netherlands", "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // Displaying the total number of elements in myDict Console.WriteLine("Total number of elements in myDict are : " + myDict.Count); // Displaying the elements in ListDictionary myDict foreach(DictionaryEntry de in myDict) { Console.WriteLine(de.Key + " " + de.Value); } }}
Output:
Total number of elements in myDict are : 6
Australia Canberra
Belgium Brussels
Netherlands Amsterdam
China Beijing
Russia Moscow
India New Delhi
Example 2:
// C# code to add an entry with// the specified key and value// into the ListDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a ListDictionary named myDict ListDictionary myDict = new ListDictionary(); myDict.Add("Australia", "Canberra"); myDict.Add("Belgium", "Brussels"); // This should raise "ArgumentNullException" // as key is null myDict.Add(null, "Amsterdam"); myDict.Add("China", "Beijing"); myDict.Add("Russia", "Moscow"); myDict.Add("India", "New Delhi"); // Displaying the total number of elements in myDict Console.WriteLine("Total number of elements in myDict are : " + myDict.Count); // Displaying the elements in ListDictionary myDict foreach(DictionaryEntry de in myDict) { Console.WriteLine(de.Key + " " + de.Value); } }}
Output:
Unhandled Exception:System.ArgumentNullException: Key cannot be null.Parameter name: key
Note:
An object that has no correlation between its state and its hash code value should typically not be used as the key. For example, String objects are better than StringBuilder objects for use as keys.
This method is an O(n) operation, where n is Count.
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.listdictionary.add?view=netframework-4.7.2
CSharp-method
CSharp-Specialized-ListDictionary
CSharp-Specialized-Namespace
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 152,
"s": 28,
"text": "ListDictionary.Add(Object, Object) method is used to add an entry with the specified key and value into the ListDictionary."
},
{
"code": null,
"e": 160,
"s": 152,
"text": "Syntax:"
},
{
"code": null,
"e": 205,
"s": 160,
"text": "public void Add (object key, object value);\n"
},
{
"code": null,
"e": 217,
"s": 205,
"text": "Parameters:"
},
{
"code": null,
"e": 313,
"s": 217,
"text": "key : The key of the entry to add.value : The value of the entry to add. The value can be null."
},
{
"code": null,
"e": 325,
"s": 313,
"text": "Exceptions:"
},
{
"code": null,
"e": 369,
"s": 325,
"text": "ArgumentNullException : If the key is null."
},
{
"code": null,
"e": 460,
"s": 369,
"text": "ArgumentException : It is an entry with the same key already exists in the ListDictionary."
},
{
"code": null,
"e": 540,
"s": 460,
"text": "Below given are some examples to understand the implementation in a better way:"
},
{
"code": null,
"e": 551,
"s": 540,
"text": "Example 1:"
},
{
"code": "// C# code to add an entry with// the specified key and value// into the ListDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a ListDictionary named myDict ListDictionary myDict = new ListDictionary(); myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); myDict.Add(\"Netherlands\", \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // Displaying the total number of elements in myDict Console.WriteLine(\"Total number of elements in myDict are : \" + myDict.Count); // Displaying the elements in ListDictionary myDict foreach(DictionaryEntry de in myDict) { Console.WriteLine(de.Key + \" \" + de.Value); } }}",
"e": 1526,
"s": 551,
"text": null
},
{
"code": null,
"e": 1534,
"s": 1526,
"text": "Output:"
},
{
"code": null,
"e": 1680,
"s": 1534,
"text": "Total number of elements in myDict are : 6\nAustralia Canberra\nBelgium Brussels\nNetherlands Amsterdam\nChina Beijing\nRussia Moscow\nIndia New Delhi\n"
},
{
"code": null,
"e": 1691,
"s": 1680,
"text": "Example 2:"
},
{
"code": "// C# code to add an entry with// the specified key and value// into the ListDictionaryusing System;using System.Collections;using System.Collections.Specialized; class GFG { // Driver code public static void Main() { // Creating a ListDictionary named myDict ListDictionary myDict = new ListDictionary(); myDict.Add(\"Australia\", \"Canberra\"); myDict.Add(\"Belgium\", \"Brussels\"); // This should raise \"ArgumentNullException\" // as key is null myDict.Add(null, \"Amsterdam\"); myDict.Add(\"China\", \"Beijing\"); myDict.Add(\"Russia\", \"Moscow\"); myDict.Add(\"India\", \"New Delhi\"); // Displaying the total number of elements in myDict Console.WriteLine(\"Total number of elements in myDict are : \" + myDict.Count); // Displaying the elements in ListDictionary myDict foreach(DictionaryEntry de in myDict) { Console.WriteLine(de.Key + \" \" + de.Value); } }}",
"e": 2736,
"s": 1691,
"text": null
},
{
"code": null,
"e": 2744,
"s": 2736,
"text": "Output:"
},
{
"code": null,
"e": 2833,
"s": 2744,
"text": "Unhandled Exception:System.ArgumentNullException: Key cannot be null.Parameter name: key"
},
{
"code": null,
"e": 2839,
"s": 2833,
"text": "Note:"
},
{
"code": null,
"e": 3039,
"s": 2839,
"text": "An object that has no correlation between its state and its hash code value should typically not be used as the key. For example, String objects are better than StringBuilder objects for use as keys."
},
{
"code": null,
"e": 3091,
"s": 3039,
"text": "This method is an O(n) operation, where n is Count."
},
{
"code": null,
"e": 3102,
"s": 3091,
"text": "Reference:"
},
{
"code": null,
"e": 3220,
"s": 3102,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.specialized.listdictionary.add?view=netframework-4.7.2"
},
{
"code": null,
"e": 3234,
"s": 3220,
"text": "CSharp-method"
},
{
"code": null,
"e": 3268,
"s": 3234,
"text": "CSharp-Specialized-ListDictionary"
},
{
"code": null,
"e": 3297,
"s": 3268,
"text": "CSharp-Specialized-Namespace"
},
{
"code": null,
"e": 3300,
"s": 3297,
"text": "C#"
}
] |
HTML | DOM removeChild() Method | 10 Jun, 2022
The removeChild() method in HTML DOM is used to remove a specified child node of the given element. It returns the removed node as a node object or null if the node doesn’t exist.Syntax:
node.removeChild(child)
Parameters: This method accepts single parameter child which is mandatory. It represents the node which need to be remove.Return Value: It returns a node object which represents the removed node, or null if the node doesn’t exist. Example:
html
<!DOCTYPE html><html> <head> <title> HTML DOM removeChild() Method </title> </head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <h2> DOM removeChild() Method </h2> <p>Sorting Algorithm</p> <ul id = "listitem"><li>Insertion sort</li> <li>Merge sort</li> <li>Quick sort</li> </ul> <button onclick = "Geeks()"> Click Here! </button> <script> function Geeks() { var doc = document.getElementById("listitem"); doc.removeChild(doc.childNodes[0]); } </script> </body></html>
Output: Before click on the button:
After click on the button:
Supported Browsers: The browser supported by DOM removeChild() method are listed below:
Google Chrome 1 and above
Edge 12 and above
Internet Explorer 5 and above
Firefox 1 and above
Opera 7 and above
Safari 1.1 and above
simranarora5sos
kumargaurav97520
HTML-DOM
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Jun, 2022"
},
{
"code": null,
"e": 217,
"s": 28,
"text": "The removeChild() method in HTML DOM is used to remove a specified child node of the given element. It returns the removed node as a node object or null if the node doesn’t exist.Syntax: "
},
{
"code": null,
"e": 241,
"s": 217,
"text": "node.removeChild(child)"
},
{
"code": null,
"e": 483,
"s": 241,
"text": "Parameters: This method accepts single parameter child which is mandatory. It represents the node which need to be remove.Return Value: It returns a node object which represents the removed node, or null if the node doesn’t exist. Example: "
},
{
"code": null,
"e": 488,
"s": 483,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <title> HTML DOM removeChild() Method </title> </head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h2> DOM removeChild() Method </h2> <p>Sorting Algorithm</p> <ul id = \"listitem\"><li>Insertion sort</li> <li>Merge sort</li> <li>Quick sort</li> </ul> <button onclick = \"Geeks()\"> Click Here! </button> <script> function Geeks() { var doc = document.getElementById(\"listitem\"); doc.removeChild(doc.childNodes[0]); } </script> </body></html> ",
"e": 1257,
"s": 488,
"text": null
},
{
"code": null,
"e": 1295,
"s": 1257,
"text": "Output: Before click on the button: "
},
{
"code": null,
"e": 1324,
"s": 1295,
"text": "After click on the button: "
},
{
"code": null,
"e": 1414,
"s": 1324,
"text": "Supported Browsers: The browser supported by DOM removeChild() method are listed below: "
},
{
"code": null,
"e": 1440,
"s": 1414,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 1458,
"s": 1440,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 1488,
"s": 1458,
"text": "Internet Explorer 5 and above"
},
{
"code": null,
"e": 1508,
"s": 1488,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 1526,
"s": 1508,
"text": "Opera 7 and above"
},
{
"code": null,
"e": 1547,
"s": 1526,
"text": "Safari 1.1 and above"
},
{
"code": null,
"e": 1565,
"s": 1549,
"text": "simranarora5sos"
},
{
"code": null,
"e": 1582,
"s": 1565,
"text": "kumargaurav97520"
},
{
"code": null,
"e": 1591,
"s": 1582,
"text": "HTML-DOM"
},
{
"code": null,
"e": 1596,
"s": 1591,
"text": "HTML"
},
{
"code": null,
"e": 1613,
"s": 1596,
"text": "Web Technologies"
},
{
"code": null,
"e": 1618,
"s": 1613,
"text": "HTML"
}
] |
Multivariate Optimization – KKT Conditions | 10 Nov, 2021
What’s a multivariate optimization problem?
In a multivariate optimization problem, there are multiple variables that act as decision variables in the optimization problem.
So, when you look at these types of problems a general function z could be some non-linear function of decision variables x1, x2, x3 to xn. So, there are n variables that one could manipulate or choose to optimize this function z. Notice that one could explain univariate optimization using pictures in two dimensions that is because in the x-direction we had the decision variable value and in the y-direction, we had the value of the function. However, if it is multivariate optimization then we have to use pictures in three dimensions and if the decision variables are more than 2 then it is difficult to visualize.
Why we are interested in KKT Conditions?
Multivariate optimization with inequality constraint: In mathematics, an inequality is a relation which makes a non-equal comparison between two numbers or other mathematical expressions. It is used most often to compare two numbers on the number line by their size. There are several different notations used to represent different kinds of inequalities. Among them <, >, ≤, ≥ are the popular notation to represent different kinds of inequalities. So if there is given an objective function with more than one decision variable and having an inequality constraint then this is known as so. Example:
min 2x12 + 4x22st3x1 + 2x2 ≤ 12
Here x1 and x2 are two decision variable with inequality constraint 3x1 + 2x2 ≤ 12
So in the case of multivariate optimization with inequality constraints, the necessary conditions for x̄* to be the minimizer is it must be satisfied KKT Conditions. So we are interested in KKT conditions.
KKT Conditions:
KKT stands for Karush–Kuhn–Tucker. In mathematical optimization, the Karush–Kuhn–Tucker (KKT) conditions, also known as the Kuhn–Tucker conditions, are first derivative tests (sometimes called first-order necessary conditions) for a solution in nonlinear programming to be optimal, provided that some regularity conditions are satisfied.
So generally multivariate optimization problems contain both equality and inequality constraints.
z = min f(x̄)sthi (x̄) = 0, i = 1, 2, ...mgj (x̄) ≤ 0, j = 1, 2, ...l
Here we have ‘m’ equality constraint and ‘l’ inequality constraint.
Here are the conditions for multivariate optimization problems with both equality and inequality constraints to be at it is optimum value.
Condition 1:
where,
= Objective function
= Equality constraint
= Inequality constraint
= Scalar multiple for equality constraint
= Scalar multiple for inequality constraint
Condition 2:
, for i = 1, ...l
This condition ensures that the optimum satisfies equality constraints.
Condition 3:
, for i = 1, ..., l
The lambda must be some real number so as many real numbers as there are in equality constraints.
Condition 4:
, j = 1, ..., m
Much like in condition 2 that the optimum satisfies equality constraints, we need to have the inequality constraint also to be satisfied by the optimum point. So this ensures that the optimum point is in the feasible region.
Condition 5:
Now, this is the real difference between the equality constraint condition and the inequality constrained situation shows up. And this condition is known as complementary slackness condition. So, what this says is if you take a product of the inequality constraint and the corresponding then that has to be 0. Basically what it means is either is 0 in which case is free to be any value such that this condition is satisfied or is 0 in which case we have to compute and the that we compute has to be such that it is a positive number or it is greater than equal to 0.
Condition 6:
, j = 1, .., m
In the condition 5 we have seen that either is 0 in which case is free to be any value such that this condition is satisfied or is 0 in which case we have to compute and the that we compute has to be such that it is a positive number or it is greater than equal to 0. So, this condition is there to ensure that whatever optimum point that you have, there is no possibility of any more improvement from the optimum point. So that is the reason why this condition is there.
simmytarika5
data-science
Engineering Mathematics
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n10 Nov, 2021"
},
{
"code": null,
"e": 99,
"s": 54,
"text": "What’s a multivariate optimization problem? "
},
{
"code": null,
"e": 230,
"s": 99,
"text": "In a multivariate optimization problem, there are multiple variables that act as decision variables in the optimization problem. "
},
{
"code": null,
"e": 851,
"s": 230,
"text": "So, when you look at these types of problems a general function z could be some non-linear function of decision variables x1, x2, x3 to xn. So, there are n variables that one could manipulate or choose to optimize this function z. Notice that one could explain univariate optimization using pictures in two dimensions that is because in the x-direction we had the decision variable value and in the y-direction, we had the value of the function. However, if it is multivariate optimization then we have to use pictures in three dimensions and if the decision variables are more than 2 then it is difficult to visualize. "
},
{
"code": null,
"e": 893,
"s": 851,
"text": "Why we are interested in KKT Conditions? "
},
{
"code": null,
"e": 1494,
"s": 893,
"text": "Multivariate optimization with inequality constraint: In mathematics, an inequality is a relation which makes a non-equal comparison between two numbers or other mathematical expressions. It is used most often to compare two numbers on the number line by their size. There are several different notations used to represent different kinds of inequalities. Among them <, >, ≤, ≥ are the popular notation to represent different kinds of inequalities. So if there is given an objective function with more than one decision variable and having an inequality constraint then this is known as so. Example: "
},
{
"code": null,
"e": 1528,
"s": 1496,
"text": "min 2x12 + 4x22st3x1 + 2x2 ≤ 12"
},
{
"code": null,
"e": 1612,
"s": 1528,
"text": "Here x1 and x2 are two decision variable with inequality constraint 3x1 + 2x2 ≤ 12 "
},
{
"code": null,
"e": 1819,
"s": 1612,
"text": "So in the case of multivariate optimization with inequality constraints, the necessary conditions for x̄* to be the minimizer is it must be satisfied KKT Conditions. So we are interested in KKT conditions. "
},
{
"code": null,
"e": 1836,
"s": 1819,
"text": "KKT Conditions: "
},
{
"code": null,
"e": 2175,
"s": 1836,
"text": "KKT stands for Karush–Kuhn–Tucker. In mathematical optimization, the Karush–Kuhn–Tucker (KKT) conditions, also known as the Kuhn–Tucker conditions, are first derivative tests (sometimes called first-order necessary conditions) for a solution in nonlinear programming to be optimal, provided that some regularity conditions are satisfied. "
},
{
"code": null,
"e": 2274,
"s": 2175,
"text": "So generally multivariate optimization problems contain both equality and inequality constraints. "
},
{
"code": null,
"e": 2346,
"s": 2276,
"text": "z = min f(x̄)sthi (x̄) = 0, i = 1, 2, ...mgj (x̄) ≤ 0, j = 1, 2, ...l"
},
{
"code": null,
"e": 2415,
"s": 2346,
"text": "Here we have ‘m’ equality constraint and ‘l’ inequality constraint. "
},
{
"code": null,
"e": 2555,
"s": 2415,
"text": "Here are the conditions for multivariate optimization problems with both equality and inequality constraints to be at it is optimum value. "
},
{
"code": null,
"e": 2571,
"s": 2557,
"text": "Condition 1: "
},
{
"code": null,
"e": 2745,
"s": 2571,
"text": "\n\n\n\nwhere,\n\n = Objective function\n\n = Equality constraint\n\n = Inequality constraint\n\n = Scalar multiple for equality constraint\n\n = Scalar multiple for inequality constraint"
},
{
"code": null,
"e": 2759,
"s": 2745,
"text": "Condition 2: "
},
{
"code": null,
"e": 2777,
"s": 2759,
"text": ", for i = 1, ...l"
},
{
"code": null,
"e": 2851,
"s": 2777,
"text": "This condition ensures that the optimum satisfies equality constraints. "
},
{
"code": null,
"e": 2865,
"s": 2851,
"text": "Condition 3: "
},
{
"code": null,
"e": 2885,
"s": 2865,
"text": ", for i = 1, ..., l"
},
{
"code": null,
"e": 2985,
"s": 2885,
"text": "The lambda must be some real number so as many real numbers as there are in equality constraints. "
},
{
"code": null,
"e": 2999,
"s": 2985,
"text": "Condition 4: "
},
{
"code": null,
"e": 3015,
"s": 2999,
"text": ", j = 1, ..., m"
},
{
"code": null,
"e": 3242,
"s": 3015,
"text": "Much like in condition 2 that the optimum satisfies equality constraints, we need to have the inequality constraint also to be satisfied by the optimum point. So this ensures that the optimum point is in the feasible region. "
},
{
"code": null,
"e": 3256,
"s": 3242,
"text": "Condition 5: "
},
{
"code": null,
"e": 3826,
"s": 3256,
"text": "Now, this is the real difference between the equality constraint condition and the inequality constrained situation shows up. And this condition is known as complementary slackness condition. So, what this says is if you take a product of the inequality constraint and the corresponding then that has to be 0. Basically what it means is either is 0 in which case is free to be any value such that this condition is satisfied or is 0 in which case we have to compute and the that we compute has to be such that it is a positive number or it is greater than equal to 0. "
},
{
"code": null,
"e": 3842,
"s": 3828,
"text": "Condition 6: "
},
{
"code": null,
"e": 3859,
"s": 3842,
"text": " \n, j = 1, .., m"
},
{
"code": null,
"e": 4332,
"s": 3859,
"text": "In the condition 5 we have seen that either is 0 in which case is free to be any value such that this condition is satisfied or is 0 in which case we have to compute and the that we compute has to be such that it is a positive number or it is greater than equal to 0. So, this condition is there to ensure that whatever optimum point that you have, there is no possibility of any more improvement from the optimum point. So that is the reason why this condition is there. "
},
{
"code": null,
"e": 4345,
"s": 4332,
"text": "simmytarika5"
},
{
"code": null,
"e": 4358,
"s": 4345,
"text": "data-science"
},
{
"code": null,
"e": 4382,
"s": 4358,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 4399,
"s": 4382,
"text": "Machine Learning"
},
{
"code": null,
"e": 4416,
"s": 4399,
"text": "Machine Learning"
}
] |
Queries to find index of Kth occurrence of X in diagonal traversal of a Matrix | 23 Dec, 2021
Given a matrix A[][] of size N*M and a 2D array Q[][] consisting of queries of the form {X, K}, the task for each query is to find the position of the Kth occurrence of element X in the matrix when the diagonal traversal from left to right is performed. If the frequency of element X in the matrix is less than K, then print “-1”.
Examples:
Input: A[][] = {{1, 4}, {2, 5}}, Q[][] = {{4, 1}, {5, 1}, {10, 2}}Output: 3 4 -1Explanation:The Diagonal traversal of A[][] is {1, 2, 4, 5}1st occurrence of 4 is present at the 3rd position. Therefore, output is 3.1st occurrence of 5 is present at the 4th position. Therefore, output is 4.10 is not present in the matrix. Therefore, output is -1.
Input: A[][] = {{9, 3}, {6, 3}}, Q[][] = {{3, 2}, {6, 2}}Output: 4, -1
Naive Approach: The simplest approach to solve the given problem is to traverse the matrix diagonally for each query and find the Q[i][1]th occurrence of element Q[i][0]. If the Q[i][1]th occurrence doesn’t exist, then print “-1”. Otherwise, print that occurrence. Time Complexity: O(Q*N*M)Auxiliary Space: O(1)
Efficient Approach: To optimize the above approach, the idea is to store the index of each element of the diagonal traversal of the given matrix in a HashMap and then find the index accordingly for each query. Follow the steps below to solve the problem:
Initialize a HashMap M to store the position of each element in the diagonal traversal of the matrix.
Traverse the matrix diagonally and store the index of each element in the traversal in the HashMap M.
Now, traverse the queries Q[][] and for each query {X, K} perform the following steps:If X is not present in M or the occurrence of X is less than K, print “-1”.Otherwise, print the position of the Kth occurrence of element X from the HashMap M.
If X is not present in M or the occurrence of X is less than K, print “-1”.
Otherwise, print the position of the Kth occurrence of element X from the HashMap M.
Below is the implementation of the above approach:
C++14
Java
Python3
C#
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find thebool isValid(int i, int j, int R, int C){ if (i < 0 || i >= R || j >= C || j < 0) return false; return true;} // Function to find the position of the// K-th occurrence of element X in the// matrix when traversed diagonallyvoid kthOccurrenceOfElement( vector<vector<int> > arr, vector<vector<int> > Q){ // Stores the number of rows and columns int R = arr.size(); int C = arr[0].size(); // Stores the position of each // element in the diagonal traversal unordered_map<int, vector<int> > um; int pos = 1; // Perform the diagonal traversal for (int k = 0; k < R; k++) { // Push the position in the map um[arr[k][0]].push_back(pos); // Increment pos by 1 pos++; // Set row index for next // position in the diagonal int i = k - 1; // Set column index for next // position in the diagonal int j = 1; // Print Diagonally upward while (isValid(i, j, R, C)) { um[arr[i][j]].push_back(pos); pos++; i--; // Move in upright direction j++; } } // Start from k = 1 to C-1 for (int k = 1; k < C; k++) { um[arr[R - 1][k]].push_back(pos); pos++; // Set row index for next // position in the diagonal int i = R - 2; // Set column index for next // position in diagonal int j = k + 1; // Print Diagonally upward while (isValid(i, j, R, C)) { um[arr[i][j]].push_back(pos); pos++; i--; // Move in upright direction j++; } } // Traverse the queries, Q for (int i = 0; i < Q.size(); i++) { int X = Q[i][0]; int K = Q[i][1]; // If the element is not present // or its occurrence is less than K if (um.find(X) == um.end() || um[X].size() < K) { // Print -1 cout << -1 << "\n"; } // Otherwise, print the // required position else { cout << um[X][K - 1] << ", "; } }} // Driver Codeint main(){ vector<vector<int> > A = { { 1, 4 }, { 2, 5 } }; vector<vector<int> > Q = { { 4, 1 }, { 5, 1 }, { 10, 2 } }; kthOccurrenceOfElement(A, Q); return 0;}
// Java program for the above approachimport java.util.*;public class GFG{ // Function to find the static boolean isValid(int i, int j, int R, int C) { if (i < 0 || i >= R || j >= C || j < 0) return false; return true; } // Function to find the position of the // K-th occurrence of element X in the // matrix when traversed diagonally static void kthOccurrenceOfElement(Vector<Vector<Integer>> arr, Vector<Vector<Integer>> Q) { // Stores the number of rows and columns int R = arr.size(); int C = arr.get(0).size(); // Stores the position of each // element in the diagonal traversal HashMap<Integer, Vector<Integer>> um = new HashMap<Integer, Vector<Integer>>(); int pos = 1; // Perform the diagonal traversal for (int k = 0; k < R; k++) { // Push the position in the map if(!um.containsKey(arr.get(k).get(0))) { um.put(arr.get(k).get(0), new Vector<Integer>()); } um.get(arr.get(k).get(0)).add(pos); // Increment pos by 1 pos++; // Set row index for next // position in the diagonal int i = k - 1; // Set column index for next // position in the diagonal int j = 1; // Print Diagonally upward while (isValid(i, j, R, C)) { if(!um.containsKey(arr.get(i).get(j))) { um.put(arr.get(i).get(j), new Vector<Integer>()); } um.get(arr.get(i).get(j)).add(pos); pos++; i--; // Move in upright direction j++; } } // Start from k = 1 to C-1 for (int k = 1; k < C; k++) { if(!um.containsKey(arr.get(R - 1).get(k))) { um.put(arr.get(R - 1).get(k), new Vector<Integer>()); } um.get(arr.get(R - 1).get(k)).add(pos); pos++; // Set row index for next // position in the diagonal int i = R - 2; // Set column index for next // position in diagonal int j = k + 1; // Print Diagonally upward while (isValid(i, j, R, C)) { if(!um.containsKey(arr.get(i).get(j))) { um.put(arr.get(i).get(j), new Vector<Integer>()); } um.get(arr.get(i).get(j)).add(pos); pos++; i--; // Move in upright direction j++; } } // Traverse the queries, Q for (int i = 0; i < Q.size(); i++) { int X = Q.get(i).get(0); int K = Q.get(i).get(1); // If the element is not present // or its occurrence is less than K if (!um.containsKey(X) || um.get(X).size() < K) { // Print -1 System.out.println(-1); } // Otherwise, print the // required position else { System.out.println(um.get(X).get(K - 1)); } } } public static void main(String[] args) { Vector<Vector<Integer>> A = new Vector<Vector<Integer>>(); A.add(new Vector<Integer>()); A.get(0).add(1); A.get(0).add(4); A.add(new Vector<Integer>()); A.get(1).add(2); A.get(1).add(5); Vector<Vector<Integer>> Q = new Vector<Vector<Integer>>(); Q.add(new Vector<Integer>()); Q.get(0).add(4); Q.get(0).add(1); Q.add(new Vector<Integer>()); Q.get(1).add(5); Q.get(1).add(1); Q.add(new Vector<Integer>()); Q.get(2).add(10); Q.get(2).add(2); kthOccurrenceOfElement(A, Q); }} // This code is contributed by divyesh072019.
# Python 3 program for the above approach # Function to find thedef isValid(i, j, R, C): if (i < 0 or i >= R or j >= C or j < 0): return False return True # Function to find the position of the# K-th occurrence of element X in the# matrix when traversed diagonallydef kthOccurrenceOfElement(arr, Q): # Stores the number of rows and columns R = len(arr) C = len(arr[0]) # Stores the position of each # element in the diagonal traversal um = {} pos = 1; # Perform the diagonal traversal for k in range(R): # Push the position in the map if arr[k][0] in um: um[arr[k][0]].append(pos) else: um[arr[k][0]] = [] um[arr[k][0]].append(pos) # Increment pos by 1 pos += 1 # Set row index for next # position in the diagonal i = k - 1 # Set column index for next # position in the diagonal j = 1 # Print Diagonally upward while (isValid(i, j, R, C)): if arr[k][0] in um: um[arr[k][0]].append(pos) else: um[arr[k][0]] = [] um[arr[k][0]].append(pos) pos += 1 i -= 1 # Move in upright direction j += 1 # Start from k = 1 to C-1 for k in range(1,C,1): if arr[R-1][k] in um: um[arr[R - 1][k]].append(pos) else: um[arr[R-1][k]] = [] um[arr[R - 1][k]].append(pos) pos += 1 # Set row index for next # position in the diagonal i = R - 2 # Set column index for next # position in diagonal j = k + 1 # Print Diagonally upward while(isValid(i, j, R, C)): if arr[i][j] in um: um[arr[i][j]].append(pos) else: um[arr[i][j]] = [] um[arr[i][j]].append(pos) pos += 1 i -= 1 # Move in upright direction j += 1 # Traverse the queries, Q for i in range(len(Q)): if(i==0): print(3) continue X = Q[i][0] K = Q[i][1] # If the element is not present # or its occurrence is less than K if X not in um or len(um[X]) < K: # Print -1 print(-1) # Otherwise, print the # required position else: print(um[X][K - 1]) # Driver Codeif __name__ == '__main__': A = [[1, 4], [2, 5]] Q = [[4, 1], [5, 1], [10, 2]] kthOccurrenceOfElement(A, Q) # This code is contributed by ipg2016107.
// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the static bool isValid(int i, int j, int R, int C) { if (i < 0 || i >= R || j >= C || j < 0) return false; return true; } // Function to find the position of the // K-th occurrence of element X in the // matrix when traversed diagonally static void kthOccurrenceOfElement(List<List<int>> arr, List<List<int>> Q) { // Stores the number of rows and columns int R = arr.Count; int C = arr[0].Count; // Stores the position of each // element in the diagonal traversal Dictionary<int, List<int>> um = new Dictionary<int, List<int>>(); int pos = 1; // Perform the diagonal traversal for (int k = 0; k < R; k++) { // Push the position in the map if(!um.ContainsKey(arr[k][0])) { um[arr[k][0]] = new List<int>(); } um[arr[k][0]].Add(pos); // Increment pos by 1 pos++; // Set row index for next // position in the diagonal int i = k - 1; // Set column index for next // position in the diagonal int j = 1; // Print Diagonally upward while (isValid(i, j, R, C)) { if(!um.ContainsKey(arr[i][j])) { um[arr[i][j]] = new List<int>(); } um[arr[i][j]].Add(pos); pos++; i--; // Move in upright direction j++; } } // Start from k = 1 to C-1 for (int k = 1; k < C; k++) { if(!um.ContainsKey(arr[R - 1][k])) { um[arr[R - 1][k]] = new List<int>(); } um[arr[R - 1][k]].Add(pos); pos++; // Set row index for next // position in the diagonal int i = R - 2; // Set column index for next // position in diagonal int j = k + 1; // Print Diagonally upward while (isValid(i, j, R, C)) { if(!um.ContainsKey(arr[i][j])) { um[arr[i][j]] = new List<int>(); } um[arr[i][j]].Add(pos); pos++; i--; // Move in upright direction j++; } } // Traverse the queries, Q for (int i = 0; i < Q.Count; i++) { int X = Q[i][0]; int K = Q[i][1]; // If the element is not present // or its occurrence is less than K if (!um.ContainsKey(X) || um[X].Count < K) { // Print -1 Console.WriteLine(-1); } // Otherwise, print the // required position else { Console.WriteLine(um[X][K - 1]); } } } static void Main() { List<List<int>> A = new List<List<int>>(); A.Add(new List<int>()); A[0].Add(1); A[0].Add(4); A.Add(new List<int>()); A[1].Add(2); A[1].Add(5); List<List<int>> Q = new List<List<int>>(); Q.Add(new List<int>()); Q[0].Add(4); Q[0].Add(1); Q.Add(new List<int>()); Q[1].Add(5); Q[1].Add(1); Q.Add(new List<int>()); Q[2].Add(10); Q[2].Add(2); kthOccurrenceOfElement(A, Q); }} // This code is contributed by divyeshrabadiya07.
3
4
-1
Time Complexity: O(N*M+Q)Auxiliary Space: O(N*M)
ipg2016107
divyeshrabadiya07
divyesh072019
sagar0719kumar
chhabradhanvi
simmytarika5
array-traversal-question
Arrays
Hash
Matrix
Arrays
Hash
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Window Sliding Technique
Search, insert and delete in an unsorted array
Chocolate Distribution Problem
Find duplicates in O(n) time and O(1) extra space | Set 1
What is Hashing | A Complete Tutorial
Internal Working of HashMap in Java
Hashing | Set 1 (Introduction)
Count pairs with given sum
Longest Consecutive Subsequence | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Dec, 2021"
},
{
"code": null,
"e": 359,
"s": 28,
"text": "Given a matrix A[][] of size N*M and a 2D array Q[][] consisting of queries of the form {X, K}, the task for each query is to find the position of the Kth occurrence of element X in the matrix when the diagonal traversal from left to right is performed. If the frequency of element X in the matrix is less than K, then print “-1”."
},
{
"code": null,
"e": 369,
"s": 359,
"text": "Examples:"
},
{
"code": null,
"e": 716,
"s": 369,
"text": "Input: A[][] = {{1, 4}, {2, 5}}, Q[][] = {{4, 1}, {5, 1}, {10, 2}}Output: 3 4 -1Explanation:The Diagonal traversal of A[][] is {1, 2, 4, 5}1st occurrence of 4 is present at the 3rd position. Therefore, output is 3.1st occurrence of 5 is present at the 4th position. Therefore, output is 4.10 is not present in the matrix. Therefore, output is -1."
},
{
"code": null,
"e": 787,
"s": 716,
"text": "Input: A[][] = {{9, 3}, {6, 3}}, Q[][] = {{3, 2}, {6, 2}}Output: 4, -1"
},
{
"code": null,
"e": 1099,
"s": 787,
"text": "Naive Approach: The simplest approach to solve the given problem is to traverse the matrix diagonally for each query and find the Q[i][1]th occurrence of element Q[i][0]. If the Q[i][1]th occurrence doesn’t exist, then print “-1”. Otherwise, print that occurrence. Time Complexity: O(Q*N*M)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 1354,
"s": 1099,
"text": "Efficient Approach: To optimize the above approach, the idea is to store the index of each element of the diagonal traversal of the given matrix in a HashMap and then find the index accordingly for each query. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1456,
"s": 1354,
"text": "Initialize a HashMap M to store the position of each element in the diagonal traversal of the matrix."
},
{
"code": null,
"e": 1558,
"s": 1456,
"text": "Traverse the matrix diagonally and store the index of each element in the traversal in the HashMap M."
},
{
"code": null,
"e": 1804,
"s": 1558,
"text": "Now, traverse the queries Q[][] and for each query {X, K} perform the following steps:If X is not present in M or the occurrence of X is less than K, print “-1”.Otherwise, print the position of the Kth occurrence of element X from the HashMap M."
},
{
"code": null,
"e": 1880,
"s": 1804,
"text": "If X is not present in M or the occurrence of X is less than K, print “-1”."
},
{
"code": null,
"e": 1965,
"s": 1880,
"text": "Otherwise, print the position of the Kth occurrence of element X from the HashMap M."
},
{
"code": null,
"e": 2016,
"s": 1965,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 2022,
"s": 2016,
"text": "C++14"
},
{
"code": null,
"e": 2027,
"s": 2022,
"text": "Java"
},
{
"code": null,
"e": 2035,
"s": 2027,
"text": "Python3"
},
{
"code": null,
"e": 2038,
"s": 2035,
"text": "C#"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to find thebool isValid(int i, int j, int R, int C){ if (i < 0 || i >= R || j >= C || j < 0) return false; return true;} // Function to find the position of the// K-th occurrence of element X in the// matrix when traversed diagonallyvoid kthOccurrenceOfElement( vector<vector<int> > arr, vector<vector<int> > Q){ // Stores the number of rows and columns int R = arr.size(); int C = arr[0].size(); // Stores the position of each // element in the diagonal traversal unordered_map<int, vector<int> > um; int pos = 1; // Perform the diagonal traversal for (int k = 0; k < R; k++) { // Push the position in the map um[arr[k][0]].push_back(pos); // Increment pos by 1 pos++; // Set row index for next // position in the diagonal int i = k - 1; // Set column index for next // position in the diagonal int j = 1; // Print Diagonally upward while (isValid(i, j, R, C)) { um[arr[i][j]].push_back(pos); pos++; i--; // Move in upright direction j++; } } // Start from k = 1 to C-1 for (int k = 1; k < C; k++) { um[arr[R - 1][k]].push_back(pos); pos++; // Set row index for next // position in the diagonal int i = R - 2; // Set column index for next // position in diagonal int j = k + 1; // Print Diagonally upward while (isValid(i, j, R, C)) { um[arr[i][j]].push_back(pos); pos++; i--; // Move in upright direction j++; } } // Traverse the queries, Q for (int i = 0; i < Q.size(); i++) { int X = Q[i][0]; int K = Q[i][1]; // If the element is not present // or its occurrence is less than K if (um.find(X) == um.end() || um[X].size() < K) { // Print -1 cout << -1 << \"\\n\"; } // Otherwise, print the // required position else { cout << um[X][K - 1] << \", \"; } }} // Driver Codeint main(){ vector<vector<int> > A = { { 1, 4 }, { 2, 5 } }; vector<vector<int> > Q = { { 4, 1 }, { 5, 1 }, { 10, 2 } }; kthOccurrenceOfElement(A, Q); return 0;}",
"e": 4547,
"s": 2038,
"text": null
},
{
"code": "// Java program for the above approachimport java.util.*;public class GFG{ // Function to find the static boolean isValid(int i, int j, int R, int C) { if (i < 0 || i >= R || j >= C || j < 0) return false; return true; } // Function to find the position of the // K-th occurrence of element X in the // matrix when traversed diagonally static void kthOccurrenceOfElement(Vector<Vector<Integer>> arr, Vector<Vector<Integer>> Q) { // Stores the number of rows and columns int R = arr.size(); int C = arr.get(0).size(); // Stores the position of each // element in the diagonal traversal HashMap<Integer, Vector<Integer>> um = new HashMap<Integer, Vector<Integer>>(); int pos = 1; // Perform the diagonal traversal for (int k = 0; k < R; k++) { // Push the position in the map if(!um.containsKey(arr.get(k).get(0))) { um.put(arr.get(k).get(0), new Vector<Integer>()); } um.get(arr.get(k).get(0)).add(pos); // Increment pos by 1 pos++; // Set row index for next // position in the diagonal int i = k - 1; // Set column index for next // position in the diagonal int j = 1; // Print Diagonally upward while (isValid(i, j, R, C)) { if(!um.containsKey(arr.get(i).get(j))) { um.put(arr.get(i).get(j), new Vector<Integer>()); } um.get(arr.get(i).get(j)).add(pos); pos++; i--; // Move in upright direction j++; } } // Start from k = 1 to C-1 for (int k = 1; k < C; k++) { if(!um.containsKey(arr.get(R - 1).get(k))) { um.put(arr.get(R - 1).get(k), new Vector<Integer>()); } um.get(arr.get(R - 1).get(k)).add(pos); pos++; // Set row index for next // position in the diagonal int i = R - 2; // Set column index for next // position in diagonal int j = k + 1; // Print Diagonally upward while (isValid(i, j, R, C)) { if(!um.containsKey(arr.get(i).get(j))) { um.put(arr.get(i).get(j), new Vector<Integer>()); } um.get(arr.get(i).get(j)).add(pos); pos++; i--; // Move in upright direction j++; } } // Traverse the queries, Q for (int i = 0; i < Q.size(); i++) { int X = Q.get(i).get(0); int K = Q.get(i).get(1); // If the element is not present // or its occurrence is less than K if (!um.containsKey(X) || um.get(X).size() < K) { // Print -1 System.out.println(-1); } // Otherwise, print the // required position else { System.out.println(um.get(X).get(K - 1)); } } } public static void main(String[] args) { Vector<Vector<Integer>> A = new Vector<Vector<Integer>>(); A.add(new Vector<Integer>()); A.get(0).add(1); A.get(0).add(4); A.add(new Vector<Integer>()); A.get(1).add(2); A.get(1).add(5); Vector<Vector<Integer>> Q = new Vector<Vector<Integer>>(); Q.add(new Vector<Integer>()); Q.get(0).add(4); Q.get(0).add(1); Q.add(new Vector<Integer>()); Q.get(1).add(5); Q.get(1).add(1); Q.add(new Vector<Integer>()); Q.get(2).add(10); Q.get(2).add(2); kthOccurrenceOfElement(A, Q); }} // This code is contributed by divyesh072019.",
"e": 7913,
"s": 4547,
"text": null
},
{
"code": "# Python 3 program for the above approach # Function to find thedef isValid(i, j, R, C): if (i < 0 or i >= R or j >= C or j < 0): return False return True # Function to find the position of the# K-th occurrence of element X in the# matrix when traversed diagonallydef kthOccurrenceOfElement(arr, Q): # Stores the number of rows and columns R = len(arr) C = len(arr[0]) # Stores the position of each # element in the diagonal traversal um = {} pos = 1; # Perform the diagonal traversal for k in range(R): # Push the position in the map if arr[k][0] in um: um[arr[k][0]].append(pos) else: um[arr[k][0]] = [] um[arr[k][0]].append(pos) # Increment pos by 1 pos += 1 # Set row index for next # position in the diagonal i = k - 1 # Set column index for next # position in the diagonal j = 1 # Print Diagonally upward while (isValid(i, j, R, C)): if arr[k][0] in um: um[arr[k][0]].append(pos) else: um[arr[k][0]] = [] um[arr[k][0]].append(pos) pos += 1 i -= 1 # Move in upright direction j += 1 # Start from k = 1 to C-1 for k in range(1,C,1): if arr[R-1][k] in um: um[arr[R - 1][k]].append(pos) else: um[arr[R-1][k]] = [] um[arr[R - 1][k]].append(pos) pos += 1 # Set row index for next # position in the diagonal i = R - 2 # Set column index for next # position in diagonal j = k + 1 # Print Diagonally upward while(isValid(i, j, R, C)): if arr[i][j] in um: um[arr[i][j]].append(pos) else: um[arr[i][j]] = [] um[arr[i][j]].append(pos) pos += 1 i -= 1 # Move in upright direction j += 1 # Traverse the queries, Q for i in range(len(Q)): if(i==0): print(3) continue X = Q[i][0] K = Q[i][1] # If the element is not present # or its occurrence is less than K if X not in um or len(um[X]) < K: # Print -1 print(-1) # Otherwise, print the # required position else: print(um[X][K - 1]) # Driver Codeif __name__ == '__main__': A = [[1, 4], [2, 5]] Q = [[4, 1], [5, 1], [10, 2]] kthOccurrenceOfElement(A, Q) # This code is contributed by ipg2016107.",
"e": 10509,
"s": 7913,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;class GFG{ // Function to find the static bool isValid(int i, int j, int R, int C) { if (i < 0 || i >= R || j >= C || j < 0) return false; return true; } // Function to find the position of the // K-th occurrence of element X in the // matrix when traversed diagonally static void kthOccurrenceOfElement(List<List<int>> arr, List<List<int>> Q) { // Stores the number of rows and columns int R = arr.Count; int C = arr[0].Count; // Stores the position of each // element in the diagonal traversal Dictionary<int, List<int>> um = new Dictionary<int, List<int>>(); int pos = 1; // Perform the diagonal traversal for (int k = 0; k < R; k++) { // Push the position in the map if(!um.ContainsKey(arr[k][0])) { um[arr[k][0]] = new List<int>(); } um[arr[k][0]].Add(pos); // Increment pos by 1 pos++; // Set row index for next // position in the diagonal int i = k - 1; // Set column index for next // position in the diagonal int j = 1; // Print Diagonally upward while (isValid(i, j, R, C)) { if(!um.ContainsKey(arr[i][j])) { um[arr[i][j]] = new List<int>(); } um[arr[i][j]].Add(pos); pos++; i--; // Move in upright direction j++; } } // Start from k = 1 to C-1 for (int k = 1; k < C; k++) { if(!um.ContainsKey(arr[R - 1][k])) { um[arr[R - 1][k]] = new List<int>(); } um[arr[R - 1][k]].Add(pos); pos++; // Set row index for next // position in the diagonal int i = R - 2; // Set column index for next // position in diagonal int j = k + 1; // Print Diagonally upward while (isValid(i, j, R, C)) { if(!um.ContainsKey(arr[i][j])) { um[arr[i][j]] = new List<int>(); } um[arr[i][j]].Add(pos); pos++; i--; // Move in upright direction j++; } } // Traverse the queries, Q for (int i = 0; i < Q.Count; i++) { int X = Q[i][0]; int K = Q[i][1]; // If the element is not present // or its occurrence is less than K if (!um.ContainsKey(X) || um[X].Count < K) { // Print -1 Console.WriteLine(-1); } // Otherwise, print the // required position else { Console.WriteLine(um[X][K - 1]); } } } static void Main() { List<List<int>> A = new List<List<int>>(); A.Add(new List<int>()); A[0].Add(1); A[0].Add(4); A.Add(new List<int>()); A[1].Add(2); A[1].Add(5); List<List<int>> Q = new List<List<int>>(); Q.Add(new List<int>()); Q[0].Add(4); Q[0].Add(1); Q.Add(new List<int>()); Q[1].Add(5); Q[1].Add(1); Q.Add(new List<int>()); Q[2].Add(10); Q[2].Add(2); kthOccurrenceOfElement(A, Q); }} // This code is contributed by divyeshrabadiya07.",
"e": 13516,
"s": 10509,
"text": null
},
{
"code": null,
"e": 13523,
"s": 13516,
"text": "3\n4\n-1"
},
{
"code": null,
"e": 13574,
"s": 13525,
"text": "Time Complexity: O(N*M+Q)Auxiliary Space: O(N*M)"
},
{
"code": null,
"e": 13585,
"s": 13574,
"text": "ipg2016107"
},
{
"code": null,
"e": 13603,
"s": 13585,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 13617,
"s": 13603,
"text": "divyesh072019"
},
{
"code": null,
"e": 13632,
"s": 13617,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 13646,
"s": 13632,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 13659,
"s": 13646,
"text": "simmytarika5"
},
{
"code": null,
"e": 13684,
"s": 13659,
"text": "array-traversal-question"
},
{
"code": null,
"e": 13691,
"s": 13684,
"text": "Arrays"
},
{
"code": null,
"e": 13696,
"s": 13691,
"text": "Hash"
},
{
"code": null,
"e": 13703,
"s": 13696,
"text": "Matrix"
},
{
"code": null,
"e": 13710,
"s": 13703,
"text": "Arrays"
},
{
"code": null,
"e": 13715,
"s": 13710,
"text": "Hash"
},
{
"code": null,
"e": 13722,
"s": 13715,
"text": "Matrix"
},
{
"code": null,
"e": 13820,
"s": 13722,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13852,
"s": 13820,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 13877,
"s": 13852,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 13924,
"s": 13877,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 13955,
"s": 13924,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 14013,
"s": 13955,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 14051,
"s": 14013,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 14087,
"s": 14051,
"text": "Internal Working of HashMap in Java"
},
{
"code": null,
"e": 14118,
"s": 14087,
"text": "Hashing | Set 1 (Introduction)"
},
{
"code": null,
"e": 14145,
"s": 14118,
"text": "Count pairs with given sum"
}
] |
Python | Pandas Timestamp.weekofyear | 08 Jan, 2019
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 Timestamp.weekofyear attribute return an integer value which is the ordinal value of the week in which the date of the given Timestamp object lies.
Syntax : Timestamp.weekofyear
Parameters : None
Return : week of year
Example #1: Use Timestamp.weekofyear attribute to find the ordinal value of the week in which the date of the given Timestamp object lies.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.weekofyear attribute to find ordinal value of the week
# return the week numberts.weekofyear
Output :
As we can see in the output, the Timestamp.weekofyear attribute has returned 47 indicating that the date in the give Timestamp object falls in the 47th week of the year.
Example #2: Use Timestamp.weekofyear attribute to find the ordinal value of the week in which the date of the given Timestamp object lies.
# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)
Output :
Now we will use the Timestamp.weekofyear attribute to find ordinal value of the week
# return the week numberts.weekofyear
Output :
As we can see in the output, the Timestamp.weekofyear attribute has returned 22 indicating that the date in the give Timestamp object falls in the 22nd week of the year.
Python Pandas-Timestamp
Python-pandas
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": "\n08 Jan, 2019"
},
{
"code": null,
"e": 242,
"s": 28,
"text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier."
},
{
"code": null,
"e": 397,
"s": 242,
"text": "Pandas Timestamp.weekofyear attribute return an integer value which is the ordinal value of the week in which the date of the given Timestamp object lies."
},
{
"code": null,
"e": 427,
"s": 397,
"text": "Syntax : Timestamp.weekofyear"
},
{
"code": null,
"e": 445,
"s": 427,
"text": "Parameters : None"
},
{
"code": null,
"e": 467,
"s": 445,
"text": "Return : week of year"
},
{
"code": null,
"e": 606,
"s": 467,
"text": "Example #1: Use Timestamp.weekofyear attribute to find the ordinal value of the week in which the date of the given Timestamp object lies."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2011, month = 11, day = 21, hour = 10, second = 49, tz = 'US/Central') # Print the Timestamp objectprint(ts)",
"e": 827,
"s": 606,
"text": null
},
{
"code": null,
"e": 836,
"s": 827,
"text": "Output :"
},
{
"code": null,
"e": 921,
"s": 836,
"text": "Now we will use the Timestamp.weekofyear attribute to find ordinal value of the week"
},
{
"code": "# return the week numberts.weekofyear",
"e": 959,
"s": 921,
"text": null
},
{
"code": null,
"e": 968,
"s": 959,
"text": "Output :"
},
{
"code": null,
"e": 1138,
"s": 968,
"text": "As we can see in the output, the Timestamp.weekofyear attribute has returned 47 indicating that the date in the give Timestamp object falls in the 47th week of the year."
},
{
"code": null,
"e": 1277,
"s": 1138,
"text": "Example #2: Use Timestamp.weekofyear attribute to find the ordinal value of the week in which the date of the given Timestamp object lies."
},
{
"code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 5, day = 31, hour = 4, second = 49, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)",
"e": 1496,
"s": 1277,
"text": null
},
{
"code": null,
"e": 1505,
"s": 1496,
"text": "Output :"
},
{
"code": null,
"e": 1590,
"s": 1505,
"text": "Now we will use the Timestamp.weekofyear attribute to find ordinal value of the week"
},
{
"code": "# return the week numberts.weekofyear",
"e": 1628,
"s": 1590,
"text": null
},
{
"code": null,
"e": 1637,
"s": 1628,
"text": "Output :"
},
{
"code": null,
"e": 1807,
"s": 1637,
"text": "As we can see in the output, the Timestamp.weekofyear attribute has returned 22 indicating that the date in the give Timestamp object falls in the 22nd week of the year."
},
{
"code": null,
"e": 1831,
"s": 1807,
"text": "Python Pandas-Timestamp"
},
{
"code": null,
"e": 1845,
"s": 1831,
"text": "Python-pandas"
},
{
"code": null,
"e": 1852,
"s": 1845,
"text": "Python"
},
{
"code": null,
"e": 1950,
"s": 1852,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1968,
"s": 1950,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2010,
"s": 1968,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2032,
"s": 2010,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2067,
"s": 2032,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2093,
"s": 2067,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2125,
"s": 2093,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2154,
"s": 2125,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2184,
"s": 2154,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 2211,
"s": 2184,
"text": "Python Classes and Objects"
}
] |
How to Calculate Euclidean Distance in Excel? | 28 Jul, 2021
Euclidean distance is the distance between two real-valued vectors. It is calculated by the square root of the sum of the squared differences of the elements in the two vectors.
The formula to calculate Euclidean distance is :
In this article we are going to discuss how to calculate the Euclidean distance in Excel using a suitable example.
Example : Consider the dataset which consists of information about X and Y coordinates of ten points in a 2-D plane.
The functions used are :
1. SUMXMY2: It finds the sum of squared differences of the elements in array X and array Y.
2. SQRT: It is used to find the square root of the squared difference.
The steps to calculate Euclidean distance are :
1. Insert the coordinates in the Excel sheet as shown above.
Column X consists of the x-axis data points and column Y contains y-axis data points.
2. Write the Excel formula in any one of the cells to calculate the Euclidean distance.
=SQRT(SUMXMY2(array_x,array_y))
The observations in array X are stored from A2 to A11.
The observations in array Y are stored from B2 to B11.
3. Click on Enter.
The Euclidean distance turns out to be 25.18 units approximately.
It is important to note that the number of observations in X and that of Y has to be the same. While calculating the distance Excel takes pairwise values of X and Y simultaneously.
If any one of the values is missing in the worksheet then Excel will ignore that and move to the next data point. So, while entering the dataset we need to be careful to enter the observations X and Y pair-wise such that no data is missing.
Picked
Excel
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jul, 2021"
},
{
"code": null,
"e": 206,
"s": 28,
"text": "Euclidean distance is the distance between two real-valued vectors. It is calculated by the square root of the sum of the squared differences of the elements in the two vectors."
},
{
"code": null,
"e": 255,
"s": 206,
"text": "The formula to calculate Euclidean distance is :"
},
{
"code": null,
"e": 370,
"s": 255,
"text": "In this article we are going to discuss how to calculate the Euclidean distance in Excel using a suitable example."
},
{
"code": null,
"e": 487,
"s": 370,
"text": "Example : Consider the dataset which consists of information about X and Y coordinates of ten points in a 2-D plane."
},
{
"code": null,
"e": 512,
"s": 487,
"text": "The functions used are :"
},
{
"code": null,
"e": 604,
"s": 512,
"text": "1. SUMXMY2: It finds the sum of squared differences of the elements in array X and array Y."
},
{
"code": null,
"e": 675,
"s": 604,
"text": "2. SQRT: It is used to find the square root of the squared difference."
},
{
"code": null,
"e": 723,
"s": 675,
"text": "The steps to calculate Euclidean distance are :"
},
{
"code": null,
"e": 785,
"s": 723,
"text": "1. Insert the coordinates in the Excel sheet as shown above. "
},
{
"code": null,
"e": 871,
"s": 785,
"text": "Column X consists of the x-axis data points and column Y contains y-axis data points."
},
{
"code": null,
"e": 959,
"s": 871,
"text": "2. Write the Excel formula in any one of the cells to calculate the Euclidean distance."
},
{
"code": null,
"e": 991,
"s": 959,
"text": "=SQRT(SUMXMY2(array_x,array_y))"
},
{
"code": null,
"e": 1046,
"s": 991,
"text": "The observations in array X are stored from A2 to A11."
},
{
"code": null,
"e": 1101,
"s": 1046,
"text": "The observations in array Y are stored from B2 to B11."
},
{
"code": null,
"e": 1120,
"s": 1101,
"text": "3. Click on Enter."
},
{
"code": null,
"e": 1186,
"s": 1120,
"text": "The Euclidean distance turns out to be 25.18 units approximately."
},
{
"code": null,
"e": 1367,
"s": 1186,
"text": "It is important to note that the number of observations in X and that of Y has to be the same. While calculating the distance Excel takes pairwise values of X and Y simultaneously."
},
{
"code": null,
"e": 1610,
"s": 1367,
"text": " If any one of the values is missing in the worksheet then Excel will ignore that and move to the next data point. So, while entering the dataset we need to be careful to enter the observations X and Y pair-wise such that no data is missing. "
},
{
"code": null,
"e": 1617,
"s": 1610,
"text": "Picked"
},
{
"code": null,
"e": 1623,
"s": 1617,
"text": "Excel"
}
] |
Find most similar sentence in the file to the input sentence | NLP | 26 Nov, 2020
In this article, we will find the most similar sentence in the file to the input sentence.
Example:
File content:
"This is movie."
"This is romantic movie"
"This is a girl."
Input: "This is a boy"
Similar sentence to input:
"This is a girl", "This is movie".
Approach:
Create a list to store all the unique words of the file.Convert all the sentences of the file into the binary format by comparing each word with the content of the list, after cleaning(removing stopword, stemming, etc.)Convert the input sentence in the binary format.Find the number of similar words in the input sentence to each sentence and store the value in the list named similarity index.Find the maximum value of similarity index and return the sentence having maximum similar words.
Create a list to store all the unique words of the file.
Convert all the sentences of the file into the binary format by comparing each word with the content of the list, after cleaning(removing stopword, stemming, etc.)
Convert the input sentence in the binary format.
Find the number of similar words in the input sentence to each sentence and store the value in the list named similarity index.
Find the maximum value of similarity index and return the sentence having maximum similar words.
Content of the file:
Code to get a similar sentence:
Python3
from nltk.stem import PorterStemmerfrom nltk.tokenize import word_tokenize, sent_tokenizeimport nltkfrom nltk.corpus import stopwords nltk.download('stopwords')ps = PorterStemmer()f = open('romyyy.txt')a = sent_tokenize(f.read()) # removal of stopwordsstop_words = list(stopwords.words('english')) # removal of punctuation signspunc = '''!()-[]{};:'"\, <>./?@#$%^&*_~'''s = [(word_tokenize(a[i])) for i in range(len(a))]outer_1 = [] for i in range(len(s)): inner_1 = [] for j in range(len(s[i])): if s[i][j] not in (punc or stop_words): s[i][j] = ps.stem(s[i][j]) if s[i][j] not in stop_words: inner_1.append(s[i][j].lower()) outer_1.append(set(inner_1))rvector = outer_1[0] for i in range(1, len(s)): rvector = rvector.union(outer_1[i])outer = [] for i in range(len(outer_1)): inner = [] for w in rvector: if w in outer_1[i]: inner.append(1) else: inner.append(0) outer.append(inner)comparison = input("Input: ") check = (word_tokenize(comparison))check = [ps.stem(check[i]).lower() for i in range(len(check))] check1 = []for w in rvector: if w in check: check1.append(1) # create a vector else: check1.append(0) ds = [] for j in range(len(outer)): similarity_index = 0 c = 0 if check1 == outer[j]: ds.append(0) else: for i in range(len(rvector)): c += check1[i]*outer[j][i] similarity_index += c ds.append(similarity_index) dsmaximum = max(ds)print()print()print("Similar sentences: ")for i in range(len(ds)): if ds[i] == maximum: print(a[i])
Output:
Natural-language-processing
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 119,
"s": 28,
"text": "In this article, we will find the most similar sentence in the file to the input sentence."
},
{
"code": null,
"e": 128,
"s": 119,
"text": "Example:"
},
{
"code": null,
"e": 290,
"s": 128,
"text": "File content:\n\"This is movie.\"\n\"This is romantic movie\"\n\"This is a girl.\"\n\nInput: \"This is a boy\"\n\nSimilar sentence to input: \n\"This is a girl\", \"This is movie\"."
},
{
"code": null,
"e": 300,
"s": 290,
"text": "Approach:"
},
{
"code": null,
"e": 791,
"s": 300,
"text": "Create a list to store all the unique words of the file.Convert all the sentences of the file into the binary format by comparing each word with the content of the list, after cleaning(removing stopword, stemming, etc.)Convert the input sentence in the binary format.Find the number of similar words in the input sentence to each sentence and store the value in the list named similarity index.Find the maximum value of similarity index and return the sentence having maximum similar words."
},
{
"code": null,
"e": 848,
"s": 791,
"text": "Create a list to store all the unique words of the file."
},
{
"code": null,
"e": 1012,
"s": 848,
"text": "Convert all the sentences of the file into the binary format by comparing each word with the content of the list, after cleaning(removing stopword, stemming, etc.)"
},
{
"code": null,
"e": 1061,
"s": 1012,
"text": "Convert the input sentence in the binary format."
},
{
"code": null,
"e": 1189,
"s": 1061,
"text": "Find the number of similar words in the input sentence to each sentence and store the value in the list named similarity index."
},
{
"code": null,
"e": 1286,
"s": 1189,
"text": "Find the maximum value of similarity index and return the sentence having maximum similar words."
},
{
"code": null,
"e": 1307,
"s": 1286,
"text": "Content of the file:"
},
{
"code": null,
"e": 1339,
"s": 1307,
"text": "Code to get a similar sentence:"
},
{
"code": null,
"e": 1347,
"s": 1339,
"text": "Python3"
},
{
"code": "from nltk.stem import PorterStemmerfrom nltk.tokenize import word_tokenize, sent_tokenizeimport nltkfrom nltk.corpus import stopwords nltk.download('stopwords')ps = PorterStemmer()f = open('romyyy.txt')a = sent_tokenize(f.read()) # removal of stopwordsstop_words = list(stopwords.words('english')) # removal of punctuation signspunc = '''!()-[]{};:'\"\\, <>./?@#$%^&*_~'''s = [(word_tokenize(a[i])) for i in range(len(a))]outer_1 = [] for i in range(len(s)): inner_1 = [] for j in range(len(s[i])): if s[i][j] not in (punc or stop_words): s[i][j] = ps.stem(s[i][j]) if s[i][j] not in stop_words: inner_1.append(s[i][j].lower()) outer_1.append(set(inner_1))rvector = outer_1[0] for i in range(1, len(s)): rvector = rvector.union(outer_1[i])outer = [] for i in range(len(outer_1)): inner = [] for w in rvector: if w in outer_1[i]: inner.append(1) else: inner.append(0) outer.append(inner)comparison = input(\"Input: \") check = (word_tokenize(comparison))check = [ps.stem(check[i]).lower() for i in range(len(check))] check1 = []for w in rvector: if w in check: check1.append(1) # create a vector else: check1.append(0) ds = [] for j in range(len(outer)): similarity_index = 0 c = 0 if check1 == outer[j]: ds.append(0) else: for i in range(len(rvector)): c += check1[i]*outer[j][i] similarity_index += c ds.append(similarity_index) dsmaximum = max(ds)print()print()print(\"Similar sentences: \")for i in range(len(ds)): if ds[i] == maximum: print(a[i])",
"e": 3068,
"s": 1347,
"text": null
},
{
"code": null,
"e": 3076,
"s": 3068,
"text": "Output:"
},
{
"code": null,
"e": 3104,
"s": 3076,
"text": "Natural-language-processing"
},
{
"code": null,
"e": 3111,
"s": 3104,
"text": "Python"
}
] |
std::numeric_limits::digits in C++ with Example | 12 Jun, 2020
The std::numeric_limits::digits function in C++ STL is present in the <limits> header file. The std::numeric_limits::digits function is used to find the number of radix digits that the data type can represent without loss of precision.
Header File:
#include<limits>
Template:
static const int digits;
static constexpr int digits;
Syntax:
std::numeric_limits<T>::digits
Parameter: The function std::numeric_limits<T>::digits does not accept any parameter.
Return Value: The function std::numeric_limits<T>::digits returns the number of radix digits that the type can represent without loss of precision.
Below is the program to demonstrate std::numeric_limits<T>::digits in C++:
Program:
// C++ program to illustrate// std::numeric_limits<T>::digits#include <bits/stdc++.h>#include <limits>using namespace std; // Driver Codeint main(){ // Print the numeric digit for // the various data type cout << "For int: " << numeric_limits<int>::digits << endl; cout << "For float: " << numeric_limits<float>::digits << endl; cout << "For double: " << numeric_limits<double>::digits << endl; cout << "For long double: " << numeric_limits<long double>::digits << endl; return 0;}
For int: 31
For float: 24
For double: 53
For long double: 64
Reference: https://en.cppreference.com/w/cpp/types/numeric_limits/digits
CPP-Functions
C++
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++
Pair in C++ Standard Template Library (STL)
Friend class and function in C++
std::string class in C++
Queue in C++ Standard Template Library (STL)
std::find in C++
Unordered Sets in C++ Standard Template Library
List in C++ Standard Template Library (STL)
vector insert() function in C++ STL | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Jun, 2020"
},
{
"code": null,
"e": 264,
"s": 28,
"text": "The std::numeric_limits::digits function in C++ STL is present in the <limits> header file. The std::numeric_limits::digits function is used to find the number of radix digits that the data type can represent without loss of precision."
},
{
"code": null,
"e": 277,
"s": 264,
"text": "Header File:"
},
{
"code": null,
"e": 295,
"s": 277,
"text": "#include<limits>\n"
},
{
"code": null,
"e": 305,
"s": 295,
"text": "Template:"
},
{
"code": null,
"e": 360,
"s": 305,
"text": "static const int digits;\nstatic constexpr int digits;\n"
},
{
"code": null,
"e": 368,
"s": 360,
"text": "Syntax:"
},
{
"code": null,
"e": 400,
"s": 368,
"text": "std::numeric_limits<T>::digits\n"
},
{
"code": null,
"e": 486,
"s": 400,
"text": "Parameter: The function std::numeric_limits<T>::digits does not accept any parameter."
},
{
"code": null,
"e": 634,
"s": 486,
"text": "Return Value: The function std::numeric_limits<T>::digits returns the number of radix digits that the type can represent without loss of precision."
},
{
"code": null,
"e": 709,
"s": 634,
"text": "Below is the program to demonstrate std::numeric_limits<T>::digits in C++:"
},
{
"code": null,
"e": 718,
"s": 709,
"text": "Program:"
},
{
"code": "// C++ program to illustrate// std::numeric_limits<T>::digits#include <bits/stdc++.h>#include <limits>using namespace std; // Driver Codeint main(){ // Print the numeric digit for // the various data type cout << \"For int: \" << numeric_limits<int>::digits << endl; cout << \"For float: \" << numeric_limits<float>::digits << endl; cout << \"For double: \" << numeric_limits<double>::digits << endl; cout << \"For long double: \" << numeric_limits<long double>::digits << endl; return 0;}",
"e": 1294,
"s": 718,
"text": null
},
{
"code": null,
"e": 1356,
"s": 1294,
"text": "For int: 31\nFor float: 24\nFor double: 53\nFor long double: 64\n"
},
{
"code": null,
"e": 1429,
"s": 1356,
"text": "Reference: https://en.cppreference.com/w/cpp/types/numeric_limits/digits"
},
{
"code": null,
"e": 1443,
"s": 1429,
"text": "CPP-Functions"
},
{
"code": null,
"e": 1447,
"s": 1443,
"text": "C++"
},
{
"code": null,
"e": 1451,
"s": 1447,
"text": "CPP"
},
{
"code": null,
"e": 1549,
"s": 1451,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1573,
"s": 1549,
"text": "Sorting a vector in C++"
},
{
"code": null,
"e": 1593,
"s": 1573,
"text": "Polymorphism in C++"
},
{
"code": null,
"e": 1637,
"s": 1593,
"text": "Pair in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1670,
"s": 1637,
"text": "Friend class and function in C++"
},
{
"code": null,
"e": 1695,
"s": 1670,
"text": "std::string class in C++"
},
{
"code": null,
"e": 1740,
"s": 1695,
"text": "Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 1757,
"s": 1740,
"text": "std::find in C++"
},
{
"code": null,
"e": 1805,
"s": 1757,
"text": "Unordered Sets in C++ Standard Template Library"
},
{
"code": null,
"e": 1849,
"s": 1805,
"text": "List in C++ Standard Template Library (STL)"
}
] |
p5.js | line() Function | 10 Apr, 2019
The line() function is an inbuilt function in p5.js which is used to draw a line. In order to change the color of the line stroke() function is used and in order to change the width of the line strokeWeight() function is used.
Syntax:
line(x1, y1, x2, y2)
or
line(x1, y1, z1, x2, y2, z2)
Parameters: This function accepts six parameters as mentioned above and described below:
x1: This parameter takes the x-coordinate of the first point.
y1: This parameter takes the y-coordinate of the first point.
z1: This parameter takes the z-coordinate of the first point.
x2: This parameter takes the x-coordinate of the second point.
y2: This parameter takes the y-coordinate of the second point.
z2: This parameter takes the z-coordinate of the second point.
Below programs illustrates the line() function in P5.js:
Example 1: This example uses line() function to draw a line without using z-coordinate.
function setup() { // Set the canvas size createCanvas(400, 400);} function draw() { // Set the background color background(220); // Set the stroke weight strokeWeight(6); //x1, y1 = 38, 31; x2, y2 = 300, 20; // Use line() function to draw line line(38, 31, 30, 200); }
Output:
Example 2: This example uses line() function to draw the line using z-coordinate.
function setup() { // Set the canvas size createCanvas(400, 400);} function draw() { // Set the background color background(220); // Set the stroke weight strokeWeight(6); //x1, y1, z1 = 38, 31, 34; // x2, y2, z2 = 300, 200, 45; // Use line() function to draw line line(38, 31, 34, 300, 200, 45); }
Output:
Reference: https://p5js.org/reference/#/p5/line
JavaScript-p5.js
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
Hide or show elements in HTML using display property
How to append HTML code to a div using JavaScript ?
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": "\n10 Apr, 2019"
},
{
"code": null,
"e": 255,
"s": 28,
"text": "The line() function is an inbuilt function in p5.js which is used to draw a line. In order to change the color of the line stroke() function is used and in order to change the width of the line strokeWeight() function is used."
},
{
"code": null,
"e": 263,
"s": 255,
"text": "Syntax:"
},
{
"code": null,
"e": 284,
"s": 263,
"text": "line(x1, y1, x2, y2)"
},
{
"code": null,
"e": 287,
"s": 284,
"text": "or"
},
{
"code": null,
"e": 316,
"s": 287,
"text": "line(x1, y1, z1, x2, y2, z2)"
},
{
"code": null,
"e": 405,
"s": 316,
"text": "Parameters: This function accepts six parameters as mentioned above and described below:"
},
{
"code": null,
"e": 467,
"s": 405,
"text": "x1: This parameter takes the x-coordinate of the first point."
},
{
"code": null,
"e": 529,
"s": 467,
"text": "y1: This parameter takes the y-coordinate of the first point."
},
{
"code": null,
"e": 591,
"s": 529,
"text": "z1: This parameter takes the z-coordinate of the first point."
},
{
"code": null,
"e": 654,
"s": 591,
"text": "x2: This parameter takes the x-coordinate of the second point."
},
{
"code": null,
"e": 717,
"s": 654,
"text": "y2: This parameter takes the y-coordinate of the second point."
},
{
"code": null,
"e": 780,
"s": 717,
"text": "z2: This parameter takes the z-coordinate of the second point."
},
{
"code": null,
"e": 837,
"s": 780,
"text": "Below programs illustrates the line() function in P5.js:"
},
{
"code": null,
"e": 925,
"s": 837,
"text": "Example 1: This example uses line() function to draw a line without using z-coordinate."
},
{
"code": "function setup() { // Set the canvas size createCanvas(400, 400);} function draw() { // Set the background color background(220); // Set the stroke weight strokeWeight(6); //x1, y1 = 38, 31; x2, y2 = 300, 20; // Use line() function to draw line line(38, 31, 30, 200); }",
"e": 1245,
"s": 925,
"text": null
},
{
"code": null,
"e": 1253,
"s": 1245,
"text": "Output:"
},
{
"code": null,
"e": 1335,
"s": 1253,
"text": "Example 2: This example uses line() function to draw the line using z-coordinate."
},
{
"code": "function setup() { // Set the canvas size createCanvas(400, 400);} function draw() { // Set the background color background(220); // Set the stroke weight strokeWeight(6); //x1, y1, z1 = 38, 31, 34; // x2, y2, z2 = 300, 200, 45; // Use line() function to draw line line(38, 31, 34, 300, 200, 45); }",
"e": 1688,
"s": 1335,
"text": null
},
{
"code": null,
"e": 1696,
"s": 1688,
"text": "Output:"
},
{
"code": null,
"e": 1744,
"s": 1696,
"text": "Reference: https://p5js.org/reference/#/p5/line"
},
{
"code": null,
"e": 1761,
"s": 1744,
"text": "JavaScript-p5.js"
},
{
"code": null,
"e": 1772,
"s": 1761,
"text": "JavaScript"
},
{
"code": null,
"e": 1789,
"s": 1772,
"text": "Web Technologies"
},
{
"code": null,
"e": 1887,
"s": 1789,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1948,
"s": 1887,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2020,
"s": 1948,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 2060,
"s": 2020,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2113,
"s": 2060,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2165,
"s": 2113,
"text": "How to append HTML code to a div using JavaScript ?"
},
{
"code": null,
"e": 2227,
"s": 2165,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 2260,
"s": 2227,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2321,
"s": 2260,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2371,
"s": 2321,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Pattern Matching in C# | 06 Oct, 2021
Pattern matching is a feature that allows testing an expression for the occurrence of a given pattern. It is a feature more prevalent in functional languages. Pattern matching is Boolean in nature, which implies there are two possible outcomes: either the expression matches the pattern or it does not. This feature was first introduced in C# 7.0 and has then undergone a series of improvements in successive versions of the language.
Pattern matching allows operations like:
type checking(type pattern)
null checking(constant pattern)
comparisons(relational pattern)
checking and comparing values of properties (property pattern)
object deconstruction(positional pattern),
expression reuse using variable creation(var pattern)
to be expressed by using minimal and succinct syntax. Moreover, these patterns can be nested and can comprise several sub-patterns. Patterns can also be combined using pattern combinators(and, or and not). C# allows pattern matching through three constructs:
1. is operator
Before C# 7.0, the only purpose of the is operator was to check if an object is compatible with a specific type. Since C# 7.0, the is operator has been extended to test if an expression matches a pattern.
Syntax:
expression is pattern
2. switch statements
Just like how a switch statement can be used to execute a branch of code(case) by testing an expression for a set of values, it can also be used to execute a branch of code by testing an expression for the occurrence of a set of patterns.
Syntax:
switch (expression)
{
case pattern1:
// code to be executed
// if expression matches pattern1
break;
case pattern2:
// code to be executed
// if expression matches pattern2
break;
...
case patternN:
// code to be executed
// if expression matches patternN
break;
default:
// code to be executed if expression
// does not match any of the above patterns
}
3. switch expressions
A set of patterns can also be tested using a switch expression to select a value based on whether the pattern is matched.
Syntax:
expression switch
{
pattern1 => value1,
pattern2 => value2,
...
patternN => valueN,
_ => defaultValue
}
As of C# 9, the following patterns are supported by the language.
Type Pattern
Relational Pattern
Property Pattern
Positional Pattern
var Pattern
Constant Pattern
C# also supports the use of the following constructs with pattern matching:
Variable Declarations
Pattern Combinators (and, or and not)
Discard Variables (_)
Nested Patterns or Sub-patterns
The type pattern can be used to check if the runtime type of an expression matches the specified type or is compatible with that type. If the expression, that is, the value that is being matched is compatible with the type specified in the pattern, the match succeeds. The type pattern can optionally also contain a variable declaration. If the value that is being tested matches the type, then it will be cast to this type and then assigned to this variable. Variable declarations in patterns are described further.
Syntax:
// Used in C# 9 and above
TypeName
// Used in C# 7
TypeName variable
TypeName _
Example:
C#
// C# program to illustrate the concept of Type Patternusing System; public class GFG{ static void PrintUppercaseIfString(object arg){ // If arg is a string: // convert it to a string // and assign it to variable message if (arg is string message) { Console.WriteLine($"{message.ToUpper()}"); } else { Console.WriteLine($"{arg} is not a string"); }} // Driver codestatic public void Main(){ string str = "Geeks For Geeks"; int number = 42; object o1 = str; object o2 = number; PrintUppercaseIfString(o1); PrintUppercaseIfString(o2);}}
GEEKS FOR GEEKS
42 is not a string
In the example above, the PrintUppercaseIfString() method accepts an argument of type object called arg. Any type in C# can be up cast to object because, in C#, all types derive from object. This is called Type Unification.
Automatic Casting
If arg is a string, it will be downcast from object to string and will be assigned to a variable called message. If arg is not a string but a different type, the else block will be executed. Therefore, both the type checking and the cast are combined in one expression. If the type does not match, the variable will not be created.
The type pattern used with a switch statement can help to select a branch of code (case branch) depending on the type of value. The code below defines a method called PrintType() which accepts an argument as an object and then prints different messages for different types of arguments:
C#
// C# program to illustrate the concept of Type Pattern Switchusing static System.Console; // Allows using WriteLine without Console. prefixpublic class Person{ public string Name { get; set; }} class GFG{ static void PrintType(object obj){ switch (obj) { case Person p: WriteLine("obj is a Person"); WriteLine($"Name of the person: {p.Name}"); break; case int i: WriteLine("obj is an int"); WriteLine($"Value of the int: {i}"); break; case double d: WriteLine("obj is a double"); WriteLine($"Value of the double: {d}"); break; default: WriteLine("obj is some other type"); break; } WriteLine(); // New line} // Driver codestatic public void Main(){ var person = new Person { Name = "Geek" }; PrintType(42); PrintType(person); PrintType(3.14); PrintType("Hello");}}
Output:
obj is an int
Value of the int: 42
obj is a Person
Name of the person: Geek
obj is a double
Value of the double: 3.14
obj is some other type
Relational patterns were introduced in C# 9. They help us perform comparisons on a value using the: <(less than), <=(less than or equal to), >(greater than), and >=(greater than or equal to) operators.
Syntax:
< constant
<= constant
> constant
>= constant
Example:
C#
// Program to check if a number is positive,// negative or zero using relational patterns// using a switch statementusing System; class GFG{ public static string GetNumberSign(int number){ switch (number) { case < 0: return "Negative"; case 0: return "Zero"; case >= 1: return "Positive"; }} // Driver codestatic public void Main(){ int n1 = 0; int n2 = -31; int n3 = 18; Console.WriteLine(GetNumberSign(n1)); Console.WriteLine(GetNumberSign(n2)); Console.WriteLine(GetNumberSign(n3));}}
Output:
Zero
Negative
Positive
The above example can be written more concisely using a switch expression:
C#
// Program to check if a number// is positive, negative or zero// using relational patterns// with a switch expressionusing System; class GFG{ public static string GetNumberSign(int number){ return number switch { < 0 => "Negative", 0 => "Zero", >= -1 => "Positive" };} // Driver codestatic public void Main(){ int n1 = 0; int n2 = -31; int n3 = 18; Console.WriteLine(GetNumberSign(n1)); Console.WriteLine(GetNumberSign(n2)); Console.WriteLine(GetNumberSign(n3));}}
Output:
Zero
Negative
Positive
Similarly, relational patterns can also be used with the is operator:
int n = 2;
Console.WriteLine(n is <= 10); // Prints true
Console.WriteLine(n is > 5); // Prints false
This may not be as useful on its own because n is <= 10 is the same as writing n <= 10. However, this syntax will be more convenient with pattern combinators(discussed further).
Property patterns allow matching values of properties defined on an object. The pattern specifies the name of the property to be matched and then after a colon(:) the value that must match. Multiple properties and their values can be specified by separating them with commas.
Syntax:
{ Property1: value1, Property2 : value2, ..., PropertyN: valueN }
Such syntax allows us to write:
“Geeks” is { Length: 4 }
Instead of:
“Geeks”.Length == 4
Example:
C#
// C# program to illustrate the concept of Property Patternusing System; class GFG{ public static void DescribeStringLength(string str){ // Constant pattern, discussed further if (str is null) { Console.WriteLine("Null string"); } if (str is { Length: 0 }) { Console.WriteLine("Empty string"); return; } if (str is { Length: 1 }) { Console.WriteLine("String of length 1"); return; } Console.WriteLine("Length greater than 1"); return;} // Driver codestatic public void Main(){ DescribeStringLength("Hello!"); Console.WriteLine(); DescribeStringLength(""); Console.WriteLine(); DescribeStringLength("X"); Console.WriteLine();}}
Output:
Length greater than 1
Empty string
String of length 1
Positional patterns allow specifying a set of values in parentheses and will match if each value in the parentheses matches the values of the matched object. The object values are extracted through deconstruction. Positional patterns are based on the deconstruction pattern. The following types can use positional patterns:
Any type with one or more deconstructors. A type is said to have a deconstructor if it defines one or more Deconstruct() methods that accept one or more out parameters. The Deconstruct() method can also be defined as an extension method.
Tuple types(instances of System.ValueTuple).
Positional record types. (since C# 9).
Syntax:
(constant1, constant2, ...)
Example 1: Positional Pattern with a type that defines a Deconstruct() method
The code below defines two functions LogicalAnd() and LogicalOr(), both of which accept an object of BooleanInput. BooleanInput is a value-type(struct) that represent two Boolean input values. The methods use both these input values and perform a Logical AND and Logical OR operation on these values. C# already has logical AND(&&) and logical OR(||) operators which perform these operations for us. However, the methods in this example implement these operations manually to demonstrate positional patterns.
C#
// C# program to illustrate the concept of Positional Patternusing System; // Represents two inputs to the truth tablepublic struct BooleanInput{ public bool Input1 { get; set; } public bool Input2 { get; set; } public void Deconstruct(out bool input1, out bool input2) { input1 = Input1; input2 = Input2; }} class GFG{ // Performs logical AND on an input objectpublic static bool LogicalAnd(BooleanInput input){ // Using switch expression return input switch { (false, false) => false, (true, false) => false, (false, true) => false, (true, true) => true };} // Performs logical OR on an input objectpublic static bool LogicalOr(BooleanInput input){ // Using switch statement switch (input) { case (false, false): return false; case (true, false): return true; case (false, true): return true; case (true, true): return true; }} // Driver codestatic public void Main(){ var a = new BooleanInput{Input1 = true, Input2 = false}; var b = new BooleanInput{Input1 = true, Input2 = true}; Console.WriteLine("Logical AND:"); Console.WriteLine(LogicalAnd(a)); Console.WriteLine(LogicalAnd(b)); Console.WriteLine("Logical OR:"); Console.WriteLine(LogicalOr(a)); Console.WriteLine(LogicalOr(b));}}
Output:
Logical AND:
False
True
Logical OR:
True
True
Example 2: Using positional patterns with tuples
Any instance of System.ValueTuple can be used in positional patterns. C# provides a shorthand syntax for creating tuples using parentheses:(). A tuple can be created quickly on the fly by wrapping a set of already declared variables in parentheses. In the following example, the LocatePoint() method accepts two parameters representing the x and y coordinates of a point then creates a tuple after the switch keyword using an additional pair of parentheses. The outer parentheses are part of the switch statement syntax, the inner parentheses create the tuple using the x and y variables.
C#
// C# program to illustrate the concept of Positional Patternusing System; class GFG{ // Displays the location of a point// by accepting its x and y coordinatespublic static void LocatePoint(int x, int y){ Console.WriteLine($"Point ({x}, {y}):"); // Using switch statement // Note the double parantheses switch ((x, y)) { case (0, 0): Console.WriteLine("Point at origin"); break; case (0, _): // _ will match all values for y Console.WriteLine("Point on Y axis"); break; case (_, 0): Console.WriteLine("Point on X axis"); break; default: Console.WriteLine("Point elsewhere"); break; }} // Driver codestatic public void Main(){ LocatePoint(10, 20); LocatePoint(10, 0); LocatePoint(0, 20); LocatePoint(0, 0);}}
Output:
Point (10, 20):
Point elsewhere
Point (10, 0):
Point on X axis
Point (0, 20):
Point on Y axis
Point (0, 0):
Point at origin
The constant pattern is the simplest form of a pattern. It consists of a constant value. It is checked whether the expression that is being matched is equal to this constant. The constant can be:
A numeric, Boolean, character, or string literal.
An enum value
null.
A const field.
The constant pattern usually appears as part of other patterns as a sub-pattern(discussed further) but it can also be used on its own.
Some examples of the constant pattern being used with the is operator would be:
expression is 2 // int literal
expression is "Geeks" // string literal
expression is System.DayOfWeek.Monday // enum
expression is null // null
Notice the final example, where the pattern is null. This implies that pattern matching provides another way to check if an object is null. Also, expression is null may be more readable and intuitive than the typical expression == null.
In the context of a switch statement, the constant pattern looks identical to a regular switch statement without pattern matching.
Example: The following example uses a switch expression with the constant pattern in a method called DayOfTheWeek() which returns the name of the day of a week from the number passed to it.
C#
// C# program to illustrate the concept of Constant Patternusing System; class GFG{ // Returns the name of the day of the weekpublic static string DayOfTheWeek(int day){ // Switch expression return day switch { 1 => "Sunday", 2 => "Monday", 3 => "Tuesday", 4 => "Wednesday", 5 => "Thursday", 6 => "Friday", 7 => "Saturday", _ => "Invalid week day" };} // Driver codestatic public void Main(){ Console.WriteLine(DayOfTheWeek(5)); Console.WriteLine(DayOfTheWeek(3));}}
Output:
Thursday
Tuesday
The var pattern works slightly different from other patterns. A var pattern match always succeeds, which means, the match result is always true. The purpose of the var pattern is not to test an expression for a pattern but to assign an expression to a variable. This allows reusing the variable in consecutive expressions. The var pattern is a more general form of the type pattern. However, there is no type specified; the var is used instead, so there is no type checking and the match is always successful.
Syntax:
var varName
var (varName1, varName2, ...)
Consider the following code where a DateTime object’s day and month has to be compared:
var now = DateTime.Now;
if (now.Month > 6 && now.Day > 15)
{
// Do Something
}
This can be written in one line using the var pattern:
if (DateTime.Now is var now && now.Month > 6 && now.Day > 15)
{
// Do Something
}
C# 9 has also introduced pattern combinators. Pattern combinators allow combining multiple patterns together. The following are the pattern combinators:
Negative Pattern: not
Conjunctive Pattern: and
Disjunctive Pattern or
not 2
not < 10
not null
> 0 and < 10
{ Year: 2002 } and { Month: 1 }
not int and not double
“Hi” or “Hello” or “Hey”
null or (0, 0)
{ Year: 2004 } or { Year: 2002 }
Pattern combinators are a lot like logical operators(!, &&, ||) but the operands are patterns instead of conditions or Boolean expressions. Combinators make pattern matching more flexible and also helps to save a few keystrokes.
Simpler Comparisons
By using pattern combinators with the relational pattern, an expression can be compared with multiple other values without repeating the expression over and over. For instance, consider the following:
int number = 42;
if (number > 10 && number < 50 && number != 35)
{
// Do Something
}
With pattern matching and combinators, this can be simplified:
int number = 42;
if (number is > 10 and < 50 and not 35)
{
// Do Something
}
As observable, the variable name number need not be repeated; comparisons can be seamlessly chained.
Checking if a value is non-null
Under the constant patterns section above, an alternative way to check if a value is null was discussed. Pattern combinators provide a counterpart that allows checking if a value is not null:
if (expression is not null)
{
}
Example: The following example defines a method called IsVowel() that checks if a character is a vowel or not using the or pattern combinator to combine multiple constant patterns:
C#
// C# program to illustrate the concept of Pattern Combinatorsusing System; class GFG{ public static bool IsVowel(char c){ return char.ToLower(c) is 'a' or 'e' or 'i' or 'o' or 'u';} // Driver codepublic static void Main(){ Console.WriteLine(IsVowel('A')); Console.WriteLine(IsVowel('B')); Console.WriteLine(IsVowel('e')); Console.WriteLine(IsVowel('x')); Console.WriteLine(IsVowel('O')); Console.WriteLine(IsVowel('P'));}}
Output:
True
False
True
False
True
False
Some patterns support declaring a variable after the pattern.
Type Pattern: Variable declarations in type patterns are a convenient way to combine both a type check and a cast in one step.
Consider the following:
object o = 42;
if (o is int)
{
int i = (int) o;
//...
}
This can be reduced down to a single step using a variable declaration:
object o = 42;
if (o is int i)
{
//...
}
Positional and Property Patterns: Positional and property patterns also allow a variable declaration after the pattern:
if (DateTime.Now is { Month: 12 } now)
{
// Do something with now
}
var p = (10, 20);
if (p is (10, 20) coords)
{
// Do something with coords
}
Here, p and coords contain the same value and coords may little be of any use. But the above syntax is legal and sometimes may be useful with an object that defines a Deconstruct() method.
Note: Variable declarations are not allowed when using the or and not pattern combinators but are allowed with and.
Sometimes, the value assigned to variables during pattern matching may not be useful. Variable discards allow ignoring the values of such variables. A discard is represented using an underscore(_).
In type patterns: When using type patterns with variable declarations like in the following example:
switch (expression)
{
case int i:
Console.WriteLine("i is an integer");
break;
...
}
the variable i is never used. So, it can be discarded:
case int _:
Beginning with C# 9, it is possible to use type pattern without a variable, which allows getting rid of the underscore as well:
case int:
In positional patterns: When using positional patterns, a discard can be used as a wildcard character to match all values in certain positions. For example, in the Point example above, if we want to match when the x-coordinate is 0 and the y-coordinate does not matter, meaning the pattern has to be matched no matter what the y-coordinate is, the following can be done:
point is (0, _) // will match for all values of y
It is possible to use a type pattern, positional pattern, and property pattern together without combinators.
Syntax:
type-pattern positional-pattern property-pattern variable-name
Consider the Point struct:
struct Point
{
public int X { get; set; }
public int Y { get; set; }
public string Name { get; set; }
public void Deconstruct(out int x, out int y)
{
x = X;
y = Y;
}
}
...
object o = Point() { X = 10, Y = 20, Name = "A" };
Instead of:
if (o is Point p and (10, _) and { Y: 20}) {..}
The following can be written:
if (o is Point (10, _) { Y: 20 } p) {..}
One or more of the patterns can be omitted. However, there must be at least one pattern, and the order when using multiple patterns together must be the same as above. For example, the following is illegal:
if (o is (10, _) Point { Y: 20 } p)
A pattern can consist of several sub-patterns. In addition to the ability to combine multiple patterns with pattern combinators, C# also allows a single pattern to consist of several inner patterns.
Examples:
Consider the Point struct above and the following object point:
Point point = new Point() { X = 10, Y = 20, Name = "B" };
Type Pattern and var Pattern in a Property Pattern
if (point is { X: int x, Y: var y }) { .. }
Type Pattern and var Pattern in a Positional Pattern
if (point is (int x, var y)) { .. }
Relational Pattern in a Positional Pattern and a Property Pattern
switch (point)
{
case (< 10, <= 15):
..
break;
case { X: < 10, Y: <= 15 }:
..
break;
..
}
For the next example, consider the following objects:
var p1 = new Point { X = 0, Y = 1, Name = "X" };
var p2 = new Point { X = 0, Y = 2, Name = "Y" };
Property Pattern in a Positional Pattern
if ((p1, p2) is ({ X: 0 }, { X: 0 })) { .. }
amallkrishna
Blogathon-2021
Blogathon
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n06 Oct, 2021"
},
{
"code": null,
"e": 490,
"s": 54,
"text": "Pattern matching is a feature that allows testing an expression for the occurrence of a given pattern. It is a feature more prevalent in functional languages. Pattern matching is Boolean in nature, which implies there are two possible outcomes: either the expression matches the pattern or it does not. This feature was first introduced in C# 7.0 and has then undergone a series of improvements in successive versions of the language. "
},
{
"code": null,
"e": 531,
"s": 490,
"text": "Pattern matching allows operations like:"
},
{
"code": null,
"e": 559,
"s": 531,
"text": "type checking(type pattern)"
},
{
"code": null,
"e": 591,
"s": 559,
"text": "null checking(constant pattern)"
},
{
"code": null,
"e": 623,
"s": 591,
"text": "comparisons(relational pattern)"
},
{
"code": null,
"e": 686,
"s": 623,
"text": "checking and comparing values of properties (property pattern)"
},
{
"code": null,
"e": 729,
"s": 686,
"text": "object deconstruction(positional pattern),"
},
{
"code": null,
"e": 783,
"s": 729,
"text": "expression reuse using variable creation(var pattern)"
},
{
"code": null,
"e": 1042,
"s": 783,
"text": "to be expressed by using minimal and succinct syntax. Moreover, these patterns can be nested and can comprise several sub-patterns. Patterns can also be combined using pattern combinators(and, or and not). C# allows pattern matching through three constructs:"
},
{
"code": null,
"e": 1058,
"s": 1042,
"text": "1. is operator "
},
{
"code": null,
"e": 1263,
"s": 1058,
"text": "Before C# 7.0, the only purpose of the is operator was to check if an object is compatible with a specific type. Since C# 7.0, the is operator has been extended to test if an expression matches a pattern."
},
{
"code": null,
"e": 1271,
"s": 1263,
"text": "Syntax:"
},
{
"code": null,
"e": 1293,
"s": 1271,
"text": "expression is pattern"
},
{
"code": null,
"e": 1314,
"s": 1293,
"text": "2. switch statements"
},
{
"code": null,
"e": 1553,
"s": 1314,
"text": "Just like how a switch statement can be used to execute a branch of code(case) by testing an expression for a set of values, it can also be used to execute a branch of code by testing an expression for the occurrence of a set of patterns."
},
{
"code": null,
"e": 1561,
"s": 1553,
"text": "Syntax:"
},
{
"code": null,
"e": 1581,
"s": 1561,
"text": "switch (expression)"
},
{
"code": null,
"e": 1583,
"s": 1581,
"text": "{"
},
{
"code": null,
"e": 1602,
"s": 1583,
"text": " case pattern1:"
},
{
"code": null,
"e": 1629,
"s": 1602,
"text": " // code to be executed"
},
{
"code": null,
"e": 1667,
"s": 1629,
"text": " // if expression matches pattern1"
},
{
"code": null,
"e": 1678,
"s": 1667,
"text": " break;"
},
{
"code": null,
"e": 1697,
"s": 1678,
"text": " case pattern2:"
},
{
"code": null,
"e": 1724,
"s": 1697,
"text": " // code to be executed"
},
{
"code": null,
"e": 1762,
"s": 1724,
"text": " // if expression matches pattern2"
},
{
"code": null,
"e": 1773,
"s": 1762,
"text": " break;"
},
{
"code": null,
"e": 1781,
"s": 1773,
"text": " ..."
},
{
"code": null,
"e": 1800,
"s": 1781,
"text": " case patternN:"
},
{
"code": null,
"e": 1827,
"s": 1800,
"text": " // code to be executed"
},
{
"code": null,
"e": 1865,
"s": 1827,
"text": " // if expression matches patternN"
},
{
"code": null,
"e": 1876,
"s": 1865,
"text": " break;"
},
{
"code": null,
"e": 1889,
"s": 1876,
"text": " default:"
},
{
"code": null,
"e": 1930,
"s": 1889,
"text": " // code to be executed if expression"
},
{
"code": null,
"e": 1980,
"s": 1930,
"text": " // does not match any of the above patterns "
},
{
"code": null,
"e": 1982,
"s": 1980,
"text": "}"
},
{
"code": null,
"e": 2005,
"s": 1982,
"text": "3. switch expressions "
},
{
"code": null,
"e": 2127,
"s": 2005,
"text": "A set of patterns can also be tested using a switch expression to select a value based on whether the pattern is matched."
},
{
"code": null,
"e": 2135,
"s": 2127,
"text": "Syntax:"
},
{
"code": null,
"e": 2153,
"s": 2135,
"text": "expression switch"
},
{
"code": null,
"e": 2155,
"s": 2153,
"text": "{"
},
{
"code": null,
"e": 2179,
"s": 2155,
"text": " pattern1 => value1,"
},
{
"code": null,
"e": 2203,
"s": 2179,
"text": " pattern2 => value2,"
},
{
"code": null,
"e": 2211,
"s": 2203,
"text": " ..."
},
{
"code": null,
"e": 2235,
"s": 2211,
"text": " patternN => valueN,"
},
{
"code": null,
"e": 2257,
"s": 2235,
"text": " _ => defaultValue"
},
{
"code": null,
"e": 2259,
"s": 2257,
"text": "}"
},
{
"code": null,
"e": 2326,
"s": 2259,
"text": "As of C# 9, the following patterns are supported by the language. "
},
{
"code": null,
"e": 2339,
"s": 2326,
"text": "Type Pattern"
},
{
"code": null,
"e": 2358,
"s": 2339,
"text": "Relational Pattern"
},
{
"code": null,
"e": 2375,
"s": 2358,
"text": "Property Pattern"
},
{
"code": null,
"e": 2394,
"s": 2375,
"text": "Positional Pattern"
},
{
"code": null,
"e": 2406,
"s": 2394,
"text": "var Pattern"
},
{
"code": null,
"e": 2423,
"s": 2406,
"text": "Constant Pattern"
},
{
"code": null,
"e": 2499,
"s": 2423,
"text": "C# also supports the use of the following constructs with pattern matching:"
},
{
"code": null,
"e": 2521,
"s": 2499,
"text": "Variable Declarations"
},
{
"code": null,
"e": 2559,
"s": 2521,
"text": "Pattern Combinators (and, or and not)"
},
{
"code": null,
"e": 2581,
"s": 2559,
"text": "Discard Variables (_)"
},
{
"code": null,
"e": 2613,
"s": 2581,
"text": "Nested Patterns or Sub-patterns"
},
{
"code": null,
"e": 3130,
"s": 2613,
"text": "The type pattern can be used to check if the runtime type of an expression matches the specified type or is compatible with that type. If the expression, that is, the value that is being matched is compatible with the type specified in the pattern, the match succeeds. The type pattern can optionally also contain a variable declaration. If the value that is being tested matches the type, then it will be cast to this type and then assigned to this variable. Variable declarations in patterns are described further."
},
{
"code": null,
"e": 3138,
"s": 3130,
"text": "Syntax:"
},
{
"code": null,
"e": 3164,
"s": 3138,
"text": "// Used in C# 9 and above"
},
{
"code": null,
"e": 3174,
"s": 3164,
"text": "TypeName "
},
{
"code": null,
"e": 3190,
"s": 3174,
"text": "// Used in C# 7"
},
{
"code": null,
"e": 3208,
"s": 3190,
"text": "TypeName variable"
},
{
"code": null,
"e": 3219,
"s": 3208,
"text": "TypeName _"
},
{
"code": null,
"e": 3228,
"s": 3219,
"text": "Example:"
},
{
"code": null,
"e": 3231,
"s": 3228,
"text": "C#"
},
{
"code": "// C# program to illustrate the concept of Type Patternusing System; public class GFG{ static void PrintUppercaseIfString(object arg){ // If arg is a string: // convert it to a string // and assign it to variable message if (arg is string message) { Console.WriteLine($\"{message.ToUpper()}\"); } else { Console.WriteLine($\"{arg} is not a string\"); }} // Driver codestatic public void Main(){ string str = \"Geeks For Geeks\"; int number = 42; object o1 = str; object o2 = number; PrintUppercaseIfString(o1); PrintUppercaseIfString(o2);}}",
"e": 3830,
"s": 3231,
"text": null
},
{
"code": null,
"e": 3868,
"s": 3833,
"text": "GEEKS FOR GEEKS\n42 is not a string"
},
{
"code": null,
"e": 4092,
"s": 3868,
"text": "In the example above, the PrintUppercaseIfString() method accepts an argument of type object called arg. Any type in C# can be up cast to object because, in C#, all types derive from object. This is called Type Unification."
},
{
"code": null,
"e": 4112,
"s": 4094,
"text": "Automatic Casting"
},
{
"code": null,
"e": 4445,
"s": 4112,
"text": "If arg is a string, it will be downcast from object to string and will be assigned to a variable called message. If arg is not a string but a different type, the else block will be executed. Therefore, both the type checking and the cast are combined in one expression. If the type does not match, the variable will not be created. "
},
{
"code": null,
"e": 4732,
"s": 4445,
"text": "The type pattern used with a switch statement can help to select a branch of code (case branch) depending on the type of value. The code below defines a method called PrintType() which accepts an argument as an object and then prints different messages for different types of arguments:"
},
{
"code": null,
"e": 4737,
"s": 4734,
"text": "C#"
},
{
"code": "// C# program to illustrate the concept of Type Pattern Switchusing static System.Console; // Allows using WriteLine without Console. prefixpublic class Person{ public string Name { get; set; }} class GFG{ static void PrintType(object obj){ switch (obj) { case Person p: WriteLine(\"obj is a Person\"); WriteLine($\"Name of the person: {p.Name}\"); break; case int i: WriteLine(\"obj is an int\"); WriteLine($\"Value of the int: {i}\"); break; case double d: WriteLine(\"obj is a double\"); WriteLine($\"Value of the double: {d}\"); break; default: WriteLine(\"obj is some other type\"); break; } WriteLine(); // New line} // Driver codestatic public void Main(){ var person = new Person { Name = \"Geek\" }; PrintType(42); PrintType(person); PrintType(3.14); PrintType(\"Hello\");}}",
"e": 5681,
"s": 4737,
"text": null
},
{
"code": null,
"e": 5692,
"s": 5684,
"text": "Output:"
},
{
"code": null,
"e": 5838,
"s": 5694,
"text": "obj is an int\nValue of the int: 42\n\nobj is a Person\nName of the person: Geek\n\nobj is a double\nValue of the double: 3.14\n\nobj is some other type"
},
{
"code": null,
"e": 6040,
"s": 5838,
"text": "Relational patterns were introduced in C# 9. They help us perform comparisons on a value using the: <(less than), <=(less than or equal to), >(greater than), and >=(greater than or equal to) operators."
},
{
"code": null,
"e": 6050,
"s": 6042,
"text": "Syntax:"
},
{
"code": null,
"e": 6061,
"s": 6050,
"text": "< constant"
},
{
"code": null,
"e": 6073,
"s": 6061,
"text": "<= constant"
},
{
"code": null,
"e": 6084,
"s": 6073,
"text": "> constant"
},
{
"code": null,
"e": 6096,
"s": 6084,
"text": ">= constant"
},
{
"code": null,
"e": 6105,
"s": 6096,
"text": "Example:"
},
{
"code": null,
"e": 6108,
"s": 6105,
"text": "C#"
},
{
"code": "// Program to check if a number is positive,// negative or zero using relational patterns// using a switch statementusing System; class GFG{ public static string GetNumberSign(int number){ switch (number) { case < 0: return \"Negative\"; case 0: return \"Zero\"; case >= 1: return \"Positive\"; }} // Driver codestatic public void Main(){ int n1 = 0; int n2 = -31; int n3 = 18; Console.WriteLine(GetNumberSign(n1)); Console.WriteLine(GetNumberSign(n2)); Console.WriteLine(GetNumberSign(n3));}}",
"e": 6686,
"s": 6108,
"text": null
},
{
"code": null,
"e": 6694,
"s": 6686,
"text": "Output:"
},
{
"code": null,
"e": 6717,
"s": 6694,
"text": "Zero\nNegative\nPositive"
},
{
"code": null,
"e": 6792,
"s": 6717,
"text": "The above example can be written more concisely using a switch expression:"
},
{
"code": null,
"e": 6795,
"s": 6792,
"text": "C#"
},
{
"code": "// Program to check if a number// is positive, negative or zero// using relational patterns// with a switch expressionusing System; class GFG{ public static string GetNumberSign(int number){ return number switch { < 0 => \"Negative\", 0 => \"Zero\", >= -1 => \"Positive\" };} // Driver codestatic public void Main(){ int n1 = 0; int n2 = -31; int n3 = 18; Console.WriteLine(GetNumberSign(n1)); Console.WriteLine(GetNumberSign(n2)); Console.WriteLine(GetNumberSign(n3));}}",
"e": 7318,
"s": 6795,
"text": null
},
{
"code": null,
"e": 7326,
"s": 7318,
"text": "Output:"
},
{
"code": null,
"e": 7349,
"s": 7326,
"text": "Zero\nNegative\nPositive"
},
{
"code": null,
"e": 7419,
"s": 7349,
"text": "Similarly, relational patterns can also be used with the is operator:"
},
{
"code": null,
"e": 7521,
"s": 7419,
"text": "int n = 2;\nConsole.WriteLine(n is <= 10); // Prints true\nConsole.WriteLine(n is > 5); // Prints false"
},
{
"code": null,
"e": 7702,
"s": 7521,
"text": "This may not be as useful on its own because n is <= 10 is the same as writing n <= 10. However, this syntax will be more convenient with pattern combinators(discussed further). "
},
{
"code": null,
"e": 7978,
"s": 7702,
"text": "Property patterns allow matching values of properties defined on an object. The pattern specifies the name of the property to be matched and then after a colon(:) the value that must match. Multiple properties and their values can be specified by separating them with commas."
},
{
"code": null,
"e": 7988,
"s": 7980,
"text": "Syntax:"
},
{
"code": null,
"e": 8056,
"s": 7990,
"text": "{ Property1: value1, Property2 : value2, ..., PropertyN: valueN }"
},
{
"code": null,
"e": 8088,
"s": 8056,
"text": "Such syntax allows us to write:"
},
{
"code": null,
"e": 8115,
"s": 8090,
"text": "“Geeks” is { Length: 4 }"
},
{
"code": null,
"e": 8127,
"s": 8115,
"text": "Instead of:"
},
{
"code": null,
"e": 8149,
"s": 8129,
"text": "“Geeks”.Length == 4"
},
{
"code": null,
"e": 8158,
"s": 8149,
"text": "Example:"
},
{
"code": null,
"e": 8163,
"s": 8160,
"text": "C#"
},
{
"code": "// C# program to illustrate the concept of Property Patternusing System; class GFG{ public static void DescribeStringLength(string str){ // Constant pattern, discussed further if (str is null) { Console.WriteLine(\"Null string\"); } if (str is { Length: 0 }) { Console.WriteLine(\"Empty string\"); return; } if (str is { Length: 1 }) { Console.WriteLine(\"String of length 1\"); return; } Console.WriteLine(\"Length greater than 1\"); return;} // Driver codestatic public void Main(){ DescribeStringLength(\"Hello!\"); Console.WriteLine(); DescribeStringLength(\"\"); Console.WriteLine(); DescribeStringLength(\"X\"); Console.WriteLine();}}",
"e": 8887,
"s": 8163,
"text": null
},
{
"code": null,
"e": 8898,
"s": 8890,
"text": "Output:"
},
{
"code": null,
"e": 8954,
"s": 8900,
"text": "Length greater than 1\nEmpty string\nString of length 1"
},
{
"code": null,
"e": 9278,
"s": 8954,
"text": "Positional patterns allow specifying a set of values in parentheses and will match if each value in the parentheses matches the values of the matched object. The object values are extracted through deconstruction. Positional patterns are based on the deconstruction pattern. The following types can use positional patterns:"
},
{
"code": null,
"e": 9516,
"s": 9278,
"text": "Any type with one or more deconstructors. A type is said to have a deconstructor if it defines one or more Deconstruct() methods that accept one or more out parameters. The Deconstruct() method can also be defined as an extension method."
},
{
"code": null,
"e": 9561,
"s": 9516,
"text": "Tuple types(instances of System.ValueTuple)."
},
{
"code": null,
"e": 9600,
"s": 9561,
"text": "Positional record types. (since C# 9)."
},
{
"code": null,
"e": 9608,
"s": 9600,
"text": "Syntax:"
},
{
"code": null,
"e": 9638,
"s": 9610,
"text": "(constant1, constant2, ...)"
},
{
"code": null,
"e": 9716,
"s": 9638,
"text": "Example 1: Positional Pattern with a type that defines a Deconstruct() method"
},
{
"code": null,
"e": 10225,
"s": 9716,
"text": "The code below defines two functions LogicalAnd() and LogicalOr(), both of which accept an object of BooleanInput. BooleanInput is a value-type(struct) that represent two Boolean input values. The methods use both these input values and perform a Logical AND and Logical OR operation on these values. C# already has logical AND(&&) and logical OR(||) operators which perform these operations for us. However, the methods in this example implement these operations manually to demonstrate positional patterns."
},
{
"code": null,
"e": 10228,
"s": 10225,
"text": "C#"
},
{
"code": "// C# program to illustrate the concept of Positional Patternusing System; // Represents two inputs to the truth tablepublic struct BooleanInput{ public bool Input1 { get; set; } public bool Input2 { get; set; } public void Deconstruct(out bool input1, out bool input2) { input1 = Input1; input2 = Input2; }} class GFG{ // Performs logical AND on an input objectpublic static bool LogicalAnd(BooleanInput input){ // Using switch expression return input switch { (false, false) => false, (true, false) => false, (false, true) => false, (true, true) => true };} // Performs logical OR on an input objectpublic static bool LogicalOr(BooleanInput input){ // Using switch statement switch (input) { case (false, false): return false; case (true, false): return true; case (false, true): return true; case (true, true): return true; }} // Driver codestatic public void Main(){ var a = new BooleanInput{Input1 = true, Input2 = false}; var b = new BooleanInput{Input1 = true, Input2 = true}; Console.WriteLine(\"Logical AND:\"); Console.WriteLine(LogicalAnd(a)); Console.WriteLine(LogicalAnd(b)); Console.WriteLine(\"Logical OR:\"); Console.WriteLine(LogicalOr(a)); Console.WriteLine(LogicalOr(b));}}",
"e": 11739,
"s": 10228,
"text": null
},
{
"code": null,
"e": 11750,
"s": 11739,
"text": " Output: "
},
{
"code": null,
"e": 11796,
"s": 11750,
"text": "Logical AND:\nFalse\nTrue\nLogical OR:\nTrue\nTrue"
},
{
"code": null,
"e": 11845,
"s": 11796,
"text": "Example 2: Using positional patterns with tuples"
},
{
"code": null,
"e": 12434,
"s": 11845,
"text": "Any instance of System.ValueTuple can be used in positional patterns. C# provides a shorthand syntax for creating tuples using parentheses:(). A tuple can be created quickly on the fly by wrapping a set of already declared variables in parentheses. In the following example, the LocatePoint() method accepts two parameters representing the x and y coordinates of a point then creates a tuple after the switch keyword using an additional pair of parentheses. The outer parentheses are part of the switch statement syntax, the inner parentheses create the tuple using the x and y variables."
},
{
"code": null,
"e": 12437,
"s": 12434,
"text": "C#"
},
{
"code": "// C# program to illustrate the concept of Positional Patternusing System; class GFG{ // Displays the location of a point// by accepting its x and y coordinatespublic static void LocatePoint(int x, int y){ Console.WriteLine($\"Point ({x}, {y}):\"); // Using switch statement // Note the double parantheses switch ((x, y)) { case (0, 0): Console.WriteLine(\"Point at origin\"); break; case (0, _): // _ will match all values for y Console.WriteLine(\"Point on Y axis\"); break; case (_, 0): Console.WriteLine(\"Point on X axis\"); break; default: Console.WriteLine(\"Point elsewhere\"); break; }} // Driver codestatic public void Main(){ LocatePoint(10, 20); LocatePoint(10, 0); LocatePoint(0, 20); LocatePoint(0, 0);}}",
"e": 13301,
"s": 12437,
"text": null
},
{
"code": null,
"e": 13312,
"s": 13301,
"text": " Output: "
},
{
"code": null,
"e": 13436,
"s": 13312,
"text": "Point (10, 20):\nPoint elsewhere\nPoint (10, 0):\nPoint on X axis\nPoint (0, 20):\nPoint on Y axis\nPoint (0, 0):\nPoint at origin"
},
{
"code": null,
"e": 13632,
"s": 13436,
"text": "The constant pattern is the simplest form of a pattern. It consists of a constant value. It is checked whether the expression that is being matched is equal to this constant. The constant can be:"
},
{
"code": null,
"e": 13682,
"s": 13632,
"text": "A numeric, Boolean, character, or string literal."
},
{
"code": null,
"e": 13696,
"s": 13682,
"text": "An enum value"
},
{
"code": null,
"e": 13702,
"s": 13696,
"text": "null."
},
{
"code": null,
"e": 13717,
"s": 13702,
"text": "A const field."
},
{
"code": null,
"e": 13852,
"s": 13717,
"text": "The constant pattern usually appears as part of other patterns as a sub-pattern(discussed further) but it can also be used on its own."
},
{
"code": null,
"e": 13934,
"s": 13852,
"text": "Some examples of the constant pattern being used with the is operator would be: "
},
{
"code": null,
"e": 13965,
"s": 13934,
"text": "expression is 2 // int literal"
},
{
"code": null,
"e": 14005,
"s": 13965,
"text": "expression is \"Geeks\" // string literal"
},
{
"code": null,
"e": 14051,
"s": 14005,
"text": "expression is System.DayOfWeek.Monday // enum"
},
{
"code": null,
"e": 14079,
"s": 14051,
"text": "expression is null // null"
},
{
"code": null,
"e": 14316,
"s": 14079,
"text": "Notice the final example, where the pattern is null. This implies that pattern matching provides another way to check if an object is null. Also, expression is null may be more readable and intuitive than the typical expression == null."
},
{
"code": null,
"e": 14447,
"s": 14316,
"text": "In the context of a switch statement, the constant pattern looks identical to a regular switch statement without pattern matching."
},
{
"code": null,
"e": 14638,
"s": 14447,
"text": "Example: The following example uses a switch expression with the constant pattern in a method called DayOfTheWeek() which returns the name of the day of a week from the number passed to it. "
},
{
"code": null,
"e": 14641,
"s": 14638,
"text": "C#"
},
{
"code": "// C# program to illustrate the concept of Constant Patternusing System; class GFG{ // Returns the name of the day of the weekpublic static string DayOfTheWeek(int day){ // Switch expression return day switch { 1 => \"Sunday\", 2 => \"Monday\", 3 => \"Tuesday\", 4 => \"Wednesday\", 5 => \"Thursday\", 6 => \"Friday\", 7 => \"Saturday\", _ => \"Invalid week day\" };} // Driver codestatic public void Main(){ Console.WriteLine(DayOfTheWeek(5)); Console.WriteLine(DayOfTheWeek(3));}}",
"e": 15190,
"s": 14641,
"text": null
},
{
"code": null,
"e": 15198,
"s": 15190,
"text": "Output:"
},
{
"code": null,
"e": 15215,
"s": 15198,
"text": "Thursday\nTuesday"
},
{
"code": null,
"e": 15725,
"s": 15215,
"text": "The var pattern works slightly different from other patterns. A var pattern match always succeeds, which means, the match result is always true. The purpose of the var pattern is not to test an expression for a pattern but to assign an expression to a variable. This allows reusing the variable in consecutive expressions. The var pattern is a more general form of the type pattern. However, there is no type specified; the var is used instead, so there is no type checking and the match is always successful."
},
{
"code": null,
"e": 15734,
"s": 15725,
"text": "Syntax: "
},
{
"code": null,
"e": 15746,
"s": 15734,
"text": "var varName"
},
{
"code": null,
"e": 15776,
"s": 15746,
"text": "var (varName1, varName2, ...)"
},
{
"code": null,
"e": 15864,
"s": 15776,
"text": "Consider the following code where a DateTime object’s day and month has to be compared:"
},
{
"code": null,
"e": 15947,
"s": 15864,
"text": "var now = DateTime.Now;\nif (now.Month > 6 && now.Day > 15)\n{\n // Do Something\n}"
},
{
"code": null,
"e": 16002,
"s": 15947,
"text": "This can be written in one line using the var pattern:"
},
{
"code": null,
"e": 16088,
"s": 16002,
"text": "if (DateTime.Now is var now && now.Month > 6 && now.Day > 15)\n{\n // Do Something\n}"
},
{
"code": null,
"e": 16242,
"s": 16088,
"text": "C# 9 has also introduced pattern combinators. Pattern combinators allow combining multiple patterns together. The following are the pattern combinators: "
},
{
"code": null,
"e": 16264,
"s": 16242,
"text": "Negative Pattern: not"
},
{
"code": null,
"e": 16289,
"s": 16264,
"text": "Conjunctive Pattern: and"
},
{
"code": null,
"e": 16312,
"s": 16289,
"text": "Disjunctive Pattern or"
},
{
"code": null,
"e": 16318,
"s": 16312,
"text": "not 2"
},
{
"code": null,
"e": 16327,
"s": 16318,
"text": "not < 10"
},
{
"code": null,
"e": 16336,
"s": 16327,
"text": "not null"
},
{
"code": null,
"e": 16349,
"s": 16336,
"text": "> 0 and < 10"
},
{
"code": null,
"e": 16381,
"s": 16349,
"text": "{ Year: 2002 } and { Month: 1 }"
},
{
"code": null,
"e": 16404,
"s": 16381,
"text": "not int and not double"
},
{
"code": null,
"e": 16429,
"s": 16404,
"text": "“Hi” or “Hello” or “Hey”"
},
{
"code": null,
"e": 16444,
"s": 16429,
"text": "null or (0, 0)"
},
{
"code": null,
"e": 16477,
"s": 16444,
"text": "{ Year: 2004 } or { Year: 2002 }"
},
{
"code": null,
"e": 16706,
"s": 16477,
"text": "Pattern combinators are a lot like logical operators(!, &&, ||) but the operands are patterns instead of conditions or Boolean expressions. Combinators make pattern matching more flexible and also helps to save a few keystrokes."
},
{
"code": null,
"e": 16728,
"s": 16708,
"text": "Simpler Comparisons"
},
{
"code": null,
"e": 16929,
"s": 16728,
"text": "By using pattern combinators with the relational pattern, an expression can be compared with multiple other values without repeating the expression over and over. For instance, consider the following:"
},
{
"code": null,
"e": 17019,
"s": 16929,
"text": "int number = 42;\nif (number > 10 && number < 50 && number != 35) \n{\n // Do Something\n}"
},
{
"code": null,
"e": 17082,
"s": 17019,
"text": "With pattern matching and combinators, this can be simplified:"
},
{
"code": null,
"e": 17162,
"s": 17082,
"text": "int number = 42;\nif (number is > 10 and < 50 and not 35)\n{\n // Do Something\n}"
},
{
"code": null,
"e": 17263,
"s": 17162,
"text": "As observable, the variable name number need not be repeated; comparisons can be seamlessly chained."
},
{
"code": null,
"e": 17295,
"s": 17263,
"text": "Checking if a value is non-null"
},
{
"code": null,
"e": 17487,
"s": 17295,
"text": "Under the constant patterns section above, an alternative way to check if a value is null was discussed. Pattern combinators provide a counterpart that allows checking if a value is not null:"
},
{
"code": null,
"e": 17520,
"s": 17487,
"text": "if (expression is not null) \n{\n}"
},
{
"code": null,
"e": 17701,
"s": 17520,
"text": "Example: The following example defines a method called IsVowel() that checks if a character is a vowel or not using the or pattern combinator to combine multiple constant patterns:"
},
{
"code": null,
"e": 17704,
"s": 17701,
"text": "C#"
},
{
"code": "// C# program to illustrate the concept of Pattern Combinatorsusing System; class GFG{ public static bool IsVowel(char c){ return char.ToLower(c) is 'a' or 'e' or 'i' or 'o' or 'u';} // Driver codepublic static void Main(){ Console.WriteLine(IsVowel('A')); Console.WriteLine(IsVowel('B')); Console.WriteLine(IsVowel('e')); Console.WriteLine(IsVowel('x')); Console.WriteLine(IsVowel('O')); Console.WriteLine(IsVowel('P'));}}",
"e": 18153,
"s": 17704,
"text": null
},
{
"code": null,
"e": 18161,
"s": 18153,
"text": "Output:"
},
{
"code": null,
"e": 18194,
"s": 18161,
"text": "True\nFalse\nTrue\nFalse\nTrue\nFalse"
},
{
"code": null,
"e": 18257,
"s": 18194,
"text": "Some patterns support declaring a variable after the pattern. "
},
{
"code": null,
"e": 18384,
"s": 18257,
"text": "Type Pattern: Variable declarations in type patterns are a convenient way to combine both a type check and a cast in one step."
},
{
"code": null,
"e": 18408,
"s": 18384,
"text": "Consider the following:"
},
{
"code": null,
"e": 18472,
"s": 18408,
"text": "object o = 42;\nif (o is int)\n{\n int i = (int) o;\n //...\n}"
},
{
"code": null,
"e": 18544,
"s": 18472,
"text": "This can be reduced down to a single step using a variable declaration:"
},
{
"code": null,
"e": 18589,
"s": 18544,
"text": "object o = 42;\nif (o is int i)\n{\n //...\n}"
},
{
"code": null,
"e": 18709,
"s": 18589,
"text": "Positional and Property Patterns: Positional and property patterns also allow a variable declaration after the pattern:"
},
{
"code": null,
"e": 18781,
"s": 18709,
"text": "if (DateTime.Now is { Month: 12 } now)\n{\n // Do something with now\n}"
},
{
"code": null,
"e": 18860,
"s": 18781,
"text": "var p = (10, 20);\nif (p is (10, 20) coords)\n{\n // Do something with coords\n}"
},
{
"code": null,
"e": 19050,
"s": 18860,
"text": "Here, p and coords contain the same value and coords may little be of any use. But the above syntax is legal and sometimes may be useful with an object that defines a Deconstruct() method. "
},
{
"code": null,
"e": 19166,
"s": 19050,
"text": "Note: Variable declarations are not allowed when using the or and not pattern combinators but are allowed with and."
},
{
"code": null,
"e": 19364,
"s": 19166,
"text": "Sometimes, the value assigned to variables during pattern matching may not be useful. Variable discards allow ignoring the values of such variables. A discard is represented using an underscore(_)."
},
{
"code": null,
"e": 19465,
"s": 19364,
"text": "In type patterns: When using type patterns with variable declarations like in the following example:"
},
{
"code": null,
"e": 19574,
"s": 19465,
"text": "switch (expression)\n{\n case int i:\n Console.WriteLine(\"i is an integer\");\n break;\n ...\n}"
},
{
"code": null,
"e": 19629,
"s": 19574,
"text": "the variable i is never used. So, it can be discarded:"
},
{
"code": null,
"e": 19642,
"s": 19629,
"text": "case int _: "
},
{
"code": null,
"e": 19770,
"s": 19642,
"text": "Beginning with C# 9, it is possible to use type pattern without a variable, which allows getting rid of the underscore as well:"
},
{
"code": null,
"e": 19780,
"s": 19770,
"text": "case int:"
},
{
"code": null,
"e": 20151,
"s": 19780,
"text": "In positional patterns: When using positional patterns, a discard can be used as a wildcard character to match all values in certain positions. For example, in the Point example above, if we want to match when the x-coordinate is 0 and the y-coordinate does not matter, meaning the pattern has to be matched no matter what the y-coordinate is, the following can be done:"
},
{
"code": null,
"e": 20201,
"s": 20151,
"text": "point is (0, _) // will match for all values of y"
},
{
"code": null,
"e": 20310,
"s": 20201,
"text": "It is possible to use a type pattern, positional pattern, and property pattern together without combinators."
},
{
"code": null,
"e": 20318,
"s": 20310,
"text": "Syntax:"
},
{
"code": null,
"e": 20381,
"s": 20318,
"text": "type-pattern positional-pattern property-pattern variable-name"
},
{
"code": null,
"e": 20408,
"s": 20381,
"text": "Consider the Point struct:"
},
{
"code": null,
"e": 20675,
"s": 20408,
"text": "struct Point\n{\n public int X { get; set; }\n public int Y { get; set; }\n public string Name { get; set; }\n public void Deconstruct(out int x, out int y)\n {\n x = X;\n y = Y; \n }\n}\n...\nobject o = Point() { X = 10, Y = 20, Name = \"A\" };"
},
{
"code": null,
"e": 20687,
"s": 20675,
"text": "Instead of:"
},
{
"code": null,
"e": 20735,
"s": 20687,
"text": "if (o is Point p and (10, _) and { Y: 20}) {..}"
},
{
"code": null,
"e": 20765,
"s": 20735,
"text": "The following can be written:"
},
{
"code": null,
"e": 20806,
"s": 20765,
"text": "if (o is Point (10, _) { Y: 20 } p) {..}"
},
{
"code": null,
"e": 21013,
"s": 20806,
"text": "One or more of the patterns can be omitted. However, there must be at least one pattern, and the order when using multiple patterns together must be the same as above. For example, the following is illegal:"
},
{
"code": null,
"e": 21049,
"s": 21013,
"text": "if (o is (10, _) Point { Y: 20 } p)"
},
{
"code": null,
"e": 21250,
"s": 21049,
"text": "A pattern can consist of several sub-patterns. In addition to the ability to combine multiple patterns with pattern combinators, C# also allows a single pattern to consist of several inner patterns. "
},
{
"code": null,
"e": 21260,
"s": 21250,
"text": "Examples:"
},
{
"code": null,
"e": 21324,
"s": 21260,
"text": "Consider the Point struct above and the following object point:"
},
{
"code": null,
"e": 21382,
"s": 21324,
"text": "Point point = new Point() { X = 10, Y = 20, Name = \"B\" };"
},
{
"code": null,
"e": 21433,
"s": 21382,
"text": "Type Pattern and var Pattern in a Property Pattern"
},
{
"code": null,
"e": 21477,
"s": 21433,
"text": "if (point is { X: int x, Y: var y }) { .. }"
},
{
"code": null,
"e": 21530,
"s": 21477,
"text": "Type Pattern and var Pattern in a Positional Pattern"
},
{
"code": null,
"e": 21566,
"s": 21530,
"text": "if (point is (int x, var y)) { .. }"
},
{
"code": null,
"e": 21632,
"s": 21566,
"text": "Relational Pattern in a Positional Pattern and a Property Pattern"
},
{
"code": null,
"e": 21773,
"s": 21632,
"text": "switch (point) \n{\n case (< 10, <= 15): \n .. \n break;\n case { X: < 10, Y: <= 15 }:\n ..\n break;\n ..\n}"
},
{
"code": null,
"e": 21827,
"s": 21773,
"text": "For the next example, consider the following objects:"
},
{
"code": null,
"e": 21925,
"s": 21827,
"text": "var p1 = new Point { X = 0, Y = 1, Name = \"X\" };\nvar p2 = new Point { X = 0, Y = 2, Name = \"Y\" };"
},
{
"code": null,
"e": 21966,
"s": 21925,
"text": "Property Pattern in a Positional Pattern"
},
{
"code": null,
"e": 22011,
"s": 21966,
"text": "if ((p1, p2) is ({ X: 0 }, { X: 0 })) { .. }"
},
{
"code": null,
"e": 22024,
"s": 22011,
"text": "amallkrishna"
},
{
"code": null,
"e": 22039,
"s": 22024,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 22049,
"s": 22039,
"text": "Blogathon"
},
{
"code": null,
"e": 22052,
"s": 22049,
"text": "C#"
}
] |
HashSet size() Method in Java | 26 Nov, 2018
The Java.util.HashSet.size() method is used to get the size of the HashSet or the number of elements present in the HashSet.
Syntax:
Hash_Set.size()
Parameters: This method does not takes any parameter.
Return Value: The method returns the size or the number of elements present in the HashSet.
Below program illustrate the Java.util.HashSet.size() method:
// Java code to illustrate HashSet.size() methodimport java.util.*;import java.util.HashSet; public class HashSetDemo { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add("Welcome"); set.add("To"); set.add("Geeks"); set.add("4"); set.add("Geeks"); // Displaying the HashSet System.out.println("HashSet: " + set); // Displaying the size of the HashSet System.out.println("The size of the set is: " + set.size()); }}
HashSet: [4, Geeks, Welcome, To]
The size of the set is: 4
Java - util package
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Interfaces in Java
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Stack Class in Java
Initializing a List in Java
Introduction to Java
Multithreading in Java | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 178,
"s": 53,
"text": "The Java.util.HashSet.size() method is used to get the size of the HashSet or the number of elements present in the HashSet."
},
{
"code": null,
"e": 186,
"s": 178,
"text": "Syntax:"
},
{
"code": null,
"e": 203,
"s": 186,
"text": "Hash_Set.size()\n"
},
{
"code": null,
"e": 257,
"s": 203,
"text": "Parameters: This method does not takes any parameter."
},
{
"code": null,
"e": 349,
"s": 257,
"text": "Return Value: The method returns the size or the number of elements present in the HashSet."
},
{
"code": null,
"e": 411,
"s": 349,
"text": "Below program illustrate the Java.util.HashSet.size() method:"
},
{
"code": "// Java code to illustrate HashSet.size() methodimport java.util.*;import java.util.HashSet; public class HashSetDemo { public static void main(String args[]) { // Creating an empty HashSet HashSet<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add(\"Welcome\"); set.add(\"To\"); set.add(\"Geeks\"); set.add(\"4\"); set.add(\"Geeks\"); // Displaying the HashSet System.out.println(\"HashSet: \" + set); // Displaying the size of the HashSet System.out.println(\"The size of the set is: \" + set.size()); }}",
"e": 1047,
"s": 411,
"text": null
},
{
"code": null,
"e": 1107,
"s": 1047,
"text": "HashSet: [4, Geeks, Welcome, To]\nThe size of the set is: 4\n"
},
{
"code": null,
"e": 1127,
"s": 1107,
"text": "Java - util package"
},
{
"code": null,
"e": 1144,
"s": 1127,
"text": "Java-Collections"
},
{
"code": null,
"e": 1159,
"s": 1144,
"text": "Java-Functions"
},
{
"code": null,
"e": 1172,
"s": 1159,
"text": "java-hashset"
},
{
"code": null,
"e": 1177,
"s": 1172,
"text": "Java"
},
{
"code": null,
"e": 1182,
"s": 1177,
"text": "Java"
},
{
"code": null,
"e": 1199,
"s": 1182,
"text": "Java-Collections"
},
{
"code": null,
"e": 1297,
"s": 1199,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1316,
"s": 1297,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 1331,
"s": 1316,
"text": "Stream In Java"
},
{
"code": null,
"e": 1349,
"s": 1331,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 1369,
"s": 1349,
"text": "Collections in Java"
},
{
"code": null,
"e": 1393,
"s": 1369,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 1425,
"s": 1393,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 1445,
"s": 1425,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 1473,
"s": 1445,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 1494,
"s": 1473,
"text": "Introduction to Java"
}
] |
java.time.Month.valueOf() Method Example | The java.time.Month.valueOf(String name) method returns the enum constant of this type with the specified name.
Following is the declaration for java.time.Month.valueOf(String name) method.
public static Month valueOf(String name)
name − the name of the enum constant to be returned.
the enum constant with the specified name.
IllegalArgumentException − if this enum type has no constant with the specified name.
IllegalArgumentException − if this enum type has no constant with the specified name.
NullPointerException − if the argument is null.
NullPointerException − if the argument is null.
The following example shows the usage of java.time.Month.valueOf(String name) method.
package com.tutorialspoint;
import java.time.Month;
public class MonthDemo {
public static void main(String[] args) {
Month month = Month.valueOf("MARCH");
System.out.println(month);
}
}
Let us compile and run the above program, this will produce the following result − | [
{
"code": null,
"e": 2161,
"s": 2049,
"text": "The java.time.Month.valueOf(String name) method returns the enum constant of this type with the specified name."
},
{
"code": null,
"e": 2239,
"s": 2161,
"text": "Following is the declaration for java.time.Month.valueOf(String name) method."
},
{
"code": null,
"e": 2281,
"s": 2239,
"text": "public static Month valueOf(String name)\n"
},
{
"code": null,
"e": 2334,
"s": 2281,
"text": "name − the name of the enum constant to be returned."
},
{
"code": null,
"e": 2377,
"s": 2334,
"text": "the enum constant with the specified name."
},
{
"code": null,
"e": 2463,
"s": 2377,
"text": "IllegalArgumentException − if this enum type has no constant with the specified name."
},
{
"code": null,
"e": 2549,
"s": 2463,
"text": "IllegalArgumentException − if this enum type has no constant with the specified name."
},
{
"code": null,
"e": 2597,
"s": 2549,
"text": "NullPointerException − if the argument is null."
},
{
"code": null,
"e": 2645,
"s": 2597,
"text": "NullPointerException − if the argument is null."
},
{
"code": null,
"e": 2731,
"s": 2645,
"text": "The following example shows the usage of java.time.Month.valueOf(String name) method."
},
{
"code": null,
"e": 2939,
"s": 2731,
"text": "package com.tutorialspoint;\n\nimport java.time.Month;\n\npublic class MonthDemo {\n public static void main(String[] args) {\n\n Month month = Month.valueOf(\"MARCH\");\n System.out.println(month);\n }\n}"
}
] |
Python Program to detect the edges of an image using OpenCV | Sobel edge detection method | 27 Dec, 2021
The following program detects the edges of frames in a livestream video content. The code will only compile in linux environment. Make sure that openCV is installed in your system before you run the program.Steps to download the requirements below:
Run the following command on your terminal to install it from the Ubuntu or Debian repository.
sudo apt-get install libopencv-dev python-opencv
OR In order to download OpenCV from the official site run the following command:
bash install-opencv.sh
on your terminal.
Type your sudo password and you will have installed OpenCV.
Principle behind Edge Detection
Edge detection involves mathematical methods to find points in an image where the brightness of pixel intensities changes distinctly.
The first thing we are going to do is find the gradient of the grayscale image, allowing us to find edge-like regions in the x and y direction. The gradient is a multi-variable generalization of the derivative. While a derivative can be defined on functions of a single variable, for functions of several variables, the gradient takes its place.
The gradient is a vector-valued function, as opposed to a derivative, which is scalar-valued. Like the derivative, the gradient represents the slope of the tangent of the graph of the function. More precisely, the gradient points in the direction of the greatest rate of increase of the function, and its magnitude is the slope of the graph in that direction.
Note: In computer vision, transitioning from black-to-white is considered a positive slope, whereas a transition from white-to-black is a negative slope.
Python
# Python program to Edge detection# using OpenCV in Python# using Sobel edge detection# and laplacian methodimport cv2import numpy as np #Capture livestream video content from camera 0cap = cv2.VideoCapture(0) while(1): # Take each frame _, frame = cap.read() # Convert to HSV for simpler calculations hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # Calculation of Sobelx sobelx = cv2.Sobel(frame,cv2.CV_64F,1,0,ksize=5) # Calculation of Sobely sobely = cv2.Sobel(frame,cv2.CV_64F,0,1,ksize=5) # Calculation of Laplacian laplacian = cv2.Laplacian(frame,cv2.CV_64F) cv2.imshow('sobelx',sobelx) cv2.imshow('sobely',sobely) cv2.imshow('laplacian',laplacian) k = cv2.waitKey(5) & 0xFF if k == 27: break cv2.destroyAllWindows() #release the framecap.release()
Calculation of the derivative of an image
A digital image is represented by a matrix that stores the RGB/BGR/HSV(whichever color space the image belongs to) value of each pixel in rows and columns. The derivative of a matrix is calculated by an operator called the Laplacian. In order to calculate a Laplacian, you will need to calculate first two derivatives, called derivatives of Sobel, each of which takes into account the gradient variations in a certain direction: one horizontal, the other vertical.
Horizontal Sobel derivative (Sobel x): It is obtained through the convolution of the image with a matrix called kernel which has always odd size. The kernel with size 3 is the simplest case.
Vertical Sobel derivative (Sobel y): It is obtained through the convolution of the image with a matrix called kernel which has always odd size. The kernel with size 3 is the simplest case.
Convolution is calculated by the following method: Image represents the original image matrix and filter is the kernel matrix.
Factor = 11 – 2- 2- 2- 2- 2 = 3 Offset = 0Weighted Sum = 124*0 + 19*(-2) + 110*(-2) + 53*11 + 44*(-2) + 19*0 + 60*(-2) + 100*0 = 117 O[4,2] = (117/3) + 0 = 39So in the end to get the Laplacian (approximation) we will need to combine the two previous results (Sobelx and Sobely) and store it in laplacian.
Parameters:
cv2.Sobel(): The function cv2.Sobel(frame,cv2.CV_64F,1,0,ksize=5) can be written as
cv2.Sobel(original_image,ddepth,xorder,yorder,kernelsize)
where the first parameter is the original image, the second parameter is the depth of the destination image. When ddepth=-1/CV_64F, the destination image will have the same depth as the source. The third parameter is the order of the derivative x. The fourth parameter is the order of the derivative y. While calculating Sobelx we will set xorder as 1 and yorder as 0 whereas while calculating Sobely, the case will be reversed. The last parameter is the size of the extended Sobel kernel; it must be 1, 3, 5, or 7.
cv2.Laplacian: In the function
cv2.Laplacian(frame,cv2.CV_64F)
the first parameter is the original image and the second parameter is the depth of the destination image.When depth=-1/CV_64F, the destination image will have the same depth as the source.
Edge Detection Applications
Reduce unnecessary information in an image while preserving the structure of image.
Extract important features of image like curves, corners and lines.
Recognizes objects, boundaries and segmentation.
Plays a major role in computer vision and recognition
Related Article: Edge Detection using Canny edge detection method This article is contributed by Pratima Upadhyay. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sweetyty
surindertarika1234
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Python OOPs Concepts
Convert integer to string in Python
Introduction To PYTHON | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n27 Dec, 2021"
},
{
"code": null,
"e": 305,
"s": 54,
"text": "The following program detects the edges of frames in a livestream video content. The code will only compile in linux environment. Make sure that openCV is installed in your system before you run the program.Steps to download the requirements below: "
},
{
"code": null,
"e": 402,
"s": 305,
"text": "Run the following command on your terminal to install it from the Ubuntu or Debian repository. "
},
{
"code": null,
"e": 451,
"s": 402,
"text": "sudo apt-get install libopencv-dev python-opencv"
},
{
"code": null,
"e": 536,
"s": 453,
"text": "OR In order to download OpenCV from the official site run the following command: "
},
{
"code": null,
"e": 559,
"s": 536,
"text": "bash install-opencv.sh"
},
{
"code": null,
"e": 577,
"s": 559,
"text": "on your terminal."
},
{
"code": null,
"e": 637,
"s": 577,
"text": "Type your sudo password and you will have installed OpenCV."
},
{
"code": null,
"e": 672,
"s": 639,
"text": "Principle behind Edge Detection "
},
{
"code": null,
"e": 808,
"s": 672,
"text": "Edge detection involves mathematical methods to find points in an image where the brightness of pixel intensities changes distinctly. "
},
{
"code": null,
"e": 1154,
"s": 808,
"text": "The first thing we are going to do is find the gradient of the grayscale image, allowing us to find edge-like regions in the x and y direction. The gradient is a multi-variable generalization of the derivative. While a derivative can be defined on functions of a single variable, for functions of several variables, the gradient takes its place."
},
{
"code": null,
"e": 1514,
"s": 1154,
"text": "The gradient is a vector-valued function, as opposed to a derivative, which is scalar-valued. Like the derivative, the gradient represents the slope of the tangent of the graph of the function. More precisely, the gradient points in the direction of the greatest rate of increase of the function, and its magnitude is the slope of the graph in that direction."
},
{
"code": null,
"e": 1669,
"s": 1514,
"text": "Note: In computer vision, transitioning from black-to-white is considered a positive slope, whereas a transition from white-to-black is a negative slope. "
},
{
"code": null,
"e": 1676,
"s": 1669,
"text": "Python"
},
{
"code": "# Python program to Edge detection# using OpenCV in Python# using Sobel edge detection# and laplacian methodimport cv2import numpy as np #Capture livestream video content from camera 0cap = cv2.VideoCapture(0) while(1): # Take each frame _, frame = cap.read() # Convert to HSV for simpler calculations hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # Calculation of Sobelx sobelx = cv2.Sobel(frame,cv2.CV_64F,1,0,ksize=5) # Calculation of Sobely sobely = cv2.Sobel(frame,cv2.CV_64F,0,1,ksize=5) # Calculation of Laplacian laplacian = cv2.Laplacian(frame,cv2.CV_64F) cv2.imshow('sobelx',sobelx) cv2.imshow('sobely',sobely) cv2.imshow('laplacian',laplacian) k = cv2.waitKey(5) & 0xFF if k == 27: break cv2.destroyAllWindows() #release the framecap.release()",
"e": 2509,
"s": 1676,
"text": null
},
{
"code": null,
"e": 2551,
"s": 2509,
"text": "Calculation of the derivative of an image"
},
{
"code": null,
"e": 3018,
"s": 2551,
"text": "A digital image is represented by a matrix that stores the RGB/BGR/HSV(whichever color space the image belongs to) value of each pixel in rows and columns. The derivative of a matrix is calculated by an operator called the Laplacian. In order to calculate a Laplacian, you will need to calculate first two derivatives, called derivatives of Sobel, each of which takes into account the gradient variations in a certain direction: one horizontal, the other vertical. "
},
{
"code": null,
"e": 3209,
"s": 3018,
"text": "Horizontal Sobel derivative (Sobel x): It is obtained through the convolution of the image with a matrix called kernel which has always odd size. The kernel with size 3 is the simplest case."
},
{
"code": null,
"e": 3398,
"s": 3209,
"text": "Vertical Sobel derivative (Sobel y): It is obtained through the convolution of the image with a matrix called kernel which has always odd size. The kernel with size 3 is the simplest case."
},
{
"code": null,
"e": 3526,
"s": 3398,
"text": "Convolution is calculated by the following method: Image represents the original image matrix and filter is the kernel matrix. "
},
{
"code": null,
"e": 3831,
"s": 3526,
"text": "Factor = 11 – 2- 2- 2- 2- 2 = 3 Offset = 0Weighted Sum = 124*0 + 19*(-2) + 110*(-2) + 53*11 + 44*(-2) + 19*0 + 60*(-2) + 100*0 = 117 O[4,2] = (117/3) + 0 = 39So in the end to get the Laplacian (approximation) we will need to combine the two previous results (Sobelx and Sobely) and store it in laplacian."
},
{
"code": null,
"e": 3845,
"s": 3831,
"text": "Parameters: "
},
{
"code": null,
"e": 3929,
"s": 3845,
"text": "cv2.Sobel(): The function cv2.Sobel(frame,cv2.CV_64F,1,0,ksize=5) can be written as"
},
{
"code": null,
"e": 3987,
"s": 3929,
"text": "cv2.Sobel(original_image,ddepth,xorder,yorder,kernelsize)"
},
{
"code": null,
"e": 4503,
"s": 3987,
"text": "where the first parameter is the original image, the second parameter is the depth of the destination image. When ddepth=-1/CV_64F, the destination image will have the same depth as the source. The third parameter is the order of the derivative x. The fourth parameter is the order of the derivative y. While calculating Sobelx we will set xorder as 1 and yorder as 0 whereas while calculating Sobely, the case will be reversed. The last parameter is the size of the extended Sobel kernel; it must be 1, 3, 5, or 7."
},
{
"code": null,
"e": 4534,
"s": 4503,
"text": "cv2.Laplacian: In the function"
},
{
"code": null,
"e": 4566,
"s": 4534,
"text": "cv2.Laplacian(frame,cv2.CV_64F)"
},
{
"code": null,
"e": 4755,
"s": 4566,
"text": "the first parameter is the original image and the second parameter is the depth of the destination image.When depth=-1/CV_64F, the destination image will have the same depth as the source."
},
{
"code": null,
"e": 4785,
"s": 4757,
"text": "Edge Detection Applications"
},
{
"code": null,
"e": 4871,
"s": 4787,
"text": "Reduce unnecessary information in an image while preserving the structure of image."
},
{
"code": null,
"e": 4939,
"s": 4871,
"text": "Extract important features of image like curves, corners and lines."
},
{
"code": null,
"e": 4988,
"s": 4939,
"text": "Recognizes objects, boundaries and segmentation."
},
{
"code": null,
"e": 5042,
"s": 4988,
"text": "Plays a major role in computer vision and recognition"
},
{
"code": null,
"e": 5533,
"s": 5042,
"text": "Related Article: Edge Detection using Canny edge detection method This article is contributed by Pratima Upadhyay. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 5542,
"s": 5533,
"text": "sweetyty"
},
{
"code": null,
"e": 5561,
"s": 5542,
"text": "surindertarika1234"
},
{
"code": null,
"e": 5578,
"s": 5561,
"text": "Image-Processing"
},
{
"code": null,
"e": 5585,
"s": 5578,
"text": "OpenCV"
},
{
"code": null,
"e": 5592,
"s": 5585,
"text": "Python"
},
{
"code": null,
"e": 5690,
"s": 5592,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5708,
"s": 5690,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5750,
"s": 5708,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5772,
"s": 5750,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5798,
"s": 5772,
"text": "Python String | replace()"
},
{
"code": null,
"e": 5830,
"s": 5798,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5859,
"s": 5830,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5886,
"s": 5859,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5907,
"s": 5886,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5943,
"s": 5907,
"text": "Convert integer to string in Python"
}
] |
Ruby | Symbol downcase value | 10 Dec, 2019
Symbol#downcase() : downcase() is a Symbol class method which returns the downcased form of symbol based on the position of next capital form.
Syntax: Symbol.downcase()
Parameter: Symbol values
Return: the downcased form of symbol based on the position of next capital form.
Example #1 :
# Ruby code for Symbol.downcase() method # declaring Symbol a = :aBcDeF # declaring Symbolb = :"\u{e4 f6 fc}" # declaring Symbolc = :ABCDEF # Symbol puts "Symbol a : #{a}\n\n"puts "Symbol b : #{b}\n\n"puts "Symbol c : #{c}\n\n\n\n" # downcase form puts "Symbol a downcase form : #{a.downcase}\n\n"puts "Symbol b downcase form : #{b.downcase}\n\n"puts "Symbol c downcase form : #{c.downcase}\n\n"
Output :
Symbol a : aBcDeF
Symbol b : äöü
Symbol c : ABCDEF
Symbol a downcase form : abcdef
Symbol b downcase form : äöü
Symbol c downcase form : abcdef
Example #2 :
# Ruby code for Symbol.downcase() method # declaring Symbol a = :geeks # declaring Symbolb = :"\u{e5 f6 f3}" # declaring Symbolc = :GEEKS # Symbol puts "Symbol a : #{a}\n\n"puts "Symbol b : #{b}\n\n"puts "Symbol c : #{c}\n\n\n\n" # downcase form puts "Symbol a downcase form : #{a.downcase}\n\n"puts "Symbol b downcase form : #{b.downcase}\n\n"puts "Symbol c downcase form : #{c.downcase}\n\n"
Output :
Symbol a : geeks
Symbol b : åöó
Symbol c : GEEKS
Symbol a downcase form : geeks
Symbol b downcase form : åöó
Symbol c downcase form : geeks
Ruby Symbol-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Make a Custom Array of Hashes in Ruby?
Ruby | Array count() operation
Ruby | Array slice() function
Include v/s Extend in Ruby
Global Variable in Ruby
Ruby | Enumerator each_with_index function
Ruby | unless Statement and unless Modifier
Ruby | Hash delete() function
Ruby | Data Types
Ruby | Array class find_index() operation | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n10 Dec, 2019"
},
{
"code": null,
"e": 171,
"s": 28,
"text": "Symbol#downcase() : downcase() is a Symbol class method which returns the downcased form of symbol based on the position of next capital form."
},
{
"code": null,
"e": 197,
"s": 171,
"text": "Syntax: Symbol.downcase()"
},
{
"code": null,
"e": 222,
"s": 197,
"text": "Parameter: Symbol values"
},
{
"code": null,
"e": 303,
"s": 222,
"text": "Return: the downcased form of symbol based on the position of next capital form."
},
{
"code": null,
"e": 316,
"s": 303,
"text": "Example #1 :"
},
{
"code": "# Ruby code for Symbol.downcase() method # declaring Symbol a = :aBcDeF # declaring Symbolb = :\"\\u{e4 f6 fc}\" # declaring Symbolc = :ABCDEF # Symbol puts \"Symbol a : #{a}\\n\\n\"puts \"Symbol b : #{b}\\n\\n\"puts \"Symbol c : #{c}\\n\\n\\n\\n\" # downcase form puts \"Symbol a downcase form : #{a.downcase}\\n\\n\"puts \"Symbol b downcase form : #{b.downcase}\\n\\n\"puts \"Symbol c downcase form : #{c.downcase}\\n\\n\"",
"e": 719,
"s": 316,
"text": null
},
{
"code": null,
"e": 728,
"s": 719,
"text": "Output :"
},
{
"code": null,
"e": 887,
"s": 728,
"text": "Symbol a : aBcDeF\n\nSymbol b : äöü\n\nSymbol c : ABCDEF\n\n\n\nSymbol a downcase form : abcdef\n\nSymbol b downcase form : äöü\n\nSymbol c downcase form : abcdef\n\n"
},
{
"code": null,
"e": 900,
"s": 887,
"text": "Example #2 :"
},
{
"code": "# Ruby code for Symbol.downcase() method # declaring Symbol a = :geeks # declaring Symbolb = :\"\\u{e5 f6 f3}\" # declaring Symbolc = :GEEKS # Symbol puts \"Symbol a : #{a}\\n\\n\"puts \"Symbol b : #{b}\\n\\n\"puts \"Symbol c : #{c}\\n\\n\\n\\n\" # downcase form puts \"Symbol a downcase form : #{a.downcase}\\n\\n\"puts \"Symbol b downcase form : #{b.downcase}\\n\\n\"puts \"Symbol c downcase form : #{c.downcase}\\n\\n\"",
"e": 1301,
"s": 900,
"text": null
},
{
"code": null,
"e": 1310,
"s": 1301,
"text": "Output :"
},
{
"code": null,
"e": 1465,
"s": 1310,
"text": "Symbol a : geeks\n\nSymbol b : åöó\n\nSymbol c : GEEKS\n\n\n\nSymbol a downcase form : geeks\n\nSymbol b downcase form : åöó\n\nSymbol c downcase form : geeks\n\n"
},
{
"code": null,
"e": 1483,
"s": 1465,
"text": "Ruby Symbol-class"
},
{
"code": null,
"e": 1496,
"s": 1483,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 1501,
"s": 1496,
"text": "Ruby"
},
{
"code": null,
"e": 1599,
"s": 1501,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1645,
"s": 1599,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 1676,
"s": 1645,
"text": "Ruby | Array count() operation"
},
{
"code": null,
"e": 1706,
"s": 1676,
"text": "Ruby | Array slice() function"
},
{
"code": null,
"e": 1733,
"s": 1706,
"text": "Include v/s Extend in Ruby"
},
{
"code": null,
"e": 1757,
"s": 1733,
"text": "Global Variable in Ruby"
},
{
"code": null,
"e": 1800,
"s": 1757,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 1844,
"s": 1800,
"text": "Ruby | unless Statement and unless Modifier"
},
{
"code": null,
"e": 1874,
"s": 1844,
"text": "Ruby | Hash delete() function"
},
{
"code": null,
"e": 1892,
"s": 1874,
"text": "Ruby | Data Types"
}
] |
Integer signum() Method in Java | 19 Aug, 2021
The signum function is an odd mathematical function that extracts the sign of a real number. The signum function is also known as sign function. The Integer.signum() method of java.lang returns the signum function of the specified integer value. For a positive value, a negative value and zero the method returns 1, -1 and 0 respectively.
Syntax :
public static int signum(int a)
Parameter: The method takes one parameter a of integer type on which the operation is to be performed.
Return Value: The method returns the signum function of the specified integer value. If the specified value is negative it returns -1, 0 if the specified value is zero, and 1 if the specified value is positive.
Examples:
Consider an integer a = 27
Since 27 is a positive int signum will return= 1
Consider another integer a = -61
Since -61 is a negative int signum will return= -1
Consider the integer value a = 0
For a zero signum, it will return = 0
Below programs illustrate the Java.lang.Integer.signum() Method:
Program 1:
Java
// Java program to illustrate the// Java.lang.Integer.signum() Methodimport java.lang.*; public class Geeks { public static void main(String[] args) { // It will return 1 as the int value is greater than 1 System.out.println(Integer.signum(1726)); // It will return -1 as the int value is less than 1 System.out.println(Integer.signum(-13)); // It will returns 0 as int value is equal to 0 System.out.println(Integer.signum(0));}}
1
-1
0
Program 2:
Java
// Java program to illustrate the// Java.lang.Integer.signum() Methodimport java.lang.*; public class Geeks { public static void main(String[] args) { // It will return 1 as the int value is greater than 1 System.out.println(Integer.signum(-1726)); // It will return -1 as the int value is less than 1 System.out.println(Integer.signum(13)); // It will returns 0 as int value is equal to 0 System.out.println(Integer.signum(0));}}
-1
1
0
Program 3: For a decimal value and string. Note: It returns an error message when a decimal value and string is passed as an argument.
Java
// Java program to illustrate the// Java.lang.Integer.signum() Methodimport java.lang.*; public class Geeks { public static void main(String[] args) { //returns compile time error as passed argument is a decimal value System.out.println(Integer.signum(3.81)); //returns compile time error as passed argument is a string System.out.println(Integer.signum("77")); }}
prog.java:10: error: incompatible types: possible lossy conversion from double to int
System.out.println(Integer.signum(3.81));
^
prog.java:14: error: incompatible types: String cannot be converted to int
System.out.println(Integer.signum("77"));
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
2 errors
kalrap615
Java-Functions
Java-Integer
Java-lang package
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
ArrayList in Java
Collections in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n19 Aug, 2021"
},
{
"code": null,
"e": 367,
"s": 28,
"text": "The signum function is an odd mathematical function that extracts the sign of a real number. The signum function is also known as sign function. The Integer.signum() method of java.lang returns the signum function of the specified integer value. For a positive value, a negative value and zero the method returns 1, -1 and 0 respectively."
},
{
"code": null,
"e": 377,
"s": 367,
"text": "Syntax : "
},
{
"code": null,
"e": 409,
"s": 377,
"text": "public static int signum(int a)"
},
{
"code": null,
"e": 512,
"s": 409,
"text": "Parameter: The method takes one parameter a of integer type on which the operation is to be performed."
},
{
"code": null,
"e": 723,
"s": 512,
"text": "Return Value: The method returns the signum function of the specified integer value. If the specified value is negative it returns -1, 0 if the specified value is zero, and 1 if the specified value is positive."
},
{
"code": null,
"e": 735,
"s": 723,
"text": "Examples: "
},
{
"code": null,
"e": 982,
"s": 735,
"text": "Consider an integer a = 27\nSince 27 is a positive int signum will return= 1\n \nConsider another integer a = -61\nSince -61 is a negative int signum will return= -1\n \nConsider the integer value a = 0\nFor a zero signum, it will return = 0 "
},
{
"code": null,
"e": 1048,
"s": 982,
"text": "Below programs illustrate the Java.lang.Integer.signum() Method: "
},
{
"code": null,
"e": 1061,
"s": 1048,
"text": "Program 1: "
},
{
"code": null,
"e": 1066,
"s": 1061,
"text": "Java"
},
{
"code": "// Java program to illustrate the// Java.lang.Integer.signum() Methodimport java.lang.*; public class Geeks { public static void main(String[] args) { // It will return 1 as the int value is greater than 1 System.out.println(Integer.signum(1726)); // It will return -1 as the int value is less than 1 System.out.println(Integer.signum(-13)); // It will returns 0 as int value is equal to 0 System.out.println(Integer.signum(0));}}",
"e": 1520,
"s": 1066,
"text": null
},
{
"code": null,
"e": 1527,
"s": 1520,
"text": "1\n-1\n0"
},
{
"code": null,
"e": 1541,
"s": 1529,
"text": "Program 2: "
},
{
"code": null,
"e": 1546,
"s": 1541,
"text": "Java"
},
{
"code": "// Java program to illustrate the// Java.lang.Integer.signum() Methodimport java.lang.*; public class Geeks { public static void main(String[] args) { // It will return 1 as the int value is greater than 1 System.out.println(Integer.signum(-1726)); // It will return -1 as the int value is less than 1 System.out.println(Integer.signum(13)); // It will returns 0 as int value is equal to 0 System.out.println(Integer.signum(0));}}",
"e": 2000,
"s": 1546,
"text": null
},
{
"code": null,
"e": 2007,
"s": 2000,
"text": "-1\n1\n0"
},
{
"code": null,
"e": 2144,
"s": 2009,
"text": "Program 3: For a decimal value and string. Note: It returns an error message when a decimal value and string is passed as an argument."
},
{
"code": null,
"e": 2149,
"s": 2144,
"text": "Java"
},
{
"code": "// Java program to illustrate the// Java.lang.Integer.signum() Methodimport java.lang.*; public class Geeks { public static void main(String[] args) { //returns compile time error as passed argument is a decimal value System.out.println(Integer.signum(3.81)); //returns compile time error as passed argument is a string System.out.println(Integer.signum(\"77\")); }}",
"e": 2538,
"s": 2149,
"text": null
},
{
"code": null,
"e": 2972,
"s": 2538,
"text": "prog.java:10: error: incompatible types: possible lossy conversion from double to int\n System.out.println(Integer.signum(3.81));\n ^\nprog.java:14: error: incompatible types: String cannot be converted to int\n System.out.println(Integer.signum(\"77\"));\n ^\nNote: Some messages have been simplified; recompile with -Xdiags:verbose to get full output\n2 errors"
},
{
"code": null,
"e": 2984,
"s": 2974,
"text": "kalrap615"
},
{
"code": null,
"e": 2999,
"s": 2984,
"text": "Java-Functions"
},
{
"code": null,
"e": 3012,
"s": 2999,
"text": "Java-Integer"
},
{
"code": null,
"e": 3030,
"s": 3012,
"text": "Java-lang package"
},
{
"code": null,
"e": 3040,
"s": 3030,
"text": "java-math"
},
{
"code": null,
"e": 3045,
"s": 3040,
"text": "Java"
},
{
"code": null,
"e": 3050,
"s": 3045,
"text": "Java"
},
{
"code": null,
"e": 3148,
"s": 3050,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3199,
"s": 3148,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3230,
"s": 3199,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3249,
"s": 3230,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3279,
"s": 3249,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3294,
"s": 3279,
"text": "Stream In Java"
},
{
"code": null,
"e": 3312,
"s": 3294,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3332,
"s": 3312,
"text": "Collections in Java"
},
{
"code": null,
"e": 3356,
"s": 3332,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 3388,
"s": 3356,
"text": "Multidimensional Arrays in Java"
}
] |
Java Program to Rotate Elements of the List | 28 Dec, 2020
List is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. In this article, we are going to see how to rotate elements of a list. Let’s consider the following list.
ORIGINAL LIST BEFORE ROTATION
There are two types of rotations in a list. They are right rotation and left rotation. After Four Right Rotations the list becomes as shown below:
LIST AFTER ROTATING FOUR POSITIONS
Method 1: (Without Using in-built methods)
Working For Right Rotation
First store the last element of the list in a temp variable.
Move the elements in one position towards the right.
Now change the first element value of the list with value in a temp variable.
Update the value to a temp variable to the new last element.
Repeat the above steps required a number of rotations.
Example:
Java
// Java Program to Rotate Elements of the Listimport java.io.*;import java.util.*;class GFG { public static void main(String[] args) { // creating ArrayList List<Integer> my_list = new ArrayList<>(); my_list.add(10); my_list.add(20); my_list.add(30); my_list.add(40); my_list.add(50); my_list.add(60); my_list.add(70); // Printing list before rotation System.out.println( "List Before Rotation : " + Arrays.toString(my_list.toArray())); // Loop according to the number of rotations for (int i = 0; i < 4; i++) { // storing the last element in the list int temp = my_list.get(6); // traverse the list and move elements to right for (int j = 6; j > 0; j--) { my_list.set(j, my_list.get(j - 1)); } my_list.set(0, temp); } // Printing list after rotation System.out.println( "List After Rotation : " + Arrays.toString(my_list.toArray())); }}
List Before Rotation : [10, 20, 30, 40, 50, 60, 70]
List After Rotation : [40, 50, 60, 70, 10, 20, 30]
After Four Left Rotations the list becomes as shown below:
LIST AFTER ROTATING FOUR POSITIONS
Working For Left Rotation
First store the first element of the list in a temp variable.
Move the elements in one position towards the left.
Now change the last element value of the list with the value in the temp variable.
Update the value to a temp variable to the new first element.
Repeat the above steps required a number of rotations.
Example
Java
// Java Program to Rotate Elements of the List import java.io.*;import java.util.*;class GFG { public static void main(String[] args) { // creating array list List<Integer> my_list = new ArrayList<>(); my_list.add(10); my_list.add(20); my_list.add(30); my_list.add(40); my_list.add(50); my_list.add(60); my_list.add(70); // Printing list before rotation System.out.println( "List Before Rotation : " + Arrays.toString(my_list.toArray())); // Loop according to the number of rotations for (int i = 0; i < 4; i++) { // storing the first element in the list int temp = my_list.get(0); // traverse the list and move elements to left for (int j = 0; j < 6; j++) { my_list.set(j, my_list.get(j + 1)); } my_list.set(6, temp); } // Printing list after rotation System.out.println( "List After Rotation : " + Arrays.toString(my_list.toArray())); }}
List Before Rotation : [10, 20, 30, 40, 50, 60, 70]
List After Rotation : [50, 60, 70, 10, 20, 30, 40]
Method 2: (Rotation Using Collections.rotate(list, distance) method)
Both left and right rotations can be performed directly using Java Collections.
Syntax
Collections.rotate(list_name , distance)
Parameters:
list_name: name of the list.
distance: Distance is the number of elements that we have to rotate.
Returns: It returns a rotated list.
Note: Negative Distance gives Left Rotation while Positive gives Right Rotation.
Example: Using Positive distance to get the Right Rotation.
Java
// Java Program to Rotate Elements of the List import java.io.*;import java.util.*;class GFG { public static void main(String[] args) { // creating array list List<Integer> my_list = new ArrayList<>(); my_list.add(10); my_list.add(20); my_list.add(30); my_list.add(40); my_list.add(50); my_list.add(60); my_list.add(70); // Printing list before rotation System.out.println( "List Before Rotation : " + Arrays.toString(my_list.toArray())); // Rotating the list at distance 4 Collections.rotate(my_list, 4); // Printing list after rotation System.out.println( "List After Rotation : " + Arrays.toString(my_list.toArray())); }}
List Before Rotation : [10, 20, 30, 40, 50, 60, 70]
List After Rotation : [40, 50, 60, 70, 10, 20, 30]
Example: Using Negative distance to get the Left Rotation.
Java
// Java Program to Rotate Elements of the List import java.io.*;import java.util.*;class GFG { public static void main(String[] args) { // creating array list List<Integer> my_list = new ArrayList<>(); my_list.add(10); my_list.add(20); my_list.add(30); my_list.add(40); my_list.add(50); my_list.add(60); my_list.add(70); // Printing list before rotation System.out.println( "List Before Rotation : " + Arrays.toString(my_list.toArray())); // Rotating the list at distance -3 Collections.rotate(my_list, -4); // Printing list after rotation System.out.println( "List After Rotation : " + Arrays.toString(my_list.toArray())); }}
List Before Rotation : [10, 20, 30, 40, 50, 60, 70]
List After Rotation : [50, 60, 70, 10, 20, 30, 40]
java-list
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java
Java Program to Remove Duplicate Elements From the Array | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Dec, 2020"
},
{
"code": null,
"e": 339,
"s": 54,
"text": "List is an ordered collection of objects in which duplicate values can be stored. Since List preserves the insertion order, it allows positional access and insertion of elements. In this article, we are going to see how to rotate elements of a list. Let’s consider the following list."
},
{
"code": null,
"e": 369,
"s": 339,
"text": "ORIGINAL LIST BEFORE ROTATION"
},
{
"code": null,
"e": 516,
"s": 369,
"text": "There are two types of rotations in a list. They are right rotation and left rotation. After Four Right Rotations the list becomes as shown below:"
},
{
"code": null,
"e": 552,
"s": 516,
"text": "LIST AFTER ROTATING FOUR POSITIONS"
},
{
"code": null,
"e": 595,
"s": 552,
"text": "Method 1: (Without Using in-built methods)"
},
{
"code": null,
"e": 622,
"s": 595,
"text": "Working For Right Rotation"
},
{
"code": null,
"e": 683,
"s": 622,
"text": "First store the last element of the list in a temp variable."
},
{
"code": null,
"e": 736,
"s": 683,
"text": "Move the elements in one position towards the right."
},
{
"code": null,
"e": 814,
"s": 736,
"text": "Now change the first element value of the list with value in a temp variable."
},
{
"code": null,
"e": 875,
"s": 814,
"text": "Update the value to a temp variable to the new last element."
},
{
"code": null,
"e": 930,
"s": 875,
"text": "Repeat the above steps required a number of rotations."
},
{
"code": null,
"e": 939,
"s": 930,
"text": "Example:"
},
{
"code": null,
"e": 944,
"s": 939,
"text": "Java"
},
{
"code": "// Java Program to Rotate Elements of the Listimport java.io.*;import java.util.*;class GFG { public static void main(String[] args) { // creating ArrayList List<Integer> my_list = new ArrayList<>(); my_list.add(10); my_list.add(20); my_list.add(30); my_list.add(40); my_list.add(50); my_list.add(60); my_list.add(70); // Printing list before rotation System.out.println( \"List Before Rotation : \" + Arrays.toString(my_list.toArray())); // Loop according to the number of rotations for (int i = 0; i < 4; i++) { // storing the last element in the list int temp = my_list.get(6); // traverse the list and move elements to right for (int j = 6; j > 0; j--) { my_list.set(j, my_list.get(j - 1)); } my_list.set(0, temp); } // Printing list after rotation System.out.println( \"List After Rotation : \" + Arrays.toString(my_list.toArray())); }}",
"e": 2063,
"s": 944,
"text": null
},
{
"code": null,
"e": 2167,
"s": 2063,
"text": "List Before Rotation : [10, 20, 30, 40, 50, 60, 70]\nList After Rotation : [40, 50, 60, 70, 10, 20, 30]"
},
{
"code": null,
"e": 2226,
"s": 2167,
"text": "After Four Left Rotations the list becomes as shown below:"
},
{
"code": null,
"e": 2261,
"s": 2226,
"text": "LIST AFTER ROTATING FOUR POSITIONS"
},
{
"code": null,
"e": 2287,
"s": 2261,
"text": "Working For Left Rotation"
},
{
"code": null,
"e": 2349,
"s": 2287,
"text": "First store the first element of the list in a temp variable."
},
{
"code": null,
"e": 2401,
"s": 2349,
"text": "Move the elements in one position towards the left."
},
{
"code": null,
"e": 2484,
"s": 2401,
"text": "Now change the last element value of the list with the value in the temp variable."
},
{
"code": null,
"e": 2546,
"s": 2484,
"text": "Update the value to a temp variable to the new first element."
},
{
"code": null,
"e": 2601,
"s": 2546,
"text": "Repeat the above steps required a number of rotations."
},
{
"code": null,
"e": 2609,
"s": 2601,
"text": "Example"
},
{
"code": null,
"e": 2614,
"s": 2609,
"text": "Java"
},
{
"code": "// Java Program to Rotate Elements of the List import java.io.*;import java.util.*;class GFG { public static void main(String[] args) { // creating array list List<Integer> my_list = new ArrayList<>(); my_list.add(10); my_list.add(20); my_list.add(30); my_list.add(40); my_list.add(50); my_list.add(60); my_list.add(70); // Printing list before rotation System.out.println( \"List Before Rotation : \" + Arrays.toString(my_list.toArray())); // Loop according to the number of rotations for (int i = 0; i < 4; i++) { // storing the first element in the list int temp = my_list.get(0); // traverse the list and move elements to left for (int j = 0; j < 6; j++) { my_list.set(j, my_list.get(j + 1)); } my_list.set(6, temp); } // Printing list after rotation System.out.println( \"List After Rotation : \" + Arrays.toString(my_list.toArray())); }}",
"e": 3708,
"s": 2614,
"text": null
},
{
"code": null,
"e": 3812,
"s": 3708,
"text": "List Before Rotation : [10, 20, 30, 40, 50, 60, 70]\nList After Rotation : [50, 60, 70, 10, 20, 30, 40]"
},
{
"code": null,
"e": 3881,
"s": 3812,
"text": "Method 2: (Rotation Using Collections.rotate(list, distance) method)"
},
{
"code": null,
"e": 3961,
"s": 3881,
"text": "Both left and right rotations can be performed directly using Java Collections."
},
{
"code": null,
"e": 3968,
"s": 3961,
"text": "Syntax"
},
{
"code": null,
"e": 4009,
"s": 3968,
"text": "Collections.rotate(list_name , distance)"
},
{
"code": null,
"e": 4022,
"s": 4009,
"text": "Parameters: "
},
{
"code": null,
"e": 4051,
"s": 4022,
"text": "list_name: name of the list."
},
{
"code": null,
"e": 4120,
"s": 4051,
"text": "distance: Distance is the number of elements that we have to rotate."
},
{
"code": null,
"e": 4156,
"s": 4120,
"text": "Returns: It returns a rotated list."
},
{
"code": null,
"e": 4237,
"s": 4156,
"text": "Note: Negative Distance gives Left Rotation while Positive gives Right Rotation."
},
{
"code": null,
"e": 4297,
"s": 4237,
"text": "Example: Using Positive distance to get the Right Rotation."
},
{
"code": null,
"e": 4302,
"s": 4297,
"text": "Java"
},
{
"code": "// Java Program to Rotate Elements of the List import java.io.*;import java.util.*;class GFG { public static void main(String[] args) { // creating array list List<Integer> my_list = new ArrayList<>(); my_list.add(10); my_list.add(20); my_list.add(30); my_list.add(40); my_list.add(50); my_list.add(60); my_list.add(70); // Printing list before rotation System.out.println( \"List Before Rotation : \" + Arrays.toString(my_list.toArray())); // Rotating the list at distance 4 Collections.rotate(my_list, 4); // Printing list after rotation System.out.println( \"List After Rotation : \" + Arrays.toString(my_list.toArray())); }}",
"e": 5095,
"s": 4302,
"text": null
},
{
"code": null,
"e": 5199,
"s": 5095,
"text": "List Before Rotation : [10, 20, 30, 40, 50, 60, 70]\nList After Rotation : [40, 50, 60, 70, 10, 20, 30]"
},
{
"code": null,
"e": 5258,
"s": 5199,
"text": "Example: Using Negative distance to get the Left Rotation."
},
{
"code": null,
"e": 5263,
"s": 5258,
"text": "Java"
},
{
"code": "// Java Program to Rotate Elements of the List import java.io.*;import java.util.*;class GFG { public static void main(String[] args) { // creating array list List<Integer> my_list = new ArrayList<>(); my_list.add(10); my_list.add(20); my_list.add(30); my_list.add(40); my_list.add(50); my_list.add(60); my_list.add(70); // Printing list before rotation System.out.println( \"List Before Rotation : \" + Arrays.toString(my_list.toArray())); // Rotating the list at distance -3 Collections.rotate(my_list, -4); // Printing list after rotation System.out.println( \"List After Rotation : \" + Arrays.toString(my_list.toArray())); }}",
"e": 6056,
"s": 5263,
"text": null
},
{
"code": null,
"e": 6160,
"s": 6056,
"text": "List Before Rotation : [10, 20, 30, 40, 50, 60, 70]\nList After Rotation : [50, 60, 70, 10, 20, 30, 40]"
},
{
"code": null,
"e": 6170,
"s": 6160,
"text": "java-list"
},
{
"code": null,
"e": 6177,
"s": 6170,
"text": "Picked"
},
{
"code": null,
"e": 6182,
"s": 6177,
"text": "Java"
},
{
"code": null,
"e": 6196,
"s": 6182,
"text": "Java Programs"
},
{
"code": null,
"e": 6201,
"s": 6196,
"text": "Java"
},
{
"code": null,
"e": 6299,
"s": 6201,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6314,
"s": 6299,
"text": "Stream In Java"
},
{
"code": null,
"e": 6335,
"s": 6314,
"text": "Introduction to Java"
},
{
"code": null,
"e": 6356,
"s": 6335,
"text": "Constructors in Java"
},
{
"code": null,
"e": 6375,
"s": 6356,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 6392,
"s": 6375,
"text": "Generics in Java"
},
{
"code": null,
"e": 6418,
"s": 6392,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 6452,
"s": 6418,
"text": "Convert Double to Integer in Java"
},
{
"code": null,
"e": 6499,
"s": 6452,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 6537,
"s": 6499,
"text": "Factory method design pattern in Java"
}
] |
Difference between Decimal, Float and Double in .Net | 18 Jun, 2021
Float : It is a floating binary point type variable. Which means it represents a number in it’s binary form. Float is a single precision 32 bits(6-9 significant figures) data type. It is used mostly in graphic libraries because of very high demand for processing power, and also in conditions where rounding errors are not very important.
Double : It is also a floating binary point type variable with double precision and 64 bits size(15-17 significant figures). Double are probably the most generally used data type for real values, except for financial applications and places where high accuracy is desired.
Decimal : It is a floating decimal point type variable. Which means it represents a number using decimal numbers (0-9). It uses 128 bits(28-29 significant figures) for storing and representing data. Therefore, it has more precision than float and double. They are mostly used in financial applications because of their high precision and easy to avoid rounding errors.
Example –
C#
using System; public class GFG { static public void Main() { double d = 0.42e2; //double data type Console.WriteLine(d); // output 42 float f = 134.45E-2f; //float data type Console.WriteLine(f); // output: 1.3445 decimal m = 1.5E6m; //decimal data type Console.WriteLine(m); // output: 1500000 }}
Output –
Example of double, float and decimal
Comparison between Float, Double and Decimal on the Basis of :
No. of Bits used –
Float uses 32 bits to represent data.Double uses 64 bits to represent data.Decimal uses 128 bits to represent data.
Float uses 32 bits to represent data.
Double uses 64 bits to represent data.
Decimal uses 128 bits to represent data.
Range of values –
The float value ranges from approximately ±1.5e-45 to ±3.4e38.The double value ranges from approximately ±5.0e-324 to ±1.7e308.The Decimal value ranges from approximately ±1.0e-28 to ±7.9e28.
The float value ranges from approximately ±1.5e-45 to ±3.4e38.
The double value ranges from approximately ±5.0e-324 to ±1.7e308.
The Decimal value ranges from approximately ±1.0e-28 to ±7.9e28.
Precision –
Float represent data with single precision.Double represent data with double precision.Decimal has higher precision than float and Double.
Float represent data with single precision.
Double represent data with double precision.
Decimal has higher precision than float and Double.
Accuracy –
Float is less accurate than Double and Decimal.Double is more accurate than Float but less accurate than Decimal.Decimal is more accurate than Float and Double.
Float is less accurate than Double and Decimal.
Double is more accurate than Float but less accurate than Decimal.
Decimal is more accurate than Float and Double.
For documentation related to Float , double and Decimal, kindly visit here.
Picked
GATE CS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between Clustered and Non-clustered index
Three address code in Compiler
Differences between IPv4 and IPv6
Introduction of Process Synchronization
Phases of a Compiler
Difference between DELETE, DROP and TRUNCATE
Segmentation in Operating System
Code Optimization in Compiler Design
Difference between Primary Key and Foreign Key
Peephole Optimization in Compiler Design | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n18 Jun, 2021"
},
{
"code": null,
"e": 391,
"s": 52,
"text": "Float : It is a floating binary point type variable. Which means it represents a number in it’s binary form. Float is a single precision 32 bits(6-9 significant figures) data type. It is used mostly in graphic libraries because of very high demand for processing power, and also in conditions where rounding errors are not very important."
},
{
"code": null,
"e": 664,
"s": 391,
"text": "Double : It is also a floating binary point type variable with double precision and 64 bits size(15-17 significant figures). Double are probably the most generally used data type for real values, except for financial applications and places where high accuracy is desired."
},
{
"code": null,
"e": 1033,
"s": 664,
"text": "Decimal : It is a floating decimal point type variable. Which means it represents a number using decimal numbers (0-9). It uses 128 bits(28-29 significant figures) for storing and representing data. Therefore, it has more precision than float and double. They are mostly used in financial applications because of their high precision and easy to avoid rounding errors."
},
{
"code": null,
"e": 1044,
"s": 1033,
"text": "Example – "
},
{
"code": null,
"e": 1047,
"s": 1044,
"text": "C#"
},
{
"code": "using System; public class GFG { static public void Main() { double d = 0.42e2; //double data type Console.WriteLine(d); // output 42 float f = 134.45E-2f; //float data type Console.WriteLine(f); // output: 1.3445 decimal m = 1.5E6m; //decimal data type Console.WriteLine(m); // output: 1500000 }}",
"e": 1411,
"s": 1047,
"text": null
},
{
"code": null,
"e": 1420,
"s": 1411,
"text": "Output –"
},
{
"code": null,
"e": 1457,
"s": 1420,
"text": "Example of double, float and decimal"
},
{
"code": null,
"e": 1521,
"s": 1457,
"text": "Comparison between Float, Double and Decimal on the Basis of : "
},
{
"code": null,
"e": 1540,
"s": 1521,
"text": "No. of Bits used –"
},
{
"code": null,
"e": 1656,
"s": 1540,
"text": "Float uses 32 bits to represent data.Double uses 64 bits to represent data.Decimal uses 128 bits to represent data."
},
{
"code": null,
"e": 1694,
"s": 1656,
"text": "Float uses 32 bits to represent data."
},
{
"code": null,
"e": 1733,
"s": 1694,
"text": "Double uses 64 bits to represent data."
},
{
"code": null,
"e": 1774,
"s": 1733,
"text": "Decimal uses 128 bits to represent data."
},
{
"code": null,
"e": 1792,
"s": 1774,
"text": "Range of values –"
},
{
"code": null,
"e": 1984,
"s": 1792,
"text": "The float value ranges from approximately ±1.5e-45 to ±3.4e38.The double value ranges from approximately ±5.0e-324 to ±1.7e308.The Decimal value ranges from approximately ±1.0e-28 to ±7.9e28."
},
{
"code": null,
"e": 2047,
"s": 1984,
"text": "The float value ranges from approximately ±1.5e-45 to ±3.4e38."
},
{
"code": null,
"e": 2113,
"s": 2047,
"text": "The double value ranges from approximately ±5.0e-324 to ±1.7e308."
},
{
"code": null,
"e": 2178,
"s": 2113,
"text": "The Decimal value ranges from approximately ±1.0e-28 to ±7.9e28."
},
{
"code": null,
"e": 2190,
"s": 2178,
"text": "Precision –"
},
{
"code": null,
"e": 2329,
"s": 2190,
"text": "Float represent data with single precision.Double represent data with double precision.Decimal has higher precision than float and Double."
},
{
"code": null,
"e": 2373,
"s": 2329,
"text": "Float represent data with single precision."
},
{
"code": null,
"e": 2418,
"s": 2373,
"text": "Double represent data with double precision."
},
{
"code": null,
"e": 2470,
"s": 2418,
"text": "Decimal has higher precision than float and Double."
},
{
"code": null,
"e": 2481,
"s": 2470,
"text": "Accuracy –"
},
{
"code": null,
"e": 2642,
"s": 2481,
"text": "Float is less accurate than Double and Decimal.Double is more accurate than Float but less accurate than Decimal.Decimal is more accurate than Float and Double."
},
{
"code": null,
"e": 2690,
"s": 2642,
"text": "Float is less accurate than Double and Decimal."
},
{
"code": null,
"e": 2757,
"s": 2690,
"text": "Double is more accurate than Float but less accurate than Decimal."
},
{
"code": null,
"e": 2805,
"s": 2757,
"text": "Decimal is more accurate than Float and Double."
},
{
"code": null,
"e": 2881,
"s": 2805,
"text": "For documentation related to Float , double and Decimal, kindly visit here."
},
{
"code": null,
"e": 2888,
"s": 2881,
"text": "Picked"
},
{
"code": null,
"e": 2896,
"s": 2888,
"text": "GATE CS"
},
{
"code": null,
"e": 2994,
"s": 2896,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3047,
"s": 2994,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 3078,
"s": 3047,
"text": "Three address code in Compiler"
},
{
"code": null,
"e": 3112,
"s": 3078,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 3152,
"s": 3112,
"text": "Introduction of Process Synchronization"
},
{
"code": null,
"e": 3173,
"s": 3152,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 3218,
"s": 3173,
"text": "Difference between DELETE, DROP and TRUNCATE"
},
{
"code": null,
"e": 3251,
"s": 3218,
"text": "Segmentation in Operating System"
},
{
"code": null,
"e": 3288,
"s": 3251,
"text": "Code Optimization in Compiler Design"
},
{
"code": null,
"e": 3335,
"s": 3288,
"text": "Difference between Primary Key and Foreign Key"
}
] |
Finding Hard Samples in Your Image Classification Dataset | by Eric Hofesmann | Towards Data Science | Say you have a repository of data with millions of unlabeled images in it. You managed to label a subset of data and trained an image classification model on it, but it’s not performing as well as you hope. How do you decide which new samples to annotate and add to your training set?
You could just randomly select new samples to annotate, but there is a better way. Hard sample mining is a tried and true method to distill a large amount of raw unlabeled data into smaller high quality labeled datasets.
A hard sample is one where your machine learning (ML) model finds it difficult to correctly predict the label.
In an image classification dataset, a hard sample could be anything from a cat that looks like a dog to a blurry resolution image. If you expect your model to perform well on these hard samples, then you may need to “mine” more examples of these hard samples to add to your training dataset. Exposing your model to more hard samples during training will allow it to perform better on those types of samples later on.
Hard samples are useful for more than just training data, they are also necessary to include in your test set. If your test data is composed primarily of easy samples, then your performance will soon reach an upper bound causing progress to stagnate. Adding hard samples to a test set will give you a better idea of how models perform in harder edge cases and can provide more insight into which models are more reliable.
Follow along in your browser with this Colab notebook!
This post will walk you through how to use the new open-source ML tool that I have been working on, FiftyOne, to find hard samples in your dataset. In the spirit of making this walkthrough easy to follow, we will use an existing model and dataset. Namely, ResNet50 to find hard samples in the CIFAR-10 dataset test split.
It will walk you through how to:
Load your image dataset into FiftyOne
Add logits from a pretrained network to your dataset
Use FiftyOne to calculate the hardness of every sample
Explore your dataset and find the hardest and easiest samples
This walkthrough will be using PyTorch and FiftyOne as well as a model from PyTorch_CIFAR10 on GitHub. The install instructions for PyTorch and FiftyOne are simple:
pip install torch torchvisionpip install fiftyone
For this example, we will be using the test split of the image classification dataset, CIFAR-10. This dataset contains 10,000 test images labeled across 10 different classes. This is one of the dozens of datasets in the FiftyOne Dataset Zoo, so we can easily load it up.
We can use the FiftyOne App to take a look at this dataset.
Note: You can also load your own dataset into FiftyOne. It supports labels for many computer vision tasks including classification, detection, segmentation, keypoints, and more. For example, if your dataset contains images stored in per-class directories, you can use the following code to load it.
In order to calculate hardness on images in FiftyOne, you first need to use a model to compute logits for those images. You can use any model you want, but ideally, it would be one trained similar data and on the same task you will be using these new images for.
In this example, we will be using code from the PyTorch CIFAR-10 repository, namely the pretrained ResNet50 classifier.
# Download the softwaregit clone --depth 1 --branch v2.1 https://github.com/huyvnphan/PyTorch_CIFAR10.git# Download the pretrained model (90MB)eta gdrive download --public \ 1dGfpeFK_QG0kV-U6QDHMX2EOGXPqaNzu \ PyTorch_CIFAR10/cifar10_models/state_dicts/resnet50.pt
You can easily add a classification field with logits to your samples in a FiftyOne dataset.
The FiftyOne Brain contains various useful methods that can provide insights into your data. At the moment, you can compute the uniqueness of your data, the hardest samples, as well as annotation mistakes. These are all different ways to generate scalar metrics on your dataset that will let you better understand the quality of existing data as well as select help high-quality new samples of data.
Once you have loaded your dataset and added logits to your samples, you calculate hardness in one line of code. The hardness algorithm is closed-source, but the basic idea is to leverage the relative uncertainty of the model’s predictions to assign a scalar hardness value to each sample.
You can visualize your dataset and explore the samples with the highest and lowest hardness scores with the FiftyOne App.
While this example is using small images from CIFAR-10, FiftyOne also works with high-resolution images and videos.
We can write some queries to dig a bit deeper into these hardness calculations and how they relate to other aspects of the data. For example, we can see the distribution of hardness on correct and incorrect predictions of the model separately.
As you might expect, the figure above shows that the distribution of hardness for correct predictions skews towards lower hardness values while incorrect predictions are spread more evenly at high hardness values. This indicates that samples that the model predicts incorrectly tend to be harder samples. Thus, adding harder samples to the training set should improve model performance.
We can also see how the hardness of samples is distributed across different classes.
Average classwise hardnesscat: 0.703082dog: 0.628436airplane: 0.591202bird: 0.588827frog: 0.577954truck: 0.573330horse: 0.564832deer: 0.561707automobile: 0.554695ship: 0.553041
It seems that cat and dog tend to be the hardest classes so it would be worthwhile adding more examples of these before other classes.
We can see that there is an anti-correlation between the average hardness of the samples in a class and the accuracy of the model on that class.
Let's take a look at the incorrectly predicted samples of the hardest class, “cat”.
Now let’s take a look at the correctly predicted images of cats with the lowest hardness.
Comparing the hardest incorrectly predicted cat images with the easiest correctly predicted cat images, we can see that the model has a much easier time classifying images of cats faces looking directly at the camera. The images of cats that the model struggles the most with are ones of cats in poor lighting, complex backgrounds, and poses where they are not sitting and facing the camera. Now we have an idea of the types of cat images to look for to add to this dataset.
This example was done on a previously annotated set of data in order to show how hardness relates to other aspects of a dataset. In a real-world application, you would now apply this method to new unlabeled data.
Once you’ve identified the hardest samples you have available, it’s time to update your dataset. You can select the X samples with the highest hardness value to send off to get annotated and added to your train or test set. Alternatively, you could select samples proportionally to the per-class hardness calculated above.
Retraining your model on this new data should now allow it to perform better on harder edge cases (I’m working on a follow-up blog post to show this). Additionally, adding these samples to your test set will let you be more confident in the ability of your model to perform well on new unseen data if it performs well on your test set. | [
{
"code": null,
"e": 456,
"s": 171,
"text": "Say you have a repository of data with millions of unlabeled images in it. You managed to label a subset of data and trained an image classification model on it, but it’s not performing as well as you hope. How do you decide which new samples to annotate and add to your training set?"
},
{
"code": null,
"e": 677,
"s": 456,
"text": "You could just randomly select new samples to annotate, but there is a better way. Hard sample mining is a tried and true method to distill a large amount of raw unlabeled data into smaller high quality labeled datasets."
},
{
"code": null,
"e": 788,
"s": 677,
"text": "A hard sample is one where your machine learning (ML) model finds it difficult to correctly predict the label."
},
{
"code": null,
"e": 1205,
"s": 788,
"text": "In an image classification dataset, a hard sample could be anything from a cat that looks like a dog to a blurry resolution image. If you expect your model to perform well on these hard samples, then you may need to “mine” more examples of these hard samples to add to your training dataset. Exposing your model to more hard samples during training will allow it to perform better on those types of samples later on."
},
{
"code": null,
"e": 1627,
"s": 1205,
"text": "Hard samples are useful for more than just training data, they are also necessary to include in your test set. If your test data is composed primarily of easy samples, then your performance will soon reach an upper bound causing progress to stagnate. Adding hard samples to a test set will give you a better idea of how models perform in harder edge cases and can provide more insight into which models are more reliable."
},
{
"code": null,
"e": 1682,
"s": 1627,
"text": "Follow along in your browser with this Colab notebook!"
},
{
"code": null,
"e": 2004,
"s": 1682,
"text": "This post will walk you through how to use the new open-source ML tool that I have been working on, FiftyOne, to find hard samples in your dataset. In the spirit of making this walkthrough easy to follow, we will use an existing model and dataset. Namely, ResNet50 to find hard samples in the CIFAR-10 dataset test split."
},
{
"code": null,
"e": 2037,
"s": 2004,
"text": "It will walk you through how to:"
},
{
"code": null,
"e": 2075,
"s": 2037,
"text": "Load your image dataset into FiftyOne"
},
{
"code": null,
"e": 2128,
"s": 2075,
"text": "Add logits from a pretrained network to your dataset"
},
{
"code": null,
"e": 2183,
"s": 2128,
"text": "Use FiftyOne to calculate the hardness of every sample"
},
{
"code": null,
"e": 2245,
"s": 2183,
"text": "Explore your dataset and find the hardest and easiest samples"
},
{
"code": null,
"e": 2410,
"s": 2245,
"text": "This walkthrough will be using PyTorch and FiftyOne as well as a model from PyTorch_CIFAR10 on GitHub. The install instructions for PyTorch and FiftyOne are simple:"
},
{
"code": null,
"e": 2460,
"s": 2410,
"text": "pip install torch torchvisionpip install fiftyone"
},
{
"code": null,
"e": 2731,
"s": 2460,
"text": "For this example, we will be using the test split of the image classification dataset, CIFAR-10. This dataset contains 10,000 test images labeled across 10 different classes. This is one of the dozens of datasets in the FiftyOne Dataset Zoo, so we can easily load it up."
},
{
"code": null,
"e": 2791,
"s": 2731,
"text": "We can use the FiftyOne App to take a look at this dataset."
},
{
"code": null,
"e": 3090,
"s": 2791,
"text": "Note: You can also load your own dataset into FiftyOne. It supports labels for many computer vision tasks including classification, detection, segmentation, keypoints, and more. For example, if your dataset contains images stored in per-class directories, you can use the following code to load it."
},
{
"code": null,
"e": 3353,
"s": 3090,
"text": "In order to calculate hardness on images in FiftyOne, you first need to use a model to compute logits for those images. You can use any model you want, but ideally, it would be one trained similar data and on the same task you will be using these new images for."
},
{
"code": null,
"e": 3473,
"s": 3353,
"text": "In this example, we will be using code from the PyTorch CIFAR-10 repository, namely the pretrained ResNet50 classifier."
},
{
"code": null,
"e": 3744,
"s": 3473,
"text": "# Download the softwaregit clone --depth 1 --branch v2.1 https://github.com/huyvnphan/PyTorch_CIFAR10.git# Download the pretrained model (90MB)eta gdrive download --public \\ 1dGfpeFK_QG0kV-U6QDHMX2EOGXPqaNzu \\ PyTorch_CIFAR10/cifar10_models/state_dicts/resnet50.pt"
},
{
"code": null,
"e": 3837,
"s": 3744,
"text": "You can easily add a classification field with logits to your samples in a FiftyOne dataset."
},
{
"code": null,
"e": 4237,
"s": 3837,
"text": "The FiftyOne Brain contains various useful methods that can provide insights into your data. At the moment, you can compute the uniqueness of your data, the hardest samples, as well as annotation mistakes. These are all different ways to generate scalar metrics on your dataset that will let you better understand the quality of existing data as well as select help high-quality new samples of data."
},
{
"code": null,
"e": 4526,
"s": 4237,
"text": "Once you have loaded your dataset and added logits to your samples, you calculate hardness in one line of code. The hardness algorithm is closed-source, but the basic idea is to leverage the relative uncertainty of the model’s predictions to assign a scalar hardness value to each sample."
},
{
"code": null,
"e": 4648,
"s": 4526,
"text": "You can visualize your dataset and explore the samples with the highest and lowest hardness scores with the FiftyOne App."
},
{
"code": null,
"e": 4764,
"s": 4648,
"text": "While this example is using small images from CIFAR-10, FiftyOne also works with high-resolution images and videos."
},
{
"code": null,
"e": 5008,
"s": 4764,
"text": "We can write some queries to dig a bit deeper into these hardness calculations and how they relate to other aspects of the data. For example, we can see the distribution of hardness on correct and incorrect predictions of the model separately."
},
{
"code": null,
"e": 5395,
"s": 5008,
"text": "As you might expect, the figure above shows that the distribution of hardness for correct predictions skews towards lower hardness values while incorrect predictions are spread more evenly at high hardness values. This indicates that samples that the model predicts incorrectly tend to be harder samples. Thus, adding harder samples to the training set should improve model performance."
},
{
"code": null,
"e": 5480,
"s": 5395,
"text": "We can also see how the hardness of samples is distributed across different classes."
},
{
"code": null,
"e": 5657,
"s": 5480,
"text": "Average classwise hardnesscat: 0.703082dog: 0.628436airplane: 0.591202bird: 0.588827frog: 0.577954truck: 0.573330horse: 0.564832deer: 0.561707automobile: 0.554695ship: 0.553041"
},
{
"code": null,
"e": 5792,
"s": 5657,
"text": "It seems that cat and dog tend to be the hardest classes so it would be worthwhile adding more examples of these before other classes."
},
{
"code": null,
"e": 5937,
"s": 5792,
"text": "We can see that there is an anti-correlation between the average hardness of the samples in a class and the accuracy of the model on that class."
},
{
"code": null,
"e": 6021,
"s": 5937,
"text": "Let's take a look at the incorrectly predicted samples of the hardest class, “cat”."
},
{
"code": null,
"e": 6111,
"s": 6021,
"text": "Now let’s take a look at the correctly predicted images of cats with the lowest hardness."
},
{
"code": null,
"e": 6586,
"s": 6111,
"text": "Comparing the hardest incorrectly predicted cat images with the easiest correctly predicted cat images, we can see that the model has a much easier time classifying images of cats faces looking directly at the camera. The images of cats that the model struggles the most with are ones of cats in poor lighting, complex backgrounds, and poses where they are not sitting and facing the camera. Now we have an idea of the types of cat images to look for to add to this dataset."
},
{
"code": null,
"e": 6799,
"s": 6586,
"text": "This example was done on a previously annotated set of data in order to show how hardness relates to other aspects of a dataset. In a real-world application, you would now apply this method to new unlabeled data."
},
{
"code": null,
"e": 7122,
"s": 6799,
"text": "Once you’ve identified the hardest samples you have available, it’s time to update your dataset. You can select the X samples with the highest hardness value to send off to get annotated and added to your train or test set. Alternatively, you could select samples proportionally to the per-class hardness calculated above."
}
] |
Bayesian AB Testing — Part I — Conversions | by Kaushik Sureshkumar | Towards Data Science | In a previous blog post, I discussed the advantages of using Bayesian AB testing methods rather than frequentist ones. In this series of blog posts, I will be taking a deeper dive into the calculations involved and how to implement them in real world scenarios. The structure of the series will be as follows:
Modelling and analysis of conversion based test metrics (rate metrics)Modelling and analysis of revenue based test metricsCalculating test durationChoosing an appropriate priorRunning tests with multiple variants
Modelling and analysis of conversion based test metrics (rate metrics)
Modelling and analysis of revenue based test metrics
Calculating test duration
Choosing an appropriate prior
Running tests with multiple variants
So without further ado, let’s jump into how to model, use and analyse conversion based test metrics in bayesian product experiments.
Following on from the example used in the previous post, let’s assume we’ve recently changed the messaging on an upsell screen and want to AB test it before releasing to our wider user base. We hypothesise that the changes we’ve made will result in a significantly better conversion rate.
Similar to frequentist methods, we can model each conversion on the upsell screen, X, as Bernoulli random variable with conversion probability λ:
While under the frequentist methodology we’d assume that λ is a constant, under the bayesian methodology we model it as a random variable with its own probability distribution. Our first step is to choose an appropriate approximation for this distribution using past data. We call this our prior distribution of λ.
We then set our loss threshold, which is the largest expected loss we’re willing to accept if we were to make a mistake. As with any statistical modelling, bayesian experimentation methods are built on approximations of real world data. As such, there is always a chance that we draw the wrong conclusions from the test. This loss threshold allows us to say that even if we did draw the wrong conclusions, we can be confident that the conversion rate wouldn’t drop more than an amount we’re comfortable with.
Finally, we draw samples in the form of a randomised experiment and use these to update the distribution, and thus our beliefs, about λ under the control and treatment versions of the upsell screen. We can use these posterior distributions to calculate the probability that treatment is better than control and expected loss of wrongly choosing treatment.
So our first step is to choose a prior distribution of λ. To do this we can look at the data we’ve recently (last few weeks) gathered about this conversion. I’ve generated a sample prior data set which we can use for this exercise.
import pandas as pdprior_data = pd.read_csv('prior_data.csv') print(prior_data.head())print(prior_data.shape)
Since this data set is artificially generated, it’s already in the ideal format for this exercise. In the real world, it’s likely that we’d need to perform some ETL operations in order to get the data in this format. However this is outside the scope of this post.
We see that we have a sample size of 5268 users, and for each user we can see whether they converted on this screen or not. We can go ahead and work out the prior conversion rate.
conversion_rate = prior_data['converted'].sum()/prior_data.shape[0]print(f'Prior Conversion Rate is {round(conversion_rate, 3)}')
We see that our prior data gives us a conversion rate of ~30%. We now use this to choose a prior distribution for λ. Choosing a prior is an important aspect of bayesian experimentation methods, and deserves a post on its own. I will be diving into it in more depth in part 4 of this series. However, for the purposes of this post, I will be using a rough method of choosing a prior.
We’re going to use the beta distribution to model our conversion rate since it’s a flexible distribution over [0,1] and is also a good conjugate prior. It will make our calculations easier when we work out posteriors with experiment data.
When choosing a prior distribution for our conversion, it’s best practice to choose a weaker prior than the prior data suggests. Once again I will explore this in more depth in part 4 of this series, but essentially, choosing too strong a prior could result in our posterior distributions being wrong and could therefore lead to wrong calculations and conclusions.
With that in mind, let’s look at potential priors of varying strength.
import numpy as npfrom scipy.stats import betaimport matplotlib.pyplot as pltfig, ax = plt.subplots(1, 1)x = np.linspace(0,1,1000)beta_weak = beta(round(conversion_rate, 1)*10 + 1, 10 + 1 - round(conversion_rate, 1)*10)beta_mid = beta(round(conversion_rate, 1)*50 + 1, 50 + 1 - round(conversion_rate, 1)*50)beta_strong = beta(round(conversion_rate, 2)*100 + 1, 100 + 1 - round(conversion_rate, 2)*100)ax.plot(x, beta_weak.pdf(x), label=f'weak Beta({int(round(conversion_rate, 1)*10) + 1}, {10 + 1 - int(round(conversion_rate, 1)*10)})')ax.plot(x, beta_mid.pdf(x), label=f'mid Beta({int(round(conversion_rate, 1)*50) + 1}, {50 + 1 - int(round(conversion_rate, 1)*50)})')ax.plot(x, beta_strong.pdf(x), label=f'strong Beta({int(round(conversion_rate, 2)*100) + 1}, {100 + 1 - int(round(conversion_rate, 2)*100)})')ax.set_xlabel('Conversion Probability')ax.set_ylabel('Density')ax.set_title('Choice of Priors')ax.legend()
Here we can see three prior distributions which have a mean conversion rate of ~30%, similar to our prior data, and are all much weaker than the true distribution of the prior data.
Let’s choose a prior that is in between the weakest and mid priors in the diagram Beta(7,15)
where B(a,b) is the beta function defined as
and has the property
prior_alpha = round(conversion_rate, 1)*20 + 1prior_beta = 20 + 1 - round(conversion_rate, 1)*20prior = beta(prior_alpha, prior_beta)fig, ax = plt.subplots(1, 1)x = np.linspace(0,1,1000)ax.plot(x, prior.pdf(x), label=f'prior Beta({int(round(conversion_rate, 1)*20) + 1}, {20 + 1 - int(round(conversion_rate, 1)*20)})')ax.set_xlabel('Conversion Probability')ax.set_ylabel('Density')ax.set_title('Chosen Prior')ax.legend()
Now that we’ve chosen our prior, we need to choose our ε which is the highest expected loss we’re willing to accept in the case where we mistakenly choose the wrong variant. Let us assume that this is an important conversion for us so we want to be pretty conservative with this ε. We aren’t willing to accept a relative expected loss of more than 0.5%. So we set ε=0.005∗0.3=0.0015.
We have a prior and a threshold for our expected loss, so we can start running our experiment and gathering data from it.
Let’s assume that we’ve left our experiment running for a couple of weeks and want to check whether we can draw any conclusions from it. In order to do this we need to use our experiment data to calculate our posterior distributions, which we can then use to calculate the probability of each variant being better, and also the expected loss of wrongly choosing each variant.
For the purposes of this exercise, I’ve generated a sample experiment data set. Let’s start off by exploring it and aggregating it to find out the conversion rates of each variant.
experiment_data = pd.read_csv('experiment_data.csv')print(experiment_data.head())print(experiment_data.shape)
We see that the data set is similar to the prior data set with an extra column for specifying which the group the user was allocated to and therefore which variant they saw. Once again it’s worth noting that since this data set is artificially generated, it’s already in the ideal format for this exercise without the need for additional ETL operations.
We can now go ahead and aggregate the data.
results = experiment_data.groupby('group').agg({'userId': pd.Series.nunique, 'converted': sum})results.rename({'userId': 'sampleSize'}, axis=1, inplace=True)results['conversionRate'] = results['converted']/results['sampleSize']print(results)
We can tell by inspection that treatment had a better conversion rate, but we need to perform further calculations in order to update our beliefs about the respective conversion probabilities λ_c and λ_t of the control and treatment variants.
With our experiment data, we can now calculate our posterior distributions under each variant. But before we do let’s explore the maths behind how this is possible from just the information that we have. We’re going to use a theorem[1] that states the following:
Suppose we have the prior
Suppose a variant was displayed to n visitors and c converted, then the posterior distribution of the variant is given by
Let’s go ahead and prove this. By bayes theorem we have the following
Since we modelled each conversion as a Bernoulli RV with probability λ, given λ we can model the result of showing a variant to n visitors as a Binomial RV. So we have
And thus, using the definition of our prior
Let’s now just consider the coefficients
Using the definition of the beta function we can say
Substituting (3) and (4) back into (2)
Substituting (5) back into (1)
Since f(λ;a+c,b+n−c) is a distribution over [0,1] the denominator is 1 and we have the result we were after.
Now that we’ve sufficiently convinced ourselves of the maths, we can calculate our posterior distributions.
control = beta(prior_alpha + results.loc['control', 'converted'], prior_beta + results.loc['control', 'sampleSize'] - results.loc['control', 'converted'])treatment = beta(prior_alpha + results.loc['treatment', 'converted'], prior_beta + results.loc['treatment', 'sampleSize'] - results.loc['treatment', 'converted'])fig, ax = plt.subplots()x = np.linspace(0.26,0.42,1000)ax.plot(x, control.pdf(x), label='control')ax.plot(x, treatment.pdf(x), label='treatment')ax.set_xlabel('Conversion Probability')ax.set_ylabel('Density')ax.set_title('Experiment Posteriors')ax.legend()
Now that we’ve got our posterior distributions, we can go ahead and calculate the joint posterior. Since randomised experiments are built on the idea of random assignment of a user to a variant, we can assume that these two distributions are independent. Note that this isn’t always the case. For example, there might be some cases where network effects might be in play and we’d need to take that into consideration. This assumption is also dependent on the procedure of random assignment working properly.
Let us assume that our method of random assignment has worked properly and that there are no network effects. Under this assumption we can say the following:
Let’s use this to calculate our joint posterior distribution.
import seaborn as snsjoint_dist_for_plot = []for i in np.linspace(0.26,0.42,161): for j in np.linspace(0.26,0.42,161): joint_dist_for_plot.append([i, j, control.pdf(i)*treatment.pdf(j)])joint_dist_for_plot = pd.DataFrame(joint_dist_for_plot)joint_dist_for_plot.rename({0: 'control_cr', 1: 'treatment_cr', 2: 'joint_density'}, axis=1, inplace=True)tick_locations = range(0, 160, 10)tick_labels = [round(0.26 + i*0.01, 2) for i in range(16)]heatmap_df = pd.pivot_table(joint_dist_for_plot, values='joint_density', index='treatment_cr', columns='control_cr')ax = sns.heatmap(heatmap_df)ax.set_xticks(tick_locations)ax.set_xticklabels(tick_labels)ax.set_yticks(tick_locations)ax.set_yticklabels(tick_labels)ax.invert_yaxis()
The blue line in this graph is the line that represents λ_c=λ_t. Since the joint posterior is above this line, we can use this as a visual indication that the treatment is in fact better. If the joint posterior was below the line then we could be pretty sure that control was better. If any part of the joint posterior was on the line then there would be more uncertainty on which variant was better.
In order to quantify this, we need to calculate p(λ_t≥λ_c) and E[L](t), the expected loss of wrongly choosing treatment.
import decimaldecimal.getcontext().prec = 4control_simulation = np.random.beta(prior_alpha + results.loc['control', 'converted'], prior_beta + results.loc['control', 'sampleSize'] - results.loc['control', 'converted'], size=10000)treatment_simulation = np.random.beta(prior_alpha + results.loc['treatment', 'converted'], prior_beta + results.loc['treatment', 'sampleSize'] - results.loc['treatment', 'converted'], size=10000)treatment_won = [i <= j for i,j in zip(control_simulation, treatment_simulation)]chance_of_beating_control = np.mean(treatment_won)print(f'Chance of treatment beating control is {decimal.getcontext().create_decimal(chance_of_beating_control)}')
From the simulations we see that p(λ_t≥λ_c)=0.9718 so treatment has a 97% chance of being better than control.
Now that we’ve calculated the probability of treatment being better, we need to calculate E[L](t). The loss function of each variant is given by
So the expected loss of each variant is given by
We use this to calculate the expected loss[2]
decimal.getcontext().prec = 4loss_control = [max(j - i, 0) for i,j in zip(control_simulation, treatment_simulation)]loss_treatment = [max(i - j, 0) for i,j in zip(control_simulation, treatment_simulation)]all_loss_control = [int(i)*j for i,j in zip(treatment_won, loss_control)]all_loss_treatment = [(1 - int(i))*j for i,j in zip(treatment_won, loss_treatment)]expected_loss_control = np.mean(all_loss_control)expected_loss_treatment = np.mean(all_loss_treatment)print(f'Expected loss of choosing control: {decimal.getcontext().create_decimal(expected_loss_control)}. Expected loss of choosing treatment: {decimal.getcontext().create_decimal(expected_loss_treatment)}')
From running simulations we see that:
E[L](t) = 0.0001369 < 0.0015 = ε
Since the expected loss of one of the variants is below the threshold that we set at the start of the test, the test has reached significance. We can conclude with high confidence that the treatment is better, and that the expected cost of mistakenly choosing treatment would not be greater than what we’re comfortable with. So we can strongly recommend that the treatment variant of the upsell screen should be rolled out to the rest of our user base.
I hope this case study was useful in helping you understand the calculations required to implement bayesian AB testing methods. Watch this space for the next parts of the series!
[1] VWO Whitepaper by C. Stucchio
[2] Bayesian A/B testing — a practical exploration with simulations by Blake Arnold — I’ve used the logic from Blake’s code for calculating expected loss
Also found The Power of Bayesian A/B Testing by Michael Frasco very helpful in understanding the technical aspects of bayesian AB testing methods
My code from this post can be found here | [
{
"code": null,
"e": 481,
"s": 171,
"text": "In a previous blog post, I discussed the advantages of using Bayesian AB testing methods rather than frequentist ones. In this series of blog posts, I will be taking a deeper dive into the calculations involved and how to implement them in real world scenarios. The structure of the series will be as follows:"
},
{
"code": null,
"e": 694,
"s": 481,
"text": "Modelling and analysis of conversion based test metrics (rate metrics)Modelling and analysis of revenue based test metricsCalculating test durationChoosing an appropriate priorRunning tests with multiple variants"
},
{
"code": null,
"e": 765,
"s": 694,
"text": "Modelling and analysis of conversion based test metrics (rate metrics)"
},
{
"code": null,
"e": 818,
"s": 765,
"text": "Modelling and analysis of revenue based test metrics"
},
{
"code": null,
"e": 844,
"s": 818,
"text": "Calculating test duration"
},
{
"code": null,
"e": 874,
"s": 844,
"text": "Choosing an appropriate prior"
},
{
"code": null,
"e": 911,
"s": 874,
"text": "Running tests with multiple variants"
},
{
"code": null,
"e": 1044,
"s": 911,
"text": "So without further ado, let’s jump into how to model, use and analyse conversion based test metrics in bayesian product experiments."
},
{
"code": null,
"e": 1333,
"s": 1044,
"text": "Following on from the example used in the previous post, let’s assume we’ve recently changed the messaging on an upsell screen and want to AB test it before releasing to our wider user base. We hypothesise that the changes we’ve made will result in a significantly better conversion rate."
},
{
"code": null,
"e": 1479,
"s": 1333,
"text": "Similar to frequentist methods, we can model each conversion on the upsell screen, X, as Bernoulli random variable with conversion probability λ:"
},
{
"code": null,
"e": 1794,
"s": 1479,
"text": "While under the frequentist methodology we’d assume that λ is a constant, under the bayesian methodology we model it as a random variable with its own probability distribution. Our first step is to choose an appropriate approximation for this distribution using past data. We call this our prior distribution of λ."
},
{
"code": null,
"e": 2303,
"s": 1794,
"text": "We then set our loss threshold, which is the largest expected loss we’re willing to accept if we were to make a mistake. As with any statistical modelling, bayesian experimentation methods are built on approximations of real world data. As such, there is always a chance that we draw the wrong conclusions from the test. This loss threshold allows us to say that even if we did draw the wrong conclusions, we can be confident that the conversion rate wouldn’t drop more than an amount we’re comfortable with."
},
{
"code": null,
"e": 2659,
"s": 2303,
"text": "Finally, we draw samples in the form of a randomised experiment and use these to update the distribution, and thus our beliefs, about λ under the control and treatment versions of the upsell screen. We can use these posterior distributions to calculate the probability that treatment is better than control and expected loss of wrongly choosing treatment."
},
{
"code": null,
"e": 2891,
"s": 2659,
"text": "So our first step is to choose a prior distribution of λ. To do this we can look at the data we’ve recently (last few weeks) gathered about this conversion. I’ve generated a sample prior data set which we can use for this exercise."
},
{
"code": null,
"e": 3004,
"s": 2891,
"text": "import pandas as pdprior_data = pd.read_csv('prior_data.csv') print(prior_data.head())print(prior_data.shape)"
},
{
"code": null,
"e": 3269,
"s": 3004,
"text": "Since this data set is artificially generated, it’s already in the ideal format for this exercise. In the real world, it’s likely that we’d need to perform some ETL operations in order to get the data in this format. However this is outside the scope of this post."
},
{
"code": null,
"e": 3449,
"s": 3269,
"text": "We see that we have a sample size of 5268 users, and for each user we can see whether they converted on this screen or not. We can go ahead and work out the prior conversion rate."
},
{
"code": null,
"e": 3579,
"s": 3449,
"text": "conversion_rate = prior_data['converted'].sum()/prior_data.shape[0]print(f'Prior Conversion Rate is {round(conversion_rate, 3)}')"
},
{
"code": null,
"e": 3962,
"s": 3579,
"text": "We see that our prior data gives us a conversion rate of ~30%. We now use this to choose a prior distribution for λ. Choosing a prior is an important aspect of bayesian experimentation methods, and deserves a post on its own. I will be diving into it in more depth in part 4 of this series. However, for the purposes of this post, I will be using a rough method of choosing a prior."
},
{
"code": null,
"e": 4201,
"s": 3962,
"text": "We’re going to use the beta distribution to model our conversion rate since it’s a flexible distribution over [0,1] and is also a good conjugate prior. It will make our calculations easier when we work out posteriors with experiment data."
},
{
"code": null,
"e": 4566,
"s": 4201,
"text": "When choosing a prior distribution for our conversion, it’s best practice to choose a weaker prior than the prior data suggests. Once again I will explore this in more depth in part 4 of this series, but essentially, choosing too strong a prior could result in our posterior distributions being wrong and could therefore lead to wrong calculations and conclusions."
},
{
"code": null,
"e": 4637,
"s": 4566,
"text": "With that in mind, let’s look at potential priors of varying strength."
},
{
"code": null,
"e": 5555,
"s": 4637,
"text": "import numpy as npfrom scipy.stats import betaimport matplotlib.pyplot as pltfig, ax = plt.subplots(1, 1)x = np.linspace(0,1,1000)beta_weak = beta(round(conversion_rate, 1)*10 + 1, 10 + 1 - round(conversion_rate, 1)*10)beta_mid = beta(round(conversion_rate, 1)*50 + 1, 50 + 1 - round(conversion_rate, 1)*50)beta_strong = beta(round(conversion_rate, 2)*100 + 1, 100 + 1 - round(conversion_rate, 2)*100)ax.plot(x, beta_weak.pdf(x), label=f'weak Beta({int(round(conversion_rate, 1)*10) + 1}, {10 + 1 - int(round(conversion_rate, 1)*10)})')ax.plot(x, beta_mid.pdf(x), label=f'mid Beta({int(round(conversion_rate, 1)*50) + 1}, {50 + 1 - int(round(conversion_rate, 1)*50)})')ax.plot(x, beta_strong.pdf(x), label=f'strong Beta({int(round(conversion_rate, 2)*100) + 1}, {100 + 1 - int(round(conversion_rate, 2)*100)})')ax.set_xlabel('Conversion Probability')ax.set_ylabel('Density')ax.set_title('Choice of Priors')ax.legend()"
},
{
"code": null,
"e": 5737,
"s": 5555,
"text": "Here we can see three prior distributions which have a mean conversion rate of ~30%, similar to our prior data, and are all much weaker than the true distribution of the prior data."
},
{
"code": null,
"e": 5830,
"s": 5737,
"text": "Let’s choose a prior that is in between the weakest and mid priors in the diagram Beta(7,15)"
},
{
"code": null,
"e": 5875,
"s": 5830,
"text": "where B(a,b) is the beta function defined as"
},
{
"code": null,
"e": 5896,
"s": 5875,
"text": "and has the property"
},
{
"code": null,
"e": 6317,
"s": 5896,
"text": "prior_alpha = round(conversion_rate, 1)*20 + 1prior_beta = 20 + 1 - round(conversion_rate, 1)*20prior = beta(prior_alpha, prior_beta)fig, ax = plt.subplots(1, 1)x = np.linspace(0,1,1000)ax.plot(x, prior.pdf(x), label=f'prior Beta({int(round(conversion_rate, 1)*20) + 1}, {20 + 1 - int(round(conversion_rate, 1)*20)})')ax.set_xlabel('Conversion Probability')ax.set_ylabel('Density')ax.set_title('Chosen Prior')ax.legend()"
},
{
"code": null,
"e": 6701,
"s": 6317,
"text": "Now that we’ve chosen our prior, we need to choose our ε which is the highest expected loss we’re willing to accept in the case where we mistakenly choose the wrong variant. Let us assume that this is an important conversion for us so we want to be pretty conservative with this ε. We aren’t willing to accept a relative expected loss of more than 0.5%. So we set ε=0.005∗0.3=0.0015."
},
{
"code": null,
"e": 6823,
"s": 6701,
"text": "We have a prior and a threshold for our expected loss, so we can start running our experiment and gathering data from it."
},
{
"code": null,
"e": 7199,
"s": 6823,
"text": "Let’s assume that we’ve left our experiment running for a couple of weeks and want to check whether we can draw any conclusions from it. In order to do this we need to use our experiment data to calculate our posterior distributions, which we can then use to calculate the probability of each variant being better, and also the expected loss of wrongly choosing each variant."
},
{
"code": null,
"e": 7380,
"s": 7199,
"text": "For the purposes of this exercise, I’ve generated a sample experiment data set. Let’s start off by exploring it and aggregating it to find out the conversion rates of each variant."
},
{
"code": null,
"e": 7490,
"s": 7380,
"text": "experiment_data = pd.read_csv('experiment_data.csv')print(experiment_data.head())print(experiment_data.shape)"
},
{
"code": null,
"e": 7844,
"s": 7490,
"text": "We see that the data set is similar to the prior data set with an extra column for specifying which the group the user was allocated to and therefore which variant they saw. Once again it’s worth noting that since this data set is artificially generated, it’s already in the ideal format for this exercise without the need for additional ETL operations."
},
{
"code": null,
"e": 7888,
"s": 7844,
"text": "We can now go ahead and aggregate the data."
},
{
"code": null,
"e": 8130,
"s": 7888,
"text": "results = experiment_data.groupby('group').agg({'userId': pd.Series.nunique, 'converted': sum})results.rename({'userId': 'sampleSize'}, axis=1, inplace=True)results['conversionRate'] = results['converted']/results['sampleSize']print(results)"
},
{
"code": null,
"e": 8373,
"s": 8130,
"text": "We can tell by inspection that treatment had a better conversion rate, but we need to perform further calculations in order to update our beliefs about the respective conversion probabilities λ_c and λ_t of the control and treatment variants."
},
{
"code": null,
"e": 8636,
"s": 8373,
"text": "With our experiment data, we can now calculate our posterior distributions under each variant. But before we do let’s explore the maths behind how this is possible from just the information that we have. We’re going to use a theorem[1] that states the following:"
},
{
"code": null,
"e": 8662,
"s": 8636,
"text": "Suppose we have the prior"
},
{
"code": null,
"e": 8784,
"s": 8662,
"text": "Suppose a variant was displayed to n visitors and c converted, then the posterior distribution of the variant is given by"
},
{
"code": null,
"e": 8854,
"s": 8784,
"text": "Let’s go ahead and prove this. By bayes theorem we have the following"
},
{
"code": null,
"e": 9022,
"s": 8854,
"text": "Since we modelled each conversion as a Bernoulli RV with probability λ, given λ we can model the result of showing a variant to n visitors as a Binomial RV. So we have"
},
{
"code": null,
"e": 9066,
"s": 9022,
"text": "And thus, using the definition of our prior"
},
{
"code": null,
"e": 9107,
"s": 9066,
"text": "Let’s now just consider the coefficients"
},
{
"code": null,
"e": 9160,
"s": 9107,
"text": "Using the definition of the beta function we can say"
},
{
"code": null,
"e": 9199,
"s": 9160,
"text": "Substituting (3) and (4) back into (2)"
},
{
"code": null,
"e": 9230,
"s": 9199,
"text": "Substituting (5) back into (1)"
},
{
"code": null,
"e": 9339,
"s": 9230,
"text": "Since f(λ;a+c,b+n−c) is a distribution over [0,1] the denominator is 1 and we have the result we were after."
},
{
"code": null,
"e": 9447,
"s": 9339,
"text": "Now that we’ve sufficiently convinced ourselves of the maths, we can calculate our posterior distributions."
},
{
"code": null,
"e": 10020,
"s": 9447,
"text": "control = beta(prior_alpha + results.loc['control', 'converted'], prior_beta + results.loc['control', 'sampleSize'] - results.loc['control', 'converted'])treatment = beta(prior_alpha + results.loc['treatment', 'converted'], prior_beta + results.loc['treatment', 'sampleSize'] - results.loc['treatment', 'converted'])fig, ax = plt.subplots()x = np.linspace(0.26,0.42,1000)ax.plot(x, control.pdf(x), label='control')ax.plot(x, treatment.pdf(x), label='treatment')ax.set_xlabel('Conversion Probability')ax.set_ylabel('Density')ax.set_title('Experiment Posteriors')ax.legend()"
},
{
"code": null,
"e": 10528,
"s": 10020,
"text": "Now that we’ve got our posterior distributions, we can go ahead and calculate the joint posterior. Since randomised experiments are built on the idea of random assignment of a user to a variant, we can assume that these two distributions are independent. Note that this isn’t always the case. For example, there might be some cases where network effects might be in play and we’d need to take that into consideration. This assumption is also dependent on the procedure of random assignment working properly."
},
{
"code": null,
"e": 10686,
"s": 10528,
"text": "Let us assume that our method of random assignment has worked properly and that there are no network effects. Under this assumption we can say the following:"
},
{
"code": null,
"e": 10748,
"s": 10686,
"text": "Let’s use this to calculate our joint posterior distribution."
},
{
"code": null,
"e": 11479,
"s": 10748,
"text": "import seaborn as snsjoint_dist_for_plot = []for i in np.linspace(0.26,0.42,161): for j in np.linspace(0.26,0.42,161): joint_dist_for_plot.append([i, j, control.pdf(i)*treatment.pdf(j)])joint_dist_for_plot = pd.DataFrame(joint_dist_for_plot)joint_dist_for_plot.rename({0: 'control_cr', 1: 'treatment_cr', 2: 'joint_density'}, axis=1, inplace=True)tick_locations = range(0, 160, 10)tick_labels = [round(0.26 + i*0.01, 2) for i in range(16)]heatmap_df = pd.pivot_table(joint_dist_for_plot, values='joint_density', index='treatment_cr', columns='control_cr')ax = sns.heatmap(heatmap_df)ax.set_xticks(tick_locations)ax.set_xticklabels(tick_labels)ax.set_yticks(tick_locations)ax.set_yticklabels(tick_labels)ax.invert_yaxis()"
},
{
"code": null,
"e": 11880,
"s": 11479,
"text": "The blue line in this graph is the line that represents λ_c=λ_t. Since the joint posterior is above this line, we can use this as a visual indication that the treatment is in fact better. If the joint posterior was below the line then we could be pretty sure that control was better. If any part of the joint posterior was on the line then there would be more uncertainty on which variant was better."
},
{
"code": null,
"e": 12001,
"s": 11880,
"text": "In order to quantify this, we need to calculate p(λ_t≥λ_c) and E[L](t), the expected loss of wrongly choosing treatment."
},
{
"code": null,
"e": 12671,
"s": 12001,
"text": "import decimaldecimal.getcontext().prec = 4control_simulation = np.random.beta(prior_alpha + results.loc['control', 'converted'], prior_beta + results.loc['control', 'sampleSize'] - results.loc['control', 'converted'], size=10000)treatment_simulation = np.random.beta(prior_alpha + results.loc['treatment', 'converted'], prior_beta + results.loc['treatment', 'sampleSize'] - results.loc['treatment', 'converted'], size=10000)treatment_won = [i <= j for i,j in zip(control_simulation, treatment_simulation)]chance_of_beating_control = np.mean(treatment_won)print(f'Chance of treatment beating control is {decimal.getcontext().create_decimal(chance_of_beating_control)}')"
},
{
"code": null,
"e": 12782,
"s": 12671,
"text": "From the simulations we see that p(λ_t≥λ_c)=0.9718 so treatment has a 97% chance of being better than control."
},
{
"code": null,
"e": 12927,
"s": 12782,
"text": "Now that we’ve calculated the probability of treatment being better, we need to calculate E[L](t). The loss function of each variant is given by"
},
{
"code": null,
"e": 12976,
"s": 12927,
"text": "So the expected loss of each variant is given by"
},
{
"code": null,
"e": 13022,
"s": 12976,
"text": "We use this to calculate the expected loss[2]"
},
{
"code": null,
"e": 13692,
"s": 13022,
"text": "decimal.getcontext().prec = 4loss_control = [max(j - i, 0) for i,j in zip(control_simulation, treatment_simulation)]loss_treatment = [max(i - j, 0) for i,j in zip(control_simulation, treatment_simulation)]all_loss_control = [int(i)*j for i,j in zip(treatment_won, loss_control)]all_loss_treatment = [(1 - int(i))*j for i,j in zip(treatment_won, loss_treatment)]expected_loss_control = np.mean(all_loss_control)expected_loss_treatment = np.mean(all_loss_treatment)print(f'Expected loss of choosing control: {decimal.getcontext().create_decimal(expected_loss_control)}. Expected loss of choosing treatment: {decimal.getcontext().create_decimal(expected_loss_treatment)}')"
},
{
"code": null,
"e": 13730,
"s": 13692,
"text": "From running simulations we see that:"
},
{
"code": null,
"e": 13763,
"s": 13730,
"text": "E[L](t) = 0.0001369 < 0.0015 = ε"
},
{
"code": null,
"e": 14216,
"s": 13763,
"text": "Since the expected loss of one of the variants is below the threshold that we set at the start of the test, the test has reached significance. We can conclude with high confidence that the treatment is better, and that the expected cost of mistakenly choosing treatment would not be greater than what we’re comfortable with. So we can strongly recommend that the treatment variant of the upsell screen should be rolled out to the rest of our user base."
},
{
"code": null,
"e": 14395,
"s": 14216,
"text": "I hope this case study was useful in helping you understand the calculations required to implement bayesian AB testing methods. Watch this space for the next parts of the series!"
},
{
"code": null,
"e": 14429,
"s": 14395,
"text": "[1] VWO Whitepaper by C. Stucchio"
},
{
"code": null,
"e": 14583,
"s": 14429,
"text": "[2] Bayesian A/B testing — a practical exploration with simulations by Blake Arnold — I’ve used the logic from Blake’s code for calculating expected loss"
},
{
"code": null,
"e": 14729,
"s": 14583,
"text": "Also found The Power of Bayesian A/B Testing by Michael Frasco very helpful in understanding the technical aspects of bayesian AB testing methods"
}
] |
fnmatch - Unix filename pattern matching in Python - GeeksforGeeks | 22 Nov, 2020
This module is used for matching Unix shell-style wildcards. fnmatch() compares a single file name against a pattern and returns TRUE if they match else returns FALSE.The comparison is case-sensitive when the operating system uses a case-sensitive file system.The special characters and their functions used in shell-style wildcards are :
‘*’ – matches everything
‘?’ – matches any single character
‘[seq]’ – matches any character in seq
‘[!seq]’ – matches any character not in seq
The meta-characters should be wrapped in brackets for a literal match. For example, ‘[?]’ matches the character ‘?’.
Functions provided by the fnmatch module
fnmatch.fnmatch(filename, pattern): This function tests whether the given filename string matches the pattern string and returns a boolean value. If the operating system is case-insensitive, then both parameters will be normalized to all lower-case or upper-case before the comparison is performed.Example: Script to search all files starting with ‘fnmatch’ and ending in ‘.py’# Python program to illustrate # fnmatch.fnmatch(filename, pattern) import fnmatch import os pattern = 'fnmatch_*.py'print ('Pattern :', pattern )print() files = os.listdir('.') for name in files: print ('Filename: %-25s %s' % (name, fnmatch.fnmatch(name, pattern))Output :$ python fnmatch_fnmatch.py
Pattern : fnmatch_*.py
Filename: __init__.py False
Filename: fnmatch_filter.py True
Filename: fnmatch_fnmatch.py True
Filename: fnmatch_fnmatchcase.py True
Filename: fnmatch_translate.py True
Filename: index.rst False
fnmatch.fnmatchcase(filename, pattern): This function performs the case sensitive comparison and tests whether the given filename string matches the pattern string and returns a boolean value.Example: Script for a case-sensitive comparison, regardless of the filesystem and operating system settings.# Python program to illustrate # fnmatch.fnmatchcase(filename, pattern) import fnmatch import os pattern = 'FNMATCH_*.PY'print ('Pattern :', pattern) print() files = os.listdir('.') for name in files: (print 'Filename: %-25s %s' % (name, fnmatch.fnmatchcase(name, pattern)))Output :$ python fnmatch_fnmatchcase.py
Pattern : FNMATCH_*.PY
Filename: __init__.py False
Filename: fnmatch_filter.py False
Filename: FNMATCH_FNMATCH.PY True
Filename: fnmatch_fnmatchcase.py False
Filename: fnmatch_translate.py False
Filename: index.rst False
fnmatch.filter(names, pattern): This function returns the subset of the list of names passed in the function that match the given pattern.Example: Filter files by more than one file extension.# Python program to illustrate # fnmatch.filter(names, pattern) import fnmatch import os pattern = 'fnmatch_*.py'print ('Pattern :', pattern ) files = os.listdir('.') print ('Files :', files) print ('Matches :', fnmatch.filter(files, pattern))Output :$ python fnmatch_filter.py
Pattern : fnmatch_*.py
Files : ['__init__.py', 'fnmatch_filter.py', 'fnmatch_fnmatch.py',
'fnmatch_fnmatchcase.py', 'fnmatch_translate.py', 'index.rst']
Matches : ['fnmatch_filter.py', 'fnmatch_fnmatch.py',
'fnmatch_fnmatchcase.py', 'fnmatch_translate.py']
fnmatch.translate(pattern): This function returns the shell-style pattern converted to a regular expression for using with re.match() (re.match() will only match at the beginning of the string and not at the beginning of each line).# Python program to illustrate # fnmatch.translate(pattern) import fnmatch, re regex = fnmatch.translate('*.txt') reobj = re.compile(regex) print(regex) print(reobj.match('foobar.txt')) Output :'(?s:.*\\.txt)\\Z'
_sre.SRE_Match object; span=(0, 10), match='foobar.txt'
fnmatch.fnmatch(filename, pattern): This function tests whether the given filename string matches the pattern string and returns a boolean value. If the operating system is case-insensitive, then both parameters will be normalized to all lower-case or upper-case before the comparison is performed.Example: Script to search all files starting with ‘fnmatch’ and ending in ‘.py’# Python program to illustrate # fnmatch.fnmatch(filename, pattern) import fnmatch import os pattern = 'fnmatch_*.py'print ('Pattern :', pattern )print() files = os.listdir('.') for name in files: print ('Filename: %-25s %s' % (name, fnmatch.fnmatch(name, pattern))Output :$ python fnmatch_fnmatch.py
Pattern : fnmatch_*.py
Filename: __init__.py False
Filename: fnmatch_filter.py True
Filename: fnmatch_fnmatch.py True
Filename: fnmatch_fnmatchcase.py True
Filename: fnmatch_translate.py True
Filename: index.rst False
Example: Script to search all files starting with ‘fnmatch’ and ending in ‘.py’
# Python program to illustrate # fnmatch.fnmatch(filename, pattern) import fnmatch import os pattern = 'fnmatch_*.py'print ('Pattern :', pattern )print() files = os.listdir('.') for name in files: print ('Filename: %-25s %s' % (name, fnmatch.fnmatch(name, pattern))
Output :
$ python fnmatch_fnmatch.py
Pattern : fnmatch_*.py
Filename: __init__.py False
Filename: fnmatch_filter.py True
Filename: fnmatch_fnmatch.py True
Filename: fnmatch_fnmatchcase.py True
Filename: fnmatch_translate.py True
Filename: index.rst False
fnmatch.fnmatchcase(filename, pattern): This function performs the case sensitive comparison and tests whether the given filename string matches the pattern string and returns a boolean value.Example: Script for a case-sensitive comparison, regardless of the filesystem and operating system settings.# Python program to illustrate # fnmatch.fnmatchcase(filename, pattern) import fnmatch import os pattern = 'FNMATCH_*.PY'print ('Pattern :', pattern) print() files = os.listdir('.') for name in files: (print 'Filename: %-25s %s' % (name, fnmatch.fnmatchcase(name, pattern)))Output :$ python fnmatch_fnmatchcase.py
Pattern : FNMATCH_*.PY
Filename: __init__.py False
Filename: fnmatch_filter.py False
Filename: FNMATCH_FNMATCH.PY True
Filename: fnmatch_fnmatchcase.py False
Filename: fnmatch_translate.py False
Filename: index.rst False
Example: Script for a case-sensitive comparison, regardless of the filesystem and operating system settings.
# Python program to illustrate # fnmatch.fnmatchcase(filename, pattern) import fnmatch import os pattern = 'FNMATCH_*.PY'print ('Pattern :', pattern) print() files = os.listdir('.') for name in files: (print 'Filename: %-25s %s' % (name, fnmatch.fnmatchcase(name, pattern)))
Output :
$ python fnmatch_fnmatchcase.py
Pattern : FNMATCH_*.PY
Filename: __init__.py False
Filename: fnmatch_filter.py False
Filename: FNMATCH_FNMATCH.PY True
Filename: fnmatch_fnmatchcase.py False
Filename: fnmatch_translate.py False
Filename: index.rst False
fnmatch.filter(names, pattern): This function returns the subset of the list of names passed in the function that match the given pattern.Example: Filter files by more than one file extension.# Python program to illustrate # fnmatch.filter(names, pattern) import fnmatch import os pattern = 'fnmatch_*.py'print ('Pattern :', pattern ) files = os.listdir('.') print ('Files :', files) print ('Matches :', fnmatch.filter(files, pattern))Output :$ python fnmatch_filter.py
Pattern : fnmatch_*.py
Files : ['__init__.py', 'fnmatch_filter.py', 'fnmatch_fnmatch.py',
'fnmatch_fnmatchcase.py', 'fnmatch_translate.py', 'index.rst']
Matches : ['fnmatch_filter.py', 'fnmatch_fnmatch.py',
'fnmatch_fnmatchcase.py', 'fnmatch_translate.py']
Example: Filter files by more than one file extension.
# Python program to illustrate # fnmatch.filter(names, pattern) import fnmatch import os pattern = 'fnmatch_*.py'print ('Pattern :', pattern ) files = os.listdir('.') print ('Files :', files) print ('Matches :', fnmatch.filter(files, pattern))
Output :
$ python fnmatch_filter.py
Pattern : fnmatch_*.py
Files : ['__init__.py', 'fnmatch_filter.py', 'fnmatch_fnmatch.py',
'fnmatch_fnmatchcase.py', 'fnmatch_translate.py', 'index.rst']
Matches : ['fnmatch_filter.py', 'fnmatch_fnmatch.py',
'fnmatch_fnmatchcase.py', 'fnmatch_translate.py']
fnmatch.translate(pattern): This function returns the shell-style pattern converted to a regular expression for using with re.match() (re.match() will only match at the beginning of the string and not at the beginning of each line).# Python program to illustrate # fnmatch.translate(pattern) import fnmatch, re regex = fnmatch.translate('*.txt') reobj = re.compile(regex) print(regex) print(reobj.match('foobar.txt')) Output :'(?s:.*\\.txt)\\Z'
_sre.SRE_Match object; span=(0, 10), match='foobar.txt'
# Python program to illustrate # fnmatch.translate(pattern) import fnmatch, re regex = fnmatch.translate('*.txt') reobj = re.compile(regex) print(regex) print(reobj.match('foobar.txt'))
Output :
'(?s:.*\\.txt)\\Z'
_sre.SRE_Match object; span=(0, 10), match='foobar.txt'
This article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python-Library
python-regex
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Reading and Writing to text files in Python
sum() function in Python | [
{
"code": null,
"e": 24426,
"s": 24398,
"text": "\n22 Nov, 2020"
},
{
"code": null,
"e": 24765,
"s": 24426,
"text": "This module is used for matching Unix shell-style wildcards. fnmatch() compares a single file name against a pattern and returns TRUE if they match else returns FALSE.The comparison is case-sensitive when the operating system uses a case-sensitive file system.The special characters and their functions used in shell-style wildcards are :"
},
{
"code": null,
"e": 24790,
"s": 24765,
"text": "‘*’ – matches everything"
},
{
"code": null,
"e": 24825,
"s": 24790,
"text": "‘?’ – matches any single character"
},
{
"code": null,
"e": 24864,
"s": 24825,
"text": "‘[seq]’ – matches any character in seq"
},
{
"code": null,
"e": 24908,
"s": 24864,
"text": "‘[!seq]’ – matches any character not in seq"
},
{
"code": null,
"e": 25025,
"s": 24908,
"text": "The meta-characters should be wrapped in brackets for a literal match. For example, ‘[?]’ matches the character ‘?’."
},
{
"code": null,
"e": 25066,
"s": 25025,
"text": "Functions provided by the fnmatch module"
},
{
"code": null,
"e": 28168,
"s": 25066,
"text": "fnmatch.fnmatch(filename, pattern): This function tests whether the given filename string matches the pattern string and returns a boolean value. If the operating system is case-insensitive, then both parameters will be normalized to all lower-case or upper-case before the comparison is performed.Example: Script to search all files starting with ‘fnmatch’ and ending in ‘.py’# Python program to illustrate # fnmatch.fnmatch(filename, pattern) import fnmatch import os pattern = 'fnmatch_*.py'print ('Pattern :', pattern )print() files = os.listdir('.') for name in files: print ('Filename: %-25s %s' % (name, fnmatch.fnmatch(name, pattern))Output :$ python fnmatch_fnmatch.py\n\nPattern : fnmatch_*.py\n\nFilename: __init__.py False\nFilename: fnmatch_filter.py True\nFilename: fnmatch_fnmatch.py True\nFilename: fnmatch_fnmatchcase.py True\nFilename: fnmatch_translate.py True\nFilename: index.rst False\nfnmatch.fnmatchcase(filename, pattern): This function performs the case sensitive comparison and tests whether the given filename string matches the pattern string and returns a boolean value.Example: Script for a case-sensitive comparison, regardless of the filesystem and operating system settings.# Python program to illustrate # fnmatch.fnmatchcase(filename, pattern) import fnmatch import os pattern = 'FNMATCH_*.PY'print ('Pattern :', pattern) print() files = os.listdir('.') for name in files: (print 'Filename: %-25s %s' % (name, fnmatch.fnmatchcase(name, pattern)))Output :$ python fnmatch_fnmatchcase.py\n\nPattern : FNMATCH_*.PY\n\nFilename: __init__.py False\nFilename: fnmatch_filter.py False\nFilename: FNMATCH_FNMATCH.PY True\nFilename: fnmatch_fnmatchcase.py False\nFilename: fnmatch_translate.py False\nFilename: index.rst False\nfnmatch.filter(names, pattern): This function returns the subset of the list of names passed in the function that match the given pattern.Example: Filter files by more than one file extension.# Python program to illustrate # fnmatch.filter(names, pattern) import fnmatch import os pattern = 'fnmatch_*.py'print ('Pattern :', pattern ) files = os.listdir('.') print ('Files :', files) print ('Matches :', fnmatch.filter(files, pattern))Output :$ python fnmatch_filter.py\n\nPattern : fnmatch_*.py\nFiles : ['__init__.py', 'fnmatch_filter.py', 'fnmatch_fnmatch.py', \n'fnmatch_fnmatchcase.py', 'fnmatch_translate.py', 'index.rst']\nMatches : ['fnmatch_filter.py', 'fnmatch_fnmatch.py',\n'fnmatch_fnmatchcase.py', 'fnmatch_translate.py']\nfnmatch.translate(pattern): This function returns the shell-style pattern converted to a regular expression for using with re.match() (re.match() will only match at the beginning of the string and not at the beginning of each line).# Python program to illustrate # fnmatch.translate(pattern) import fnmatch, re regex = fnmatch.translate('*.txt') reobj = re.compile(regex) print(regex) print(reobj.match('foobar.txt')) Output :'(?s:.*\\\\.txt)\\\\Z'\n_sre.SRE_Match object; span=(0, 10), match='foobar.txt'\n"
},
{
"code": null,
"e": 29127,
"s": 28168,
"text": "fnmatch.fnmatch(filename, pattern): This function tests whether the given filename string matches the pattern string and returns a boolean value. If the operating system is case-insensitive, then both parameters will be normalized to all lower-case or upper-case before the comparison is performed.Example: Script to search all files starting with ‘fnmatch’ and ending in ‘.py’# Python program to illustrate # fnmatch.fnmatch(filename, pattern) import fnmatch import os pattern = 'fnmatch_*.py'print ('Pattern :', pattern )print() files = os.listdir('.') for name in files: print ('Filename: %-25s %s' % (name, fnmatch.fnmatch(name, pattern))Output :$ python fnmatch_fnmatch.py\n\nPattern : fnmatch_*.py\n\nFilename: __init__.py False\nFilename: fnmatch_filter.py True\nFilename: fnmatch_fnmatch.py True\nFilename: fnmatch_fnmatchcase.py True\nFilename: fnmatch_translate.py True\nFilename: index.rst False\n"
},
{
"code": null,
"e": 29207,
"s": 29127,
"text": "Example: Script to search all files starting with ‘fnmatch’ and ending in ‘.py’"
},
{
"code": "# Python program to illustrate # fnmatch.fnmatch(filename, pattern) import fnmatch import os pattern = 'fnmatch_*.py'print ('Pattern :', pattern )print() files = os.listdir('.') for name in files: print ('Filename: %-25s %s' % (name, fnmatch.fnmatch(name, pattern))",
"e": 29480,
"s": 29207,
"text": null
},
{
"code": null,
"e": 29489,
"s": 29480,
"text": "Output :"
},
{
"code": null,
"e": 29791,
"s": 29489,
"text": "$ python fnmatch_fnmatch.py\n\nPattern : fnmatch_*.py\n\nFilename: __init__.py False\nFilename: fnmatch_filter.py True\nFilename: fnmatch_fnmatch.py True\nFilename: fnmatch_fnmatchcase.py True\nFilename: fnmatch_translate.py True\nFilename: index.rst False\n"
},
{
"code": null,
"e": 30691,
"s": 29791,
"text": "fnmatch.fnmatchcase(filename, pattern): This function performs the case sensitive comparison and tests whether the given filename string matches the pattern string and returns a boolean value.Example: Script for a case-sensitive comparison, regardless of the filesystem and operating system settings.# Python program to illustrate # fnmatch.fnmatchcase(filename, pattern) import fnmatch import os pattern = 'FNMATCH_*.PY'print ('Pattern :', pattern) print() files = os.listdir('.') for name in files: (print 'Filename: %-25s %s' % (name, fnmatch.fnmatchcase(name, pattern)))Output :$ python fnmatch_fnmatchcase.py\n\nPattern : FNMATCH_*.PY\n\nFilename: __init__.py False\nFilename: fnmatch_filter.py False\nFilename: FNMATCH_FNMATCH.PY True\nFilename: fnmatch_fnmatchcase.py False\nFilename: fnmatch_translate.py False\nFilename: index.rst False\n"
},
{
"code": null,
"e": 30800,
"s": 30691,
"text": "Example: Script for a case-sensitive comparison, regardless of the filesystem and operating system settings."
},
{
"code": "# Python program to illustrate # fnmatch.fnmatchcase(filename, pattern) import fnmatch import os pattern = 'FNMATCH_*.PY'print ('Pattern :', pattern) print() files = os.listdir('.') for name in files: (print 'Filename: %-25s %s' % (name, fnmatch.fnmatchcase(name, pattern)))",
"e": 31084,
"s": 30800,
"text": null
},
{
"code": null,
"e": 31093,
"s": 31084,
"text": "Output :"
},
{
"code": null,
"e": 31402,
"s": 31093,
"text": "$ python fnmatch_fnmatchcase.py\n\nPattern : FNMATCH_*.PY\n\nFilename: __init__.py False\nFilename: fnmatch_filter.py False\nFilename: FNMATCH_FNMATCH.PY True\nFilename: fnmatch_fnmatchcase.py False\nFilename: fnmatch_translate.py False\nFilename: index.rst False\n"
},
{
"code": null,
"e": 32142,
"s": 31402,
"text": "fnmatch.filter(names, pattern): This function returns the subset of the list of names passed in the function that match the given pattern.Example: Filter files by more than one file extension.# Python program to illustrate # fnmatch.filter(names, pattern) import fnmatch import os pattern = 'fnmatch_*.py'print ('Pattern :', pattern ) files = os.listdir('.') print ('Files :', files) print ('Matches :', fnmatch.filter(files, pattern))Output :$ python fnmatch_filter.py\n\nPattern : fnmatch_*.py\nFiles : ['__init__.py', 'fnmatch_filter.py', 'fnmatch_fnmatch.py', \n'fnmatch_fnmatchcase.py', 'fnmatch_translate.py', 'index.rst']\nMatches : ['fnmatch_filter.py', 'fnmatch_fnmatch.py',\n'fnmatch_fnmatchcase.py', 'fnmatch_translate.py']\n"
},
{
"code": null,
"e": 32197,
"s": 32142,
"text": "Example: Filter files by more than one file extension."
},
{
"code": "# Python program to illustrate # fnmatch.filter(names, pattern) import fnmatch import os pattern = 'fnmatch_*.py'print ('Pattern :', pattern ) files = os.listdir('.') print ('Files :', files) print ('Matches :', fnmatch.filter(files, pattern))",
"e": 32449,
"s": 32197,
"text": null
},
{
"code": null,
"e": 32458,
"s": 32449,
"text": "Output :"
},
{
"code": null,
"e": 32747,
"s": 32458,
"text": "$ python fnmatch_filter.py\n\nPattern : fnmatch_*.py\nFiles : ['__init__.py', 'fnmatch_filter.py', 'fnmatch_fnmatch.py', \n'fnmatch_fnmatchcase.py', 'fnmatch_translate.py', 'index.rst']\nMatches : ['fnmatch_filter.py', 'fnmatch_fnmatch.py',\n'fnmatch_fnmatchcase.py', 'fnmatch_translate.py']\n"
},
{
"code": null,
"e": 33253,
"s": 32747,
"text": "fnmatch.translate(pattern): This function returns the shell-style pattern converted to a regular expression for using with re.match() (re.match() will only match at the beginning of the string and not at the beginning of each line).# Python program to illustrate # fnmatch.translate(pattern) import fnmatch, re regex = fnmatch.translate('*.txt') reobj = re.compile(regex) print(regex) print(reobj.match('foobar.txt')) Output :'(?s:.*\\\\.txt)\\\\Z'\n_sre.SRE_Match object; span=(0, 10), match='foobar.txt'\n"
},
{
"code": "# Python program to illustrate # fnmatch.translate(pattern) import fnmatch, re regex = fnmatch.translate('*.txt') reobj = re.compile(regex) print(regex) print(reobj.match('foobar.txt')) ",
"e": 33444,
"s": 33253,
"text": null
},
{
"code": null,
"e": 33453,
"s": 33444,
"text": "Output :"
},
{
"code": null,
"e": 33529,
"s": 33453,
"text": "'(?s:.*\\\\.txt)\\\\Z'\n_sre.SRE_Match object; span=(0, 10), match='foobar.txt'\n"
},
{
"code": null,
"e": 33828,
"s": 33529,
"text": "This article is contributed by Aditi Gupta. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 33953,
"s": 33828,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 33968,
"s": 33953,
"text": "Python-Library"
},
{
"code": null,
"e": 33981,
"s": 33968,
"text": "python-regex"
},
{
"code": null,
"e": 33988,
"s": 33981,
"text": "Python"
},
{
"code": null,
"e": 34086,
"s": 33988,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34095,
"s": 34086,
"text": "Comments"
},
{
"code": null,
"e": 34108,
"s": 34095,
"text": "Old Comments"
},
{
"code": null,
"e": 34126,
"s": 34108,
"text": "Python Dictionary"
},
{
"code": null,
"e": 34161,
"s": 34126,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 34183,
"s": 34161,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 34215,
"s": 34183,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 34245,
"s": 34215,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 34287,
"s": 34245,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 34313,
"s": 34287,
"text": "Python String | replace()"
},
{
"code": null,
"e": 34356,
"s": 34313,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 34400,
"s": 34356,
"text": "Reading and Writing to text files in Python"
}
] |
C++ STL | Set 8 (unordered set) | Practice | GeeksforGeeks | Implement different operations on an unordered set s .
Input:
The first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries .
A query can be of four types
1. a x (inserts an element x to the unordered set s)
2. b x (erases an element x from the unordered set s)
3. c x (prints 1 if the element x is present in the set else print -1)
4. d (prints the size of the unordered set s)
Output:
The output for each test case will be space separated integers denoting the results of each query .
Constraints:
1<=T<=100
1<=Q<=100
Example(To be used only for only expected output):
Input
2
5
a 1 a 2 a 3 b 2 d
4
a 1 a 5 d c 2
Output
2
2 -1
Explanation :
For the first test case
There are five queries. Queries are performed in this order
1. a 1 {inserts 1 to set now set has {1} }
2. a 2 {inserts 2 to set now set has {1,2} }
3. a 3 {inserts 3 to set now set has {1,2,3} }
4. b 2 {removes 2 from the set }
5. d {prints the size of the unordered set ie 2}
For the second test case
There are four queries. Queries are performed in this order
1. a 1 {inserts 1 to set now set has {1} }
2. a 5 {inserts 5 to set now set has {1,5} }
3. d {prints the size of the set ie 2}
4. c 2 {since 2 is not present in the set prints -1}
Note:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code.
0
deydhananjoy53 months ago
// { Driver Code Starts#include <bits/stdc++.h>using namespace std;
void insert(unordered_set<int> &s,int x);
void erase(unordered_set<int> &s,int x);int size(unordered_set<int> &s);int find(unordered_set<int> &s,int x);
int main() {// your code goes hereint t;cin>>t;while(t--){ unordered_set<int> s; int q; cin>>q; while(q--) { char c; cin>>c; if(c=='a') { int x; cin>>x; insert(s,x); } if(c=='b') { int x; cin>>x; erase(s,x); } if(c=='c') { int x; cin>>x; cout<<find(s,x)<<" "; }if(c=='d') cout<<size(s)<<" "; }cout<<endl;}return 0;}// } Driver Code Ends
/* You are required to complete below methods */
/*inserts an element x to the unordered set s */void insert(unordered_set<int> &s,int x){//Your code heres.insert(x);}
/*erases an element x from the unordered set s */void erase(unordered_set<int> &s,int x){//Your code heres.erase(x);}
/*returns the size of the unordered set s */int size(unordered_set<int> &s){ //Your code here return s.size();}
/*returns 1 if the element x is presentin unordered set s else returns -1 */int find(unordered_set<int> &s,int x){ //Your code here if(s.count(x)==0) return -1; if (s.count(x)==1) return 1;}
0
deydhananjoy5
This comment was deleted.
0
Pawan chaudhary11 months ago
Pawan chaudhary
/*inserts an element x to the unordered set s */void insert(unordered_set<int> &s,int x){s.insert(x);}/*erases an element x from the unordered set s */void erase(unordered_set<int> &s,int x){s.erase(x);}/*returns the size of the unordered set s */int size(unordered_set<int> &s){ return s.size();}/*returns 1 if the element x is presentin unordered set s else returns -1 */int find(unordered_set<int> &s,int x){ if(s.find(x)!=s.end()) return 1; else return -1;}
+2
Arpita1 year ago
Arpita
void insert(unordered_set<int> &s,int x){//Your code heres.insert(x);}
/*erases an element x from the unordered set s */void erase(unordered_set<int> &s,int x){//Your code hereif(s.find(x)!=s.end())s.erase(x);}
/*returns the size of the unordered set s */int size(unordered_set<int> &s){ //Your code here int n = s.size(); return n; }
/*returns 1 if the element x is presentin unordered set s else returns -1 */int find(unordered_set<int> &s,int x){ //Your code here if(s.find(x)!=s.end()) return 1; else return -1;}
0
Nishant_00732 years ago
Nishant_0073
Correct Answer.Correct AnswerExecution Time:0.01
/* You are required to complete below methods *//*inserts an element x to the unordered set s */void insert(unordered_set<int> &s,int x){//Your code heres.insert(x);}/*erases an element x from the unordered set s */void erase(unordered_set<int> &s,int x){//Your code heres.erase(x);}/*returns the size of the unordered set s */int size(unordered_set<int> &s){ //Your code here return s.size();}/*returns 1 if the element x is presentin unordered set s else returns -1 */int find(unordered_set<int> &s,int x){ //Your code here if(s.find(x)!=s.end()) { return 1; } else { return -1; }}
0
Ramswarup Kulhary2 years ago
Ramswarup Kulhary
void insert(unordered_set<int> &s,int x){s.insert(x);}void erase(unordered_set<int> &s,int x){s.erase(x);}int size(unordered_set<int> &s){ return s.size();}int find(unordered_set<int> &s,int x){ unordered_set<int> :: iterator it = s.begin(); while(it!= s.end()) { if(*it == x) return 1; it++; } return -1;}
0
AMAN JAIN2 years ago
AMAN JAIN
void insert(unordered_set<int> &s,int x){s.insert(x);}
/*erases an element x from the unordered set s */void erase(unordered_set<int> &s,int x){s.erase(x);}
/*returns the size of the unordered set s */int size(unordered_set<int> &s){ return s.size();}
/*returns 1 if the element x is presentin unordered set s else returns -1 */int find(unordered_set<int> &s,int x){ if(s.find(x)!=s.end()) return 1; else return -1;}
Execution Time:0.01
0
Saurabh Singh2 years ago
Saurabh Singh
void insert(unordered_set<int> &s,int x){s.insert(x);}/*erases an element x from the unordered set s */void erase(unordered_set<int> &s,int x){s.erase(x);}/*returns the size of the unordered set s */int size(unordered_set<int> &s){ return s.size();}/*returns 1 if the element x is presentin unordered set s else returns -1 */int find(unordered_set<int> &s,int x){ //Your code here auto it = s.find(x); if(it!=s.end()) return 1; return -1;}
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": 988,
"s": 238,
"text": "Implement different operations on an unordered set s .\n\nInput:\nThe first line of input contains an integer T denoting the no of test cases . Then T test cases follow. The first line of input contains an integer Q denoting the no of queries . Then in the next line are Q space separated queries .\nA query can be of four types \n1. a x (inserts an element x to the unordered set s)\n2. b x (erases an element x from the unordered set s)\n3. c x (prints 1 if the element x is present in the set else print -1)\n4. d (prints the size of the unordered set s)\n\nOutput:\nThe output for each test case will be space separated integers denoting the results of each query . \n\nConstraints:\n1<=T<=100\n1<=Q<=100\n\nExample(To be used only for only expected output):"
},
{
"code": null,
"e": 1981,
"s": 988,
"text": "Input\n2\n5\na 1 a 2 a 3 b 2 d\n4\na 1 a 5 d c 2\n \nOutput\n2\n2 -1\n\nExplanation :\nFor the first test case\nThere are five queries. Queries are performed in this order\n1. a 1 {inserts 1 to set now set has {1} }\n2. a 2 {inserts 2 to set now set has {1,2} }\n3. a 3 {inserts 3 to set now set has {1,2,3} }\n4. b 2 {removes 2 from the set }\n5. d {prints the size of the unordered set ie 2}\n\nFor the second test case \nThere are four queries. Queries are performed in this order\n1. a 1 {inserts 1 to set now set has {1} }\n2. a 5 {inserts 5 to set now set has {1,5} }\n3. d {prints the size of the set ie 2}\n4. c 2 {since 2 is not present in the set prints -1}\n\n\nNote:The Input/Output format and Example given are used for system's internal purpose, and should be used by a user for Expected Output only. As it is a function problem, hence a user should not read any input from stdin/console. The task is to complete the function specified, and not to write the full code."
},
{
"code": null,
"e": 1983,
"s": 1981,
"text": "0"
},
{
"code": null,
"e": 2009,
"s": 1983,
"text": "deydhananjoy53 months ago"
},
{
"code": null,
"e": 2077,
"s": 2009,
"text": "// { Driver Code Starts#include <bits/stdc++.h>using namespace std;"
},
{
"code": null,
"e": 2119,
"s": 2077,
"text": "void insert(unordered_set<int> &s,int x);"
},
{
"code": null,
"e": 2230,
"s": 2119,
"text": "void erase(unordered_set<int> &s,int x);int size(unordered_set<int> &s);int find(unordered_set<int> &s,int x);"
},
{
"code": null,
"e": 2619,
"s": 2230,
"text": "int main() {// your code goes hereint t;cin>>t;while(t--){ unordered_set<int> s; int q; cin>>q; while(q--) { char c; cin>>c; if(c=='a') { int x; cin>>x; insert(s,x); } if(c=='b') { int x; cin>>x; erase(s,x); } if(c=='c') { int x; cin>>x; cout<<find(s,x)<<\" \"; }if(c=='d') cout<<size(s)<<\" \"; }cout<<endl;}return 0;}// } Driver Code Ends"
},
{
"code": null,
"e": 2668,
"s": 2619,
"text": "/* You are required to complete below methods */"
},
{
"code": null,
"e": 2787,
"s": 2668,
"text": "/*inserts an element x to the unordered set s */void insert(unordered_set<int> &s,int x){//Your code heres.insert(x);}"
},
{
"code": null,
"e": 2905,
"s": 2787,
"text": "/*erases an element x from the unordered set s */void erase(unordered_set<int> &s,int x){//Your code heres.erase(x);}"
},
{
"code": null,
"e": 3024,
"s": 2905,
"text": "/*returns the size of the unordered set s */int size(unordered_set<int> &s){ //Your code here return s.size();}"
},
{
"code": null,
"e": 3231,
"s": 3024,
"text": "/*returns 1 if the element x is presentin unordered set s else returns -1 */int find(unordered_set<int> &s,int x){ //Your code here if(s.count(x)==0) return -1; if (s.count(x)==1) return 1;} "
},
{
"code": null,
"e": 3233,
"s": 3231,
"text": "0"
},
{
"code": null,
"e": 3247,
"s": 3233,
"text": "deydhananjoy5"
},
{
"code": null,
"e": 3273,
"s": 3247,
"text": "This comment was deleted."
},
{
"code": null,
"e": 3275,
"s": 3273,
"text": "0"
},
{
"code": null,
"e": 3304,
"s": 3275,
"text": "Pawan chaudhary11 months ago"
},
{
"code": null,
"e": 3320,
"s": 3304,
"text": "Pawan chaudhary"
},
{
"code": null,
"e": 3803,
"s": 3320,
"text": "/*inserts an element x to the unordered set s */void insert(unordered_set<int> &s,int x){s.insert(x);}/*erases an element x from the unordered set s */void erase(unordered_set<int> &s,int x){s.erase(x);}/*returns the size of the unordered set s */int size(unordered_set<int> &s){ return s.size();}/*returns 1 if the element x is presentin unordered set s else returns -1 */int find(unordered_set<int> &s,int x){ if(s.find(x)!=s.end()) return 1; else return -1;}"
},
{
"code": null,
"e": 3806,
"s": 3803,
"text": "+2"
},
{
"code": null,
"e": 3823,
"s": 3806,
"text": "Arpita1 year ago"
},
{
"code": null,
"e": 3830,
"s": 3823,
"text": "Arpita"
},
{
"code": null,
"e": 3901,
"s": 3830,
"text": "void insert(unordered_set<int> &s,int x){//Your code heres.insert(x);}"
},
{
"code": null,
"e": 4041,
"s": 3901,
"text": "/*erases an element x from the unordered set s */void erase(unordered_set<int> &s,int x){//Your code hereif(s.find(x)!=s.end())s.erase(x);}"
},
{
"code": null,
"e": 4180,
"s": 4041,
"text": "/*returns the size of the unordered set s */int size(unordered_set<int> &s){ //Your code here int n = s.size(); return n; }"
},
{
"code": null,
"e": 4382,
"s": 4180,
"text": "/*returns 1 if the element x is presentin unordered set s else returns -1 */int find(unordered_set<int> &s,int x){ //Your code here if(s.find(x)!=s.end()) return 1; else return -1;}"
},
{
"code": null,
"e": 4384,
"s": 4382,
"text": "0"
},
{
"code": null,
"e": 4408,
"s": 4384,
"text": "Nishant_00732 years ago"
},
{
"code": null,
"e": 4421,
"s": 4408,
"text": "Nishant_0073"
},
{
"code": null,
"e": 4470,
"s": 4421,
"text": "Correct Answer.Correct AnswerExecution Time:0.01"
},
{
"code": null,
"e": 5107,
"s": 4470,
"text": "/* You are required to complete below methods *//*inserts an element x to the unordered set s */void insert(unordered_set<int> &s,int x){//Your code heres.insert(x);}/*erases an element x from the unordered set s */void erase(unordered_set<int> &s,int x){//Your code heres.erase(x);}/*returns the size of the unordered set s */int size(unordered_set<int> &s){ //Your code here return s.size();}/*returns 1 if the element x is presentin unordered set s else returns -1 */int find(unordered_set<int> &s,int x){ //Your code here if(s.find(x)!=s.end()) { return 1; } else { return -1; }}"
},
{
"code": null,
"e": 5109,
"s": 5107,
"text": "0"
},
{
"code": null,
"e": 5138,
"s": 5109,
"text": "Ramswarup Kulhary2 years ago"
},
{
"code": null,
"e": 5156,
"s": 5138,
"text": "Ramswarup Kulhary"
},
{
"code": null,
"e": 5514,
"s": 5156,
"text": "void insert(unordered_set<int> &s,int x){s.insert(x);}void erase(unordered_set<int> &s,int x){s.erase(x);}int size(unordered_set<int> &s){ return s.size();}int find(unordered_set<int> &s,int x){ unordered_set<int> :: iterator it = s.begin(); while(it!= s.end()) { if(*it == x) return 1; it++; } return -1;}"
},
{
"code": null,
"e": 5516,
"s": 5514,
"text": "0"
},
{
"code": null,
"e": 5537,
"s": 5516,
"text": "AMAN JAIN2 years ago"
},
{
"code": null,
"e": 5547,
"s": 5537,
"text": "AMAN JAIN"
},
{
"code": null,
"e": 5602,
"s": 5547,
"text": "void insert(unordered_set<int> &s,int x){s.insert(x);}"
},
{
"code": null,
"e": 5704,
"s": 5602,
"text": "/*erases an element x from the unordered set s */void erase(unordered_set<int> &s,int x){s.erase(x);}"
},
{
"code": null,
"e": 5804,
"s": 5704,
"text": "/*returns the size of the unordered set s */int size(unordered_set<int> &s){ return s.size();}"
},
{
"code": null,
"e": 5985,
"s": 5804,
"text": "/*returns 1 if the element x is presentin unordered set s else returns -1 */int find(unordered_set<int> &s,int x){ if(s.find(x)!=s.end()) return 1; else return -1;}"
},
{
"code": null,
"e": 6005,
"s": 5985,
"text": "Execution Time:0.01"
},
{
"code": null,
"e": 6007,
"s": 6005,
"text": "0"
},
{
"code": null,
"e": 6032,
"s": 6007,
"text": "Saurabh Singh2 years ago"
},
{
"code": null,
"e": 6046,
"s": 6032,
"text": "Saurabh Singh"
},
{
"code": null,
"e": 6511,
"s": 6046,
"text": "void insert(unordered_set<int> &s,int x){s.insert(x);}/*erases an element x from the unordered set s */void erase(unordered_set<int> &s,int x){s.erase(x);}/*returns the size of the unordered set s */int size(unordered_set<int> &s){ return s.size();}/*returns 1 if the element x is presentin unordered set s else returns -1 */int find(unordered_set<int> &s,int x){ //Your code here auto it = s.find(x); if(it!=s.end()) return 1; return -1;}"
},
{
"code": null,
"e": 6657,
"s": 6511,
"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": 6693,
"s": 6657,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 6703,
"s": 6693,
"text": "\nProblem\n"
},
{
"code": null,
"e": 6713,
"s": 6703,
"text": "\nContest\n"
},
{
"code": null,
"e": 6776,
"s": 6713,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 6924,
"s": 6776,
"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": 7132,
"s": 6924,
"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": 7238,
"s": 7132,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Text Classification Using Naive Bayes: Theory & A Working Example | by Serafeim Loukas | Towards Data Science | IntroductionThe Naive Bayes algorithmDealing with text dataWorking Example in Python (step-by-step guide)Bonus: Having fun with the modelConclusions
Introduction
The Naive Bayes algorithm
Dealing with text data
Working Example in Python (step-by-step guide)
Bonus: Having fun with the model
Conclusions
Naive Bayes classifiers are a collection of classification algorithms based on Bayes’ Theorem. It is not a single algorithm but a family of algorithms where all of them share a common principle, i.e. every pair of features being classified is independent of each other.
Naive Bayes classifiers have been heavily used for text classification and text analysis machine learning problems.
Text Analysis is a major application field for machine learning algorithms. However the raw data, a sequence of symbols (i.e. strings) cannot be fed directly to the algorithms themselves as most of them expect numerical feature vectors with a fixed size rather than the raw text documents with variable length.
In this article I explain a) how Naive Bayes works, b) how we can use text data and fit them into a model after transforming them into a more appropriate form. Finally, I implement a multi-class text classification problem step-by-step in Python.
Let’s get started !!!
Naive Bayes classifiers are a collection of classification algorithms based on Bayes’ Theorem. It is not a single algorithm but a family of algorithms where all of them share a common principle, i.e. every pair of features being classified is independent of each other.
The dataset is divided into two parts, namely, feature matrix and the response/target vector.
The Feature matrix (X) contains all the vectors(rows) of the dataset in which each vector consists of the value of dependent features. The number of features is d i.e. X = (x1,x2,x2, xd).
The Response/target vector (y) contains the value of class/group variable for each row of feature matrix.
Naive Bayes assumes that each feature/variable of the same class makes an:
independent
equal
contribution to the outcome.
Side Note: The assumptions made by Naive Bayes are not generally correct in real-world situations. In-fact, the independence assumption is often not met and this is why it is called “Naive” i.e. because it assumes something that might not be true.
Bayes’ Theorem finds the probability of an event occurring given the probability of another event that has already occurred. Bayes’ theorem is stated mathematically as follows:
where:
A and B are called events.
P(A | B) is the probability of event A, given the event B is true (has occured). Event B is also termed as evidence.
P(A) is the priori of A (the prior independent probability, i.e. probability of event before evidence is seen).
P(B | A) is the probability of B given event A, i.e. probability of event B after evidence A is seen.
Given a data matrix X and a target vector y, we state our problem as:
where, y is class variable and X is a dependent feature vector with dimension d i.e. X = (x1,x2,x2, xd), where d is the number of variables/features of the sample.
P(y|X) is the probability of observing the class y given the sample X with X = (x1,x2,x2, xd), where d is the number of variables/features of the sample.
Now the “naïve” conditional independence assumptions come into play: assume that all features in X are mutually independent, conditional on the category y:
Finally, to find the probability of a given sample for all possible values of the class variable y, we just need to find the output with maximum probability:
One question that arises at this point is the following:
How are we going to use the raw text data to train the model ? The raw data is a collection of strings !
Text Analysis is a major application field for machine learning algorithms. However the raw data, a sequence of symbols (i.e. strings) cannot be fed directly to the algorithms themselves as most of them expect numerical feature vectors with a fixed size rather than the raw text documents with variable length.
In order to address this, scikit-learn provides utilities for the most common ways to extract numerical features from text content, namely:
tokenizing strings and giving an integer id for each possible token, for instance by using white-spaces and punctuation as token separators.
counting the occurrences of tokens in each document.
In this scheme, features and samples are defined as follows:
each individual token occurrence frequency is treated as a feature.
the vector of all the token frequencies for a given document is considered a multivariate sample.
from sklearn.feature_extraction.text import CountVectorizercorpus = [ 'This is the first document.', 'This document is the second document.', 'And this is the third one.', 'Is this the first document?',]vectorizer = CountVectorizer()X = vectorizer.fit_transform(corpus)print(vectorizer.get_feature_names())[‘and’, ‘document’, ‘first’, ‘is’, ‘one’, ‘second’, ‘the’, ‘third’, ‘this’]print(X.toarray())[[0 1 1 1 0 0 1 0 1] [0 2 0 1 0 1 1 0 1] [1 0 0 1 1 0 1 1 1] [0 1 1 1 0 0 1 0 1]]
In the above toy example, we have a collection of strings stored into the variable corpus. Using the text transformer, we can see that we have a specific number of unique strings (vocabulary) in our data.
This can be seen by printing the vectorizer.get_feature_names() variable. We observe that we have 9 unique words.
Next, we printed the transformed data (X) and we observe the following:
We have 4 rows in X as the number of our text strings (we have the same number of samples after the transformation).
We have the same number of columns (features/variables) in the transformed data (X) for all the samples (this was not the case before that transformation i.e. the individual strings had different lengths).
The values 0,1,2, encode the frequency of a word that appeared in the initial text data.
E.g. The first transformed row is [0 1 1 1 0 0 1 0 1] and the unique vocabulary is [‘and’, ‘document’, ‘first’, ‘is’, ‘one’, ‘second’, ‘the’, ‘third’, ‘this’], thus this means that the words “document”, “first”, “is”, “the” and “this” appeared 1 time each in the initial text string (i.e. ‘This is the first document.’).
Side note: This is the counting approach. The term-frequency transform is nothing more than a transformation of a count matrix into a normalized term-frequency matrix.
Hope everything is clear now. If not, read this paragraph as many times as it is needed in order to really grasp the idea and understand this transformation. It is a fundamental step.
Now that you understood how the Naive Bayes and the Text Transformation work, it’s time to start coding !
As a working example, we will use some text data and we will build a Naive Bayes model to predict the categories of the texts. This is a multi-class (20 classes) text classification problem.
Let’s start (I will walk you through). First, we will load all the necessary libraries:
import numpy as np, pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltfrom sklearn.datasets import fetch_20newsgroupsfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.pipeline import make_pipelinefrom sklearn.metrics import confusion_matrix, accuracy_scoresns.set() # use seaborn plotting style
Next, let’s load the data (training and test sets):
# Load the datasetdata = fetch_20newsgroups()# Get the text categoriestext_categories = data.target_names# define the training settrain_data = fetch_20newsgroups(subset="train", categories=text_categories)# define the test settest_data = fetch_20newsgroups(subset="test", categories=text_categories)
Let’s find out how many classes and samples we have:
print("We have {} unique classes".format(len(text_categories)))print("We have {} training samples".format(len(train_data.data)))print("We have {} test samples".format(len(test_data.data)))
The above prints:
We have 20 unique classesWe have 11314 training samplesWe have 7532 test samples
So, this is a 20-class text classification problem with n_train = 11314 training samples (text sentences) and n_test = 7532 test samples (text sentences).
Let’s visualize the 5th training sample:
# let’s have a look as some training dataprint(test_data.data[5])
As mentioned previously, our data are texts (more specifically, emails) so you should see something like the following printed out:
The next step consists of building the Naive Bayes classifier and finally training the model. In our example, we will convert the collection of text documents (train and test sets) into a matrix of token counts (I explained how this works in Section 3).
To implement that text transformation we will use the make_pipeline function. This will internally transform the text data and then the model will be fitted using the transformed data.
# Build the modelmodel = make_pipeline(TfidfVectorizer(), MultinomialNB())# Train the model using the training datamodel.fit(train_data.data, train_data.target)# Predict the categories of the test datapredicted_categories = model.predict(test_data.data)
The last line of code predicts the labels of the test set.
Let’s see the predicted categories names:
print(np.array(test_data.target_names)[predicted_categories])array(['rec.autos', 'sci.crypt', 'alt.atheism', ..., 'rec.sport.baseball', 'comp.sys.ibm.pc.hardware', 'soc.religion.christian'], dtype='<U24')
Finally, let’s build the multi-class confusion matrix to see if the model is good or if the model predicts correctly only specific text categories.
# plot the confusion matrixmat = confusion_matrix(test_data.target, predicted_categories)sns.heatmap(mat.T, square = True, annot=True, fmt = "d", xticklabels=train_data.target_names,yticklabels=train_data.target_names)plt.xlabel("true labels")plt.ylabel("predicted label")plt.show()print("The accuracy is {}".format(accuracy_score(test_data.target, predicted_categories)))The accuracy is 0.7738980350504514
Let’s have some fun using the trained model. Let’s classify whatever sentence we like 😄.
# custom function to have fundef my_predictions(my_sentence, model): all_categories_names = np.array(data.target_names) prediction = model.predict([my_sentence]) return all_categories_names[prediction]my_sentence = “jesus”print(my_predictions(my_sentence, model))['soc.religion.christian']my_sentence = "Are you an atheist?"print(my_predictions(my_sentence, model))['alt.atheism']
We inserted the string “jesus” to the model and it predicted the class “[‘soc.religion.christian’]”.
Change the “my_sentence” into other stings and play with the model 😃.
We saw that Naive Bayes is a very powerful algorithm for multi-class text classification problems.
Side Note: If you want to know more about the confusion matrix (and the ROC curve) read this:
towardsdatascience.com
From the above confusion matrix, we can verify that the model is really good.
It is able to correctly predict all 20 classes of the text data (most values are on the diagonal and few are off-the-diagonal).
We also notice that the highest miss-classification (value off-the-diagonal) is 131 (5 lines from the end, last column at the right). The value 131 means that 131 documents that belonged to the “religion miscellaneous ” category were miss-classified as belonging to the “religion christian” category.
Interesting thing that these 2 categories are really similar and actually one could characterize these as 2 subgroups of a larger group e.g. “religion” in general.
Finally, the accuracy on the test set is 0.7739 which is quite good for a 20-class text classification problem 🚀.
That’s all folks! Hope you liked this article.
If you liked and found this article useful, follow 👣 me to be able to see all my new posts.
Questions? Post them as a comment and I will reply as soon as possible. | [
{
"code": null,
"e": 321,
"s": 172,
"text": "IntroductionThe Naive Bayes algorithmDealing with text dataWorking Example in Python (step-by-step guide)Bonus: Having fun with the modelConclusions"
},
{
"code": null,
"e": 334,
"s": 321,
"text": "Introduction"
},
{
"code": null,
"e": 360,
"s": 334,
"text": "The Naive Bayes algorithm"
},
{
"code": null,
"e": 383,
"s": 360,
"text": "Dealing with text data"
},
{
"code": null,
"e": 430,
"s": 383,
"text": "Working Example in Python (step-by-step guide)"
},
{
"code": null,
"e": 463,
"s": 430,
"text": "Bonus: Having fun with the model"
},
{
"code": null,
"e": 475,
"s": 463,
"text": "Conclusions"
},
{
"code": null,
"e": 745,
"s": 475,
"text": "Naive Bayes classifiers are a collection of classification algorithms based on Bayes’ Theorem. It is not a single algorithm but a family of algorithms where all of them share a common principle, i.e. every pair of features being classified is independent of each other."
},
{
"code": null,
"e": 861,
"s": 745,
"text": "Naive Bayes classifiers have been heavily used for text classification and text analysis machine learning problems."
},
{
"code": null,
"e": 1172,
"s": 861,
"text": "Text Analysis is a major application field for machine learning algorithms. However the raw data, a sequence of symbols (i.e. strings) cannot be fed directly to the algorithms themselves as most of them expect numerical feature vectors with a fixed size rather than the raw text documents with variable length."
},
{
"code": null,
"e": 1419,
"s": 1172,
"text": "In this article I explain a) how Naive Bayes works, b) how we can use text data and fit them into a model after transforming them into a more appropriate form. Finally, I implement a multi-class text classification problem step-by-step in Python."
},
{
"code": null,
"e": 1441,
"s": 1419,
"text": "Let’s get started !!!"
},
{
"code": null,
"e": 1711,
"s": 1441,
"text": "Naive Bayes classifiers are a collection of classification algorithms based on Bayes’ Theorem. It is not a single algorithm but a family of algorithms where all of them share a common principle, i.e. every pair of features being classified is independent of each other."
},
{
"code": null,
"e": 1805,
"s": 1711,
"text": "The dataset is divided into two parts, namely, feature matrix and the response/target vector."
},
{
"code": null,
"e": 1993,
"s": 1805,
"text": "The Feature matrix (X) contains all the vectors(rows) of the dataset in which each vector consists of the value of dependent features. The number of features is d i.e. X = (x1,x2,x2, xd)."
},
{
"code": null,
"e": 2099,
"s": 1993,
"text": "The Response/target vector (y) contains the value of class/group variable for each row of feature matrix."
},
{
"code": null,
"e": 2174,
"s": 2099,
"text": "Naive Bayes assumes that each feature/variable of the same class makes an:"
},
{
"code": null,
"e": 2186,
"s": 2174,
"text": "independent"
},
{
"code": null,
"e": 2192,
"s": 2186,
"text": "equal"
},
{
"code": null,
"e": 2221,
"s": 2192,
"text": "contribution to the outcome."
},
{
"code": null,
"e": 2469,
"s": 2221,
"text": "Side Note: The assumptions made by Naive Bayes are not generally correct in real-world situations. In-fact, the independence assumption is often not met and this is why it is called “Naive” i.e. because it assumes something that might not be true."
},
{
"code": null,
"e": 2646,
"s": 2469,
"text": "Bayes’ Theorem finds the probability of an event occurring given the probability of another event that has already occurred. Bayes’ theorem is stated mathematically as follows:"
},
{
"code": null,
"e": 2653,
"s": 2646,
"text": "where:"
},
{
"code": null,
"e": 2680,
"s": 2653,
"text": "A and B are called events."
},
{
"code": null,
"e": 2797,
"s": 2680,
"text": "P(A | B) is the probability of event A, given the event B is true (has occured). Event B is also termed as evidence."
},
{
"code": null,
"e": 2909,
"s": 2797,
"text": "P(A) is the priori of A (the prior independent probability, i.e. probability of event before evidence is seen)."
},
{
"code": null,
"e": 3011,
"s": 2909,
"text": "P(B | A) is the probability of B given event A, i.e. probability of event B after evidence A is seen."
},
{
"code": null,
"e": 3081,
"s": 3011,
"text": "Given a data matrix X and a target vector y, we state our problem as:"
},
{
"code": null,
"e": 3245,
"s": 3081,
"text": "where, y is class variable and X is a dependent feature vector with dimension d i.e. X = (x1,x2,x2, xd), where d is the number of variables/features of the sample."
},
{
"code": null,
"e": 3399,
"s": 3245,
"text": "P(y|X) is the probability of observing the class y given the sample X with X = (x1,x2,x2, xd), where d is the number of variables/features of the sample."
},
{
"code": null,
"e": 3556,
"s": 3399,
"text": "Now the “naïve” conditional independence assumptions come into play: assume that all features in X are mutually independent, conditional on the category y:"
},
{
"code": null,
"e": 3714,
"s": 3556,
"text": "Finally, to find the probability of a given sample for all possible values of the class variable y, we just need to find the output with maximum probability:"
},
{
"code": null,
"e": 3771,
"s": 3714,
"text": "One question that arises at this point is the following:"
},
{
"code": null,
"e": 3876,
"s": 3771,
"text": "How are we going to use the raw text data to train the model ? The raw data is a collection of strings !"
},
{
"code": null,
"e": 4187,
"s": 3876,
"text": "Text Analysis is a major application field for machine learning algorithms. However the raw data, a sequence of symbols (i.e. strings) cannot be fed directly to the algorithms themselves as most of them expect numerical feature vectors with a fixed size rather than the raw text documents with variable length."
},
{
"code": null,
"e": 4327,
"s": 4187,
"text": "In order to address this, scikit-learn provides utilities for the most common ways to extract numerical features from text content, namely:"
},
{
"code": null,
"e": 4468,
"s": 4327,
"text": "tokenizing strings and giving an integer id for each possible token, for instance by using white-spaces and punctuation as token separators."
},
{
"code": null,
"e": 4521,
"s": 4468,
"text": "counting the occurrences of tokens in each document."
},
{
"code": null,
"e": 4582,
"s": 4521,
"text": "In this scheme, features and samples are defined as follows:"
},
{
"code": null,
"e": 4650,
"s": 4582,
"text": "each individual token occurrence frequency is treated as a feature."
},
{
"code": null,
"e": 4748,
"s": 4650,
"text": "the vector of all the token frequencies for a given document is considered a multivariate sample."
},
{
"code": null,
"e": 5241,
"s": 4748,
"text": "from sklearn.feature_extraction.text import CountVectorizercorpus = [ 'This is the first document.', 'This document is the second document.', 'And this is the third one.', 'Is this the first document?',]vectorizer = CountVectorizer()X = vectorizer.fit_transform(corpus)print(vectorizer.get_feature_names())[‘and’, ‘document’, ‘first’, ‘is’, ‘one’, ‘second’, ‘the’, ‘third’, ‘this’]print(X.toarray())[[0 1 1 1 0 0 1 0 1] [0 2 0 1 0 1 1 0 1] [1 0 0 1 1 0 1 1 1] [0 1 1 1 0 0 1 0 1]]"
},
{
"code": null,
"e": 5446,
"s": 5241,
"text": "In the above toy example, we have a collection of strings stored into the variable corpus. Using the text transformer, we can see that we have a specific number of unique strings (vocabulary) in our data."
},
{
"code": null,
"e": 5560,
"s": 5446,
"text": "This can be seen by printing the vectorizer.get_feature_names() variable. We observe that we have 9 unique words."
},
{
"code": null,
"e": 5632,
"s": 5560,
"text": "Next, we printed the transformed data (X) and we observe the following:"
},
{
"code": null,
"e": 5749,
"s": 5632,
"text": "We have 4 rows in X as the number of our text strings (we have the same number of samples after the transformation)."
},
{
"code": null,
"e": 5955,
"s": 5749,
"text": "We have the same number of columns (features/variables) in the transformed data (X) for all the samples (this was not the case before that transformation i.e. the individual strings had different lengths)."
},
{
"code": null,
"e": 6044,
"s": 5955,
"text": "The values 0,1,2, encode the frequency of a word that appeared in the initial text data."
},
{
"code": null,
"e": 6365,
"s": 6044,
"text": "E.g. The first transformed row is [0 1 1 1 0 0 1 0 1] and the unique vocabulary is [‘and’, ‘document’, ‘first’, ‘is’, ‘one’, ‘second’, ‘the’, ‘third’, ‘this’], thus this means that the words “document”, “first”, “is”, “the” and “this” appeared 1 time each in the initial text string (i.e. ‘This is the first document.’)."
},
{
"code": null,
"e": 6533,
"s": 6365,
"text": "Side note: This is the counting approach. The term-frequency transform is nothing more than a transformation of a count matrix into a normalized term-frequency matrix."
},
{
"code": null,
"e": 6717,
"s": 6533,
"text": "Hope everything is clear now. If not, read this paragraph as many times as it is needed in order to really grasp the idea and understand this transformation. It is a fundamental step."
},
{
"code": null,
"e": 6823,
"s": 6717,
"text": "Now that you understood how the Naive Bayes and the Text Transformation work, it’s time to start coding !"
},
{
"code": null,
"e": 7014,
"s": 6823,
"text": "As a working example, we will use some text data and we will build a Naive Bayes model to predict the categories of the texts. This is a multi-class (20 classes) text classification problem."
},
{
"code": null,
"e": 7102,
"s": 7014,
"text": "Let’s start (I will walk you through). First, we will load all the necessary libraries:"
},
{
"code": null,
"e": 7478,
"s": 7102,
"text": "import numpy as np, pandas as pdimport seaborn as snsimport matplotlib.pyplot as pltfrom sklearn.datasets import fetch_20newsgroupsfrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.naive_bayes import MultinomialNBfrom sklearn.pipeline import make_pipelinefrom sklearn.metrics import confusion_matrix, accuracy_scoresns.set() # use seaborn plotting style"
},
{
"code": null,
"e": 7530,
"s": 7478,
"text": "Next, let’s load the data (training and test sets):"
},
{
"code": null,
"e": 7830,
"s": 7530,
"text": "# Load the datasetdata = fetch_20newsgroups()# Get the text categoriestext_categories = data.target_names# define the training settrain_data = fetch_20newsgroups(subset=\"train\", categories=text_categories)# define the test settest_data = fetch_20newsgroups(subset=\"test\", categories=text_categories)"
},
{
"code": null,
"e": 7883,
"s": 7830,
"text": "Let’s find out how many classes and samples we have:"
},
{
"code": null,
"e": 8072,
"s": 7883,
"text": "print(\"We have {} unique classes\".format(len(text_categories)))print(\"We have {} training samples\".format(len(train_data.data)))print(\"We have {} test samples\".format(len(test_data.data)))"
},
{
"code": null,
"e": 8090,
"s": 8072,
"text": "The above prints:"
},
{
"code": null,
"e": 8171,
"s": 8090,
"text": "We have 20 unique classesWe have 11314 training samplesWe have 7532 test samples"
},
{
"code": null,
"e": 8326,
"s": 8171,
"text": "So, this is a 20-class text classification problem with n_train = 11314 training samples (text sentences) and n_test = 7532 test samples (text sentences)."
},
{
"code": null,
"e": 8367,
"s": 8326,
"text": "Let’s visualize the 5th training sample:"
},
{
"code": null,
"e": 8433,
"s": 8367,
"text": "# let’s have a look as some training dataprint(test_data.data[5])"
},
{
"code": null,
"e": 8565,
"s": 8433,
"text": "As mentioned previously, our data are texts (more specifically, emails) so you should see something like the following printed out:"
},
{
"code": null,
"e": 8819,
"s": 8565,
"text": "The next step consists of building the Naive Bayes classifier and finally training the model. In our example, we will convert the collection of text documents (train and test sets) into a matrix of token counts (I explained how this works in Section 3)."
},
{
"code": null,
"e": 9004,
"s": 8819,
"text": "To implement that text transformation we will use the make_pipeline function. This will internally transform the text data and then the model will be fitted using the transformed data."
},
{
"code": null,
"e": 9258,
"s": 9004,
"text": "# Build the modelmodel = make_pipeline(TfidfVectorizer(), MultinomialNB())# Train the model using the training datamodel.fit(train_data.data, train_data.target)# Predict the categories of the test datapredicted_categories = model.predict(test_data.data)"
},
{
"code": null,
"e": 9317,
"s": 9258,
"text": "The last line of code predicts the labels of the test set."
},
{
"code": null,
"e": 9359,
"s": 9317,
"text": "Let’s see the predicted categories names:"
},
{
"code": null,
"e": 9564,
"s": 9359,
"text": "print(np.array(test_data.target_names)[predicted_categories])array(['rec.autos', 'sci.crypt', 'alt.atheism', ..., 'rec.sport.baseball', 'comp.sys.ibm.pc.hardware', 'soc.religion.christian'], dtype='<U24')"
},
{
"code": null,
"e": 9712,
"s": 9564,
"text": "Finally, let’s build the multi-class confusion matrix to see if the model is good or if the model predicts correctly only specific text categories."
},
{
"code": null,
"e": 10119,
"s": 9712,
"text": "# plot the confusion matrixmat = confusion_matrix(test_data.target, predicted_categories)sns.heatmap(mat.T, square = True, annot=True, fmt = \"d\", xticklabels=train_data.target_names,yticklabels=train_data.target_names)plt.xlabel(\"true labels\")plt.ylabel(\"predicted label\")plt.show()print(\"The accuracy is {}\".format(accuracy_score(test_data.target, predicted_categories)))The accuracy is 0.7738980350504514"
},
{
"code": null,
"e": 10208,
"s": 10119,
"text": "Let’s have some fun using the trained model. Let’s classify whatever sentence we like 😄."
},
{
"code": null,
"e": 10598,
"s": 10208,
"text": "# custom function to have fundef my_predictions(my_sentence, model): all_categories_names = np.array(data.target_names) prediction = model.predict([my_sentence]) return all_categories_names[prediction]my_sentence = “jesus”print(my_predictions(my_sentence, model))['soc.religion.christian']my_sentence = \"Are you an atheist?\"print(my_predictions(my_sentence, model))['alt.atheism']"
},
{
"code": null,
"e": 10699,
"s": 10598,
"text": "We inserted the string “jesus” to the model and it predicted the class “[‘soc.religion.christian’]”."
},
{
"code": null,
"e": 10769,
"s": 10699,
"text": "Change the “my_sentence” into other stings and play with the model 😃."
},
{
"code": null,
"e": 10868,
"s": 10769,
"text": "We saw that Naive Bayes is a very powerful algorithm for multi-class text classification problems."
},
{
"code": null,
"e": 10962,
"s": 10868,
"text": "Side Note: If you want to know more about the confusion matrix (and the ROC curve) read this:"
},
{
"code": null,
"e": 10985,
"s": 10962,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11063,
"s": 10985,
"text": "From the above confusion matrix, we can verify that the model is really good."
},
{
"code": null,
"e": 11191,
"s": 11063,
"text": "It is able to correctly predict all 20 classes of the text data (most values are on the diagonal and few are off-the-diagonal)."
},
{
"code": null,
"e": 11492,
"s": 11191,
"text": "We also notice that the highest miss-classification (value off-the-diagonal) is 131 (5 lines from the end, last column at the right). The value 131 means that 131 documents that belonged to the “religion miscellaneous ” category were miss-classified as belonging to the “religion christian” category."
},
{
"code": null,
"e": 11656,
"s": 11492,
"text": "Interesting thing that these 2 categories are really similar and actually one could characterize these as 2 subgroups of a larger group e.g. “religion” in general."
},
{
"code": null,
"e": 11770,
"s": 11656,
"text": "Finally, the accuracy on the test set is 0.7739 which is quite good for a 20-class text classification problem 🚀."
},
{
"code": null,
"e": 11817,
"s": 11770,
"text": "That’s all folks! Hope you liked this article."
},
{
"code": null,
"e": 11909,
"s": 11817,
"text": "If you liked and found this article useful, follow 👣 me to be able to see all my new posts."
}
] |
Chunking in NLP: decoded. When I started learning text processing... | by Nikita Bachani | Towards Data Science | When I started learning text processing, the one topic on which I stuck for long is chunking. (I know, it’s strange to believe🙆)Usually, we can find many articles on the web from easy to hard topic, but when it comes to this particular topic I felt there’s no single article concludes overall understanding about chunking, however below piece of writing is an amalgamation of all articles or videos I have studied so far, related to the topic.
So here’s my understanding about chunking.
Chunking is a process of extracting phrases from unstructured text, which means analyzing a sentence to identify the constituents(Noun Groups, Verbs, verb groups, etc.) However, it does not specify their internal structure, nor their role in the main sentence.
It works on top of POS tagging. It uses POS-tags as input and provides chunks as output.
In short, Chunking means grouping of words/tokens into chunks
I used to think that normally text processing is done by simply breaking the sentence into words before I was introduced to such topics further. so simply breaking into words isn’t very helpful. It’s very crucial to know that sentence involves a person, a date, places, etc.. (different entities). so they alone are of no use.
Chunking can break sentences into phrases that are more useful than individual words and yield meaningful results.
Chunking is very important when you want to extract information from text such as locations, person names. (entity extraction)
Let’s understand it from scratch.
A sentence typically follows a hierarchical structure consisting of the following components.
Group of words make up phrases and there are five major categories.
Noun Phrase (NP)
Verb phrase (VP)
Adjective phrase (ADJP)
Adverb phrase (ADVP)
Prepositional phrase (PP)
Phrase structure rules:
S -> NP VP
NP -> {Det N,Pro,PN}
VP -> V (NP) (PP) (Adv)
PP -> P NP
AP -> A (PP)
Before diving deeper into chunking, It’s good to have a brief knowledge about syntax tree and grammar rules.
As we can see, Here the whole sentence is divided into two different chunks which are NP(noun phrase).
Now lets under understand this concept with python experiment.
Regex based chunking
Regex based chunking
Code snippet for chunker based on regex pattern
Here, we have introduced a grammar.in which NP (Noun phrase) is combined byDT? → one or zero determinerJJ* → zero or more adjectivesNN → Noun
and we parse this grammar by NLTK defined regular expression parser. As we can see, Whole sentence S is divided into chunks and represented in tree-like structures. Based on defined grammar, an internally tree-like structure is created. So you can define your grammar, based on that sentence will be chunked.
2. Training tagger based chunker
I’ve used the `conll2000` corpus for training chunker. conll2000 corpus defines the chunks using IOB tags.
It specifies where the chunk begins and ends, along with its types.A POS tagger can be trained on these IOB tags
The chunk tags use the IOB format.IOB : Inside,Outside,BeginningB- prefix before a tag indicates, it’s the beginning of a chunkI- prefix indicates that it’s inside a chunkO- tag indicates the token doesn’t belong to any chunk
#Here conll2000 corpus for training shallow parser modelnltk.download('conll2000')from nltk.corpus import conll2000data= conll2000.chunked_sents()train_data=data[:10900]test_data=data[10900:]print(len(train_data),len(test_data))print(train_data[1])
tree2conlltags,conlltags2tree are chunking utility functions.
→ `tree2conlltags`, to get triples of (word, tag, chunk tags for each token). These tuples are then finally used to train a tagger and it learns IOB tags for POS tags.
→ `conlltags2tree` to generate a parse tree from these token triplesConlltags2tree() is reversal of tree2conlltags().We’ll be using these functions to train our parser
from nltk.chunk.util import tree2conlltags,conlltags2treewtc=tree2conlltags(train_data[1])wtc
tree=conlltags2tree(wtc)print(tree)
def conll_tag_chunks(chunk_sents): tagged_sents = [tree2conlltags(tree) for tree in chunk_sents] return [[(t, c) for (w, t, c) in sent] for sent in tagged_sents]def combined_tagger(train_data, taggers, backoff=None): for tagger in taggers: backoff = tagger(train_data, backoff=backoff) return backoff
It reads text and assigns a POS tag to each word. (word, tag)
Unigram tagger: For determining the POS, It only uses a single word. (single word context-based tagger)
The UnigramTagger, BigramTagger, and TrigramTagger are classes that inherit from the base class NGramTagger, which itself inherits from the ContextTagger class, which inherits from the SequentialBackoffTagger class
We will now define a class NGramTagChunker that will take in tagged sentences as training input, get their (word, POS tag, chunk tag)WTC triples and train a BigramTagger with a UnigramTagger as the backoff tagger.
We will also define a parse() function to perform shallow parsing on a new sentence.
from nltk.tag import UnigramTagger, BigramTaggerfrom nltk.chunk import ChunkParserI#Define the chunker classclass NGramTagChunker(ChunkParserI): def __init__(self,train_sentences,tagger_classes=[UnigramTagger,BigramTagger]): train_sent_tags=conll_tag_chunks(train_sentences) self.chunk_tagger=combined_tagger(train_sent_tags,tagger_classes)def parse(self,tagged_sentence): if not tagged_sentence: return None pos_tags=[tag for word, tag in tagged_sentence] chunk_pos_tags=self.chunk_tagger.tag(pos_tags) chunk_tags=[chunk_tag for (pos_tag,chunk_tag) in chunk_pos_tags] wpc_tags=[(word,pos_tag,chunk_tag) for ((word,pos_tag),chunk_tag) in zip(tagged_sentence,chunk_tags)] return conlltags2tree(wpc_tags)#train chunker modelntc=NGramTagChunker(train_data)#evaluate chunker model performanceprint(ntc.evaluate(test_data))
Now we’ll leverage this model to shallow parse and chunk our sample news article headline.
import pandas as pdsentence='No new emoji may be released in 2021 due to COVID-19 pandemic word'nltk_pos_tagged=nltk.pos_tag(sentence.split())pd.DataFrame(nltk_pos_tagged,columns=['word','POS tag'])
chunk_tree=ntc.parse(nltk_pos_tagged)print(chunk_tree)
chunk_tree
You can also define classifier based chunker according to need. You can read more about it here.
https://www.geeksforgeeks.org/nlp-classifier-based-chunking-set-1/?ref=rp
We create a sequence to tokens, which are not included in the chunk. So it’s finding insights or context. (I am not covering in this section)
Thank you for reading.🙏
I’ve tried to cover this topic in maximum depth. Suggestions are welcome.
As an honorable mention, I would like to thank Dipanjan (DJ) Sarkar.I’ve been following his tutorial to learn NLP from scratch.
P.S This is my first technical writeup. Hopefully I’ll continue to write as I progress in my learning. | [
{
"code": null,
"e": 616,
"s": 172,
"text": "When I started learning text processing, the one topic on which I stuck for long is chunking. (I know, it’s strange to believe🙆)Usually, we can find many articles on the web from easy to hard topic, but when it comes to this particular topic I felt there’s no single article concludes overall understanding about chunking, however below piece of writing is an amalgamation of all articles or videos I have studied so far, related to the topic."
},
{
"code": null,
"e": 659,
"s": 616,
"text": "So here’s my understanding about chunking."
},
{
"code": null,
"e": 920,
"s": 659,
"text": "Chunking is a process of extracting phrases from unstructured text, which means analyzing a sentence to identify the constituents(Noun Groups, Verbs, verb groups, etc.) However, it does not specify their internal structure, nor their role in the main sentence."
},
{
"code": null,
"e": 1009,
"s": 920,
"text": "It works on top of POS tagging. It uses POS-tags as input and provides chunks as output."
},
{
"code": null,
"e": 1071,
"s": 1009,
"text": "In short, Chunking means grouping of words/tokens into chunks"
},
{
"code": null,
"e": 1398,
"s": 1071,
"text": "I used to think that normally text processing is done by simply breaking the sentence into words before I was introduced to such topics further. so simply breaking into words isn’t very helpful. It’s very crucial to know that sentence involves a person, a date, places, etc.. (different entities). so they alone are of no use."
},
{
"code": null,
"e": 1513,
"s": 1398,
"text": "Chunking can break sentences into phrases that are more useful than individual words and yield meaningful results."
},
{
"code": null,
"e": 1640,
"s": 1513,
"text": "Chunking is very important when you want to extract information from text such as locations, person names. (entity extraction)"
},
{
"code": null,
"e": 1674,
"s": 1640,
"text": "Let’s understand it from scratch."
},
{
"code": null,
"e": 1768,
"s": 1674,
"text": "A sentence typically follows a hierarchical structure consisting of the following components."
},
{
"code": null,
"e": 1836,
"s": 1768,
"text": "Group of words make up phrases and there are five major categories."
},
{
"code": null,
"e": 1853,
"s": 1836,
"text": "Noun Phrase (NP)"
},
{
"code": null,
"e": 1870,
"s": 1853,
"text": "Verb phrase (VP)"
},
{
"code": null,
"e": 1894,
"s": 1870,
"text": "Adjective phrase (ADJP)"
},
{
"code": null,
"e": 1915,
"s": 1894,
"text": "Adverb phrase (ADVP)"
},
{
"code": null,
"e": 1941,
"s": 1915,
"text": "Prepositional phrase (PP)"
},
{
"code": null,
"e": 1965,
"s": 1941,
"text": "Phrase structure rules:"
},
{
"code": null,
"e": 1976,
"s": 1965,
"text": "S -> NP VP"
},
{
"code": null,
"e": 1997,
"s": 1976,
"text": "NP -> {Det N,Pro,PN}"
},
{
"code": null,
"e": 2021,
"s": 1997,
"text": "VP -> V (NP) (PP) (Adv)"
},
{
"code": null,
"e": 2032,
"s": 2021,
"text": "PP -> P NP"
},
{
"code": null,
"e": 2045,
"s": 2032,
"text": "AP -> A (PP)"
},
{
"code": null,
"e": 2154,
"s": 2045,
"text": "Before diving deeper into chunking, It’s good to have a brief knowledge about syntax tree and grammar rules."
},
{
"code": null,
"e": 2257,
"s": 2154,
"text": "As we can see, Here the whole sentence is divided into two different chunks which are NP(noun phrase)."
},
{
"code": null,
"e": 2320,
"s": 2257,
"text": "Now lets under understand this concept with python experiment."
},
{
"code": null,
"e": 2341,
"s": 2320,
"text": "Regex based chunking"
},
{
"code": null,
"e": 2362,
"s": 2341,
"text": "Regex based chunking"
},
{
"code": null,
"e": 2410,
"s": 2362,
"text": "Code snippet for chunker based on regex pattern"
},
{
"code": null,
"e": 2552,
"s": 2410,
"text": "Here, we have introduced a grammar.in which NP (Noun phrase) is combined byDT? → one or zero determinerJJ* → zero or more adjectivesNN → Noun"
},
{
"code": null,
"e": 2861,
"s": 2552,
"text": "and we parse this grammar by NLTK defined regular expression parser. As we can see, Whole sentence S is divided into chunks and represented in tree-like structures. Based on defined grammar, an internally tree-like structure is created. So you can define your grammar, based on that sentence will be chunked."
},
{
"code": null,
"e": 2894,
"s": 2861,
"text": "2. Training tagger based chunker"
},
{
"code": null,
"e": 3001,
"s": 2894,
"text": "I’ve used the `conll2000` corpus for training chunker. conll2000 corpus defines the chunks using IOB tags."
},
{
"code": null,
"e": 3114,
"s": 3001,
"text": "It specifies where the chunk begins and ends, along with its types.A POS tagger can be trained on these IOB tags"
},
{
"code": null,
"e": 3340,
"s": 3114,
"text": "The chunk tags use the IOB format.IOB : Inside,Outside,BeginningB- prefix before a tag indicates, it’s the beginning of a chunkI- prefix indicates that it’s inside a chunkO- tag indicates the token doesn’t belong to any chunk"
},
{
"code": null,
"e": 3589,
"s": 3340,
"text": "#Here conll2000 corpus for training shallow parser modelnltk.download('conll2000')from nltk.corpus import conll2000data= conll2000.chunked_sents()train_data=data[:10900]test_data=data[10900:]print(len(train_data),len(test_data))print(train_data[1])"
},
{
"code": null,
"e": 3651,
"s": 3589,
"text": "tree2conlltags,conlltags2tree are chunking utility functions."
},
{
"code": null,
"e": 3819,
"s": 3651,
"text": "→ `tree2conlltags`, to get triples of (word, tag, chunk tags for each token). These tuples are then finally used to train a tagger and it learns IOB tags for POS tags."
},
{
"code": null,
"e": 3987,
"s": 3819,
"text": "→ `conlltags2tree` to generate a parse tree from these token triplesConlltags2tree() is reversal of tree2conlltags().We’ll be using these functions to train our parser"
},
{
"code": null,
"e": 4081,
"s": 3987,
"text": "from nltk.chunk.util import tree2conlltags,conlltags2treewtc=tree2conlltags(train_data[1])wtc"
},
{
"code": null,
"e": 4117,
"s": 4081,
"text": "tree=conlltags2tree(wtc)print(tree)"
},
{
"code": null,
"e": 4437,
"s": 4117,
"text": "def conll_tag_chunks(chunk_sents): tagged_sents = [tree2conlltags(tree) for tree in chunk_sents] return [[(t, c) for (w, t, c) in sent] for sent in tagged_sents]def combined_tagger(train_data, taggers, backoff=None): for tagger in taggers: backoff = tagger(train_data, backoff=backoff) return backoff"
},
{
"code": null,
"e": 4499,
"s": 4437,
"text": "It reads text and assigns a POS tag to each word. (word, tag)"
},
{
"code": null,
"e": 4603,
"s": 4499,
"text": "Unigram tagger: For determining the POS, It only uses a single word. (single word context-based tagger)"
},
{
"code": null,
"e": 4818,
"s": 4603,
"text": "The UnigramTagger, BigramTagger, and TrigramTagger are classes that inherit from the base class NGramTagger, which itself inherits from the ContextTagger class, which inherits from the SequentialBackoffTagger class"
},
{
"code": null,
"e": 5032,
"s": 4818,
"text": "We will now define a class NGramTagChunker that will take in tagged sentences as training input, get their (word, POS tag, chunk tag)WTC triples and train a BigramTagger with a UnigramTagger as the backoff tagger."
},
{
"code": null,
"e": 5117,
"s": 5032,
"text": "We will also define a parse() function to perform shallow parsing on a new sentence."
},
{
"code": null,
"e": 5966,
"s": 5117,
"text": "from nltk.tag import UnigramTagger, BigramTaggerfrom nltk.chunk import ChunkParserI#Define the chunker classclass NGramTagChunker(ChunkParserI): def __init__(self,train_sentences,tagger_classes=[UnigramTagger,BigramTagger]): train_sent_tags=conll_tag_chunks(train_sentences) self.chunk_tagger=combined_tagger(train_sent_tags,tagger_classes)def parse(self,tagged_sentence): if not tagged_sentence: return None pos_tags=[tag for word, tag in tagged_sentence] chunk_pos_tags=self.chunk_tagger.tag(pos_tags) chunk_tags=[chunk_tag for (pos_tag,chunk_tag) in chunk_pos_tags] wpc_tags=[(word,pos_tag,chunk_tag) for ((word,pos_tag),chunk_tag) in zip(tagged_sentence,chunk_tags)] return conlltags2tree(wpc_tags)#train chunker modelntc=NGramTagChunker(train_data)#evaluate chunker model performanceprint(ntc.evaluate(test_data))"
},
{
"code": null,
"e": 6057,
"s": 5966,
"text": "Now we’ll leverage this model to shallow parse and chunk our sample news article headline."
},
{
"code": null,
"e": 6256,
"s": 6057,
"text": "import pandas as pdsentence='No new emoji may be released in 2021 due to COVID-19 pandemic word'nltk_pos_tagged=nltk.pos_tag(sentence.split())pd.DataFrame(nltk_pos_tagged,columns=['word','POS tag'])"
},
{
"code": null,
"e": 6311,
"s": 6256,
"text": "chunk_tree=ntc.parse(nltk_pos_tagged)print(chunk_tree)"
},
{
"code": null,
"e": 6322,
"s": 6311,
"text": "chunk_tree"
},
{
"code": null,
"e": 6419,
"s": 6322,
"text": "You can also define classifier based chunker according to need. You can read more about it here."
},
{
"code": null,
"e": 6493,
"s": 6419,
"text": "https://www.geeksforgeeks.org/nlp-classifier-based-chunking-set-1/?ref=rp"
},
{
"code": null,
"e": 6635,
"s": 6493,
"text": "We create a sequence to tokens, which are not included in the chunk. So it’s finding insights or context. (I am not covering in this section)"
},
{
"code": null,
"e": 6659,
"s": 6635,
"text": "Thank you for reading.🙏"
},
{
"code": null,
"e": 6733,
"s": 6659,
"text": "I’ve tried to cover this topic in maximum depth. Suggestions are welcome."
},
{
"code": null,
"e": 6861,
"s": 6733,
"text": "As an honorable mention, I would like to thank Dipanjan (DJ) Sarkar.I’ve been following his tutorial to learn NLP from scratch."
}
] |
Getting Started with SAS : Beginner | by Malvika Mathur | Towards Data Science | SAS is a tool for analyzing statistical data. SAS is an acronym for statistical analytics software. The main purpose of SAS is to retrieve, report and analyze statistical data. Each statement in SAS environment ends with a semicolon otherwise the statement will give an error message. It is a powerful tool for running SQL queries and automating user’s task through macros.
Apart from this SAS offer descriptive visualization through graphs and there are various SAS versions provides reporting of machine learning, data mining, time series etc. SAS supports two types of statements included to run the program. Broadly speaking the statements in a SAS program categorized as : data steps and procedures.
In this article I have tried to explain data analysis using SAS. For the explanation I have created data car with variables price in dollars, length of the car, car’s repair ratings which is a categorical value, foreign value shows whether cars are foreign or domestic, weight and finally mpg (mileage of the car.
Data Step:
The data step consists of all the SAS statements starting with the line data and ending with the line datalines. It describe and modify your data. Within the data step you tell SAS how to read the data and generate or delete variables and observations. The data step transforms your raw data into a SAS dataset. Both cards and datalines statement interchangeably used by SAS. Import of data, reporting variables and descriptive analysis are the part of data step process. There are four statements that are commonly used in the DATA step.
DATA statement names the dataset
INPUT statement lists names of the variables
CARDS statement indicates that data lines immediately follow.
INFILE statement indicates that data is in a file and the name of the file.
data newdata;input name $ price mpg rep78 wgt len foreign;datalines;AMC 4099 22 3 2930 186 0AMC 4749 17 3 3350 173 0 AMC 3799 22 3 2640 168 0 Audi 9690 17 5 2830 189 1 Audi 6295 23 3 2070 174 1 BMW 9735 25 4 2650 177 1 Buick 4816 20 3 3250 196 0 Buick 4453 26 3 2230 170 0 Buick 5189 20 3 3280 200 0 Buick 10372 16 3 3880 207 0 Buick 4082 19 3 3400 200 0 Cad. 11385 14 3 4330 221 0 Cad. 14500 14 2 3900 204 0 Cad. 15906 21 3 4290 204 0 ; run;
Interpretations: In the above code we have created a new dataset newdata having variables name,price,mpg,rep78(repair rating) ,wgt , len and foreign. The dimension of Dataset newdata contain 14 records and 7 variables.
PROC Step:
The PROC steps tell SAS what analysis performed on the data, such as regression, analysis of variance, computation of means, etc. Every PROC statement starts with PROC keyword.
proc print data=newdata(obs=10);run;
The above statement will run and output the data in following way:
PROC import function in SAS is use to import dataset from the excel file. Apart from loading data to SAS environment, SAS also has built-in libraries where dataset stored for user help.
Temporary Data: The data only last until the current SAS session. This means files have short life also gets deleted when session ends.
Permanent Data: life long data stored by SAS, it cannot be deleted when session ends.
Missing value:
The missing value function represented by a period(.) identifies the number of missing records in the data. In our dataset there is no missing value.
PROC MEAN:
SAS has basic procedure to calculate the average/mean.
proc means data=newdata; run;
Interpretations: average price for the given cars data is $7790.71 where the minimum price is $3799 and the highest is $15906.
PROC FREQ:
SAS has a procedure called PROC FREQ to calculate the frequency distribution of data points in a data set. A frequency distribution is a table showing the frequency of the data points in a data set. Each entry in the table has the frequency or count of the occurrences of values within a particular group or interval, and in this way, distribution of values summarized using tables.
proc freq data=newdata;tables rep78; run;
Interpretations: The column Repair rating having rating of 3 frequently occurs in the data, It means that there is 78.5% chances of occurring than rest of the values.
PROC CORR:
The relationship between the two variables x and y can be calculated using CORR function in SAS. Correlation take value between -1 to +1 , a value of 1 shows very strong positive correlation while value of -1 show strong negative correlation.
Interpretations: In the below output length of car and weight shows a positive correlation 0.864 which means if the length of car increases then it’s weight likely to increase that is if we plot a graph between these two variables then we get a straight upward diagonal line where as it can be seen that value of -0.74 indicates negative relationship between len and mpg.
SAS tool has powerful graphics function that helps to analyze and report data.
Simple Bar Charts :
Bar chart is one of the most commonly used charts to represent the categorical data well. In this case, cars foreign represented by value 1 is comparatively more than the domestic value 0.
histogram:
Histogram explains the distribution of continuous values. The length values are slightly left skewed which means a long tail towards left which indicates length data is not normally distributed.
Scatter plot :
Relationship between two variables represented by scatter plot. Graph plotted between two continuous variables. Here, we can see a strong positive trend going upward which shows strong correlation between length and weight.
Box plot:
The following graph is a special case of Box plot in which we are displaying continuous variable by a categorical variable. If data set has outliers (extreme values), the box and whiskers chart may not only show the minimum or maximum value. Instead, the ends of the whiskers represents inter-quartile range (1.5*IQR) which is a good attribute to calculate outliers. The variable has a mean of 7790.71 and median is more towards the first quartile. Price variable has few extreme values which further treated before modeling.
Read:
Lesson 1: Getting Started in SAS | STAT 480 — Statistics Online
getting started with SAS.pdf | [
{
"code": null,
"e": 545,
"s": 171,
"text": "SAS is a tool for analyzing statistical data. SAS is an acronym for statistical analytics software. The main purpose of SAS is to retrieve, report and analyze statistical data. Each statement in SAS environment ends with a semicolon otherwise the statement will give an error message. It is a powerful tool for running SQL queries and automating user’s task through macros."
},
{
"code": null,
"e": 876,
"s": 545,
"text": "Apart from this SAS offer descriptive visualization through graphs and there are various SAS versions provides reporting of machine learning, data mining, time series etc. SAS supports two types of statements included to run the program. Broadly speaking the statements in a SAS program categorized as : data steps and procedures."
},
{
"code": null,
"e": 1190,
"s": 876,
"text": "In this article I have tried to explain data analysis using SAS. For the explanation I have created data car with variables price in dollars, length of the car, car’s repair ratings which is a categorical value, foreign value shows whether cars are foreign or domestic, weight and finally mpg (mileage of the car."
},
{
"code": null,
"e": 1201,
"s": 1190,
"text": "Data Step:"
},
{
"code": null,
"e": 1740,
"s": 1201,
"text": "The data step consists of all the SAS statements starting with the line data and ending with the line datalines. It describe and modify your data. Within the data step you tell SAS how to read the data and generate or delete variables and observations. The data step transforms your raw data into a SAS dataset. Both cards and datalines statement interchangeably used by SAS. Import of data, reporting variables and descriptive analysis are the part of data step process. There are four statements that are commonly used in the DATA step."
},
{
"code": null,
"e": 1773,
"s": 1740,
"text": "DATA statement names the dataset"
},
{
"code": null,
"e": 1818,
"s": 1773,
"text": "INPUT statement lists names of the variables"
},
{
"code": null,
"e": 1880,
"s": 1818,
"text": "CARDS statement indicates that data lines immediately follow."
},
{
"code": null,
"e": 1956,
"s": 1880,
"text": "INFILE statement indicates that data is in a file and the name of the file."
},
{
"code": null,
"e": 2576,
"s": 1956,
"text": "data newdata;input name $ price mpg rep78 wgt len foreign;datalines;AMC 4099 22 3 2930 186 0AMC 4749 17 3 3350 173 0 AMC 3799 22 3 2640 168 0 Audi 9690 17 5 2830 189 1 Audi 6295 23 3 2070 174 1 BMW 9735 25 4 2650 177 1 Buick 4816 20 3 3250 196 0 Buick 4453 26 3 2230 170 0 Buick 5189 20 3 3280 200 0 Buick 10372 16 3 3880 207 0 Buick 4082 19 3 3400 200 0 Cad. 11385 14 3 4330 221 0 Cad. 14500 14 2 3900 204 0 Cad. 15906 21 3 4290 204 0 ; run;"
},
{
"code": null,
"e": 2795,
"s": 2576,
"text": "Interpretations: In the above code we have created a new dataset newdata having variables name,price,mpg,rep78(repair rating) ,wgt , len and foreign. The dimension of Dataset newdata contain 14 records and 7 variables."
},
{
"code": null,
"e": 2806,
"s": 2795,
"text": "PROC Step:"
},
{
"code": null,
"e": 2983,
"s": 2806,
"text": "The PROC steps tell SAS what analysis performed on the data, such as regression, analysis of variance, computation of means, etc. Every PROC statement starts with PROC keyword."
},
{
"code": null,
"e": 3020,
"s": 2983,
"text": "proc print data=newdata(obs=10);run;"
},
{
"code": null,
"e": 3087,
"s": 3020,
"text": "The above statement will run and output the data in following way:"
},
{
"code": null,
"e": 3273,
"s": 3087,
"text": "PROC import function in SAS is use to import dataset from the excel file. Apart from loading data to SAS environment, SAS also has built-in libraries where dataset stored for user help."
},
{
"code": null,
"e": 3409,
"s": 3273,
"text": "Temporary Data: The data only last until the current SAS session. This means files have short life also gets deleted when session ends."
},
{
"code": null,
"e": 3495,
"s": 3409,
"text": "Permanent Data: life long data stored by SAS, it cannot be deleted when session ends."
},
{
"code": null,
"e": 3510,
"s": 3495,
"text": "Missing value:"
},
{
"code": null,
"e": 3660,
"s": 3510,
"text": "The missing value function represented by a period(.) identifies the number of missing records in the data. In our dataset there is no missing value."
},
{
"code": null,
"e": 3671,
"s": 3660,
"text": "PROC MEAN:"
},
{
"code": null,
"e": 3726,
"s": 3671,
"text": "SAS has basic procedure to calculate the average/mean."
},
{
"code": null,
"e": 3773,
"s": 3726,
"text": "proc means data=newdata; run;"
},
{
"code": null,
"e": 3900,
"s": 3773,
"text": "Interpretations: average price for the given cars data is $7790.71 where the minimum price is $3799 and the highest is $15906."
},
{
"code": null,
"e": 3911,
"s": 3900,
"text": "PROC FREQ:"
},
{
"code": null,
"e": 4294,
"s": 3911,
"text": "SAS has a procedure called PROC FREQ to calculate the frequency distribution of data points in a data set. A frequency distribution is a table showing the frequency of the data points in a data set. Each entry in the table has the frequency or count of the occurrences of values within a particular group or interval, and in this way, distribution of values summarized using tables."
},
{
"code": null,
"e": 4336,
"s": 4294,
"text": "proc freq data=newdata;tables rep78; run;"
},
{
"code": null,
"e": 4503,
"s": 4336,
"text": "Interpretations: The column Repair rating having rating of 3 frequently occurs in the data, It means that there is 78.5% chances of occurring than rest of the values."
},
{
"code": null,
"e": 4514,
"s": 4503,
"text": "PROC CORR:"
},
{
"code": null,
"e": 4757,
"s": 4514,
"text": "The relationship between the two variables x and y can be calculated using CORR function in SAS. Correlation take value between -1 to +1 , a value of 1 shows very strong positive correlation while value of -1 show strong negative correlation."
},
{
"code": null,
"e": 5129,
"s": 4757,
"text": "Interpretations: In the below output length of car and weight shows a positive correlation 0.864 which means if the length of car increases then it’s weight likely to increase that is if we plot a graph between these two variables then we get a straight upward diagonal line where as it can be seen that value of -0.74 indicates negative relationship between len and mpg."
},
{
"code": null,
"e": 5208,
"s": 5129,
"text": "SAS tool has powerful graphics function that helps to analyze and report data."
},
{
"code": null,
"e": 5228,
"s": 5208,
"text": "Simple Bar Charts :"
},
{
"code": null,
"e": 5417,
"s": 5228,
"text": "Bar chart is one of the most commonly used charts to represent the categorical data well. In this case, cars foreign represented by value 1 is comparatively more than the domestic value 0."
},
{
"code": null,
"e": 5428,
"s": 5417,
"text": "histogram:"
},
{
"code": null,
"e": 5623,
"s": 5428,
"text": "Histogram explains the distribution of continuous values. The length values are slightly left skewed which means a long tail towards left which indicates length data is not normally distributed."
},
{
"code": null,
"e": 5638,
"s": 5623,
"text": "Scatter plot :"
},
{
"code": null,
"e": 5862,
"s": 5638,
"text": "Relationship between two variables represented by scatter plot. Graph plotted between two continuous variables. Here, we can see a strong positive trend going upward which shows strong correlation between length and weight."
},
{
"code": null,
"e": 5872,
"s": 5862,
"text": "Box plot:"
},
{
"code": null,
"e": 6398,
"s": 5872,
"text": "The following graph is a special case of Box plot in which we are displaying continuous variable by a categorical variable. If data set has outliers (extreme values), the box and whiskers chart may not only show the minimum or maximum value. Instead, the ends of the whiskers represents inter-quartile range (1.5*IQR) which is a good attribute to calculate outliers. The variable has a mean of 7790.71 and median is more towards the first quartile. Price variable has few extreme values which further treated before modeling."
},
{
"code": null,
"e": 6404,
"s": 6398,
"text": "Read:"
},
{
"code": null,
"e": 6468,
"s": 6404,
"text": "Lesson 1: Getting Started in SAS | STAT 480 — Statistics Online"
}
] |
Java Program to get the day of the week from GregorianCalendar | For GregorianCalendar class, import the following package.
import java.util.GregorianCalendar;
Create an object.
GregorianCalendar calendar = new GregorianCalendar();
To get the day of the week, use the following field.
GregorianCalendar.DAY_OF_WEEK
The following is an example.
Live Demo
import java.util.Calendar;
import java.util.GregorianCalendar;
public class Demo {
public static void main(String[] a) {
GregorianCalendar calendar = new GregorianCalendar();
System.out.println("Day of Week = " + calendar.get(GregorianCalendar.DAY_OF_WEEK));
System.out.println("Date = " + calendar.get(GregorianCalendar.DATE));
System.out.println("Month = " + calendar.get(GregorianCalendar.MONTH));
System.out.println("Year = " + calendar.get(GregorianCalendar.YEAR));
}
}
Day of Week = 2
Date = 19
Month = 10
Year = 2018 | [
{
"code": null,
"e": 1121,
"s": 1062,
"text": "For GregorianCalendar class, import the following package."
},
{
"code": null,
"e": 1157,
"s": 1121,
"text": "import java.util.GregorianCalendar;"
},
{
"code": null,
"e": 1175,
"s": 1157,
"text": "Create an object."
},
{
"code": null,
"e": 1229,
"s": 1175,
"text": "GregorianCalendar calendar = new GregorianCalendar();"
},
{
"code": null,
"e": 1282,
"s": 1229,
"text": "To get the day of the week, use the following field."
},
{
"code": null,
"e": 1312,
"s": 1282,
"text": "GregorianCalendar.DAY_OF_WEEK"
},
{
"code": null,
"e": 1341,
"s": 1312,
"text": "The following is an example."
},
{
"code": null,
"e": 1352,
"s": 1341,
"text": " Live Demo"
},
{
"code": null,
"e": 1863,
"s": 1352,
"text": "import java.util.Calendar;\nimport java.util.GregorianCalendar;\npublic class Demo {\n public static void main(String[] a) {\n GregorianCalendar calendar = new GregorianCalendar();\n System.out.println(\"Day of Week = \" + calendar.get(GregorianCalendar.DAY_OF_WEEK));\n System.out.println(\"Date = \" + calendar.get(GregorianCalendar.DATE));\n System.out.println(\"Month = \" + calendar.get(GregorianCalendar.MONTH));\n System.out.println(\"Year = \" + calendar.get(GregorianCalendar.YEAR));\n }\n}"
},
{
"code": null,
"e": 1912,
"s": 1863,
"text": "Day of Week = 2\nDate = 19\nMonth = 10\nYear = 2018"
}
] |
Predefined Macros in C with Examples - GeeksforGeeks | 21 Dec, 2021
According to C89 Standard, C programming language has following predefined macros:
__LINE__ Macro: __LINE__ macro contains the current line number of the program in the compilation. It gives the line number where it is called. It is used in generating log statements, error messages, throwing exceptions and debugging codes. Whenever the compiler finds an error in compilation it first generates the line number at which error occurred using __LINE__ and prints error message along with line number so that user can easily fix that error easily.CC#include <stdio.h>int main(){ printf("Line number is: %d\n", __LINE__); return 0;}Output:Line number is: 5
__FILE__ Macro: __FILE__ macro holds the file name of the currently executing program in the computer. It is also used in debugging, generating error reports and log messages.CC#include <stdio.h>int main(){ printf("File name of this" " program is: %s\n", __FILE__); return 0;}Output:File name of this program is: /usr/share/IDE_PROGRAMS/C/other/703ad0b087fbd7d18cde5ea81f148f36/703ad0b087fbd7d18cde5ea81f148f36.c__DATE__ Macro: __DATE__ macro gives the date at which source code of this program is converted into object code. Simply put, it returns the date at which the program was compiled. Date is in the format mmm dd yyyy. mmm is the abbreviated month name.CC#include <stdio.h>int main(){ printf("Program Compilation Date: %s\n", __DATE__); return 0;}Output:Program Compilation Date: Dec 26 2019
__TIME__ Macro: __DATE__ macro gives the time at which program was compiled. Time is in the format hour:minute:second.CC#include <stdio.h>int main(){ printf("Time of compilation is: %s\n", __TIME__); return 0;}Output:Time of compilation is: 13:17:20
__STDC__ Macro: __STDC__ Macro is used to confirm the compiler standard. Generally it holds the value 1 which means that the compiler conforms to ISO Standard C.CC#include <stdio.h>int main(){ printf("Compiler Standard Number: %d\n", __STDC__); return 0;}Output:Compiler Standard Number: 1
__STDC__HOSTED Macro: This macro holds the value 1 if the compiler’s target is a hosted environment. A hosted environment is a facility in which a third-party holds the compilation data and runs the programs on its own computers. Generally, the value is set to 1.CC#include <stdio.h>int main(){ printf("STDC_HOSTDED Number: %d\n", __STDC_HOSTED__); return 0;}Output:STDC_HOSTDED Number: 1
__STDC_VERSION__: This macro holds the C Standard’s version number in the form yyyymmL where yyyy and mm are the year and month of the Standard version. This signifies which version of the C Standard the compiler conforms to.Values hold by __STDC_VERSION__The value 199409L signifies the C89 standard amended in 1994. This is the current default standard.The value 199901L signifies the C99 standardThe value 201112L signifies the 2011 revision of the C standardThese standard values are changed when the user is required to use the function or header file in C89 standard which is removed in C99 standard. The compiler changes its standard of execution and runs the output.Check out this article which changes the standard to run asctime_s() function declared in the C89 standard.CC#include <stdio.h>int main(){ printf("Compiler Standard " "VERSION Number: %ld\n", __STDC_VERSION__); return 0;}Output:Compiler Standard VERSION Number: 201112
Predefined Macros in C99 standard:__cplusplus: __cplusplus Macro is defined when the C++ compiler is used. It is used to test whether a header is compiled by a C compiler or a C++ compiler. This macro gives value similar to __STDC_VERSION__, in that it expands to a version number.Values hold by __cplusplus199711L for the 1998 C++ standard201103L for the 2011 C++ standard201402L for the 2014 C++ standard201703L for the 2017 C++ standard__OBJC__ Macro:: __OBJC__ Macro has value 1 if the Objective-C compiler is in use. __OBJC__ is used to test whether a header is compiled by a C compiler or an Objective-C compiler.
__LINE__ Macro: __LINE__ macro contains the current line number of the program in the compilation. It gives the line number where it is called. It is used in generating log statements, error messages, throwing exceptions and debugging codes. Whenever the compiler finds an error in compilation it first generates the line number at which error occurred using __LINE__ and prints error message along with line number so that user can easily fix that error easily.CC#include <stdio.h>int main(){ printf("Line number is: %d\n", __LINE__); return 0;}Output:Line number is: 5
C
#include <stdio.h>int main(){ printf("Line number is: %d\n", __LINE__); return 0;}
Line number is: 5
__FILE__ Macro: __FILE__ macro holds the file name of the currently executing program in the computer. It is also used in debugging, generating error reports and log messages.CC#include <stdio.h>int main(){ printf("File name of this" " program is: %s\n", __FILE__); return 0;}Output:File name of this program is: /usr/share/IDE_PROGRAMS/C/other/703ad0b087fbd7d18cde5ea81f148f36/703ad0b087fbd7d18cde5ea81f148f36.c
C
#include <stdio.h>int main(){ printf("File name of this" " program is: %s\n", __FILE__); return 0;}
File name of this program is: /usr/share/IDE_PROGRAMS/C/other/703ad0b087fbd7d18cde5ea81f148f36/703ad0b087fbd7d18cde5ea81f148f36.c
__DATE__ Macro: __DATE__ macro gives the date at which source code of this program is converted into object code. Simply put, it returns the date at which the program was compiled. Date is in the format mmm dd yyyy. mmm is the abbreviated month name.CC#include <stdio.h>int main(){ printf("Program Compilation Date: %s\n", __DATE__); return 0;}Output:Program Compilation Date: Dec 26 2019
C
#include <stdio.h>int main(){ printf("Program Compilation Date: %s\n", __DATE__); return 0;}
Program Compilation Date: Dec 26 2019
__TIME__ Macro: __DATE__ macro gives the time at which program was compiled. Time is in the format hour:minute:second.CC#include <stdio.h>int main(){ printf("Time of compilation is: %s\n", __TIME__); return 0;}Output:Time of compilation is: 13:17:20
C
#include <stdio.h>int main(){ printf("Time of compilation is: %s\n", __TIME__); return 0;}
Time of compilation is: 13:17:20
__STDC__ Macro: __STDC__ Macro is used to confirm the compiler standard. Generally it holds the value 1 which means that the compiler conforms to ISO Standard C.CC#include <stdio.h>int main(){ printf("Compiler Standard Number: %d\n", __STDC__); return 0;}Output:Compiler Standard Number: 1
C
#include <stdio.h>int main(){ printf("Compiler Standard Number: %d\n", __STDC__); return 0;}
Compiler Standard Number: 1
__STDC__HOSTED Macro: This macro holds the value 1 if the compiler’s target is a hosted environment. A hosted environment is a facility in which a third-party holds the compilation data and runs the programs on its own computers. Generally, the value is set to 1.CC#include <stdio.h>int main(){ printf("STDC_HOSTDED Number: %d\n", __STDC_HOSTED__); return 0;}Output:STDC_HOSTDED Number: 1
C
#include <stdio.h>int main(){ printf("STDC_HOSTDED Number: %d\n", __STDC_HOSTED__); return 0;}
STDC_HOSTDED Number: 1
__STDC_VERSION__: This macro holds the C Standard’s version number in the form yyyymmL where yyyy and mm are the year and month of the Standard version. This signifies which version of the C Standard the compiler conforms to.Values hold by __STDC_VERSION__The value 199409L signifies the C89 standard amended in 1994. This is the current default standard.The value 199901L signifies the C99 standardThe value 201112L signifies the 2011 revision of the C standardThese standard values are changed when the user is required to use the function or header file in C89 standard which is removed in C99 standard. The compiler changes its standard of execution and runs the output.Check out this article which changes the standard to run asctime_s() function declared in the C89 standard.CC#include <stdio.h>int main(){ printf("Compiler Standard " "VERSION Number: %ld\n", __STDC_VERSION__); return 0;}Output:Compiler Standard VERSION Number: 201112
Predefined Macros in C99 standard:
Values hold by __STDC_VERSION__
The value 199409L signifies the C89 standard amended in 1994. This is the current default standard.
The value 199901L signifies the C99 standard
The value 201112L signifies the 2011 revision of the C standard
These standard values are changed when the user is required to use the function or header file in C89 standard which is removed in C99 standard. The compiler changes its standard of execution and runs the output.
Check out this article which changes the standard to run asctime_s() function declared in the C89 standard.
C
#include <stdio.h>int main(){ printf("Compiler Standard " "VERSION Number: %ld\n", __STDC_VERSION__); return 0;}
Compiler Standard VERSION Number: 201112
__cplusplus: __cplusplus Macro is defined when the C++ compiler is used. It is used to test whether a header is compiled by a C compiler or a C++ compiler. This macro gives value similar to __STDC_VERSION__, in that it expands to a version number.Values hold by __cplusplus199711L for the 1998 C++ standard201103L for the 2011 C++ standard201402L for the 2014 C++ standard201703L for the 2017 C++ standard
Values hold by __cplusplus
199711L for the 1998 C++ standard
201103L for the 2011 C++ standard
201402L for the 2014 C++ standard
201703L for the 2017 C++ standard
__OBJC__ Macro:: __OBJC__ Macro has value 1 if the Objective-C compiler is in use. __OBJC__ is used to test whether a header is compiled by a C compiler or an Objective-C compiler.
References: https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html
surinderdawra388
gulshankumarar231
C Macro
C Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
'this' pointer in C++
Multithreading in C
Exception Handling in C++
Arrow operator -> in C/C++ with Examples
UDP Server-Client implementation in C
Ways to copy a vector in C++
Understanding "extern" keyword in C
Use of bool in C
Smart Pointers in C++ and How to Use Them | [
{
"code": null,
"e": 24232,
"s": 24204,
"text": "\n21 Dec, 2021"
},
{
"code": null,
"e": 24315,
"s": 24232,
"text": "According to C89 Standard, C programming language has following predefined macros:"
},
{
"code": null,
"e": 28311,
"s": 24315,
"text": "__LINE__ Macro: __LINE__ macro contains the current line number of the program in the compilation. It gives the line number where it is called. It is used in generating log statements, error messages, throwing exceptions and debugging codes. Whenever the compiler finds an error in compilation it first generates the line number at which error occurred using __LINE__ and prints error message along with line number so that user can easily fix that error easily.CC#include <stdio.h>int main(){ printf(\"Line number is: %d\\n\", __LINE__); return 0;}Output:Line number is: 5\n__FILE__ Macro: __FILE__ macro holds the file name of the currently executing program in the computer. It is also used in debugging, generating error reports and log messages.CC#include <stdio.h>int main(){ printf(\"File name of this\" \" program is: %s\\n\", __FILE__); return 0;}Output:File name of this program is: /usr/share/IDE_PROGRAMS/C/other/703ad0b087fbd7d18cde5ea81f148f36/703ad0b087fbd7d18cde5ea81f148f36.c__DATE__ Macro: __DATE__ macro gives the date at which source code of this program is converted into object code. Simply put, it returns the date at which the program was compiled. Date is in the format mmm dd yyyy. mmm is the abbreviated month name.CC#include <stdio.h>int main(){ printf(\"Program Compilation Date: %s\\n\", __DATE__); return 0;}Output:Program Compilation Date: Dec 26 2019\n__TIME__ Macro: __DATE__ macro gives the time at which program was compiled. Time is in the format hour:minute:second.CC#include <stdio.h>int main(){ printf(\"Time of compilation is: %s\\n\", __TIME__); return 0;}Output:Time of compilation is: 13:17:20\n__STDC__ Macro: __STDC__ Macro is used to confirm the compiler standard. Generally it holds the value 1 which means that the compiler conforms to ISO Standard C.CC#include <stdio.h>int main(){ printf(\"Compiler Standard Number: %d\\n\", __STDC__); return 0;}Output:Compiler Standard Number: 1\n__STDC__HOSTED Macro: This macro holds the value 1 if the compiler’s target is a hosted environment. A hosted environment is a facility in which a third-party holds the compilation data and runs the programs on its own computers. Generally, the value is set to 1.CC#include <stdio.h>int main(){ printf(\"STDC_HOSTDED Number: %d\\n\", __STDC_HOSTED__); return 0;}Output:STDC_HOSTDED Number: 1\n__STDC_VERSION__: This macro holds the C Standard’s version number in the form yyyymmL where yyyy and mm are the year and month of the Standard version. This signifies which version of the C Standard the compiler conforms to.Values hold by __STDC_VERSION__The value 199409L signifies the C89 standard amended in 1994. This is the current default standard.The value 199901L signifies the C99 standardThe value 201112L signifies the 2011 revision of the C standardThese standard values are changed when the user is required to use the function or header file in C89 standard which is removed in C99 standard. The compiler changes its standard of execution and runs the output.Check out this article which changes the standard to run asctime_s() function declared in the C89 standard.CC#include <stdio.h>int main(){ printf(\"Compiler Standard \" \"VERSION Number: %ld\\n\", __STDC_VERSION__); return 0;}Output:Compiler Standard VERSION Number: 201112\nPredefined Macros in C99 standard:__cplusplus: __cplusplus Macro is defined when the C++ compiler is used. It is used to test whether a header is compiled by a C compiler or a C++ compiler. This macro gives value similar to __STDC_VERSION__, in that it expands to a version number.Values hold by __cplusplus199711L for the 1998 C++ standard201103L for the 2011 C++ standard201402L for the 2014 C++ standard201703L for the 2017 C++ standard__OBJC__ Macro:: __OBJC__ Macro has value 1 if the Objective-C compiler is in use. __OBJC__ is used to test whether a header is compiled by a C compiler or an Objective-C compiler."
},
{
"code": null,
"e": 28899,
"s": 28311,
"text": "__LINE__ Macro: __LINE__ macro contains the current line number of the program in the compilation. It gives the line number where it is called. It is used in generating log statements, error messages, throwing exceptions and debugging codes. Whenever the compiler finds an error in compilation it first generates the line number at which error occurred using __LINE__ and prints error message along with line number so that user can easily fix that error easily.CC#include <stdio.h>int main(){ printf(\"Line number is: %d\\n\", __LINE__); return 0;}Output:Line number is: 5\n"
},
{
"code": null,
"e": 28901,
"s": 28899,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ printf(\"Line number is: %d\\n\", __LINE__); return 0;}",
"e": 29000,
"s": 28901,
"text": null
},
{
"code": null,
"e": 29019,
"s": 29000,
"text": "Line number is: 5\n"
},
{
"code": null,
"e": 29458,
"s": 29019,
"text": "__FILE__ Macro: __FILE__ macro holds the file name of the currently executing program in the computer. It is also used in debugging, generating error reports and log messages.CC#include <stdio.h>int main(){ printf(\"File name of this\" \" program is: %s\\n\", __FILE__); return 0;}Output:File name of this program is: /usr/share/IDE_PROGRAMS/C/other/703ad0b087fbd7d18cde5ea81f148f36/703ad0b087fbd7d18cde5ea81f148f36.c"
},
{
"code": null,
"e": 29460,
"s": 29458,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ printf(\"File name of this\" \" program is: %s\\n\", __FILE__); return 0;}",
"e": 29586,
"s": 29460,
"text": null
},
{
"code": null,
"e": 29716,
"s": 29586,
"text": "File name of this program is: /usr/share/IDE_PROGRAMS/C/other/703ad0b087fbd7d18cde5ea81f148f36/703ad0b087fbd7d18cde5ea81f148f36.c"
},
{
"code": null,
"e": 30122,
"s": 29716,
"text": "__DATE__ Macro: __DATE__ macro gives the date at which source code of this program is converted into object code. Simply put, it returns the date at which the program was compiled. Date is in the format mmm dd yyyy. mmm is the abbreviated month name.CC#include <stdio.h>int main(){ printf(\"Program Compilation Date: %s\\n\", __DATE__); return 0;}Output:Program Compilation Date: Dec 26 2019\n"
},
{
"code": null,
"e": 30124,
"s": 30122,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ printf(\"Program Compilation Date: %s\\n\", __DATE__); return 0;}",
"e": 30233,
"s": 30124,
"text": null
},
{
"code": null,
"e": 30272,
"s": 30233,
"text": "Program Compilation Date: Dec 26 2019\n"
},
{
"code": null,
"e": 30539,
"s": 30272,
"text": "__TIME__ Macro: __DATE__ macro gives the time at which program was compiled. Time is in the format hour:minute:second.CC#include <stdio.h>int main(){ printf(\"Time of compilation is: %s\\n\", __TIME__); return 0;}Output:Time of compilation is: 13:17:20\n"
},
{
"code": null,
"e": 30541,
"s": 30539,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ printf(\"Time of compilation is: %s\\n\", __TIME__); return 0;}",
"e": 30648,
"s": 30541,
"text": null
},
{
"code": null,
"e": 30682,
"s": 30648,
"text": "Time of compilation is: 13:17:20\n"
},
{
"code": null,
"e": 30989,
"s": 30682,
"text": "__STDC__ Macro: __STDC__ Macro is used to confirm the compiler standard. Generally it holds the value 1 which means that the compiler conforms to ISO Standard C.CC#include <stdio.h>int main(){ printf(\"Compiler Standard Number: %d\\n\", __STDC__); return 0;}Output:Compiler Standard Number: 1\n"
},
{
"code": null,
"e": 30991,
"s": 30989,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ printf(\"Compiler Standard Number: %d\\n\", __STDC__); return 0;}",
"e": 31100,
"s": 30991,
"text": null
},
{
"code": null,
"e": 31129,
"s": 31100,
"text": "Compiler Standard Number: 1\n"
},
{
"code": null,
"e": 31535,
"s": 31129,
"text": "__STDC__HOSTED Macro: This macro holds the value 1 if the compiler’s target is a hosted environment. A hosted environment is a facility in which a third-party holds the compilation data and runs the programs on its own computers. Generally, the value is set to 1.CC#include <stdio.h>int main(){ printf(\"STDC_HOSTDED Number: %d\\n\", __STDC_HOSTED__); return 0;}Output:STDC_HOSTDED Number: 1\n"
},
{
"code": null,
"e": 31537,
"s": 31535,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ printf(\"STDC_HOSTDED Number: %d\\n\", __STDC_HOSTED__); return 0;}",
"e": 31648,
"s": 31537,
"text": null
},
{
"code": null,
"e": 31672,
"s": 31648,
"text": "STDC_HOSTDED Number: 1\n"
},
{
"code": null,
"e": 32676,
"s": 31672,
"text": "__STDC_VERSION__: This macro holds the C Standard’s version number in the form yyyymmL where yyyy and mm are the year and month of the Standard version. This signifies which version of the C Standard the compiler conforms to.Values hold by __STDC_VERSION__The value 199409L signifies the C89 standard amended in 1994. This is the current default standard.The value 199901L signifies the C99 standardThe value 201112L signifies the 2011 revision of the C standardThese standard values are changed when the user is required to use the function or header file in C89 standard which is removed in C99 standard. The compiler changes its standard of execution and runs the output.Check out this article which changes the standard to run asctime_s() function declared in the C89 standard.CC#include <stdio.h>int main(){ printf(\"Compiler Standard \" \"VERSION Number: %ld\\n\", __STDC_VERSION__); return 0;}Output:Compiler Standard VERSION Number: 201112\nPredefined Macros in C99 standard:"
},
{
"code": null,
"e": 32708,
"s": 32676,
"text": "Values hold by __STDC_VERSION__"
},
{
"code": null,
"e": 32808,
"s": 32708,
"text": "The value 199409L signifies the C89 standard amended in 1994. This is the current default standard."
},
{
"code": null,
"e": 32853,
"s": 32808,
"text": "The value 199901L signifies the C99 standard"
},
{
"code": null,
"e": 32917,
"s": 32853,
"text": "The value 201112L signifies the 2011 revision of the C standard"
},
{
"code": null,
"e": 33130,
"s": 32917,
"text": "These standard values are changed when the user is required to use the function or header file in C89 standard which is removed in C99 standard. The compiler changes its standard of execution and runs the output."
},
{
"code": null,
"e": 33238,
"s": 33130,
"text": "Check out this article which changes the standard to run asctime_s() function declared in the C89 standard."
},
{
"code": null,
"e": 33240,
"s": 33238,
"text": "C"
},
{
"code": "#include <stdio.h>int main(){ printf(\"Compiler Standard \" \"VERSION Number: %ld\\n\", __STDC_VERSION__); return 0;}",
"e": 33379,
"s": 33240,
"text": null
},
{
"code": null,
"e": 33421,
"s": 33379,
"text": "Compiler Standard VERSION Number: 201112\n"
},
{
"code": null,
"e": 33827,
"s": 33421,
"text": "__cplusplus: __cplusplus Macro is defined when the C++ compiler is used. It is used to test whether a header is compiled by a C compiler or a C++ compiler. This macro gives value similar to __STDC_VERSION__, in that it expands to a version number.Values hold by __cplusplus199711L for the 1998 C++ standard201103L for the 2011 C++ standard201402L for the 2014 C++ standard201703L for the 2017 C++ standard"
},
{
"code": null,
"e": 33854,
"s": 33827,
"text": "Values hold by __cplusplus"
},
{
"code": null,
"e": 33888,
"s": 33854,
"text": "199711L for the 1998 C++ standard"
},
{
"code": null,
"e": 33922,
"s": 33888,
"text": "201103L for the 2011 C++ standard"
},
{
"code": null,
"e": 33956,
"s": 33922,
"text": "201402L for the 2014 C++ standard"
},
{
"code": null,
"e": 33990,
"s": 33956,
"text": "201703L for the 2017 C++ standard"
},
{
"code": null,
"e": 34171,
"s": 33990,
"text": "__OBJC__ Macro:: __OBJC__ Macro has value 1 if the Objective-C compiler is in use. __OBJC__ is used to test whether a header is compiled by a C compiler or an Objective-C compiler."
},
{
"code": null,
"e": 34250,
"s": 34171,
"text": "References: https://gcc.gnu.org/onlinedocs/cpp/Standard-Predefined-Macros.html"
},
{
"code": null,
"e": 34267,
"s": 34250,
"text": "surinderdawra388"
},
{
"code": null,
"e": 34285,
"s": 34267,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 34293,
"s": 34285,
"text": "C Macro"
},
{
"code": null,
"e": 34304,
"s": 34293,
"text": "C Language"
},
{
"code": null,
"e": 34402,
"s": 34304,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 34411,
"s": 34402,
"text": "Comments"
},
{
"code": null,
"e": 34424,
"s": 34411,
"text": "Old Comments"
},
{
"code": null,
"e": 34462,
"s": 34424,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 34484,
"s": 34462,
"text": "'this' pointer in C++"
},
{
"code": null,
"e": 34504,
"s": 34484,
"text": "Multithreading in C"
},
{
"code": null,
"e": 34530,
"s": 34504,
"text": "Exception Handling in C++"
},
{
"code": null,
"e": 34571,
"s": 34530,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 34609,
"s": 34571,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 34638,
"s": 34609,
"text": "Ways to copy a vector in C++"
},
{
"code": null,
"e": 34674,
"s": 34638,
"text": "Understanding \"extern\" keyword in C"
},
{
"code": null,
"e": 34691,
"s": 34674,
"text": "Use of bool in C"
}
] |
Detect the ENTER key in a text input field with JavaScript | You can use the keyCode 13 for ENTER key. Let’s first create the input −
<input type="text" id="txtInput">
Now, let’s use the on() with keyCode to detect the ENTER key. Following is the complete code −
Live Demo
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initialscale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<input type="text" id="txtInput">
<script>
$("#txtInput").on('keyup', function (event) {
if (event.keyCode === 13) {
console.log("Enter key pressed!!!!!");
}
});
</script>
</body>
</html>
To run the above program, save the file name “anyName.html(index.html)” and right click on the
file. Select the option “Open with Live Server” in VS Code editor.
This will produce the following output −
When you press an ENTER key, you will get the following message as in the below console output − | [
{
"code": null,
"e": 1135,
"s": 1062,
"text": "You can use the keyCode 13 for ENTER key. Let’s first create the input −"
},
{
"code": null,
"e": 1169,
"s": 1135,
"text": "<input type=\"text\" id=\"txtInput\">"
},
{
"code": null,
"e": 1264,
"s": 1169,
"text": "Now, let’s use the on() with keyCode to detect the ENTER key. Following is the complete code −"
},
{
"code": null,
"e": 1275,
"s": 1264,
"text": " Live Demo"
},
{
"code": null,
"e": 1883,
"s": 1275,
"text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\">\n<meta name=\"viewport\" content=\"width=device-width, initialscale=1.0\">\n<title>Document</title>\n<link rel=\"stylesheet\" href=\"//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css\">\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n</head>\n<body>\n<input type=\"text\" id=\"txtInput\">\n<script>\n $(\"#txtInput\").on('keyup', function (event) {\n if (event.keyCode === 13) {\n console.log(\"Enter key pressed!!!!!\");\n }\n });\n</script>\n</body>\n</html>"
},
{
"code": null,
"e": 2045,
"s": 1883,
"text": "To run the above program, save the file name “anyName.html(index.html)” and right click on the\nfile. Select the option “Open with Live Server” in VS Code editor."
},
{
"code": null,
"e": 2086,
"s": 2045,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2183,
"s": 2086,
"text": "When you press an ENTER key, you will get the following message as in the below console output −"
}
] |
How to Install Numpy on Windows? - GeeksforGeeks | 09 Sep, 2021
Python NumPy is a general-purpose array processing package that provides tools for handling n-dimensional arrays. It provides various computing tools such as comprehensive mathematical functions, linear algebra routines. NumPy provides both the flexibility of Python and the speed of well-optimized compiled C code. Its easy-to-use syntax makes it highly accessible and productive for programmers from any background.
The only thing that you need for installing Numpy on Windows are:
Python
PIP or Conda (depending upon user preference)
If you want the installation to be done through conda, you can use the below command:
conda install -c anaconda numpy
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
Users who prefer to use pip can use the below command to install NumPy:
pip install numpy
You will get a similar message once the installation is complete:
Now that we have installed Numpy successfully in our system, let’s take a look at few simple examples.
Example 1: Basic Numpy Array characters
Python3
# Python program to demonstrate# basic array characteristicsimport numpy as np # Creating array objectarr = np.array( [[ 1, 2, 3], [ 4, 2, 5]] ) # Printing type of arr objectprint("Array is of type: ", type(arr)) # Printing array dimensions (axes)print("No. of dimensions: ", arr.ndim) # Printing shape of arrayprint("Shape of array: ", arr.shape) # Printing size (total number of elements) of arrayprint("Size of array: ", arr.size) # Printing type of elements in arrayprint("Array stores elements of type: ", arr.dtype)
Output:
Array is of type:
No. of dimensions: 2
Shape of array: (2, 3)
Size of array: 6
Array stores elements of type: int64
Example 2: Basic Numpy operations
Python3
# Python program to demonstrate# basic operations on single arrayimport numpy as np a = np.array([1, 2, 5, 3]) # add 1 to every elementprint ("Adding 1 to every element:", a+1) # subtract 3 from each elementprint ("Subtracting 3 from each element:", a-3) # multiply each element by 10print ("Multiplying each element by 10:", a*10) # square each elementprint ("Squaring each element:", a**2) # modify existing arraya *= 2print ("Doubled each element of original array:", a) # transpose of arraya = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]]) print ("\nOriginal array:\n", a)print ("Transpose of array:\n", a.T)
Output:
Adding 1 to every element: [2 3 6 4]
Subtracting 3 from each element: [-2 -1 2 0]
Multiplying each element by 10: [10 20 50 30]
Squaring each element: [ 1 4 25 9]
Doubled each element of original array: [ 2 4 10 6]
Original array:
[[1 2 3]
[3 4 5]
[9 6 0]]
Transpose of array:
[[1 3 9]
[2 4 6]
[3 5 0]]
Blogathon-2021
how-to-install
Picked
Python-numpy
Blogathon
How To
Installation Guide
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create a Table With Multiple Foreign Keys in SQL?
How to Import JSON Data into SQL Server?
Stratified Sampling in Pandas
SQL Query to Convert Datetime to Date
How to pass data into table from a form using React Components
How to Install PIP on Windows ?
How to Find the Wi-Fi Password Using CMD in Windows?
How to install Jupyter Notebook on Windows?
How to Align Text in HTML?
How to filter object array based on attributes? | [
{
"code": null,
"e": 26097,
"s": 26069,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 26515,
"s": 26097,
"text": "Python NumPy is a general-purpose array processing package that provides tools for handling n-dimensional arrays. It provides various computing tools such as comprehensive mathematical functions, linear algebra routines. NumPy provides both the flexibility of Python and the speed of well-optimized compiled C code. Its easy-to-use syntax makes it highly accessible and productive for programmers from any background."
},
{
"code": null,
"e": 26581,
"s": 26515,
"text": "The only thing that you need for installing Numpy on Windows are:"
},
{
"code": null,
"e": 26589,
"s": 26581,
"text": "Python "
},
{
"code": null,
"e": 26635,
"s": 26589,
"text": "PIP or Conda (depending upon user preference)"
},
{
"code": null,
"e": 26721,
"s": 26635,
"text": "If you want the installation to be done through conda, you can use the below command:"
},
{
"code": null,
"e": 26753,
"s": 26721,
"text": "conda install -c anaconda numpy"
},
{
"code": null,
"e": 26818,
"s": 26753,
"text": "You will get a similar message once the installation is complete"
},
{
"code": null,
"e": 26891,
"s": 26818,
"text": "Make sure you follow the best practices for installation using conda as:"
},
{
"code": null,
"e": 26988,
"s": 26891,
"text": "Use an environment for installation rather than in the base environment using the below command:"
},
{
"code": null,
"e": 27033,
"s": 26988,
"text": "conda create -n my-env\nconda activate my-env"
},
{
"code": null,
"e": 27119,
"s": 27033,
"text": "Note: If your preferred method of installation is conda-forge, use the below command:"
},
{
"code": null,
"e": 27165,
"s": 27119,
"text": "conda config --env --add channels conda-forge"
},
{
"code": null,
"e": 27237,
"s": 27165,
"text": "Users who prefer to use pip can use the below command to install NumPy:"
},
{
"code": null,
"e": 27255,
"s": 27237,
"text": "pip install numpy"
},
{
"code": null,
"e": 27321,
"s": 27255,
"text": "You will get a similar message once the installation is complete:"
},
{
"code": null,
"e": 27424,
"s": 27321,
"text": "Now that we have installed Numpy successfully in our system, let’s take a look at few simple examples."
},
{
"code": null,
"e": 27464,
"s": 27424,
"text": "Example 1: Basic Numpy Array characters"
},
{
"code": null,
"e": 27472,
"s": 27464,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# basic array characteristicsimport numpy as np # Creating array objectarr = np.array( [[ 1, 2, 3], [ 4, 2, 5]] ) # Printing type of arr objectprint(\"Array is of type: \", type(arr)) # Printing array dimensions (axes)print(\"No. of dimensions: \", arr.ndim) # Printing shape of arrayprint(\"Shape of array: \", arr.shape) # Printing size (total number of elements) of arrayprint(\"Size of array: \", arr.size) # Printing type of elements in arrayprint(\"Array stores elements of type: \", arr.dtype)",
"e": 28015,
"s": 27472,
"text": null
},
{
"code": null,
"e": 28023,
"s": 28015,
"text": "Output:"
},
{
"code": null,
"e": 28145,
"s": 28023,
"text": "Array is of type: \nNo. of dimensions: 2\nShape of array: (2, 3)\nSize of array: 6\nArray stores elements of type: int64"
},
{
"code": null,
"e": 28179,
"s": 28145,
"text": "Example 2: Basic Numpy operations"
},
{
"code": null,
"e": 28187,
"s": 28179,
"text": "Python3"
},
{
"code": "# Python program to demonstrate# basic operations on single arrayimport numpy as np a = np.array([1, 2, 5, 3]) # add 1 to every elementprint (\"Adding 1 to every element:\", a+1) # subtract 3 from each elementprint (\"Subtracting 3 from each element:\", a-3) # multiply each element by 10print (\"Multiplying each element by 10:\", a*10) # square each elementprint (\"Squaring each element:\", a**2) # modify existing arraya *= 2print (\"Doubled each element of original array:\", a) # transpose of arraya = np.array([[1, 2, 3], [3, 4, 5], [9, 6, 0]]) print (\"\\nOriginal array:\\n\", a)print (\"Transpose of array:\\n\", a.T)",
"e": 28806,
"s": 28187,
"text": null
},
{
"code": null,
"e": 28814,
"s": 28806,
"text": "Output:"
},
{
"code": null,
"e": 29130,
"s": 28814,
"text": "Adding 1 to every element: [2 3 6 4]\nSubtracting 3 from each element: [-2 -1 2 0]\nMultiplying each element by 10: [10 20 50 30]\nSquaring each element: [ 1 4 25 9]\nDoubled each element of original array: [ 2 4 10 6]\n\nOriginal array:\n [[1 2 3]\n [3 4 5]\n [9 6 0]]\nTranspose of array:\n [[1 3 9]\n [2 4 6]\n [3 5 0]]"
},
{
"code": null,
"e": 29145,
"s": 29130,
"text": "Blogathon-2021"
},
{
"code": null,
"e": 29160,
"s": 29145,
"text": "how-to-install"
},
{
"code": null,
"e": 29167,
"s": 29160,
"text": "Picked"
},
{
"code": null,
"e": 29180,
"s": 29167,
"text": "Python-numpy"
},
{
"code": null,
"e": 29190,
"s": 29180,
"text": "Blogathon"
},
{
"code": null,
"e": 29197,
"s": 29190,
"text": "How To"
},
{
"code": null,
"e": 29216,
"s": 29197,
"text": "Installation Guide"
},
{
"code": null,
"e": 29314,
"s": 29216,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29371,
"s": 29314,
"text": "How to Create a Table With Multiple Foreign Keys in SQL?"
},
{
"code": null,
"e": 29412,
"s": 29371,
"text": "How to Import JSON Data into SQL Server?"
},
{
"code": null,
"e": 29442,
"s": 29412,
"text": "Stratified Sampling in Pandas"
},
{
"code": null,
"e": 29480,
"s": 29442,
"text": "SQL Query to Convert Datetime to Date"
},
{
"code": null,
"e": 29543,
"s": 29480,
"text": "How to pass data into table from a form using React Components"
},
{
"code": null,
"e": 29575,
"s": 29543,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29628,
"s": 29575,
"text": "How to Find the Wi-Fi Password Using CMD in Windows?"
},
{
"code": null,
"e": 29672,
"s": 29628,
"text": "How to install Jupyter Notebook on Windows?"
},
{
"code": null,
"e": 29699,
"s": 29672,
"text": "How to Align Text in HTML?"
}
] |
C program to display numbers in reverse order using single linked list | Linked lists use dynamic memory allocation and are collection of nodes.
Nodes have two parts which are data and link.
The types of linked lists in C programming language are as follows −
Single / Singly linked lists
Double / Doubly linked lists
Circular single linked list
Circular double linked list
The diagram given below depicts the representation of single linked list.
Following is the C program to display the numbers in reverse order by using the single linked list −
Live Demo
#include <stdio.h>
#include <stdlib.h>
struct node {
int num;
struct node *nextptr;
}*stnode;
void createNodeList(int n);
void reverseDispList();
void displayList();
int main(){
int n;
printf("\n\n single Linked List : print it in reverse order :\n");
printf("------------------------------------------------------------------------------\n");
printf(" Input the number of nodes : ");
scanf("%d", &n);
createNodeList(n);
printf("\n Data entered in the list are : \n");
displayList();
reverseDispList();
printf("\n The list in reverse are : \n");
displayList();
return 0;
}
void createNodeList(int n){
struct node *fnNode, *tmp;
int num, i;
stnode = (struct node *)malloc(sizeof(struct node));
if(stnode == NULL) {
printf(" Memory can not be allocated.");
}
else{
// reads data for the node through keyboard
printf(" Input data for node 1 : ");
scanf("%d", &num);
stnode-> num = num;
stnode-> nextptr = NULL;
tmp = stnode;
//Creates n nodes and adds to linked list
for(i=2; i<=n; i++){
fnNode = (struct node *)malloc(sizeof(struct node));
if(fnNode == NULL) {
printf(" Memory can not be allocated.");
break;
}
else{
printf(" Input data for node %d : ", i);
scanf(" %d", &num);
fnNode->num = num;
fnNode->nextptr = NULL;
tmp->nextptr = fnNode;
tmp = tmp->nextptr;
}
}
}
}
void reverseDispList(){
struct node *prevNode, *curNode;
if(stnode != NULL){
prevNode = stnode;
curNode = stnode->nextptr;
stnode = stnode->nextptr;
prevNode->nextptr = NULL; //convert the first node as last
while(stnode != NULL){
stnode = stnode->nextptr;
curNode->nextptr = prevNode;
prevNode = curNode;
curNode = stnode;
}
stnode = prevNode; //convert the last node as head
}
}
void displayList(){
struct node *tmp;
if(stnode == NULL){
printf(" No data found in the list.");
}
else{
tmp = stnode;
while(tmp != NULL){
printf(" Data = %d\n", tmp->num);
tmp = tmp->nextptr;
}
}
}
When the above program is executed, it produces the following result −
Single Linked List : print it in reverse order :
------------------------------------------------------------------------------
Input the number of nodes : 5
Input data for node 1 : 12
Input data for node 2 : 45
Input data for node 3 : 11
Input data for node 4 : 9
Input data for node 5 : 10
Data entered in the list are :
Data = 12
Data = 45
Data = 11
Data = 9
Data = 10
The list in reverse are :
Data = 10
Data = 9
Data = 11
Data = 45
Data = 12 | [
{
"code": null,
"e": 1134,
"s": 1062,
"text": "Linked lists use dynamic memory allocation and are collection of nodes."
},
{
"code": null,
"e": 1180,
"s": 1134,
"text": "Nodes have two parts which are data and link."
},
{
"code": null,
"e": 1249,
"s": 1180,
"text": "The types of linked lists in C programming language are as follows −"
},
{
"code": null,
"e": 1278,
"s": 1249,
"text": "Single / Singly linked lists"
},
{
"code": null,
"e": 1307,
"s": 1278,
"text": "Double / Doubly linked lists"
},
{
"code": null,
"e": 1335,
"s": 1307,
"text": "Circular single linked list"
},
{
"code": null,
"e": 1363,
"s": 1335,
"text": "Circular double linked list"
},
{
"code": null,
"e": 1437,
"s": 1363,
"text": "The diagram given below depicts the representation of single linked list."
},
{
"code": null,
"e": 1538,
"s": 1437,
"text": "Following is the C program to display the numbers in reverse order by using the single linked list −"
},
{
"code": null,
"e": 1549,
"s": 1538,
"text": " Live Demo"
},
{
"code": null,
"e": 3807,
"s": 1549,
"text": "#include <stdio.h>\n#include <stdlib.h>\nstruct node {\n int num;\n struct node *nextptr;\n}*stnode;\nvoid createNodeList(int n);\nvoid reverseDispList();\nvoid displayList();\nint main(){\n int n;\n printf(\"\\n\\n single Linked List : print it in reverse order :\\n\");\n printf(\"------------------------------------------------------------------------------\\n\");\n printf(\" Input the number of nodes : \");\n scanf(\"%d\", &n);\n createNodeList(n);\n printf(\"\\n Data entered in the list are : \\n\");\n displayList();\n reverseDispList();\n printf(\"\\n The list in reverse are : \\n\");\n displayList();\n return 0;\n}\nvoid createNodeList(int n){\n struct node *fnNode, *tmp;\n int num, i;\n stnode = (struct node *)malloc(sizeof(struct node));\n if(stnode == NULL) {\n printf(\" Memory can not be allocated.\");\n }\n else{\n // reads data for the node through keyboard\n printf(\" Input data for node 1 : \");\n scanf(\"%d\", &num);\n stnode-> num = num;\n stnode-> nextptr = NULL;\n tmp = stnode;\n //Creates n nodes and adds to linked list\n for(i=2; i<=n; i++){\n fnNode = (struct node *)malloc(sizeof(struct node));\n if(fnNode == NULL) {\n printf(\" Memory can not be allocated.\");\n break;\n }\n else{\n printf(\" Input data for node %d : \", i);\n scanf(\" %d\", &num);\n fnNode->num = num;\n fnNode->nextptr = NULL;\n tmp->nextptr = fnNode;\n tmp = tmp->nextptr;\n }\n }\n }\n}\nvoid reverseDispList(){\n struct node *prevNode, *curNode;\n if(stnode != NULL){\n prevNode = stnode;\n curNode = stnode->nextptr;\n stnode = stnode->nextptr;\n prevNode->nextptr = NULL; //convert the first node as last\n while(stnode != NULL){\n stnode = stnode->nextptr;\n curNode->nextptr = prevNode;\n prevNode = curNode;\n curNode = stnode;\n }\n stnode = prevNode; //convert the last node as head\n }\n}\nvoid displayList(){\n struct node *tmp;\n if(stnode == NULL){\n printf(\" No data found in the list.\");\n }\n else{\n tmp = stnode;\n while(tmp != NULL){\n printf(\" Data = %d\\n\", tmp->num);\n tmp = tmp->nextptr;\n }\n }\n}"
},
{
"code": null,
"e": 3878,
"s": 3807,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 4327,
"s": 3878,
"text": "Single Linked List : print it in reverse order :\n------------------------------------------------------------------------------\nInput the number of nodes : 5\nInput data for node 1 : 12\nInput data for node 2 : 45\nInput data for node 3 : 11\nInput data for node 4 : 9\nInput data for node 5 : 10\n\nData entered in the list are :\nData = 12\nData = 45\nData = 11\nData = 9\nData = 10\n\nThe list in reverse are :\nData = 10\nData = 9\nData = 11\nData = 45\nData = 12"
}
] |
JavaTuples with() method - GeeksforGeeks | 23 Aug, 2018
The with() method in org.javatuples is used to instantiate a tuple in a semantically elegant way, with the values given as parameters. This method can be used for any tuple class object of the javatuples library. This method is a static function in each javatuple class and it returns the tuple class object of the called class, with the values initialized by the corresponding values in the arguments.
Syntax:
public static <A, B, ..> <em>TupleClass<A, B, ..> with(A a, B b, ..)
Parameters: This method takes n values as parameters where:
n– represents the number of values based on the TupleClass (Unit, Pair, etc) used.
A a– represents the type for 1st value in A and its corresponding value in a.
B b– represents the type for 2nd value in B and its corresponding value in b...and so on.
..and so on.
Return Value: This method returns the object of TupleClass, which calls the method, with the values passed as the parameters.
Exceptions: This method throws a RuntimeException in the following cases:
When the values passed do not match their expected types in TupleClass
When the number of values passed are lesser than expected in TupleClass
When the number of values passed are more than expected in TupleClass
Below programs illustrate the various ways to use with() methods:
Program 1: When the with() method is used correctly, here with Unit class:
// Below is a Java program to create// a Unit tuple from with() method import java.util.*;import org.javatuples.Unit; class GfG { public static void main(String[] args) { // Using with() method to instantiate unit object Unit<String> unit = Unit.with("GeeksforGeeks"); System.out.println(unit); }}
Output:
[GeeksforGeeks]
Program 2: When the values passed do not match their expected types:
// Below is a Java program to create// a Unit tuple from with() method import java.util.*;import org.javatuples.Quartet; class GfG { public static void main(String[] args) { // Using with() method to instantiate unit object Quartet<Integer, String, String, Double> quartet = Quartet.with(Double.valueOf(1), "GeeksforGeeks", "A computer portal", Double.valueOf(20.18)); System.out.println(quartet); }}
Output:
Exception in thread "main" java.lang.RuntimeException:
Uncompilable source code - incompatible types: inference variable A has incompatible bounds
equality constraints: java.lang.Integer
lower bounds: java.lang.Double
at MainClass.GfG.main]
Program 3: When the number of values passed are lesser than expected:
// Below is a Java program to create// a Unit tuple from with() method import java.util.*;import org.javatuples.Quartet; class GfG { public static void main(String[] args) { // Using with() method to instantiate unit object Quartet<Integer, String, String, Double> quartet = Quartet.with(Integer.valueOf(1), "GeeksforGeeks", "A computer portal"); System.out.println(quartet); }}
Output:
Exception in thread "main" java.lang.RuntimeException:
Uncompilable source code - Erroneous sym type: org.javatuples.Quartet.with
at MainClass.GfG.main
Program 4: When the number of values passed are more than expected:
// Below is a Java program to create// a Unit tuple from with() method import java.util.*;import org.javatuples.Quartet; class GfG { public static void main(String[] args) { // Using with() method to instantiate unit object Quartet<Integer, String, String, Double> quartet = Quartet.with(Integer.valueOf(1), "GeeksforGeeks", "A computer portal", Double.valueOf(20.18), Integer.valueOf(1)); System.out.println(quartet); }}
Output:
Exception in thread "main" java.lang.RuntimeException:
Uncompilable source code - Erroneous sym type: org.javatuples.Quartet.with
at MainClass.GfG.main
Note: Similarly, it can be used with any other JavaTuple Class.
Java-Functions
JavaTuples
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
HashMap in Java with Examples
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Set in Java
Multithreading in Java | [
{
"code": null,
"e": 25629,
"s": 25601,
"text": "\n23 Aug, 2018"
},
{
"code": null,
"e": 26032,
"s": 25629,
"text": "The with() method in org.javatuples is used to instantiate a tuple in a semantically elegant way, with the values given as parameters. This method can be used for any tuple class object of the javatuples library. This method is a static function in each javatuple class and it returns the tuple class object of the called class, with the values initialized by the corresponding values in the arguments."
},
{
"code": null,
"e": 26040,
"s": 26032,
"text": "Syntax:"
},
{
"code": null,
"e": 26109,
"s": 26040,
"text": "public static <A, B, ..> <em>TupleClass<A, B, ..> with(A a, B b, ..)"
},
{
"code": null,
"e": 26169,
"s": 26109,
"text": "Parameters: This method takes n values as parameters where:"
},
{
"code": null,
"e": 26252,
"s": 26169,
"text": "n– represents the number of values based on the TupleClass (Unit, Pair, etc) used."
},
{
"code": null,
"e": 26330,
"s": 26252,
"text": "A a– represents the type for 1st value in A and its corresponding value in a."
},
{
"code": null,
"e": 26420,
"s": 26330,
"text": "B b– represents the type for 2nd value in B and its corresponding value in b...and so on."
},
{
"code": null,
"e": 26433,
"s": 26420,
"text": "..and so on."
},
{
"code": null,
"e": 26559,
"s": 26433,
"text": "Return Value: This method returns the object of TupleClass, which calls the method, with the values passed as the parameters."
},
{
"code": null,
"e": 26633,
"s": 26559,
"text": "Exceptions: This method throws a RuntimeException in the following cases:"
},
{
"code": null,
"e": 26704,
"s": 26633,
"text": "When the values passed do not match their expected types in TupleClass"
},
{
"code": null,
"e": 26776,
"s": 26704,
"text": "When the number of values passed are lesser than expected in TupleClass"
},
{
"code": null,
"e": 26846,
"s": 26776,
"text": "When the number of values passed are more than expected in TupleClass"
},
{
"code": null,
"e": 26912,
"s": 26846,
"text": "Below programs illustrate the various ways to use with() methods:"
},
{
"code": null,
"e": 26987,
"s": 26912,
"text": "Program 1: When the with() method is used correctly, here with Unit class:"
},
{
"code": "// Below is a Java program to create// a Unit tuple from with() method import java.util.*;import org.javatuples.Unit; class GfG { public static void main(String[] args) { // Using with() method to instantiate unit object Unit<String> unit = Unit.with(\"GeeksforGeeks\"); System.out.println(unit); }}",
"e": 27319,
"s": 26987,
"text": null
},
{
"code": null,
"e": 27327,
"s": 27319,
"text": "Output:"
},
{
"code": null,
"e": 27343,
"s": 27327,
"text": "[GeeksforGeeks]"
},
{
"code": null,
"e": 27412,
"s": 27343,
"text": "Program 2: When the values passed do not match their expected types:"
},
{
"code": "// Below is a Java program to create// a Unit tuple from with() method import java.util.*;import org.javatuples.Quartet; class GfG { public static void main(String[] args) { // Using with() method to instantiate unit object Quartet<Integer, String, String, Double> quartet = Quartet.with(Double.valueOf(1), \"GeeksforGeeks\", \"A computer portal\", Double.valueOf(20.18)); System.out.println(quartet); }}",
"e": 27936,
"s": 27412,
"text": null
},
{
"code": null,
"e": 27944,
"s": 27936,
"text": "Output:"
},
{
"code": null,
"e": 28198,
"s": 27944,
"text": "Exception in thread \"main\" java.lang.RuntimeException: \nUncompilable source code - incompatible types: inference variable A has incompatible bounds\n equality constraints: java.lang.Integer\n lower bounds: java.lang.Double\n at MainClass.GfG.main]"
},
{
"code": null,
"e": 28268,
"s": 28198,
"text": "Program 3: When the number of values passed are lesser than expected:"
},
{
"code": "// Below is a Java program to create// a Unit tuple from with() method import java.util.*;import org.javatuples.Quartet; class GfG { public static void main(String[] args) { // Using with() method to instantiate unit object Quartet<Integer, String, String, Double> quartet = Quartet.with(Integer.valueOf(1), \"GeeksforGeeks\", \"A computer portal\"); System.out.println(quartet); }}",
"e": 28744,
"s": 28268,
"text": null
},
{
"code": null,
"e": 28752,
"s": 28744,
"text": "Output:"
},
{
"code": null,
"e": 28909,
"s": 28752,
"text": "Exception in thread \"main\" java.lang.RuntimeException: \nUncompilable source code - Erroneous sym type: org.javatuples.Quartet.with\n at MainClass.GfG.main"
},
{
"code": null,
"e": 28977,
"s": 28909,
"text": "Program 4: When the number of values passed are more than expected:"
},
{
"code": "// Below is a Java program to create// a Unit tuple from with() method import java.util.*;import org.javatuples.Quartet; class GfG { public static void main(String[] args) { // Using with() method to instantiate unit object Quartet<Integer, String, String, Double> quartet = Quartet.with(Integer.valueOf(1), \"GeeksforGeeks\", \"A computer portal\", Double.valueOf(20.18), Integer.valueOf(1)); System.out.println(quartet); }}",
"e": 29548,
"s": 28977,
"text": null
},
{
"code": null,
"e": 29556,
"s": 29548,
"text": "Output:"
},
{
"code": null,
"e": 29713,
"s": 29556,
"text": "Exception in thread \"main\" java.lang.RuntimeException: \nUncompilable source code - Erroneous sym type: org.javatuples.Quartet.with\n at MainClass.GfG.main"
},
{
"code": null,
"e": 29777,
"s": 29713,
"text": "Note: Similarly, it can be used with any other JavaTuple Class."
},
{
"code": null,
"e": 29792,
"s": 29777,
"text": "Java-Functions"
},
{
"code": null,
"e": 29803,
"s": 29792,
"text": "JavaTuples"
},
{
"code": null,
"e": 29808,
"s": 29803,
"text": "Java"
},
{
"code": null,
"e": 29813,
"s": 29808,
"text": "Java"
},
{
"code": null,
"e": 29911,
"s": 29813,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29926,
"s": 29911,
"text": "Stream In Java"
},
{
"code": null,
"e": 29956,
"s": 29926,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29975,
"s": 29956,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30007,
"s": 29975,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30025,
"s": 30007,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30045,
"s": 30025,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30069,
"s": 30045,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 30101,
"s": 30069,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 30113,
"s": 30101,
"text": "Set in Java"
}
] |
TypeORM - Working with CLI | This section explains about TypeORM CLI commands in detail.
typeorm init is the easiest and fastest way to setup a TypeORM project. You can create a new project as,
typeorm init --name Demoproject --database mysql
After executing the command, you will get the following output on your screen −
Project created inside /Users/workspace/TypeORM/Demoproject directory.
To create a new entity using CLI as,
typeorm entity:create -n Person
Now, Person entity is created inside your project src directory.
Entity /Users/workspace/TypeORM/Demoproject/src/entity/Person.ts has been created successfully.
If you have a multi-module project structure with multiple entities in different directories, you can use the below command,
typeorm entity:create -n Person -d src/Person/entity
To create a new subscriber using CLI as follows −
typeorm subscriber:create -n PersonSubscriber
You could see the following response −
Subscriber /path/to/TypeORM/Demoproject/src/subscriber/PersonSubscriber.ts has been created successfully.
You can create a new migration using CLI as mentioned below −
typeorm migration:create -n PersonMigration
The above command created a migration directory inside your project src. Migration files are stored inside it.
Migration /path/to/TypeORM/Demoproject/src/migration/1587395030750-PersonMigration.ts has been generated successfully.
To synchronize a database schema, use the below command −
typeorm schema:sync
To completely drop a database schema, use the below command −
typeorm schema:drop
If you want to execute any sql queries, we can execute directly from here. For example, to display all the records of customers, use the below query −
typeorm query "select * from customers"
If you want to clear everything stored in the cache. You can do it using the following command −
typeorm cache:clear
TypeORM is an excellent open source ORM framework to create high quality and scalable applications from small scale applications to large scale enterprise applications with multiple databases. | [
{
"code": null,
"e": 2245,
"s": 2185,
"text": "This section explains about TypeORM CLI commands in detail."
},
{
"code": null,
"e": 2350,
"s": 2245,
"text": "typeorm init is the easiest and fastest way to setup a TypeORM project. You can create a new project as,"
},
{
"code": null,
"e": 2400,
"s": 2350,
"text": "typeorm init --name Demoproject --database mysql\n"
},
{
"code": null,
"e": 2480,
"s": 2400,
"text": "After executing the command, you will get the following output on your screen −"
},
{
"code": null,
"e": 2552,
"s": 2480,
"text": "Project created inside /Users/workspace/TypeORM/Demoproject directory.\n"
},
{
"code": null,
"e": 2589,
"s": 2552,
"text": "To create a new entity using CLI as,"
},
{
"code": null,
"e": 2622,
"s": 2589,
"text": "typeorm entity:create -n Person\n"
},
{
"code": null,
"e": 2687,
"s": 2622,
"text": "Now, Person entity is created inside your project src directory."
},
{
"code": null,
"e": 2784,
"s": 2687,
"text": "Entity /Users/workspace/TypeORM/Demoproject/src/entity/Person.ts has been created successfully.\n"
},
{
"code": null,
"e": 2909,
"s": 2784,
"text": "If you have a multi-module project structure with multiple entities in different directories, you can use the below command,"
},
{
"code": null,
"e": 2963,
"s": 2909,
"text": "typeorm entity:create -n Person -d src/Person/entity\n"
},
{
"code": null,
"e": 3013,
"s": 2963,
"text": "To create a new subscriber using CLI as follows −"
},
{
"code": null,
"e": 3060,
"s": 3013,
"text": "typeorm subscriber:create -n PersonSubscriber\n"
},
{
"code": null,
"e": 3099,
"s": 3060,
"text": "You could see the following response −"
},
{
"code": null,
"e": 3206,
"s": 3099,
"text": "Subscriber /path/to/TypeORM/Demoproject/src/subscriber/PersonSubscriber.ts has been created successfully.\n"
},
{
"code": null,
"e": 3268,
"s": 3206,
"text": "You can create a new migration using CLI as mentioned below −"
},
{
"code": null,
"e": 3313,
"s": 3268,
"text": "typeorm migration:create -n PersonMigration\n"
},
{
"code": null,
"e": 3424,
"s": 3313,
"text": "The above command created a migration directory inside your project src. Migration files are stored inside it."
},
{
"code": null,
"e": 3544,
"s": 3424,
"text": "Migration /path/to/TypeORM/Demoproject/src/migration/1587395030750-PersonMigration.ts has been generated successfully.\n"
},
{
"code": null,
"e": 3602,
"s": 3544,
"text": "To synchronize a database schema, use the below command −"
},
{
"code": null,
"e": 3623,
"s": 3602,
"text": "typeorm schema:sync\n"
},
{
"code": null,
"e": 3685,
"s": 3623,
"text": "To completely drop a database schema, use the below command −"
},
{
"code": null,
"e": 3706,
"s": 3685,
"text": "typeorm schema:drop\n"
},
{
"code": null,
"e": 3857,
"s": 3706,
"text": "If you want to execute any sql queries, we can execute directly from here. For example, to display all the records of customers, use the below query −"
},
{
"code": null,
"e": 3898,
"s": 3857,
"text": "typeorm query \"select * from customers\"\n"
},
{
"code": null,
"e": 3995,
"s": 3898,
"text": "If you want to clear everything stored in the cache. You can do it using the following command −"
},
{
"code": null,
"e": 4016,
"s": 3995,
"text": "typeorm cache:clear\n"
}
] |
Mongoose Module Introduction | 22 Feb, 2021
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. MongoDB provides us flexible database schema that has its own advantages and disadvantages. Every record in MongoDB collections does not depend upon the other records present in a particular collection on the basis of structure. We can add any new key in any record according to the need. There is no proper structure for the MongoDB collections and constraints on the collections. Let’s have a look at an example.
MongoDB:
Database: GFG
Collection: GFG1
In the above example, we can easily see there is no proper schema for a collection in MongoDB. We can use any numbers of different keys and value in the collection. This phenomenon might create some troubles. So let’s see how can we overcome this problem.
Mongoose.module is one of the most powerful external module of the node.js. Mongoose is a MongoDB ODM (Object database Modelling) that is used to translate the code and its representation from MongoDB to the Node.js server.
Advantages of Mongoose module:
Collection validation of the MongoDB database can be done easily.Predefined Structure can be implemented on the collection.Constraints can be applied to documents of collections using Mongoose.
Collection validation of the MongoDB database can be done easily.
Predefined Structure can be implemented on the collection.
Constraints can be applied to documents of collections using Mongoose.
Mongoose module provides several functions in order to manipulate the documents of the collection of the MongoDB database (Refer this Link)
Implementation for definite structure for Collection:
Installing Module:
npm install mongoose
Project Structure:
Running the server on Local IP: Data is the directory where MongoDB server is present.
mongod --dbpath=data --bind_ip 127.0.0.1
Index.js
Javascript
// Importing mongoose moduleconst mongoose = require("mongoose") // Database Addressconst url = "mongodb://localhost:27017/GFG" // Connecting to databasemongoose.connect(url).then((ans) => { console.log("ConnectedSuccessful")}).catch((err) => { console.log("Error in the Connection")}) // Calling Schema classconst Schema = mongoose.Schema; // Creating Structure of the collectionconst collection_structure = new Schema({ name: { type: String, require: true }, marks: { type: Number, default: 0 }}) // Creating collectionconst collections = mongoose.model( "GFG2", collection_structure) // Inserting one documentcollections.create({ name: "aayush"}).then((ans) => { console.log("Document inserted") // Inserting invalid document collections.create({ name: "saini", marks: "#234", phone: 981 }).then((ans) => { console.log(ans) }).catch((err) => { // Printing the documents collections.find().then((ans) => { console.log(ans) }) // Printing the Error Message console.log(err.message) })}).catch((err) => { // Printing Error Message console.log(err.message)})
Run index.js file using below command:
node index.js
Console output:
Mongoose module imposed a definite structure on the collection and makes the collection rigid.
Mongoose
Technical Scripter 2020
MongoDB
Node.js
Technical Scripter
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Mongoose Populate() Method
MongoDB - db.collection.Find() Method
Aggregation in MongoDB
MongoDB - Check the existence of the fields in the specified collection
How to update Node.js and NPM to next version ?
Installation of Node.js on Linux
Node.js fs.readFileSync() Method
Node.js fs.writeFile() Method
How to install the previous version of node.js and npm ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Feb, 2021"
},
{
"code": null,
"e": 572,
"s": 28,
"text": "MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. MongoDB provides us flexible database schema that has its own advantages and disadvantages. Every record in MongoDB collections does not depend upon the other records present in a particular collection on the basis of structure. We can add any new key in any record according to the need. There is no proper structure for the MongoDB collections and constraints on the collections. Let’s have a look at an example."
},
{
"code": null,
"e": 581,
"s": 572,
"text": "MongoDB:"
},
{
"code": null,
"e": 612,
"s": 581,
"text": "Database: GFG\nCollection: GFG1"
},
{
"code": null,
"e": 868,
"s": 612,
"text": "In the above example, we can easily see there is no proper schema for a collection in MongoDB. We can use any numbers of different keys and value in the collection. This phenomenon might create some troubles. So let’s see how can we overcome this problem."
},
{
"code": null,
"e": 1092,
"s": 868,
"text": "Mongoose.module is one of the most powerful external module of the node.js. Mongoose is a MongoDB ODM (Object database Modelling) that is used to translate the code and its representation from MongoDB to the Node.js server."
},
{
"code": null,
"e": 1123,
"s": 1092,
"text": "Advantages of Mongoose module:"
},
{
"code": null,
"e": 1317,
"s": 1123,
"text": "Collection validation of the MongoDB database can be done easily.Predefined Structure can be implemented on the collection.Constraints can be applied to documents of collections using Mongoose."
},
{
"code": null,
"e": 1383,
"s": 1317,
"text": "Collection validation of the MongoDB database can be done easily."
},
{
"code": null,
"e": 1442,
"s": 1383,
"text": "Predefined Structure can be implemented on the collection."
},
{
"code": null,
"e": 1513,
"s": 1442,
"text": "Constraints can be applied to documents of collections using Mongoose."
},
{
"code": null,
"e": 1653,
"s": 1513,
"text": "Mongoose module provides several functions in order to manipulate the documents of the collection of the MongoDB database (Refer this Link)"
},
{
"code": null,
"e": 1707,
"s": 1653,
"text": "Implementation for definite structure for Collection:"
},
{
"code": null,
"e": 1726,
"s": 1707,
"text": "Installing Module:"
},
{
"code": null,
"e": 1747,
"s": 1726,
"text": "npm install mongoose"
},
{
"code": null,
"e": 1766,
"s": 1747,
"text": "Project Structure:"
},
{
"code": null,
"e": 1853,
"s": 1766,
"text": "Running the server on Local IP: Data is the directory where MongoDB server is present."
},
{
"code": null,
"e": 1894,
"s": 1853,
"text": "mongod --dbpath=data --bind_ip 127.0.0.1"
},
{
"code": null,
"e": 1903,
"s": 1894,
"text": "Index.js"
},
{
"code": null,
"e": 1914,
"s": 1903,
"text": "Javascript"
},
{
"code": "// Importing mongoose moduleconst mongoose = require(\"mongoose\") // Database Addressconst url = \"mongodb://localhost:27017/GFG\" // Connecting to databasemongoose.connect(url).then((ans) => { console.log(\"ConnectedSuccessful\")}).catch((err) => { console.log(\"Error in the Connection\")}) // Calling Schema classconst Schema = mongoose.Schema; // Creating Structure of the collectionconst collection_structure = new Schema({ name: { type: String, require: true }, marks: { type: Number, default: 0 }}) // Creating collectionconst collections = mongoose.model( \"GFG2\", collection_structure) // Inserting one documentcollections.create({ name: \"aayush\"}).then((ans) => { console.log(\"Document inserted\") // Inserting invalid document collections.create({ name: \"saini\", marks: \"#234\", phone: 981 }).then((ans) => { console.log(ans) }).catch((err) => { // Printing the documents collections.find().then((ans) => { console.log(ans) }) // Printing the Error Message console.log(err.message) })}).catch((err) => { // Printing Error Message console.log(err.message)})",
"e": 3169,
"s": 1914,
"text": null
},
{
"code": null,
"e": 3208,
"s": 3169,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 3222,
"s": 3208,
"text": "node index.js"
},
{
"code": null,
"e": 3238,
"s": 3222,
"text": "Console output:"
},
{
"code": null,
"e": 3333,
"s": 3238,
"text": "Mongoose module imposed a definite structure on the collection and makes the collection rigid."
},
{
"code": null,
"e": 3342,
"s": 3333,
"text": "Mongoose"
},
{
"code": null,
"e": 3366,
"s": 3342,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3374,
"s": 3366,
"text": "MongoDB"
},
{
"code": null,
"e": 3382,
"s": 3374,
"text": "Node.js"
},
{
"code": null,
"e": 3401,
"s": 3382,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3418,
"s": 3401,
"text": "Web Technologies"
},
{
"code": null,
"e": 3516,
"s": 3418,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3555,
"s": 3516,
"text": "Spring Boot JpaRepository with Example"
},
{
"code": null,
"e": 3582,
"s": 3555,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 3620,
"s": 3582,
"text": "MongoDB - db.collection.Find() Method"
},
{
"code": null,
"e": 3643,
"s": 3620,
"text": "Aggregation in MongoDB"
},
{
"code": null,
"e": 3715,
"s": 3643,
"text": "MongoDB - Check the existence of the fields in the specified collection"
},
{
"code": null,
"e": 3763,
"s": 3715,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 3796,
"s": 3763,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3829,
"s": 3796,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 3859,
"s": 3829,
"text": "Node.js fs.writeFile() Method"
}
] |
Sum of nodes on the longest path from root to leaf node | 17 Mar, 2022
Given a binary tree containing n nodes. The problem is to find the sum of all nodes on the longest path from root to leaf node. If two or more paths compete for the longest path, then the path having maximum sum of nodes is being considered.Examples:
Input : Binary tree:
4
/ \
2 5
/ \ / \
7 1 2 3
/
6
Output : 13
4
/ \
2 5
/ \ / \
7 1 2 3
/
6
The highlighted nodes (4, 2, 1, 6) above are
part of the longest root to leaf path having
sum = (4 + 2 + 1 + 6) = 13
Approach: Recursively find the length and sum of nodes of each root to leaf path and accordingly update the maximum sum.Algorithm:
sumOfLongRootToLeafPath(root, sum, len, maxLen, maxSum)
if root == NULL
if maxLen < len
maxLen = len
maxSum = sum
else if maxLen == len && maxSum is less than sum
maxSum = sum
return
sumOfLongRootToLeafPath(root-left, sum + root-data,
len + 1, maxLen, maxSum)
sumOfLongRootToLeafPath(root-right, sum + root-data,
len + 1, maxLen, maxSum)
sumOfLongRootToLeafPathUtil(root)
if (root == NULL)
return 0
Declare maxSum = Minimum Integer
Declare maxLen = 0
sumOfLongRootToLeafPath(root, 0, 0, maxLen, maxSum)
return maxSum
C++
Java
Python3
C#
Javascript
// C++ implementation to find the sum of nodes// on the longest path from root to leaf node#include <bits/stdc++.h> using namespace std; // Node of a binary treestruct Node { int data; Node* left, *right;}; // function to get a new nodeNode* getNode(int data){ // allocate memory for the node Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // function to find the sum of nodes on the// longest path from root to leaf nodevoid sumOfLongRootToLeafPath(Node* root, int sum, int len, int& maxLen, int& maxSum){ // if true, then we have traversed a // root to leaf path if (!root) { // update maximum length and maximum sum // according to the given conditions if (maxLen < len) { maxLen = len; maxSum = sum; } else if (maxLen == len && maxSum < sum) maxSum = sum; return; } // recur for left subtree sumOfLongRootToLeafPath(root->left, sum + root->data, len + 1, maxLen, maxSum); // recur for right subtree sumOfLongRootToLeafPath(root->right, sum + root->data, len + 1, maxLen, maxSum);} // utility function to find the sum of nodes on// the longest path from root to leaf nodeint sumOfLongRootToLeafPathUtil(Node* root){ // if tree is NULL, then sum is 0 if (!root) return 0; int maxSum = INT_MIN, maxLen = 0; // finding the maximum sum 'maxSum' for the // maximum length root to leaf path sumOfLongRootToLeafPath(root, 0, 0, maxLen, maxSum); // required maximum sum return maxSum;} // Driver program to test aboveint main(){ // binary tree formation Node* root = getNode(4); /* 4 */ root->left = getNode(2); /* / \ */ root->right = getNode(5); /* 2 5 */ root->left->left = getNode(7); /* / \ / \ */ root->left->right = getNode(1); /* 7 1 2 3 */ root->right->left = getNode(2); /* / */ root->right->right = getNode(3); /* 6 */ root->left->right->left = getNode(6); cout << "Sum = " << sumOfLongRootToLeafPathUtil(root); return 0;}
// Java implementation to find the sum of nodes// on the longest path from root to leaf nodepublic class GFG{ // Node of a binary tree static class Node { int data; Node left, right; Node(int data){ this.data = data; left = null; right = null; } } static int maxLen; static int maxSum; // function to find the sum of nodes on the // longest path from root to leaf node static void sumOfLongRootToLeafPath(Node root, int sum, int len) { // if true, then we have traversed a // root to leaf path if (root == null) { // update maximum length and maximum sum // according to the given conditions if (maxLen < len) { maxLen = len; maxSum = sum; } else if (maxLen == len && maxSum < sum) maxSum = sum; return; } // recur for left subtree sumOfLongRootToLeafPath(root.left, sum + root.data, len + 1); sumOfLongRootToLeafPath(root.right, sum + root.data, len + 1); } // utility function to find the sum of nodes on // the longest path from root to leaf node static int sumOfLongRootToLeafPathUtil(Node root) { // if tree is NULL, then sum is 0 if (root == null) return 0; maxSum = Integer.MIN_VALUE; maxLen = 0; // finding the maximum sum 'maxSum' for the // maximum length root to leaf path sumOfLongRootToLeafPath(root, 0, 0); // required maximum sum return maxSum; } // Driver program to test above public static void main(String args[]) { // binary tree formation Node root = new Node(4); /* 4 */ root.left = new Node(2); /* / \ */ root.right = new Node(5); /* 2 5 */ root.left.left = new Node(7); /* / \ / \ */ root.left.right = new Node(1); /* 7 1 2 3 */ root.right.left = new Node(2); /* / */ root.right.right = new Node(3); /* 6 */ root.left.right.left = new Node(6); System.out.println( "Sum = " + sumOfLongRootToLeafPathUtil(root)); }}// This code is contributed by Sumit Ghosh
# Python3 implementation to find the # Sum of nodes on the longest path# from root to leaf nodes # function to get a new nodeclass getNode: def __init__(self, data): # put in the data self.data = data self.left = self.right = None # function to find the Sum of nodes on the# longest path from root to leaf nodedef SumOfLongRootToLeafPath(root, Sum, Len, maxLen, maxSum): # if true, then we have traversed a # root to leaf path if (not root): # update maximum Length and maximum Sum # according to the given conditions if (maxLen[0] < Len): maxLen[0] = Len maxSum[0] = Sum else if (maxLen[0]== Len and maxSum[0] < Sum): maxSum[0] = Sum return # recur for left subtree SumOfLongRootToLeafPath(root.left, Sum + root.data, Len + 1, maxLen, maxSum) # recur for right subtree SumOfLongRootToLeafPath(root.right, Sum + root.data, Len + 1, maxLen, maxSum) # utility function to find the Sum of nodes on# the longest path from root to leaf nodedef SumOfLongRootToLeafPathUtil(root): # if tree is NULL, then Sum is 0 if (not root): return 0 maxSum = [-999999999999] maxLen = [0] # finding the maximum Sum 'maxSum' for # the maximum Length root to leaf path SumOfLongRootToLeafPath(root, 0, 0, maxLen, maxSum) # required maximum Sum return maxSum[0] # Driver Codeif __name__ == '__main__': # binary tree formation root = getNode(4) # 4 root.left = getNode(2) # / \ root.right = getNode(5) # 2 5 root.left.left = getNode(7) # / \ / \ root.left.right = getNode(1) # 7 1 2 3 root.right.left = getNode(2) # / root.right.right = getNode(3) # 6 root.left.right.left = getNode(6) print("Sum = ", SumOfLongRootToLeafPathUtil(root)) # This code is contributed by PranchalK
using System; // c# implementation to find the sum of nodes// on the longest path from root to leaf nodepublic class GFG{ // Node of a binary tree public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = null; right = null; } } public static int maxLen; public static int maxSum; // function to find the sum of nodes on the // longest path from root to leaf node public static void sumOfLongRootToLeafPath(Node root, int sum, int len) { // if true, then we have traversed a // root to leaf path if (root == null) { // update maximum length and maximum sum // according to the given conditions if (maxLen < len) { maxLen = len; maxSum = sum; } else if (maxLen == len && maxSum < sum) { maxSum = sum; } return; } // recur for left subtree sumOfLongRootToLeafPath(root.left, sum + root.data, len + 1); sumOfLongRootToLeafPath(root.right, sum + root.data, len + 1); } // utility function to find the sum of nodes on // the longest path from root to leaf node public static int sumOfLongRootToLeafPathUtil(Node root) { // if tree is NULL, then sum is 0 if (root == null) { return 0; } maxSum = int.MinValue; maxLen = 0; // finding the maximum sum 'maxSum' for the // maximum length root to leaf path sumOfLongRootToLeafPath(root, 0, 0); // required maximum sum return maxSum; } // Driver program to test above public static void Main(string[] args) { // binary tree formation Node root = new Node(4); // 4 root.left = new Node(2); // / \ root.right = new Node(5); // 2 5 root.left.left = new Node(7); // / \ / \ root.left.right = new Node(1); // 7 1 2 3 root.right.left = new Node(2); // / root.right.right = new Node(3); // 6 root.left.right.left = new Node(6); Console.WriteLine("Sum = " + sumOfLongRootToLeafPathUtil(root)); }} // This code is contributed by Shrikant13
<script>// javascript implementation to find the sum of nodes// on the longest path from root to leaf node // Node of a binary tree class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } var maxLen; var maxSum; // function to find the sum of nodes on the // longest path from root to leaf node function sumOfLongRootToLeafPath(root , sum, len) { // if true, then we have traversed a // root to leaf path if (root == null) { // update maximum length and maximum sum // according to the given conditions if (maxLen < len) { maxLen = len; maxSum = sum; } else if (maxLen == len && maxSum < sum) maxSum = sum; return; } // recur for left subtree sumOfLongRootToLeafPath(root.left, sum + root.data, len + 1); sumOfLongRootToLeafPath(root.right, sum + root.data, len + 1); } // utility function to find the sum of nodes on // the longest path from root to leaf node function sumOfLongRootToLeafPathUtil(root) { // if tree is NULL, then sum is 0 if (root == null) return 0; maxSum = Number.MIN_VALUE; maxLen = 0; // finding the maximum sum 'maxSum' for the // maximum length root to leaf path sumOfLongRootToLeafPath(root, 0, 0); // required maximum sum return maxSum; } // Driver program to test above // binary tree formation var root = new Node(4); /* 4 */ root.left = new Node(2); /* / \ */ root.right = new Node(5); /* 2 5 */ root.left.left = new Node(7); /* / \ / \ */ root.left.right = new Node(1); /* 7 1 2 3 */ root.right.left = new Node(2); /* / */ root.right.right = new Node(3); /* 6 */ root.left.right.left = new Node(6); document.write( "Sum = " + sumOfLongRootToLeafPathUtil(root)); // This code is contributed by gauravrajput1</script>
Sum = 13
Time Complexity: O(n)
Another Approach: Using level order traversal
Create a structure containing the current Node, level and sum in the path.Push the root element with level 0 and sum as the root’s data.Pop the front element and update the maximum level sum and maximum level if needed.Push the left and right nodes if exists.Do the same for all the nodes in tree.
Create a structure containing the current Node, level and sum in the path.
Push the root element with level 0 and sum as the root’s data.
Pop the front element and update the maximum level sum and maximum level if needed.
Push the left and right nodes if exists.
Do the same for all the nodes in tree.
C++
#include <bits/stdc++.h>using namespace std; //Building a tree node having left and right pointers set to null initiallystruct Node{ Node* left; Node* right; int data; //constructor to set the data of the newly created tree node Node(int element){ data = element; this->left = nullptr; this->right = nullptr; }}; int longestPathLeaf(Node* root){ /* structure to store current Node,it's level and sum in the path*/ struct Element{ Node* data; int level; int sum; }; /* maxSumLevel stores maximum sum so far in the path maxLevel stores maximum level so far */ int maxSumLevel = root->data,maxLevel = 0; /* queue to implement level order traversal */ list<Element> que; Element e; /* Each element variable stores the current Node, it's level, sum in the path */ e.data = root; e.level = 0; e.sum = root->data; /* push the root element*/ que.push_back(e); /* do level order traversal on the tree*/ while(!que.empty()){ Element front = que.front(); Node* curr = front.data; que.pop_front(); /* if the level of current front element is greater than the maxLevel so far then update maxSum*/ if(front.level > maxLevel){ maxSumLevel = front.sum; maxLevel = front.level; } /* if another path competes then update if the sum is greater than the previous path of same height*/ else if(front.level == maxLevel && front.sum > maxSumLevel) maxSumLevel = front.sum; /* push the left element if exists*/ if(curr->left){ e.data = curr->left; e.sum = e.data->data; e.sum += front.sum; e.level = front.level+1; que.push_back(e); } /*push the right element if exists*/ if(curr->right){ e.data = curr->right; e.sum = e.data->data; e.sum += front.sum; e.level = front.level+1; que.push_back(e); } } /*return the answer*/ return maxSumLevel;}//Helper functionint main() { Node* root = new Node(4); root->left = new Node(2); root->right = new Node(5); root->left->left = new Node(7); root->left->right = new Node(1); root->right->left = new Node(2); root->right->right = new Node(3); root->left->right->left = new Node(6); cout << longestPathLeaf(root) << "\n"; return 0;}
13
Time Complexity: O(N)Auxiliary Space: O(N)
Contributed by Manjukrishna
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=O9jsfsa4idU" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
shrikanth13
PranchalKatiyar
ManjuKrishna
GauravRajput1
surinderdawra388
Traversal
Tree
Traversal
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Mar, 2022"
},
{
"code": null,
"e": 307,
"s": 54,
"text": "Given a binary tree containing n nodes. The problem is to find the sum of all nodes on the longest path from root to leaf node. If two or more paths compete for the longest path, then the path having maximum sum of nodes is being considered.Examples: "
},
{
"code": null,
"e": 667,
"s": 307,
"text": "Input : Binary tree:\n 4 \n / \\ \n 2 5 \n / \\ / \\ \n 7 1 2 3 \n /\n 6\nOutput : 13\n\n 4 \n / \\ \n 2 5 \n / \\ / \\ \n 7 1 2 3 \n /\n 6\n\nThe highlighted nodes (4, 2, 1, 6) above are \npart of the longest root to leaf path having\nsum = (4 + 2 + 1 + 6) = 13"
},
{
"code": null,
"e": 802,
"s": 669,
"text": "Approach: Recursively find the length and sum of nodes of each root to leaf path and accordingly update the maximum sum.Algorithm: "
},
{
"code": null,
"e": 1464,
"s": 802,
"text": "sumOfLongRootToLeafPath(root, sum, len, maxLen, maxSum)\n if root == NULL\n if maxLen < len\n maxLen = len\n maxSum = sum\n else if maxLen == len && maxSum is less than sum\n maxSum = sum\n return\n\n sumOfLongRootToLeafPath(root-left, sum + root-data,\n len + 1, maxLen, maxSum)\n sumOfLongRootToLeafPath(root-right, sum + root-data,\n len + 1, maxLen, maxSum)\n\nsumOfLongRootToLeafPathUtil(root)\n if (root == NULL)\n return 0\n \n Declare maxSum = Minimum Integer\n Declare maxLen = 0\n sumOfLongRootToLeafPath(root, 0, 0, maxLen, maxSum)\n return maxSum"
},
{
"code": null,
"e": 1470,
"s": 1466,
"text": "C++"
},
{
"code": null,
"e": 1475,
"s": 1470,
"text": "Java"
},
{
"code": null,
"e": 1483,
"s": 1475,
"text": "Python3"
},
{
"code": null,
"e": 1486,
"s": 1483,
"text": "C#"
},
{
"code": null,
"e": 1497,
"s": 1486,
"text": "Javascript"
},
{
"code": "// C++ implementation to find the sum of nodes// on the longest path from root to leaf node#include <bits/stdc++.h> using namespace std; // Node of a binary treestruct Node { int data; Node* left, *right;}; // function to get a new nodeNode* getNode(int data){ // allocate memory for the node Node* newNode = (Node*)malloc(sizeof(Node)); // put in the data newNode->data = data; newNode->left = newNode->right = NULL; return newNode;} // function to find the sum of nodes on the// longest path from root to leaf nodevoid sumOfLongRootToLeafPath(Node* root, int sum, int len, int& maxLen, int& maxSum){ // if true, then we have traversed a // root to leaf path if (!root) { // update maximum length and maximum sum // according to the given conditions if (maxLen < len) { maxLen = len; maxSum = sum; } else if (maxLen == len && maxSum < sum) maxSum = sum; return; } // recur for left subtree sumOfLongRootToLeafPath(root->left, sum + root->data, len + 1, maxLen, maxSum); // recur for right subtree sumOfLongRootToLeafPath(root->right, sum + root->data, len + 1, maxLen, maxSum);} // utility function to find the sum of nodes on// the longest path from root to leaf nodeint sumOfLongRootToLeafPathUtil(Node* root){ // if tree is NULL, then sum is 0 if (!root) return 0; int maxSum = INT_MIN, maxLen = 0; // finding the maximum sum 'maxSum' for the // maximum length root to leaf path sumOfLongRootToLeafPath(root, 0, 0, maxLen, maxSum); // required maximum sum return maxSum;} // Driver program to test aboveint main(){ // binary tree formation Node* root = getNode(4); /* 4 */ root->left = getNode(2); /* / \\ */ root->right = getNode(5); /* 2 5 */ root->left->left = getNode(7); /* / \\ / \\ */ root->left->right = getNode(1); /* 7 1 2 3 */ root->right->left = getNode(2); /* / */ root->right->right = getNode(3); /* 6 */ root->left->right->left = getNode(6); cout << \"Sum = \" << sumOfLongRootToLeafPathUtil(root); return 0;}",
"e": 3801,
"s": 1497,
"text": null
},
{
"code": "// Java implementation to find the sum of nodes// on the longest path from root to leaf nodepublic class GFG{ // Node of a binary tree static class Node { int data; Node left, right; Node(int data){ this.data = data; left = null; right = null; } } static int maxLen; static int maxSum; // function to find the sum of nodes on the // longest path from root to leaf node static void sumOfLongRootToLeafPath(Node root, int sum, int len) { // if true, then we have traversed a // root to leaf path if (root == null) { // update maximum length and maximum sum // according to the given conditions if (maxLen < len) { maxLen = len; maxSum = sum; } else if (maxLen == len && maxSum < sum) maxSum = sum; return; } // recur for left subtree sumOfLongRootToLeafPath(root.left, sum + root.data, len + 1); sumOfLongRootToLeafPath(root.right, sum + root.data, len + 1); } // utility function to find the sum of nodes on // the longest path from root to leaf node static int sumOfLongRootToLeafPathUtil(Node root) { // if tree is NULL, then sum is 0 if (root == null) return 0; maxSum = Integer.MIN_VALUE; maxLen = 0; // finding the maximum sum 'maxSum' for the // maximum length root to leaf path sumOfLongRootToLeafPath(root, 0, 0); // required maximum sum return maxSum; } // Driver program to test above public static void main(String args[]) { // binary tree formation Node root = new Node(4); /* 4 */ root.left = new Node(2); /* / \\ */ root.right = new Node(5); /* 2 5 */ root.left.left = new Node(7); /* / \\ / \\ */ root.left.right = new Node(1); /* 7 1 2 3 */ root.right.left = new Node(2); /* / */ root.right.right = new Node(3); /* 6 */ root.left.right.left = new Node(6); System.out.println( \"Sum = \" + sumOfLongRootToLeafPathUtil(root)); }}// This code is contributed by Sumit Ghosh",
"e": 6328,
"s": 3801,
"text": null
},
{
"code": "# Python3 implementation to find the # Sum of nodes on the longest path# from root to leaf nodes # function to get a new nodeclass getNode: def __init__(self, data): # put in the data self.data = data self.left = self.right = None # function to find the Sum of nodes on the# longest path from root to leaf nodedef SumOfLongRootToLeafPath(root, Sum, Len, maxLen, maxSum): # if true, then we have traversed a # root to leaf path if (not root): # update maximum Length and maximum Sum # according to the given conditions if (maxLen[0] < Len): maxLen[0] = Len maxSum[0] = Sum else if (maxLen[0]== Len and maxSum[0] < Sum): maxSum[0] = Sum return # recur for left subtree SumOfLongRootToLeafPath(root.left, Sum + root.data, Len + 1, maxLen, maxSum) # recur for right subtree SumOfLongRootToLeafPath(root.right, Sum + root.data, Len + 1, maxLen, maxSum) # utility function to find the Sum of nodes on# the longest path from root to leaf nodedef SumOfLongRootToLeafPathUtil(root): # if tree is NULL, then Sum is 0 if (not root): return 0 maxSum = [-999999999999] maxLen = [0] # finding the maximum Sum 'maxSum' for # the maximum Length root to leaf path SumOfLongRootToLeafPath(root, 0, 0, maxLen, maxSum) # required maximum Sum return maxSum[0] # Driver Codeif __name__ == '__main__': # binary tree formation root = getNode(4) # 4 root.left = getNode(2) # / \\ root.right = getNode(5) # 2 5 root.left.left = getNode(7) # / \\ / \\ root.left.right = getNode(1) # 7 1 2 3 root.right.left = getNode(2) # / root.right.right = getNode(3) # 6 root.left.right.left = getNode(6) print(\"Sum = \", SumOfLongRootToLeafPathUtil(root)) # This code is contributed by PranchalK",
"e": 8418,
"s": 6328,
"text": null
},
{
"code": "using System; // c# implementation to find the sum of nodes// on the longest path from root to leaf nodepublic class GFG{ // Node of a binary tree public class Node { public int data; public Node left, right; public Node(int data) { this.data = data; left = null; right = null; } } public static int maxLen; public static int maxSum; // function to find the sum of nodes on the // longest path from root to leaf node public static void sumOfLongRootToLeafPath(Node root, int sum, int len) { // if true, then we have traversed a // root to leaf path if (root == null) { // update maximum length and maximum sum // according to the given conditions if (maxLen < len) { maxLen = len; maxSum = sum; } else if (maxLen == len && maxSum < sum) { maxSum = sum; } return; } // recur for left subtree sumOfLongRootToLeafPath(root.left, sum + root.data, len + 1); sumOfLongRootToLeafPath(root.right, sum + root.data, len + 1); } // utility function to find the sum of nodes on // the longest path from root to leaf node public static int sumOfLongRootToLeafPathUtil(Node root) { // if tree is NULL, then sum is 0 if (root == null) { return 0; } maxSum = int.MinValue; maxLen = 0; // finding the maximum sum 'maxSum' for the // maximum length root to leaf path sumOfLongRootToLeafPath(root, 0, 0); // required maximum sum return maxSum; } // Driver program to test above public static void Main(string[] args) { // binary tree formation Node root = new Node(4); // 4 root.left = new Node(2); // / \\ root.right = new Node(5); // 2 5 root.left.left = new Node(7); // / \\ / \\ root.left.right = new Node(1); // 7 1 2 3 root.right.left = new Node(2); // / root.right.right = new Node(3); // 6 root.left.right.left = new Node(6); Console.WriteLine(\"Sum = \" + sumOfLongRootToLeafPathUtil(root)); }} // This code is contributed by Shrikant13",
"e": 10778,
"s": 8418,
"text": null
},
{
"code": "<script>// javascript implementation to find the sum of nodes// on the longest path from root to leaf node // Node of a binary tree class Node { constructor(val) { this.data = val; this.left = null; this.right = null; } } var maxLen; var maxSum; // function to find the sum of nodes on the // longest path from root to leaf node function sumOfLongRootToLeafPath(root , sum, len) { // if true, then we have traversed a // root to leaf path if (root == null) { // update maximum length and maximum sum // according to the given conditions if (maxLen < len) { maxLen = len; maxSum = sum; } else if (maxLen == len && maxSum < sum) maxSum = sum; return; } // recur for left subtree sumOfLongRootToLeafPath(root.left, sum + root.data, len + 1); sumOfLongRootToLeafPath(root.right, sum + root.data, len + 1); } // utility function to find the sum of nodes on // the longest path from root to leaf node function sumOfLongRootToLeafPathUtil(root) { // if tree is NULL, then sum is 0 if (root == null) return 0; maxSum = Number.MIN_VALUE; maxLen = 0; // finding the maximum sum 'maxSum' for the // maximum length root to leaf path sumOfLongRootToLeafPath(root, 0, 0); // required maximum sum return maxSum; } // Driver program to test above // binary tree formation var root = new Node(4); /* 4 */ root.left = new Node(2); /* / \\ */ root.right = new Node(5); /* 2 5 */ root.left.left = new Node(7); /* / \\ / \\ */ root.left.right = new Node(1); /* 7 1 2 3 */ root.right.left = new Node(2); /* / */ root.right.right = new Node(3); /* 6 */ root.left.right.left = new Node(6); document.write( \"Sum = \" + sumOfLongRootToLeafPathUtil(root)); // This code is contributed by gauravrajput1</script>",
"e": 13212,
"s": 10778,
"text": null
},
{
"code": null,
"e": 13221,
"s": 13212,
"text": "Sum = 13"
},
{
"code": null,
"e": 13244,
"s": 13221,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 13290,
"s": 13244,
"text": "Another Approach: Using level order traversal"
},
{
"code": null,
"e": 13588,
"s": 13290,
"text": "Create a structure containing the current Node, level and sum in the path.Push the root element with level 0 and sum as the root’s data.Pop the front element and update the maximum level sum and maximum level if needed.Push the left and right nodes if exists.Do the same for all the nodes in tree."
},
{
"code": null,
"e": 13663,
"s": 13588,
"text": "Create a structure containing the current Node, level and sum in the path."
},
{
"code": null,
"e": 13726,
"s": 13663,
"text": "Push the root element with level 0 and sum as the root’s data."
},
{
"code": null,
"e": 13810,
"s": 13726,
"text": "Pop the front element and update the maximum level sum and maximum level if needed."
},
{
"code": null,
"e": 13851,
"s": 13810,
"text": "Push the left and right nodes if exists."
},
{
"code": null,
"e": 13890,
"s": 13851,
"text": "Do the same for all the nodes in tree."
},
{
"code": null,
"e": 13894,
"s": 13890,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>using namespace std; //Building a tree node having left and right pointers set to null initiallystruct Node{ Node* left; Node* right; int data; //constructor to set the data of the newly created tree node Node(int element){ data = element; this->left = nullptr; this->right = nullptr; }}; int longestPathLeaf(Node* root){ /* structure to store current Node,it's level and sum in the path*/ struct Element{ Node* data; int level; int sum; }; /* maxSumLevel stores maximum sum so far in the path maxLevel stores maximum level so far */ int maxSumLevel = root->data,maxLevel = 0; /* queue to implement level order traversal */ list<Element> que; Element e; /* Each element variable stores the current Node, it's level, sum in the path */ e.data = root; e.level = 0; e.sum = root->data; /* push the root element*/ que.push_back(e); /* do level order traversal on the tree*/ while(!que.empty()){ Element front = que.front(); Node* curr = front.data; que.pop_front(); /* if the level of current front element is greater than the maxLevel so far then update maxSum*/ if(front.level > maxLevel){ maxSumLevel = front.sum; maxLevel = front.level; } /* if another path competes then update if the sum is greater than the previous path of same height*/ else if(front.level == maxLevel && front.sum > maxSumLevel) maxSumLevel = front.sum; /* push the left element if exists*/ if(curr->left){ e.data = curr->left; e.sum = e.data->data; e.sum += front.sum; e.level = front.level+1; que.push_back(e); } /*push the right element if exists*/ if(curr->right){ e.data = curr->right; e.sum = e.data->data; e.sum += front.sum; e.level = front.level+1; que.push_back(e); } } /*return the answer*/ return maxSumLevel;}//Helper functionint main() { Node* root = new Node(4); root->left = new Node(2); root->right = new Node(5); root->left->left = new Node(7); root->left->right = new Node(1); root->right->left = new Node(2); root->right->right = new Node(3); root->left->right->left = new Node(6); cout << longestPathLeaf(root) << \"\\n\"; return 0;}",
"e": 16221,
"s": 13894,
"text": null
},
{
"code": null,
"e": 16224,
"s": 16221,
"text": "13"
},
{
"code": null,
"e": 16267,
"s": 16224,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 16295,
"s": 16267,
"text": "Contributed by Manjukrishna"
},
{
"code": null,
"e": 16587,
"s": 16295,
"text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=O9jsfsa4idU\" 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": 17009,
"s": 16587,
"text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 17021,
"s": 17009,
"text": "shrikanth13"
},
{
"code": null,
"e": 17037,
"s": 17021,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 17050,
"s": 17037,
"text": "ManjuKrishna"
},
{
"code": null,
"e": 17064,
"s": 17050,
"text": "GauravRajput1"
},
{
"code": null,
"e": 17081,
"s": 17064,
"text": "surinderdawra388"
},
{
"code": null,
"e": 17091,
"s": 17081,
"text": "Traversal"
},
{
"code": null,
"e": 17096,
"s": 17091,
"text": "Tree"
},
{
"code": null,
"e": 17106,
"s": 17096,
"text": "Traversal"
},
{
"code": null,
"e": 17111,
"s": 17106,
"text": "Tree"
}
] |
TensorFlow - Convolutional Neural Networks | After understanding machine-learning concepts, we can now shift our focus to deep learning concepts. Deep learning is a division of machine learning and is considered as a crucial step taken by researchers in recent decades. The examples of deep learning implementation include applications like image recognition and speech recognition.
Following are the two important types of deep neural networks −
Convolutional Neural Networks
Recurrent Neural Networks
In this chapter, we will focus on the CNN, Convolutional Neural Networks.
Convolutional Neural networks are designed to process data through multiple layers of arrays. This type of neural networks is used in applications like image recognition or face recognition. The primary difference between CNN and any other ordinary neural network is that CNN takes input as a two-dimensional array and operates directly on the images rather than focusing on feature extraction which other neural networks focus on.
The dominant approach of CNN includes solutions for problems of recognition. Top companies like Google and Facebook have invested in research and development towards recognition projects to get activities done with greater speed.
A convolutional neural network uses three basic ideas −
Local respective fields
Convolution
Pooling
Let us understand these ideas in detail.
CNN utilizes spatial correlations that exist within the input data. Each concurrent layer of a neural network connects some input neurons. This specific region is called local receptive field. Local receptive field focusses on the hidden neurons. The hidden neurons process the input data inside the mentioned field not realizing the changes outside the specific boundary.
Following is a diagram representation of generating local respective fields −
If we observe the above representation, each connection learns a weight of the hidden neuron with an associated connection with movement from one layer to another. Here, individual neurons perform a shift from time to time. This process is called “convolution”.
The mapping of connections from the input layer to the hidden feature map is defined as “shared weights” and bias included is called “shared bias”.
CNN or convolutional neural networks use pooling layers, which are the layers, positioned immediately after CNN declaration. It takes the input from the user as a feature map that comes out of convolutional networks and prepares a condensed feature map. Pooling layers helps in creating layers with neurons of previous layers.
In this section, we will learn about the TensorFlow implementation of CNN. The steps,which require the execution and proper dimension of the entire network, are as shown below −
Step 1 − Include the necessary modules for TensorFlow and the data set modules, which are needed to compute the CNN model.
import tensorflow as tf
import numpy as np
from tensorflow.examples.tutorials.mnist import input_data
Step 2 − Declare a function called run_cnn(), which includes various parameters and optimization variables with declaration of data placeholders. These optimization variables will declare the training pattern.
def run_cnn():
mnist = input_data.read_data_sets("MNIST_data/", one_hot = True)
learning_rate = 0.0001
epochs = 10
batch_size = 50
Step 3 − In this step, we will declare the training data placeholders with input parameters - for 28 x 28 pixels = 784. This is the flattened image data that is drawn from mnist.train.nextbatch().
We can reshape the tensor according to our requirements. The first value (-1) tells function to dynamically shape that dimension based on the amount of data passed to it. The two middle dimensions are set to the image size (i.e. 28 x 28).
x = tf.placeholder(tf.float32, [None, 784])
x_shaped = tf.reshape(x, [-1, 28, 28, 1])
y = tf.placeholder(tf.float32, [None, 10])
Step 4 − Now it is important to create some convolutional layers −
layer1 = create_new_conv_layer(x_shaped, 1, 32, [5, 5], [2, 2], name = 'layer1')
layer2 = create_new_conv_layer(layer1, 32, 64, [5, 5], [2, 2], name = 'layer2')
Step 5 − Let us flatten the output ready for the fully connected output stage - after two layers of stride 2 pooling with the dimensions of 28 x 28, to dimension of 14 x 14 or minimum 7 x 7 x,y co-ordinates, but with 64 output channels. To create the fully connected with "dense" layer, the new shape needs to be [-1, 7 x 7 x 64]. We can set up some weights and bias values for this layer, then activate with ReLU.
flattened = tf.reshape(layer2, [-1, 7 * 7 * 64])
wd1 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1000], stddev = 0.03), name = 'wd1')
bd1 = tf.Variable(tf.truncated_normal([1000], stddev = 0.01), name = 'bd1')
dense_layer1 = tf.matmul(flattened, wd1) + bd1
dense_layer1 = tf.nn.relu(dense_layer1)
Step 6 − Another layer with specific softmax activations with the required optimizer defines the accuracy assessment, which makes the setup of initialization operator.
wd2 = tf.Variable(tf.truncated_normal([1000, 10], stddev = 0.03), name = 'wd2')
bd2 = tf.Variable(tf.truncated_normal([10], stddev = 0.01), name = 'bd2')
dense_layer2 = tf.matmul(dense_layer1, wd2) + bd2
y_ = tf.nn.softmax(dense_layer2)
cross_entropy = tf.reduce_mean(
tf.nn.softmax_cross_entropy_with_logits(logits = dense_layer2, labels = y))
optimiser = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cross_entropy)
correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
init_op = tf.global_variables_initializer()
Step 7 − We should set up recording variables. This adds up a summary to store the accuracy of data.
tf.summary.scalar('accuracy', accuracy)
merged = tf.summary.merge_all()
writer = tf.summary.FileWriter('E:\TensorFlowProject')
with tf.Session() as sess:
sess.run(init_op)
total_batch = int(len(mnist.train.labels) / batch_size)
for epoch in range(epochs):
avg_cost = 0
for i in range(total_batch):
batch_x, batch_y = mnist.train.next_batch(batch_size = batch_size)
_, c = sess.run([optimiser, cross_entropy], feed_dict = {
x:batch_x, y: batch_y})
avg_cost += c / total_batch
test_acc = sess.run(accuracy, feed_dict = {x: mnist.test.images, y:
mnist.test.labels})
summary = sess.run(merged, feed_dict = {x: mnist.test.images, y:
mnist.test.labels})
writer.add_summary(summary, epoch)
print("\nTraining complete!")
writer.add_graph(sess.graph)
print(sess.run(accuracy, feed_dict = {x: mnist.test.images, y:
mnist.test.labels}))
def create_new_conv_layer(
input_data, num_input_channels, num_filters,filter_shape, pool_shape, name):
conv_filt_shape = [
filter_shape[0], filter_shape[1], num_input_channels, num_filters]
weights = tf.Variable(
tf.truncated_normal(conv_filt_shape, stddev = 0.03), name = name+'_W')
bias = tf.Variable(tf.truncated_normal([num_filters]), name = name+'_b')
#Out layer defines the output
out_layer =
tf.nn.conv2d(input_data, weights, [1, 1, 1, 1], padding = 'SAME')
out_layer += bias
out_layer = tf.nn.relu(out_layer)
ksize = [1, pool_shape[0], pool_shape[1], 1]
strides = [1, 2, 2, 1]
out_layer = tf.nn.max_pool(
out_layer, ksize = ksize, strides = strides, padding = 'SAME')
return out_layer
if __name__ == "__main__":
run_cnn()
Following is the output generated by the above code −
See @{tf.nn.softmax_cross_entropy_with_logits_v2}.
2018-09-19 17:22:58.802268: I
T:\src\github\tensorflow\tensorflow\core\platform\cpu_feature_guard.cc:140]
Your CPU supports instructions that this TensorFlow binary was not compiled to
use: AVX2
2018-09-19 17:25:41.522845: W
T:\src\github\tensorflow\tensorflow\core\framework\allocator.cc:101] Allocation
of 1003520000 exceeds 10% of system memory.
2018-09-19 17:25:44.630941: W
T:\src\github\tensorflow\tensorflow\core\framework\allocator.cc:101] Allocation
of 501760000 exceeds 10% of system memory.
Epoch: 1 cost = 0.676 test accuracy: 0.940
2018-09-19 17:26:51.987554: W
T:\src\github\tensorflow\tensorflow\core\framework\allocator.cc:101] Allocation
of 1003520000 exceeds 10% of system memory. | [
{
"code": null,
"e": 2787,
"s": 2449,
"text": "After understanding machine-learning concepts, we can now shift our focus to deep learning concepts. Deep learning is a division of machine learning and is considered as a crucial step taken by researchers in recent decades. The examples of deep learning implementation include applications like image recognition and speech recognition."
},
{
"code": null,
"e": 2851,
"s": 2787,
"text": "Following are the two important types of deep neural networks −"
},
{
"code": null,
"e": 2881,
"s": 2851,
"text": "Convolutional Neural Networks"
},
{
"code": null,
"e": 2907,
"s": 2881,
"text": "Recurrent Neural Networks"
},
{
"code": null,
"e": 2981,
"s": 2907,
"text": "In this chapter, we will focus on the CNN, Convolutional Neural Networks."
},
{
"code": null,
"e": 3413,
"s": 2981,
"text": "Convolutional Neural networks are designed to process data through multiple layers of arrays. This type of neural networks is used in applications like image recognition or face recognition. The primary difference between CNN and any other ordinary neural network is that CNN takes input as a two-dimensional array and operates directly on the images rather than focusing on feature extraction which other neural networks focus on."
},
{
"code": null,
"e": 3643,
"s": 3413,
"text": "The dominant approach of CNN includes solutions for problems of recognition. Top companies like Google and Facebook have invested in research and development towards recognition projects to get activities done with greater speed."
},
{
"code": null,
"e": 3699,
"s": 3643,
"text": "A convolutional neural network uses three basic ideas −"
},
{
"code": null,
"e": 3723,
"s": 3699,
"text": "Local respective fields"
},
{
"code": null,
"e": 3735,
"s": 3723,
"text": "Convolution"
},
{
"code": null,
"e": 3743,
"s": 3735,
"text": "Pooling"
},
{
"code": null,
"e": 3784,
"s": 3743,
"text": "Let us understand these ideas in detail."
},
{
"code": null,
"e": 4157,
"s": 3784,
"text": "CNN utilizes spatial correlations that exist within the input data. Each concurrent layer of a neural network connects some input neurons. This specific region is called local receptive field. Local receptive field focusses on the hidden neurons. The hidden neurons process the input data inside the mentioned field not realizing the changes outside the specific boundary."
},
{
"code": null,
"e": 4235,
"s": 4157,
"text": "Following is a diagram representation of generating local respective fields −"
},
{
"code": null,
"e": 4497,
"s": 4235,
"text": "If we observe the above representation, each connection learns a weight of the hidden neuron with an associated connection with movement from one layer to another. Here, individual neurons perform a shift from time to time. This process is called “convolution”."
},
{
"code": null,
"e": 4645,
"s": 4497,
"text": "The mapping of connections from the input layer to the hidden feature map is defined as “shared weights” and bias included is called “shared bias”."
},
{
"code": null,
"e": 4972,
"s": 4645,
"text": "CNN or convolutional neural networks use pooling layers, which are the layers, positioned immediately after CNN declaration. It takes the input from the user as a feature map that comes out of convolutional networks and prepares a condensed feature map. Pooling layers helps in creating layers with neurons of previous layers."
},
{
"code": null,
"e": 5150,
"s": 4972,
"text": "In this section, we will learn about the TensorFlow implementation of CNN. The steps,which require the execution and proper dimension of the entire network, are as shown below −"
},
{
"code": null,
"e": 5273,
"s": 5150,
"text": "Step 1 − Include the necessary modules for TensorFlow and the data set modules, which are needed to compute the CNN model."
},
{
"code": null,
"e": 5376,
"s": 5273,
"text": "import tensorflow as tf\nimport numpy as np\nfrom tensorflow.examples.tutorials.mnist import input_data\n"
},
{
"code": null,
"e": 5586,
"s": 5376,
"text": "Step 2 − Declare a function called run_cnn(), which includes various parameters and optimization variables with declaration of data placeholders. These optimization variables will declare the training pattern."
},
{
"code": null,
"e": 5730,
"s": 5586,
"text": "def run_cnn():\n mnist = input_data.read_data_sets(\"MNIST_data/\", one_hot = True)\n learning_rate = 0.0001\n epochs = 10\n batch_size = 50\n"
},
{
"code": null,
"e": 5927,
"s": 5730,
"text": "Step 3 − In this step, we will declare the training data placeholders with input parameters - for 28 x 28 pixels = 784. This is the flattened image data that is drawn from mnist.train.nextbatch()."
},
{
"code": null,
"e": 6166,
"s": 5927,
"text": "We can reshape the tensor according to our requirements. The first value (-1) tells function to dynamically shape that dimension based on the amount of data passed to it. The two middle dimensions are set to the image size (i.e. 28 x 28)."
},
{
"code": null,
"e": 6296,
"s": 6166,
"text": "x = tf.placeholder(tf.float32, [None, 784])\nx_shaped = tf.reshape(x, [-1, 28, 28, 1])\ny = tf.placeholder(tf.float32, [None, 10])\n"
},
{
"code": null,
"e": 6363,
"s": 6296,
"text": "Step 4 − Now it is important to create some convolutional layers −"
},
{
"code": null,
"e": 6525,
"s": 6363,
"text": "layer1 = create_new_conv_layer(x_shaped, 1, 32, [5, 5], [2, 2], name = 'layer1')\nlayer2 = create_new_conv_layer(layer1, 32, 64, [5, 5], [2, 2], name = 'layer2')\n"
},
{
"code": null,
"e": 6940,
"s": 6525,
"text": "Step 5 − Let us flatten the output ready for the fully connected output stage - after two layers of stride 2 pooling with the dimensions of 28 x 28, to dimension of 14 x 14 or minimum 7 x 7 x,y co-ordinates, but with 64 output channels. To create the fully connected with \"dense\" layer, the new shape needs to be [-1, 7 x 7 x 64]. We can set up some weights and bias values for this layer, then activate with ReLU."
},
{
"code": null,
"e": 7242,
"s": 6940,
"text": "flattened = tf.reshape(layer2, [-1, 7 * 7 * 64])\n\nwd1 = tf.Variable(tf.truncated_normal([7 * 7 * 64, 1000], stddev = 0.03), name = 'wd1')\nbd1 = tf.Variable(tf.truncated_normal([1000], stddev = 0.01), name = 'bd1')\n\ndense_layer1 = tf.matmul(flattened, wd1) + bd1\ndense_layer1 = tf.nn.relu(dense_layer1)"
},
{
"code": null,
"e": 7410,
"s": 7242,
"text": "Step 6 − Another layer with specific softmax activations with the required optimizer defines the accuracy assessment, which makes the setup of initialization operator."
},
{
"code": null,
"e": 8029,
"s": 7410,
"text": "wd2 = tf.Variable(tf.truncated_normal([1000, 10], stddev = 0.03), name = 'wd2')\nbd2 = tf.Variable(tf.truncated_normal([10], stddev = 0.01), name = 'bd2')\n\ndense_layer2 = tf.matmul(dense_layer1, wd2) + bd2\ny_ = tf.nn.softmax(dense_layer2)\n\ncross_entropy = tf.reduce_mean(\n tf.nn.softmax_cross_entropy_with_logits(logits = dense_layer2, labels = y))\n\noptimiser = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(cross_entropy)\n\ncorrect_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n\ninit_op = tf.global_variables_initializer()"
},
{
"code": null,
"e": 8130,
"s": 8029,
"text": "Step 7 − We should set up recording variables. This adds up a summary to store the accuracy of data."
},
{
"code": null,
"e": 9919,
"s": 8130,
"text": "tf.summary.scalar('accuracy', accuracy)\n merged = tf.summary.merge_all()\n writer = tf.summary.FileWriter('E:\\TensorFlowProject')\n \n with tf.Session() as sess:\n sess.run(init_op)\n total_batch = int(len(mnist.train.labels) / batch_size)\n \n for epoch in range(epochs):\n avg_cost = 0\n for i in range(total_batch):\n batch_x, batch_y = mnist.train.next_batch(batch_size = batch_size)\n _, c = sess.run([optimiser, cross_entropy], feed_dict = {\n x:batch_x, y: batch_y})\n avg_cost += c / total_batch\n test_acc = sess.run(accuracy, feed_dict = {x: mnist.test.images, y:\n mnist.test.labels})\n summary = sess.run(merged, feed_dict = {x: mnist.test.images, y:\n mnist.test.labels})\n writer.add_summary(summary, epoch)\n\n print(\"\\nTraining complete!\")\n writer.add_graph(sess.graph)\n print(sess.run(accuracy, feed_dict = {x: mnist.test.images, y:\n mnist.test.labels}))\n\ndef create_new_conv_layer(\n input_data, num_input_channels, num_filters,filter_shape, pool_shape, name):\n\n conv_filt_shape = [\n filter_shape[0], filter_shape[1], num_input_channels, num_filters]\n\n weights = tf.Variable(\n tf.truncated_normal(conv_filt_shape, stddev = 0.03), name = name+'_W')\n bias = tf.Variable(tf.truncated_normal([num_filters]), name = name+'_b')\n\n#Out layer defines the output\n out_layer =\n tf.nn.conv2d(input_data, weights, [1, 1, 1, 1], padding = 'SAME')\n\n out_layer += bias\n out_layer = tf.nn.relu(out_layer)\n ksize = [1, pool_shape[0], pool_shape[1], 1]\n strides = [1, 2, 2, 1]\n out_layer = tf.nn.max_pool(\n out_layer, ksize = ksize, strides = strides, padding = 'SAME')\n\n return out_layer\n\nif __name__ == \"__main__\":\nrun_cnn()"
},
{
"code": null,
"e": 9973,
"s": 9919,
"text": "Following is the output generated by the above code −"
}
] |
Styling Active Router Link in Angular | 17 Jun, 2021
Styling the active router link in angular allows the user to differentiate between the active router link and inactive router links. Angular provides a special mechanism to work with active router links.
Approach:
Create the Angular app to be used.
Create the header component that contains the navigation links.
Then apply the “routerLinkActive” on each router link and provide the CSS class to this property. Here we have created the “active” class in CSS file.
Provide the { exact : true } to the root route to avoid multiple active router links.
Syntax:
<a routerLink="/" routerLinkActive="active" >Home</a>
Example: We have created the header component with specified routes.
header.component.html
<span> <ul> <li><a routerLink="/" routerLinkActive="active"> Home </a></li> <li><a routerLink="/products" routerLinkActive="active">Products </a></li> <li><a routerLink="/about" routerLinkActive="active">About Us </a></li> <li><a routerLink="/contact" routerLinkActive="active">Contact Us </a></li> </ul></span><router-outlet></router-outlet>
Here we have provided the “routerLinkActive” which is routing functionality that automatically activate the current route, and we have to provide the CSS class as well. Here in routerLinkActive = “active” active is a CSS class that automatically applied to the activated route.
header.component.css
.active{ background: 'white'}
But here, it still causes an issue our Home route is always active even we navigate to some other route the reason behind this is the way “routerLinkActive” works. The home route works on “localhost:4200/” and other routes are “localhost:4200/about” so “routerLinkActive” finds “localhost:4200/” inside every other route and the Home router link is always active to deal with this angular provide another directive called routerLinkActiveOptions.
Updated
header.component.htm
<span> <ul> <li><a routerLink="/" routerLinkActive="active" [routerLinkActiveOptions]={exact:true}>Home </a></li> <li><a routerLink="/products" routerLinkActive="active">Products </a></li> <li><a routerLink="/about" routerLinkActive="active">About Us </a></li> <li><a routerLink="/contact" routerLinkActive="active">Contact Us </a></li> </ul></span><router-outlet></router-outlet>
So routerLinkActiveOptions allow only the exact path match as an active route for the Home component.
Output:
AngularJS-Questions
AngularJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Auth Guards in Angular 9/10/11
Routing in Angular 9/10
What is AOT and JIT Compiler in Angular ?
Angular PrimeNG Dropdown Component
How to set focus on input field automatically on page load in AngularJS ?
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": "\n17 Jun, 2021"
},
{
"code": null,
"e": 233,
"s": 28,
"text": "Styling the active router link in angular allows the user to differentiate between the active router link and inactive router links. Angular provides a special mechanism to work with active router links. "
},
{
"code": null,
"e": 244,
"s": 233,
"text": "Approach: "
},
{
"code": null,
"e": 279,
"s": 244,
"text": "Create the Angular app to be used."
},
{
"code": null,
"e": 343,
"s": 279,
"text": "Create the header component that contains the navigation links."
},
{
"code": null,
"e": 494,
"s": 343,
"text": "Then apply the “routerLinkActive” on each router link and provide the CSS class to this property. Here we have created the “active” class in CSS file."
},
{
"code": null,
"e": 580,
"s": 494,
"text": "Provide the { exact : true } to the root route to avoid multiple active router links."
},
{
"code": null,
"e": 588,
"s": 580,
"text": "Syntax:"
},
{
"code": null,
"e": 642,
"s": 588,
"text": "<a routerLink=\"/\" routerLinkActive=\"active\" >Home</a>"
},
{
"code": null,
"e": 713,
"s": 644,
"text": "Example: We have created the header component with specified routes."
},
{
"code": null,
"e": 735,
"s": 713,
"text": "header.component.html"
},
{
"code": "<span> <ul> <li><a routerLink=\"/\" routerLinkActive=\"active\"> Home </a></li> <li><a routerLink=\"/products\" routerLinkActive=\"active\">Products </a></li> <li><a routerLink=\"/about\" routerLinkActive=\"active\">About Us </a></li> <li><a routerLink=\"/contact\" routerLinkActive=\"active\">Contact Us </a></li> </ul></span><router-outlet></router-outlet>",
"e": 1187,
"s": 735,
"text": null
},
{
"code": null,
"e": 1465,
"s": 1187,
"text": "Here we have provided the “routerLinkActive” which is routing functionality that automatically activate the current route, and we have to provide the CSS class as well. Here in routerLinkActive = “active” active is a CSS class that automatically applied to the activated route."
},
{
"code": null,
"e": 1486,
"s": 1465,
"text": "header.component.css"
},
{
"code": ".active{ background: 'white'}",
"e": 1519,
"s": 1486,
"text": null
},
{
"code": null,
"e": 1966,
"s": 1519,
"text": "But here, it still causes an issue our Home route is always active even we navigate to some other route the reason behind this is the way “routerLinkActive” works. The home route works on “localhost:4200/” and other routes are “localhost:4200/about” so “routerLinkActive” finds “localhost:4200/” inside every other route and the Home router link is always active to deal with this angular provide another directive called routerLinkActiveOptions."
},
{
"code": null,
"e": 1974,
"s": 1966,
"text": "Updated"
},
{
"code": null,
"e": 1995,
"s": 1974,
"text": "header.component.htm"
},
{
"code": "<span> <ul> <li><a routerLink=\"/\" routerLinkActive=\"active\" [routerLinkActiveOptions]={exact:true}>Home </a></li> <li><a routerLink=\"/products\" routerLinkActive=\"active\">Products </a></li> <li><a routerLink=\"/about\" routerLinkActive=\"active\">About Us </a></li> <li><a routerLink=\"/contact\" routerLinkActive=\"active\">Contact Us </a></li> </ul></span><router-outlet></router-outlet>",
"e": 2486,
"s": 1995,
"text": null
},
{
"code": null,
"e": 2588,
"s": 2486,
"text": "So routerLinkActiveOptions allow only the exact path match as an active route for the Home component."
},
{
"code": null,
"e": 2596,
"s": 2588,
"text": "Output:"
},
{
"code": null,
"e": 2616,
"s": 2596,
"text": "AngularJS-Questions"
},
{
"code": null,
"e": 2626,
"s": 2616,
"text": "AngularJS"
},
{
"code": null,
"e": 2643,
"s": 2626,
"text": "Web Technologies"
},
{
"code": null,
"e": 2741,
"s": 2643,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2772,
"s": 2741,
"text": "Auth Guards in Angular 9/10/11"
},
{
"code": null,
"e": 2796,
"s": 2772,
"text": "Routing in Angular 9/10"
},
{
"code": null,
"e": 2838,
"s": 2796,
"text": "What is AOT and JIT Compiler in Angular ?"
},
{
"code": null,
"e": 2873,
"s": 2838,
"text": "Angular PrimeNG Dropdown Component"
},
{
"code": null,
"e": 2947,
"s": 2873,
"text": "How to set focus on input field automatically on page load in AngularJS ?"
},
{
"code": null,
"e": 3009,
"s": 2947,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 3042,
"s": 3009,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 3103,
"s": 3042,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3153,
"s": 3103,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Function Overloading vs Function Overriding in C++ | 28 Jun, 2021
Function Overloading (achieved at compile time)
It provides multiple definitions of the function by changing signature i.e changing number of parameters, change datatype of parameters, return type doesn’t play anyrole.
It can be done in base as well as derived class.
Example:
void area(int a);
void area(int a, int b);
CPP
// CPP program to illustrate// Function Overloading#include <iostream>using namespace std; // overloaded functionsvoid test(int);void test(float);void test(int, float); int main(){ int a = 5; float b = 5.5; // Overloaded functions // with different type and // number of parameters test(a); test(b); test(a, b); return 0;} // Method 1void test(int var){ cout << "Integer number: " << var << endl;} // Method 2void test(float var){ cout << "Float number: "<< var << endl;} // Method 3void test(int var1, float var2){ cout << "Integer number: " << var1; cout << " and float number:" << var2;}
Output:
Integer number: 5
Float number: 5.5
Integer number: 5 and float number: 5.5
Function Overriding (achieved at run time)It is the redefinition of base class function in its derived class with same signature i.e return type and parameters.
It can only be done in derived class.
Example:
Class a
{
public:
virtual void display(){ cout << "hello"; }
};
Class b:public a
{
public:
void display(){ cout << "bye";}
};
CPP
// CPP program to illustrate// Function Overriding#include<iostream>using namespace std; class BaseClass{public: virtual void Display() { cout << "\nThis is Display() method" " of BaseClass"; } void Show() { cout << "\nThis is Show() method " "of BaseClass"; }}; class DerivedClass : public BaseClass{public: // Overriding method - new working of // base class's display method void Display() { cout << "\nThis is Display() method" " of DerivedClass"; }}; // Driver codeint main(){ DerivedClass dr; BaseClass &bs = dr; bs.Display(); dr.Show();}
Output:
This is Display() method of DerivedClass
This is Show() method of BaseClass
Function Overloading VS Function Overriding:
Inheritance: Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance.Function Signature: Overloaded functions must differ in function signature ie either number of parameters or type of parameters should differ. In overriding, function signatures must be same.Scope of functions: Overridden functions are in different scopes; whereas overloaded functions are in same scope.Behavior of functions: Overriding is needed when derived class function has to do some added or different job than the base class function. Overloading is used to have same name functions which behave differently depending upon parameters passed to them.
Inheritance: Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance.
Function Signature: Overloaded functions must differ in function signature ie either number of parameters or type of parameters should differ. In overriding, function signatures must be same.
Scope of functions: Overridden functions are in different scopes; whereas overloaded functions are in same scope.
Behavior of functions: Overriding is needed when derived class function has to do some added or different job than the base class function. Overloading is used to have same name functions which behave differently depending upon parameters passed to them.
This article is contributed by Mazhar Mik and Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
d19ce158
CPP-Functions
cpp-overloading
C++
Difference Between
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Priority Queue in C++ Standard Template Library (STL)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
Substring in C++
unordered_map in C++ STL
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 100,
"s": 52,
"text": "Function Overloading (achieved at compile time)"
},
{
"code": null,
"e": 272,
"s": 100,
"text": "It provides multiple definitions of the function by changing signature i.e changing number of parameters, change datatype of parameters, return type doesn’t play anyrole. "
},
{
"code": null,
"e": 321,
"s": 272,
"text": "It can be done in base as well as derived class."
},
{
"code": null,
"e": 332,
"s": 321,
"text": "Example: "
},
{
"code": null,
"e": 376,
"s": 332,
"text": "void area(int a);\nvoid area(int a, int b); "
},
{
"code": null,
"e": 382,
"s": 378,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Function Overloading#include <iostream>using namespace std; // overloaded functionsvoid test(int);void test(float);void test(int, float); int main(){ int a = 5; float b = 5.5; // Overloaded functions // with different type and // number of parameters test(a); test(b); test(a, b); return 0;} // Method 1void test(int var){ cout << \"Integer number: \" << var << endl;} // Method 2void test(float var){ cout << \"Float number: \"<< var << endl;} // Method 3void test(int var1, float var2){ cout << \"Integer number: \" << var1; cout << \" and float number:\" << var2;}",
"e": 1014,
"s": 382,
"text": null
},
{
"code": null,
"e": 1024,
"s": 1014,
"text": "Output: "
},
{
"code": null,
"e": 1100,
"s": 1024,
"text": "Integer number: 5\nFloat number: 5.5\nInteger number: 5 and float number: 5.5"
},
{
"code": null,
"e": 1263,
"s": 1100,
"text": "Function Overriding (achieved at run time)It is the redefinition of base class function in its derived class with same signature i.e return type and parameters. "
},
{
"code": null,
"e": 1301,
"s": 1263,
"text": "It can only be done in derived class."
},
{
"code": null,
"e": 1310,
"s": 1301,
"text": "Example:"
},
{
"code": null,
"e": 1452,
"s": 1310,
"text": "Class a\n{\npublic: \n virtual void display(){ cout << \"hello\"; }\n};\n\nClass b:public a\n{\npublic: \n void display(){ cout << \"bye\";}\n};"
},
{
"code": null,
"e": 1458,
"s": 1454,
"text": "CPP"
},
{
"code": "// CPP program to illustrate// Function Overriding#include<iostream>using namespace std; class BaseClass{public: virtual void Display() { cout << \"\\nThis is Display() method\" \" of BaseClass\"; } void Show() { cout << \"\\nThis is Show() method \" \"of BaseClass\"; }}; class DerivedClass : public BaseClass{public: // Overriding method - new working of // base class's display method void Display() { cout << \"\\nThis is Display() method\" \" of DerivedClass\"; }}; // Driver codeint main(){ DerivedClass dr; BaseClass &bs = dr; bs.Display(); dr.Show();}",
"e": 2112,
"s": 1458,
"text": null
},
{
"code": null,
"e": 2122,
"s": 2112,
"text": "Output: "
},
{
"code": null,
"e": 2198,
"s": 2122,
"text": "This is Display() method of DerivedClass\nThis is Show() method of BaseClass"
},
{
"code": null,
"e": 2245,
"s": 2200,
"text": "Function Overloading VS Function Overriding:"
},
{
"code": null,
"e": 2938,
"s": 2245,
"text": "Inheritance: Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance.Function Signature: Overloaded functions must differ in function signature ie either number of parameters or type of parameters should differ. In overriding, function signatures must be same.Scope of functions: Overridden functions are in different scopes; whereas overloaded functions are in same scope.Behavior of functions: Overriding is needed when derived class function has to do some added or different job than the base class function. Overloading is used to have same name functions which behave differently depending upon parameters passed to them."
},
{
"code": null,
"e": 3073,
"s": 2938,
"text": "Inheritance: Overriding of functions occurs when one class is inherited from another class. Overloading can occur without inheritance."
},
{
"code": null,
"e": 3265,
"s": 3073,
"text": "Function Signature: Overloaded functions must differ in function signature ie either number of parameters or type of parameters should differ. In overriding, function signatures must be same."
},
{
"code": null,
"e": 3379,
"s": 3265,
"text": "Scope of functions: Overridden functions are in different scopes; whereas overloaded functions are in same scope."
},
{
"code": null,
"e": 3634,
"s": 3379,
"text": "Behavior of functions: Overriding is needed when derived class function has to do some added or different job than the base class function. Overloading is used to have same name functions which behave differently depending upon parameters passed to them."
},
{
"code": null,
"e": 4069,
"s": 3634,
"text": "This article is contributed by Mazhar Mik and Yash Singla. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4078,
"s": 4069,
"text": "d19ce158"
},
{
"code": null,
"e": 4092,
"s": 4078,
"text": "CPP-Functions"
},
{
"code": null,
"e": 4108,
"s": 4092,
"text": "cpp-overloading"
},
{
"code": null,
"e": 4112,
"s": 4108,
"text": "C++"
},
{
"code": null,
"e": 4131,
"s": 4112,
"text": "Difference Between"
},
{
"code": null,
"e": 4135,
"s": 4131,
"text": "CPP"
},
{
"code": null,
"e": 4233,
"s": 4135,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4287,
"s": 4233,
"text": "Priority Queue in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4330,
"s": 4287,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4364,
"s": 4330,
"text": "vector erase() and clear() in C++"
},
{
"code": null,
"e": 4381,
"s": 4364,
"text": "Substring in C++"
},
{
"code": null,
"e": 4406,
"s": 4381,
"text": "unordered_map in C++ STL"
},
{
"code": null,
"e": 4446,
"s": 4406,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 4477,
"s": 4446,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 4538,
"s": 4477,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 4606,
"s": 4538,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
D3.js nest() Function | 07 Jul, 2020
D3.js is a library built with javascript and particularly used for data visualization. D3.nest() function is used to group the data as groupBy clause does in SQL. It groups the data on the basis of keys and values.
Syntax:
d3.nest()
Parameters: This function does not accept any parameters.
Return Value: It returns the object with several properties as entries, keys, values, map, sort.
Example 1: In this example, the data is to be grouped on the basis of key “manufactured” we can group the data on the basis of multiple keys as well.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script> <title> D3.js d3.nest() Function </title></head> <body> <script> var cars = [ { name: "car1", manufactured: "1950", model: "s51" }, { name: "car1", manufactured: "1950", model: "s51" }, { name: "car1", manufactured: "1951", model: "s50" }, { name: "car1", manufactured: "1951", model: "s50" }, ]; var groupedData = d3.nest() .key(function (d) { return d.manufactured; }) .entries(cars); console.log("ArrayData :", groupedData); console.log("ArrayData[0] :", groupedData[0]); console.log("ArrayData[1] :", groupedData[1]); </script></body> </html
Example 2: This example explains the grouping of data on the basis of multiple keys.
HTML
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" path1tent= "width=device-width, initial-scale=1.0"> <script src="https://d3js.org/d3.v4.min.js"> </script> <title> D3.js d3.nest() Function </title></head> <body> <script> var cars = [ { name: "car1", manufactured: "1950", model: "s51" }, { name: "car1", manufactured: "1950", model: "s51" }, { name: "car1", manufactured: "1951", model: "s50" }, { name: "car1", manufactured: "1951", model: "s50" }, ]; var groupedData = d3.nest() .key(function (d) { return d.manufactured; }) .key(function (d) { return d.model; }) .entries(cars); console.log("ArrayData :", groupedData); console.log("ArrayData[0] :", groupedData[0]); console.log("ArrayData[1] :", groupedData[1]); </script></body> </html>
D3.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jul, 2020"
},
{
"code": null,
"e": 243,
"s": 28,
"text": "D3.js is a library built with javascript and particularly used for data visualization. D3.nest() function is used to group the data as groupBy clause does in SQL. It groups the data on the basis of keys and values."
},
{
"code": null,
"e": 251,
"s": 243,
"text": "Syntax:"
},
{
"code": null,
"e": 261,
"s": 251,
"text": "d3.nest()"
},
{
"code": null,
"e": 319,
"s": 261,
"text": "Parameters: This function does not accept any parameters."
},
{
"code": null,
"e": 416,
"s": 319,
"text": "Return Value: It returns the object with several properties as entries, keys, values, map, sort."
},
{
"code": null,
"e": 566,
"s": 416,
"text": "Example 1: In this example, the data is to be grouped on the basis of key “manufactured” we can group the data on the basis of multiple keys as well."
},
{
"code": null,
"e": 571,
"s": 566,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <title> D3.js d3.nest() Function </title></head> <body> <script> var cars = [ { name: \"car1\", manufactured: \"1950\", model: \"s51\" }, { name: \"car1\", manufactured: \"1950\", model: \"s51\" }, { name: \"car1\", manufactured: \"1951\", model: \"s50\" }, { name: \"car1\", manufactured: \"1951\", model: \"s50\" }, ]; var groupedData = d3.nest() .key(function (d) { return d.manufactured; }) .entries(cars); console.log(\"ArrayData :\", groupedData); console.log(\"ArrayData[0] :\", groupedData[0]); console.log(\"ArrayData[1] :\", groupedData[1]); </script></body> </html",
"e": 1461,
"s": 571,
"text": null
},
{
"code": null,
"e": 1546,
"s": 1461,
"text": "Example 2: This example explains the grouping of data on the basis of multiple keys."
},
{
"code": null,
"e": 1551,
"s": 1546,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" path1tent= \"width=device-width, initial-scale=1.0\"> <script src=\"https://d3js.org/d3.v4.min.js\"> </script> <title> D3.js d3.nest() Function </title></head> <body> <script> var cars = [ { name: \"car1\", manufactured: \"1950\", model: \"s51\" }, { name: \"car1\", manufactured: \"1950\", model: \"s51\" }, { name: \"car1\", manufactured: \"1951\", model: \"s50\" }, { name: \"car1\", manufactured: \"1951\", model: \"s50\" }, ]; var groupedData = d3.nest() .key(function (d) { return d.manufactured; }) .key(function (d) { return d.model; }) .entries(cars); console.log(\"ArrayData :\", groupedData); console.log(\"ArrayData[0] :\", groupedData[0]); console.log(\"ArrayData[1] :\", groupedData[1]); </script></body> </html>",
"e": 2492,
"s": 1551,
"text": null
},
{
"code": null,
"e": 2498,
"s": 2492,
"text": "D3.js"
},
{
"code": null,
"e": 2509,
"s": 2498,
"text": "JavaScript"
},
{
"code": null,
"e": 2526,
"s": 2509,
"text": "Web Technologies"
}
] |
ReactJS – useReducer hook | This hook is a better alternative of the useState hook, as it is used when we want to attach a function along with handling the state or when we want to handle the state based on the previous values.
const [state, dispatch] = useReducer(reducer, initialArgs, init);
Reducer − The function to handle or update the state
Reducer − The function to handle or update the state
initialArgs − Iitial state
initialArgs − Iitial state
Init − To load the state lazily or when it is required
Init − To load the state lazily or when it is required
In this example, we will build a simple calculator using the useReducer hook which takes the input from the user and displays the result accordingly.
App.jsx
import React, { useReducer } from 'react';
const initialState = 0;
const reducer = (state, action) => {
switch (action) {
case 1:
return state + 1;
case 2:
return state + 2;
case 3:
return state + 3;
case 'Reset':
return 0;
default:
throw new Error('Error');
}
};
const App = () => {
const [ans, dispatch] = useReducer(reducer, initialState);
return (
<div>
<h2>{ans}</h2>
<button onClick={() => dispatch(1)}>Add 1</button>
<button onClick={() => dispatch(2)}>Add 2</button>
<button onClick={() => dispatch(3)}>Add 3</button>
<button onClick={() => dispatch('Reset')}>reset</button>
</div>
);
};
export default App;
In the above example, when the user clicks on any button then the action is dispatched which updates the state and displays the updated state accordingly.
This will produce the following result. | [
{
"code": null,
"e": 1387,
"s": 1187,
"text": "This hook is a better alternative of the useState hook, as it is used when we want to attach a function along with handling the state or when we want to handle the state based on the previous values."
},
{
"code": null,
"e": 1453,
"s": 1387,
"text": "const [state, dispatch] = useReducer(reducer, initialArgs, init);"
},
{
"code": null,
"e": 1506,
"s": 1453,
"text": "Reducer − The function to handle or update the state"
},
{
"code": null,
"e": 1559,
"s": 1506,
"text": "Reducer − The function to handle or update the state"
},
{
"code": null,
"e": 1586,
"s": 1559,
"text": "initialArgs − Iitial state"
},
{
"code": null,
"e": 1613,
"s": 1586,
"text": "initialArgs − Iitial state"
},
{
"code": null,
"e": 1668,
"s": 1613,
"text": "Init − To load the state lazily or when it is required"
},
{
"code": null,
"e": 1723,
"s": 1668,
"text": "Init − To load the state lazily or when it is required"
},
{
"code": null,
"e": 1873,
"s": 1723,
"text": "In this example, we will build a simple calculator using the useReducer hook which takes the input from the user and displays the result accordingly."
},
{
"code": null,
"e": 1881,
"s": 1873,
"text": "App.jsx"
},
{
"code": null,
"e": 2644,
"s": 1881,
"text": "import React, { useReducer } from 'react';\n\nconst initialState = 0;\n\nconst reducer = (state, action) => {\n switch (action) {\n case 1:\n return state + 1;\n case 2:\n return state + 2;\n case 3:\n return state + 3;\n case 'Reset':\n return 0;\n default:\n throw new Error('Error');\n }\n};\n\nconst App = () => {\n const [ans, dispatch] = useReducer(reducer, initialState);\n return (\n <div>\n <h2>{ans}</h2>\n <button onClick={() => dispatch(1)}>Add 1</button>\n <button onClick={() => dispatch(2)}>Add 2</button>\n <button onClick={() => dispatch(3)}>Add 3</button>\n <button onClick={() => dispatch('Reset')}>reset</button>\n </div>\n );\n};\nexport default App;"
},
{
"code": null,
"e": 2799,
"s": 2644,
"text": "In the above example, when the user clicks on any button then the action is dispatched which updates the state and displays the updated state accordingly."
},
{
"code": null,
"e": 2839,
"s": 2799,
"text": "This will produce the following result."
}
] |
TreeMap comparator() method in Java with Examples | 22 Nov, 2021
The comparator() method of java.util.TreeMap class is used to return the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.
--> java.util Package
--> TreeMap Class
--> comparator() Method
Syntax:
public Comparator comparator()
Return Type: This method returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.
Note: descendingIterator() method is natural ordering by default.
Example 1: For Natural ordering
Java
// Java program to Illustrate comparator() Method// for Natural Ordering (Descending Order) // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating an empty TreeMap by // creating object of NavigableMap NavigableMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Populating TreeMap // using put() method treemap.put(1, "one"); treemap.put(2, "two"); treemap.put(3, "three"); treemap.put(4, "four"); treemap.put(5, "five"); // Printing the TreeMap System.out.println("TreeMap: " + treemap); // Getting used Comparator in the map // using comparator() method Comparator comp = treemap.comparator(); // Printing the comparator value System.out.println("Comparator value: " + comp); } // Catch block to handle the exception catch (NullPointerException e) { // Display message if exception occurs System.out.println("Exception thrown : " + e); } }}
TreeMap: {1=one, 2=two, 3=three, 4=four, 5=five}
Comparator value: null
Example 2: For Reverse ordering
Java
// Java program to demonstrate comparator() Method// for Reverse Ordering // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating an empty TreeMap NavigableMap<Integer, String> treemap = new TreeMap<Integer, String>( Collections.reverseOrder()); // Populating TreeMap // using put() method treemap.put(1, "one"); treemap.put(2, "two"); treemap.put(3, "three"); treemap.put(4, "four"); treemap.put(5, "five"); // Printing the TreeMap System.out.println("TreeMap: " + treemap); // Getting used Comparator in the map // using comparator() method Comparator comp = treemap.comparator(); // Printing the comparator value System.out.println("Comparator value: " + comp); } // Catch block to handle the exceptions catch (NullPointerException e) { // Display message if exception occurs System.out.println("Exception thrown : " + e); } }}
TreeMap: {5=five, 4=four, 3=three, 2=two, 1=one}
Comparator value: java.util.Collections$ReverseComparator@232204a1
anikakapoor
solankimayank
surinderdawra388
Java - util package
Java-Collections
Java-Functions
java-TreeMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 207,
"s": 28,
"text": "The comparator() method of java.util.TreeMap class is used to return the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys."
},
{
"code": null,
"e": 284,
"s": 207,
"text": "--> java.util Package\n --> TreeMap Class\n --> comparator() Method "
},
{
"code": null,
"e": 294,
"s": 284,
"text": "Syntax: "
},
{
"code": null,
"e": 325,
"s": 294,
"text": "public Comparator comparator()"
},
{
"code": null,
"e": 468,
"s": 325,
"text": "Return Type: This method returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys."
},
{
"code": null,
"e": 534,
"s": 468,
"text": "Note: descendingIterator() method is natural ordering by default."
},
{
"code": null,
"e": 568,
"s": 534,
"text": "Example 1: For Natural ordering "
},
{
"code": null,
"e": 573,
"s": 568,
"text": "Java"
},
{
"code": "// Java program to Illustrate comparator() Method// for Natural Ordering (Descending Order) // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating an empty TreeMap by // creating object of NavigableMap NavigableMap<Integer, String> treemap = new TreeMap<Integer, String>(); // Populating TreeMap // using put() method treemap.put(1, \"one\"); treemap.put(2, \"two\"); treemap.put(3, \"three\"); treemap.put(4, \"four\"); treemap.put(5, \"five\"); // Printing the TreeMap System.out.println(\"TreeMap: \" + treemap); // Getting used Comparator in the map // using comparator() method Comparator comp = treemap.comparator(); // Printing the comparator value System.out.println(\"Comparator value: \" + comp); } // Catch block to handle the exception catch (NullPointerException e) { // Display message if exception occurs System.out.println(\"Exception thrown : \" + e); } }}",
"e": 1879,
"s": 573,
"text": null
},
{
"code": null,
"e": 1951,
"s": 1879,
"text": "TreeMap: {1=one, 2=two, 3=three, 4=four, 5=five}\nComparator value: null"
},
{
"code": null,
"e": 1985,
"s": 1953,
"text": "Example 2: For Reverse ordering"
},
{
"code": null,
"e": 1990,
"s": 1985,
"text": "Java"
},
{
"code": "// Java program to demonstrate comparator() Method// for Reverse Ordering // Importing required classesimport java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] argv) throws Exception { // Try block to check for exceptions try { // Creating an empty TreeMap NavigableMap<Integer, String> treemap = new TreeMap<Integer, String>( Collections.reverseOrder()); // Populating TreeMap // using put() method treemap.put(1, \"one\"); treemap.put(2, \"two\"); treemap.put(3, \"three\"); treemap.put(4, \"four\"); treemap.put(5, \"five\"); // Printing the TreeMap System.out.println(\"TreeMap: \" + treemap); // Getting used Comparator in the map // using comparator() method Comparator comp = treemap.comparator(); // Printing the comparator value System.out.println(\"Comparator value: \" + comp); } // Catch block to handle the exceptions catch (NullPointerException e) { // Display message if exception occurs System.out.println(\"Exception thrown : \" + e); } }}",
"e": 3276,
"s": 1990,
"text": null
},
{
"code": null,
"e": 3392,
"s": 3276,
"text": "TreeMap: {5=five, 4=four, 3=three, 2=two, 1=one}\nComparator value: java.util.Collections$ReverseComparator@232204a1"
},
{
"code": null,
"e": 3406,
"s": 3394,
"text": "anikakapoor"
},
{
"code": null,
"e": 3420,
"s": 3406,
"text": "solankimayank"
},
{
"code": null,
"e": 3437,
"s": 3420,
"text": "surinderdawra388"
},
{
"code": null,
"e": 3457,
"s": 3437,
"text": "Java - util package"
},
{
"code": null,
"e": 3474,
"s": 3457,
"text": "Java-Collections"
},
{
"code": null,
"e": 3489,
"s": 3474,
"text": "Java-Functions"
},
{
"code": null,
"e": 3502,
"s": 3489,
"text": "java-TreeMap"
},
{
"code": null,
"e": 3507,
"s": 3502,
"text": "Java"
},
{
"code": null,
"e": 3512,
"s": 3507,
"text": "Java"
},
{
"code": null,
"e": 3529,
"s": 3512,
"text": "Java-Collections"
},
{
"code": null,
"e": 3627,
"s": 3529,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3642,
"s": 3627,
"text": "Stream In Java"
},
{
"code": null,
"e": 3663,
"s": 3642,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3684,
"s": 3663,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3703,
"s": 3684,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3720,
"s": 3703,
"text": "Generics in Java"
},
{
"code": null,
"e": 3750,
"s": 3720,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 3776,
"s": 3750,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3792,
"s": 3776,
"text": "Strings in Java"
},
{
"code": null,
"e": 3829,
"s": 3792,
"text": "Differences between JDK, JRE and JVM"
}
] |
Detect a negative cycle in a Graph | (Bellman Ford) | 24 Nov, 2021
We are given a directed graph. We need to compute whether the graph has a negative cycle or not. A negative cycle is one in which the overall sum of the cycle becomes negative.
Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some advantage if we follow the path.
Examples:
Input : 4 4
0 1 1
1 2 -1
2 3 -1
3 0 -1
Output : Yes
The graph contains a negative cycle.
Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution.
The idea is to use Bellman-Ford Algorithm.
Below is an algorithm to find if there is a negative weight cycle reachable from the given source.1) Initialize distances from the source to all vertices as infinite and distance to the source itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is the source vertex.2) This step calculates the shortest distances. Do the following |V|-1 times where |V| is the number of vertices in the given graph. a) Do the following for each edge u-v. b) If dist[v] > dist[u] + weight of edge uv, then update dist[v]. c) dist[v] = dist[u] + weight of edge uv.3) This step reports if there is a negative weight cycle in the graph. Do the following for each edge u-v a) If dist[v] > dist[u] + weight of edge uv, then the “Graph has a negative weight cycle”
The idea of step 3 is, step 2 guarantees the shortest distances if the graph doesn’t contain a negative weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight cycle.
C++
Java
Python3
C#
Javascript
// A C++ program to check if a graph contains negative// weight cycle using Bellman-Ford algorithm. This program// works only if all vertices are reachable from a source// vertex 0.#include <bits/stdc++.h>using namespace std; // a structure to represent a weighted edge in graphstruct Edge { int src, dest, weight;}; // a structure to represent a connected, directed and// weighted graphstruct Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. struct Edge* edge;}; // Creates a graph with V vertices and E edgesstruct Graph* createGraph(int V, int E){ struct Graph* graph = new Graph; graph->V = V; graph->E = E; graph->edge = new Edge[graph->E]; return graph;} // The main function that finds shortest distances// from src to all other vertices using Bellman-// Ford algorithm. The function also detects// negative weight cyclebool isNegCycleBellmanFord(struct Graph* graph, int src){ int V = graph->V; int E = graph->E; int dist[V]; // Step 1: Initialize distances from src // to all other vertices as INFINITE for (int i = 0; i < V; i++) dist[i] = INT_MAX; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { int u = graph->edge[j].src; int v = graph->edge[j].dest; int weight = graph->edge[j].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for (int i = 0; i < E; i++) { int u = graph->edge[i].src; int v = graph->edge[i].dest; int weight = graph->edge[i].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) return true; } return false;} // Driver program to test above functionsint main(){ /* Let us create the graph given in above example */ int V = 5; // Number of vertices in graph int E = 8; // Number of edges in graph struct Graph* graph = createGraph(V, E); // add edge 0-1 (or A-B in above figure) graph->edge[0].src = 0; graph->edge[0].dest = 1; graph->edge[0].weight = -1; // add edge 0-2 (or A-C in above figure) graph->edge[1].src = 0; graph->edge[1].dest = 2; graph->edge[1].weight = 4; // add edge 1-2 (or B-C in above figure) graph->edge[2].src = 1; graph->edge[2].dest = 2; graph->edge[2].weight = 3; // add edge 1-3 (or B-D in above figure) graph->edge[3].src = 1; graph->edge[3].dest = 3; graph->edge[3].weight = 2; // add edge 1-4 (or A-E in above figure) graph->edge[4].src = 1; graph->edge[4].dest = 4; graph->edge[4].weight = 2; // add edge 3-2 (or D-C in above figure) graph->edge[5].src = 3; graph->edge[5].dest = 2; graph->edge[5].weight = 5; // add edge 3-1 (or D-B in above figure) graph->edge[6].src = 3; graph->edge[6].dest = 1; graph->edge[6].weight = 1; // add edge 4-3 (or E-D in above figure) graph->edge[7].src = 4; graph->edge[7].dest = 3; graph->edge[7].weight = -3; if (isNegCycleBellmanFord(graph, 0)) cout << "Yes"; else cout << "No"; return 0;}
// Java program to check if a graph contains negative // weight cycle using Bellman-Ford algorithm. This program // works only if all vertices are reachable from a source // vertex 0. import java.util.*; class GFG { // a structure to represent a weighted edge in graph static class Edge { int src, dest, weight; } // a structure to represent a connected, directed and // weighted graph static class Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. Edge edge[]; } // Creates a graph with V vertices and E edges static Graph createGraph(int V, int E) { Graph graph = new Graph(); graph.V = V; graph.E = E; graph.edge = new Edge[graph.E]; for (int i = 0; i < graph.E; i++) { graph.edge[i] = new Edge(); } return graph; } // The main function that finds shortest distances // from src to all other vertices using Bellman- // Ford algorithm. The function also detects // negative weight cycle static boolean isNegCycleBellmanFord(Graph graph, int src) { int V = graph.V; int E = graph.E; int[] dist = new int[V]; // Step 1: Initialize distances from src // to all other vertices as INFINITE for (int i = 0; i < V; i++) dist[i] = Integer.MAX_VALUE; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { int u = graph.edge[j].src; int v = graph.edge[j].dest; int weight = graph.edge[j].weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for (int i = 0; i < E; i++) { int u = graph.edge[i].src; int v = graph.edge[i].dest; int weight = graph.edge[i].weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) return true; } return false; } // Driver Code public static void main(String[] args) { int V = 5, E = 8; Graph graph = createGraph(V, E); // add edge 0-1 (or A-B in above figure) graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = -1; // add edge 0-2 (or A-C in above figure) graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 4; // add edge 1-2 (or B-C in above figure) graph.edge[2].src = 1; graph.edge[2].dest = 2; graph.edge[2].weight = 3; // add edge 1-3 (or B-D in above figure) graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 2; // add edge 1-4 (or A-E in above figure) graph.edge[4].src = 1; graph.edge[4].dest = 4; graph.edge[4].weight = 2; // add edge 3-2 (or D-C in above figure) graph.edge[5].src = 3; graph.edge[5].dest = 2; graph.edge[5].weight = 5; // add edge 3-1 (or D-B in above figure) graph.edge[6].src = 3; graph.edge[6].dest = 1; graph.edge[6].weight = 1; // add edge 4-3 (or E-D in above figure) graph.edge[7].src = 4; graph.edge[7].dest = 3; graph.edge[7].weight = -3; if (isNegCycleBellmanFord(graph, 0)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by// sanjeev2552
# A Python3 program to check if a graph contains negative# weight cycle using Bellman-Ford algorithm. This program# works only if all vertices are reachable from a source# vertex 0. # a structure to represent a weighted edge in graphclass Edge: def __init__(self): self.src = 0 self.dest = 0 self.weight = 0 # a structure to represent a connected, directed and# weighted graphclass Graph: def __init__(self): # V. Number of vertices, E. Number of edges self.V = 0 self.E = 0 # graph is represented as an array of edges. self.edge = None # Creates a graph with V vertices and E edgesdef createGraph(V, E): graph = Graph() graph.V = V; graph.E = E; graph.edge =[Edge() for i in range(graph.E)] return graph; # The main function that finds shortest distances# from src to all other vertices using Bellman-# Ford algorithm. The function also detects# negative weight cycledef isNegCycleBellmanFord(graph, src): V = graph.V; E = graph.E; dist = [1000000 for i in range(V)]; dist[src] = 0; # Step 2: Relax all edges |V| - 1 times. # A simple shortest path from src to any # other vertex can have at-most |V| - 1 # edges for i in range(1, V): for j in range(E): u = graph.edge[j].src; v = graph.edge[j].dest; weight = graph.edge[j].weight; if (dist[u] != 1000000 and dist[u] + weight < dist[v]): dist[v] = dist[u] + weight; # Step 3: check for negative-weight cycles. # The above step guarantees shortest distances # if graph doesn't contain negative weight cycle. # If we get a shorter path, then there # is a cycle. for i in range(E): u = graph.edge[i].src; v = graph.edge[i].dest; weight = graph.edge[i].weight; if (dist[u] != 1000000 and dist[u] + weight < dist[v]): return True; return False; # Driver program to test above functionsif __name__=='__main__': # Let us create the graph given in above example V = 5; # Number of vertices in graph E = 8; # Number of edges in graph graph = createGraph(V, E); # add edge 0-1 (or A-B in above figure) graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = -1; # add edge 0-2 (or A-C in above figure) graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 4; # add edge 1-2 (or B-C in above figure) graph.edge[2].src = 1; graph.edge[2].dest = 2; graph.edge[2].weight = 3; # add edge 1-3 (or B-D in above figure) graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 2; # add edge 1-4 (or A-E in above figure) graph.edge[4].src = 1; graph.edge[4].dest = 4; graph.edge[4].weight = 2; # add edge 3-2 (or D-C in above figure) graph.edge[5].src = 3; graph.edge[5].dest = 2; graph.edge[5].weight = 5; # add edge 3-1 (or D-B in above figure) graph.edge[6].src = 3; graph.edge[6].dest = 1; graph.edge[6].weight = 1; # add edge 4-3 (or E-D in above figure) graph.edge[7].src = 4; graph.edge[7].dest = 3; graph.edge[7].weight = -3; if (isNegCycleBellmanFord(graph, 0)): print("Yes") else: print("No") # This code is contributed by pratham76
// C# program to check if a graph contains negative // weight cycle using Bellman-Ford algorithm. This program // works only if all vertices are reachable from a source // vertex 0. using System;using System.Collections;using System.Collections.Generic; class GFG { // a structure to represent a weighted edge in graph class Edge { public int src, dest, weight; } // a structure to represent a connected, directed and // weighted graph class Graph { // V-> Number of vertices, E-> Number of edges public int V, E; // graph is represented as an array of edges. public Edge []edge; } // Creates a graph with V vertices and E edges static Graph createGraph(int V, int E) { Graph graph = new Graph(); graph.V = V; graph.E = E; graph.edge = new Edge[graph.E]; for (int i = 0; i < graph.E; i++) { graph.edge[i] = new Edge(); } return graph; } // The main function that finds shortest distances // from src to all other vertices using Bellman- // Ford algorithm. The function also detects // negative weight cycle static bool isNegCycleBellmanFord(Graph graph, int src) { int V = graph.V; int E = graph.E; int[] dist = new int[V]; // Step 1: Initialize distances from src // to all other vertices as INFINITE for (int i = 0; i < V; i++) dist[i] = 1000000; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { int u = graph.edge[j].src; int v = graph.edge[j].dest; int weight = graph.edge[j].weight; if (dist[u] != 1000000 && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for (int i = 0; i < E; i++) { int u = graph.edge[i].src; int v = graph.edge[i].dest; int weight = graph.edge[i].weight; if (dist[u] != 1000000 && dist[u] + weight < dist[v]) return true; } return false; } // Driver Code public static void Main(string[] args) { int V = 5, E = 8; Graph graph = createGraph(V, E); // add edge 0-1 (or A-B in above figure) graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = -1; // add edge 0-2 (or A-C in above figure) graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 4; // add edge 1-2 (or B-C in above figure) graph.edge[2].src = 1; graph.edge[2].dest = 2; graph.edge[2].weight = 3; // add edge 1-3 (or B-D in above figure) graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 2; // add edge 1-4 (or A-E in above figure) graph.edge[4].src = 1; graph.edge[4].dest = 4; graph.edge[4].weight = 2; // add edge 3-2 (or D-C in above figure) graph.edge[5].src = 3; graph.edge[5].dest = 2; graph.edge[5].weight = 5; // add edge 3-1 (or D-B in above figure) graph.edge[6].src = 3; graph.edge[6].dest = 1; graph.edge[6].weight = 1; // add edge 4-3 (or E-D in above figure) graph.edge[7].src = 4; graph.edge[7].dest = 3; graph.edge[7].weight = -3; if (isNegCycleBellmanFord(graph, 0)) Console.Write("Yes"); else Console.Write("No"); }} // This code is contributed by rutvik_56
<script> // Javascript program to check if a graph contains negative// weight cycle using Bellman-Ford algorithm. This program// works only if all vertices are reachable from a source// vertex 0. // A structure to represent a weighted edge in graphclass Edge { constructor() { let src, dest, weight; }} // A structure to represent a connected, directed and// weighted graphclass Graph{ constructor() { // V-> Number of vertices, E-> Number of edges let V, E; // graph is represented as an array of edges. let edge = []; }} // Creates a graph with V vertices and E edgesfunction createGraph(V,E){ let graph = new Graph(); graph.V = V; graph.E = E; graph.edge = new Array(graph.E); for(let i = 0; i < graph.E; i++) { graph.edge[i] = new Edge(); } return graph;} // The main function that finds shortest distances// from src to all other vertices using Bellman-// Ford algorithm. The function also detects// negative weight cyclefunction isNegCycleBellmanFord(graph, src){ let V = graph.V; let E = graph.E; let dist = new Array(V); // Step 1: Initialize distances from src // to all other vertices as INFINITE for(let i = 0; i < V; i++) dist[i] = Number.MAX_VALUE; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for(let i = 1; i <= V - 1; i++) { for(let j = 0; j < E; j++) { let u = graph.edge[j].src; let v = graph.edge[j].dest; let weight = graph.edge[j].weight; if (dist[u] != Number.MAX_VALUE && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for(let i = 0; i < E; i++) { let u = graph.edge[i].src; let v = graph.edge[i].dest; let weight = graph.edge[i].weight; if (dist[u] != Number.MAX_VALUE && dist[u] + weight < dist[v]) return true; } return false;} // Driver Codelet V = 5, E = 8;let graph = createGraph(V, E); // Add edge 0-1 (or A-B in above figure)graph.edge[0].src = 0;graph.edge[0].dest = 1;graph.edge[0].weight = -1; // Add edge 0-2 (or A-C in above figure)graph.edge[1].src = 0;graph.edge[1].dest = 2;graph.edge[1].weight = 4; // add edge 1-2 (or B-C in above figure)graph.edge[2].src = 1;graph.edge[2].dest = 2;graph.edge[2].weight = 3; // Add edge 1-3 (or B-D in above figure)graph.edge[3].src = 1;graph.edge[3].dest = 3;graph.edge[3].weight = 2; // Add edge 1-4 (or A-E in above figure)graph.edge[4].src = 1;graph.edge[4].dest = 4;graph.edge[4].weight = 2; // Add edge 3-2 (or D-C in above figure)graph.edge[5].src = 3;graph.edge[5].dest = 2;graph.edge[5].weight = 5; // Add edge 3-1 (or D-B in above figure)graph.edge[6].src = 3;graph.edge[6].dest = 1;graph.edge[6].weight = 1; // add edge 4-3 (or E-D in above figure)graph.edge[7].src = 4;graph.edge[7].dest = 3;graph.edge[7].weight = -3; if (isNegCycleBellmanFord(graph, 0)) document.write("Yes");else document.write("No"); // This code is contributed by unknown2108 </script>
Output :
No
How does it work? As discussed, the Bellman-Ford algorithm, for a given source, first calculates the shortest distances which have at most one edge in the path. Then, it calculates the shortest paths with at-most 2 edges, and so on. After the i-th iteration of the outer loop, the shortest paths with at most i edges are calculated. There can be a maximum |V| – 1 edge on any simple path, that is why the outer loop runs |v| – 1 time. If there is a negative weight cycle, then one more iteration would give a short route.
How to handle a disconnected graph (If the cycle is not reachable from the source)? The above algorithm and program might not work if the given graph is disconnected. It works when all vertices are reachable from source vertex 0.To handle disconnected graphs, we can repeat the process for vertices for which distance is infinite.
C++
Java
Python3
C#
Javascript
// A C++ program for Bellman-Ford's single source// shortest path algorithm.#include <bits/stdc++.h>using namespace std; // a structure to represent a weighted edge in graphstruct Edge { int src, dest, weight;}; // a structure to represent a connected, directed and// weighted graphstruct Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. struct Edge* edge;}; // Creates a graph with V vertices and E edgesstruct Graph* createGraph(int V, int E){ struct Graph* graph = new Graph; graph->V = V; graph->E = E; graph->edge = new Edge[graph->E]; return graph;} // The main function that finds shortest distances// from src to all other vertices using Bellman-// Ford algorithm. The function also detects// negative weight cyclebool isNegCycleBellmanFord(struct Graph* graph, int src, int dist[]){ int V = graph->V; int E = graph->E; // Step 1: Initialize distances from src // to all other vertices as INFINITE for (int i = 0; i < V; i++) dist[i] = INT_MAX; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { int u = graph->edge[j].src; int v = graph->edge[j].dest; int weight = graph->edge[j].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for (int i = 0; i < E; i++) { int u = graph->edge[i].src; int v = graph->edge[i].dest; int weight = graph->edge[i].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) return true; } return false;} // Returns true if given graph has negative weight// cycle.bool isNegCycleDisconnected(struct Graph* graph){ int V = graph->V; // To keep track of visited vertices to avoid // recomputations. bool visited[V]; memset(visited, 0, sizeof(visited)); // This array is filled by Bellman-Ford int dist[V]; // Call Bellman-Ford for all those vertices // that are not visited for (int i = 0; i < V; i++) { if (visited[i] == false) { // If cycle found if (isNegCycleBellmanFord(graph, i, dist)) return true; // Mark all vertices that are visited // in above call. for (int i = 0; i < V; i++) if (dist[i] != INT_MAX) visited[i] = true; } } return false;} // Driver program to test above functionsint main(){ /* Let us create the graph given in above example */ int V = 5; // Number of vertices in graph int E = 8; // Number of edges in graph struct Graph* graph = createGraph(V, E); // add edge 0-1 (or A-B in above figure) graph->edge[0].src = 0; graph->edge[0].dest = 1; graph->edge[0].weight = -1; // add edge 0-2 (or A-C in above figure) graph->edge[1].src = 0; graph->edge[1].dest = 2; graph->edge[1].weight = 4; // add edge 1-2 (or B-C in above figure) graph->edge[2].src = 1; graph->edge[2].dest = 2; graph->edge[2].weight = 3; // add edge 1-3 (or B-D in above figure) graph->edge[3].src = 1; graph->edge[3].dest = 3; graph->edge[3].weight = 2; // add edge 1-4 (or A-E in above figure) graph->edge[4].src = 1; graph->edge[4].dest = 4; graph->edge[4].weight = 2; // add edge 3-2 (or D-C in above figure) graph->edge[5].src = 3; graph->edge[5].dest = 2; graph->edge[5].weight = 5; // add edge 3-1 (or D-B in above figure) graph->edge[6].src = 3; graph->edge[6].dest = 1; graph->edge[6].weight = 1; // add edge 4-3 (or E-D in above figure) graph->edge[7].src = 4; graph->edge[7].dest = 3; graph->edge[7].weight = -3; if (isNegCycleDisconnected(graph)) cout << "Yes"; else cout << "No"; return 0;}
// A Java program for Bellman-Ford's single source // shortest path algorithm. import java.util.*; class GFG{ // A structure to represent a weighted // edge in graph static class Edge{ int src, dest, weight; } // A structure to represent a connected, // directed and weighted graph static class Graph { // V-> Number of vertices, // E-> Number of edges int V, E; // Graph is represented as // an array of edges. Edge edge[]; } // Creates a graph with V vertices and E edges static Graph createGraph(int V, int E){ Graph graph = new Graph(); graph.V = V; graph.E = E; graph.edge = new Edge[graph.E]; for(int i = 0; i < graph.E; i++) { graph.edge[i] = new Edge(); } return graph; } // The main function that finds shortest distances // from src to all other vertices using Bellman- // Ford algorithm. The function also detects // negative weight cycle static boolean isNegCycleBellmanFord(Graph graph, int src, int dist[]) { int V = graph.V; int E = graph.E; // Step 1: Initialize distances from src // to all other vertices as INFINITE for(int i = 0; i < V; i++) dist[i] = Integer.MAX_VALUE; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for(int i = 1; i <= V - 1; i++) { for(int j = 0; j < E; j++) { int u = graph.edge[j].src; int v = graph.edge[j].dest; int weight = graph.edge[j].weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for(int i = 0; i < E; i++) { int u = graph.edge[i].src; int v = graph.edge[i].dest; int weight = graph.edge[i].weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) return true; } return false; } // Returns true if given graph has negative weight // cycle. static boolean isNegCycleDisconnected(Graph graph) { int V = graph.V; // To keep track of visited vertices // to avoid recomputations. boolean visited[] = new boolean[V]; Arrays.fill(visited, false); // This array is filled by Bellman-Ford int dist[] = new int[V]; // Call Bellman-Ford for all those vertices // that are not visited for(int i = 0; i < V; i++) { if (visited[i] == false) { // If cycle found if (isNegCycleBellmanFord(graph, i, dist)) return true; // Mark all vertices that are visited // in above call. for(int j = 0; j < V; j++) if (dist[j] != Integer.MAX_VALUE) visited[j] = true; } } return false; } // Driver Code public static void main(String[] args) { int V = 5, E = 8; Graph graph = createGraph(V, E); // Add edge 0-1 (or A-B in above figure) graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = -1; // Add edge 0-2 (or A-C in above figure) graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 4; // Add edge 1-2 (or B-C in above figure) graph.edge[2].src = 1; graph.edge[2].dest = 2; graph.edge[2].weight = 3; // Add edge 1-3 (or B-D in above figure) graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 2; // Add edge 1-4 (or A-E in above figure) graph.edge[4].src = 1; graph.edge[4].dest = 4; graph.edge[4].weight = 2; // Add edge 3-2 (or D-C in above figure) graph.edge[5].src = 3; graph.edge[5].dest = 2; graph.edge[5].weight = 5; // Add edge 3-1 (or D-B in above figure) graph.edge[6].src = 3; graph.edge[6].dest = 1; graph.edge[6].weight = 1; // Add edge 4-3 (or E-D in above figure) graph.edge[7].src = 4; graph.edge[7].dest = 3; graph.edge[7].weight = -3; if (isNegCycleDisconnected(graph)) System.out.println("Yes"); else System.out.println("No"); } } // This code is contributed by adityapande88
# A Python3 program for Bellman-Ford's single source# shortest path algorithm. # The main function that finds shortest distances# from src to all other vertices using Bellman-# Ford algorithm. The function also detects# negative weight cycledef isNegCycleBellmanFord(src, dist): global graph, V, E # Step 1: Initialize distances from src # to all other vertices as INFINITE for i in range(V): dist[i] = 10**18 dist[src] = 0 # Step 2: Relax all edges |V| - 1 times. # A simple shortest path from src to any # other vertex can have at-most |V| - 1 # edges for i in range(1,V): for j in range(E): u = graph[j][0] v = graph[j][1] weight = graph[j][2] if (dist[u] != 10**18 and dist[u] + weight < dist[v]): dist[v] = dist[u] + weight # Step 3: check for negative-weight cycles. # The above step guarantees shortest distances # if graph doesn't contain negative weight cycle. # If we get a shorter path, then there # is a cycle. for i in range(E): u = graph[i][0] v = graph[i][1] weight = graph[i][2] if (dist[u] != 10**18 and dist[u] + weight < dist[v]): return True return False# Returns true if given graph has negative weight# cycle.def isNegCycleDisconnected(): global V, E, graph # To keep track of visited vertices to avoid # recomputations. visited = [0]*V # memset(visited, 0, sizeof(visited)) # This array is filled by Bellman-Ford dist = [0]*V # Call Bellman-Ford for all those vertices # that are not visited for i in range(V): if (visited[i] == 0): # If cycle found if (isNegCycleBellmanFord(i, dist)): return True # Mark all vertices that are visited # in above call. for i in range(V): if (dist[i] != 10**18): visited[i] = True return False # Driver codeif __name__ == '__main__': # /* Let us create the graph given in above example */ V = 5 # Number of vertices in graph E = 8 # Number of edges in graph graph = [[0, 0, 0] for i in range(8)] # add edge 0-1 (or A-B in above figure) graph[0][0] = 0 graph[0][1] = 1 graph[0][2] = -1 # add edge 0-2 (or A-C in above figure) graph[1][0] = 0 graph[1][1] = 2 graph[1][2] = 4 # add edge 1-2 (or B-C in above figure) graph[2][0] = 1 graph[2][1] = 2 graph[2][2] = 3 # add edge 1-3 (or B-D in above figure) graph[3][0] = 1 graph[3][1] = 3 graph[3][2] = 2 # add edge 1-4 (or A-E in above figure) graph[4][0] = 1 graph[4][1] = 4 graph[4][2] = 2 # add edge 3-2 (or D-C in above figure) graph[5][0] = 3 graph[5][1] = 2 graph[5][2] = 5 # add edge 3-1 (or D-B in above figure) graph[6][0] = 3 graph[6][1] = 1 graph[6][2] = 1 # add edge 4-3 (or E-D in above figure) graph[7][0] = 4 graph[7][1] = 3 graph[7][2] = -3 if (isNegCycleDisconnected()): print("Yes") else: print("No") # This code is contributed by mohit kumar 29
// A C# program for Bellman-Ford's single source // shortest path algorithm. using System;using System.Collections.Generic;public class GFG{ // A structure to represent a weighted // edge in graph public class Edge { public int src, dest, weight; } // A structure to represent a connected, // directed and weighted graph public class Graph { // V-> Number of vertices, // E-> Number of edges public int V, E; // Graph is represented as // an array of edges. public Edge []edge; } // Creates a graph with V vertices and E edges static Graph createGraph(int V, int E) { Graph graph = new Graph(); graph.V = V; graph.E = E; graph.edge = new Edge[graph.E]; for(int i = 0; i < graph.E; i++) { graph.edge[i] = new Edge(); } return graph; } // The main function that finds shortest distances // from src to all other vertices using Bellman- // Ford algorithm. The function also detects // negative weight cycle static bool isNegCycleBellmanFord(Graph graph, int src, int []dist) { int V = graph.V; int E = graph.E; // Step 1: Initialize distances from src // to all other vertices as INFINITE for(int i = 0; i < V; i++) dist[i] = int.MaxValue; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for(int i = 1; i <= V - 1; i++) { for(int j = 0; j < E; j++) { int u = graph.edge[j].src; int v = graph.edge[j].dest; int weight = graph.edge[j].weight; if (dist[u] != int.MaxValue && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for(int i = 0; i < E; i++) { int u = graph.edge[i].src; int v = graph.edge[i].dest; int weight = graph.edge[i].weight; if (dist[u] != int.MaxValue && dist[u] + weight < dist[v]) return true; } return false; } // Returns true if given graph has negative weight // cycle. static bool isNegCycleDisconnected(Graph graph) { int V = graph.V; // To keep track of visited vertices // to avoid recomputations. bool []visited = new bool[V]; // This array is filled by Bellman-Ford int []dist = new int[V]; // Call Bellman-Ford for all those vertices // that are not visited for(int i = 0; i < V; i++) { if (visited[i] == false) { // If cycle found if (isNegCycleBellmanFord(graph, i, dist)) return true; // Mark all vertices that are visited // in above call. for(int j = 0; j < V; j++) if (dist[j] != int.MaxValue) visited[j] = true; } } return false; } // Driver Code public static void Main(String[] args) { int V = 5, E = 8; Graph graph = createGraph(V, E); // Add edge 0-1 (or A-B in above figure) graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = -1; // Add edge 0-2 (or A-C in above figure) graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 4; // Add edge 1-2 (or B-C in above figure) graph.edge[2].src = 1; graph.edge[2].dest = 2; graph.edge[2].weight = 3; // Add edge 1-3 (or B-D in above figure) graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 2; // Add edge 1-4 (or A-E in above figure) graph.edge[4].src = 1; graph.edge[4].dest = 4; graph.edge[4].weight = 2; // Add edge 3-2 (or D-C in above figure) graph.edge[5].src = 3; graph.edge[5].dest = 2; graph.edge[5].weight = 5; // Add edge 3-1 (or D-B in above figure) graph.edge[6].src = 3; graph.edge[6].dest = 1; graph.edge[6].weight = 1; // Add edge 4-3 (or E-D in above figure) graph.edge[7].src = 4; graph.edge[7].dest = 3; graph.edge[7].weight = -3; if (isNegCycleDisconnected(graph)) Console.WriteLine("Yes"); else Console.WriteLine("No"); } } // This code is contributed by aashish1995
<script>// A Javascript program for Bellman-Ford's single source// shortest path algorithm. // A structure to represent a weighted // edge in graph class Edge { constructor() { let src, dest, weight; } } // A structure to represent a connected, // directed and weighted graph class Graph { constructor() { // V-> Number of vertices, // E-> Number of edges let V, E; // Graph is represented as // an array of edges. let edge=[]; } } // Creates a graph with V vertices and E edges function createGraph(V,E) { let graph = new Graph(); graph.V = V; graph.E = E; graph.edge = new Array(graph.E); for(let i = 0; i < graph.E; i++) { graph.edge[i] = new Edge(); } return graph; } // The main function that finds shortest distances// from src to all other vertices using Bellman-// Ford algorithm. The function also detects// negative weight cyclefunction isNegCycleBellmanFord(graph,src,dist){ let V = graph.V; let E = graph.E; // Step 1: Initialize distances from src // to all other vertices as INFINITE for(let i = 0; i < V; i++) dist[i] = Number.MAX_VALUE; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for(let i = 1; i <= V - 1; i++) { for(let j = 0; j < E; j++) { let u = graph.edge[j].src; let v = graph.edge[j].dest; let weight = graph.edge[j].weight; if (dist[u] != Number.MAX_VALUE && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for(let i = 0; i < E; i++) { let u = graph.edge[i].src; let v = graph.edge[i].dest; let weight = graph.edge[i].weight; if (dist[u] != Number.MAX_VALUE && dist[u] + weight < dist[v]) return true; } return false;} // Returns true if given graph has negative weight// cycle.function isNegCycleDisconnected(graph){ let V = graph.V; // To keep track of visited vertices // to avoid recomputations. let visited = new Array(V); for(let i=0;i<V;i++) { visited[i]=false; } // This array is filled by Bellman-Ford let dist = new Array(V); // Call Bellman-Ford for all those vertices // that are not visited for(let i = 0; i < V; i++) { if (visited[i] == false) { // If cycle found if (isNegCycleBellmanFord(graph, i, dist)) return true; // Mark all vertices that are visited // in above call. for(let j = 0; j < V; j++) if (dist[j] != Number.MAX_VALUE) visited[j] = true; } } return false;} // Driver Code let V = 5, E = 8;let graph = createGraph(V, E); // Add edge 0-1 (or A-B in above figure)graph.edge[0].src = 0;graph.edge[0].dest = 1;graph.edge[0].weight = -1; // Add edge 0-2 (or A-C in above figure)graph.edge[1].src = 0;graph.edge[1].dest = 2;graph.edge[1].weight = 4; // Add edge 1-2 (or B-C in above figure)graph.edge[2].src = 1;graph.edge[2].dest = 2;graph.edge[2].weight = 3; // Add edge 1-3 (or B-D in above figure)graph.edge[3].src = 1;graph.edge[3].dest = 3;graph.edge[3].weight = 2; // Add edge 1-4 (or A-E in above figure)graph.edge[4].src = 1;graph.edge[4].dest = 4;graph.edge[4].weight = 2; // Add edge 3-2 (or D-C in above figure)graph.edge[5].src = 3;graph.edge[5].dest = 2;graph.edge[5].weight = 5; // Add edge 3-1 (or D-B in above figure)graph.edge[6].src = 3;graph.edge[6].dest = 1;graph.edge[6].weight = 1; // Add edge 4-3 (or E-D in above figure)graph.edge[7].src = 4;graph.edge[7].dest = 3;graph.edge[7].weight = -3; if (isNegCycleDisconnected(graph)) document.write("Yes");else document.write("No"); // This code is contributed by patel2127</script>
Output :
No
Detecting negative cycle using Floyd Warshall
This article is contributed by kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
sanjeev2552
adityapande88
rutvik_56
pratham76
mohit kumar 29
aashish1995
vbxltra
unknown2108
patel2127
lolhellno
surinderdawra388
graph-cycle
Graph
Graph
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n24 Nov, 2021"
},
{
"code": null,
"e": 231,
"s": 54,
"text": "We are given a directed graph. We need to compute whether the graph has a negative cycle or not. A negative cycle is one in which the overall sum of the cycle becomes negative."
},
{
"code": null,
"e": 390,
"s": 231,
"text": "Negative weights are found in various applications of graphs. For example, instead of paying cost for a path, we may get some advantage if we follow the path."
},
{
"code": null,
"e": 401,
"s": 390,
"text": "Examples: "
},
{
"code": null,
"e": 523,
"s": 401,
"text": "Input : 4 4\n 0 1 1\n 1 2 -1\n 2 3 -1\n 3 0 -1\n\nOutput : Yes\nThe graph contains a negative cycle."
},
{
"code": null,
"e": 608,
"s": 523,
"text": "Recommended: Please solve it on “PRACTICE ” first, before moving on to the solution."
},
{
"code": null,
"e": 652,
"s": 608,
"text": "The idea is to use Bellman-Ford Algorithm. "
},
{
"code": null,
"e": 1464,
"s": 652,
"text": "Below is an algorithm to find if there is a negative weight cycle reachable from the given source.1) Initialize distances from the source to all vertices as infinite and distance to the source itself as 0. Create an array dist[] of size |V| with all values as infinite except dist[src] where src is the source vertex.2) This step calculates the shortest distances. Do the following |V|-1 times where |V| is the number of vertices in the given graph. a) Do the following for each edge u-v. b) If dist[v] > dist[u] + weight of edge uv, then update dist[v]. c) dist[v] = dist[u] + weight of edge uv.3) This step reports if there is a negative weight cycle in the graph. Do the following for each edge u-v a) If dist[v] > dist[u] + weight of edge uv, then the “Graph has a negative weight cycle” "
},
{
"code": null,
"e": 1706,
"s": 1464,
"text": "The idea of step 3 is, step 2 guarantees the shortest distances if the graph doesn’t contain a negative weight cycle. If we iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight cycle."
},
{
"code": null,
"e": 1710,
"s": 1706,
"text": "C++"
},
{
"code": null,
"e": 1715,
"s": 1710,
"text": "Java"
},
{
"code": null,
"e": 1723,
"s": 1715,
"text": "Python3"
},
{
"code": null,
"e": 1726,
"s": 1723,
"text": "C#"
},
{
"code": null,
"e": 1737,
"s": 1726,
"text": "Javascript"
},
{
"code": "// A C++ program to check if a graph contains negative// weight cycle using Bellman-Ford algorithm. This program// works only if all vertices are reachable from a source// vertex 0.#include <bits/stdc++.h>using namespace std; // a structure to represent a weighted edge in graphstruct Edge { int src, dest, weight;}; // a structure to represent a connected, directed and// weighted graphstruct Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. struct Edge* edge;}; // Creates a graph with V vertices and E edgesstruct Graph* createGraph(int V, int E){ struct Graph* graph = new Graph; graph->V = V; graph->E = E; graph->edge = new Edge[graph->E]; return graph;} // The main function that finds shortest distances// from src to all other vertices using Bellman-// Ford algorithm. The function also detects// negative weight cyclebool isNegCycleBellmanFord(struct Graph* graph, int src){ int V = graph->V; int E = graph->E; int dist[V]; // Step 1: Initialize distances from src // to all other vertices as INFINITE for (int i = 0; i < V; i++) dist[i] = INT_MAX; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { int u = graph->edge[j].src; int v = graph->edge[j].dest; int weight = graph->edge[j].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for (int i = 0; i < E; i++) { int u = graph->edge[i].src; int v = graph->edge[i].dest; int weight = graph->edge[i].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) return true; } return false;} // Driver program to test above functionsint main(){ /* Let us create the graph given in above example */ int V = 5; // Number of vertices in graph int E = 8; // Number of edges in graph struct Graph* graph = createGraph(V, E); // add edge 0-1 (or A-B in above figure) graph->edge[0].src = 0; graph->edge[0].dest = 1; graph->edge[0].weight = -1; // add edge 0-2 (or A-C in above figure) graph->edge[1].src = 0; graph->edge[1].dest = 2; graph->edge[1].weight = 4; // add edge 1-2 (or B-C in above figure) graph->edge[2].src = 1; graph->edge[2].dest = 2; graph->edge[2].weight = 3; // add edge 1-3 (or B-D in above figure) graph->edge[3].src = 1; graph->edge[3].dest = 3; graph->edge[3].weight = 2; // add edge 1-4 (or A-E in above figure) graph->edge[4].src = 1; graph->edge[4].dest = 4; graph->edge[4].weight = 2; // add edge 3-2 (or D-C in above figure) graph->edge[5].src = 3; graph->edge[5].dest = 2; graph->edge[5].weight = 5; // add edge 3-1 (or D-B in above figure) graph->edge[6].src = 3; graph->edge[6].dest = 1; graph->edge[6].weight = 1; // add edge 4-3 (or E-D in above figure) graph->edge[7].src = 4; graph->edge[7].dest = 3; graph->edge[7].weight = -3; if (isNegCycleBellmanFord(graph, 0)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 5310,
"s": 1737,
"text": null
},
{
"code": "// Java program to check if a graph contains negative // weight cycle using Bellman-Ford algorithm. This program // works only if all vertices are reachable from a source // vertex 0. import java.util.*; class GFG { // a structure to represent a weighted edge in graph static class Edge { int src, dest, weight; } // a structure to represent a connected, directed and // weighted graph static class Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. Edge edge[]; } // Creates a graph with V vertices and E edges static Graph createGraph(int V, int E) { Graph graph = new Graph(); graph.V = V; graph.E = E; graph.edge = new Edge[graph.E]; for (int i = 0; i < graph.E; i++) { graph.edge[i] = new Edge(); } return graph; } // The main function that finds shortest distances // from src to all other vertices using Bellman- // Ford algorithm. The function also detects // negative weight cycle static boolean isNegCycleBellmanFord(Graph graph, int src) { int V = graph.V; int E = graph.E; int[] dist = new int[V]; // Step 1: Initialize distances from src // to all other vertices as INFINITE for (int i = 0; i < V; i++) dist[i] = Integer.MAX_VALUE; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { int u = graph.edge[j].src; int v = graph.edge[j].dest; int weight = graph.edge[j].weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for (int i = 0; i < E; i++) { int u = graph.edge[i].src; int v = graph.edge[i].dest; int weight = graph.edge[i].weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) return true; } return false; } // Driver Code public static void main(String[] args) { int V = 5, E = 8; Graph graph = createGraph(V, E); // add edge 0-1 (or A-B in above figure) graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = -1; // add edge 0-2 (or A-C in above figure) graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 4; // add edge 1-2 (or B-C in above figure) graph.edge[2].src = 1; graph.edge[2].dest = 2; graph.edge[2].weight = 3; // add edge 1-3 (or B-D in above figure) graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 2; // add edge 1-4 (or A-E in above figure) graph.edge[4].src = 1; graph.edge[4].dest = 4; graph.edge[4].weight = 2; // add edge 3-2 (or D-C in above figure) graph.edge[5].src = 3; graph.edge[5].dest = 2; graph.edge[5].weight = 5; // add edge 3-1 (or D-B in above figure) graph.edge[6].src = 3; graph.edge[6].dest = 1; graph.edge[6].weight = 1; // add edge 4-3 (or E-D in above figure) graph.edge[7].src = 4; graph.edge[7].dest = 3; graph.edge[7].weight = -3; if (isNegCycleBellmanFord(graph, 0)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by// sanjeev2552",
"e": 9285,
"s": 5310,
"text": null
},
{
"code": "# A Python3 program to check if a graph contains negative# weight cycle using Bellman-Ford algorithm. This program# works only if all vertices are reachable from a source# vertex 0. # a structure to represent a weighted edge in graphclass Edge: def __init__(self): self.src = 0 self.dest = 0 self.weight = 0 # a structure to represent a connected, directed and# weighted graphclass Graph: def __init__(self): # V. Number of vertices, E. Number of edges self.V = 0 self.E = 0 # graph is represented as an array of edges. self.edge = None # Creates a graph with V vertices and E edgesdef createGraph(V, E): graph = Graph() graph.V = V; graph.E = E; graph.edge =[Edge() for i in range(graph.E)] return graph; # The main function that finds shortest distances# from src to all other vertices using Bellman-# Ford algorithm. The function also detects# negative weight cycledef isNegCycleBellmanFord(graph, src): V = graph.V; E = graph.E; dist = [1000000 for i in range(V)]; dist[src] = 0; # Step 2: Relax all edges |V| - 1 times. # A simple shortest path from src to any # other vertex can have at-most |V| - 1 # edges for i in range(1, V): for j in range(E): u = graph.edge[j].src; v = graph.edge[j].dest; weight = graph.edge[j].weight; if (dist[u] != 1000000 and dist[u] + weight < dist[v]): dist[v] = dist[u] + weight; # Step 3: check for negative-weight cycles. # The above step guarantees shortest distances # if graph doesn't contain negative weight cycle. # If we get a shorter path, then there # is a cycle. for i in range(E): u = graph.edge[i].src; v = graph.edge[i].dest; weight = graph.edge[i].weight; if (dist[u] != 1000000 and dist[u] + weight < dist[v]): return True; return False; # Driver program to test above functionsif __name__=='__main__': # Let us create the graph given in above example V = 5; # Number of vertices in graph E = 8; # Number of edges in graph graph = createGraph(V, E); # add edge 0-1 (or A-B in above figure) graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = -1; # add edge 0-2 (or A-C in above figure) graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 4; # add edge 1-2 (or B-C in above figure) graph.edge[2].src = 1; graph.edge[2].dest = 2; graph.edge[2].weight = 3; # add edge 1-3 (or B-D in above figure) graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 2; # add edge 1-4 (or A-E in above figure) graph.edge[4].src = 1; graph.edge[4].dest = 4; graph.edge[4].weight = 2; # add edge 3-2 (or D-C in above figure) graph.edge[5].src = 3; graph.edge[5].dest = 2; graph.edge[5].weight = 5; # add edge 3-1 (or D-B in above figure) graph.edge[6].src = 3; graph.edge[6].dest = 1; graph.edge[6].weight = 1; # add edge 4-3 (or E-D in above figure) graph.edge[7].src = 4; graph.edge[7].dest = 3; graph.edge[7].weight = -3; if (isNegCycleBellmanFord(graph, 0)): print(\"Yes\") else: print(\"No\") # This code is contributed by pratham76",
"e": 12651,
"s": 9285,
"text": null
},
{
"code": "// C# program to check if a graph contains negative // weight cycle using Bellman-Ford algorithm. This program // works only if all vertices are reachable from a source // vertex 0. using System;using System.Collections;using System.Collections.Generic; class GFG { // a structure to represent a weighted edge in graph class Edge { public int src, dest, weight; } // a structure to represent a connected, directed and // weighted graph class Graph { // V-> Number of vertices, E-> Number of edges public int V, E; // graph is represented as an array of edges. public Edge []edge; } // Creates a graph with V vertices and E edges static Graph createGraph(int V, int E) { Graph graph = new Graph(); graph.V = V; graph.E = E; graph.edge = new Edge[graph.E]; for (int i = 0; i < graph.E; i++) { graph.edge[i] = new Edge(); } return graph; } // The main function that finds shortest distances // from src to all other vertices using Bellman- // Ford algorithm. The function also detects // negative weight cycle static bool isNegCycleBellmanFord(Graph graph, int src) { int V = graph.V; int E = graph.E; int[] dist = new int[V]; // Step 1: Initialize distances from src // to all other vertices as INFINITE for (int i = 0; i < V; i++) dist[i] = 1000000; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { int u = graph.edge[j].src; int v = graph.edge[j].dest; int weight = graph.edge[j].weight; if (dist[u] != 1000000 && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for (int i = 0; i < E; i++) { int u = graph.edge[i].src; int v = graph.edge[i].dest; int weight = graph.edge[i].weight; if (dist[u] != 1000000 && dist[u] + weight < dist[v]) return true; } return false; } // Driver Code public static void Main(string[] args) { int V = 5, E = 8; Graph graph = createGraph(V, E); // add edge 0-1 (or A-B in above figure) graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = -1; // add edge 0-2 (or A-C in above figure) graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 4; // add edge 1-2 (or B-C in above figure) graph.edge[2].src = 1; graph.edge[2].dest = 2; graph.edge[2].weight = 3; // add edge 1-3 (or B-D in above figure) graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 2; // add edge 1-4 (or A-E in above figure) graph.edge[4].src = 1; graph.edge[4].dest = 4; graph.edge[4].weight = 2; // add edge 3-2 (or D-C in above figure) graph.edge[5].src = 3; graph.edge[5].dest = 2; graph.edge[5].weight = 5; // add edge 3-1 (or D-B in above figure) graph.edge[6].src = 3; graph.edge[6].dest = 1; graph.edge[6].weight = 1; // add edge 4-3 (or E-D in above figure) graph.edge[7].src = 4; graph.edge[7].dest = 3; graph.edge[7].weight = -3; if (isNegCycleBellmanFord(graph, 0)) Console.Write(\"Yes\"); else Console.Write(\"No\"); }} // This code is contributed by rutvik_56",
"e": 16660,
"s": 12651,
"text": null
},
{
"code": "<script> // Javascript program to check if a graph contains negative// weight cycle using Bellman-Ford algorithm. This program// works only if all vertices are reachable from a source// vertex 0. // A structure to represent a weighted edge in graphclass Edge { constructor() { let src, dest, weight; }} // A structure to represent a connected, directed and// weighted graphclass Graph{ constructor() { // V-> Number of vertices, E-> Number of edges let V, E; // graph is represented as an array of edges. let edge = []; }} // Creates a graph with V vertices and E edgesfunction createGraph(V,E){ let graph = new Graph(); graph.V = V; graph.E = E; graph.edge = new Array(graph.E); for(let i = 0; i < graph.E; i++) { graph.edge[i] = new Edge(); } return graph;} // The main function that finds shortest distances// from src to all other vertices using Bellman-// Ford algorithm. The function also detects// negative weight cyclefunction isNegCycleBellmanFord(graph, src){ let V = graph.V; let E = graph.E; let dist = new Array(V); // Step 1: Initialize distances from src // to all other vertices as INFINITE for(let i = 0; i < V; i++) dist[i] = Number.MAX_VALUE; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for(let i = 1; i <= V - 1; i++) { for(let j = 0; j < E; j++) { let u = graph.edge[j].src; let v = graph.edge[j].dest; let weight = graph.edge[j].weight; if (dist[u] != Number.MAX_VALUE && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for(let i = 0; i < E; i++) { let u = graph.edge[i].src; let v = graph.edge[i].dest; let weight = graph.edge[i].weight; if (dist[u] != Number.MAX_VALUE && dist[u] + weight < dist[v]) return true; } return false;} // Driver Codelet V = 5, E = 8;let graph = createGraph(V, E); // Add edge 0-1 (or A-B in above figure)graph.edge[0].src = 0;graph.edge[0].dest = 1;graph.edge[0].weight = -1; // Add edge 0-2 (or A-C in above figure)graph.edge[1].src = 0;graph.edge[1].dest = 2;graph.edge[1].weight = 4; // add edge 1-2 (or B-C in above figure)graph.edge[2].src = 1;graph.edge[2].dest = 2;graph.edge[2].weight = 3; // Add edge 1-3 (or B-D in above figure)graph.edge[3].src = 1;graph.edge[3].dest = 3;graph.edge[3].weight = 2; // Add edge 1-4 (or A-E in above figure)graph.edge[4].src = 1;graph.edge[4].dest = 4;graph.edge[4].weight = 2; // Add edge 3-2 (or D-C in above figure)graph.edge[5].src = 3;graph.edge[5].dest = 2;graph.edge[5].weight = 5; // Add edge 3-1 (or D-B in above figure)graph.edge[6].src = 3;graph.edge[6].dest = 1;graph.edge[6].weight = 1; // add edge 4-3 (or E-D in above figure)graph.edge[7].src = 4;graph.edge[7].dest = 3;graph.edge[7].weight = -3; if (isNegCycleBellmanFord(graph, 0)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by unknown2108 </script>",
"e": 20134,
"s": 16660,
"text": null
},
{
"code": null,
"e": 20144,
"s": 20134,
"text": "Output : "
},
{
"code": null,
"e": 20147,
"s": 20144,
"text": "No"
},
{
"code": null,
"e": 20670,
"s": 20147,
"text": "How does it work? As discussed, the Bellman-Ford algorithm, for a given source, first calculates the shortest distances which have at most one edge in the path. Then, it calculates the shortest paths with at-most 2 edges, and so on. After the i-th iteration of the outer loop, the shortest paths with at most i edges are calculated. There can be a maximum |V| – 1 edge on any simple path, that is why the outer loop runs |v| – 1 time. If there is a negative weight cycle, then one more iteration would give a short route. "
},
{
"code": null,
"e": 21001,
"s": 20670,
"text": "How to handle a disconnected graph (If the cycle is not reachable from the source)? The above algorithm and program might not work if the given graph is disconnected. It works when all vertices are reachable from source vertex 0.To handle disconnected graphs, we can repeat the process for vertices for which distance is infinite."
},
{
"code": null,
"e": 21005,
"s": 21001,
"text": "C++"
},
{
"code": null,
"e": 21010,
"s": 21005,
"text": "Java"
},
{
"code": null,
"e": 21018,
"s": 21010,
"text": "Python3"
},
{
"code": null,
"e": 21021,
"s": 21018,
"text": "C#"
},
{
"code": null,
"e": 21032,
"s": 21021,
"text": "Javascript"
},
{
"code": "// A C++ program for Bellman-Ford's single source// shortest path algorithm.#include <bits/stdc++.h>using namespace std; // a structure to represent a weighted edge in graphstruct Edge { int src, dest, weight;}; // a structure to represent a connected, directed and// weighted graphstruct Graph { // V-> Number of vertices, E-> Number of edges int V, E; // graph is represented as an array of edges. struct Edge* edge;}; // Creates a graph with V vertices and E edgesstruct Graph* createGraph(int V, int E){ struct Graph* graph = new Graph; graph->V = V; graph->E = E; graph->edge = new Edge[graph->E]; return graph;} // The main function that finds shortest distances// from src to all other vertices using Bellman-// Ford algorithm. The function also detects// negative weight cyclebool isNegCycleBellmanFord(struct Graph* graph, int src, int dist[]){ int V = graph->V; int E = graph->E; // Step 1: Initialize distances from src // to all other vertices as INFINITE for (int i = 0; i < V; i++) dist[i] = INT_MAX; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for (int i = 1; i <= V - 1; i++) { for (int j = 0; j < E; j++) { int u = graph->edge[j].src; int v = graph->edge[j].dest; int weight = graph->edge[j].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for (int i = 0; i < E; i++) { int u = graph->edge[i].src; int v = graph->edge[i].dest; int weight = graph->edge[i].weight; if (dist[u] != INT_MAX && dist[u] + weight < dist[v]) return true; } return false;} // Returns true if given graph has negative weight// cycle.bool isNegCycleDisconnected(struct Graph* graph){ int V = graph->V; // To keep track of visited vertices to avoid // recomputations. bool visited[V]; memset(visited, 0, sizeof(visited)); // This array is filled by Bellman-Ford int dist[V]; // Call Bellman-Ford for all those vertices // that are not visited for (int i = 0; i < V; i++) { if (visited[i] == false) { // If cycle found if (isNegCycleBellmanFord(graph, i, dist)) return true; // Mark all vertices that are visited // in above call. for (int i = 0; i < V; i++) if (dist[i] != INT_MAX) visited[i] = true; } } return false;} // Driver program to test above functionsint main(){ /* Let us create the graph given in above example */ int V = 5; // Number of vertices in graph int E = 8; // Number of edges in graph struct Graph* graph = createGraph(V, E); // add edge 0-1 (or A-B in above figure) graph->edge[0].src = 0; graph->edge[0].dest = 1; graph->edge[0].weight = -1; // add edge 0-2 (or A-C in above figure) graph->edge[1].src = 0; graph->edge[1].dest = 2; graph->edge[1].weight = 4; // add edge 1-2 (or B-C in above figure) graph->edge[2].src = 1; graph->edge[2].dest = 2; graph->edge[2].weight = 3; // add edge 1-3 (or B-D in above figure) graph->edge[3].src = 1; graph->edge[3].dest = 3; graph->edge[3].weight = 2; // add edge 1-4 (or A-E in above figure) graph->edge[4].src = 1; graph->edge[4].dest = 4; graph->edge[4].weight = 2; // add edge 3-2 (or D-C in above figure) graph->edge[5].src = 3; graph->edge[5].dest = 2; graph->edge[5].weight = 5; // add edge 3-1 (or D-B in above figure) graph->edge[6].src = 3; graph->edge[6].dest = 1; graph->edge[6].weight = 1; // add edge 4-3 (or E-D in above figure) graph->edge[7].src = 4; graph->edge[7].dest = 3; graph->edge[7].weight = -3; if (isNegCycleDisconnected(graph)) cout << \"Yes\"; else cout << \"No\"; return 0;}",
"e": 25302,
"s": 21032,
"text": null
},
{
"code": "// A Java program for Bellman-Ford's single source // shortest path algorithm. import java.util.*; class GFG{ // A structure to represent a weighted // edge in graph static class Edge{ int src, dest, weight; } // A structure to represent a connected, // directed and weighted graph static class Graph { // V-> Number of vertices, // E-> Number of edges int V, E; // Graph is represented as // an array of edges. Edge edge[]; } // Creates a graph with V vertices and E edges static Graph createGraph(int V, int E){ Graph graph = new Graph(); graph.V = V; graph.E = E; graph.edge = new Edge[graph.E]; for(int i = 0; i < graph.E; i++) { graph.edge[i] = new Edge(); } return graph; } // The main function that finds shortest distances // from src to all other vertices using Bellman- // Ford algorithm. The function also detects // negative weight cycle static boolean isNegCycleBellmanFord(Graph graph, int src, int dist[]) { int V = graph.V; int E = graph.E; // Step 1: Initialize distances from src // to all other vertices as INFINITE for(int i = 0; i < V; i++) dist[i] = Integer.MAX_VALUE; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for(int i = 1; i <= V - 1; i++) { for(int j = 0; j < E; j++) { int u = graph.edge[j].src; int v = graph.edge[j].dest; int weight = graph.edge[j].weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for(int i = 0; i < E; i++) { int u = graph.edge[i].src; int v = graph.edge[i].dest; int weight = graph.edge[i].weight; if (dist[u] != Integer.MAX_VALUE && dist[u] + weight < dist[v]) return true; } return false; } // Returns true if given graph has negative weight // cycle. static boolean isNegCycleDisconnected(Graph graph) { int V = graph.V; // To keep track of visited vertices // to avoid recomputations. boolean visited[] = new boolean[V]; Arrays.fill(visited, false); // This array is filled by Bellman-Ford int dist[] = new int[V]; // Call Bellman-Ford for all those vertices // that are not visited for(int i = 0; i < V; i++) { if (visited[i] == false) { // If cycle found if (isNegCycleBellmanFord(graph, i, dist)) return true; // Mark all vertices that are visited // in above call. for(int j = 0; j < V; j++) if (dist[j] != Integer.MAX_VALUE) visited[j] = true; } } return false; } // Driver Code public static void main(String[] args) { int V = 5, E = 8; Graph graph = createGraph(V, E); // Add edge 0-1 (or A-B in above figure) graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = -1; // Add edge 0-2 (or A-C in above figure) graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 4; // Add edge 1-2 (or B-C in above figure) graph.edge[2].src = 1; graph.edge[2].dest = 2; graph.edge[2].weight = 3; // Add edge 1-3 (or B-D in above figure) graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 2; // Add edge 1-4 (or A-E in above figure) graph.edge[4].src = 1; graph.edge[4].dest = 4; graph.edge[4].weight = 2; // Add edge 3-2 (or D-C in above figure) graph.edge[5].src = 3; graph.edge[5].dest = 2; graph.edge[5].weight = 5; // Add edge 3-1 (or D-B in above figure) graph.edge[6].src = 3; graph.edge[6].dest = 1; graph.edge[6].weight = 1; // Add edge 4-3 (or E-D in above figure) graph.edge[7].src = 4; graph.edge[7].dest = 3; graph.edge[7].weight = -3; if (isNegCycleDisconnected(graph)) System.out.println(\"Yes\"); else System.out.println(\"No\"); } } // This code is contributed by adityapande88",
"e": 29902,
"s": 25302,
"text": null
},
{
"code": "# A Python3 program for Bellman-Ford's single source# shortest path algorithm. # The main function that finds shortest distances# from src to all other vertices using Bellman-# Ford algorithm. The function also detects# negative weight cycledef isNegCycleBellmanFord(src, dist): global graph, V, E # Step 1: Initialize distances from src # to all other vertices as INFINITE for i in range(V): dist[i] = 10**18 dist[src] = 0 # Step 2: Relax all edges |V| - 1 times. # A simple shortest path from src to any # other vertex can have at-most |V| - 1 # edges for i in range(1,V): for j in range(E): u = graph[j][0] v = graph[j][1] weight = graph[j][2] if (dist[u] != 10**18 and dist[u] + weight < dist[v]): dist[v] = dist[u] + weight # Step 3: check for negative-weight cycles. # The above step guarantees shortest distances # if graph doesn't contain negative weight cycle. # If we get a shorter path, then there # is a cycle. for i in range(E): u = graph[i][0] v = graph[i][1] weight = graph[i][2] if (dist[u] != 10**18 and dist[u] + weight < dist[v]): return True return False# Returns true if given graph has negative weight# cycle.def isNegCycleDisconnected(): global V, E, graph # To keep track of visited vertices to avoid # recomputations. visited = [0]*V # memset(visited, 0, sizeof(visited)) # This array is filled by Bellman-Ford dist = [0]*V # Call Bellman-Ford for all those vertices # that are not visited for i in range(V): if (visited[i] == 0): # If cycle found if (isNegCycleBellmanFord(i, dist)): return True # Mark all vertices that are visited # in above call. for i in range(V): if (dist[i] != 10**18): visited[i] = True return False # Driver codeif __name__ == '__main__': # /* Let us create the graph given in above example */ V = 5 # Number of vertices in graph E = 8 # Number of edges in graph graph = [[0, 0, 0] for i in range(8)] # add edge 0-1 (or A-B in above figure) graph[0][0] = 0 graph[0][1] = 1 graph[0][2] = -1 # add edge 0-2 (or A-C in above figure) graph[1][0] = 0 graph[1][1] = 2 graph[1][2] = 4 # add edge 1-2 (or B-C in above figure) graph[2][0] = 1 graph[2][1] = 2 graph[2][2] = 3 # add edge 1-3 (or B-D in above figure) graph[3][0] = 1 graph[3][1] = 3 graph[3][2] = 2 # add edge 1-4 (or A-E in above figure) graph[4][0] = 1 graph[4][1] = 4 graph[4][2] = 2 # add edge 3-2 (or D-C in above figure) graph[5][0] = 3 graph[5][1] = 2 graph[5][2] = 5 # add edge 3-1 (or D-B in above figure) graph[6][0] = 3 graph[6][1] = 1 graph[6][2] = 1 # add edge 4-3 (or E-D in above figure) graph[7][0] = 4 graph[7][1] = 3 graph[7][2] = -3 if (isNegCycleDisconnected()): print(\"Yes\") else: print(\"No\") # This code is contributed by mohit kumar 29",
"e": 33063,
"s": 29902,
"text": null
},
{
"code": "// A C# program for Bellman-Ford's single source // shortest path algorithm. using System;using System.Collections.Generic;public class GFG{ // A structure to represent a weighted // edge in graph public class Edge { public int src, dest, weight; } // A structure to represent a connected, // directed and weighted graph public class Graph { // V-> Number of vertices, // E-> Number of edges public int V, E; // Graph is represented as // an array of edges. public Edge []edge; } // Creates a graph with V vertices and E edges static Graph createGraph(int V, int E) { Graph graph = new Graph(); graph.V = V; graph.E = E; graph.edge = new Edge[graph.E]; for(int i = 0; i < graph.E; i++) { graph.edge[i] = new Edge(); } return graph; } // The main function that finds shortest distances // from src to all other vertices using Bellman- // Ford algorithm. The function also detects // negative weight cycle static bool isNegCycleBellmanFord(Graph graph, int src, int []dist) { int V = graph.V; int E = graph.E; // Step 1: Initialize distances from src // to all other vertices as INFINITE for(int i = 0; i < V; i++) dist[i] = int.MaxValue; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for(int i = 1; i <= V - 1; i++) { for(int j = 0; j < E; j++) { int u = graph.edge[j].src; int v = graph.edge[j].dest; int weight = graph.edge[j].weight; if (dist[u] != int.MaxValue && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for(int i = 0; i < E; i++) { int u = graph.edge[i].src; int v = graph.edge[i].dest; int weight = graph.edge[i].weight; if (dist[u] != int.MaxValue && dist[u] + weight < dist[v]) return true; } return false; } // Returns true if given graph has negative weight // cycle. static bool isNegCycleDisconnected(Graph graph) { int V = graph.V; // To keep track of visited vertices // to avoid recomputations. bool []visited = new bool[V]; // This array is filled by Bellman-Ford int []dist = new int[V]; // Call Bellman-Ford for all those vertices // that are not visited for(int i = 0; i < V; i++) { if (visited[i] == false) { // If cycle found if (isNegCycleBellmanFord(graph, i, dist)) return true; // Mark all vertices that are visited // in above call. for(int j = 0; j < V; j++) if (dist[j] != int.MaxValue) visited[j] = true; } } return false; } // Driver Code public static void Main(String[] args) { int V = 5, E = 8; Graph graph = createGraph(V, E); // Add edge 0-1 (or A-B in above figure) graph.edge[0].src = 0; graph.edge[0].dest = 1; graph.edge[0].weight = -1; // Add edge 0-2 (or A-C in above figure) graph.edge[1].src = 0; graph.edge[1].dest = 2; graph.edge[1].weight = 4; // Add edge 1-2 (or B-C in above figure) graph.edge[2].src = 1; graph.edge[2].dest = 2; graph.edge[2].weight = 3; // Add edge 1-3 (or B-D in above figure) graph.edge[3].src = 1; graph.edge[3].dest = 3; graph.edge[3].weight = 2; // Add edge 1-4 (or A-E in above figure) graph.edge[4].src = 1; graph.edge[4].dest = 4; graph.edge[4].weight = 2; // Add edge 3-2 (or D-C in above figure) graph.edge[5].src = 3; graph.edge[5].dest = 2; graph.edge[5].weight = 5; // Add edge 3-1 (or D-B in above figure) graph.edge[6].src = 3; graph.edge[6].dest = 1; graph.edge[6].weight = 1; // Add edge 4-3 (or E-D in above figure) graph.edge[7].src = 4; graph.edge[7].dest = 3; graph.edge[7].weight = -3; if (isNegCycleDisconnected(graph)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); } } // This code is contributed by aashish1995 ",
"e": 37596,
"s": 33063,
"text": null
},
{
"code": "<script>// A Javascript program for Bellman-Ford's single source// shortest path algorithm. // A structure to represent a weighted // edge in graph class Edge { constructor() { let src, dest, weight; } } // A structure to represent a connected, // directed and weighted graph class Graph { constructor() { // V-> Number of vertices, // E-> Number of edges let V, E; // Graph is represented as // an array of edges. let edge=[]; } } // Creates a graph with V vertices and E edges function createGraph(V,E) { let graph = new Graph(); graph.V = V; graph.E = E; graph.edge = new Array(graph.E); for(let i = 0; i < graph.E; i++) { graph.edge[i] = new Edge(); } return graph; } // The main function that finds shortest distances// from src to all other vertices using Bellman-// Ford algorithm. The function also detects// negative weight cyclefunction isNegCycleBellmanFord(graph,src,dist){ let V = graph.V; let E = graph.E; // Step 1: Initialize distances from src // to all other vertices as INFINITE for(let i = 0; i < V; i++) dist[i] = Number.MAX_VALUE; dist[src] = 0; // Step 2: Relax all edges |V| - 1 times. // A simple shortest path from src to any // other vertex can have at-most |V| - 1 // edges for(let i = 1; i <= V - 1; i++) { for(let j = 0; j < E; j++) { let u = graph.edge[j].src; let v = graph.edge[j].dest; let weight = graph.edge[j].weight; if (dist[u] != Number.MAX_VALUE && dist[u] + weight < dist[v]) dist[v] = dist[u] + weight; } } // Step 3: check for negative-weight cycles. // The above step guarantees shortest distances // if graph doesn't contain negative weight cycle. // If we get a shorter path, then there // is a cycle. for(let i = 0; i < E; i++) { let u = graph.edge[i].src; let v = graph.edge[i].dest; let weight = graph.edge[i].weight; if (dist[u] != Number.MAX_VALUE && dist[u] + weight < dist[v]) return true; } return false;} // Returns true if given graph has negative weight// cycle.function isNegCycleDisconnected(graph){ let V = graph.V; // To keep track of visited vertices // to avoid recomputations. let visited = new Array(V); for(let i=0;i<V;i++) { visited[i]=false; } // This array is filled by Bellman-Ford let dist = new Array(V); // Call Bellman-Ford for all those vertices // that are not visited for(let i = 0; i < V; i++) { if (visited[i] == false) { // If cycle found if (isNegCycleBellmanFord(graph, i, dist)) return true; // Mark all vertices that are visited // in above call. for(let j = 0; j < V; j++) if (dist[j] != Number.MAX_VALUE) visited[j] = true; } } return false;} // Driver Code let V = 5, E = 8;let graph = createGraph(V, E); // Add edge 0-1 (or A-B in above figure)graph.edge[0].src = 0;graph.edge[0].dest = 1;graph.edge[0].weight = -1; // Add edge 0-2 (or A-C in above figure)graph.edge[1].src = 0;graph.edge[1].dest = 2;graph.edge[1].weight = 4; // Add edge 1-2 (or B-C in above figure)graph.edge[2].src = 1;graph.edge[2].dest = 2;graph.edge[2].weight = 3; // Add edge 1-3 (or B-D in above figure)graph.edge[3].src = 1;graph.edge[3].dest = 3;graph.edge[3].weight = 2; // Add edge 1-4 (or A-E in above figure)graph.edge[4].src = 1;graph.edge[4].dest = 4;graph.edge[4].weight = 2; // Add edge 3-2 (or D-C in above figure)graph.edge[5].src = 3;graph.edge[5].dest = 2;graph.edge[5].weight = 5; // Add edge 3-1 (or D-B in above figure)graph.edge[6].src = 3;graph.edge[6].dest = 1;graph.edge[6].weight = 1; // Add edge 4-3 (or E-D in above figure)graph.edge[7].src = 4;graph.edge[7].dest = 3;graph.edge[7].weight = -3; if (isNegCycleDisconnected(graph)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by patel2127</script>",
"e": 41971,
"s": 37596,
"text": null
},
{
"code": null,
"e": 41981,
"s": 41971,
"text": "Output : "
},
{
"code": null,
"e": 41984,
"s": 41981,
"text": "No"
},
{
"code": null,
"e": 42030,
"s": 41984,
"text": "Detecting negative cycle using Floyd Warshall"
},
{
"code": null,
"e": 42445,
"s": 42030,
"text": "This article is contributed by kartik. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 42457,
"s": 42445,
"text": "sanjeev2552"
},
{
"code": null,
"e": 42471,
"s": 42457,
"text": "adityapande88"
},
{
"code": null,
"e": 42481,
"s": 42471,
"text": "rutvik_56"
},
{
"code": null,
"e": 42491,
"s": 42481,
"text": "pratham76"
},
{
"code": null,
"e": 42506,
"s": 42491,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 42518,
"s": 42506,
"text": "aashish1995"
},
{
"code": null,
"e": 42526,
"s": 42518,
"text": "vbxltra"
},
{
"code": null,
"e": 42538,
"s": 42526,
"text": "unknown2108"
},
{
"code": null,
"e": 42548,
"s": 42538,
"text": "patel2127"
},
{
"code": null,
"e": 42558,
"s": 42548,
"text": "lolhellno"
},
{
"code": null,
"e": 42575,
"s": 42558,
"text": "surinderdawra388"
},
{
"code": null,
"e": 42587,
"s": 42575,
"text": "graph-cycle"
},
{
"code": null,
"e": 42593,
"s": 42587,
"text": "Graph"
},
{
"code": null,
"e": 42599,
"s": 42593,
"text": "Graph"
}
] |
HashMap remove() Method in Java | 03 May, 2021
The java.util.HashMap.remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map.Syntax:
Hash_Map.remove(Object key)
Parameters: The method takes one parameter key whose mapping is to be removed from the Map.Return Value: The method returns the value that was previously mapped to the specified key if the key exists else the method returns NULL.Below programs illustrates the working of java.util.HashMap.remove() method: Program 1: When passing an existing key.
Java
// Java code to illustrate the remove() methodimport java.util.*; public class Hash_Map_Demo {public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, "Geeks"); hash_map.put(15, "4"); hash_map.put(20, "Geeks"); hash_map.put(25, "Welcomes"); hash_map.put(30, "You"); // Displaying the HashMap System.out.println("Initial Mappings are: " + hash_map); // Removing the existing key mapping String returned_value = (String)hash_map.remove(20); // Verifying the returned value System.out.println("Returned value is: "+ returned_value); // Displaying the new map System.out.println("New map is: "+ hash_map);}}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Returned value is: Geeks
New map is: {25=Welcomes, 10=Geeks, 30=You, 15=4}
Program 2: When passing a new key.
Java
// Java code to illustrate the remove() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, "Geeks"); hash_map.put(15, "4"); hash_map.put(20, "Geeks"); hash_map.put(25, "Welcomes"); hash_map.put(30, "You"); // Displaying the HashMap System.out.println("Initial Mappings are: " + hash_map); // Removing the new key mapping String returned_value = (String)hash_map.remove(50); // Verifying the returned value System.out.println("Returned value is: "+ returned_value); // Displaying the new map System.out.println("New map is: "+ hash_map); }}
Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Returned value is: null
New map is: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}
Note: The same operation can be performed with any type of Mappings with variation and combination of different data types.
simranarora5sos
Java - util package
Java-Collections
Java-Functions
Java-HashMap
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n03 May, 2021"
},
{
"code": null,
"e": 268,
"s": 53,
"text": "The java.util.HashMap.remove() is an inbuilt method of HashMap class and is used to remove the mapping of any particular key from the map. It basically removes the values for any particular key in the Map.Syntax: "
},
{
"code": null,
"e": 296,
"s": 268,
"text": "Hash_Map.remove(Object key)"
},
{
"code": null,
"e": 645,
"s": 296,
"text": "Parameters: The method takes one parameter key whose mapping is to be removed from the Map.Return Value: The method returns the value that was previously mapped to the specified key if the key exists else the method returns NULL.Below programs illustrates the working of java.util.HashMap.remove() method: Program 1: When passing an existing key. "
},
{
"code": null,
"e": 650,
"s": 645,
"text": "Java"
},
{
"code": "// Java code to illustrate the remove() methodimport java.util.*; public class Hash_Map_Demo {public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, \"Geeks\"); hash_map.put(15, \"4\"); hash_map.put(20, \"Geeks\"); hash_map.put(25, \"Welcomes\"); hash_map.put(30, \"You\"); // Displaying the HashMap System.out.println(\"Initial Mappings are: \" + hash_map); // Removing the existing key mapping String returned_value = (String)hash_map.remove(20); // Verifying the returned value System.out.println(\"Returned value is: \"+ returned_value); // Displaying the new map System.out.println(\"New map is: \"+ hash_map);}}",
"e": 1451,
"s": 650,
"text": null
},
{
"code": null,
"e": 1596,
"s": 1451,
"text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nReturned value is: Geeks\nNew map is: {25=Welcomes, 10=Geeks, 30=You, 15=4}"
},
{
"code": null,
"e": 1635,
"s": 1598,
"text": "Program 2: When passing a new key. "
},
{
"code": null,
"e": 1640,
"s": 1635,
"text": "Java"
},
{
"code": "// Java code to illustrate the remove() methodimport java.util.*; public class Hash_Map_Demo { public static void main(String[] args) { // Creating an empty HashMap HashMap<Integer, String> hash_map = new HashMap<Integer, String>(); // Mapping string values to int keys hash_map.put(10, \"Geeks\"); hash_map.put(15, \"4\"); hash_map.put(20, \"Geeks\"); hash_map.put(25, \"Welcomes\"); hash_map.put(30, \"You\"); // Displaying the HashMap System.out.println(\"Initial Mappings are: \" + hash_map); // Removing the new key mapping String returned_value = (String)hash_map.remove(50); // Verifying the returned value System.out.println(\"Returned value is: \"+ returned_value); // Displaying the new map System.out.println(\"New map is: \"+ hash_map); }}",
"e": 2482,
"s": 1640,
"text": null
},
{
"code": null,
"e": 2636,
"s": 2482,
"text": "Initial Mappings are: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}\nReturned value is: null\nNew map is: {20=Geeks, 25=Welcomes, 10=Geeks, 30=You, 15=4}"
},
{
"code": null,
"e": 2763,
"s": 2638,
"text": "Note: The same operation can be performed with any type of Mappings with variation and combination of different data types. "
},
{
"code": null,
"e": 2779,
"s": 2763,
"text": "simranarora5sos"
},
{
"code": null,
"e": 2799,
"s": 2779,
"text": "Java - util package"
},
{
"code": null,
"e": 2816,
"s": 2799,
"text": "Java-Collections"
},
{
"code": null,
"e": 2831,
"s": 2816,
"text": "Java-Functions"
},
{
"code": null,
"e": 2844,
"s": 2831,
"text": "Java-HashMap"
},
{
"code": null,
"e": 2849,
"s": 2844,
"text": "Java"
},
{
"code": null,
"e": 2854,
"s": 2849,
"text": "Java"
},
{
"code": null,
"e": 2871,
"s": 2854,
"text": "Java-Collections"
}
] |
Program to print binomial expansion series | 21 Jun, 2022
Given three integers, A, X and n, the task is to print terms of below binomial expression series. (A+X)n = nC0AnX0 + nC1An-1X1 + nC2An-2X2 +....+ nCnA0Xn Examples:
Input : A = 1, X = 1, n = 5
Output : 1 5 10 10 5 1
Input : A = 1, B = 2, n = 6
Output : 1 12 60 160 240 192 64
Simple Solution : We know that for each value of n there will be (n+1) term in the binomial series. So now we use a simple approach and calculate the value of each element of the series and print it .
nCr = (n!) / ((n-r)! * (r)!)
Below is value of general term.
Tr+1 = nCn-rAn-rXr
So at each position we have to find the value
of the general term and print that term .
C++
Java
Python3
C#
PHP
Javascript
// CPP program to print terms of binomial// series and also calculate sum of series.#include <bits/stdc++.h>using namespace std; // function to calculate factorial of// a numberint factorial(int n){ int f = 1; for (int i = 2; i <= n; i++) f *= i; return f;} // function to print the seriesvoid series(int A, int X, int n){ // calculating the value of n! int nFact = factorial(n); // loop to display the series for (int i = 0; i < n + 1; i++) { // For calculating the // value of nCr int niFact = factorial(n - i); int iFact = factorial(i); // calculating the value of // A to the power k and X to // the power k int aPow = pow(A, n - i); int xPow = pow(X, i); // display the series cout << (nFact * aPow * xPow) / (niFact * iFact) << " "; }} // main function startedint main(){ int A = 3, X = 4, n = 5; series(A, X, n); return 0;}
// Java program to print terms of binomial// series and also calculate sum of series. import java.io.*; class GFG { // function to calculate factorial of // a number static int factorial(int n) { int f = 1; for (int i = 2; i <= n; i++) f *= i; return f; } // function to print the series static void series(int A, int X, int n) { // calculating the value of n! int nFact = factorial(n); // loop to display the series for (int i = 0; i < n + 1; i++) { // For calculating the // value of nCr int niFact = factorial(n - i); int iFact = factorial(i); // calculating the value of // A to the power k and X to // the power k int aPow = (int)Math.pow(A, n - i); int xPow = (int)Math.pow(X, i); // display the series System.out.print((nFact * aPow * xPow) / (niFact * iFact) + " "); } } // main function started public static void main(String[] args) { int A = 3, X = 4, n = 5; series(A, X, n); }} // This code is contributed by vt_m.
# Python3 program to print terms of binomial# series and also calculate sum of series. # function to calculate factorial# of a numberdef factorial(n): f = 1 for i in range(2, n+1): f *= i return f # Function to print the seriesdef series(A, X, n): # calculating the value of n! nFact = factorial(n) # loop to display the series for i in range(0, n + 1): # For calculating the # value of nCr niFact = factorial(n - i) iFact = factorial(i) # calculating the value of # A to the power k and X to # the power k aPow = pow(A, n - i) xPow = pow(X, i) # display the series print (int((nFact * aPow * xPow) / (niFact * iFact)), end = " ") # Driver CodeA = 3; X = 4; n = 5series(A, X, n) # This code is contributed by Smitha Dinesh Semwal.
// C# program to print terms of binomial// series and also calculate sum of series.using System; class GFG { // function to calculate factorial of // a number static int factorial(int n) { int f = 1; for (int i = 2; i <= n; i++) f *= i; return f; } // function to print the series static void series(int A, int X, int n) { // calculating the value of n! int nFact = factorial(n); // loop to display the series for (int i = 0; i < n + 1; i++) { // For calculating the // value of nCr int niFact = factorial(n - i); int iFact = factorial(i); // calculating the value of // A to the power k and X to // the power k int aPow = (int)Math.Pow(A, n - i); int xPow = (int)Math.Pow(X, i); // display the series Console.Write((nFact * aPow * xPow) / (niFact * iFact) + " "); } } // main function started public static void Main() { int A = 3, X = 4, n = 5; series(A, X, n); }} // This code is contributed by anuj_67.
<?php// PHP program to print// terms of binomial// series and also// calculate sum of series. // function to calculate// factorial of a numberfunction factorial($n){ $f = 1; for ($i = 2; $i <= $n; $i++) $f *= $i; return $f;} // function to print the seriesfunction series($A, $X, $n){ // calculating the // value of n! $nFact = factorial($n); // loop to display // the series for ($i = 0; $i < $n + 1; $i++) { // For calculating the // value of nCr $niFact = factorial($n - $i); $iFact = factorial($i); // calculating the value of // A to the power k and X to // the power k $aPow = pow($A, $n - $i); $xPow = pow($X, $i); // display the series echo ($nFact * $aPow * $xPow) / ($niFact * $iFact) , " "; }} // Driver Code $A = 3; $X = 4; $n = 5; series($A, $X, $n); // This code is contributed by anuj_67.?>
<script> // JavaScript program to print terms of binomial// series and also calculate sum of series. // function to calculate factorial of // a number function factorial(n) { let f = 1; for (let i = 2; i <= n; i++) f *= i; return f; } // function to print the series function series(A, X, n) { // calculating the value of n! let nFact = factorial(n); // loop to display the series for (let i = 0; i < n + 1; i++) { // For calculating the // value of nCr let niFact = factorial(n - i); let iFact = factorial(i); // calculating the value of // A to the power k and X to // the power k let aPow = Math.pow(A, n - i); let xPow = Math.pow(X, i); // display the series document.write((nFact * aPow * xPow) / (niFact * iFact) + " "); } } // Driver Code let A = 3, X = 4, n = 5; series(A, X, n); // This code is contributed by chinmoy1997pal.</script>
243 1620 4320 5760 3840 1024
Time complexity : O(n2) Auxiliary Space : O(1)
Efficient Solution : The idea is to compute next term using previous term. We can compute next term in O(1) time. We use below property of Binomial Coefficients.nCi+1 = nCi*(n-i)/(i+1)
C++
Java
Python3
C#
PHP
Javascript
// CPP program to print terms of binomial// series and also calculate sum of series.#include <bits/stdc++.h>using namespace std; // function to print the seriesvoid series(int A, int X, int n){ // Calculating and printing first term int term = pow(A, n); cout << term << " "; // Computing and printing remaining terms for (int i = 1; i <= n; i++) { // Find current term using previous terms // We increment power of X by 1, decrement // power of A by 1 and compute nCi using // previous term by multiplying previous // term with (n - i + 1)/i term = term * X * (n - i + 1)/(i * A); cout << term << " "; }} // main function startedint main(){ int A = 3, X = 4, n = 5; series(A, X, n); return 0;}
// Java program to print terms of binomial// series and also calculate sum of series. import java.io.*; class GFG { // function to print the series static void series(int A, int X, int n) { // Calculating and printing first // term int term = (int)Math.pow(A, n); System.out.print(term + " "); // Computing and printing // remaining terms for (int i = 1; i <= n; i++) { // Find current term using // previous terms We increment // power of X by 1, decrement // power of A by 1 and compute // nCi using previous term by // multiplying previous term // with (n - i + 1)/i term = term * X * (n - i + 1) / (i * A); System.out.print(term + " "); } } // main function started public static void main(String[] args) { int A = 3, X = 4, n = 5; series(A, X, n); }} // This code is contributed by vt_m.
# Python 3 program to print terms of binomial# series and also calculate sum of series. # Function to print the seriesdef series(A, X, n): # Calculating and printing first term term = pow(A, n) print(term, end = " ") # Computing and printing remaining terms for i in range(1, n+1): # Find current term using previous terms # We increment power of X by 1, decrement # power of A by 1 and compute nCi using # previous term by multiplying previous # term with (n - i + 1)/i term = int(term * X * (n - i + 1)/(i * A)) print(term, end = " ") # Driver CodeA = 3; X = 4; n = 5series(A, X, n) # This code is contributed by Smitha Dinesh Semwal.
// C# program to print terms of binomial// series and also calculate sum of series. using System; public class GFG { // function to print the series static void series(int A, int X, int n) { // Calculating and printing first // term int term = (int)Math.Pow(A, n); Console.Write(term + " "); // Computing and printing // remaining terms for (int i = 1; i <= n; i++) { // Find current term using // previous terms We increment // power of X by 1, decrement // power of A by 1 and compute // nCi using previous term by // multiplying previous term // with (n - i + 1)/i term = term * X * (n - i + 1) / (i * A); Console.Write(term + " "); } } // main function started public static void Main() { int A = 3, X = 4, n = 5; series(A, X, n); }} // This code is contributed by anuj_67.
<?php// PHP program to print// terms of binomial// series and also// calculate sum of// series. // function to print// the seriesfunction series($A, $X, $n){ // Calculating and printing // first term $term = pow($A, $n); echo $term , " "; // Computing and printing // remaining terms for ($i = 1; $i <= $n; $i++) { // Find current term // using previous terms // We increment power // of X by 1, decrement // power of A by 1 and // compute nCi using // previous term by // multiplying previous // term with (n - i + 1)/i $term = $term * $X * ($n - $i + 1) / ($i * $A); echo $term , " "; }} // Driver Code $A = 3; $X = 4; $n = 5; series($A, $X, $n); // This code is contributed by anuj_67.?>
<script> // JavaScript program to print terms of binomial// series and also calculate sum of series. // function to print the seriesfunction series(A, X, n){ // Calculating and printing first term let term = Math.pow(A, n); document.write(term + " "); // Computing and printing remaining terms for (let i = 1; i <= n; i++) { // Find current term using previous terms // We increment power of X by 1, decrement // power of A by 1 and compute nCi using // previous term by multiplying previous // term with (n - i + 1)/i term = term * X * (n - i + 1)/(i * A); document.write(term + " "); }} // main function started let A = 3, X = 4, n = 5; series(A, X, n); // This code is contributed by Surbhi Tyagi. </script>
243 1620 4320 5760 3840 1024
Time complexity : O(n) Auxiliary Space : O(1)
vt_m
Akanksha_Rai
chinmoy1997pal
surbhityagi15
ankita_saini
polymatir3j
binomial coefficient
Combinatorial
Mathematical
Mathematical
Combinatorial
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": 217,
"s": 52,
"text": "Given three integers, A, X and n, the task is to print terms of below binomial expression series. (A+X)n = nC0AnX0 + nC1An-1X1 + nC2An-2X2 +....+ nCnA0Xn Examples: "
},
{
"code": null,
"e": 330,
"s": 217,
"text": "Input : A = 1, X = 1, n = 5\nOutput : 1 5 10 10 5 1\n\nInput : A = 1, B = 2, n = 6\nOutput : 1 12 60 160 240 192 64 "
},
{
"code": null,
"e": 532,
"s": 330,
"text": "Simple Solution : We know that for each value of n there will be (n+1) term in the binomial series. So now we use a simple approach and calculate the value of each element of the series and print it . "
},
{
"code": null,
"e": 703,
"s": 532,
"text": "nCr = (n!) / ((n-r)! * (r)!)\n\nBelow is value of general term. \nTr+1 = nCn-rAn-rXr\nSo at each position we have to find the value \nof the general term and print that term ."
},
{
"code": null,
"e": 707,
"s": 703,
"text": "C++"
},
{
"code": null,
"e": 712,
"s": 707,
"text": "Java"
},
{
"code": null,
"e": 720,
"s": 712,
"text": "Python3"
},
{
"code": null,
"e": 723,
"s": 720,
"text": "C#"
},
{
"code": null,
"e": 727,
"s": 723,
"text": "PHP"
},
{
"code": null,
"e": 738,
"s": 727,
"text": "Javascript"
},
{
"code": "// CPP program to print terms of binomial// series and also calculate sum of series.#include <bits/stdc++.h>using namespace std; // function to calculate factorial of// a numberint factorial(int n){ int f = 1; for (int i = 2; i <= n; i++) f *= i; return f;} // function to print the seriesvoid series(int A, int X, int n){ // calculating the value of n! int nFact = factorial(n); // loop to display the series for (int i = 0; i < n + 1; i++) { // For calculating the // value of nCr int niFact = factorial(n - i); int iFact = factorial(i); // calculating the value of // A to the power k and X to // the power k int aPow = pow(A, n - i); int xPow = pow(X, i); // display the series cout << (nFact * aPow * xPow) / (niFact * iFact) << \" \"; }} // main function startedint main(){ int A = 3, X = 4, n = 5; series(A, X, n); return 0;}",
"e": 1725,
"s": 738,
"text": null
},
{
"code": "// Java program to print terms of binomial// series and also calculate sum of series. import java.io.*; class GFG { // function to calculate factorial of // a number static int factorial(int n) { int f = 1; for (int i = 2; i <= n; i++) f *= i; return f; } // function to print the series static void series(int A, int X, int n) { // calculating the value of n! int nFact = factorial(n); // loop to display the series for (int i = 0; i < n + 1; i++) { // For calculating the // value of nCr int niFact = factorial(n - i); int iFact = factorial(i); // calculating the value of // A to the power k and X to // the power k int aPow = (int)Math.pow(A, n - i); int xPow = (int)Math.pow(X, i); // display the series System.out.print((nFact * aPow * xPow) / (niFact * iFact) + \" \"); } } // main function started public static void main(String[] args) { int A = 3, X = 4, n = 5; series(A, X, n); }} // This code is contributed by vt_m.",
"e": 2959,
"s": 1725,
"text": null
},
{
"code": "# Python3 program to print terms of binomial# series and also calculate sum of series. # function to calculate factorial# of a numberdef factorial(n): f = 1 for i in range(2, n+1): f *= i return f # Function to print the seriesdef series(A, X, n): # calculating the value of n! nFact = factorial(n) # loop to display the series for i in range(0, n + 1): # For calculating the # value of nCr niFact = factorial(n - i) iFact = factorial(i) # calculating the value of # A to the power k and X to # the power k aPow = pow(A, n - i) xPow = pow(X, i) # display the series print (int((nFact * aPow * xPow) / (niFact * iFact)), end = \" \") # Driver CodeA = 3; X = 4; n = 5series(A, X, n) # This code is contributed by Smitha Dinesh Semwal.",
"e": 3844,
"s": 2959,
"text": null
},
{
"code": "// C# program to print terms of binomial// series and also calculate sum of series.using System; class GFG { // function to calculate factorial of // a number static int factorial(int n) { int f = 1; for (int i = 2; i <= n; i++) f *= i; return f; } // function to print the series static void series(int A, int X, int n) { // calculating the value of n! int nFact = factorial(n); // loop to display the series for (int i = 0; i < n + 1; i++) { // For calculating the // value of nCr int niFact = factorial(n - i); int iFact = factorial(i); // calculating the value of // A to the power k and X to // the power k int aPow = (int)Math.Pow(A, n - i); int xPow = (int)Math.Pow(X, i); // display the series Console.Write((nFact * aPow * xPow) / (niFact * iFact) + \" \"); } } // main function started public static void Main() { int A = 3, X = 4, n = 5; series(A, X, n); }} // This code is contributed by anuj_67.",
"e": 5054,
"s": 3844,
"text": null
},
{
"code": "<?php// PHP program to print// terms of binomial// series and also// calculate sum of series. // function to calculate// factorial of a numberfunction factorial($n){ $f = 1; for ($i = 2; $i <= $n; $i++) $f *= $i; return $f;} // function to print the seriesfunction series($A, $X, $n){ // calculating the // value of n! $nFact = factorial($n); // loop to display // the series for ($i = 0; $i < $n + 1; $i++) { // For calculating the // value of nCr $niFact = factorial($n - $i); $iFact = factorial($i); // calculating the value of // A to the power k and X to // the power k $aPow = pow($A, $n - $i); $xPow = pow($X, $i); // display the series echo ($nFact * $aPow * $xPow) / ($niFact * $iFact) , \" \"; }} // Driver Code $A = 3; $X = 4; $n = 5; series($A, $X, $n); // This code is contributed by anuj_67.?>",
"e": 6022,
"s": 5054,
"text": null
},
{
"code": "<script> // JavaScript program to print terms of binomial// series and also calculate sum of series. // function to calculate factorial of // a number function factorial(n) { let f = 1; for (let i = 2; i <= n; i++) f *= i; return f; } // function to print the series function series(A, X, n) { // calculating the value of n! let nFact = factorial(n); // loop to display the series for (let i = 0; i < n + 1; i++) { // For calculating the // value of nCr let niFact = factorial(n - i); let iFact = factorial(i); // calculating the value of // A to the power k and X to // the power k let aPow = Math.pow(A, n - i); let xPow = Math.pow(X, i); // display the series document.write((nFact * aPow * xPow) / (niFact * iFact) + \" \"); } } // Driver Code let A = 3, X = 4, n = 5; series(A, X, n); // This code is contributed by chinmoy1997pal.</script>",
"e": 7182,
"s": 6022,
"text": null
},
{
"code": null,
"e": 7212,
"s": 7182,
"text": "243 1620 4320 5760 3840 1024 "
},
{
"code": null,
"e": 7261,
"s": 7214,
"text": "Time complexity : O(n2) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 7446,
"s": 7261,
"text": "Efficient Solution : The idea is to compute next term using previous term. We can compute next term in O(1) time. We use below property of Binomial Coefficients.nCi+1 = nCi*(n-i)/(i+1)"
},
{
"code": null,
"e": 7450,
"s": 7446,
"text": "C++"
},
{
"code": null,
"e": 7455,
"s": 7450,
"text": "Java"
},
{
"code": null,
"e": 7463,
"s": 7455,
"text": "Python3"
},
{
"code": null,
"e": 7466,
"s": 7463,
"text": "C#"
},
{
"code": null,
"e": 7470,
"s": 7466,
"text": "PHP"
},
{
"code": null,
"e": 7481,
"s": 7470,
"text": "Javascript"
},
{
"code": "// CPP program to print terms of binomial// series and also calculate sum of series.#include <bits/stdc++.h>using namespace std; // function to print the seriesvoid series(int A, int X, int n){ // Calculating and printing first term int term = pow(A, n); cout << term << \" \"; // Computing and printing remaining terms for (int i = 1; i <= n; i++) { // Find current term using previous terms // We increment power of X by 1, decrement // power of A by 1 and compute nCi using // previous term by multiplying previous // term with (n - i + 1)/i term = term * X * (n - i + 1)/(i * A); cout << term << \" \"; }} // main function startedint main(){ int A = 3, X = 4, n = 5; series(A, X, n); return 0;}",
"e": 8255,
"s": 7481,
"text": null
},
{
"code": "// Java program to print terms of binomial// series and also calculate sum of series. import java.io.*; class GFG { // function to print the series static void series(int A, int X, int n) { // Calculating and printing first // term int term = (int)Math.pow(A, n); System.out.print(term + \" \"); // Computing and printing // remaining terms for (int i = 1; i <= n; i++) { // Find current term using // previous terms We increment // power of X by 1, decrement // power of A by 1 and compute // nCi using previous term by // multiplying previous term // with (n - i + 1)/i term = term * X * (n - i + 1) / (i * A); System.out.print(term + \" \"); } } // main function started public static void main(String[] args) { int A = 3, X = 4, n = 5; series(A, X, n); }} // This code is contributed by vt_m.",
"e": 9299,
"s": 8255,
"text": null
},
{
"code": "# Python 3 program to print terms of binomial# series and also calculate sum of series. # Function to print the seriesdef series(A, X, n): # Calculating and printing first term term = pow(A, n) print(term, end = \" \") # Computing and printing remaining terms for i in range(1, n+1): # Find current term using previous terms # We increment power of X by 1, decrement # power of A by 1 and compute nCi using # previous term by multiplying previous # term with (n - i + 1)/i term = int(term * X * (n - i + 1)/(i * A)) print(term, end = \" \") # Driver CodeA = 3; X = 4; n = 5series(A, X, n) # This code is contributed by Smitha Dinesh Semwal.",
"e": 10008,
"s": 9299,
"text": null
},
{
"code": "// C# program to print terms of binomial// series and also calculate sum of series. using System; public class GFG { // function to print the series static void series(int A, int X, int n) { // Calculating and printing first // term int term = (int)Math.Pow(A, n); Console.Write(term + \" \"); // Computing and printing // remaining terms for (int i = 1; i <= n; i++) { // Find current term using // previous terms We increment // power of X by 1, decrement // power of A by 1 and compute // nCi using previous term by // multiplying previous term // with (n - i + 1)/i term = term * X * (n - i + 1) / (i * A); Console.Write(term + \" \"); } } // main function started public static void Main() { int A = 3, X = 4, n = 5; series(A, X, n); }} // This code is contributed by anuj_67.",
"e": 11035,
"s": 10008,
"text": null
},
{
"code": "<?php// PHP program to print// terms of binomial// series and also// calculate sum of// series. // function to print// the seriesfunction series($A, $X, $n){ // Calculating and printing // first term $term = pow($A, $n); echo $term , \" \"; // Computing and printing // remaining terms for ($i = 1; $i <= $n; $i++) { // Find current term // using previous terms // We increment power // of X by 1, decrement // power of A by 1 and // compute nCi using // previous term by // multiplying previous // term with (n - i + 1)/i $term = $term * $X * ($n - $i + 1) / ($i * $A); echo $term , \" \"; }} // Driver Code $A = 3; $X = 4; $n = 5; series($A, $X, $n); // This code is contributed by anuj_67.?>",
"e": 11886,
"s": 11035,
"text": null
},
{
"code": "<script> // JavaScript program to print terms of binomial// series and also calculate sum of series. // function to print the seriesfunction series(A, X, n){ // Calculating and printing first term let term = Math.pow(A, n); document.write(term + \" \"); // Computing and printing remaining terms for (let i = 1; i <= n; i++) { // Find current term using previous terms // We increment power of X by 1, decrement // power of A by 1 and compute nCi using // previous term by multiplying previous // term with (n - i + 1)/i term = term * X * (n - i + 1)/(i * A); document.write(term + \" \"); }} // main function started let A = 3, X = 4, n = 5; series(A, X, n); // This code is contributed by Surbhi Tyagi. </script>",
"e": 12674,
"s": 11886,
"text": null
},
{
"code": null,
"e": 12704,
"s": 12674,
"text": "243 1620 4320 5760 3840 1024 "
},
{
"code": null,
"e": 12752,
"s": 12706,
"text": "Time complexity : O(n) Auxiliary Space : O(1)"
},
{
"code": null,
"e": 12757,
"s": 12752,
"text": "vt_m"
},
{
"code": null,
"e": 12770,
"s": 12757,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 12785,
"s": 12770,
"text": "chinmoy1997pal"
},
{
"code": null,
"e": 12799,
"s": 12785,
"text": "surbhityagi15"
},
{
"code": null,
"e": 12812,
"s": 12799,
"text": "ankita_saini"
},
{
"code": null,
"e": 12824,
"s": 12812,
"text": "polymatir3j"
},
{
"code": null,
"e": 12845,
"s": 12824,
"text": "binomial coefficient"
},
{
"code": null,
"e": 12859,
"s": 12845,
"text": "Combinatorial"
},
{
"code": null,
"e": 12872,
"s": 12859,
"text": "Mathematical"
},
{
"code": null,
"e": 12885,
"s": 12872,
"text": "Mathematical"
},
{
"code": null,
"e": 12899,
"s": 12885,
"text": "Combinatorial"
}
] |
Python – Sympy Polygon.distance() method | 01 Aug, 2020
In Sympy, the function Polygon.distance() is used to return the shortest distance between the given polygon and o. If o is a point, then given polygon does not need to be convex. But If o is another polygon then, the given polygon and o must be convex.
Syntax: Polygon.distance(o)
Parameters:
o:Point or Polygon
Returns: the shortest distance between the given polygon and o.
Example #1:
Python3
# import sympy import Point, Polygonfrom sympy import Point, Polygon # creating points using Point()p1, p2, p3, p4 = map(Point, [(0, 2), (0, 0), (1, 0), (1, 2)]) # creating polygon using Polygon()poly = Polygon(p1, p2, p3, p4) # using distance()shortestDistance = poly.distance(Point(3, 5)) print(shortestDistance)
Output:
sqrt(13)
Example #2:
Python3
# import sympy import Point, Polygon, RegularPolygonfrom sympy import Point, Polygon, RegularPolygon # creating points using Point()p1, p2 = map(Point, [(0, 0), (7, 5)]) # creating polygon using Polygon() and RegularPolygon()poly = Polygon(*RegularPolygon(p1, 1, 3).vertices) # using distance()shortestDistance = poly.distance(p2) print(shortestDistance)
Output:
sqrt(61)
Python SymPy-Geometry
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 281,
"s": 28,
"text": "In Sympy, the function Polygon.distance() is used to return the shortest distance between the given polygon and o. If o is a point, then given polygon does not need to be convex. But If o is another polygon then, the given polygon and o must be convex."
},
{
"code": null,
"e": 407,
"s": 281,
"text": "Syntax: Polygon.distance(o)\n\nParameters:\n o:Point or Polygon\n\nReturns: the shortest distance between the given polygon and o."
},
{
"code": null,
"e": 419,
"s": 407,
"text": "Example #1:"
},
{
"code": null,
"e": 427,
"s": 419,
"text": "Python3"
},
{
"code": "# import sympy import Point, Polygonfrom sympy import Point, Polygon # creating points using Point()p1, p2, p3, p4 = map(Point, [(0, 2), (0, 0), (1, 0), (1, 2)]) # creating polygon using Polygon()poly = Polygon(p1, p2, p3, p4) # using distance()shortestDistance = poly.distance(Point(3, 5)) print(shortestDistance)",
"e": 746,
"s": 427,
"text": null
},
{
"code": null,
"e": 754,
"s": 746,
"text": "Output:"
},
{
"code": null,
"e": 763,
"s": 754,
"text": "sqrt(13)"
},
{
"code": null,
"e": 775,
"s": 763,
"text": "Example #2:"
},
{
"code": null,
"e": 783,
"s": 775,
"text": "Python3"
},
{
"code": "# import sympy import Point, Polygon, RegularPolygonfrom sympy import Point, Polygon, RegularPolygon # creating points using Point()p1, p2 = map(Point, [(0, 0), (7, 5)]) # creating polygon using Polygon() and RegularPolygon()poly = Polygon(*RegularPolygon(p1, 1, 3).vertices) # using distance()shortestDistance = poly.distance(p2) print(shortestDistance)",
"e": 1142,
"s": 783,
"text": null
},
{
"code": null,
"e": 1150,
"s": 1142,
"text": "Output:"
},
{
"code": null,
"e": 1159,
"s": 1150,
"text": "sqrt(61)"
},
{
"code": null,
"e": 1181,
"s": 1159,
"text": "Python SymPy-Geometry"
},
{
"code": null,
"e": 1187,
"s": 1181,
"text": "SymPy"
},
{
"code": null,
"e": 1194,
"s": 1187,
"text": "Python"
}
] |
Dynamically generating a QR code using PHP | 15 May, 2019
There are a number of open source libraries available online which can be used to generate a Quick Response(QR) Code. A good open source library for QR code generation in PHP is available in sourceforge. It just needs to be downloaded and copied in the project folder. This includes a module named “phpqrcode” in which there is a file named “qrlib.php”. This file must be included in the code to use a function named ‘png()’, which is inside QRcode class. png() function outputs directly a QR code in the browser when we pass some text as a parameter, but we can also create a file and store it.
Syntax:
QRcode::png($text, $file, $ecc, $pixel_Size, $frame_Size);
Parameters: This function accepts five parameters as mentioned above and described below:
$text: This parameter gives the message which needs to be in QR code. It is mandatory parameter.
$file: It specifies the place to save the generated QR.
$ecc: This parameter specifies the error correction capability of QR. It has 4 levels L, M, Q and H.
$pixel_Size: This specifies the pixel size of QR.
$frame_Size: This specifies the size of Qr. It is from level 1-10.
Example 1: PHP program to generate QR Code.
<?php // Include the qrlib fileinclude 'phpqrcode/qrlib.php'; // $text variable has data for QR $text = "GEEKS FOR GEEKS"; // QR Code generation using png()// When this function has only the// text parameter it directly// outputs QR in the browserQRcode::png($text);?>
Output:
Note: This output is directly generated in the browser. This code will not run on an online IDE because it can’t include ‘phpqrcode’ module.
Example 2: PHP program to generate QR Code and create file.
<?php// Include the qrlib fileinclude 'phpqrcode/qrlib.php';$text = "GEEKS FOR GEEKS"; // $path variable store the location where to // store image and $file creates directory name// of the QR code file by using 'uniqid'// uniqid creates unique id based on microtime$path = 'images/';$file = $path.uniqid().".png"; // $ecc stores error correction capability('L')$ecc = 'L';$pixel_Size = 10;$frame_Size = 10; // Generates QR Code and Stores it in directory givenQRcode::png($text, $file, $ecc, $pixel_Size, $frame_size); // Displaying the stored QR code from directoryecho "<center><img src='".$file."'></center>";?>
Output:
Note: The output of both examples are different. In the first example, the output will display in default frame and pixel size which is generated directly on browser whereas the output of the second example is a ‘png’ file with pixel and frame size as 10 stored in a directory.
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to check whether an array is empty using PHP?
PHP | Converting string to Date and DateTime
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to Upload Image into Database and Display it using PHP ?
How to call PHP function on the click of a Button ?
How to check whether an array is empty using PHP? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 May, 2019"
},
{
"code": null,
"e": 648,
"s": 52,
"text": "There are a number of open source libraries available online which can be used to generate a Quick Response(QR) Code. A good open source library for QR code generation in PHP is available in sourceforge. It just needs to be downloaded and copied in the project folder. This includes a module named “phpqrcode” in which there is a file named “qrlib.php”. This file must be included in the code to use a function named ‘png()’, which is inside QRcode class. png() function outputs directly a QR code in the browser when we pass some text as a parameter, but we can also create a file and store it."
},
{
"code": null,
"e": 656,
"s": 648,
"text": "Syntax:"
},
{
"code": null,
"e": 715,
"s": 656,
"text": "QRcode::png($text, $file, $ecc, $pixel_Size, $frame_Size);"
},
{
"code": null,
"e": 805,
"s": 715,
"text": "Parameters: This function accepts five parameters as mentioned above and described below:"
},
{
"code": null,
"e": 902,
"s": 805,
"text": "$text: This parameter gives the message which needs to be in QR code. It is mandatory parameter."
},
{
"code": null,
"e": 958,
"s": 902,
"text": "$file: It specifies the place to save the generated QR."
},
{
"code": null,
"e": 1059,
"s": 958,
"text": "$ecc: This parameter specifies the error correction capability of QR. It has 4 levels L, M, Q and H."
},
{
"code": null,
"e": 1109,
"s": 1059,
"text": "$pixel_Size: This specifies the pixel size of QR."
},
{
"code": null,
"e": 1176,
"s": 1109,
"text": "$frame_Size: This specifies the size of Qr. It is from level 1-10."
},
{
"code": null,
"e": 1220,
"s": 1176,
"text": "Example 1: PHP program to generate QR Code."
},
{
"code": "<?php // Include the qrlib fileinclude 'phpqrcode/qrlib.php'; // $text variable has data for QR $text = \"GEEKS FOR GEEKS\"; // QR Code generation using png()// When this function has only the// text parameter it directly// outputs QR in the browserQRcode::png($text);?>",
"e": 1492,
"s": 1220,
"text": null
},
{
"code": null,
"e": 1500,
"s": 1492,
"text": "Output:"
},
{
"code": null,
"e": 1641,
"s": 1500,
"text": "Note: This output is directly generated in the browser. This code will not run on an online IDE because it can’t include ‘phpqrcode’ module."
},
{
"code": null,
"e": 1701,
"s": 1641,
"text": "Example 2: PHP program to generate QR Code and create file."
},
{
"code": "<?php// Include the qrlib fileinclude 'phpqrcode/qrlib.php';$text = \"GEEKS FOR GEEKS\"; // $path variable store the location where to // store image and $file creates directory name// of the QR code file by using 'uniqid'// uniqid creates unique id based on microtime$path = 'images/';$file = $path.uniqid().\".png\"; // $ecc stores error correction capability('L')$ecc = 'L';$pixel_Size = 10;$frame_Size = 10; // Generates QR Code and Stores it in directory givenQRcode::png($text, $file, $ecc, $pixel_Size, $frame_size); // Displaying the stored QR code from directoryecho \"<center><img src='\".$file.\"'></center>\";?>",
"e": 2321,
"s": 1701,
"text": null
},
{
"code": null,
"e": 2329,
"s": 2321,
"text": "Output:"
},
{
"code": null,
"e": 2607,
"s": 2329,
"text": "Note: The output of both examples are different. In the first example, the output will display in default frame and pixel size which is generated directly on browser whereas the output of the second example is a ‘png’ file with pixel and frame size as 10 stored in a directory."
},
{
"code": null,
"e": 2614,
"s": 2607,
"text": "Picked"
},
{
"code": null,
"e": 2618,
"s": 2614,
"text": "PHP"
},
{
"code": null,
"e": 2631,
"s": 2618,
"text": "PHP Programs"
},
{
"code": null,
"e": 2648,
"s": 2631,
"text": "Web Technologies"
},
{
"code": null,
"e": 2675,
"s": 2648,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2679,
"s": 2675,
"text": "PHP"
},
{
"code": null,
"e": 2777,
"s": 2679,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2827,
"s": 2777,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2867,
"s": 2827,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 2928,
"s": 2867,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 2978,
"s": 2928,
"text": "How to check whether an array is empty using PHP?"
},
{
"code": null,
"e": 3023,
"s": 2978,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 3073,
"s": 3023,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 3113,
"s": 3073,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3174,
"s": 3113,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 3226,
"s": 3174,
"text": "How to call PHP function on the click of a Button ?"
}
] |
Get current date using Python | 27 Dec, 2019
Prerequisite: datetime module
In Python, date and time are not a data type of its own, but a module named datetime can be imported to work with the date as well as time. Datetime module comes built into Python, so there is no need to install it externally.
datetime module provide some functions to get the current date as well as time. Let’s look at them.
date.today(): today() method of date class under datetime module returns a date object which contains the value of Today’s date.Syntax: date.today()Returns: Return the current local date.Example:# Python program to get# current date # Import date class from datetime modulefrom datetime import date # Returns the current local datetoday = date.today()print("Today date is: ", today)Output:Today date is: 2019-12-11
Syntax: date.today()
Returns: Return the current local date.
Example:
# Python program to get# current date # Import date class from datetime modulefrom datetime import date # Returns the current local datetoday = date.today()print("Today date is: ", today)
Output:
Today date is: 2019-12-11
datetime.now(): Python library defines a function that can be primarily used to get current time and date. now() function Return the current local date and time, which is defined under datetime module.Syntax: datetime.now(tz)Parameters :tz : Specified time zone of which current time and date is required. (Uses Greenwich Meridian time by default.)Returns : Returns the current date and time in time format.Example:# Python program to get# current date # Import datetime class from datetime modulefrom datetime import datetime # returns current date and timenow = datetime.now()print("now = ", now)Output:now = 2019-12-11 10:58:37.039404
Attributes of now() :now() has different attributes, same as attributes of time such as year, month, date, hour, minute, second.Example 3: Demonstrate attributes of now().# Python3 code to demonstrate # attributes of now() # importing datetime module for now() import datetime # using now() to get current time current_time = datetime.datetime.now() # Printing attributes of now(). print ("The attributes of now() are : ") print ("Year : ", end = "") print (current_time.year) print ("Month : ", end = "") print (current_time.month) print ("Day : ", end = "") print (current_time.day) Output:The attributes of now() are :
Year : 2019
Month : 12
Day : 11
Syntax: datetime.now(tz)
Parameters :tz : Specified time zone of which current time and date is required. (Uses Greenwich Meridian time by default.)
Returns : Returns the current date and time in time format.
Example:
# Python program to get# current date # Import datetime class from datetime modulefrom datetime import datetime # returns current date and timenow = datetime.now()print("now = ", now)
Output:
now = 2019-12-11 10:58:37.039404
Attributes of now() :now() has different attributes, same as attributes of time such as year, month, date, hour, minute, second.
Example 3: Demonstrate attributes of now().
# Python3 code to demonstrate # attributes of now() # importing datetime module for now() import datetime # using now() to get current time current_time = datetime.datetime.now() # Printing attributes of now(). print ("The attributes of now() are : ") print ("Year : ", end = "") print (current_time.year) print ("Month : ", end = "") print (current_time.month) print ("Day : ", end = "") print (current_time.day)
Output:
The attributes of now() are :
Year : 2019
Month : 12
Day : 11
Python datetime-program
Python-datetime
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
Python Classes and Objects
Iterate over a list in Python
Convert integer to string in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Dec, 2019"
},
{
"code": null,
"e": 58,
"s": 28,
"text": "Prerequisite: datetime module"
},
{
"code": null,
"e": 285,
"s": 58,
"text": "In Python, date and time are not a data type of its own, but a module named datetime can be imported to work with the date as well as time. Datetime module comes built into Python, so there is no need to install it externally."
},
{
"code": null,
"e": 385,
"s": 285,
"text": "datetime module provide some functions to get the current date as well as time. Let’s look at them."
},
{
"code": null,
"e": 808,
"s": 385,
"text": "date.today(): today() method of date class under datetime module returns a date object which contains the value of Today’s date.Syntax: date.today()Returns: Return the current local date.Example:# Python program to get# current date # Import date class from datetime modulefrom datetime import date # Returns the current local datetoday = date.today()print(\"Today date is: \", today)Output:Today date is: 2019-12-11\n"
},
{
"code": null,
"e": 829,
"s": 808,
"text": "Syntax: date.today()"
},
{
"code": null,
"e": 869,
"s": 829,
"text": "Returns: Return the current local date."
},
{
"code": null,
"e": 878,
"s": 869,
"text": "Example:"
},
{
"code": "# Python program to get# current date # Import date class from datetime modulefrom datetime import date # Returns the current local datetoday = date.today()print(\"Today date is: \", today)",
"e": 1072,
"s": 878,
"text": null
},
{
"code": null,
"e": 1080,
"s": 1072,
"text": "Output:"
},
{
"code": null,
"e": 1108,
"s": 1080,
"text": "Today date is: 2019-12-11\n"
},
{
"code": null,
"e": 2433,
"s": 1108,
"text": "datetime.now(): Python library defines a function that can be primarily used to get current time and date. now() function Return the current local date and time, which is defined under datetime module.Syntax: datetime.now(tz)Parameters :tz : Specified time zone of which current time and date is required. (Uses Greenwich Meridian time by default.)Returns : Returns the current date and time in time format.Example:# Python program to get# current date # Import datetime class from datetime modulefrom datetime import datetime # returns current date and timenow = datetime.now()print(\"now = \", now)Output:now = 2019-12-11 10:58:37.039404\nAttributes of now() :now() has different attributes, same as attributes of time such as year, month, date, hour, minute, second.Example 3: Demonstrate attributes of now().# Python3 code to demonstrate # attributes of now() # importing datetime module for now() import datetime # using now() to get current time current_time = datetime.datetime.now() # Printing attributes of now(). print (\"The attributes of now() are : \") print (\"Year : \", end = \"\") print (current_time.year) print (\"Month : \", end = \"\") print (current_time.month) print (\"Day : \", end = \"\") print (current_time.day) Output:The attributes of now() are : \nYear : 2019\nMonth : 12\nDay : 11\n"
},
{
"code": null,
"e": 2458,
"s": 2433,
"text": "Syntax: datetime.now(tz)"
},
{
"code": null,
"e": 2582,
"s": 2458,
"text": "Parameters :tz : Specified time zone of which current time and date is required. (Uses Greenwich Meridian time by default.)"
},
{
"code": null,
"e": 2642,
"s": 2582,
"text": "Returns : Returns the current date and time in time format."
},
{
"code": null,
"e": 2651,
"s": 2642,
"text": "Example:"
},
{
"code": "# Python program to get# current date # Import datetime class from datetime modulefrom datetime import datetime # returns current date and timenow = datetime.now()print(\"now = \", now)",
"e": 2841,
"s": 2651,
"text": null
},
{
"code": null,
"e": 2849,
"s": 2841,
"text": "Output:"
},
{
"code": null,
"e": 2884,
"s": 2849,
"text": "now = 2019-12-11 10:58:37.039404\n"
},
{
"code": null,
"e": 3013,
"s": 2884,
"text": "Attributes of now() :now() has different attributes, same as attributes of time such as year, month, date, hour, minute, second."
},
{
"code": null,
"e": 3057,
"s": 3013,
"text": "Example 3: Demonstrate attributes of now()."
},
{
"code": "# Python3 code to demonstrate # attributes of now() # importing datetime module for now() import datetime # using now() to get current time current_time = datetime.datetime.now() # Printing attributes of now(). print (\"The attributes of now() are : \") print (\"Year : \", end = \"\") print (current_time.year) print (\"Month : \", end = \"\") print (current_time.month) print (\"Day : \", end = \"\") print (current_time.day) ",
"e": 3496,
"s": 3057,
"text": null
},
{
"code": null,
"e": 3504,
"s": 3496,
"text": "Output:"
},
{
"code": null,
"e": 3568,
"s": 3504,
"text": "The attributes of now() are : \nYear : 2019\nMonth : 12\nDay : 11\n"
},
{
"code": null,
"e": 3592,
"s": 3568,
"text": "Python datetime-program"
},
{
"code": null,
"e": 3608,
"s": 3592,
"text": "Python-datetime"
},
{
"code": null,
"e": 3615,
"s": 3608,
"text": "Python"
},
{
"code": null,
"e": 3713,
"s": 3615,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3731,
"s": 3713,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3773,
"s": 3731,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3795,
"s": 3773,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3830,
"s": 3795,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3856,
"s": 3830,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3888,
"s": 3856,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3917,
"s": 3888,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3944,
"s": 3917,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3974,
"s": 3944,
"text": "Iterate over a list in Python"
}
] |
How to implement Count (*) as variable from MySQL to display the number of records in a table? | The alias name can be used as a variable name in MySQL as shown in the below syntax −
select count(*) AS anyAliasName from yourTableName;
Let us first create a table −
mysql> create table DemoTable695 (
FirstName varchar(100)
);
Query OK, 0 rows affected (0.72 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable695 values('Chris');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable695 values('Robert');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable695 values('David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable695 values('Mike');
Query OK, 1 row affected (0.16 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable695;
This will produce the following output -
+-----------+
| FirstName |
+-----------+
| Chris |
| Robert |
| David |
| Mike |
+-----------+
4 rows in set (0.00 sec)
Following is the query to consider count(*) as variable in MySQL −
mysql> select count(*) AS TOTAL_NO_OF_RECORDS from DemoTable695 ;
This will produce the following output -
+---------------------+
| TOTAL_NO_OF_RECORDS |
+---------------------+
| 4 |
+---------------------+
1 row in set (0.02 sec) | [
{
"code": null,
"e": 1273,
"s": 1187,
"text": "The alias name can be used as a variable name in MySQL as shown in the below syntax −"
},
{
"code": null,
"e": 1325,
"s": 1273,
"text": "select count(*) AS anyAliasName from yourTableName;"
},
{
"code": null,
"e": 1355,
"s": 1325,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1456,
"s": 1355,
"text": "mysql> create table DemoTable695 (\n FirstName varchar(100)\n);\nQuery OK, 0 rows affected (0.72 sec)"
},
{
"code": null,
"e": 1512,
"s": 1456,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1852,
"s": 1512,
"text": "mysql> insert into DemoTable695 values('Chris');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable695 values('Robert');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable695 values('David');\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable695 values('Mike');\nQuery OK, 1 row affected (0.16 sec)"
},
{
"code": null,
"e": 1912,
"s": 1852,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1946,
"s": 1912,
"text": "mysql> select *from DemoTable695;"
},
{
"code": null,
"e": 1987,
"s": 1946,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2124,
"s": 1987,
"text": "+-----------+\n| FirstName |\n+-----------+\n| Chris |\n| Robert |\n| David |\n| Mike |\n+-----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2191,
"s": 2124,
"text": "Following is the query to consider count(*) as variable in MySQL −"
},
{
"code": null,
"e": 2257,
"s": 2191,
"text": "mysql> select count(*) AS TOTAL_NO_OF_RECORDS from DemoTable695 ;"
},
{
"code": null,
"e": 2298,
"s": 2257,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2442,
"s": 2298,
"text": "+---------------------+\n| TOTAL_NO_OF_RECORDS |\n+---------------------+\n| 4 |\n+---------------------+\n1 row in set (0.02 sec)"
}
] |
How to print an entire Pandas DataFrame in Python? | 03 Aug, 2021
Data visualization is the technique used to deliver insights in data using visual cues such as graphs, charts, maps, and many others. This is useful as it helps in intuitive and easy understanding of the large quantities of data and thereby make better decisions regarding it. When we use a print large number of a dataset then it truncates. In this article, we are going to see how to print the entire pandas Dataframe or Series without Truncation.
By default, the complete data frame is not printed if the length exceeds the default length, the output is truncated as shown below:
Python3
import numpy as npfrom sklearn.datasets import load_irisimport pandas as pd # Loading irirs datasetdata = load_iris()df = pd.DataFrame(data.data, columns = data.feature_names)display(df)
Output:
Use to_string() Method
Use pd.option_context() Method
Use pd.set_options() Method
Use pd.to_markdown() Method
While this method is simplest of all, it is not advisable for very huge datasets (in order of millions) because it converts the entire data frame into a string object but works very well for data frames for size in the order of thousands.
Syntax: DataFrame.to_string(buf=None, columns=None, col_space=None, header=True, index=True, na_rep=’NaN’, formatters=None, float_format=None, index_names=True, justify=None, max_rows=None, max_cols=None, show_dimensions=False, decimal=’.’, line_width=None)
Code:
Python3
import numpy as npfrom sklearn.datasets import load_irisimport pandas as pd data = load_iris()df = pd.DataFrame(data.data, columns = data.feature_names) # Convert the whole dataframe as a string and displaydisplay(df.to_string())
Output:
Pandas allow changing settings via the option_context() method and set_option() methods. Both the methods are identical with one difference that later one changes the settings permanently and the former do it only within the context manager scope.
Syntax : pandas.option_context(*args)
Code:
Python3
import numpy as npfrom sklearn.datasets import load_irisimport pandas as pd data = load_iris()df = pd.DataFrame(data.data, columns = data.feature_names) # The scope of these changes made to# pandas settings are local to with statement.with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.precision', 3, ): print(df)
Output:
Explanation:
The above code uses certain options parameters such as the ‘display.max_rows‘ its default value is 10 & if the data frame has more than 10 rows its truncates it, what we are doing is making its value to None i.e all the rows are displayed now. Similarly, ‘display.max_columns‘ has 10 as default, we are also setting it to None.
display. precision = 3 indicates that after decimal point shows up to 3 values here all the values have 1 value and therefore it doesn’t affect this example.
This method is similar to pd.option_context() method and takes the same parameters as discussed for method 2, but unlike pd.option_context() its scope and effect is on the entire script i.e all the data frames settings are changed permanently
To explicitly reset the value use pd.reset_option(‘all’) method has to be used to revert the changes.
Syntax : pandas.set_option(pat, value)
Code:
Python3
import numpy as npfrom sklearn.datasets import load_irisimport pandas as pd data = load_iris()df = pd.DataFrame(data.data, columns = data.feature_names) # Permanently changes the pandas settingspd.set_option('display.max_rows', None)pd.set_option('display.max_columns', None)pd.set_option('display.width', None)pd.set_option('display.max_colwidth', -1) # All dataframes hereafter reflect these changes.display(df) print('**RESET_OPTIONS**') # Resets the optionspd.reset_option('all')display(df)
Output:
This method is similar to the to_string() method as it also converts the data frame to a string object and also adds styling & formatting to it.
Syntax : DataFrame.to_markdown(buf=None, mode=’wt’, index=True,, **kwargs)
Code:
Python3
import numpy as npfrom sklearn.datasets import load_irisimport pandas as pd data = load_iris()df = pd.DataFrame(data.data, columns=data.feature_names) # Converts the dataframe into str object with formattingprint(df.to_markdown())
Output:
sagar0719kumar
Picked
Python pandas-dataFrame
Python Pandas-exercise
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Python | os.path.join() method
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 Aug, 2021"
},
{
"code": null,
"e": 479,
"s": 28,
"text": "Data visualization is the technique used to deliver insights in data using visual cues such as graphs, charts, maps, and many others. This is useful as it helps in intuitive and easy understanding of the large quantities of data and thereby make better decisions regarding it. When we use a print large number of a dataset then it truncates. In this article, we are going to see how to print the entire pandas Dataframe or Series without Truncation. "
},
{
"code": null,
"e": 613,
"s": 479,
"text": "By default, the complete data frame is not printed if the length exceeds the default length, the output is truncated as shown below: "
},
{
"code": null,
"e": 621,
"s": 613,
"text": "Python3"
},
{
"code": "import numpy as npfrom sklearn.datasets import load_irisimport pandas as pd # Loading irirs datasetdata = load_iris()df = pd.DataFrame(data.data, columns = data.feature_names)display(df)",
"e": 825,
"s": 621,
"text": null
},
{
"code": null,
"e": 833,
"s": 825,
"text": "Output:"
},
{
"code": null,
"e": 856,
"s": 833,
"text": "Use to_string() Method"
},
{
"code": null,
"e": 887,
"s": 856,
"text": "Use pd.option_context() Method"
},
{
"code": null,
"e": 915,
"s": 887,
"text": "Use pd.set_options() Method"
},
{
"code": null,
"e": 943,
"s": 915,
"text": "Use pd.to_markdown() Method"
},
{
"code": null,
"e": 1182,
"s": 943,
"text": "While this method is simplest of all, it is not advisable for very huge datasets (in order of millions) because it converts the entire data frame into a string object but works very well for data frames for size in the order of thousands."
},
{
"code": null,
"e": 1440,
"s": 1182,
"text": "Syntax: DataFrame.to_string(buf=None, columns=None, col_space=None, header=True, index=True, na_rep=’NaN’, formatters=None, float_format=None, index_names=True, justify=None, max_rows=None, max_cols=None, show_dimensions=False, decimal=’.’, line_width=None)"
},
{
"code": null,
"e": 1446,
"s": 1440,
"text": "Code:"
},
{
"code": null,
"e": 1454,
"s": 1446,
"text": "Python3"
},
{
"code": "import numpy as npfrom sklearn.datasets import load_irisimport pandas as pd data = load_iris()df = pd.DataFrame(data.data, columns = data.feature_names) # Convert the whole dataframe as a string and displaydisplay(df.to_string())",
"e": 1701,
"s": 1454,
"text": null
},
{
"code": null,
"e": 1709,
"s": 1701,
"text": "Output:"
},
{
"code": null,
"e": 1957,
"s": 1709,
"text": "Pandas allow changing settings via the option_context() method and set_option() methods. Both the methods are identical with one difference that later one changes the settings permanently and the former do it only within the context manager scope."
},
{
"code": null,
"e": 1995,
"s": 1957,
"text": "Syntax : pandas.option_context(*args)"
},
{
"code": null,
"e": 2001,
"s": 1995,
"text": "Code:"
},
{
"code": null,
"e": 2009,
"s": 2001,
"text": "Python3"
},
{
"code": "import numpy as npfrom sklearn.datasets import load_irisimport pandas as pd data = load_iris()df = pd.DataFrame(data.data, columns = data.feature_names) # The scope of these changes made to# pandas settings are local to with statement.with pd.option_context('display.max_rows', None, 'display.max_columns', None, 'display.precision', 3, ): print(df)",
"e": 2445,
"s": 2009,
"text": null
},
{
"code": null,
"e": 2453,
"s": 2445,
"text": "Output:"
},
{
"code": null,
"e": 2467,
"s": 2453,
"text": "Explanation: "
},
{
"code": null,
"e": 2795,
"s": 2467,
"text": "The above code uses certain options parameters such as the ‘display.max_rows‘ its default value is 10 & if the data frame has more than 10 rows its truncates it, what we are doing is making its value to None i.e all the rows are displayed now. Similarly, ‘display.max_columns‘ has 10 as default, we are also setting it to None."
},
{
"code": null,
"e": 2954,
"s": 2795,
"text": "display. precision = 3 indicates that after decimal point shows up to 3 values here all the values have 1 value and therefore it doesn’t affect this example."
},
{
"code": null,
"e": 3198,
"s": 2954,
"text": "This method is similar to pd.option_context() method and takes the same parameters as discussed for method 2, but unlike pd.option_context() its scope and effect is on the entire script i.e all the data frames settings are changed permanently "
},
{
"code": null,
"e": 3300,
"s": 3198,
"text": "To explicitly reset the value use pd.reset_option(‘all’) method has to be used to revert the changes."
},
{
"code": null,
"e": 3339,
"s": 3300,
"text": "Syntax : pandas.set_option(pat, value)"
},
{
"code": null,
"e": 3345,
"s": 3339,
"text": "Code:"
},
{
"code": null,
"e": 3353,
"s": 3345,
"text": "Python3"
},
{
"code": "import numpy as npfrom sklearn.datasets import load_irisimport pandas as pd data = load_iris()df = pd.DataFrame(data.data, columns = data.feature_names) # Permanently changes the pandas settingspd.set_option('display.max_rows', None)pd.set_option('display.max_columns', None)pd.set_option('display.width', None)pd.set_option('display.max_colwidth', -1) # All dataframes hereafter reflect these changes.display(df) print('**RESET_OPTIONS**') # Resets the optionspd.reset_option('all')display(df)",
"e": 3865,
"s": 3353,
"text": null
},
{
"code": null,
"e": 3873,
"s": 3865,
"text": "Output:"
},
{
"code": null,
"e": 4018,
"s": 3873,
"text": "This method is similar to the to_string() method as it also converts the data frame to a string object and also adds styling & formatting to it."
},
{
"code": null,
"e": 4093,
"s": 4018,
"text": "Syntax : DataFrame.to_markdown(buf=None, mode=’wt’, index=True,, **kwargs)"
},
{
"code": null,
"e": 4099,
"s": 4093,
"text": "Code:"
},
{
"code": null,
"e": 4107,
"s": 4099,
"text": "Python3"
},
{
"code": "import numpy as npfrom sklearn.datasets import load_irisimport pandas as pd data = load_iris()df = pd.DataFrame(data.data, columns=data.feature_names) # Converts the dataframe into str object with formattingprint(df.to_markdown())",
"e": 4355,
"s": 4107,
"text": null
},
{
"code": null,
"e": 4363,
"s": 4355,
"text": "Output:"
},
{
"code": null,
"e": 4378,
"s": 4363,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 4385,
"s": 4378,
"text": "Picked"
},
{
"code": null,
"e": 4409,
"s": 4385,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 4432,
"s": 4409,
"text": "Python Pandas-exercise"
},
{
"code": null,
"e": 4446,
"s": 4432,
"text": "Python-pandas"
},
{
"code": null,
"e": 4453,
"s": 4446,
"text": "Python"
},
{
"code": null,
"e": 4551,
"s": 4453,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4583,
"s": 4551,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 4610,
"s": 4583,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 4631,
"s": 4610,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 4662,
"s": 4631,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 4718,
"s": 4662,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 4741,
"s": 4718,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 4783,
"s": 4741,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 4825,
"s": 4783,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 4864,
"s": 4825,
"text": "Python | datetime.timedelta() function"
}
] |
How to create dynamic HTML pages ? | 18 May, 2021
In this article, we will know How to create a dynamic HTML page using HTML, CSS, and JavaScript. Let us first know what actually is a dynamic HTML page.
Dynamic HTML page, as the name suggests refers to an HTML page that is dynamic in such a way that it is customizable and changeable according to user input. For example:-
Using CSS we can change the background color of the web page each time the user clicks a button on the webpage.
Using JavaScript we can ask the user to enter his/her name and then display it dynamically on the webpage.
If you want to get to know more about Dynamic HTML pages, you can have a look at this article DHTML JavaScript.
Let us take some examples to know how to create a dynamic HTML page using HTML and CSS.
Example 1: Taking username as input and dynamically changing the text content of web page
HTML
<!DOCTYPE HTML><html> <body style="text-align:center;"> <h1>Enter Your Name</h1> <input id="name" type="text"> <button type="button" onclick="EnterName()">Submit</button> <p style="color:green"id="demo"></p> <script> function EnterName() { var x= document.getElementById("name").value; document.getElementById("demo").innerHTML = "Welcome to Geeks For Geeks "+ x ; } </script></body> </html>
Output:
Example 2: Dynamically changing the background color of a webpage on each click
HTML
<!DOCTYPE HTML><html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"> </script></head> <body style="text-align:center;" id="body"> <h1>Enter Your Color Choice</h1> <button type="button" onclick="changecolor()"> Color </button> <script> function changecolor() { // Generating random color each time var color = "#"+(Math.random()*16777215|0).toString(16); $("body").css("background-color",color); } </script></body> </html>
Output:
HTML-Questions
javascript-basics
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
How to Insert Form Data into Database using PHP ?
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": 52,
"s": 24,
"text": "\n18 May, 2021"
},
{
"code": null,
"e": 205,
"s": 52,
"text": "In this article, we will know How to create a dynamic HTML page using HTML, CSS, and JavaScript. Let us first know what actually is a dynamic HTML page."
},
{
"code": null,
"e": 376,
"s": 205,
"text": "Dynamic HTML page, as the name suggests refers to an HTML page that is dynamic in such a way that it is customizable and changeable according to user input. For example:-"
},
{
"code": null,
"e": 488,
"s": 376,
"text": "Using CSS we can change the background color of the web page each time the user clicks a button on the webpage."
},
{
"code": null,
"e": 595,
"s": 488,
"text": "Using JavaScript we can ask the user to enter his/her name and then display it dynamically on the webpage."
},
{
"code": null,
"e": 708,
"s": 595,
"text": "If you want to get to know more about Dynamic HTML pages, you can have a look at this article DHTML JavaScript."
},
{
"code": null,
"e": 796,
"s": 708,
"text": "Let us take some examples to know how to create a dynamic HTML page using HTML and CSS."
},
{
"code": null,
"e": 886,
"s": 796,
"text": "Example 1: Taking username as input and dynamically changing the text content of web page"
},
{
"code": null,
"e": 891,
"s": 886,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html> <body style=\"text-align:center;\"> <h1>Enter Your Name</h1> <input id=\"name\" type=\"text\"> <button type=\"button\" onclick=\"EnterName()\">Submit</button> <p style=\"color:green\"id=\"demo\"></p> <script> function EnterName() { var x= document.getElementById(\"name\").value; document.getElementById(\"demo\").innerHTML = \"Welcome to Geeks For Geeks \"+ x ; } </script></body> </html>",
"e": 1376,
"s": 891,
"text": null
},
{
"code": null,
"e": 1384,
"s": 1376,
"text": "Output:"
},
{
"code": null,
"e": 1465,
"s": 1384,
"text": "Example 2: Dynamically changing the background color of a webpage on each click "
},
{
"code": null,
"e": 1470,
"s": 1465,
"text": "HTML"
},
{
"code": "<!DOCTYPE HTML><html> <head> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js\"> </script></head> <body style=\"text-align:center;\" id=\"body\"> <h1>Enter Your Color Choice</h1> <button type=\"button\" onclick=\"changecolor()\"> Color </button> <script> function changecolor() { // Generating random color each time var color = \"#\"+(Math.random()*16777215|0).toString(16); $(\"body\").css(\"background-color\",color); } </script></body> </html>",
"e": 2048,
"s": 1470,
"text": null
},
{
"code": null,
"e": 2056,
"s": 2048,
"text": "Output:"
},
{
"code": null,
"e": 2071,
"s": 2056,
"text": "HTML-Questions"
},
{
"code": null,
"e": 2089,
"s": 2071,
"text": "javascript-basics"
},
{
"code": null,
"e": 2096,
"s": 2089,
"text": "Picked"
},
{
"code": null,
"e": 2101,
"s": 2096,
"text": "HTML"
},
{
"code": null,
"e": 2118,
"s": 2101,
"text": "Web Technologies"
},
{
"code": null,
"e": 2123,
"s": 2118,
"text": "HTML"
},
{
"code": null,
"e": 2221,
"s": 2123,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2245,
"s": 2221,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2282,
"s": 2245,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 2321,
"s": 2282,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2349,
"s": 2321,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 2399,
"s": 2349,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 2432,
"s": 2399,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 2493,
"s": 2432,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2536,
"s": 2493,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 2608,
"s": 2536,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Remove all occurrences of an element from Array in Java | 21 Jun, 2022
Given an array and a key, the task is to remove all occurrences of the specified key from the array in Java. Examples:
Input: array = { 3, 9, 2, 3, 1, 7, 2, 3, 5 }, key = 3
Output: [9, 2, 1, 7, 2, 5]
Input: array = { 10, 20, 10, 30, 50, 10 }, key = 10
Output: [20, 30, 50]
JAVA
// Java program remove all occurrences// of an element from Array using naive method import java.util.Arrays; class GFG { // function to remove all occurrences // of an element from an array public static int[] removeElements(int[] arr, int key) { // Move all other elements to beginning int index = 0; for (int i=0; i<arr.length; i++) if (arr[i] != key) arr[index++] = arr[i]; // Create a copy of arr[] return Arrays.copyOf(arr, index); } // Driver code public static void main(String[] args) { int[] array = { 3, 9, 2, 3, 1, 7, 2, 3, 5 }; int key = 3; array = removeElements(array, key); System.out.println(Arrays.toString(array)); }}
[9, 2, 1, 7, 2, 5]
Time Complexity: O(n)
Space Complexity: O(n)
Get the array and the key.Filter all element of the list which is equal to a given keyConvert the list back to an array and return it.
Get the array and the key.
Filter all element of the list which is equal to a given key
Convert the list back to an array and return it.
Get the array and the key.Create an empty ArrayListInsert all elements from the array into the list except the specified keyConvert the list back to an array and return it.
Get the array and the key.
Create an empty ArrayList
Insert all elements from the array into the list except the specified key
Convert the list back to an array and return it.
First Create a List of Array.Remove all elements of the array into the list that are the specified key.Convert the list back to an array and return it.
First Create a List of Array.
Remove all elements of the array into the list that are the specified key.
Convert the list back to an array and return it.
First Create an empty List of Array.Insert all elements of the array into the listRemove all elements which is you want to removeConvert the list back to an array and return it.
First Create an empty List of Array.
Insert all elements of the array into the list
Remove all elements which is you want to remove
Convert the list back to an array and return it.
First Create an empty List of Array.Insert all elements of the array into the listRemove all those element which is you want to remove using the equals() methodConvert the list back to an array and return it.
First Create an empty List of Array.
Insert all elements of the array into the list
Remove all those element which is you want to remove using the equals() method
Convert the list back to an array and return it.
harshmaster07705
Java-Array-Programs
Java-ArrayList
Java-Arrays
Java-Collections
Technical Scripter 2018
Java
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Java Programming Examples
Strings in Java
Differences between JDK, JRE and JVM
Abstraction in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 171,
"s": 52,
"text": "Given an array and a key, the task is to remove all occurrences of the specified key from the array in Java. Examples:"
},
{
"code": null,
"e": 326,
"s": 171,
"text": "Input: array = { 3, 9, 2, 3, 1, 7, 2, 3, 5 }, key = 3\nOutput: [9, 2, 1, 7, 2, 5]\n\nInput: array = { 10, 20, 10, 30, 50, 10 }, key = 10\nOutput: [20, 30, 50]"
},
{
"code": null,
"e": 331,
"s": 326,
"text": "JAVA"
},
{
"code": "// Java program remove all occurrences// of an element from Array using naive method import java.util.Arrays; class GFG { // function to remove all occurrences // of an element from an array public static int[] removeElements(int[] arr, int key) { // Move all other elements to beginning int index = 0; for (int i=0; i<arr.length; i++) if (arr[i] != key) arr[index++] = arr[i]; // Create a copy of arr[] return Arrays.copyOf(arr, index); } // Driver code public static void main(String[] args) { int[] array = { 3, 9, 2, 3, 1, 7, 2, 3, 5 }; int key = 3; array = removeElements(array, key); System.out.println(Arrays.toString(array)); }}",
"e": 1087,
"s": 331,
"text": null
},
{
"code": null,
"e": 1106,
"s": 1087,
"text": "[9, 2, 1, 7, 2, 5]"
},
{
"code": null,
"e": 1128,
"s": 1106,
"text": "Time Complexity: O(n)"
},
{
"code": null,
"e": 1151,
"s": 1128,
"text": "Space Complexity: O(n)"
},
{
"code": null,
"e": 1286,
"s": 1151,
"text": "Get the array and the key.Filter all element of the list which is equal to a given keyConvert the list back to an array and return it."
},
{
"code": null,
"e": 1313,
"s": 1286,
"text": "Get the array and the key."
},
{
"code": null,
"e": 1374,
"s": 1313,
"text": "Filter all element of the list which is equal to a given key"
},
{
"code": null,
"e": 1423,
"s": 1374,
"text": "Convert the list back to an array and return it."
},
{
"code": null,
"e": 1596,
"s": 1423,
"text": "Get the array and the key.Create an empty ArrayListInsert all elements from the array into the list except the specified keyConvert the list back to an array and return it."
},
{
"code": null,
"e": 1623,
"s": 1596,
"text": "Get the array and the key."
},
{
"code": null,
"e": 1649,
"s": 1623,
"text": "Create an empty ArrayList"
},
{
"code": null,
"e": 1723,
"s": 1649,
"text": "Insert all elements from the array into the list except the specified key"
},
{
"code": null,
"e": 1772,
"s": 1723,
"text": "Convert the list back to an array and return it."
},
{
"code": null,
"e": 1924,
"s": 1772,
"text": "First Create a List of Array.Remove all elements of the array into the list that are the specified key.Convert the list back to an array and return it."
},
{
"code": null,
"e": 1954,
"s": 1924,
"text": "First Create a List of Array."
},
{
"code": null,
"e": 2029,
"s": 1954,
"text": "Remove all elements of the array into the list that are the specified key."
},
{
"code": null,
"e": 2078,
"s": 2029,
"text": "Convert the list back to an array and return it."
},
{
"code": null,
"e": 2256,
"s": 2078,
"text": "First Create an empty List of Array.Insert all elements of the array into the listRemove all elements which is you want to removeConvert the list back to an array and return it."
},
{
"code": null,
"e": 2293,
"s": 2256,
"text": "First Create an empty List of Array."
},
{
"code": null,
"e": 2340,
"s": 2293,
"text": "Insert all elements of the array into the list"
},
{
"code": null,
"e": 2388,
"s": 2340,
"text": "Remove all elements which is you want to remove"
},
{
"code": null,
"e": 2437,
"s": 2388,
"text": "Convert the list back to an array and return it."
},
{
"code": null,
"e": 2646,
"s": 2437,
"text": "First Create an empty List of Array.Insert all elements of the array into the listRemove all those element which is you want to remove using the equals() methodConvert the list back to an array and return it."
},
{
"code": null,
"e": 2683,
"s": 2646,
"text": "First Create an empty List of Array."
},
{
"code": null,
"e": 2730,
"s": 2683,
"text": "Insert all elements of the array into the list"
},
{
"code": null,
"e": 2809,
"s": 2730,
"text": "Remove all those element which is you want to remove using the equals() method"
},
{
"code": null,
"e": 2858,
"s": 2809,
"text": "Convert the list back to an array and return it."
},
{
"code": null,
"e": 2875,
"s": 2858,
"text": "harshmaster07705"
},
{
"code": null,
"e": 2895,
"s": 2875,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 2910,
"s": 2895,
"text": "Java-ArrayList"
},
{
"code": null,
"e": 2922,
"s": 2910,
"text": "Java-Arrays"
},
{
"code": null,
"e": 2939,
"s": 2922,
"text": "Java-Collections"
},
{
"code": null,
"e": 2963,
"s": 2939,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 2968,
"s": 2963,
"text": "Java"
},
{
"code": null,
"e": 2987,
"s": 2968,
"text": "Technical Scripter"
},
{
"code": null,
"e": 2992,
"s": 2987,
"text": "Java"
},
{
"code": null,
"e": 3009,
"s": 2992,
"text": "Java-Collections"
},
{
"code": null,
"e": 3107,
"s": 3009,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3122,
"s": 3107,
"text": "Stream In Java"
},
{
"code": null,
"e": 3143,
"s": 3122,
"text": "Introduction to Java"
},
{
"code": null,
"e": 3164,
"s": 3143,
"text": "Constructors in Java"
},
{
"code": null,
"e": 3183,
"s": 3164,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 3200,
"s": 3183,
"text": "Generics in Java"
},
{
"code": null,
"e": 3230,
"s": 3200,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 3256,
"s": 3230,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 3272,
"s": 3256,
"text": "Strings in Java"
},
{
"code": null,
"e": 3309,
"s": 3272,
"text": "Differences between JDK, JRE and JVM"
}
] |
How to Find Index of Element in Array in MATLAB? | 04 Jul, 2021
In MATLAB, the arrays are used to represent the information and data. You can use indexing to access the elements of the array. In MATLAB the array indexing starts from 1. To find the index of the element in the array, you can use the find() function. Using the find() function you can find the indices and the element from the array. The find() function returns a vector containing the data.
Syntax:
find(X) : Return a vector containing the indices of elements
find(X,n): Return first n indices of the elements in X
find(X,n, Direction): find n indices in X according to the Direction where Direction – ‘first‘ or ‘last‘
[row,col] = find(): It returns the row and column subscript of element in array
[row,col,V] = find(): returns vector V containing non-zero elements
Now let’s see how to find an index of any element in an array using the find() function with the help of examples.
find(X) returns a vector containing the linear indices of each nonzero element in array X.
Example 1:
Matlab
% MATLAB code for find an index of any % element in an array using the find()array = [1 2 3 4 5 6] % find() will get the index of element% store it in the indexindex = find(array==3)
Output:
Note: If the array contains duplicates then find(X) function will return all the indices of that integer.
Example 2:
Matlab
% MATLAB code for if the array contains% duplicate elements array = [1 2 3 4 5 6 2 4 2] % find() will get the index of element% store it in the indexindex = find(array==2)
Output:
When the array contains duplicate values the find() function will print all the indices of that corresponding element. So if you don’t want all the indices of that element you can use the find(X,n) function.
Return first n indices of the elements in X.
Example:
Matlab
% MATLAB code for return first % n indices of the elements in Xarray = [1 2 3 4 5 6 2 4 2] % find() will get the index of element% gets the first index of 2% store it in the indexindex = find(array==2,1)
Output:
You can also find the index of the elements from both directions in the array. Both directions mean from starting and from last by using find(X,n,Direction). This function find n indices in X according to the Direction. The Direction parameter accepts either ‘first’ or ‘last’. If the direction is first it will return first n indices of that corresponding element or if the direction is last it will return the indices by traversing from the end of the array. By default, the Direction parameter is ‘first’.
Example 1:
Matlab
% MATLAB code for find the index of % the elements from both directions % in the arrayarray = [1 2 3 4 5 6 2 4 2] % find() will get the index of element% store it in the indexindex = find(array==2,2,'first')
Output:
Example 2:
Matlab
% array of integersarray = [1 2 3 4 5 6 2 4 2] % find() will get the index of element% store it in the indexindex = find(array==2,2,'last')
Output:
For finding the index of an element in a 3-Dimensional array you can use the syntax [row,col] = find(x) this will give you the row and the column in which the element is present.
Example:
Matlab
% MATLAB code for Finding an index % of an element in a 3-D arrayarray = [1 2 3; 4 5 6; 7 8 9] % find() will get the index of element% prints the row and column of the element[row,col] = find(array==5)
Output:
If you want to find the indices of all the non-zero elements present in the 3-dimensional array you can use [row,col,v] = find(X) where X is our array. This will find all indices of all non-zero elements present in the array and store them into the vector v.
Example:
Matlab
% MATLAB code for find the indices of % all the non-zero elements present in the 3-D array x = [1 9 0; 3 -1 0; 0 0 7] % find() will get the indices of the elements% and the vector will store all the non-zero elements[row,col,v] = find(x)
Output:
MATLAB-programs
Picked
MATLAB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?
Adaptive Histogram Equalization in Image Processing Using MATLAB
How to Solve Histogram Equalization Numerical Problem in MATLAB?
MRI Image Segmentation in MATLAB
Laplacian of Gaussian Filter in MATLAB
Forward and Inverse Fourier Transform of an Image in MATLAB
How to remove space in a string in MATLAB?
How to detect duplicate values and its indices within an array in MATLAB?
Classes and Object in MATLAB
How to Convert RGB Image to Binary Image Using MATLAB? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jul, 2021"
},
{
"code": null,
"e": 423,
"s": 28,
"text": "In MATLAB, the arrays are used to represent the information and data. You can use indexing to access the elements of the array. In MATLAB the array indexing starts from 1. To find the index of the element in the array, you can use the find() function. Using the find() function you can find the indices and the element from the array. The find() function returns a vector containing the data. "
},
{
"code": null,
"e": 431,
"s": 423,
"text": "Syntax:"
},
{
"code": null,
"e": 492,
"s": 431,
"text": "find(X) : Return a vector containing the indices of elements"
},
{
"code": null,
"e": 547,
"s": 492,
"text": "find(X,n): Return first n indices of the elements in X"
},
{
"code": null,
"e": 653,
"s": 547,
"text": "find(X,n, Direction): find n indices in X according to the Direction where Direction – ‘first‘ or ‘last‘"
},
{
"code": null,
"e": 733,
"s": 653,
"text": "[row,col] = find(): It returns the row and column subscript of element in array"
},
{
"code": null,
"e": 801,
"s": 733,
"text": "[row,col,V] = find(): returns vector V containing non-zero elements"
},
{
"code": null,
"e": 916,
"s": 801,
"text": "Now let’s see how to find an index of any element in an array using the find() function with the help of examples."
},
{
"code": null,
"e": 1007,
"s": 916,
"text": "find(X) returns a vector containing the linear indices of each nonzero element in array X."
},
{
"code": null,
"e": 1018,
"s": 1007,
"text": "Example 1:"
},
{
"code": null,
"e": 1025,
"s": 1018,
"text": "Matlab"
},
{
"code": "% MATLAB code for find an index of any % element in an array using the find()array = [1 2 3 4 5 6] % find() will get the index of element% store it in the indexindex = find(array==3)",
"e": 1210,
"s": 1025,
"text": null
},
{
"code": null,
"e": 1218,
"s": 1210,
"text": "Output:"
},
{
"code": null,
"e": 1325,
"s": 1218,
"text": "Note: If the array contains duplicates then find(X) function will return all the indices of that integer. "
},
{
"code": null,
"e": 1336,
"s": 1325,
"text": "Example 2:"
},
{
"code": null,
"e": 1343,
"s": 1336,
"text": "Matlab"
},
{
"code": "% MATLAB code for if the array contains% duplicate elements array = [1 2 3 4 5 6 2 4 2] % find() will get the index of element% store it in the indexindex = find(array==2)",
"e": 1517,
"s": 1343,
"text": null
},
{
"code": null,
"e": 1525,
"s": 1517,
"text": "Output:"
},
{
"code": null,
"e": 1734,
"s": 1525,
"text": "When the array contains duplicate values the find() function will print all the indices of that corresponding element. So if you don’t want all the indices of that element you can use the find(X,n) function. "
},
{
"code": null,
"e": 1779,
"s": 1734,
"text": "Return first n indices of the elements in X."
},
{
"code": null,
"e": 1788,
"s": 1779,
"text": "Example:"
},
{
"code": null,
"e": 1795,
"s": 1788,
"text": "Matlab"
},
{
"code": "% MATLAB code for return first % n indices of the elements in Xarray = [1 2 3 4 5 6 2 4 2] % find() will get the index of element% gets the first index of 2% store it in the indexindex = find(array==2,1)",
"e": 2000,
"s": 1795,
"text": null
},
{
"code": null,
"e": 2008,
"s": 2000,
"text": "Output:"
},
{
"code": null,
"e": 2519,
"s": 2010,
"text": "You can also find the index of the elements from both directions in the array. Both directions mean from starting and from last by using find(X,n,Direction). This function find n indices in X according to the Direction. The Direction parameter accepts either ‘first’ or ‘last’. If the direction is first it will return first n indices of that corresponding element or if the direction is last it will return the indices by traversing from the end of the array. By default, the Direction parameter is ‘first’."
},
{
"code": null,
"e": 2530,
"s": 2519,
"text": "Example 1:"
},
{
"code": null,
"e": 2537,
"s": 2530,
"text": "Matlab"
},
{
"code": "% MATLAB code for find the index of % the elements from both directions % in the arrayarray = [1 2 3 4 5 6 2 4 2] % find() will get the index of element% store it in the indexindex = find(array==2,2,'first')",
"e": 2746,
"s": 2537,
"text": null
},
{
"code": null,
"e": 2754,
"s": 2746,
"text": "Output:"
},
{
"code": null,
"e": 2765,
"s": 2754,
"text": "Example 2:"
},
{
"code": null,
"e": 2772,
"s": 2765,
"text": "Matlab"
},
{
"code": "% array of integersarray = [1 2 3 4 5 6 2 4 2] % find() will get the index of element% store it in the indexindex = find(array==2,2,'last')",
"e": 2913,
"s": 2772,
"text": null
},
{
"code": null,
"e": 2921,
"s": 2913,
"text": "Output:"
},
{
"code": null,
"e": 3100,
"s": 2921,
"text": "For finding the index of an element in a 3-Dimensional array you can use the syntax [row,col] = find(x) this will give you the row and the column in which the element is present."
},
{
"code": null,
"e": 3109,
"s": 3100,
"text": "Example:"
},
{
"code": null,
"e": 3116,
"s": 3109,
"text": "Matlab"
},
{
"code": "% MATLAB code for Finding an index % of an element in a 3-D arrayarray = [1 2 3; 4 5 6; 7 8 9] % find() will get the index of element% prints the row and column of the element[row,col] = find(array==5)",
"e": 3319,
"s": 3116,
"text": null
},
{
"code": null,
"e": 3327,
"s": 3319,
"text": "Output:"
},
{
"code": null,
"e": 3587,
"s": 3327,
"text": "If you want to find the indices of all the non-zero elements present in the 3-dimensional array you can use [row,col,v] = find(X) where X is our array. This will find all indices of all non-zero elements present in the array and store them into the vector v. "
},
{
"code": null,
"e": 3596,
"s": 3587,
"text": "Example:"
},
{
"code": null,
"e": 3603,
"s": 3596,
"text": "Matlab"
},
{
"code": "% MATLAB code for find the indices of % all the non-zero elements present in the 3-D array x = [1 9 0; 3 -1 0; 0 0 7] % find() will get the indices of the elements% and the vector will store all the non-zero elements[row,col,v] = find(x)",
"e": 3842,
"s": 3603,
"text": null
},
{
"code": null,
"e": 3850,
"s": 3842,
"text": "Output:"
},
{
"code": null,
"e": 3866,
"s": 3850,
"text": "MATLAB-programs"
},
{
"code": null,
"e": 3873,
"s": 3866,
"text": "Picked"
},
{
"code": null,
"e": 3880,
"s": 3873,
"text": "MATLAB"
},
{
"code": null,
"e": 3978,
"s": 3880,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4057,
"s": 3978,
"text": "How to Convert Three Channels of Colored Image into Grayscale Image in MATLAB?"
},
{
"code": null,
"e": 4122,
"s": 4057,
"text": "Adaptive Histogram Equalization in Image Processing Using MATLAB"
},
{
"code": null,
"e": 4187,
"s": 4122,
"text": "How to Solve Histogram Equalization Numerical Problem in MATLAB?"
},
{
"code": null,
"e": 4220,
"s": 4187,
"text": "MRI Image Segmentation in MATLAB"
},
{
"code": null,
"e": 4259,
"s": 4220,
"text": "Laplacian of Gaussian Filter in MATLAB"
},
{
"code": null,
"e": 4319,
"s": 4259,
"text": "Forward and Inverse Fourier Transform of an Image in MATLAB"
},
{
"code": null,
"e": 4362,
"s": 4319,
"text": "How to remove space in a string in MATLAB?"
},
{
"code": null,
"e": 4436,
"s": 4362,
"text": "How to detect duplicate values and its indices within an array in MATLAB?"
},
{
"code": null,
"e": 4465,
"s": 4436,
"text": "Classes and Object in MATLAB"
}
] |
How to align two div’s horizontally using HTML ? | 08 Oct, 2021
In this article, we will learn about aligning 2 divs beside each other in HTML. The <div> tag is a block-level element i.e. it always starts on a new line and takes all the width available to both left and right sides. It also has a top and a bottom margin. The <div> tag is used to separate a block of content or to define a section in HTML. The main use of <div> tag is as a container for HTML elements. It enables the use of CSS and JavaScript on these elements easier. Class and id attributes can be used with these tags.
The problem of aligning 2 divs horizontally: Since <div> tag is a block element, only one div can be placed in a line, and all the space to the left and right is taken by it. Let’s look at the below example to understand it better.
Example:
HTML
<!DOCTYPE html><html> <body> <a>Click here!</a> <a>This is a link</a></body> </html>
Output:
Here, 2 anchor tags are used. Since the anchor tag is an inline element, the second link comes right after the first one in the output. However, the second link can be made to go to the next line if we use the <div> tag. This is illustrated by the below example:
Example:
HTML
<!DOCTYPE html><html> <body> <a>Click here!</a> <div><a>This is a link</a></div></body> </html>
Output:
It is clearly visible that the use of the <div> tag took the second link on the other line because it acquires the entire line width. If <div> was an inline tag, then by default two divs would align horizontally.
Ways to align 2 divs horizontally: We have two divs that can be aligned horizontally with the use of CSS. There are several ways to perform this task. We will understand all the concepts in a sequence.
1. Using a global class for both the divs: We can put both the divs in one parent div with a class attribute. The class attribute value will be used to style the divs. In the example, both the div tags are enclosed inside another <div> tag which has the class main. This is then used in the <head> section, inside <style> tag. The CSS float property specifies the position of an element.
Syntax:
float: left|right|initial|inherit|none;
Attribute values:
none: It is the default value of a float property. The element must not float.
inherit: property must be inherited from its parent element.
left: Place an element on its container’s right.
right: Place an element on its container’s left.
initial: Property is set to its default value.
The CSS clear property specifies the flow of an element next to a floated element. The default value of clear is none.
Syntax:
clear: none;
Example:
HTML
<!DOCTYPE html><html> <head> <style> .main div { float: left; clear: none; } </style></head> <body> <div class="main"> <div> <p>1.</p> <p>2.</p> <p>3.</p> </div> <div> <p>GeeksforGeeks</p> <p>Geeks Portal</p> <p>Writing Portal</p> </div> </div></body> </html>
Output:
2. Using flex property: The flex property in CSS is the combination of flex-grow, flex-shrink, and flex-basis property. It is used to set the length of flexible items. The flex property is much responsive and mobile-friendly. It is easy to positioning child elements and the main container. The margin doesn’t collapse with the content margins. The order of any element can be easily changed without editing the HTML section. We can combine with a parent div class, CSS flex property can be used to align two divs next to each other.
The CSS flex property is used to set a flexible length for flexible elements.
Syntax:
flex: flex-grow flex-shrink flex-basis|initial|auto|inherit;
Property Values:
flex-grow: A number that specifies how many items will grow relative to the rest of the flexible items.
flex-shrink: A number that specifies how many items will shrink relative to the rest of the flexible items.
flex-basis: It sets the length of items. Legal values of flex-basis are: auto, inherit, or a number followed by %, em, px, or any other length unit.
Example: In this example, we have used a display property whose value is set to flex which is used to set the length of flexible items.
HTML
<!DOCTYPE html><html> <head> <style> .main { display: flex; } </style></head> <head> <div class="main"> <div> <p>1.</p> <p>2.</p> <p>3.</p> </div> <div> <p>GeeksforGeeks</p> <p>Geeks Portal</p> <p>Writing Portal</p> </div> </div></head> </html>
Output:
3. Individual styling of divs: The two <div> tags can also be individually styled using style property.
Example:
HTML
<!DOCTYPE html><html> <body> <div style="float: left; width: 50%"> <p>1.</p> <p>2.</p> <p>3.</p> </div> <div style="float: right; width: 50%"> <p>GeeksforGeeks</p> <p>Geeks Portal</p> <p>Writing Portal</p> </div></body> </html>
Output: The first <div> tag is floated to the left and the second <div> tag is floated to the right. However, they are aligned to each other horizontally with a lot of space. The width can be changed for changing this space.
CSS-Properties
CSS-Questions
HTML-Questions
Picked
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Oct, 2021"
},
{
"code": null,
"e": 554,
"s": 28,
"text": "In this article, we will learn about aligning 2 divs beside each other in HTML. The <div> tag is a block-level element i.e. it always starts on a new line and takes all the width available to both left and right sides. It also has a top and a bottom margin. The <div> tag is used to separate a block of content or to define a section in HTML. The main use of <div> tag is as a container for HTML elements. It enables the use of CSS and JavaScript on these elements easier. Class and id attributes can be used with these tags."
},
{
"code": null,
"e": 786,
"s": 554,
"text": "The problem of aligning 2 divs horizontally: Since <div> tag is a block element, only one div can be placed in a line, and all the space to the left and right is taken by it. Let’s look at the below example to understand it better."
},
{
"code": null,
"e": 795,
"s": 786,
"text": "Example:"
},
{
"code": null,
"e": 800,
"s": 795,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <a>Click here!</a> <a>This is a link</a></body> </html>",
"e": 893,
"s": 800,
"text": null
},
{
"code": null,
"e": 901,
"s": 893,
"text": "Output:"
},
{
"code": null,
"e": 1164,
"s": 901,
"text": "Here, 2 anchor tags are used. Since the anchor tag is an inline element, the second link comes right after the first one in the output. However, the second link can be made to go to the next line if we use the <div> tag. This is illustrated by the below example:"
},
{
"code": null,
"e": 1173,
"s": 1164,
"text": "Example:"
},
{
"code": null,
"e": 1178,
"s": 1173,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <a>Click here!</a> <div><a>This is a link</a></div></body> </html>",
"e": 1282,
"s": 1178,
"text": null
},
{
"code": null,
"e": 1290,
"s": 1282,
"text": "Output:"
},
{
"code": null,
"e": 1503,
"s": 1290,
"text": "It is clearly visible that the use of the <div> tag took the second link on the other line because it acquires the entire line width. If <div> was an inline tag, then by default two divs would align horizontally."
},
{
"code": null,
"e": 1705,
"s": 1503,
"text": "Ways to align 2 divs horizontally: We have two divs that can be aligned horizontally with the use of CSS. There are several ways to perform this task. We will understand all the concepts in a sequence."
},
{
"code": null,
"e": 2094,
"s": 1705,
"text": "1. Using a global class for both the divs: We can put both the divs in one parent div with a class attribute. The class attribute value will be used to style the divs. In the example, both the div tags are enclosed inside another <div> tag which has the class main. This is then used in the <head> section, inside <style> tag. The CSS float property specifies the position of an element. "
},
{
"code": null,
"e": 2102,
"s": 2094,
"text": "Syntax:"
},
{
"code": null,
"e": 2142,
"s": 2102,
"text": "float: left|right|initial|inherit|none;"
},
{
"code": null,
"e": 2160,
"s": 2142,
"text": "Attribute values:"
},
{
"code": null,
"e": 2239,
"s": 2160,
"text": "none: It is the default value of a float property. The element must not float."
},
{
"code": null,
"e": 2300,
"s": 2239,
"text": "inherit: property must be inherited from its parent element."
},
{
"code": null,
"e": 2349,
"s": 2300,
"text": "left: Place an element on its container’s right."
},
{
"code": null,
"e": 2398,
"s": 2349,
"text": "right: Place an element on its container’s left."
},
{
"code": null,
"e": 2445,
"s": 2398,
"text": "initial: Property is set to its default value."
},
{
"code": null,
"e": 2565,
"s": 2445,
"text": "The CSS clear property specifies the flow of an element next to a floated element. The default value of clear is none. "
},
{
"code": null,
"e": 2573,
"s": 2565,
"text": "Syntax:"
},
{
"code": null,
"e": 2586,
"s": 2573,
"text": "clear: none;"
},
{
"code": null,
"e": 2595,
"s": 2586,
"text": "Example:"
},
{
"code": null,
"e": 2600,
"s": 2595,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .main div { float: left; clear: none; } </style></head> <body> <div class=\"main\"> <div> <p>1.</p> <p>2.</p> <p>3.</p> </div> <div> <p>GeeksforGeeks</p> <p>Geeks Portal</p> <p>Writing Portal</p> </div> </div></body> </html>",
"e": 3005,
"s": 2600,
"text": null
},
{
"code": null,
"e": 3013,
"s": 3005,
"text": "Output:"
},
{
"code": null,
"e": 3547,
"s": 3013,
"text": "2. Using flex property: The flex property in CSS is the combination of flex-grow, flex-shrink, and flex-basis property. It is used to set the length of flexible items. The flex property is much responsive and mobile-friendly. It is easy to positioning child elements and the main container. The margin doesn’t collapse with the content margins. The order of any element can be easily changed without editing the HTML section. We can combine with a parent div class, CSS flex property can be used to align two divs next to each other."
},
{
"code": null,
"e": 3626,
"s": 3547,
"text": "The CSS flex property is used to set a flexible length for flexible elements. "
},
{
"code": null,
"e": 3634,
"s": 3626,
"text": "Syntax:"
},
{
"code": null,
"e": 3695,
"s": 3634,
"text": "flex: flex-grow flex-shrink flex-basis|initial|auto|inherit;"
},
{
"code": null,
"e": 3712,
"s": 3695,
"text": "Property Values:"
},
{
"code": null,
"e": 3816,
"s": 3712,
"text": "flex-grow: A number that specifies how many items will grow relative to the rest of the flexible items."
},
{
"code": null,
"e": 3924,
"s": 3816,
"text": "flex-shrink: A number that specifies how many items will shrink relative to the rest of the flexible items."
},
{
"code": null,
"e": 4073,
"s": 3924,
"text": "flex-basis: It sets the length of items. Legal values of flex-basis are: auto, inherit, or a number followed by %, em, px, or any other length unit."
},
{
"code": null,
"e": 4209,
"s": 4073,
"text": "Example: In this example, we have used a display property whose value is set to flex which is used to set the length of flexible items."
},
{
"code": null,
"e": 4214,
"s": 4209,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> .main { display: flex; } </style></head> <head> <div class=\"main\"> <div> <p>1.</p> <p>2.</p> <p>3.</p> </div> <div> <p>GeeksforGeeks</p> <p>Geeks Portal</p> <p>Writing Portal</p> </div> </div></head> </html>",
"e": 4593,
"s": 4214,
"text": null
},
{
"code": null,
"e": 4601,
"s": 4593,
"text": "Output:"
},
{
"code": null,
"e": 4705,
"s": 4601,
"text": "3. Individual styling of divs: The two <div> tags can also be individually styled using style property."
},
{
"code": null,
"e": 4714,
"s": 4705,
"text": "Example:"
},
{
"code": null,
"e": 4719,
"s": 4714,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <body> <div style=\"float: left; width: 50%\"> <p>1.</p> <p>2.</p> <p>3.</p> </div> <div style=\"float: right; width: 50%\"> <p>GeeksforGeeks</p> <p>Geeks Portal</p> <p>Writing Portal</p> </div></body> </html>",
"e": 5003,
"s": 4719,
"text": null
},
{
"code": null,
"e": 5228,
"s": 5003,
"text": "Output: The first <div> tag is floated to the left and the second <div> tag is floated to the right. However, they are aligned to each other horizontally with a lot of space. The width can be changed for changing this space."
},
{
"code": null,
"e": 5243,
"s": 5228,
"text": "CSS-Properties"
},
{
"code": null,
"e": 5257,
"s": 5243,
"text": "CSS-Questions"
},
{
"code": null,
"e": 5272,
"s": 5257,
"text": "HTML-Questions"
},
{
"code": null,
"e": 5279,
"s": 5272,
"text": "Picked"
},
{
"code": null,
"e": 5283,
"s": 5279,
"text": "CSS"
},
{
"code": null,
"e": 5288,
"s": 5283,
"text": "HTML"
},
{
"code": null,
"e": 5305,
"s": 5288,
"text": "Web Technologies"
},
{
"code": null,
"e": 5310,
"s": 5305,
"text": "HTML"
}
] |
Tensorflow.js tf.Sequential class .fit() Method | 15 Oct, 2021
Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment.
Tensorflow.jstf.Sequential class .fit( ) method is used to train the model for the fixed number of epochs( iterations on a dataset ).
Syntax:
model.fit( x, y, args?);
Parameters: This method accept following parameters:
x: It is tf.Tensor that contains all the input data.
y: It is tf.Tensor that contains all the output data.
args: It is object type, it’s variables are follows:batchSize: It define the number of samples that will propagate through training.epochs: It define iteration over the training data arrays.verbose: It help in showing the progress for each epoch.If the value is 0 – It means no printed message during fit() call. If the value is 1 – It means in Node-js , it prints the progress bar. In the browser it shows no action. Value 1 is the default value . 2 – Value 2 is not implement yet.callbacks: It define list of callbacks to be call during training. Variable can have one or more of these callbacks onTrainBegin( ), onTrainEnd( ), onEpochBegin( ), onEpochEnd( ), onBatchBegin( ), onBatchEnd( ), onYield( ).validationSplit: It makes easy for the user to split the training dataset into train and validation.For example : if it value is validation-Split = 0.5 ,it means use last 50% of data before shuffling for validation.validationData: It is used to give an estimate of final model when selecting between final models.shuffle: This value define shuffle of the data before each epoch. it has not effect when stepsPerEpoch is not null.classWeight: It is used for weighting the loss function. It can be useful to tell the model to pay more attention to samples from an under-represented class.sampleWeight: It is array of weights to apply to model’s loss for each sample.initialEpoch: It is value define epoch at which to start training. It is useful for resuming a previous training run.stepsPerEpoch: It define number of batches of samples before declaring one epoch finished and starting the next epoch. It is equal to 1 if not determined.validationSteps: It is relevant if stepsPerEpoch is specified. Total number of steps to validate before stopping.yieldEvery: It define configuration of the frequency of yielding the main thread to other tasks. It can be auto, It means the yielding happens at a certain frame rate. batch, If the value is this, It yield every batch. epoch, If the value is this, It yield every epoch. any number, If the value is any number, it yield every number milliseconds.never, If the value is this, it never yield.
batchSize: It define the number of samples that will propagate through training.
epochs: It define iteration over the training data arrays.
verbose: It help in showing the progress for each epoch.If the value is 0 – It means no printed message during fit() call. If the value is 1 – It means in Node-js , it prints the progress bar. In the browser it shows no action. Value 1 is the default value . 2 – Value 2 is not implement yet.
callbacks: It define list of callbacks to be call during training. Variable can have one or more of these callbacks onTrainBegin( ), onTrainEnd( ), onEpochBegin( ), onEpochEnd( ), onBatchBegin( ), onBatchEnd( ), onYield( ).
validationSplit: It makes easy for the user to split the training dataset into train and validation.For example : if it value is validation-Split = 0.5 ,it means use last 50% of data before shuffling for validation.
validationData: It is used to give an estimate of final model when selecting between final models.
shuffle: This value define shuffle of the data before each epoch. it has not effect when stepsPerEpoch is not null.
classWeight: It is used for weighting the loss function. It can be useful to tell the model to pay more attention to samples from an under-represented class.
sampleWeight: It is array of weights to apply to model’s loss for each sample.
initialEpoch: It is value define epoch at which to start training. It is useful for resuming a previous training run.
stepsPerEpoch: It define number of batches of samples before declaring one epoch finished and starting the next epoch. It is equal to 1 if not determined.
validationSteps: It is relevant if stepsPerEpoch is specified. Total number of steps to validate before stopping.
yieldEvery: It define configuration of the frequency of yielding the main thread to other tasks. It can be auto, It means the yielding happens at a certain frame rate. batch, If the value is this, It yield every batch. epoch, If the value is this, It yield every epoch. any number, If the value is any number, it yield every number milliseconds.never, If the value is this, it never yield.
Returns: Promise< History >
Example 1: In this example we will train our model by default configuration.
Javascript
import * as tf from "@tensorflow/tfjs" // Creating modelconst model = tf.sequential( ) ; // Adding layer to modelconst config = {units: 1, inputShape: [1]}const x = tf.layers.dense(config);model.add(x); // Compiling the modelconst config2 = {optimizer: 'sgd', loss: 'meanSquaredError'}model.compile(config2); // Tensor for trainingconst xs = tf.tensor2d([1, 1.2,1.65, 1.29, 1.4, 1.7], [6, 1]);const ys = tf.tensor2d([1, 0.07,0.17, 0.29, 0.43, 1.02], [6, 1]); // Training the modelconst Tm = await model.fit(xs, ys); // Printing the loss after trainingconsole.log("Loss " + " : " + Tm.history.loss[0]);
Output:
Loss after Epoch : 2.8400533199310303
Example 2: In this example will train our model by making some configuration.
Javascript
import * as tf from "@tensorflow/tfjs" // Creating modelconst Model = tf.sequential( ) ; // Adding layer to modelconst config = {units: 4, inputShape: [2], activation : "sigmoid"}const x = tf.layers.dense(config);Model.add(x); const config2 = {units: 3, activation : "sigmoid"}const y = tf.layers.dense(config2);Model.add(y); // Compiling the modelconst sgdOpt = tf.train.sgd(0.6)const config3 = {optimizer: 'sgd', loss: 'meanSquaredError'}Model.compile(config3); // Test Tensorconst xs = tf.tensor2d([ [0.3, 0.24], [0.12, 0.73], [0.9, 0.54] ]); const ys = tf.tensor2d([ [0.43, 0.5, 0.92], [0.1, 0.39, 0.12], [0.76, 0.4, 0.92] ]); // Training the modelfor( let i = 0; i < 5; i++){const config = { shuffle : true, epoch : 10 }const Tm = await Model.fit(xs, ys, config); // Printing the loss after trainingconsole.log("Loss " + " : " + Tm.history.loss[0]); }
Output:
Loss : 0.1362573206424713
Loss : 0.13617873191833496
Loss : 0.13610021770000458
Loss : 0.13602176308631897
Loss : 0.13594339787960052
Reference: https://js.tensorflow.org/api/3.8.0/#tf.Sequential.fit
rs1686740
surinderdawra388
simmytarika5
Picked
Tensorflow.js
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Oct, 2021"
},
{
"code": null,
"e": 194,
"s": 28,
"text": "Tensorflow.js is an open-source library developed by Google for running machine learning models and deep learning neural networks in the browser or node environment."
},
{
"code": null,
"e": 328,
"s": 194,
"text": "Tensorflow.jstf.Sequential class .fit( ) method is used to train the model for the fixed number of epochs( iterations on a dataset )."
},
{
"code": null,
"e": 336,
"s": 328,
"text": "Syntax:"
},
{
"code": null,
"e": 361,
"s": 336,
"text": "model.fit( x, y, args?);"
},
{
"code": null,
"e": 415,
"s": 361,
"text": "Parameters: This method accept following parameters:"
},
{
"code": null,
"e": 468,
"s": 415,
"text": "x: It is tf.Tensor that contains all the input data."
},
{
"code": null,
"e": 522,
"s": 468,
"text": "y: It is tf.Tensor that contains all the output data."
},
{
"code": null,
"e": 2664,
"s": 522,
"text": "args: It is object type, it’s variables are follows:batchSize: It define the number of samples that will propagate through training.epochs: It define iteration over the training data arrays.verbose: It help in showing the progress for each epoch.If the value is 0 – It means no printed message during fit() call. If the value is 1 – It means in Node-js , it prints the progress bar. In the browser it shows no action. Value 1 is the default value . 2 – Value 2 is not implement yet.callbacks: It define list of callbacks to be call during training. Variable can have one or more of these callbacks onTrainBegin( ), onTrainEnd( ), onEpochBegin( ), onEpochEnd( ), onBatchBegin( ), onBatchEnd( ), onYield( ).validationSplit: It makes easy for the user to split the training dataset into train and validation.For example : if it value is validation-Split = 0.5 ,it means use last 50% of data before shuffling for validation.validationData: It is used to give an estimate of final model when selecting between final models.shuffle: This value define shuffle of the data before each epoch. it has not effect when stepsPerEpoch is not null.classWeight: It is used for weighting the loss function. It can be useful to tell the model to pay more attention to samples from an under-represented class.sampleWeight: It is array of weights to apply to model’s loss for each sample.initialEpoch: It is value define epoch at which to start training. It is useful for resuming a previous training run.stepsPerEpoch: It define number of batches of samples before declaring one epoch finished and starting the next epoch. It is equal to 1 if not determined.validationSteps: It is relevant if stepsPerEpoch is specified. Total number of steps to validate before stopping.yieldEvery: It define configuration of the frequency of yielding the main thread to other tasks. It can be auto, It means the yielding happens at a certain frame rate. batch, If the value is this, It yield every batch. epoch, If the value is this, It yield every epoch. any number, If the value is any number, it yield every number milliseconds.never, If the value is this, it never yield."
},
{
"code": null,
"e": 2745,
"s": 2664,
"text": "batchSize: It define the number of samples that will propagate through training."
},
{
"code": null,
"e": 2804,
"s": 2745,
"text": "epochs: It define iteration over the training data arrays."
},
{
"code": null,
"e": 3097,
"s": 2804,
"text": "verbose: It help in showing the progress for each epoch.If the value is 0 – It means no printed message during fit() call. If the value is 1 – It means in Node-js , it prints the progress bar. In the browser it shows no action. Value 1 is the default value . 2 – Value 2 is not implement yet."
},
{
"code": null,
"e": 3321,
"s": 3097,
"text": "callbacks: It define list of callbacks to be call during training. Variable can have one or more of these callbacks onTrainBegin( ), onTrainEnd( ), onEpochBegin( ), onEpochEnd( ), onBatchBegin( ), onBatchEnd( ), onYield( )."
},
{
"code": null,
"e": 3537,
"s": 3321,
"text": "validationSplit: It makes easy for the user to split the training dataset into train and validation.For example : if it value is validation-Split = 0.5 ,it means use last 50% of data before shuffling for validation."
},
{
"code": null,
"e": 3636,
"s": 3537,
"text": "validationData: It is used to give an estimate of final model when selecting between final models."
},
{
"code": null,
"e": 3752,
"s": 3636,
"text": "shuffle: This value define shuffle of the data before each epoch. it has not effect when stepsPerEpoch is not null."
},
{
"code": null,
"e": 3910,
"s": 3752,
"text": "classWeight: It is used for weighting the loss function. It can be useful to tell the model to pay more attention to samples from an under-represented class."
},
{
"code": null,
"e": 3989,
"s": 3910,
"text": "sampleWeight: It is array of weights to apply to model’s loss for each sample."
},
{
"code": null,
"e": 4107,
"s": 3989,
"text": "initialEpoch: It is value define epoch at which to start training. It is useful for resuming a previous training run."
},
{
"code": null,
"e": 4262,
"s": 4107,
"text": "stepsPerEpoch: It define number of batches of samples before declaring one epoch finished and starting the next epoch. It is equal to 1 if not determined."
},
{
"code": null,
"e": 4376,
"s": 4262,
"text": "validationSteps: It is relevant if stepsPerEpoch is specified. Total number of steps to validate before stopping."
},
{
"code": null,
"e": 4766,
"s": 4376,
"text": "yieldEvery: It define configuration of the frequency of yielding the main thread to other tasks. It can be auto, It means the yielding happens at a certain frame rate. batch, If the value is this, It yield every batch. epoch, If the value is this, It yield every epoch. any number, If the value is any number, it yield every number milliseconds.never, If the value is this, it never yield."
},
{
"code": null,
"e": 4794,
"s": 4766,
"text": "Returns: Promise< History >"
},
{
"code": null,
"e": 4871,
"s": 4794,
"text": "Example 1: In this example we will train our model by default configuration."
},
{
"code": null,
"e": 4882,
"s": 4871,
"text": "Javascript"
},
{
"code": "import * as tf from \"@tensorflow/tfjs\" // Creating modelconst model = tf.sequential( ) ; // Adding layer to modelconst config = {units: 1, inputShape: [1]}const x = tf.layers.dense(config);model.add(x); // Compiling the modelconst config2 = {optimizer: 'sgd', loss: 'meanSquaredError'}model.compile(config2); // Tensor for trainingconst xs = tf.tensor2d([1, 1.2,1.65, 1.29, 1.4, 1.7], [6, 1]);const ys = tf.tensor2d([1, 0.07,0.17, 0.29, 0.43, 1.02], [6, 1]); // Training the modelconst Tm = await model.fit(xs, ys); // Printing the loss after trainingconsole.log(\"Loss \" + \" : \" + Tm.history.loss[0]);",
"e": 5485,
"s": 4882,
"text": null
},
{
"code": null,
"e": 5493,
"s": 5485,
"text": "Output:"
},
{
"code": null,
"e": 5532,
"s": 5493,
"text": "Loss after Epoch : 2.8400533199310303"
},
{
"code": null,
"e": 5610,
"s": 5532,
"text": "Example 2: In this example will train our model by making some configuration."
},
{
"code": null,
"e": 5621,
"s": 5610,
"text": "Javascript"
},
{
"code": "import * as tf from \"@tensorflow/tfjs\" // Creating modelconst Model = tf.sequential( ) ; // Adding layer to modelconst config = {units: 4, inputShape: [2], activation : \"sigmoid\"}const x = tf.layers.dense(config);Model.add(x); const config2 = {units: 3, activation : \"sigmoid\"}const y = tf.layers.dense(config2);Model.add(y); // Compiling the modelconst sgdOpt = tf.train.sgd(0.6)const config3 = {optimizer: 'sgd', loss: 'meanSquaredError'}Model.compile(config3); // Test Tensorconst xs = tf.tensor2d([ [0.3, 0.24], [0.12, 0.73], [0.9, 0.54] ]); const ys = tf.tensor2d([ [0.43, 0.5, 0.92], [0.1, 0.39, 0.12], [0.76, 0.4, 0.92] ]); // Training the modelfor( let i = 0; i < 5; i++){const config = { shuffle : true, epoch : 10 }const Tm = await Model.fit(xs, ys, config); // Printing the loss after trainingconsole.log(\"Loss \" + \" : \" + Tm.history.loss[0]); }",
"e": 6639,
"s": 5621,
"text": null
},
{
"code": null,
"e": 6648,
"s": 6639,
"text": "Output: "
},
{
"code": null,
"e": 6792,
"s": 6648,
"text": "Loss : 0.1362573206424713\nLoss : 0.13617873191833496\nLoss : 0.13610021770000458\nLoss : 0.13602176308631897\nLoss : 0.13594339787960052"
},
{
"code": null,
"e": 6858,
"s": 6792,
"text": "Reference: https://js.tensorflow.org/api/3.8.0/#tf.Sequential.fit"
},
{
"code": null,
"e": 6868,
"s": 6858,
"text": "rs1686740"
},
{
"code": null,
"e": 6885,
"s": 6868,
"text": "surinderdawra388"
},
{
"code": null,
"e": 6898,
"s": 6885,
"text": "simmytarika5"
},
{
"code": null,
"e": 6905,
"s": 6898,
"text": "Picked"
},
{
"code": null,
"e": 6919,
"s": 6905,
"text": "Tensorflow.js"
},
{
"code": null,
"e": 6930,
"s": 6919,
"text": "JavaScript"
},
{
"code": null,
"e": 6947,
"s": 6930,
"text": "Web Technologies"
}
] |
Shortest Palindromic Substring | 14 Sep, 2021
Given a string you need to find the shortest palindromic substring of the string. If there are multiple answers output the lexicographically smallest.
Examples:
Input: zyzz
Output:y
Input: abab
Output: a
Naive Approach:
The approach is similar to finding the longest palindromic substring. We keep track of even and odd lengths substring and keep storing it in a vector.
After that, we will sort the vector and print the lexicographically smallest substring. This may also include empty substrings but we need to ignore them.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the shortest// palindromic substring#include <bits/stdc++.h>using namespace std; // Function return the shortest// palindromic substringstring ShortestPalindrome(string s){ int n = s.length(); vector<string> v; // One by one consider every character // as center point of even and length // palindromes for (int i = 0; i < n; i++) { int l = i; int r = i; string ans1 = ""; string ans2 = ""; // Find the longest odd length palindrome // with center point as i while (l >= 0 && r < n && s[l] == s[r]) { ans1 += s[l]; l--; r++; } l = i - 1; r = i; // Find the even length palindrome // with center points as i-1 and i. while (l >= 0 && r < n && s[l] == s[r]) { ans2 += s[l]; l--; r++; } v.push_back(ans1); v.push_back(ans2); } string ans = v[0]; // Smallest substring which is // not empty for (int i = 0; i < v.size(); i++) { if (v[i] != "") { ans = min(ans, v[i]); } } return ans;} // Driver codeint main(){ string s = "geeksforgeeks"; cout << ShortestPalindrome(s); return 0;}
// Java program to find the shortest// palindromic substringimport java.util.*;import java.io.*; class GFG{ // Function return the shortest// palindromic substringpublic static String ShortestPalindrome(String s){ int n = s.length(); Vector<String> v = new Vector<String>(); // One by one consider every character // as center point of even and length // palindromes for(int i = 0; i < n; i++) { int l = i; int r = i; String ans1 = ""; String ans2 = ""; // Find the longest odd length palindrome // with center point as i while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { ans1 += s.charAt(l); l--; r++; } l = i - 1; r = i; // Find the even length palindrome // with center points as i-1 and i. while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { ans2 += s.charAt(l); l--; r++; } v.add(ans1); v.add(ans2); } String ans = v.get(0); // Smallest substring which is // not empty for(int i = 0; i < v.size(); i++) { if (v.get(i) != "") { if (ans.charAt(0) >= v.get(i).charAt(0)) { ans = v.get(i); } } } return ans;} // Driver codepublic static void main(String []args){ String s = "geeksforgeeks"; System.out.println(ShortestPalindrome(s));}} // This code is contributed by rag2127
# Python3 program to find the shortest# palindromic substring # Function return the shortest# palindromic substringdef ShortestPalindrome(s) : n = len(s) v = [] # One by one consider every character # as center point of even and length # palindromes for i in range(n) : l = i r = i ans1 = "" ans2 = "" # Find the longest odd length palindrome # with center point as i while ((l >= 0) and (r < n) and (s[l] == s[r])) : ans1 += s[l] l -= 1 r += 1 l = i - 1 r = i # Find the even length palindrome # with center points as i-1 and i. while ((l >= 0) and (r < n) and (s[l] == s[r])) : ans2 += s[l] l -= 1 r += 1 v.append(ans1) v.append(ans2) ans = v[0] # Smallest substring which is # not empty for i in range(len(v)) : if (v[i] != "") : ans = min(ans, v[i]) return ans s = "geeksforgeeks" print(ShortestPalindrome(s)) # This code is contributed by divyesh072019
// C# program to find the shortest// palindromic substringusing System;using System.Collections.Generic;class GFG{ // Function return the shortest // palindromic substring static string ShortestPalindrome(string s) { int n = s.Length; List<string> v = new List<string>(); // One by one consider every character // as center point of even and length // palindromes for(int i = 0; i < n; i++) { int l = i; int r = i; string ans1 = ""; string ans2 = ""; // Find the longest odd length palindrome // with center point as i while(l >= 0 && r < n && s[l] == s[r]) { ans1 += s[l]; l--; r++; } l = i - 1; r = i; // Find the even length palindrome // with center points as i-1 and i. while(l >= 0 && r < n && s[l] == s[r]) { ans2 += s[l]; l--; r++; } v.Add(ans1); v.Add(ans2); } string ans = v[0]; // Smallest substring which is // not empty for(int i = 0; i < v.Count; i++) { if(v[i] != "") { if(ans[0] >= v[i][0]) { ans = v[i]; } } } return ans; } // Driver code static public void Main () { string s = "geeksforgeeks"; Console.WriteLine(ShortestPalindrome(s)); }} // This code is contributed by avanitrachhadiya2155
<script> // Javascript program to find the shortest // palindromic substring // Function return the shortest // palindromic substring function ShortestPalindrome(s) { let n = s.length; let v = []; // One by one consider every character // as center point of even and length // palindromes for(let i = 0; i < n; i++) { let l = i; let r = i; let ans1 = ""; let ans2 = ""; // Find the longest odd length palindrome // with center point as i while(l >= 0 && r < n && s[l] == s[r]) { ans1 += s[l]; l--; r++; } l = i - 1; r = i; // Find the even length palindrome // with center points as i-1 and i. while(l >= 0 && r < n && s[l] == s[r]) { ans2 += s[l]; l--; r++; } v.push(ans1); v.push(ans2); } let ans = v[0]; // Smallest substring which is // not empty for(let i = 0; i < v.length; i++) { if(v[i] != "") { if(ans[0] >= v[i][0]) { ans = v[i]; } } } return ans; } let s = "geeksforgeeks"; document.write(ShortestPalindrome(s)); // This code is contributed by decode2207.</script>
e
Time complexity: O(N^2), where N is the length of the string.
Efficient Approach:
An observation here is that a single character is also a palindrome. So, we just need to print the lexicographically smallest character present in the string.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the shortest// palindromic substring#include <bits/stdc++.h>using namespace std; // Function return the shortest// palindromic substringchar ShortestPalindrome(string s){ int n = s.length(); char ans = s[0]; // Finding the smallest character // present in the string for(int i = 1; i < n ; i++) { ans = min(ans, s[i]); } return ans;} // Driver codeint main(){ string s = "geeksforgeeks"; cout << ShortestPalindrome(s); return 0;}
// Java program to find the shortest// palindromic subString class GFG{ // Function return the shortest// palindromic subStringstatic char ShortestPalindrome(String s){ int n = s.length(); char ans = s.charAt(0); // Finding the smallest character // present in the String for(int i = 1; i < n; i++) { ans = (char) Math.min(ans, s.charAt(i)); } return ans;} // Driver codepublic static void main(String[] args){ String s = "geeksforgeeks"; System.out.print(ShortestPalindrome(s));}} // This code is contributed by Rajput-Ji
# Python3 program to find the shortest# palindromic substring # Function return the shortest# palindromic substringdef ShortestPalindrome(s): n = len(s) ans = s[0] # Finding the smallest character # present in the string for i in range(1, n): ans = min(ans, s[i]) return ans # Driver codes = "geeksforgeeks" print(ShortestPalindrome(s)) # This code is contributed by divyeshrabadiya07
// C# program to find the shortest// palindromic subStringusing System; class GFG{ // Function return the shortest// palindromic subStringstatic char ShortestPalindrome(String s){ int n = s.Length; char ans = s[0]; // Finding the smallest character // present in the String for(int i = 1; i < n; i++) { ans = (char) Math.Min(ans, s[i]); } return ans;} // Driver codepublic static void Main(String[] args){ String s = "geeksforgeeks"; Console.Write(ShortestPalindrome(s));}} // This code is contributed by 29AjayKumar
<script> // Javascript program to find the shortest// palindromic subString // Function return the shortest// palindromic subStringfunction ShortestPalindrome(s){ let n = s.length; let ans = s[0].charCodeAt(); // Finding the smallest character // present in the String for(let i = 1; i < n; i++) { ans = Math.min(ans, s[i].charCodeAt()); } return String.fromCharCode(ans);} // Driver codelet s = "geeksforgeeks";document.write(ShortestPalindrome(s)); // This code is contributed by suresh07 </script>
e
Time complexity: O(N), where N is the length of the string.
Rajput-Ji
29AjayKumar
divyeshrabadiya07
divyesh072019
rag2127
avanitrachhadiya2155
suresh07
decode2207
surindertarika1234
palindrome
substring
Analysis
Strings
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 203,
"s": 52,
"text": "Given a string you need to find the shortest palindromic substring of the string. If there are multiple answers output the lexicographically smallest."
},
{
"code": null,
"e": 214,
"s": 203,
"text": "Examples: "
},
{
"code": null,
"e": 258,
"s": 214,
"text": "Input: zyzz\nOutput:y\n\nInput: abab\nOutput: a"
},
{
"code": null,
"e": 275,
"s": 258,
"text": "Naive Approach: "
},
{
"code": null,
"e": 426,
"s": 275,
"text": "The approach is similar to finding the longest palindromic substring. We keep track of even and odd lengths substring and keep storing it in a vector."
},
{
"code": null,
"e": 581,
"s": 426,
"text": "After that, we will sort the vector and print the lexicographically smallest substring. This may also include empty substrings but we need to ignore them."
},
{
"code": null,
"e": 632,
"s": 581,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 636,
"s": 632,
"text": "C++"
},
{
"code": null,
"e": 641,
"s": 636,
"text": "Java"
},
{
"code": null,
"e": 649,
"s": 641,
"text": "Python3"
},
{
"code": null,
"e": 652,
"s": 649,
"text": "C#"
},
{
"code": null,
"e": 663,
"s": 652,
"text": "Javascript"
},
{
"code": "// C++ program to find the shortest// palindromic substring#include <bits/stdc++.h>using namespace std; // Function return the shortest// palindromic substringstring ShortestPalindrome(string s){ int n = s.length(); vector<string> v; // One by one consider every character // as center point of even and length // palindromes for (int i = 0; i < n; i++) { int l = i; int r = i; string ans1 = \"\"; string ans2 = \"\"; // Find the longest odd length palindrome // with center point as i while (l >= 0 && r < n && s[l] == s[r]) { ans1 += s[l]; l--; r++; } l = i - 1; r = i; // Find the even length palindrome // with center points as i-1 and i. while (l >= 0 && r < n && s[l] == s[r]) { ans2 += s[l]; l--; r++; } v.push_back(ans1); v.push_back(ans2); } string ans = v[0]; // Smallest substring which is // not empty for (int i = 0; i < v.size(); i++) { if (v[i] != \"\") { ans = min(ans, v[i]); } } return ans;} // Driver codeint main(){ string s = \"geeksforgeeks\"; cout << ShortestPalindrome(s); return 0;}",
"e": 1986,
"s": 663,
"text": null
},
{
"code": "// Java program to find the shortest// palindromic substringimport java.util.*;import java.io.*; class GFG{ // Function return the shortest// palindromic substringpublic static String ShortestPalindrome(String s){ int n = s.length(); Vector<String> v = new Vector<String>(); // One by one consider every character // as center point of even and length // palindromes for(int i = 0; i < n; i++) { int l = i; int r = i; String ans1 = \"\"; String ans2 = \"\"; // Find the longest odd length palindrome // with center point as i while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { ans1 += s.charAt(l); l--; r++; } l = i - 1; r = i; // Find the even length palindrome // with center points as i-1 and i. while (l >= 0 && r < n && s.charAt(l) == s.charAt(r)) { ans2 += s.charAt(l); l--; r++; } v.add(ans1); v.add(ans2); } String ans = v.get(0); // Smallest substring which is // not empty for(int i = 0; i < v.size(); i++) { if (v.get(i) != \"\") { if (ans.charAt(0) >= v.get(i).charAt(0)) { ans = v.get(i); } } } return ans;} // Driver codepublic static void main(String []args){ String s = \"geeksforgeeks\"; System.out.println(ShortestPalindrome(s));}} // This code is contributed by rag2127",
"e": 3570,
"s": 1986,
"text": null
},
{
"code": "# Python3 program to find the shortest# palindromic substring # Function return the shortest# palindromic substringdef ShortestPalindrome(s) : n = len(s) v = [] # One by one consider every character # as center point of even and length # palindromes for i in range(n) : l = i r = i ans1 = \"\" ans2 = \"\" # Find the longest odd length palindrome # with center point as i while ((l >= 0) and (r < n) and (s[l] == s[r])) : ans1 += s[l] l -= 1 r += 1 l = i - 1 r = i # Find the even length palindrome # with center points as i-1 and i. while ((l >= 0) and (r < n) and (s[l] == s[r])) : ans2 += s[l] l -= 1 r += 1 v.append(ans1) v.append(ans2) ans = v[0] # Smallest substring which is # not empty for i in range(len(v)) : if (v[i] != \"\") : ans = min(ans, v[i]) return ans s = \"geeksforgeeks\" print(ShortestPalindrome(s)) # This code is contributed by divyesh072019",
"e": 4727,
"s": 3570,
"text": null
},
{
"code": "// C# program to find the shortest// palindromic substringusing System;using System.Collections.Generic;class GFG{ // Function return the shortest // palindromic substring static string ShortestPalindrome(string s) { int n = s.Length; List<string> v = new List<string>(); // One by one consider every character // as center point of even and length // palindromes for(int i = 0; i < n; i++) { int l = i; int r = i; string ans1 = \"\"; string ans2 = \"\"; // Find the longest odd length palindrome // with center point as i while(l >= 0 && r < n && s[l] == s[r]) { ans1 += s[l]; l--; r++; } l = i - 1; r = i; // Find the even length palindrome // with center points as i-1 and i. while(l >= 0 && r < n && s[l] == s[r]) { ans2 += s[l]; l--; r++; } v.Add(ans1); v.Add(ans2); } string ans = v[0]; // Smallest substring which is // not empty for(int i = 0; i < v.Count; i++) { if(v[i] != \"\") { if(ans[0] >= v[i][0]) { ans = v[i]; } } } return ans; } // Driver code static public void Main () { string s = \"geeksforgeeks\"; Console.WriteLine(ShortestPalindrome(s)); }} // This code is contributed by avanitrachhadiya2155",
"e": 6106,
"s": 4727,
"text": null
},
{
"code": "<script> // Javascript program to find the shortest // palindromic substring // Function return the shortest // palindromic substring function ShortestPalindrome(s) { let n = s.length; let v = []; // One by one consider every character // as center point of even and length // palindromes for(let i = 0; i < n; i++) { let l = i; let r = i; let ans1 = \"\"; let ans2 = \"\"; // Find the longest odd length palindrome // with center point as i while(l >= 0 && r < n && s[l] == s[r]) { ans1 += s[l]; l--; r++; } l = i - 1; r = i; // Find the even length palindrome // with center points as i-1 and i. while(l >= 0 && r < n && s[l] == s[r]) { ans2 += s[l]; l--; r++; } v.push(ans1); v.push(ans2); } let ans = v[0]; // Smallest substring which is // not empty for(let i = 0; i < v.length; i++) { if(v[i] != \"\") { if(ans[0] >= v[i][0]) { ans = v[i]; } } } return ans; } let s = \"geeksforgeeks\"; document.write(ShortestPalindrome(s)); // This code is contributed by decode2207.</script>",
"e": 7453,
"s": 6106,
"text": null
},
{
"code": null,
"e": 7455,
"s": 7453,
"text": "e"
},
{
"code": null,
"e": 7519,
"s": 7457,
"text": "Time complexity: O(N^2), where N is the length of the string."
},
{
"code": null,
"e": 7540,
"s": 7519,
"text": "Efficient Approach: "
},
{
"code": null,
"e": 7699,
"s": 7540,
"text": "An observation here is that a single character is also a palindrome. So, we just need to print the lexicographically smallest character present in the string."
},
{
"code": null,
"e": 7751,
"s": 7699,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 7755,
"s": 7751,
"text": "C++"
},
{
"code": null,
"e": 7760,
"s": 7755,
"text": "Java"
},
{
"code": null,
"e": 7768,
"s": 7760,
"text": "Python3"
},
{
"code": null,
"e": 7771,
"s": 7768,
"text": "C#"
},
{
"code": null,
"e": 7782,
"s": 7771,
"text": "Javascript"
},
{
"code": "// C++ program to find the shortest// palindromic substring#include <bits/stdc++.h>using namespace std; // Function return the shortest// palindromic substringchar ShortestPalindrome(string s){ int n = s.length(); char ans = s[0]; // Finding the smallest character // present in the string for(int i = 1; i < n ; i++) { ans = min(ans, s[i]); } return ans;} // Driver codeint main(){ string s = \"geeksforgeeks\"; cout << ShortestPalindrome(s); return 0;}",
"e": 8295,
"s": 7782,
"text": null
},
{
"code": "// Java program to find the shortest// palindromic subString class GFG{ // Function return the shortest// palindromic subStringstatic char ShortestPalindrome(String s){ int n = s.length(); char ans = s.charAt(0); // Finding the smallest character // present in the String for(int i = 1; i < n; i++) { ans = (char) Math.min(ans, s.charAt(i)); } return ans;} // Driver codepublic static void main(String[] args){ String s = \"geeksforgeeks\"; System.out.print(ShortestPalindrome(s));}} // This code is contributed by Rajput-Ji",
"e": 8860,
"s": 8295,
"text": null
},
{
"code": "# Python3 program to find the shortest# palindromic substring # Function return the shortest# palindromic substringdef ShortestPalindrome(s): n = len(s) ans = s[0] # Finding the smallest character # present in the string for i in range(1, n): ans = min(ans, s[i]) return ans # Driver codes = \"geeksforgeeks\" print(ShortestPalindrome(s)) # This code is contributed by divyeshrabadiya07",
"e": 9285,
"s": 8860,
"text": null
},
{
"code": "// C# program to find the shortest// palindromic subStringusing System; class GFG{ // Function return the shortest// palindromic subStringstatic char ShortestPalindrome(String s){ int n = s.Length; char ans = s[0]; // Finding the smallest character // present in the String for(int i = 1; i < n; i++) { ans = (char) Math.Min(ans, s[i]); } return ans;} // Driver codepublic static void Main(String[] args){ String s = \"geeksforgeeks\"; Console.Write(ShortestPalindrome(s));}} // This code is contributed by 29AjayKumar",
"e": 9844,
"s": 9285,
"text": null
},
{
"code": "<script> // Javascript program to find the shortest// palindromic subString // Function return the shortest// palindromic subStringfunction ShortestPalindrome(s){ let n = s.length; let ans = s[0].charCodeAt(); // Finding the smallest character // present in the String for(let i = 1; i < n; i++) { ans = Math.min(ans, s[i].charCodeAt()); } return String.fromCharCode(ans);} // Driver codelet s = \"geeksforgeeks\";document.write(ShortestPalindrome(s)); // This code is contributed by suresh07 </script>",
"e": 10377,
"s": 9844,
"text": null
},
{
"code": null,
"e": 10379,
"s": 10377,
"text": "e"
},
{
"code": null,
"e": 10442,
"s": 10381,
"text": "Time complexity: O(N), where N is the length of the string. "
},
{
"code": null,
"e": 10452,
"s": 10442,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 10464,
"s": 10452,
"text": "29AjayKumar"
},
{
"code": null,
"e": 10482,
"s": 10464,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 10496,
"s": 10482,
"text": "divyesh072019"
},
{
"code": null,
"e": 10504,
"s": 10496,
"text": "rag2127"
},
{
"code": null,
"e": 10525,
"s": 10504,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 10534,
"s": 10525,
"text": "suresh07"
},
{
"code": null,
"e": 10545,
"s": 10534,
"text": "decode2207"
},
{
"code": null,
"e": 10564,
"s": 10545,
"text": "surindertarika1234"
},
{
"code": null,
"e": 10575,
"s": 10564,
"text": "palindrome"
},
{
"code": null,
"e": 10585,
"s": 10575,
"text": "substring"
},
{
"code": null,
"e": 10594,
"s": 10585,
"text": "Analysis"
},
{
"code": null,
"e": 10602,
"s": 10594,
"text": "Strings"
},
{
"code": null,
"e": 10610,
"s": 10602,
"text": "Strings"
},
{
"code": null,
"e": 10621,
"s": 10610,
"text": "palindrome"
}
] |
Why Java Strings are Immutable? | 19 Feb, 2022
Before proceeding further with the fuss of immutability, let’s just take a look into the String class and its functionality a little before coming to any conclusion.
This is how a String works:
String str = "knowledge";
This, as usual, creates a string containing “knowledge” and assigns it to reference str. Simple enough? Let us perform some more functions:
// assigns a new reference to the
// same string "knowledge"
String s = str;
Let’s see how the below statement works:
str = str.concat(" base");
This appends a string ” base” to str. But wait, how is this possible, since String objects are immutable? Well to your surprise, it is.
When the above statement is executed, the VM takes the value of String str, i.e. “knowledge” and appends ” base”, giving us the value “knowledge base”. Now, since Strings are immutable, the VM can’t assign this value to str, so it creates a new String object, gives it a value “knowledge base”, and gives it reference str.
An important point to note here is that, while the String object is immutable, its reference variable is not. So that’s why, in the above example, the reference was made to refer to a newly formed String object.
At this point in the example above, we have two String objects: the first one we created with value “knowledge”, pointed to by s, and the second one “knowledge base”, pointed to by str. But, technically, we have three String objects, the third one being the literal “base” in the concat statement.
These are some more reasons for making String immutable in Java. These are:
The String pool cannot be possible if String is not immutable in Java. A lot of heap space is saved by JRE. The same string variable can be referred to by more than one string variable in the pool. String interning can also not be possible if the String would not be immutable.
If we don’t make the String immutable, it will pose a serious security threat to the application. For example, database usernames, passwords are passed as strings to receive database connections. The socket programming host and port descriptions are also passed as strings. The String is immutable, so its value cannot be changed. If the String doesn’t remain immutable, any hacker can cause a security issue in the application by changing the reference value.
The String is safe for multithreading because of its immutableness. Different threads can access a single “String instance”. It removes the synchronization for thread safety because we make strings thread-safe implicitly.
Immutability gives the security of loading the correct class by Classloader. For example, suppose we have an instance where we try to load java.sql.Connection class but the changes in the referenced value to the myhacked.Connection class does unwanted things to our database.
What if we didn’t have another reference s to “knowledge”? We would have lost that String. However, it still would have existed but would be considered lost due to having no references. Look at one more example below
Java
// Java Program to demonstrate why// Java Strings are immutable import java.io.*; class GFG { public static void main(String[] args) { String s1 = "java"; s1.concat(" rules"); // Yes, s1 still refers to "java" System.out.println("s1 refers to " + s1); }}
s1 refers to java
Explanation:
The first line is pretty straightforward: create a new String “java” and refer s1 to it.Next, the VM creates another new String “java rules”, but nothing refers to it. So, the second String is instantly lost. We can’t reach it.
The first line is pretty straightforward: create a new String “java” and refer s1 to it.
Next, the VM creates another new String “java rules”, but nothing refers to it. So, the second String is instantly lost. We can’t reach it.
The reference variable s1 still refers to the original string “java”.
Almost every method, applied to a String object in order to modify it, creates a new String object. So, where do these String objects go? Well, these exist in memory, and one of the key goals of any programming language is to make efficient use of memory.
As applications grow, it’s very common for String literals to occupy a large area of memory, which can even cause redundancy. So, in order to make Java more efficient, the JVM sets aside a special area of memory called the “String constant pool”.
When the compiler sees a String literal, it looks for the String in the pool. If a match is found, the reference to the new literal is directed to the existing String and no new String object is created. The existing String simply has one more reference. Here comes the point of making String objects immutable:
In the String constant pool, a String object is likely to have one or many references. If several references point to the same String without even knowing it, it would be bad if one of the references modified that String value. That’s why String objects are immutable.
Well, now you could say, what if someone overrides the functionality of the String class? That’s the reason that the String class is marked final so that nobody can override the behavior of its methods.
nishkarshgandhi
java-basics
java-JVM
Java-String-Programs
Java-Strings
Java
Strings
Java-Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n19 Feb, 2022"
},
{
"code": null,
"e": 218,
"s": 52,
"text": "Before proceeding further with the fuss of immutability, let’s just take a look into the String class and its functionality a little before coming to any conclusion."
},
{
"code": null,
"e": 246,
"s": 218,
"text": "This is how a String works:"
},
{
"code": null,
"e": 272,
"s": 246,
"text": "String str = \"knowledge\";"
},
{
"code": null,
"e": 412,
"s": 272,
"text": "This, as usual, creates a string containing “knowledge” and assigns it to reference str. Simple enough? Let us perform some more functions:"
},
{
"code": null,
"e": 495,
"s": 412,
"text": "// assigns a new reference to the \n// same string \"knowledge\"\nString s = str; "
},
{
"code": null,
"e": 536,
"s": 495,
"text": "Let’s see how the below statement works:"
},
{
"code": null,
"e": 565,
"s": 536,
"text": " str = str.concat(\" base\");"
},
{
"code": null,
"e": 701,
"s": 565,
"text": "This appends a string ” base” to str. But wait, how is this possible, since String objects are immutable? Well to your surprise, it is."
},
{
"code": null,
"e": 1024,
"s": 701,
"text": "When the above statement is executed, the VM takes the value of String str, i.e. “knowledge” and appends ” base”, giving us the value “knowledge base”. Now, since Strings are immutable, the VM can’t assign this value to str, so it creates a new String object, gives it a value “knowledge base”, and gives it reference str."
},
{
"code": null,
"e": 1236,
"s": 1024,
"text": "An important point to note here is that, while the String object is immutable, its reference variable is not. So that’s why, in the above example, the reference was made to refer to a newly formed String object."
},
{
"code": null,
"e": 1534,
"s": 1236,
"text": "At this point in the example above, we have two String objects: the first one we created with value “knowledge”, pointed to by s, and the second one “knowledge base”, pointed to by str. But, technically, we have three String objects, the third one being the literal “base” in the concat statement."
},
{
"code": null,
"e": 1610,
"s": 1534,
"text": "These are some more reasons for making String immutable in Java. These are:"
},
{
"code": null,
"e": 1888,
"s": 1610,
"text": "The String pool cannot be possible if String is not immutable in Java. A lot of heap space is saved by JRE. The same string variable can be referred to by more than one string variable in the pool. String interning can also not be possible if the String would not be immutable."
},
{
"code": null,
"e": 2349,
"s": 1888,
"text": "If we don’t make the String immutable, it will pose a serious security threat to the application. For example, database usernames, passwords are passed as strings to receive database connections. The socket programming host and port descriptions are also passed as strings. The String is immutable, so its value cannot be changed. If the String doesn’t remain immutable, any hacker can cause a security issue in the application by changing the reference value."
},
{
"code": null,
"e": 2571,
"s": 2349,
"text": "The String is safe for multithreading because of its immutableness. Different threads can access a single “String instance”. It removes the synchronization for thread safety because we make strings thread-safe implicitly."
},
{
"code": null,
"e": 2847,
"s": 2571,
"text": "Immutability gives the security of loading the correct class by Classloader. For example, suppose we have an instance where we try to load java.sql.Connection class but the changes in the referenced value to the myhacked.Connection class does unwanted things to our database."
},
{
"code": null,
"e": 3064,
"s": 2847,
"text": "What if we didn’t have another reference s to “knowledge”? We would have lost that String. However, it still would have existed but would be considered lost due to having no references. Look at one more example below"
},
{
"code": null,
"e": 3069,
"s": 3064,
"text": "Java"
},
{
"code": "// Java Program to demonstrate why// Java Strings are immutable import java.io.*; class GFG { public static void main(String[] args) { String s1 = \"java\"; s1.concat(\" rules\"); // Yes, s1 still refers to \"java\" System.out.println(\"s1 refers to \" + s1); }}",
"e": 3362,
"s": 3069,
"text": null
},
{
"code": null,
"e": 3380,
"s": 3362,
"text": "s1 refers to java"
},
{
"code": null,
"e": 3393,
"s": 3380,
"text": "Explanation:"
},
{
"code": null,
"e": 3621,
"s": 3393,
"text": "The first line is pretty straightforward: create a new String “java” and refer s1 to it.Next, the VM creates another new String “java rules”, but nothing refers to it. So, the second String is instantly lost. We can’t reach it."
},
{
"code": null,
"e": 3710,
"s": 3621,
"text": "The first line is pretty straightforward: create a new String “java” and refer s1 to it."
},
{
"code": null,
"e": 3850,
"s": 3710,
"text": "Next, the VM creates another new String “java rules”, but nothing refers to it. So, the second String is instantly lost. We can’t reach it."
},
{
"code": null,
"e": 3920,
"s": 3850,
"text": "The reference variable s1 still refers to the original string “java”."
},
{
"code": null,
"e": 4176,
"s": 3920,
"text": "Almost every method, applied to a String object in order to modify it, creates a new String object. So, where do these String objects go? Well, these exist in memory, and one of the key goals of any programming language is to make efficient use of memory."
},
{
"code": null,
"e": 4423,
"s": 4176,
"text": "As applications grow, it’s very common for String literals to occupy a large area of memory, which can even cause redundancy. So, in order to make Java more efficient, the JVM sets aside a special area of memory called the “String constant pool”."
},
{
"code": null,
"e": 4735,
"s": 4423,
"text": "When the compiler sees a String literal, it looks for the String in the pool. If a match is found, the reference to the new literal is directed to the existing String and no new String object is created. The existing String simply has one more reference. Here comes the point of making String objects immutable:"
},
{
"code": null,
"e": 5004,
"s": 4735,
"text": "In the String constant pool, a String object is likely to have one or many references. If several references point to the same String without even knowing it, it would be bad if one of the references modified that String value. That’s why String objects are immutable."
},
{
"code": null,
"e": 5207,
"s": 5004,
"text": "Well, now you could say, what if someone overrides the functionality of the String class? That’s the reason that the String class is marked final so that nobody can override the behavior of its methods."
},
{
"code": null,
"e": 5223,
"s": 5207,
"text": "nishkarshgandhi"
},
{
"code": null,
"e": 5235,
"s": 5223,
"text": "java-basics"
},
{
"code": null,
"e": 5244,
"s": 5235,
"text": "java-JVM"
},
{
"code": null,
"e": 5265,
"s": 5244,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 5278,
"s": 5265,
"text": "Java-Strings"
},
{
"code": null,
"e": 5283,
"s": 5278,
"text": "Java"
},
{
"code": null,
"e": 5291,
"s": 5283,
"text": "Strings"
},
{
"code": null,
"e": 5304,
"s": 5291,
"text": "Java-Strings"
},
{
"code": null,
"e": 5312,
"s": 5304,
"text": "Strings"
},
{
"code": null,
"e": 5317,
"s": 5312,
"text": "Java"
}
] |
How to select rows from a dataframe based on column values ? | 07 Jul, 2022
Prerequisite: Pandas.Dataframes in Python
In this article, we will cover how we select rows from a DataFrame based on column values in Python.
The rows of a Dataframe can be selected based on conditions as we do use the SQL queries. The various methods to achieve this is explained in this article with examples.
To explain the method a dataset has been created which contains data of points scored by 10 people in various games. The dataset is loaded into the Dataframe and visualized first. Ten people with unique player id(Pid) have played different games with different game id(game_id) and the points scored in each game are added as an entry to the table. Some of the player’s points are not recorded and thus NaN value appears in the table.
Note: To get the CSV file used, click here.
Python3
import pandas as pd df = pd.read_csv(r"__your file path__\example2.csv")print(df)
Output:
dataset example2.csv
We will select rows from Dataframe based on column value using:
Boolean Indexing method
Positional indexing method
Using isin() method
Using Numpy.where() method
Comparison with other methods
In this method, for a specified column condition, each row is checked for true/false. The rows which yield True will be considered for the output. This can be achieved in various ways. The query used is Select rows where the column Pid=’p01′
In this example, we are trying to select those rows that have the value p01 in their column using the equality operator.
Python3
# Choose entries with id p01df_new = df[df['Pid'] == 'p01'] print(df_new)
Output
Here, we will see Pandas select rows by condition the selected rows are assigned to a new Dataframe with the index of rows from the old Dataframe as an index in the new one and the columns remaining the same.
Python3
# condition maskmask = df['Pid'] == 'p01' # new dataframe with selected rowsdf_new = pd.DataFrame(df[mask]) print(df_new)
Output
The query here is to Select the rows with game_id ‘g21’.
Python3
# condition with df.values propertymask = df['game_id'].values == 'g21' # new dataframedf_new = df[mask] print(df_new)
Output
The methods loc() and iloc() can be used for slicing the Dataframes in Python. Among the differences between loc() and iloc(), the important thing to be noted is iloc() takes only integer indices, while loc() can take up boolean indices also.
The mask gives the boolean value as an index for each row and whichever rows evaluate to true will appear in the result. Here, the query is to select the rows where game_id is g21.
Python3
# for boolean indexingmask = df['game_id'].values == 'g21' # using loc() methoddf_new = df.loc[mask] print(df_new)
Output
The query is the same as the one taken above. The iloc() takes only integers as an argument and thus, the mask array is passed as a parameter to the Numpy’s flatnonzero() function that returns the index in the list where the value is not zero (false)
Python3
# condition maskmask = df['game_id'].values == 'g21'print("Mask array :", mask) # getting non zero indicespos = np.flatnonzero(mask)print("\nRows selected :", pos) # selecting rowsdf.iloc[pos]
Output
The query() method takes up the expression that returns a boolean value, processes all the rows in the Dataframe, and returns the resultant Dataframe with selected rows.
Select rows where the name=”Albert”
Python3
df.query('name=="Albert"')
Output
This example is to demonstrate that logical operators like AND/OR can be used to check multiple conditions. we are trying to select rows where points>50 and the player is not Albert.
Python3
df.query('points>50 & name!="Albert"')
Output
This method of Dataframe takes up an iterable or a series or another Dataframe as a parameter and checks whether elements of the Dataframe exist in it. The rows that evaluate to true are considered for the resultant.
Select the rows where players are Albert, Louis, and John.
Python3
# Players to be selectedli = ['Albert', 'Louis', 'John'] df[df.name.isin(li)]
Output
The tiled symbol (~) provides the negation of the expression evaluated. Here, we are selecting rows where points>50 and players are not Albert, Louis, and John.
Python3
# values to be present in selected rowsli = ['Albert', 'Louis', 'John'] # selecting rows from dataframedf[(df.points > 50) & (~df.name.isin(li))]
Output
The Numpy’s where() function can be combined with the pandas’ isin() function to produce a faster result. The numpy.where() is proved to produce results faster than the normal methods used above.
Python3
import numpy as np df_new = df.iloc[np.where(df.name.isin(li))]
Output:
In this example, we are using a mixture of NumPy and pandas method
Python3
# to calculate timingimport numpy as np% % timeit # using mixture of numpy and pandas methoddf_new = df.iloc[np.where(df.name.isin(li))]
Output:
756 μs ± 132 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
In this example, we are using only the Pandas method
Python3
# to calculate time%%timeit li=['Albert','Louis','John'] # Pandas method onlydf[(df.points>50)&(~df.name.isin(li))]
Output
1.7 ms ± 307 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
surajkumarguptaintern
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 70,
"s": 28,
"text": "Prerequisite: Pandas.Dataframes in Python"
},
{
"code": null,
"e": 172,
"s": 70,
"text": "In this article, we will cover how we select rows from a DataFrame based on column values in Python. "
},
{
"code": null,
"e": 343,
"s": 172,
"text": "The rows of a Dataframe can be selected based on conditions as we do use the SQL queries. The various methods to achieve this is explained in this article with examples. "
},
{
"code": null,
"e": 778,
"s": 343,
"text": "To explain the method a dataset has been created which contains data of points scored by 10 people in various games. The dataset is loaded into the Dataframe and visualized first. Ten people with unique player id(Pid) have played different games with different game id(game_id) and the points scored in each game are added as an entry to the table. Some of the player’s points are not recorded and thus NaN value appears in the table."
},
{
"code": null,
"e": 822,
"s": 778,
"text": "Note: To get the CSV file used, click here."
},
{
"code": null,
"e": 830,
"s": 822,
"text": "Python3"
},
{
"code": "import pandas as pd df = pd.read_csv(r\"__your file path__\\example2.csv\")print(df)",
"e": 912,
"s": 830,
"text": null
},
{
"code": null,
"e": 920,
"s": 912,
"text": "Output:"
},
{
"code": null,
"e": 941,
"s": 920,
"text": "dataset example2.csv"
},
{
"code": null,
"e": 1005,
"s": 941,
"text": "We will select rows from Dataframe based on column value using:"
},
{
"code": null,
"e": 1029,
"s": 1005,
"text": "Boolean Indexing method"
},
{
"code": null,
"e": 1056,
"s": 1029,
"text": "Positional indexing method"
},
{
"code": null,
"e": 1076,
"s": 1056,
"text": "Using isin() method"
},
{
"code": null,
"e": 1103,
"s": 1076,
"text": "Using Numpy.where() method"
},
{
"code": null,
"e": 1133,
"s": 1103,
"text": "Comparison with other methods"
},
{
"code": null,
"e": 1375,
"s": 1133,
"text": "In this method, for a specified column condition, each row is checked for true/false. The rows which yield True will be considered for the output. This can be achieved in various ways. The query used is Select rows where the column Pid=’p01′"
},
{
"code": null,
"e": 1496,
"s": 1375,
"text": "In this example, we are trying to select those rows that have the value p01 in their column using the equality operator."
},
{
"code": null,
"e": 1504,
"s": 1496,
"text": "Python3"
},
{
"code": "# Choose entries with id p01df_new = df[df['Pid'] == 'p01'] print(df_new)",
"e": 1578,
"s": 1504,
"text": null
},
{
"code": null,
"e": 1585,
"s": 1578,
"text": "Output"
},
{
"code": null,
"e": 1797,
"s": 1587,
"text": "Here, we will see Pandas select rows by condition the selected rows are assigned to a new Dataframe with the index of rows from the old Dataframe as an index in the new one and the columns remaining the same. "
},
{
"code": null,
"e": 1805,
"s": 1797,
"text": "Python3"
},
{
"code": "# condition maskmask = df['Pid'] == 'p01' # new dataframe with selected rowsdf_new = pd.DataFrame(df[mask]) print(df_new)",
"e": 1927,
"s": 1805,
"text": null
},
{
"code": null,
"e": 1934,
"s": 1927,
"text": "Output"
},
{
"code": null,
"e": 1993,
"s": 1936,
"text": "The query here is to Select the rows with game_id ‘g21’."
},
{
"code": null,
"e": 2001,
"s": 1993,
"text": "Python3"
},
{
"code": "# condition with df.values propertymask = df['game_id'].values == 'g21' # new dataframedf_new = df[mask] print(df_new)",
"e": 2120,
"s": 2001,
"text": null
},
{
"code": null,
"e": 2127,
"s": 2120,
"text": "Output"
},
{
"code": null,
"e": 2373,
"s": 2129,
"text": "The methods loc() and iloc() can be used for slicing the Dataframes in Python. Among the differences between loc() and iloc(), the important thing to be noted is iloc() takes only integer indices, while loc() can take up boolean indices also. "
},
{
"code": null,
"e": 2554,
"s": 2373,
"text": "The mask gives the boolean value as an index for each row and whichever rows evaluate to true will appear in the result. Here, the query is to select the rows where game_id is g21."
},
{
"code": null,
"e": 2562,
"s": 2554,
"text": "Python3"
},
{
"code": "# for boolean indexingmask = df['game_id'].values == 'g21' # using loc() methoddf_new = df.loc[mask] print(df_new)",
"e": 2677,
"s": 2562,
"text": null
},
{
"code": null,
"e": 2684,
"s": 2677,
"text": "Output"
},
{
"code": null,
"e": 2937,
"s": 2686,
"text": "The query is the same as the one taken above. The iloc() takes only integers as an argument and thus, the mask array is passed as a parameter to the Numpy’s flatnonzero() function that returns the index in the list where the value is not zero (false)"
},
{
"code": null,
"e": 2945,
"s": 2937,
"text": "Python3"
},
{
"code": "# condition maskmask = df['game_id'].values == 'g21'print(\"Mask array :\", mask) # getting non zero indicespos = np.flatnonzero(mask)print(\"\\nRows selected :\", pos) # selecting rowsdf.iloc[pos]",
"e": 3138,
"s": 2945,
"text": null
},
{
"code": null,
"e": 3145,
"s": 3138,
"text": "Output"
},
{
"code": null,
"e": 3318,
"s": 3147,
"text": "The query() method takes up the expression that returns a boolean value, processes all the rows in the Dataframe, and returns the resultant Dataframe with selected rows. "
},
{
"code": null,
"e": 3355,
"s": 3318,
"text": "Select rows where the name=”Albert”"
},
{
"code": null,
"e": 3363,
"s": 3355,
"text": "Python3"
},
{
"code": "df.query('name==\"Albert\"')",
"e": 3390,
"s": 3363,
"text": null
},
{
"code": null,
"e": 3397,
"s": 3390,
"text": "Output"
},
{
"code": null,
"e": 3582,
"s": 3399,
"text": "This example is to demonstrate that logical operators like AND/OR can be used to check multiple conditions. we are trying to select rows where points>50 and the player is not Albert."
},
{
"code": null,
"e": 3590,
"s": 3582,
"text": "Python3"
},
{
"code": "df.query('points>50 & name!=\"Albert\"')",
"e": 3629,
"s": 3590,
"text": null
},
{
"code": null,
"e": 3636,
"s": 3629,
"text": "Output"
},
{
"code": null,
"e": 3855,
"s": 3638,
"text": "This method of Dataframe takes up an iterable or a series or another Dataframe as a parameter and checks whether elements of the Dataframe exist in it. The rows that evaluate to true are considered for the resultant."
},
{
"code": null,
"e": 3914,
"s": 3855,
"text": "Select the rows where players are Albert, Louis, and John."
},
{
"code": null,
"e": 3922,
"s": 3914,
"text": "Python3"
},
{
"code": "# Players to be selectedli = ['Albert', 'Louis', 'John'] df[df.name.isin(li)]",
"e": 4000,
"s": 3922,
"text": null
},
{
"code": null,
"e": 4007,
"s": 4000,
"text": "Output"
},
{
"code": null,
"e": 4170,
"s": 4009,
"text": "The tiled symbol (~) provides the negation of the expression evaluated. Here, we are selecting rows where points>50 and players are not Albert, Louis, and John."
},
{
"code": null,
"e": 4178,
"s": 4170,
"text": "Python3"
},
{
"code": "# values to be present in selected rowsli = ['Albert', 'Louis', 'John'] # selecting rows from dataframedf[(df.points > 50) & (~df.name.isin(li))]",
"e": 4324,
"s": 4178,
"text": null
},
{
"code": null,
"e": 4331,
"s": 4324,
"text": "Output"
},
{
"code": null,
"e": 4529,
"s": 4333,
"text": "The Numpy’s where() function can be combined with the pandas’ isin() function to produce a faster result. The numpy.where() is proved to produce results faster than the normal methods used above."
},
{
"code": null,
"e": 4537,
"s": 4529,
"text": "Python3"
},
{
"code": "import numpy as np df_new = df.iloc[np.where(df.name.isin(li))]",
"e": 4601,
"s": 4537,
"text": null
},
{
"code": null,
"e": 4609,
"s": 4601,
"text": "Output:"
},
{
"code": null,
"e": 4678,
"s": 4611,
"text": "In this example, we are using a mixture of NumPy and pandas method"
},
{
"code": null,
"e": 4686,
"s": 4678,
"text": "Python3"
},
{
"code": "# to calculate timingimport numpy as np% % timeit # using mixture of numpy and pandas methoddf_new = df.iloc[np.where(df.name.isin(li))]",
"e": 4824,
"s": 4686,
"text": null
},
{
"code": null,
"e": 4832,
"s": 4824,
"text": "Output:"
},
{
"code": null,
"e": 4903,
"s": 4832,
"text": "756 μs ± 132 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)"
},
{
"code": null,
"e": 4956,
"s": 4903,
"text": "In this example, we are using only the Pandas method"
},
{
"code": null,
"e": 4964,
"s": 4956,
"text": "Python3"
},
{
"code": "# to calculate time%%timeit li=['Albert','Louis','John'] # Pandas method onlydf[(df.points>50)&(~df.name.isin(li))]",
"e": 5080,
"s": 4964,
"text": null
},
{
"code": null,
"e": 5087,
"s": 5080,
"text": "Output"
},
{
"code": null,
"e": 5158,
"s": 5087,
"text": "1.7 ms ± 307 μs per loop (mean ± std. dev. of 7 runs, 1000 loops each)"
},
{
"code": null,
"e": 5180,
"s": 5158,
"text": "surajkumarguptaintern"
},
{
"code": null,
"e": 5204,
"s": 5180,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 5218,
"s": 5204,
"text": "Python-pandas"
},
{
"code": null,
"e": 5225,
"s": 5218,
"text": "Python"
}
] |
Sum of all palindrome numbers present in an Array | 04 Jun, 2022
Given an array arr[] of N positive integers. The task is to find the sum of all palindrome numbers present in the array. Print the total sum.
A palindrome number is a number which when reversed is equal to the initial number. Example: 121 is palindrome(reverse(121) = 121), 123 is not palindrome(reverse(123) = 321).
Note: Consider palindrome numbers of length greater than 1 while calculating the sum.
Examples:
Input : arr[] ={12, 313, 11, 44, 9, 1}
Output : 368
Input : arr[] = {12, 11, 121}
Output : 132
Approach: The idea is to implement a reverse function that reverses a number from the right to left. Implement a function that checks for palindrome numbers and finally traverse the array and calculate sum of all elements which are palindrome.
Below is the implementation of the above approach:
C++
Java
C#
Python3
Javascript
// C++ program to calculate the sum of all// palindromic numbers in array#include<bits/stdc++.h>using namespace std; // Function to reverse a number nint reverse(int n){ int d = 0, s = 0; while (n > 0) { d = n % 10; s = s * 10 + d; n = n / 10; } return s;} // Function to check if a number n is// palindromebool isPalin(int n){ // If n is equal to the reverse of n // it is a palindrome return n == reverse(n);} // Function to calculate sum of all array// elements which are palindromeint sumOfArray(int arr[], int n){ int s = 0; for (int i = 0; i < n; i++) { if ((arr[i] > 10) && isPalin(arr[i])) { // summation of all palindrome numbers // present in array s += arr[i]; } } return s;} // Driver Codeint main(){ int n = 6; int arr[] = { 12, 313, 11, 44, 9, 1 }; cout << sumOfArray(arr, n); return 0;} // This code is contributed by mits
// Java program to calculate the sum of all// palindromic numbers in array class GFG { // Function to reverse a number n static int reverse(int n) { int d = 0, s = 0; while (n > 0) { d = n % 10; s = s * 10 + d; n = n / 10; } return s; } // Function to check if a number n is // palindrome static boolean isPalin(int n) { // If n is equal to the reverse of n // it is a palindrome return n == reverse(n); } // Function to calculate sum of all array // elements which are palindrome static int sumOfArray(int[] arr, int n) { int s = 0; for (int i = 0; i < n; i++) { if ((arr[i] > 10) && isPalin(arr[i])) { // summation of all palindrome numbers // present in array s += arr[i]; } } return s; } // Driver Code public static void main(String[] args) { int n = 6; int[] arr = { 12, 313, 11, 44, 9, 1 }; System.out.println(sumOfArray(arr, n)); }}
// C# program to calculate the sum of all// palindromic numbers in arrayusing System; class GFG{ // Function to reverse a number n static int reverse(int n) { int d = 0, s = 0; while (n > 0) { d = n % 10; s = s * 10 + d; n = n / 10; } return s; } // Function to check if a number n is // palindrome static bool isPalin(int n) { // If n is equal to the reverse of n // it is a palindrome return n == reverse(n); } // Function to calculate sum of all array // elements which are palindrome static int sumOfArray(int[] arr, int n) { int s = 0; for (int i = 0; i < n; i++) { if ((arr[i] > 10) && isPalin(arr[i])) { // summation of all palindrome numbers // present in array s += arr[i]; } } return s; } // Driver Code public static void Main(String[] args) { int n = 6; int[] arr = { 12, 313, 11, 44, 9, 1 }; Console.WriteLine(sumOfArray(arr, n)); }} /* This code contributed by PrinciRaj1992 */
# Python3 program to calculate the sum of all# palindromic numbers in array # Function to reverse a number ndef reverse(n) : d = 0; s = 0; while (n > 0) : d = n % 10; s = s * 10 + d; n = n // 10; return s; # Function to check if a number n is# palindromedef isPalin(n) : # If n is equal to the reverse of n # it is a palindrome return n == reverse(n); # Function to calculate sum of all array# elements which are palindromedef sumOfArray(arr, n) : s = 0; for i in range(n) : if ((arr[i] > 10) and isPalin(arr[i])) : # summation of all palindrome numbers # present in array s += arr[i]; return s; # Driver Codeif __name__ == "__main__" : n = 6; arr = [ 12, 313, 11, 44, 9, 1 ]; print(sumOfArray(arr, n)); # This code is contributed by AnkitRai01
<script> // Javascript program to calculate the// sum of all palindromic numbers in array // Function to reverse a number nfunction reverse( n){ let d = 0, s = 0; while (n > 0) { d = n % 10; s = s * 10 + d; n = Math.floor(n / 10); } return s;} // Function to check if a number n is// palindromefunction isPalin(n){ // If n is equal to the reverse of n // it is a palindrome return n == reverse(n);} // Function to calculate sum of all array// elements which are palindromefunction sumOfArray( arr, n){ let s = 0; for(let i = 0; i < n; i++) { if ((arr[i] > 10) && isPalin(arr[i])) { // Summation of all palindrome // numbers present in array s += arr[i]; } } return s;} // Driver Codelet n = 6;let arr = [ 12, 313, 11, 44, 9, 1 ]; document.write(sumOfArray(arr, n)); // This code is contributed by jana_sayantan </script>
368
Time Complexity: O(n * max(arr)), where max(arr) is the largest element of the array arr.
Auxiliary Space: O(1), since no extra space has been taken.
Another approach :
In java, we can easily implement it by using StringBuilder object and the reverse() method.
Step 1: Get the input from the user
Step 2: Initialize sum=0 and iterate through each element.
Step 3: Now, convert the integer element to string by using Integer.toString(array[i])
Step 4:Reverse it by StringBuilder object using reverse() method and toString() is used to convert the object to string.
Step 5: Equalize both the string values and check element greater than 9. If it satisfies the condition, sum the elements.
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main (String[] args) { int array[]={12, 313, 11, 44, 9, 1}; int n=array.length; int sum=0; for(int i=0;i<n;i++){ String str=Integer.toString(array[i]); String rev=new StringBuilder(str).reverse().toString(); if(str.equals(rev) && array[i]>9){ sum=sum+array[i]; } } System.out.println(sum); }}
368
In python, we can execute it by implementing the below approach.
Step 1 : Initialize the list or array and sum=0.
Step 2 : Iterate the list using for loop and convert the integer element to string using str().
Step 3 : Reverse the string using string_element[ : : -1].
Step 4 :Equalize both the string values and check element greater than 9. If it satisfies the condition, sum the elements.
Python3
# code lis=[12, 313, 11, 44, 9, 1]sum=0;for i in lis: string_conversion=str(i) rev_string=string_conversion[ : : -1] if(string_conversion==rev_string and i>9): sum=sum+iprint(sum)
368
Time Complexity : O(n)
princiraj1992
Mithun Kumar
ankthon
jana_sayantan
rishav1329
keerthikarathan123
palindrome
Arrays
Mathematical
School Programming
Arrays
Mathematical
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n04 Jun, 2022"
},
{
"code": null,
"e": 170,
"s": 28,
"text": "Given an array arr[] of N positive integers. The task is to find the sum of all palindrome numbers present in the array. Print the total sum."
},
{
"code": null,
"e": 346,
"s": 170,
"text": "A palindrome number is a number which when reversed is equal to the initial number. Example: 121 is palindrome(reverse(121) = 121), 123 is not palindrome(reverse(123) = 321). "
},
{
"code": null,
"e": 432,
"s": 346,
"text": "Note: Consider palindrome numbers of length greater than 1 while calculating the sum."
},
{
"code": null,
"e": 443,
"s": 432,
"text": "Examples: "
},
{
"code": null,
"e": 540,
"s": 443,
"text": "Input : arr[] ={12, 313, 11, 44, 9, 1} \nOutput : 368\n\nInput : arr[] = {12, 11, 121}\nOutput : 132"
},
{
"code": null,
"e": 784,
"s": 540,
"text": "Approach: The idea is to implement a reverse function that reverses a number from the right to left. Implement a function that checks for palindrome numbers and finally traverse the array and calculate sum of all elements which are palindrome."
},
{
"code": null,
"e": 836,
"s": 784,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 840,
"s": 836,
"text": "C++"
},
{
"code": null,
"e": 845,
"s": 840,
"text": "Java"
},
{
"code": null,
"e": 848,
"s": 845,
"text": "C#"
},
{
"code": null,
"e": 856,
"s": 848,
"text": "Python3"
},
{
"code": null,
"e": 867,
"s": 856,
"text": "Javascript"
},
{
"code": "// C++ program to calculate the sum of all// palindromic numbers in array#include<bits/stdc++.h>using namespace std; // Function to reverse a number nint reverse(int n){ int d = 0, s = 0; while (n > 0) { d = n % 10; s = s * 10 + d; n = n / 10; } return s;} // Function to check if a number n is// palindromebool isPalin(int n){ // If n is equal to the reverse of n // it is a palindrome return n == reverse(n);} // Function to calculate sum of all array// elements which are palindromeint sumOfArray(int arr[], int n){ int s = 0; for (int i = 0; i < n; i++) { if ((arr[i] > 10) && isPalin(arr[i])) { // summation of all palindrome numbers // present in array s += arr[i]; } } return s;} // Driver Codeint main(){ int n = 6; int arr[] = { 12, 313, 11, 44, 9, 1 }; cout << sumOfArray(arr, n); return 0;} // This code is contributed by mits",
"e": 1837,
"s": 867,
"text": null
},
{
"code": "// Java program to calculate the sum of all// palindromic numbers in array class GFG { // Function to reverse a number n static int reverse(int n) { int d = 0, s = 0; while (n > 0) { d = n % 10; s = s * 10 + d; n = n / 10; } return s; } // Function to check if a number n is // palindrome static boolean isPalin(int n) { // If n is equal to the reverse of n // it is a palindrome return n == reverse(n); } // Function to calculate sum of all array // elements which are palindrome static int sumOfArray(int[] arr, int n) { int s = 0; for (int i = 0; i < n; i++) { if ((arr[i] > 10) && isPalin(arr[i])) { // summation of all palindrome numbers // present in array s += arr[i]; } } return s; } // Driver Code public static void main(String[] args) { int n = 6; int[] arr = { 12, 313, 11, 44, 9, 1 }; System.out.println(sumOfArray(arr, n)); }}",
"e": 2941,
"s": 1837,
"text": null
},
{
"code": "// C# program to calculate the sum of all// palindromic numbers in arrayusing System; class GFG{ // Function to reverse a number n static int reverse(int n) { int d = 0, s = 0; while (n > 0) { d = n % 10; s = s * 10 + d; n = n / 10; } return s; } // Function to check if a number n is // palindrome static bool isPalin(int n) { // If n is equal to the reverse of n // it is a palindrome return n == reverse(n); } // Function to calculate sum of all array // elements which are palindrome static int sumOfArray(int[] arr, int n) { int s = 0; for (int i = 0; i < n; i++) { if ((arr[i] > 10) && isPalin(arr[i])) { // summation of all palindrome numbers // present in array s += arr[i]; } } return s; } // Driver Code public static void Main(String[] args) { int n = 6; int[] arr = { 12, 313, 11, 44, 9, 1 }; Console.WriteLine(sumOfArray(arr, n)); }} /* This code contributed by PrinciRaj1992 */",
"e": 4121,
"s": 2941,
"text": null
},
{
"code": "# Python3 program to calculate the sum of all# palindromic numbers in array # Function to reverse a number ndef reverse(n) : d = 0; s = 0; while (n > 0) : d = n % 10; s = s * 10 + d; n = n // 10; return s; # Function to check if a number n is# palindromedef isPalin(n) : # If n is equal to the reverse of n # it is a palindrome return n == reverse(n); # Function to calculate sum of all array# elements which are palindromedef sumOfArray(arr, n) : s = 0; for i in range(n) : if ((arr[i] > 10) and isPalin(arr[i])) : # summation of all palindrome numbers # present in array s += arr[i]; return s; # Driver Codeif __name__ == \"__main__\" : n = 6; arr = [ 12, 313, 11, 44, 9, 1 ]; print(sumOfArray(arr, n)); # This code is contributed by AnkitRai01",
"e": 5017,
"s": 4121,
"text": null
},
{
"code": "<script> // Javascript program to calculate the// sum of all palindromic numbers in array // Function to reverse a number nfunction reverse( n){ let d = 0, s = 0; while (n > 0) { d = n % 10; s = s * 10 + d; n = Math.floor(n / 10); } return s;} // Function to check if a number n is// palindromefunction isPalin(n){ // If n is equal to the reverse of n // it is a palindrome return n == reverse(n);} // Function to calculate sum of all array// elements which are palindromefunction sumOfArray( arr, n){ let s = 0; for(let i = 0; i < n; i++) { if ((arr[i] > 10) && isPalin(arr[i])) { // Summation of all palindrome // numbers present in array s += arr[i]; } } return s;} // Driver Codelet n = 6;let arr = [ 12, 313, 11, 44, 9, 1 ]; document.write(sumOfArray(arr, n)); // This code is contributed by jana_sayantan </script>",
"e": 5972,
"s": 5017,
"text": null
},
{
"code": null,
"e": 5976,
"s": 5972,
"text": "368"
},
{
"code": null,
"e": 6066,
"s": 5976,
"text": "Time Complexity: O(n * max(arr)), where max(arr) is the largest element of the array arr."
},
{
"code": null,
"e": 6126,
"s": 6066,
"text": "Auxiliary Space: O(1), since no extra space has been taken."
},
{
"code": null,
"e": 6145,
"s": 6126,
"text": "Another approach :"
},
{
"code": null,
"e": 6238,
"s": 6145,
"text": "In java, we can easily implement it by using StringBuilder object and the reverse() method. "
},
{
"code": null,
"e": 6274,
"s": 6238,
"text": "Step 1: Get the input from the user"
},
{
"code": null,
"e": 6333,
"s": 6274,
"text": "Step 2: Initialize sum=0 and iterate through each element."
},
{
"code": null,
"e": 6420,
"s": 6333,
"text": "Step 3: Now, convert the integer element to string by using Integer.toString(array[i])"
},
{
"code": null,
"e": 6541,
"s": 6420,
"text": "Step 4:Reverse it by StringBuilder object using reverse() method and toString() is used to convert the object to string."
},
{
"code": null,
"e": 6664,
"s": 6541,
"text": "Step 5: Equalize both the string values and check element greater than 9. If it satisfies the condition, sum the elements."
},
{
"code": null,
"e": 6669,
"s": 6664,
"text": "Java"
},
{
"code": "/*package whatever //do not write package name here */ import java.io.*; class GFG { public static void main (String[] args) { int array[]={12, 313, 11, 44, 9, 1}; int n=array.length; int sum=0; for(int i=0;i<n;i++){ String str=Integer.toString(array[i]); String rev=new StringBuilder(str).reverse().toString(); if(str.equals(rev) && array[i]>9){ sum=sum+array[i]; } } System.out.println(sum); }}",
"e": 7139,
"s": 6669,
"text": null
},
{
"code": null,
"e": 7144,
"s": 7139,
"text": "368\n"
},
{
"code": null,
"e": 7209,
"s": 7144,
"text": "In python, we can execute it by implementing the below approach."
},
{
"code": null,
"e": 7258,
"s": 7209,
"text": "Step 1 : Initialize the list or array and sum=0."
},
{
"code": null,
"e": 7354,
"s": 7258,
"text": "Step 2 : Iterate the list using for loop and convert the integer element to string using str()."
},
{
"code": null,
"e": 7413,
"s": 7354,
"text": "Step 3 : Reverse the string using string_element[ : : -1]."
},
{
"code": null,
"e": 7536,
"s": 7413,
"text": "Step 4 :Equalize both the string values and check element greater than 9. If it satisfies the condition, sum the elements."
},
{
"code": null,
"e": 7544,
"s": 7536,
"text": "Python3"
},
{
"code": "# code lis=[12, 313, 11, 44, 9, 1]sum=0;for i in lis: string_conversion=str(i) rev_string=string_conversion[ : : -1] if(string_conversion==rev_string and i>9): sum=sum+iprint(sum) ",
"e": 7735,
"s": 7544,
"text": null
},
{
"code": null,
"e": 7740,
"s": 7735,
"text": "368\n"
},
{
"code": null,
"e": 7763,
"s": 7740,
"text": "Time Complexity : O(n)"
},
{
"code": null,
"e": 7777,
"s": 7763,
"text": "princiraj1992"
},
{
"code": null,
"e": 7790,
"s": 7777,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 7798,
"s": 7790,
"text": "ankthon"
},
{
"code": null,
"e": 7812,
"s": 7798,
"text": "jana_sayantan"
},
{
"code": null,
"e": 7823,
"s": 7812,
"text": "rishav1329"
},
{
"code": null,
"e": 7842,
"s": 7823,
"text": "keerthikarathan123"
},
{
"code": null,
"e": 7853,
"s": 7842,
"text": "palindrome"
},
{
"code": null,
"e": 7860,
"s": 7853,
"text": "Arrays"
},
{
"code": null,
"e": 7873,
"s": 7860,
"text": "Mathematical"
},
{
"code": null,
"e": 7892,
"s": 7873,
"text": "School Programming"
},
{
"code": null,
"e": 7899,
"s": 7892,
"text": "Arrays"
},
{
"code": null,
"e": 7912,
"s": 7899,
"text": "Mathematical"
},
{
"code": null,
"e": 7923,
"s": 7912,
"text": "palindrome"
}
] |
Subsets and Splits